#!/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 = (map3) => (path150) => {
  var fn = map3[path150];
  if (fn) return fn();
  throw new Error("Module not found in bundle: " + path150);
};
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, all4) => {
  for (var name4 in all4)
    __defProp(target, name4, { get: all4[name4], 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);
var __toBinaryNode = (base643) => new Uint8Array(Buffer.from(base643, "base64"));

// 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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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, body2) {
        super(message);
        this.name = "ResponseStatusCodeError";
        this.message = message || "Response Status Code Error";
        this.code = "UND_ERR_RESPONSE_STATUS_CODE";
        this.body = body2;
        this.status = statusCode;
        this.statusCode = statusCode;
        this.headers = headers;
      }
      static [Symbol.hasInstance](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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 i4 = 0; i4 < wellknownHeaderNames.length; ++i4) {
      const key = wellknownHeaderNames[i4];
      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 i4 = 0; i4 < wellknownHeaderNames.length; ++i4) {
      const key = headerNameLowerCasedRecord[wellknownHeaderNames[i4]];
      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 stream5 = __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(body2) {
        this[kBody] = body2;
        this[kBodyUsed] = false;
      }
      async *[Symbol.asyncIterator]() {
        assert4(!this[kBodyUsed], "disturbed");
        this[kBodyUsed] = true;
        yield* this[kBody];
      }
    };
    function wrapRequestBody(body2) {
      if (isStream3(body2)) {
        if (bodyLength(body2) === 0) {
          body2.on("data", function() {
            assert4(false);
          });
        }
        if (typeof body2.readableDidRead !== "boolean") {
          body2[kBodyUsed] = false;
          EE3.prototype.on.call(body2, "data", function() {
            this[kBodyUsed] = true;
          });
        }
        return body2;
      } else if (body2 && typeof body2.pipeTo === "function") {
        return new BodyAsyncIterable(body2);
      } else if (body2 && typeof body2 !== "string" && !ArrayBuffer.isView(body2) && isIterable2(body2)) {
        return new BodyAsyncIterable(body2);
      } else {
        return body2;
      }
    }
    __name(wrapRequestBody, "wrapRequestBody");
    function nop() {
    }
    __name(nop, "nop");
    function isStream3(obj) {
      return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
    }
    __name(isStream3, "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 buildURL2(url3, queryParams) {
      if (url3.includes("?") || url3.includes("#")) {
        throw new Error('Query params cannot be passed when url already contains "?" or "#".');
      }
      const stringified = stringify4(queryParams);
      if (stringified) {
        url3 += "?" + stringified;
      }
      return url3;
    }
    __name(buildURL2, "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(url3) {
      if (typeof url3 === "string") {
        url3 = new URL(url3);
        if (!isHttpOrHttpsPrefixed(url3.origin || url3.protocol)) {
          throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
        }
        return url3;
      }
      if (!url3 || typeof url3 !== "object") {
        throw new InvalidArgumentError("Invalid URL: The URL argument must be a non-null object.");
      }
      if (!(url3 instanceof URL)) {
        if (url3.port != null && url3.port !== "" && isValidPort(url3.port) === false) {
          throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer.");
        }
        if (url3.path != null && typeof url3.path !== "string") {
          throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined.");
        }
        if (url3.pathname != null && typeof url3.pathname !== "string") {
          throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined.");
        }
        if (url3.hostname != null && typeof url3.hostname !== "string") {
          throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined.");
        }
        if (url3.origin != null && typeof url3.origin !== "string") {
          throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined.");
        }
        if (!isHttpOrHttpsPrefixed(url3.origin || url3.protocol)) {
          throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
        }
        const port = url3.port != null ? url3.port : url3.protocol === "https:" ? 443 : 80;
        let origin2 = url3.origin != null ? url3.origin : `${url3.protocol || ""}//${url3.hostname || ""}:${port}`;
        let path150 = url3.path != null ? url3.path : `${url3.pathname || ""}${url3.search || ""}`;
        if (origin2[origin2.length - 1] === "/") {
          origin2 = origin2.slice(0, origin2.length - 1);
        }
        if (path150 && path150[0] !== "/") {
          path150 = `/${path150}`;
        }
        return new URL(`${origin2}${path150}`);
      }
      if (!isHttpOrHttpsPrefixed(url3.origin || url3.protocol)) {
        throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
      }
      return url3;
    }
    __name(parseURL, "parseURL");
    function parseOrigin(url3) {
      url3 = parseURL(url3);
      if (url3.pathname !== "/" || url3.search || url3.hash) {
        throw new InvalidArgumentError("invalid url");
      }
      return url3;
    }
    __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 isIterable2(obj) {
      return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
    }
    __name(isIterable2, "isIterable");
    function bodyLength(body2) {
      if (body2 == null) {
        return 0;
      } else if (isStream3(body2)) {
        const state = body2._readableState;
        return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null;
      } else if (isBlobLike3(body2)) {
        return body2.size != null ? body2.size : null;
      } else if (isBuffer2(body2)) {
        return body2.byteLength;
      }
      return null;
    }
    __name(bodyLength, "bodyLength");
    function isDestroyed(body2) {
      return body2 && !!(body2.destroyed || body2[kDestroyed] || stream5.isDestroyed?.(body2));
    }
    __name(isDestroyed, "isDestroyed");
    function destroy(stream6, err2) {
      if (stream6 == null || !isStream3(stream6) || isDestroyed(stream6)) {
        return;
      }
      if (typeof stream6.destroy === "function") {
        if (Object.getPrototypeOf(stream6).constructor === IncomingMessage) {
          stream6.socket = null;
        }
        stream6.destroy(err2);
      } else if (err2) {
        queueMicrotask(() => {
          stream6.emit("error", err2);
        });
      }
      if (stream6.destroyed !== true) {
        stream6[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 i4 = 0; i4 < headers.length; i4 += 2) {
        const key = headerNameToString(headers[i4]);
        let val = obj[key];
        if (val) {
          if (typeof val === "string") {
            val = [val];
            obj[key] = val;
          }
          val.push(headers[i4 + 1].toString("utf8"));
        } else {
          const headersValue = headers[i4 + 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 isBuffer2(buffer) {
      return buffer instanceof Uint8Array || Buffer.isBuffer(buffer);
    }
    __name(isBuffer2, "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(body2) {
      return !!(body2 && (stream5.isDisturbed(body2) || body2[kBodyUsed]));
    }
    __name(isDisturbed, "isDisturbed");
    function isErrored(body2) {
      return !!(body2 && stream5.isErrored(body2));
    }
    __name(isErrored, "isErrored");
    function isReadable2(body2) {
      return !!(body2 && stream5.isReadable(body2));
    }
    __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 iterator2;
      return new ReadableStream(
        {
          async start() {
            iterator2 = iterable[Symbol.asyncIterator]();
          },
          async pull(controller) {
            const { done, value } = await iterator2.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 iterator2.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 i4 = 0; i4 < characters.length; ++i4) {
        if (!isTokenCharCode(characters.charCodeAt(i4))) {
          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, name4, listener) {
      const listeners = obj[kListeners] ??= [];
      listeners.push([name4, listener]);
      obj.on(name4, listener);
      return obj;
    }
    __name(addListener, "addListener");
    function removeAllListeners(obj) {
      for (const [name4, listener] of obj[kListeners] ?? []) {
        obj.removeListener(name4, listener);
      }
      obj[kListeners] = null;
    }
    __name(removeAllListeners, "removeAllListeners");
    function errorRequest(client, request4, err2) {
      try {
        request4.onError(err2);
        assert4(request4.aborted);
      } catch (err3) {
        client.emit("error", err3);
      }
    }
    __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: isStream3,
      isIterable: isIterable2,
      isAsyncIterable: isAsyncIterable2,
      isDestroyed,
      headerNameToString,
      bufferToLowerCasedHeaderName,
      addListener,
      removeAllListeners,
      errorRequest,
      parseRawHeaders,
      parseHeaders,
      parseKeepAliveTimeout,
      destroy,
      bodyLength,
      deepClone,
      ReadableStreamFrom: ReadableStreamFrom2,
      isBuffer: isBuffer2,
      validateHandler,
      getSocketInfo,
      isFormDataLike,
      buildURL: buildURL2,
      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 util5 = __require("node:util");
    var undiciDebugLog = util5.debuglog("undici");
    var fetchDebuglog = util5.debuglog("fetch");
    var websocketDebuglog = util5.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: error40
        } = evt;
        debuglog(
          "connection to %s using %s%s errored - %s",
          `${host}${port ? `:${port}` : ""}`,
          protocol,
          version2,
          error40.message
        );
      });
      diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => {
        const {
          request: { method, path: path150, origin: origin2 }
        } = evt;
        debuglog("sending request to %s %s/%s", method, origin2, path150);
      });
      diagnosticsChannel.channel("undici:request:headers").subscribe((evt) => {
        const {
          request: { method, path: path150, origin: origin2 },
          response: { statusCode }
        } = evt;
        debuglog(
          "received response to %s %s/%s - HTTP %d",
          method,
          origin2,
          path150,
          statusCode
        );
      });
      diagnosticsChannel.channel("undici:request:trailers").subscribe((evt) => {
        const {
          request: { method, path: path150, origin: origin2 }
        } = evt;
        debuglog("trailers received from %s %s/%s", method, origin2, path150);
      });
      diagnosticsChannel.channel("undici:request:error").subscribe((evt) => {
        const {
          request: { method, path: path150, origin: origin2 },
          error: error40
        } = evt;
        debuglog(
          "request to %s %s/%s errored - %s",
          method,
          origin2,
          path150,
          error40.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: error40
          } = evt;
          debuglog(
            "connection to %s%s using %s%s errored - %s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2,
            error40.message
          );
        });
        diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => {
          const {
            request: { method, path: path150, origin: origin2 }
          } = evt;
          debuglog("sending request to %s %s/%s", method, origin2, path150);
        });
      }
      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((err2) => {
        websocketDebuglog("connection errored - %s", err2.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: isStream3,
      destroy,
      isBuffer: isBuffer2,
      isFormDataLike,
      isIterable: isIterable2,
      isBlobLike: isBlobLike3,
      buildURL: buildURL2,
      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(origin2, {
        path: path150,
        method,
        body: body2,
        headers,
        query,
        idempotent,
        blocking,
        upgrade,
        headersTimeout,
        bodyTimeout,
        reset,
        throwOnError,
        expectContinue,
        servername
      }, handler) {
        if (typeof path150 !== "string") {
          throw new InvalidArgumentError("path must be a string");
        } else if (path150[0] !== "/" && !(path150.startsWith("http://") || path150.startsWith("https://")) && method !== "CONNECT") {
          throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
        } else if (invalidPathRegex.test(path150)) {
          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 (body2 == null) {
          this.body = null;
        } else if (isStream3(body2)) {
          this.body = body2;
          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 = (err2) => {
            if (this.abort) {
              this.abort(err2);
            } else {
              this.error = err2;
            }
          };
          this.body.on("error", this.errorHandler);
        } else if (isBuffer2(body2)) {
          this.body = body2.byteLength ? body2 : null;
        } else if (ArrayBuffer.isView(body2)) {
          this.body = body2.buffer.byteLength ? Buffer.from(body2.buffer, body2.byteOffset, body2.byteLength) : null;
        } else if (body2 instanceof ArrayBuffer) {
          this.body = body2.byteLength ? Buffer.from(body2) : null;
        } else if (typeof body2 === "string") {
          this.body = body2.length ? Buffer.from(body2) : null;
        } else if (isFormDataLike(body2) || isIterable2(body2) || isBlobLike3(body2)) {
          this.body = body2;
        } 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 ? buildURL2(path150, query) : path150;
        this.origin = origin2;
        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 i4 = 0; i4 < headers.length; i4 += 2) {
            processHeader(this, headers[i4], headers[i4 + 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 i4 = 0; i4 < keys.length; ++i4) {
              processHeader(this, keys[i4], headers[keys[i4]]);
            }
          }
        } 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 (err2) {
            this.abort(err2);
          }
        }
      }
      onRequestSent() {
        if (channels.bodySent.hasSubscribers) {
          channels.bodySent.publish({ request: this });
        }
        if (this[kHandler].onRequestSent) {
          try {
            return this[kHandler].onRequestSent();
          } catch (err2) {
            this.abort(err2);
          }
        }
      }
      onConnect(abort2) {
        assert4(!this.aborted);
        assert4(!this.completed);
        if (this.error) {
          abort2(this.error);
        } else {
          this.abort = abort2;
          return this[kHandler].onConnect(abort2);
        }
      }
      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 (err2) {
          this.abort(err2);
        }
      }
      onData(chunk) {
        assert4(!this.aborted);
        assert4(!this.completed);
        try {
          return this[kHandler].onData(chunk);
        } catch (err2) {
          this.abort(err2);
          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 (err2) {
          this.onError(err2);
        }
      }
      onError(error40) {
        this.onFinally();
        if (channels.error.hasSubscribers) {
          channels.error.publish({ request: this, error: error40 });
        }
        if (this.aborted) {
          return;
        }
        this.aborted = true;
        return this[kHandler].onError(error40);
      }
      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 i4 = 0; i4 < val.length; i4++) {
          if (typeof val[i4] === "string") {
            if (!isValidHeaderValue(val[i4])) {
              throw new InvalidArgumentError(`invalid ${key} header`);
            }
            arr.push(val[i4]);
          } else if (val[i4] === null) {
            arr.push("");
          } else if (typeof val[i4] === "object") {
            throw new InvalidArgumentError(`invalid ${key} header`);
          } else {
            arr.push(`${val[i4]}`);
          }
        }
        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 EventEmitter16 = __require("node:events");
    var Dispatcher = class extends EventEmitter16 {
      static {
        __name(this, "Dispatcher");
      }
      dispatch() {
        throw new Error("not implemented");
      }
      close() {
        throw new Error("not implemented");
      }
      destroy() {
        throw new Error("not implemented");
      }
      compose(...args2) {
        const interceptors = Array.isArray(args2[0]) ? args2[0] : args2;
        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(...args2) {
        this.#dispatch(...args2);
      }
      close(...args2) {
        return this.#dispatcher.close(...args2);
      }
      destroy(...args2) {
        return this.#dispatcher.destroy(...args2);
      }
    };
    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 i4 = newInterceptors.length - 1; i4 >= 0; i4--) {
            const interceptor = this[kInterceptors][i4];
            if (typeof interceptor !== "function") {
              throw new InvalidArgumentError("interceptor must be an function");
            }
          }
        }
        this[kInterceptors] = newInterceptors;
      }
      close(callback) {
        if (callback === void 0) {
          return new Promise((resolve42, reject) => {
            this.close((err2, data) => {
              return err2 ? reject(err2) : resolve42(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 i4 = 0; i4 < callbacks.length; i4++) {
            callbacks[i4](null, null);
          }
        }, "onClosed");
        this[kClose]().then(() => this.destroy()).then(() => {
          queueMicrotask(onClosed);
        });
      }
      destroy(err2, callback) {
        if (typeof err2 === "function") {
          callback = err2;
          err2 = null;
        }
        if (callback === void 0) {
          return new Promise((resolve42, reject) => {
            this.destroy(err2, (err3, data) => {
              return err3 ? (
                /* istanbul ignore next: should never error */
                reject(err3)
              ) : resolve42(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 (!err2) {
          err2 = 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 i4 = 0; i4 < callbacks.length; i4++) {
            callbacks[i4](null, null);
          }
        }, "onDestroyed");
        this[kDestroy](err2).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 i4 = this[kInterceptors].length - 1; i4 >= 0; i4--) {
          dispatch = this[kInterceptors][i4](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 (err2) {
          if (typeof handler.onError !== "function") {
            throw new InvalidArgumentError("invalid onError method");
          }
          handler.onError(err2);
          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, delay5, arg) {
        this._onTimeout = callback;
        this._idleTimeout = delay5;
        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, delay5, arg) {
        return delay5 <= RESOLUTION_MS ? setTimeout(callback, delay5, arg) : new FastTimer(callback, delay5, 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, delay5, arg) {
        return new FastTimer(callback, delay5, 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(delay5 = 0) {
        fastNow += delay5 - 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 util5 = require_util();
    var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
    var timers = require_timers();
    function noop11() {
    }
    __name(noop11, "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 || util5.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(err2) {
          queueMicrotask(clearConnectTimeout);
          if (callback) {
            const cb = callback;
            callback = null;
            cb(err2);
          }
        });
        return socket;
      }, "connect");
    }
    __name(buildConnector, "buildConnector");
    var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop11;
      }
      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 noop11;
      }
      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)`;
      util5.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 i4 = "A".charCodeAt(0); i4 <= "Z".charCodeAt(0); i4++) {
      exports2.ALPHA.push(String.fromCharCode(i4));
      exports2.ALPHA.push(String.fromCharCode(i4 + 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 i4 = 128; i4 <= 255; i4++) {
      exports2.URL_CHAR.push(i4);
    }
    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 i4 = 32; i4 <= 255; i4++) {
      if (i4 !== 127) {
        exports2.HEADER_CHARS.push(i4);
      }
    }
    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 body2 = stringPercentDecode(encodedBody);
      if (/;(\u0020){0,}base64$/i.test(mimeType)) {
        const stringBody = isomorphicDecode(body2);
        body2 = forgivingBase64(stringBody);
        if (body2 === "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: body2 };
    }
    __name(dataURLProcessor, "dataURLProcessor");
    function URLSerializer(url3, excludeFragment = false) {
      if (!excludeFragment) {
        return url3.href;
      }
      const href = url3.href;
      const hashLength = url3.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 start2 = position.position;
      if (idx === -1) {
        position.position = input.length;
        return input.slice(start2);
      }
      position.position = idx;
      return input.slice(start2, 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 i4 = 0; i4 < length; ++i4) {
        const byte = input[i4];
        if (byte !== 37) {
          output[j2++] = byte;
        } else if (byte === 37 && !(isHexCharByte(input[i4 + 1]) && isHexCharByte(input[i4 + 2]))) {
          output[j2++] = 37;
        } else {
          output[j2++] = hexByteToNumber(input[i4 + 1]) << 4 | hexByteToNumber(input[i4 + 2]);
          i4 += 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 [name4, value] of parameters.entries()) {
        serialization += ";";
        serialization += name4;
        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 i4 = 0;
      let addition = (2 << 15) - 1;
      while (i4 < length) {
        if (i4 + addition > length) {
          addition = length - i4;
        }
        result += String.fromCharCode.apply(null, input.subarray(i4, i4 += 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 err2 = new TypeError("Illegal invocation");
          err2.code = "ERR_INVALID_THIS";
          throw err2;
        }
      } else {
        if (V3?.[Symbol.toStringTag] !== I3.prototype[Symbol.toStringTag]) {
          const err2 = new TypeError("Illegal invocation");
          err2.code = "ERR_INVALID_THIS";
          throw err2;
        }
      }
    };
    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(i4) {
      return (V3, prefix, argument, opts) => {
        if (opts?.strict !== false && !(V3 instanceof i4)) {
          throw webidl.errors.exception({
            header: prefix,
            message: `Expected ${argument} ("${webidl.util.Stringify(V3)}") to be an instance of ${i4.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, name4, opts) {
      if (webidl.util.Type(V3) !== "Object" || !types7.isTypedArray(V3) || V3.constructor.name !== T2.name) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${name4} ("${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, name4, opts) {
      if (webidl.util.Type(V3) !== "Object" || !types7.isDataView(V3)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${name4} 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, name4, opts) {
      if (types7.isAnyArrayBuffer(V3)) {
        return webidl.converters.ArrayBuffer(V3, prefix, name4, { ...opts, allowShared: false });
      }
      if (types7.isTypedArray(V3)) {
        return webidl.converters.TypedArray(V3, V3.constructor, prefix, name4, { ...opts, allowShared: false });
      }
      if (types7.isDataView(V3)) {
        return webidl.converters.DataView(V3, prefix, name4, { ...opts, allowShared: false });
      }
      throw webidl.errors.conversionFailed({
        prefix,
        argument: `${name4} ("${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 zlib5 = __require("node:zlib");
    var { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require_constants3();
    var { getGlobalOrigin } = require_global();
    var { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require_data_url();
    var { performance: performance3 } = __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 crypto18;
    try {
      crypto18 = __require("node:crypto");
      const possibleRelevantHashes = ["sha256", "sha384", "sha512"];
      supportedHashes = crypto18.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(url3) {
      for (let i4 = 0; i4 < url3.length; ++i4) {
        const code2 = url3.charCodeAt(i4);
        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 url3 = requestCurrentURL(request4);
      if (urlIsHttpHttpsScheme(url3) && badPortsSet.has(url3.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 i4 = 0; i4 < statusText.length; ++i4) {
        const c4 = statusText.charCodeAt(i4);
        if (!(c4 === 9 || // HTAB
        c4 >= 32 && c4 <= 126 || // SP / VCHAR
        c4 >= 128 && c4 <= 255)) {
          return false;
        }
      }
      return true;
    }
    __name(isValidReasonPhrase, "isValidReasonPhrase");
    var isValidHeaderName2 = 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 i4 = policyHeader.length; i4 !== 0; i4--) {
          const token2 = policyHeader[i4 - 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(performance3.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(url3, originOnly) {
      assert4(url3 instanceof URL);
      url3 = new URL(url3);
      if (url3.protocol === "file:" || url3.protocol === "about:" || url3.protocol === "blank:") {
        return "no-referrer";
      }
      url3.username = "";
      url3.password = "";
      url3.hash = "";
      if (originOnly) {
        url3.pathname = "";
        url3.search = "";
      }
      return url3;
    }
    __name(stripURLForReferrer, "stripURLForReferrer");
    function isURLPotentiallyTrustworthy(url3) {
      if (!(url3 instanceof URL)) {
        return false;
      }
      if (url3.href === "about:blank" || url3.href === "about:srcdoc") {
        return true;
      }
      if (url3.protocol === "data:") return true;
      if (url3.protocol === "file:") return true;
      return isOriginPotentiallyTrustworthy3(url3.origin);
      function isOriginPotentiallyTrustworthy3(origin2) {
        if (origin2 == null || origin2 === "null") return false;
        const originAsURL = new URL(origin2);
        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 (crypto18 === 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 metadata2 = filterMetadataListByAlgorithm(parsedMetadata, strongest);
      for (const item of metadata2) {
        const algorithm = item.algo;
        const expectedValue = item.hash;
        let actualValue = crypto18.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(metadata2) {
      const result = [];
      let empty = true;
      for (const token2 of metadata2.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 i4 = 1; i4 < metadataList.length; ++i4) {
        const metadata2 = metadataList[i4];
        if (metadata2.algo[3] === "5") {
          algorithm = "sha512";
          break;
        } else if (algorithm[3] === "3") {
          continue;
        } else if (metadata2.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 i4 = 0; i4 < metadataList.length; ++i4) {
        if (metadataList[i4].algo === algorithm) {
          metadataList[pos2++] = metadataList[i4];
        }
      }
      metadataList.length = pos2;
      return metadataList;
    }
    __name(filterMetadataListByAlgorithm, "filterMetadataListByAlgorithm");
    function compareBase64Mixed(actualValue, expectedValue) {
      if (actualValue.length !== expectedValue.length) {
        return false;
      }
      for (let i4 = 0; i4 < actualValue.length; ++i4) {
        if (actualValue[i4] !== expectedValue[i4]) {
          if (actualValue[i4] === "+" && expectedValue[i4] === "-" || actualValue[i4] === "/" && expectedValue[i4] === "_") {
            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 promise2 = new Promise((resolve42, reject) => {
        res = resolve42;
        rej = reject;
      });
      return { promise: promise2, 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(name4, 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 ${name4} 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: `${name4} Iterator`
        },
        next: { writable: true, enumerable: true, configurable: true }
      });
      return function(target, kind2) {
        return new FastIterableIterator(target, kind2);
      };
    }
    __name(createIterator, "createIterator");
    function iteratorMixin(name4, object3, kInternalIterator, keyIndex = 0, valueIndex = 1) {
      const makeIterator = createIterator(name4, 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 forEach3(callbackfn, thisArg = globalThis) {
            webidl.brandCheck(this, object3);
            webidl.argumentLengthCheck(arguments, 1, `${name4}.forEach`);
            if (typeof callbackfn !== "function") {
              throw new TypeError(
                `Failed to execute 'forEach' on '${name4}': 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(body2, processBody, processBodyError) {
      const successSteps = processBody;
      const errorSteps = processBodyError;
      let reader;
      try {
        reader = body2.stream.getReader();
      } catch (e4) {
        errorSteps(e4);
        return;
      }
      try {
        successSteps(await readAllBytes(reader));
      } catch (e4) {
        errorSteps(e4);
      }
    }
    __name(fullyReadBody, "fullyReadBody");
    function isReadableStreamLike(stream5) {
      return stream5 instanceof ReadableStream || stream5[Symbol.toStringTag] === "ReadableStream" && typeof stream5.tee === "function";
    }
    __name(isReadableStreamLike, "isReadableStreamLike");
    function readableStreamClose(controller) {
      try {
        controller.close();
        controller.byobRequest?.respond(0);
      } catch (err2) {
        if (!err2.message.includes("Controller is already closed") && !err2.message.includes("ReadableStream is already closed")) {
          throw err2;
        }
      }
    }
    __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(url3) {
      assert4("protocol" in url3);
      const protocol = url3.protocol;
      return protocol === "about:" || protocol === "blob:" || protocol === "data:";
    }
    __name(urlIsLocal, "urlIsLocal");
    function urlHasHttpsScheme(url3) {
      return typeof url3 === "string" && url3[5] === ":" && url3[0] === "h" && url3[1] === "t" && url3[2] === "t" && url3[3] === "p" && url3[4] === "s" || url3.protocol === "https:";
    }
    __name(urlHasHttpsScheme, "urlHasHttpsScheme");
    function urlIsHttpHttpsScheme(url3) {
      assert4("protocol" in url3);
      const protocol = url3.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(zlibOptions2) {
        super();
        this.#zlibOptions = zlibOptions2;
      }
      _transform(chunk, encoding, callback) {
        if (!this._inflateStream) {
          if (chunk.length === 0) {
            callback();
            return;
          }
          this._inflateStream = (chunk[0] & 15) === 8 ? zlib5.createInflate(this.#zlibOptions) : zlib5.createInflateRaw(this.#zlibOptions);
          this._inflateStream.on("data", this.push.bind(this));
          this._inflateStream.on("end", () => this.push(null));
          this._inflateStream.on("error", (err2) => this.destroy(err2));
        }
        this._inflateStream.write(chunk, encoding, callback);
      }
      _final(callback) {
        if (this._inflateStream) {
          this._inflateStream.end();
          this._inflateStream = null;
        }
        callback();
      }
    };
    function createInflate(zlibOptions2) {
      return new InflateStream(zlibOptions2);
    }
    __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(name4, list3) {
      const value = list3.get(name4, 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: isValidHeaderName2,
      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(...args2) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.stream(...args2);
      }
      arrayBuffer(...args2) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.arrayBuffer(...args2);
      }
      slice(...args2) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.slice(...args2);
      }
      text(...args2) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.text(...args2);
      }
      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 FormData7 = 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(name4, 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'"
          );
        }
        name4 = webidl.converters.USVString(name4, 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(name4, value, filename);
        this[kState].push(entry);
      }
      delete(name4) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.delete";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name4 = webidl.converters.USVString(name4, prefix, "name");
        this[kState] = this[kState].filter((entry) => entry.name !== name4);
      }
      get(name4) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.get";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name4 = webidl.converters.USVString(name4, prefix, "name");
        const idx = this[kState].findIndex((entry) => entry.name === name4);
        if (idx === -1) {
          return null;
        }
        return this[kState][idx].value;
      }
      getAll(name4) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.getAll";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name4 = webidl.converters.USVString(name4, prefix, "name");
        return this[kState].filter((entry) => entry.name === name4).map((entry) => entry.value);
      }
      has(name4) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.has";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name4 = webidl.converters.USVString(name4, prefix, "name");
        return this[kState].findIndex((entry) => entry.name === name4) !== -1;
      }
      set(name4, 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'"
          );
        }
        name4 = webidl.converters.USVString(name4, 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(name4, value, filename);
        const idx = this[kState].findIndex((entry2) => entry2.name === name4);
        if (idx !== -1) {
          this[kState] = [
            ...this[kState].slice(0, idx),
            entry,
            ...this[kState].slice(idx + 1).filter((entry2) => entry2.name !== name4)
          ];
        } 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", FormData7, kState, "name", "value");
    Object.defineProperties(FormData7.prototype, {
      append: kEnumerableProperty,
      delete: kEnumerableProperty,
      get: kEnumerableProperty,
      getAll: kEnumerableProperty,
      has: kEnumerableProperty,
      set: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "FormData",
        configurable: true
      }
    });
    function makeEntry(name4, 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: name4, value };
    }
    __name(makeEntry, "makeEntry");
    module2.exports = { FormData: FormData7, 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 i4 = 0; i4 < chars.length; ++i4) {
        if ((chars.charCodeAt(i4) & ~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 i4 = 0; i4 < length; ++i4) {
        const cp3 = boundary.charCodeAt(i4);
        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: name4, filename, contentType, encoding } = result;
        position.position += 2;
        let body2;
        {
          const boundaryIndex = input.indexOf(boundary.subarray(2), position.position);
          if (boundaryIndex === -1) {
            return "failure";
          }
          body2 = input.subarray(position.position, boundaryIndex - 4);
          position.position += body2.length;
          if (encoding === "base64") {
            body2 = Buffer.from(body2.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([body2], filename, { type: contentType });
        } else {
          value = utf8DecodeBytes(Buffer.from(body2));
        }
        assert4(isUSVString(name4));
        assert4(typeof value === "string" && isUSVString(value) || isFileLike4(value));
        entryList.push(makeEntry(name4, value, filename));
      }
    }
    __name(multipartFormDataParser, "multipartFormDataParser");
    function parseMultipartFormDataHeaders(input, position) {
      let name4 = null;
      let filename = null;
      let contentType = null;
      let encoding = null;
      while (true) {
        if (input[position.position] === 13 && input[position.position + 1] === 10) {
          if (name4 === null) {
            return "failure";
          }
          return { name: name4, 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": {
            name4 = filename = null;
            if (!bufferStartsWith(input, formDataNameBuffer, position)) {
              return "failure";
            }
            position.position += 17;
            name4 = parseMultipartFormDataName(input, position);
            if (name4 === 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 name4 = collectASequenceOfBytes(
        (char) => char !== 10 && char !== 13 && char !== 34,
        input,
        position
      );
      if (input[position.position] !== 34) {
        return null;
      } else {
        position.position++;
      }
      name4 = new TextDecoder().decode(name4).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"');
      return name4;
    }
    __name(parseMultipartFormDataName, "parseMultipartFormDataName");
    function collectASequenceOfBytes(condition, input, position) {
      let start2 = position.position;
      while (start2 < input.length && condition(input[start2])) {
        ++start2;
      }
      return input.subarray(position.position, position.position = start2);
    }
    __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, start2, position) {
      if (buffer.length < start2.length) {
        return false;
      }
      for (let i4 = 0; i4 < start2.length; i4++) {
        if (start2[i4] !== buffer[position.position + i4]) {
          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 util5 = require_util();
    var {
      ReadableStreamFrom: ReadableStreamFrom2,
      isBlobLike: isBlobLike3,
      isReadableStreamLike,
      readableStreamClose,
      createDeferredPromise,
      fullyReadBody,
      extractMimeType,
      utf8DecodeBytes
    } = require_util2();
    var { FormData: FormData7 } = 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: isArrayBuffer2 } = __require("node:util/types");
    var { serializeAMimeType } = require_data_url();
    var { multipartFormDataParser } = require_formdata_parser();
    var random2;
    try {
      const crypto18 = __require("node:crypto");
      random2 = /* @__PURE__ */ __name((max) => crypto18.randomInt(0, max), "random");
    } catch {
      random2 = /* @__PURE__ */ __name((max) => Math.floor(Math.random(max)), "random");
    }
    var textEncoder2 = new TextEncoder();
    function noop11() {
    }
    __name(noop11, "noop");
    var hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf("v18") !== 0;
    var streamRegistry;
    if (hasFinalizationRegistry) {
      streamRegistry = new FinalizationRegistry((weakRef) => {
        const stream5 = weakRef.deref();
        if (stream5 && !stream5.locked && !isDisturbed(stream5) && !isErrored(stream5)) {
          stream5.cancel("Response object has been garbage collected").catch(noop11);
        }
      });
    }
    function extractBody(object3, keepalive = false) {
      let stream5 = null;
      if (object3 instanceof ReadableStream) {
        stream5 = object3;
      } else if (isBlobLike3(object3)) {
        stream5 = object3.stream();
      } else {
        stream5 = new ReadableStream({
          async pull(controller) {
            const buffer = typeof source2 === "string" ? textEncoder2.encode(source2) : source2;
            if (buffer.byteLength) {
              controller.enqueue(buffer);
            }
            queueMicrotask(() => readableStreamClose(controller));
          },
          start() {
          },
          type: "bytes"
        });
      }
      assert4(isReadableStreamLike(stream5));
      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 (isArrayBuffer2(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 (util5.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 [name4, value] of object3) {
          if (typeof value === "string") {
            const chunk2 = textEncoder2.encode(prefix + `; name="${escape7(normalizeLinefeeds(name4))}"\r
\r
${normalizeLinefeeds(value)}\r
`);
            blobParts.push(chunk2);
            length += chunk2.byteLength;
          } else {
            const chunk2 = textEncoder2.encode(`${prefix}; name="${escape7(normalizeLinefeeds(name4))}"` + (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 = textEncoder2.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 (util5.isDisturbed(object3) || object3.locked) {
          throw new TypeError(
            "Response body object should not be disturbed or locked"
          );
        }
        stream5 = object3 instanceof ReadableStream ? object3 : ReadableStreamFrom2(object3);
      }
      if (typeof source2 === "string" || util5.isBuffer(source2)) {
        length = Buffer.byteLength(source2);
      }
      if (action != null) {
        let iterator2;
        stream5 = new ReadableStream({
          async start() {
            iterator2 = action(object3)[Symbol.asyncIterator]();
          },
          async pull(controller) {
            const { value, done } = await iterator2.next();
            if (done) {
              queueMicrotask(() => {
                controller.close();
                controller.byobRequest?.respond(0);
              });
            } else {
              if (!isErrored(stream5)) {
                const buffer = new Uint8Array(value);
                if (buffer.byteLength) {
                  controller.enqueue(buffer);
                }
              }
            }
            return controller.desiredSize > 0;
          },
          async cancel(reason) {
            await iterator2.return();
          },
          type: "bytes"
        });
      }
      const body2 = { stream: stream5, source: source2, length };
      return [body2, type];
    }
    __name(extractBody, "extractBody");
    function safelyExtractBody(object3, keepalive = false) {
      if (object3 instanceof ReadableStream) {
        assert4(!util5.isDisturbed(object3), "The body has already been consumed.");
        assert4(!object3.locked, "The stream is locked.");
      }
      return extractBody(object3, keepalive);
    }
    __name(safelyExtractBody, "safelyExtractBody");
    function cloneBody(instance2, body2) {
      const [out1, out2] = body2.stream.tee();
      body2.stream = out1;
      return {
        stream: out2,
        length: body2.length,
        source: body2.source
      };
    }
    __name(cloneBody, "cloneBody");
    function throwIfAborted(state) {
      if (state.aborted) {
        throw new DOMException("The operation was aborted.", "AbortError");
      }
    }
    __name(throwIfAborted, "throwIfAborted");
    function bodyMixinMethods(instance2) {
      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 });
          }, instance2);
        },
        arrayBuffer() {
          return consumeBody3(this, (bytes) => {
            return new Uint8Array(bytes).buffer;
          }, instance2);
        },
        text() {
          return consumeBody3(this, utf8DecodeBytes, instance2);
        },
        json() {
          return consumeBody3(this, parseJSONFromBytes, instance2);
        },
        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 FormData7();
                  fd[kState] = parsed;
                  return fd;
                }
                case "application/x-www-form-urlencoded": {
                  const entries = new URLSearchParams(value.toString());
                  const fd = new FormData7();
                  for (const [name4, value2] of entries) {
                    fd.append(name4, value2);
                  }
                  return fd;
                }
              }
            }
            throw new TypeError(
              'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
            );
          }, instance2);
        },
        bytes() {
          return consumeBody3(this, (bytes) => {
            return new Uint8Array(bytes);
          }, instance2);
        }
      };
      return methods;
    }
    __name(bodyMixinMethods, "bodyMixinMethods");
    function mixinBody(prototype2) {
      Object.assign(prototype2.prototype, bodyMixinMethods(prototype2));
    }
    __name(mixinBody, "mixinBody");
    async function consumeBody3(object3, convertBytesToJSValue, instance2) {
      webidl.brandCheck(object3, instance2);
      if (bodyUnusable(object3)) {
        throw new TypeError("Body is unusable: Body has already been read");
      }
      throwIfAborted(object3[kState]);
      const promise2 = createDeferredPromise();
      const errorSteps = /* @__PURE__ */ __name((error40) => promise2.reject(error40), "errorSteps");
      const successSteps = /* @__PURE__ */ __name((data) => {
        try {
          promise2.resolve(convertBytesToJSValue(data));
        } catch (e4) {
          errorSteps(e4);
        }
      }, "successSteps");
      if (object3[kState].body == null) {
        successSteps(Buffer.allocUnsafe(0));
        return promise2.promise;
      }
      await fullyReadBody(object3[kState].body, successSteps, errorSteps);
      return promise2.promise;
    }
    __name(consumeBody3, "consumeBody");
    function bodyUnusable(object3) {
      const body2 = object3[kState].body;
      return body2 != null && (body2.stream.locked || util5.isDisturbed(body2.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 util5 = 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 constants5 = require_constants2();
    var EMPTY_BUF = Buffer.alloc(0);
    var FastBuffer = Buffer[Symbol.species];
    var addListener = util5.addListener;
    var removeAllListeners = util5.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 start2 = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start2, 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 start2 = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start2, len)) || 0;
          }, "wasm_on_header_field"),
          wasm_on_header_value: /* @__PURE__ */ __name((p2, at2, len) => {
            assert4(currentParser.ptr === p2);
            const start2 = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start2, 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 start2 = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start2, 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 Parser6 = 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(constants5.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(delay5, type) {
        if (delay5 !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
          if (this.timeout) {
            timers.clearTimeout(this.timeout);
            this.timeout = null;
          }
          if (delay5) {
            if (type & USE_FAST_TIMER) {
              this.timeout = timers.setFastTimeout(onParserTimeout, delay5, new WeakRef(this));
            } else {
              this.timeout = setTimeout(onParserTimeout, delay5, new WeakRef(this));
              this.timeout.unref();
            }
          }
          this.timeoutValue = delay5;
        } 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 (err2) {
            throw err2;
          } finally {
            currentParser = null;
            currentBufferRef = null;
          }
          const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr;
          if (ret === constants5.ERROR.PAUSED_UPGRADE) {
            this.onUpgrade(data.slice(offset));
          } else if (ret === constants5.ERROR.PAUSED) {
            this.paused = true;
            socket.unshift(data.slice(offset));
          } else if (ret !== constants5.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, constants5.ERROR[ret], data.slice(offset));
          }
        } catch (err2) {
          util5.destroy(socket, err2);
        }
      }
      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 = util5.bufferToLowerCasedHeaderName(key);
          if (headerName === "keep-alive") {
            this.keepAlive += buf.toString();
          } else if (headerName === "connection") {
            this.connection += buf.toString();
          }
        } else if (key.length === 14 && util5.bufferToLowerCasedHeaderName(key) === "content-length") {
          this.contentLength += buf.toString();
        }
        this.trackHeader(buf.length);
      }
      trackHeader(len) {
        this.headersSize += len;
        if (this.headersSize >= this.headersMaxSize) {
          util5.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 (err2) {
          util5.destroy(socket, err2);
        }
        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) {
          util5.destroy(socket, new SocketError("bad response", util5.getSocketInfo(socket)));
          return -1;
        }
        if (upgrade && !request4.upgrade) {
          util5.destroy(socket, new SocketError("bad upgrade", util5.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 ? util5.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 ? constants5.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) {
          util5.destroy(socket, new ResponseExceededMaxSizeError());
          return -1;
        }
        this.bytesRead += buf.length;
        if (request4.onData(buf) === false) {
          return constants5.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)) {
          util5.destroy(socket, new ResponseContentLengthMismatchError());
          return -1;
        }
        request4.onComplete(headers);
        client[kQueue][client[kRunningIdx]++] = null;
        if (socket[kWriting]) {
          assert4(client[kRunning] === 0);
          util5.destroy(socket, new InformationalError("reset"));
          return constants5.ERROR.PAUSED;
        } else if (!shouldKeepAlive) {
          util5.destroy(socket, new InformationalError("reset"));
          return constants5.ERROR.PAUSED;
        } else if (socket[kReset2] && client[kRunning] === 0) {
          util5.destroy(socket, new InformationalError("reset"));
          return constants5.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");
          util5.destroy(socket, new HeadersTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_BODY) {
        if (!paused) {
          util5.destroy(socket, new BodyTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
        assert4(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]);
        util5.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 Parser6(client, socket, llhttpInstance);
      addListener(socket, "error", function(err2) {
        assert4(err2.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
        const parser6 = this[kParser];
        if (err2.code === "ECONNRESET" && parser6.statusCode && !parser6.shouldKeepAlive) {
          parser6.onMessageComplete();
          return;
        }
        this[kError] = err2;
        this[kClient][kOnError](err2);
      });
      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;
        }
        util5.destroy(this, new SocketError("other side closed", util5.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 err2 = this[kError] || new SocketError("closed", util5.getSocketInfo(this));
        client2[kSocket] = null;
        client2[kHTTPContext] = null;
        if (client2.destroyed) {
          assert4(client2[kPending] === 0);
          const requests = client2[kQueue].splice(client2[kRunningIdx]);
          for (let i4 = 0; i4 < requests.length; i4++) {
            const request4 = requests[i4];
            util5.errorRequest(client2, request4, err2);
          }
        } else if (client2[kRunning] > 0 && err2.code !== "UND_ERR_INFO") {
          const request4 = client2[kQueue][client2[kRunningIdx]];
          client2[kQueue][client2[kRunningIdx]++] = null;
          util5.errorRequest(client2, request4, err2);
        }
        client2[kPendingIdx] = client2[kRunningIdx];
        assert4(client2[kRunning] === 0);
        client2.emit("disconnect", client2[kUrl], [client2], err2);
        client2[kResume]();
      });
      let closed = false;
      socket.on("close", () => {
        closed = true;
      });
      return {
        version: "h1",
        defaultPipelining: 1,
        write(...args2) {
          return writeH1(client, ...args2);
        },
        resume() {
          resumeH1(client);
        },
        destroy(err2, callback) {
          if (closed) {
            queueMicrotask(callback);
          } else {
            socket.destroy(err2).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 && util5.bodyLength(request4.body) !== 0 && (util5.isStream(request4.body) || util5.isAsyncIterable(request4.body) || util5.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: path150, host, upgrade, blocking, reset } = request4;
      let { body: body2, headers, contentLength } = request4;
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
      if (util5.isFormDataLike(body2)) {
        if (!extractBody) {
          extractBody = require_body().extractBody;
        }
        const [bodyStream, contentType] = extractBody(body2);
        if (request4.contentType == null) {
          headers.push("content-type", contentType);
        }
        body2 = bodyStream.stream;
        contentLength = bodyStream.length;
      } else if (util5.isBlobLike(body2) && request4.contentType == null && body2.type) {
        headers.push("content-type", body2.type);
      }
      if (body2 && typeof body2.read === "function") {
        body2.read(0);
      }
      const bodyLength = util5.bodyLength(body2);
      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]) {
          util5.errorRequest(client, request4, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      const socket = client[kSocket];
      const abort2 = /* @__PURE__ */ __name((err2) => {
        if (request4.aborted || request4.completed) {
          return;
        }
        util5.errorRequest(client, request4, err2 || new RequestAbortedError());
        util5.destroy(body2);
        util5.destroy(socket, new InformationalError("aborted"));
      }, "abort");
      try {
        request4.onConnect(abort2);
      } catch (err2) {
        util5.errorRequest(client, request4, err2);
      }
      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} ${path150} 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 i4 = 0; i4 < val.length; i4++) {
              header += `${key}: ${val[i4]}\r
`;
            }
          } else {
            header += `${key}: ${val}\r
`;
          }
        }
      }
      if (channels.sendHeaders.hasSubscribers) {
        channels.sendHeaders.publish({ request: request4, headers: header, socket });
      }
      if (!body2 || bodyLength === 0) {
        writeBuffer(abort2, null, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util5.isBuffer(body2)) {
        writeBuffer(abort2, body2, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util5.isBlobLike(body2)) {
        if (typeof body2.stream === "function") {
          writeIterable(abort2, body2.stream(), client, request4, socket, contentLength, header, expectsPayload);
        } else {
          writeBlob(abort2, body2, client, request4, socket, contentLength, header, expectsPayload);
        }
      } else if (util5.isStream(body2)) {
        writeStream(abort2, body2, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util5.isIterable(body2)) {
        writeIterable(abort2, body2, client, request4, socket, contentLength, header, expectsPayload);
      } else {
        assert4(false);
      }
      return true;
    }
    __name(writeH1, "writeH1");
    function writeStream(abort2, body2, 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: abort2, 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 (err2) {
          util5.destroy(this, err2);
        }
      }, "onData");
      const onDrain = /* @__PURE__ */ __name(function() {
        if (finished2) {
          return;
        }
        if (body2.resume) {
          body2.resume();
        }
      }, "onDrain");
      const onClose = /* @__PURE__ */ __name(function() {
        queueMicrotask(() => {
          body2.removeListener("error", onFinished);
        });
        if (!finished2) {
          const err2 = new RequestAbortedError();
          queueMicrotask(() => onFinished(err2));
        }
      }, "onClose");
      const onFinished = /* @__PURE__ */ __name(function(err2) {
        if (finished2) {
          return;
        }
        finished2 = true;
        assert4(socket.destroyed || socket[kWriting] && client[kRunning] <= 1);
        socket.off("drain", onDrain).off("error", onFinished);
        body2.removeListener("data", onData).removeListener("end", onFinished).removeListener("close", onClose);
        if (!err2) {
          try {
            writer.end();
          } catch (er2) {
            err2 = er2;
          }
        }
        writer.destroy(err2);
        if (err2 && (err2.code !== "UND_ERR_INFO" || err2.message !== "reset")) {
          util5.destroy(body2, err2);
        } else {
          util5.destroy(body2);
        }
      }, "onFinished");
      body2.on("data", onData).on("end", onFinished).on("error", onFinished).on("close", onClose);
      if (body2.resume) {
        body2.resume();
      }
      socket.on("drain", onDrain).on("error", onFinished);
      if (body2.errorEmitted ?? body2.errored) {
        setImmediate(() => onFinished(body2.errored));
      } else if (body2.endEmitted ?? body2.readableEnded) {
        setImmediate(() => onFinished(null));
      }
      if (body2.closeEmitted ?? body2.closed) {
        setImmediate(onClose);
      }
    }
    __name(writeStream, "writeStream");
    function writeBuffer(abort2, body2, client, request4, socket, contentLength, header, expectsPayload) {
      try {
        if (!body2) {
          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 (util5.isBuffer(body2)) {
          assert4(contentLength === body2.byteLength, "buffer body must have content length");
          socket.cork();
          socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
          socket.write(body2);
          socket.uncork();
          request4.onBodySent(body2);
          if (!expectsPayload && request4.reset !== false) {
            socket[kReset2] = true;
          }
        }
        request4.onRequestSent();
        client[kResume]();
      } catch (err2) {
        abort2(err2);
      }
    }
    __name(writeBuffer, "writeBuffer");
    async function writeBlob(abort2, body2, client, request4, socket, contentLength, header, expectsPayload) {
      assert4(contentLength === body2.size, "blob body must have content length");
      try {
        if (contentLength != null && contentLength !== body2.size) {
          throw new RequestContentLengthMismatchError();
        }
        const buffer = Buffer.from(await body2.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 (err2) {
        abort2(err2);
      }
    }
    __name(writeBlob, "writeBlob");
    async function writeIterable(abort2, body2, 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((resolve42, reject) => {
        assert4(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve42;
        }
      }), "waitForDrain");
      socket.on("close", onDrain).on("drain", onDrain);
      const writer = new AsyncWriter({ abort: abort2, socket, request: request4, contentLength, client, expectsPayload, header });
      try {
        for await (const chunk of body2) {
          if (socket[kError]) {
            throw socket[kError];
          }
          if (!writer.write(chunk)) {
            await waitForDrain();
          }
        }
        writer.end();
      } catch (err2) {
        writer.destroy(err2);
      } finally {
        socket.off("close", onDrain).off("drain", onDrain);
      }
    }
    __name(writeIterable, "writeIterable");
    var AsyncWriter = class {
      static {
        __name(this, "AsyncWriter");
      }
      constructor({ abort: abort2, 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 = abort2;
        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(err2) {
        const { socket, client, abort: abort2 } = this;
        socket[kWriting] = false;
        if (err2) {
          assert4(client[kRunning] <= 1, "pipeline should only contain this request");
          abort2(err2);
        }
      }
    };
    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 util5 = 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 http23;
    try {
      http23 = __require("node:http2");
    } catch {
      http23 = { 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
      }
    } = http23;
    function parseH2Headers(headers) {
      const result = [];
      for (const [name4, value] of Object.entries(headers)) {
        if (Array.isArray(value)) {
          for (const subvalue of value) {
            result.push(Buffer.from(name4), Buffer.from(subvalue));
          }
        } else {
          result.push(Buffer.from(name4), 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 = http23.connect(client[kUrl], {
        createConnection: /* @__PURE__ */ __name(() => socket, "createConnection"),
        peerMaxConcurrentStreams: client[kMaxConcurrentStreams]
      });
      session[kOpenStreams] = 0;
      session[kClient] = client;
      session[kSocket] = socket;
      util5.addListener(session, "error", onHttp2SessionError);
      util5.addListener(session, "frameError", onHttp2FrameError);
      util5.addListener(session, "end", onHttp2SessionEnd);
      util5.addListener(session, "goaway", onHTTP2GoAway);
      util5.addListener(session, "close", function() {
        const { [kClient]: client2 } = this;
        const { [kSocket]: socket2 } = client2;
        const err2 = this[kSocket][kError] || this[kError] || new SocketError("closed", util5.getSocketInfo(socket2));
        client2[kHTTP2Session] = null;
        if (client2.destroyed) {
          assert4(client2[kPending] === 0);
          const requests = client2[kQueue].splice(client2[kRunningIdx]);
          for (let i4 = 0; i4 < requests.length; i4++) {
            const request4 = requests[i4];
            util5.errorRequest(client2, request4, err2);
          }
        }
      });
      session.unref();
      client[kHTTP2Session] = session;
      socket[kHTTP2Session] = session;
      util5.addListener(socket, "error", function(err2) {
        assert4(err2.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
        this[kError] = err2;
        this[kClient][kOnError](err2);
      });
      util5.addListener(socket, "end", function() {
        util5.destroy(this, new SocketError("other side closed", util5.getSocketInfo(this)));
      });
      util5.addListener(socket, "close", function() {
        const err2 = this[kError] || new SocketError("closed", util5.getSocketInfo(this));
        client[kSocket] = null;
        if (this[kHTTP2Session] != null) {
          this[kHTTP2Session].destroy(err2);
        }
        client[kPendingIdx] = client[kRunningIdx];
        assert4(client[kRunning] === 0);
        client.emit("disconnect", client[kUrl], [client], err2);
        client[kResume]();
      });
      let closed = false;
      socket.on("close", () => {
        closed = true;
      });
      return {
        version: "h2",
        defaultPipelining: Infinity,
        write(...args2) {
          return writeH2(client, ...args2);
        },
        resume() {
          resumeH2(client);
        },
        destroy(err2, callback) {
          if (closed) {
            queueMicrotask(callback);
          } else {
            socket.destroy(err2).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(err2) {
      assert4(err2.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
      this[kSocket][kError] = err2;
      this[kClient][kOnError](err2);
    }
    __name(onHttp2SessionError, "onHttp2SessionError");
    function onHttp2FrameError(type, code2, id) {
      if (id === 0) {
        const err2 = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code2}`);
        this[kSocket][kError] = err2;
        this[kClient][kOnError](err2);
      }
    }
    __name(onHttp2FrameError, "onHttp2FrameError");
    function onHttp2SessionEnd() {
      const err2 = new SocketError("other side closed", util5.getSocketInfo(this[kSocket]));
      this.destroy(err2);
      util5.destroy(this[kSocket], err2);
    }
    __name(onHttp2SessionEnd, "onHttp2SessionEnd");
    function onHTTP2GoAway(code2) {
      const err2 = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code2}`, util5.getSocketInfo(this));
      const client = this[kClient];
      client[kSocket] = null;
      client[kHTTPContext] = null;
      if (this[kHTTP2Session] != null) {
        this[kHTTP2Session].destroy(err2);
        this[kHTTP2Session] = null;
      }
      util5.destroy(this[kSocket], err2);
      if (client[kRunningIdx] < client[kQueue].length) {
        const request4 = client[kQueue][client[kRunningIdx]];
        client[kQueue][client[kRunningIdx]++] = null;
        util5.errorRequest(client, request4, err2);
        client[kPendingIdx] = client[kRunningIdx];
      }
      assert4(client[kRunning] === 0);
      client.emit("disconnect", client[kUrl], [client], err2);
      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: path150, host, upgrade, expectContinue, signal, headers: reqHeaders } = request4;
      let { body: body2 } = request4;
      if (upgrade) {
        util5.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 i4 = 0; i4 < val.length; i4++) {
            if (headers[key]) {
              headers[key] += `,${val[i4]}`;
            } else {
              headers[key] = val[i4];
            }
          }
        } else {
          headers[key] = val;
        }
      }
      let stream5;
      const { hostname: hostname4, port } = client[kUrl];
      headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname4}${port ? `:${port}` : ""}`;
      headers[HTTP2_HEADER_METHOD] = method;
      const abort2 = /* @__PURE__ */ __name((err2) => {
        if (request4.aborted || request4.completed) {
          return;
        }
        err2 = err2 || new RequestAbortedError();
        util5.errorRequest(client, request4, err2);
        if (stream5 != null) {
          util5.destroy(stream5, err2);
        }
        util5.destroy(body2, err2);
        client[kQueue][client[kRunningIdx]++] = null;
        client[kResume]();
      }, "abort");
      try {
        request4.onConnect(abort2);
      } catch (err2) {
        util5.errorRequest(client, request4, err2);
      }
      if (request4.aborted) {
        return false;
      }
      if (method === "CONNECT") {
        session.ref();
        stream5 = session.request(headers, { endStream: false, signal });
        if (stream5.id && !stream5.pending) {
          request4.onUpgrade(null, null, stream5);
          ++session[kOpenStreams];
          client[kQueue][client[kRunningIdx]++] = null;
        } else {
          stream5.once("ready", () => {
            request4.onUpgrade(null, null, stream5);
            ++session[kOpenStreams];
            client[kQueue][client[kRunningIdx]++] = null;
          });
        }
        stream5.once("close", () => {
          session[kOpenStreams] -= 1;
          if (session[kOpenStreams] === 0) session.unref();
        });
        return true;
      }
      headers[HTTP2_HEADER_PATH] = path150;
      headers[HTTP2_HEADER_SCHEME] = "https";
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
      if (body2 && typeof body2.read === "function") {
        body2.read(0);
      }
      let contentLength = util5.bodyLength(body2);
      if (util5.isFormDataLike(body2)) {
        extractBody ??= require_body().extractBody;
        const [bodyStream, contentType] = extractBody(body2);
        headers["content-type"] = contentType;
        body2 = 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]) {
          util5.errorRequest(client, request4, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      if (contentLength != null) {
        assert4(body2, "no body must not have content length");
        headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
      }
      session.ref();
      const shouldEndStream = method === "GET" || method === "HEAD" || body2 === null;
      if (expectContinue) {
        headers[HTTP2_HEADER_EXPECT] = "100-continue";
        stream5 = session.request(headers, { endStream: shouldEndStream, signal });
        stream5.once("continue", writeBodyH2);
      } else {
        stream5 = session.request(headers, {
          endStream: shouldEndStream,
          signal
        });
        writeBodyH2();
      }
      ++session[kOpenStreams];
      stream5.once("response", (headers2) => {
        const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
        request4.onResponseStarted();
        if (request4.aborted) {
          const err2 = new RequestAbortedError();
          util5.errorRequest(client, request4, err2);
          util5.destroy(stream5, err2);
          return;
        }
        if (request4.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream5.resume.bind(stream5), "") === false) {
          stream5.pause();
        }
        stream5.on("data", (chunk) => {
          if (request4.onData(chunk) === false) {
            stream5.pause();
          }
        });
      });
      stream5.once("end", () => {
        if (stream5.state?.state == null || stream5.state.state < 6) {
          request4.onComplete([]);
        }
        if (session[kOpenStreams] === 0) {
          session.unref();
        }
        abort2(new InformationalError("HTTP/2: stream half-closed (remote)"));
        client[kQueue][client[kRunningIdx]++] = null;
        client[kPendingIdx] = client[kRunningIdx];
        client[kResume]();
      });
      stream5.once("close", () => {
        session[kOpenStreams] -= 1;
        if (session[kOpenStreams] === 0) {
          session.unref();
        }
      });
      stream5.once("error", function(err2) {
        abort2(err2);
      });
      stream5.once("frameError", (type, code2) => {
        abort2(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code2}`));
      });
      return true;
      function writeBodyH2() {
        if (!body2 || contentLength === 0) {
          writeBuffer(
            abort2,
            stream5,
            null,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util5.isBuffer(body2)) {
          writeBuffer(
            abort2,
            stream5,
            body2,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util5.isBlobLike(body2)) {
          if (typeof body2.stream === "function") {
            writeIterable(
              abort2,
              stream5,
              body2.stream(),
              client,
              request4,
              client[kSocket],
              contentLength,
              expectsPayload
            );
          } else {
            writeBlob(
              abort2,
              stream5,
              body2,
              client,
              request4,
              client[kSocket],
              contentLength,
              expectsPayload
            );
          }
        } else if (util5.isStream(body2)) {
          writeStream(
            abort2,
            client[kSocket],
            expectsPayload,
            stream5,
            body2,
            client,
            request4,
            contentLength
          );
        } else if (util5.isIterable(body2)) {
          writeIterable(
            abort2,
            stream5,
            body2,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else {
          assert4(false);
        }
      }
      __name(writeBodyH2, "writeBodyH2");
    }
    __name(writeH2, "writeH2");
    function writeBuffer(abort2, h2stream, body2, client, request4, socket, contentLength, expectsPayload) {
      try {
        if (body2 != null && util5.isBuffer(body2)) {
          assert4(contentLength === body2.byteLength, "buffer body must have content length");
          h2stream.cork();
          h2stream.write(body2);
          h2stream.uncork();
          h2stream.end();
          request4.onBodySent(body2);
        }
        if (!expectsPayload) {
          socket[kReset2] = true;
        }
        request4.onRequestSent();
        client[kResume]();
      } catch (error40) {
        abort2(error40);
      }
    }
    __name(writeBuffer, "writeBuffer");
    function writeStream(abort2, socket, expectsPayload, h2stream, body2, client, request4, contentLength) {
      assert4(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      const pipe2 = pipeline3(
        body2,
        h2stream,
        (err2) => {
          if (err2) {
            util5.destroy(pipe2, err2);
            abort2(err2);
          } else {
            util5.removeAllListeners(pipe2);
            request4.onRequestSent();
            if (!expectsPayload) {
              socket[kReset2] = true;
            }
            client[kResume]();
          }
        }
      );
      util5.addListener(pipe2, "data", onPipeData);
      function onPipeData(chunk) {
        request4.onBodySent(chunk);
      }
      __name(onPipeData, "onPipeData");
    }
    __name(writeStream, "writeStream");
    async function writeBlob(abort2, h2stream, body2, client, request4, socket, contentLength, expectsPayload) {
      assert4(contentLength === body2.size, "blob body must have content length");
      try {
        if (contentLength != null && contentLength !== body2.size) {
          throw new RequestContentLengthMismatchError();
        }
        const buffer = Buffer.from(await body2.arrayBuffer());
        h2stream.cork();
        h2stream.write(buffer);
        h2stream.uncork();
        h2stream.end();
        request4.onBodySent(buffer);
        request4.onRequestSent();
        if (!expectsPayload) {
          socket[kReset2] = true;
        }
        client[kResume]();
      } catch (err2) {
        abort2(err2);
      }
    }
    __name(writeBlob, "writeBlob");
    async function writeIterable(abort2, h2stream, body2, 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((resolve42, reject) => {
        assert4(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve42;
        }
      }), "waitForDrain");
      h2stream.on("close", onDrain).on("drain", onDrain);
      try {
        for await (const chunk of body2) {
          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 (err2) {
        abort2(err2);
      } 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 util5 = 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(body2) {
        this[kBody] = body2;
        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");
        }
        util5.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 (util5.isStream(this.opts.body)) {
          if (util5.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) && util5.isIterable(this.opts.body)) {
          this.opts.body = new BodyAsyncIterable(this.opts.body);
        }
      }
      onConnect(abort2) {
        this.abort = abort2;
        this.handler.onConnect(abort2, { history: this.history });
      }
      onUpgrade(statusCode, headers, socket) {
        this.handler.onUpgrade(statusCode, headers, socket);
      }
      onError(error40) {
        this.handler.onError(error40);
      }
      onHeaders(statusCode, headers, resume, statusText) {
        this.location = this.history.length >= this.maxRedirections || util5.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: origin2, pathname, search } = util5.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
        const path150 = search ? `${pathname}${search}` : pathname;
        this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin2);
        this.opts.path = path150;
        this.opts.origin = origin2;
        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 i4 = 0; i4 < headers.length; i4 += 2) {
        if (headers[i4].length === 8 && util5.headerNameToString(headers[i4]) === "location") {
          return headers[i4 + 1];
        }
      }
    }
    __name(parseLocation, "parseLocation");
    function shouldRemoveHeader(header, removeContent, unknownOrigin) {
      if (header.length === 4) {
        return util5.headerNameToString(header) === "host";
      }
      if (removeContent && util5.headerNameToString(header).startsWith("content-")) {
        return true;
      }
      if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
        const name4 = util5.headerNameToString(header);
        return name4 === "authorization" || name4 === "cookie" || name4 === "proxy-authorization";
      }
      return false;
    }
    __name(shouldRemoveHeader, "shouldRemoveHeader");
    function cleanRequestHeaders(headers, removeContent, unknownOrigin) {
      const ret = [];
      if (Array.isArray(headers)) {
        for (let i4 = 0; i4 < headers.length; i4 += 2) {
          if (!shouldRemoveHeader(headers[i4], removeContent, unknownOrigin)) {
            ret.push(headers[i4], headers[i4 + 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 http9 = __require("node:http");
    var util5 = 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 noop11 = /* @__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(url3, {
        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] = util5.parseOrigin(url3);
        this[kConnector] = connect2;
        this[kPipelining] = pipelining != null ? pipelining : 1;
        this[kMaxHeadersSize] = maxHeaderSize || http9.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] = (err2) => onError2(this, err2);
      }
      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 origin2 = opts.origin || this[kUrl].origin;
        const request4 = new Request6(origin2, opts, handler);
        this[kQueue].push(request4);
        if (this[kResuming]) {
        } else if (util5.bodyLength(request4.body) == null && util5.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((resolve42) => {
          if (this[kSize]) {
            this[kClosedResolve] = resolve42;
          } else {
            resolve42(null);
          }
        });
      }
      async [kDestroy](err2) {
        return new Promise((resolve42) => {
          const requests = this[kQueue].splice(this[kPendingIdx]);
          for (let i4 = 0; i4 < requests.length; i4++) {
            const request4 = requests[i4];
            util5.errorRequest(this, request4, err2);
          }
          const callback = /* @__PURE__ */ __name(() => {
            if (this[kClosedResolve]) {
              this[kClosedResolve]();
              this[kClosedResolve] = null;
            }
            resolve42(null);
          }, "callback");
          if (this[kHTTPContext]) {
            this[kHTTPContext].destroy(err2, callback);
            this[kHTTPContext] = null;
          } else {
            queueMicrotask(callback);
          }
          this[kResume]();
        });
      }
    };
    var createRedirectInterceptor = require_redirect_interceptor();
    function onError2(client, err2) {
      if (client[kRunning] === 0 && err2.code !== "UND_ERR_INFO" && err2.code !== "UND_ERR_SOCKET") {
        assert4(client[kPendingIdx] === client[kRunningIdx]);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i4 = 0; i4 < requests.length; i4++) {
          const request4 = requests[i4];
          util5.errorRequest(client, request4, err2);
        }
        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((resolve42, reject) => {
          client[kConnector]({
            host,
            hostname: hostname4,
            protocol,
            port,
            servername: client[kServerName],
            localAddress: client[kLocalAddress]
          }, (err2, socket2) => {
            if (err2) {
              reject(err2);
            } else {
              resolve42(socket2);
            }
          });
        });
        if (client.destroyed) {
          util5.destroy(socket.on("error", noop11), new ClientDestroyedError());
          return;
        }
        assert4(socket);
        try {
          client[kHTTPContext] = socket.alpnProtocol === "h2" ? await connectH2(client, socket) : await connectH1(client, socket);
        } catch (err2) {
          socket.destroy().on("error", noop11);
          throw err2;
        }
        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 (err2) {
        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: err2
          });
        }
        if (err2.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]++];
            util5.errorRequest(client, request4, err2);
          }
        } else {
          onError2(client, err2);
        }
        client.emit("connectionError", client[kUrl], [client], err2);
      }
      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(origin2, 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", origin2, [pool, ...targets]);
          }
          if (pool[kClosedResolve] && queue.isEmpty()) {
            Promise.all(pool[kClients].map((c4) => c4.close())).then(pool[kClosedResolve]);
          }
        }, "onDrain");
        this[kOnConnect] = (origin2, targets) => {
          pool.emit("connect", origin2, [pool, ...targets]);
        };
        this[kOnDisconnect] = (origin2, targets, err2) => {
          pool.emit("disconnect", origin2, [pool, ...targets], err2);
        };
        this[kOnConnectionError] = (origin2, targets, err2) => {
          pool.emit("connectionError", origin2, [pool, ...targets], err2);
        };
        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((resolve42) => {
            this[kClosedResolve] = resolve42;
          });
        }
      }
      async [kDestroy](err2) {
        while (true) {
          const item = this[kQueue].shift();
          if (!item) {
            break;
          }
          item.handler.onError(err2);
        }
        await Promise.all(this[kClients].map((c4) => c4.destroy(err2)));
      }
      [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 util5 = 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(origin2, opts) {
      return new Client3(origin2, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var Pool = class extends PoolBase {
      static {
        __name(this, "Pool");
      }
      constructor(origin2, {
        connections,
        factory: factory2 = 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 factory2 !== "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] = util5.parseOrigin(origin2);
        this[kOptions] = { ...util5.deepClone(options2), connect, allowH2 };
        this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
        this[kFactory] = factory2;
        this.on("connectionError", (origin3, targets, error40) => {
          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(origin2, opts) {
      return new Pool(origin2, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var BalancedPool = class extends PoolBase {
      static {
        __name(this, "BalancedPool");
      }
      constructor(upstreams = [], { factory: factory2 = 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 factory2 !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) ? opts.interceptors.BalancedPool : [];
        this[kFactory] = factory2;
        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", (...args2) => {
          const err2 = args2[2];
          if (err2 && err2.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 i4 = 0; i4 < this[kClients].length; i4++) {
          result = getGreatestCommonDivisor(this[kClients][i4][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 util5 = 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(origin2, opts) {
      return opts && opts.connections === 1 ? new Client3(origin2, opts) : new Pool(origin2, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var Agent4 = class extends DispatcherBase {
      static {
        __name(this, "Agent");
      }
      constructor({ factory: factory2 = defaultFactory, maxRedirections = 0, connect, ...options2 } = {}) {
        super();
        if (typeof factory2 !== "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] = { ...util5.deepClone(options2), connect };
        this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
        this[kMaxRedirections] = maxRedirections;
        this[kFactory] = factory2;
        this[kClients] = /* @__PURE__ */ new Map();
        this[kOnDrain] = (origin2, targets) => {
          this.emit("drain", origin2, [this, ...targets]);
        };
        this[kOnConnect] = (origin2, targets) => {
          this.emit("connect", origin2, [this, ...targets]);
        };
        this[kOnDisconnect] = (origin2, targets, err2) => {
          this.emit("disconnect", origin2, [this, ...targets], err2);
        };
        this[kOnConnectionError] = (origin2, targets, err2) => {
          this.emit("connectionError", origin2, [this, ...targets], err2);
        };
      }
      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](err2) {
        const destroyPromises = [];
        for (const client of this[kClients].values()) {
          destroyPromises.push(client.destroy(err2));
        }
        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(origin2, opts) {
      return new Pool(origin2, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var noop11 = /* @__PURE__ */ __name(() => {
    }, "noop");
    function defaultAgentFactory(origin2, opts) {
      if (opts.connections === 1) {
        return new Client3(origin2, opts);
      }
      return new Pool(origin2, opts);
    }
    __name(defaultAgentFactory, "defaultAgentFactory");
    var Http1ProxyWrapper = class extends DispatcherBase {
      static {
        __name(this, "Http1ProxyWrapper");
      }
      #client;
      constructor(proxyUrl, { headers = {}, connect, factory: factory2 }) {
        super();
        if (!proxyUrl) {
          throw new InvalidArgumentError("Proxy URL is mandatory");
        }
        this[kProxyHeaders] = headers;
        if (factory2) {
          this.#client = factory2(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: origin2,
          path: path150 = "/",
          headers = {}
        } = opts;
        opts.path = origin2 + path150;
        if (!("host" in headers) && !("Host" in headers)) {
          const { host } = new URL5(origin2);
          headers.host = host;
        }
        opts.headers = { ...this[kProxyHeaders], ...headers };
        return this.#client[kDispatch](opts, handler);
      }
      async [kClose]() {
        return this.#client.close();
      }
      async [kDestroy](err2) {
        return this.#client.destroy(err2);
      }
    };
    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 url3 = this.#getUrl(opts);
        const { href, origin: origin2, port, protocol, username, password, hostname: proxyHostname } = url3;
        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 factory2 = /* @__PURE__ */ __name((origin3, options2) => {
          const { protocol: protocol2 } = new URL5(origin3);
          if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
            return new Http1ProxyWrapper(this[kProxy].uri, {
              headers: this[kProxyHeaders],
              connect,
              factory: agentFactory
            });
          }
          return agentFactory(origin3, options2);
        }, "factory");
        this[kClient] = clientFactory(url3, { connect });
        this[kAgent] = new Agent4({
          ...opts,
          factory: factory2,
          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: origin2,
                port,
                path: requestedPath,
                signal: opts2.signal,
                headers: {
                  ...this[kProxyHeaders],
                  host: opts2.host
                },
                servername: this[kProxyTls]?.servername || proxyHostname
              });
              if (statusCode !== 200) {
                socket.on("error", noop11).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 (err2) {
              if (err2.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
                callback(new SecureProxyConnectionError(err2));
              } else {
                callback(err2);
              }
            }
          }, "connect")
        });
      }
      dispatch(opts, handler) {
        const headers = buildHeaders3(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 buildHeaders3(headers) {
      if (Array.isArray(headers)) {
        const headersPair = {};
        for (let i4 = 0; i4 < headers.length; i4 += 2) {
          headersPair[headers[i4]] = headers[i4 + 1];
        }
        return headersPair;
      }
      return headers;
    }
    __name(buildHeaders3, "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 url3 = new URL(opts.origin);
        const agent = this.#getProxyAgentForUrl(url3);
        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](err2) {
        await this[kNoProxyAgent].destroy(err2);
        if (!this[kHttpProxyAgent][kDestroyed]) {
          await this[kHttpProxyAgent].destroy(err2);
        }
        if (!this[kHttpsProxyAgent][kDestroyed]) {
          await this[kHttpsProxyAgent].destroy(err2);
        }
      }
      #getProxyAgentForUrl(url3) {
        let { protocol, host: hostname4, port } = url3;
        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 i4 = 0; i4 < this.#noProxyEntries.length; i4++) {
          const entry = this.#noProxyEntries[i4];
          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 i4 = 0; i4 < noProxySplit.length; i4++) {
          const entry = noProxySplit[i4];
          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(abort2) {
        if (this.aborted) {
          abort2(this.reason);
        } else {
          this.abort = abort2;
        }
      }
      onBodySent(chunk) {
        if (this.handler.onBodySent) return this.handler.onBodySent(chunk);
      }
      static [kRetryHandlerDefaultRetry](err2, { state, opts }, cb) {
        const { statusCode, code: code2, headers } = err2;
        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(err2);
          return;
        }
        if (Array.isArray(methods) && !methods.includes(method)) {
          cb(err2);
          return;
        }
        if (statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode)) {
          cb(err2);
          return;
        }
        if (counter > maxRetries) {
          cb(err2);
          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: start2, size, end = size - 1 } = contentRange;
          assert4(this.start === start2, "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: start2, size, end = size - 1 } = range;
            assert4(
              start2 != null && Number.isFinite(start2),
              "content-range mismatch"
            );
            assert4(end != null && Number.isFinite(end), "invalid content-length");
            this.start = start2;
            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 err2 = new RequestRetryError("Request failed", statusCode, {
          headers,
          data: { count: this.retryCount }
        });
        this.abort(err2);
        return false;
      }
      onData(chunk) {
        this.start += chunk.length;
        return this.handler.onData(chunk);
      }
      onComplete(rawTrailers) {
        this.retryCount = 0;
        return this.handler.onComplete(rawTrailers);
      }
      onError(err2) {
        if (this.aborted || isDisturbed(this.opts.body)) {
          return this.handler.onError(err2);
        }
        if (this.retryCount - this.retryCountCheckpoint > 0) {
          this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint);
        } else {
          this.retryCount += 1;
        }
        this.retryOpts.retry(
          err2,
          {
            state: { counter: this.retryCount },
            opts: { retryOptions: this.retryOpts, ...this.opts }
          },
          onRetry.bind(this)
        );
        function onRetry(err3) {
          if (err3 != null || this.aborted || isDisturbed(this.opts.body)) {
            return this.handler.onError(err3);
          }
          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 (err4) {
            this.handler.onError(err4);
          }
        }
        __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: Readable8 } = __require("node:stream");
    var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError: AbortError4 } = require_errors();
    var util5 = 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 noop11 = /* @__PURE__ */ __name(() => {
    }, "noop");
    var BodyReadable = class extends Readable8 {
      static {
        __name(this, "BodyReadable");
      }
      constructor({
        resume,
        abort: abort2,
        contentType = "",
        contentLength,
        highWaterMark = 64 * 1024
        // Same as nodejs fs streams.
      }) {
        super({
          autoDestroy: true,
          read: resume,
          highWaterMark
        });
        this._readableState.dataEmitted = false;
        this[kAbort] = abort2;
        this[kConsume] = null;
        this[kBody] = null;
        this[kContentType] = contentType;
        this[kContentLength] = contentLength;
        this[kReading] = false;
      }
      destroy(err2) {
        if (!err2 && !this._readableState.endEmitted) {
          err2 = new RequestAbortedError();
        }
        if (err2) {
          this[kAbort]();
        }
        return super.destroy(err2);
      }
      _destroy(err2, callback) {
        if (!this[kReading]) {
          setImmediate(() => {
            callback(err2);
          });
        } else {
          callback(err2);
        }
      }
      on(ev, ...args2) {
        if (ev === "data" || ev === "readable") {
          this[kReading] = true;
        }
        return super.on(ev, ...args2);
      }
      addListener(ev, ...args2) {
        return this.on(ev, ...args2);
      }
      off(ev, ...args2) {
        const ret = super.off(ev, ...args2);
        if (ev === "data" || ev === "readable") {
          this[kReading] = this.listenerCount("data") > 0 || this.listenerCount("readable") > 0;
        }
        return ret;
      }
      removeListener(ev, ...args2) {
        return this.off(ev, ...args2);
      }
      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 util5.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((resolve42, 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 {
              resolve42(null);
            }
          }).on("error", noop11).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 util5.isDisturbed(self2) || isLocked(self2);
    }
    __name(isUnusable, "isUnusable");
    async function consume(stream5, type) {
      assert4(!stream5[kConsume]);
      return new Promise((resolve42, reject) => {
        if (isUnusable(stream5)) {
          const rState = stream5._readableState;
          if (rState.destroyed && rState.closeEmitted === false) {
            stream5.on("error", (err2) => {
              reject(err2);
            }).on("close", () => {
              reject(new TypeError("unusable"));
            });
          } else {
            reject(rState.errored ?? new TypeError("unusable"));
          }
        } else {
          queueMicrotask(() => {
            stream5[kConsume] = {
              type,
              stream: stream5,
              resolve: resolve42,
              reject,
              length: 0,
              body: []
            };
            stream5.on("error", function(err2) {
              consumeFinish(this[kConsume], err2);
            }).on("close", function() {
              if (this[kConsume].body !== null) {
                consumeFinish(this[kConsume], new RequestAbortedError());
              }
            });
            consumeStart(stream5[kConsume]);
          });
        }
      });
    }
    __name(consume, "consume");
    function consumeStart(consume2) {
      if (consume2.body === null) {
        return;
      }
      const { _readableState: state } = consume2.stream;
      if (state.bufferIndex) {
        const start2 = state.bufferIndex;
        const end = state.buffer.length;
        for (let n3 = start2; 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 start2 = bufferLength > 2 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191 ? 3 : 0;
      return buffer.utf8Slice(start2, 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 i4 = 0; i4 < chunks.length; ++i4) {
        const chunk = chunks[i4];
        buffer.set(chunk, offset);
        offset += chunk.length;
      }
      return buffer;
    }
    __name(chunksConcat, "chunksConcat");
    function consumeEnd(consume2) {
      const { type, body: body2, resolve: resolve42, stream: stream5, length } = consume2;
      try {
        if (type === "text") {
          resolve42(chunksDecode(body2, length));
        } else if (type === "json") {
          resolve42(JSON.parse(chunksDecode(body2, length)));
        } else if (type === "arrayBuffer") {
          resolve42(chunksConcat(body2, length).buffer);
        } else if (type === "blob") {
          resolve42(new Blob(body2, { type: stream5[kContentType] }));
        } else if (type === "bytes") {
          resolve42(chunksConcat(body2, length));
        }
        consumeFinish(consume2);
      } catch (err2) {
        stream5.destroy(err2);
      }
    }
    __name(consumeEnd, "consumeEnd");
    function consumePush(consume2, chunk) {
      consume2.length += chunk.length;
      consume2.body.push(chunk);
    }
    __name(consumePush, "consumePush");
    function consumeFinish(consume2, err2) {
      if (consume2.body === null) {
        return;
      }
      if (err2) {
        consume2.reject(err2);
      } 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_LIMIT2 = 128 * 1024;
    async function getResolveErrorBodyCallback({ callback, body: body2, contentType, statusCode, statusMessage, headers }) {
      assert4(body2);
      let chunks = [];
      let length = 0;
      try {
        for await (const chunk of body2) {
          chunks.push(chunk);
          length += chunk.length;
          if (length > CHUNK_LIMIT2) {
            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: Readable8 } = require_readable();
    var { InvalidArgumentError, RequestAbortedError } = require_errors();
    var util5 = 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: body2, 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 (err2) {
          if (util5.isStream(body2)) {
            util5.destroy(body2.on("error", util5.nop), err2);
          }
          throw err2;
        }
        this.method = method;
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.callback = callback;
        this.res = null;
        this.abort = null;
        this.body = body2;
        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 (util5.isStream(body2)) {
          body2.on("error", (err2) => {
            this.onError(err2);
          });
        }
        if (this.signal) {
          if (this.signal.aborted) {
            this.reason = this.signal.reason ?? new RequestAbortedError();
          } else {
            this.removeAbortListener = util5.addAbortListener(this.signal, () => {
              this.reason = this.signal.reason ?? new RequestAbortedError();
              if (this.res) {
                util5.destroy(this.res.on("error", util5.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(abort2, context2) {
        if (this.reason) {
          abort2(this.reason);
          return;
        }
        assert4(this.callback);
        this.abort = abort2;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const { callback, opaque, abort: abort2, context: context2, responseHeaders, highWaterMark } = this;
        const headers = responseHeaders === "raw" ? util5.parseRawHeaders(rawHeaders) : util5.parseHeaders(rawHeaders);
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        const parsedHeaders = responseHeaders === "raw" ? util5.parseHeaders(rawHeaders) : headers;
        const contentType = parsedHeaders["content-type"];
        const contentLength = parsedHeaders["content-length"];
        const res = new Readable8({
          resume,
          abort: abort2,
          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) {
        util5.parseHeaders(trailers, this.trailers);
        this.res.push(null);
      }
      onError(err2) {
        const { res, callback, body: body2, opaque } = this;
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err2, { opaque });
          });
        }
        if (res) {
          this.res = null;
          queueMicrotask(() => {
            util5.destroy(res, err2);
          });
        }
        if (body2) {
          this.body = null;
          util5.destroy(body2, err2);
        }
        if (this.removeAbortListener) {
          res?.off("close", this.removeAbortListener);
          this.removeAbortListener();
          this.removeAbortListener = null;
        }
      }
    };
    function request4(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve42, reject) => {
          request4.call(this, opts, (err2, data) => {
            return err2 ? reject(err2) : resolve42(data);
          });
        });
      }
      try {
        this.dispatch(opts, new RequestHandler(opts, callback));
      } catch (err2) {
        if (typeof callback !== "function") {
          throw err2;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err2, { 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 abort2(self2) {
      if (self2.abort) {
        self2.abort(self2[kSignal]?.reason);
      } else {
        self2.reason = self2[kSignal]?.reason ?? new RequestAbortedError();
      }
      removeSignal(self2);
    }
    __name(abort2, "abort");
    function addSignal(self2, signal) {
      self2.reason = null;
      self2[kSignal] = null;
      self2[kListener] = null;
      if (!signal) {
        return;
      }
      if (signal.aborted) {
        abort2(self2);
        return;
      }
      self2[kSignal] = signal;
      self2[kListener] = () => {
        abort2(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 util5 = 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, factory2, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        const { signal, method, opaque, body: body2, onInfo, responseHeaders, throwOnError } = opts;
        try {
          if (typeof callback !== "function") {
            throw new InvalidArgumentError("invalid callback");
          }
          if (typeof factory2 !== "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 (err2) {
          if (util5.isStream(body2)) {
            util5.destroy(body2.on("error", util5.nop), err2);
          }
          throw err2;
        }
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.factory = factory2;
        this.callback = callback;
        this.res = null;
        this.abort = null;
        this.context = null;
        this.trailers = null;
        this.body = body2;
        this.onInfo = onInfo || null;
        this.throwOnError = throwOnError || false;
        if (util5.isStream(body2)) {
          body2.on("error", (err2) => {
            this.onError(err2);
          });
        }
        addSignal(this, signal);
      }
      onConnect(abort2, context2) {
        if (this.reason) {
          abort2(this.reason);
          return;
        }
        assert4(this.callback);
        this.abort = abort2;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const { factory: factory2, opaque, context: context2, callback, responseHeaders } = this;
        const headers = responseHeaders === "raw" ? util5.parseRawHeaders(rawHeaders) : util5.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" ? util5.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 (factory2 === null) {
            return;
          }
          res = this.runInAsyncScope(factory2, 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 }, (err2) => {
            const { callback: callback2, res: res2, opaque: opaque2, trailers, abort: abort2 } = this;
            this.res = null;
            if (err2 || !res2.readable) {
              util5.destroy(res2, err2);
            }
            this.callback = null;
            this.runInAsyncScope(callback2, null, err2 || null, { opaque: opaque2, trailers });
            if (err2) {
              abort2();
            }
          });
        }
        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 = util5.parseHeaders(trailers);
        res.end();
      }
      onError(err2) {
        const { res, callback, opaque, body: body2 } = this;
        removeSignal(this);
        this.factory = null;
        if (res) {
          this.res = null;
          util5.destroy(res, err2);
        } else if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err2, { opaque });
          });
        }
        if (body2) {
          this.body = null;
          util5.destroy(body2, err2);
        }
      }
    };
    function stream5(opts, factory2, callback) {
      if (callback === void 0) {
        return new Promise((resolve42, reject) => {
          stream5.call(this, opts, factory2, (err2, data) => {
            return err2 ? reject(err2) : resolve42(data);
          });
        });
      }
      try {
        this.dispatch(opts, new StreamHandler(opts, factory2, callback));
      } catch (err2) {
        if (typeof callback !== "function") {
          throw err2;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err2, { opaque }));
      }
    }
    __name(stream5, "stream");
    module2.exports = stream5;
  }
});

// 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: Readable8,
      Duplex,
      PassThrough: PassThrough8
    } = __require("node:stream");
    var {
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError
    } = require_errors();
    var util5 = 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 Readable8 {
      static {
        __name(this, "PipelineRequest");
      }
      constructor() {
        super({ autoDestroy: true });
        this[kResume] = null;
      }
      _read() {
        const { [kResume]: resume } = this;
        if (resume) {
          this[kResume] = null;
          resume();
        }
      }
      _destroy(err2, callback) {
        this._read();
        callback(err2);
      }
    };
    var PipelineResponse = class extends Readable8 {
      static {
        __name(this, "PipelineResponse");
      }
      constructor(resume) {
        super({ autoDestroy: true });
        this[kResume] = resume;
      }
      _read() {
        this[kResume]();
      }
      _destroy(err2, callback) {
        if (!err2 && !this._readableState.endEmitted) {
          err2 = new RequestAbortedError();
        }
        callback(err2);
      }
    };
    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", util5.nop);
        this.ret = new Duplex({
          readableObjectMode: opts.objectMode,
          autoDestroy: true,
          read: /* @__PURE__ */ __name(() => {
            const { body: body2 } = this;
            if (body2?.resume) {
              body2.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((err2, callback) => {
            const { body: body2, req, res, ret, abort: abort2 } = this;
            if (!err2 && !ret._readableState.endEmitted) {
              err2 = new RequestAbortedError();
            }
            if (abort2 && err2) {
              abort2();
            }
            util5.destroy(body2, err2);
            util5.destroy(req, err2);
            util5.destroy(res, err2);
            removeSignal(this);
            callback(err2);
          }, "destroy")
        }).on("prefinish", () => {
          const { req } = this;
          req.push(null);
        });
        this.res = null;
        addSignal(this, signal);
      }
      onConnect(abort2, context2) {
        const { ret, res } = this;
        if (this.reason) {
          abort2(this.reason);
          return;
        }
        assert4(!res, "pipeline cannot be retried");
        assert4(!ret.destroyed);
        this.abort = abort2;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume) {
        const { opaque, handler, context: context2 } = this;
        if (statusCode < 200) {
          if (this.onInfo) {
            const headers = this.responseHeaders === "raw" ? util5.parseRawHeaders(rawHeaders) : util5.parseHeaders(rawHeaders);
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        this.res = new PipelineResponse(resume);
        let body2;
        try {
          this.handler = null;
          const headers = this.responseHeaders === "raw" ? util5.parseRawHeaders(rawHeaders) : util5.parseHeaders(rawHeaders);
          body2 = this.runInAsyncScope(handler, null, {
            statusCode,
            headers,
            opaque,
            body: this.res,
            context: context2
          });
        } catch (err2) {
          this.res.on("error", util5.nop);
          throw err2;
        }
        if (!body2 || typeof body2.on !== "function") {
          throw new InvalidReturnValueError("expected Readable");
        }
        body2.on("data", (chunk) => {
          const { ret, body: body3 } = this;
          if (!ret.push(chunk) && body3.pause) {
            body3.pause();
          }
        }).on("error", (err2) => {
          const { ret } = this;
          util5.destroy(ret, err2);
        }).on("end", () => {
          const { ret } = this;
          ret.push(null);
        }).on("close", () => {
          const { ret } = this;
          if (!ret._readableState.ended) {
            util5.destroy(ret, new RequestAbortedError());
          }
        });
        this.body = body2;
      }
      onData(chunk) {
        const { res } = this;
        return res.push(chunk);
      }
      onComplete(trailers) {
        const { res } = this;
        res.push(null);
      }
      onError(err2) {
        const { ret } = this;
        this.handler = null;
        util5.destroy(ret, err2);
      }
    };
    function pipeline3(opts, handler) {
      try {
        const pipelineHandler = new PipelineHandler(opts, handler);
        this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
        return pipelineHandler.ret;
      } catch (err2) {
        return new PassThrough8().destroy(err2);
      }
    }
    __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 util5 = 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(abort2, context2) {
        if (this.reason) {
          abort2(this.reason);
          return;
        }
        assert4(this.callback);
        this.abort = abort2;
        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" ? util5.parseRawHeaders(rawHeaders) : util5.parseHeaders(rawHeaders);
        this.runInAsyncScope(callback, null, null, {
          headers,
          socket,
          opaque,
          context: context2
        });
      }
      onError(err2) {
        const { callback, opaque } = this;
        removeSignal(this);
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err2, { opaque });
          });
        }
      }
    };
    function upgrade(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve42, reject) => {
          upgrade.call(this, opts, (err2, data) => {
            return err2 ? reject(err2) : resolve42(data);
          });
        });
      }
      try {
        const upgradeHandler = new UpgradeHandler(opts, callback);
        this.dispatch({
          ...opts,
          method: opts.method || "GET",
          upgrade: opts.protocol || "Websocket"
        }, upgradeHandler);
      } catch (err2) {
        if (typeof callback !== "function") {
          throw err2;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err2, { 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 util5 = 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(abort2, context2) {
        if (this.reason) {
          abort2(this.reason);
          return;
        }
        assert4(this.callback);
        this.abort = abort2;
        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" ? util5.parseRawHeaders(rawHeaders) : util5.parseHeaders(rawHeaders);
        }
        this.runInAsyncScope(callback, null, null, {
          statusCode,
          headers,
          socket,
          opaque,
          context: context2
        });
      }
      onError(err2) {
        const { callback, opaque } = this;
        removeSignal(this);
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err2, { opaque });
          });
        }
      }
    };
    function connect(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve42, reject) => {
          connect.call(this, opts, (err2, data) => {
            return err2 ? reject(err2) : resolve42(data);
          });
        });
      }
      try {
        const connectHandler = new ConnectHandler(opts, callback);
        this.dispatch({ ...opts, method: "CONNECT" }, connectHandler);
      } catch (err2) {
        if (typeof callback !== "function") {
          throw err2;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err2, { 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](instance2) {
        return instance2 && instance2[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: buildURL2 } = 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 i4 = 0; i4 < headers.length; i4 += 2) {
          if (headers[i4].toLocaleLowerCase() === key.toLocaleLowerCase()) {
            return headers[i4 + 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, matchHeaderValue2] of Object.entries(mockDispatch2.headers)) {
        const headerValue = getHeaderByName(headers, matchHeaderName);
        if (!matchValue(matchHeaderValue2, headerValue)) {
          return false;
        }
      }
      return true;
    }
    __name(matchHeaders, "matchHeaders");
    function safeUrl(path150) {
      if (typeof path150 !== "string") {
        return path150;
      }
      const pathSegments = path150.split("?");
      if (pathSegments.length !== 2) {
        return path150;
      }
      const qp = new URLSearchParams(pathSegments.pop());
      qp.sort();
      return [...pathSegments, qp.toString()].join("?");
    }
    __name(safeUrl, "safeUrl");
    function matchKey(mockDispatch2, { path: path150, method, body: body2, headers }) {
      const pathMatch = matchValue(mockDispatch2.path, path150);
      const methodMatch = matchValue(mockDispatch2.method, method);
      const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body2) : 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 ? buildURL2(key.path, key.query) : key.path;
      const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
      let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path150 }) => matchValue(safeUrl(path150), 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: body2 }) => typeof body2 !== "undefined" ? matchValue(body2, 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: path150, method, body: body2, headers, query } = opts;
      return {
        path: path150,
        method,
        body: body2,
        headers,
        query
      };
    }
    __name(buildKey, "buildKey");
    function generateKeyValues(data) {
      const keys = Object.keys(data);
      const result = [];
      for (let i4 = 0; i4 < keys.length; ++i4) {
        const key = keys[i4];
        const value = data[key];
        const name4 = Buffer.from(`${key}`);
        if (Array.isArray(value)) {
          for (let j2 = 0; j2 < value.length; ++j2) {
            result.push(name4, Buffer.from(`${value[j2]}`));
          }
        } else {
          result.push(name4, Buffer.from(`${value}`));
        }
      }
      return result;
    }
    __name(generateKeyValues, "generateKeyValues");
    function getStatusText2(statusCode) {
      return STATUS_CODES[statusCode] || "unknown";
    }
    __name(getStatusText2, "getStatusText");
    async function getResponse(body2) {
      const buffers = [];
      for await (const data of body2) {
        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: error40 }, delay: delay5, persist } = mockDispatch2;
      const { timesInvoked, times } = mockDispatch2;
      mockDispatch2.consumed = !persist && timesInvoked >= times;
      mockDispatch2.pending = timesInvoked < times;
      if (error40 !== null) {
        deleteMockDispatch(this[kDispatches], key);
        handler.onError(error40);
        return true;
      }
      if (typeof delay5 === "number" && delay5 > 0) {
        setTimeout(() => {
          handleReply(this[kDispatches]);
        }, delay5);
      } else {
        handleReply(this[kDispatches]);
      }
      function handleReply(mockDispatches, _data = data) {
        const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
        const body2 = typeof _data === "function" ? _data({ ...opts, headers: optsHeaders }) : _data;
        if (isPromise2(body2)) {
          body2.then((newData) => handleReply(mockDispatches, newData));
          return;
        }
        const responseData = getResponseData(body2);
        const responseHeaders = generateKeyValues(headers);
        const responseTrailers = generateKeyValues(trailers);
        handler.onConnect?.((err2) => handler.onError(err2), 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 origin2 = this[kOrigin];
      const originalDispatch = this[kOriginalDispatch];
      return /* @__PURE__ */ __name(function dispatch(opts, handler) {
        if (agent.isMockActive) {
          try {
            mockDispatch.call(this, opts, handler);
          } catch (error40) {
            if (error40 instanceof MockNotMatchedError) {
              const netConnect = agent[kGetNetConnect]();
              if (netConnect === false) {
                throw new MockNotMatchedError(`${error40.message}: subsequent request to origin ${origin2} was not allowed (net.connect disabled)`);
              }
              if (checkNetConnect(netConnect, origin2)) {
                originalDispatch.call(this, opts, handler);
              } else {
                throw new MockNotMatchedError(`${error40.message}: subsequent request to origin ${origin2} was not allowed (net.connect is not enabled for this origin)`);
              }
            } else {
              throw error40;
            }
          }
        } else {
          originalDispatch.call(this, opts, handler);
        }
      }, "dispatch");
    }
    __name(buildMockDispatch, "buildMockDispatch");
    function checkNetConnect(netConnect, origin2) {
      const url3 = new URL(origin2);
      if (netConnect === true) {
        return true;
      } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url3.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: buildURL2 } = 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 = buildURL2(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(error40) {
        if (typeof error40 === "undefined") {
          throw new InvalidArgumentError("error must be defined");
        }
        const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error: error40 });
        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(origin2, opts) {
        super(origin2, 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] = origin2;
        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(origin2, opts) {
        super(origin2, 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] = origin2;
        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: path150, data: { statusCode }, persist, times, timesInvoked, origin: origin2 }) => ({
            Method: method,
            Origin: origin2,
            Path: path150,
            "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(origin2) {
        let dispatcher = this[kMockAgentGet](origin2);
        if (!dispatcher) {
          dispatcher = this[kFactory](origin2);
          this[kMockAgentSet](origin2, 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](origin2, dispatcher) {
        this[kClients].set(origin2, dispatcher);
      }
      [kFactory](origin2) {
        const mockOptions = Object.assign({ agent: this }, this[kOptions]);
        return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin2, mockOptions) : new MockPool(origin2, mockOptions);
      }
      [kMockAgentGet](origin2) {
        const client = this[kClients].get(origin2);
        if (client) {
          return client;
        }
        if (typeof origin2 !== "string") {
          const dispatcher = this[kFactory]("http://localhost:9999");
          this[kMockAgentSet](origin2, dispatcher);
          return dispatcher;
        }
        for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) {
          if (nonExplicitDispatcher && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin2)) {
            const dispatcher = this[kFactory](origin2);
            this[kMockAgentSet](origin2, dispatcher);
            dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches];
            return dispatcher;
          }
        }
      }
      [kGetNetConnect]() {
        return this[kNetConnect];
      }
      pendingInterceptors() {
        const mockAgentClients = this[kClients];
        return Array.from(mockAgentClients.entries()).flatMap(([origin2, scope]) => scope[kDispatches].map((dispatch) => ({ ...dispatch, origin: origin2 }))).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(...args2) {
        return this.#handler.onConnect?.(...args2);
      }
      onError(...args2) {
        return this.#handler.onError?.(...args2);
      }
      onUpgrade(...args2) {
        return this.#handler.onUpgrade?.(...args2);
      }
      onResponseStarted(...args2) {
        return this.#handler.onResponseStarted?.(...args2);
      }
      onHeaders(...args2) {
        return this.#handler.onHeaders?.(...args2);
      }
      onData(...args2) {
        return this.#handler.onData?.(...args2);
      }
      onComplete(...args2) {
        return this.#handler.onComplete?.(...args2);
      }
      onBodySent(...args2) {
        return this.#handler.onBodySent?.(...args2);
      }
    };
  }
});

// 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 util5 = 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(abort2) {
        this.#abort = abort2;
        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 = util5.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(err2) {
        if (this.#dumped) {
          return;
        }
        err2 = this.#reason ?? err2;
        this.#handler.onError(err2);
      }
      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: isIP4 } = __require("node:net");
    var { lookup: lookup2 } = __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(origin2, opts, cb) {
        const ips = this.#records.get(origin2.hostname);
        if (ips == null && this.full) {
          cb(null, origin2.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(origin2, newOpts, (err2, addresses) => {
            if (err2 || addresses == null || addresses.length === 0) {
              cb(err2 ?? new InformationalError("No DNS entries found"));
              return;
            }
            this.setRecords(origin2, addresses);
            const records = this.#records.get(origin2.hostname);
            const ip = this.pick(
              origin2,
              records,
              newOpts.affinity
            );
            let port;
            if (typeof ip.port === "number") {
              port = `:${ip.port}`;
            } else if (origin2.port !== "") {
              port = `:${origin2.port}`;
            } else {
              port = "";
            }
            cb(
              null,
              `${origin2.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`
            );
          });
        } else {
          const ip = this.pick(
            origin2,
            ips,
            newOpts.affinity
          );
          if (ip == null) {
            this.#records.delete(origin2.hostname);
            this.runLookup(origin2, opts, cb);
            return;
          }
          let port;
          if (typeof ip.port === "number") {
            port = `:${ip.port}`;
          } else if (origin2.port !== "") {
            port = `:${origin2.port}`;
          } else {
            port = "";
          }
          cb(
            null,
            `${origin2.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`
          );
        }
      }
      #defaultLookup(origin2, opts, cb) {
        lookup2(
          origin2.hostname,
          {
            all: true,
            family: this.dualStack === false ? this.affinity : 0,
            order: "ipv4first"
          },
          (err2, addresses) => {
            if (err2) {
              return cb(err2);
            }
            const results = /* @__PURE__ */ new Map();
            for (const addr2 of addresses) {
              results.set(`${addr2.address}:${addr2.family}`, addr2);
            }
            cb(null, results.values());
          }
        );
      }
      #defaultPick(origin2, 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(origin2, hostnameRecords, affinity);
        }
        return ip;
      }
      setRecords(origin2, 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(origin2.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: origin2, handler, dispatch }, opts) {
        super(handler);
        this.#origin = origin2;
        this.#handler = handler;
        this.#opts = { ...opts };
        this.#state = state;
        this.#dispatch = dispatch;
      }
      onError(err2) {
        switch (err2.code) {
          case "ETIMEDOUT":
          case "ECONNREFUSED": {
            if (this.#state.dualStack) {
              this.#state.runLookup(this.#origin, this.#opts, (err3, newOrigin) => {
                if (err3) {
                  return this.#handler.onError(err3);
                }
                const dispatchOpts = {
                  ...this.#opts,
                  origin: newOrigin
                };
                this.#dispatch(dispatchOpts, this);
              });
              return;
            }
            this.#handler.onError(err2);
            return;
          }
          case "ENOTFOUND":
            this.#state.deleteRecord(this.#origin);
          // eslint-disable-next-line no-fallthrough
          default:
            this.#handler.onError(err2);
            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 instance2 = new DNSInstance(opts);
      return (dispatch) => {
        return /* @__PURE__ */ __name(function dnsInterceptor(origDispatchOpts, handler) {
          const origin2 = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
          if (isIP4(origin2.hostname) !== 0) {
            return dispatch(origDispatchOpts, handler);
          }
          instance2.runLookup(origin2, origDispatchOpts, (err2, newOrigin) => {
            if (err2) {
              return handler.onError(err2);
            }
            let dispatchOpts = null;
            dispatchOpts = {
              ...origDispatchOpts,
              servername: origin2.hostname,
              // For SNI on TLS
              origin: newOrigin,
              headers: {
                host: origin2.hostname,
                ...origDispatchOpts.headers
              }
            };
            dispatch(
              dispatchOpts,
              instance2.getHandler({ origin: origin2, 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: isValidHeaderName2,
      isValidHeaderValue
    } = require_util2();
    var { webidl } = require_webidl();
    var assert4 = __require("node:assert");
    var util5 = __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 i4 = 0;
      let j2 = potentialValue.length;
      while (j2 > i4 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j2 - 1))) --j2;
      while (j2 > i4 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i4))) ++i4;
      return i4 === 0 && j2 === potentialValue.length ? potentialValue : potentialValue.substring(i4, j2);
    }
    __name(headerValueNormalize, "headerValueNormalize");
    function fill(headers, object3) {
      if (Array.isArray(object3)) {
        for (let i4 = 0; i4 < object3.length; ++i4) {
          const header = object3[i4];
          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 i4 = 0; i4 < keys.length; ++i4) {
          appendHeader(headers, keys[i4], object3[keys[i4]]);
        }
      } else {
        throw webidl.errors.conversionFailed({
          prefix: "Headers constructor",
          argument: "Argument 1",
          types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
        });
      }
    }
    __name(fill, "fill");
    function appendHeader(headers, name4, value) {
      value = headerValueNormalize(value);
      if (!isValidHeaderName2(name4)) {
        throw webidl.errors.invalidArgument({
          prefix: "Headers.append",
          value: name4,
          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(name4, 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(init2) {
        if (init2 instanceof _HeadersList) {
          this[kHeadersMap] = new Map(init2[kHeadersMap]);
          this[kHeadersSortedMap] = init2[kHeadersSortedMap];
          this.cookies = init2.cookies === null ? null : [...init2.cookies];
        } else {
          this[kHeadersMap] = new Map(init2);
          this[kHeadersSortedMap] = null;
        }
      }
      /**
       * @see https://fetch.spec.whatwg.org/#header-list-contains
       * @param {string} name
       * @param {boolean} isLowerCase
       */
      contains(name4, isLowerCase) {
        return this[kHeadersMap].has(isLowerCase ? name4 : name4.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(name4, value, isLowerCase) {
        this[kHeadersSortedMap] = null;
        const lowercaseName = isLowerCase ? name4 : name4.toLowerCase();
        const exists3 = this[kHeadersMap].get(lowercaseName);
        if (exists3) {
          const delimiter2 = lowercaseName === "cookie" ? "; " : ", ";
          this[kHeadersMap].set(lowercaseName, {
            name: exists3.name,
            value: `${exists3.value}${delimiter2}${value}`
          });
        } else {
          this[kHeadersMap].set(lowercaseName, { name: name4, 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(name4, value, isLowerCase) {
        this[kHeadersSortedMap] = null;
        const lowercaseName = isLowerCase ? name4 : name4.toLowerCase();
        if (lowercaseName === "set-cookie") {
          this.cookies = [value];
        }
        this[kHeadersMap].set(lowercaseName, { name: name4, value });
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-delete
       * @param {string} name
       * @param {boolean} isLowerCase
       */
      delete(name4, isLowerCase) {
        this[kHeadersSortedMap] = null;
        if (!isLowerCase) name4 = name4.toLowerCase();
        if (name4 === "set-cookie") {
          this.cookies = null;
        }
        this[kHeadersMap].delete(name4);
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-get
       * @param {string} name
       * @param {boolean} isLowerCase
       * @returns {string | null}
       */
      get(name4, isLowerCase) {
        return this[kHeadersMap].get(isLowerCase ? name4 : name4.toLowerCase())?.value ?? null;
      }
      *[Symbol.iterator]() {
        for (const { 0: name4, 1: { value } } of this[kHeadersMap]) {
          yield [name4, value];
        }
      }
      get entries() {
        const headers = {};
        if (this[kHeadersMap].size !== 0) {
          for (const { name: name4, value } of this[kHeadersMap].values()) {
            headers[name4] = value;
          }
        }
        return headers;
      }
      rawValues() {
        return this[kHeadersMap].values();
      }
      get entriesList() {
        const headers = [];
        if (this[kHeadersMap].size !== 0) {
          for (const { 0: lowerName, 1: { name: name4, value } } of this[kHeadersMap]) {
            if (lowerName === "set-cookie") {
              for (const cookie of this.cookies) {
                headers.push([name4, cookie]);
              }
            } else {
              headers.push([name4, 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 iterator2 = this[kHeadersMap][Symbol.iterator]();
          const firstValue = iterator2.next().value;
          array2[0] = [firstValue[0], firstValue[1].value];
          assert4(firstValue[1].value !== null);
          for (let i4 = 1, j2 = 0, right3 = 0, left3 = 0, pivot = 0, x3, value; i4 < size; ++i4) {
            value = iterator2.next().value;
            x3 = array2[i4] = [value[0], value[1].value];
            assert4(x3[1] !== null);
            left3 = 0;
            right3 = i4;
            while (left3 < right3) {
              pivot = left3 + (right3 - left3 >> 1);
              if (array2[pivot][0] <= x3[0]) {
                left3 = pivot + 1;
              } else {
                right3 = pivot;
              }
            }
            if (i4 !== pivot) {
              j2 = i4;
              while (j2 > left3) {
                array2[j2] = array2[--j2];
              }
              array2[left3] = x3;
            }
          }
          if (!iterator2.next().done) {
            throw new TypeError("Unreachable");
          }
          return array2;
        } else {
          let i4 = 0;
          for (const { 0: name4, 1: { value } } of this[kHeadersMap]) {
            array2[i4++] = [name4, value];
            assert4(value !== null);
          }
          return array2.sort(compareHeaderName);
        }
      }
    };
    var Headers6 = class _Headers {
      static {
        __name(this, "Headers");
      }
      #guard;
      #headersList;
      constructor(init2 = void 0) {
        webidl.util.markAsUncloneable(this);
        if (init2 === kConstruct) {
          return;
        }
        this.#headersList = new HeadersList();
        this.#guard = "none";
        if (init2 !== void 0) {
          init2 = webidl.converters.HeadersInit(init2, "Headers contructor", "init");
          fill(this, init2);
        }
      }
      // https://fetch.spec.whatwg.org/#dom-headers-append
      append(name4, value) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 2, "Headers.append");
        const prefix = "Headers.append";
        name4 = webidl.converters.ByteString(name4, prefix, "name");
        value = webidl.converters.ByteString(value, prefix, "value");
        return appendHeader(this, name4, value);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-delete
      delete(name4) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.delete");
        const prefix = "Headers.delete";
        name4 = webidl.converters.ByteString(name4, prefix, "name");
        if (!isValidHeaderName2(name4)) {
          throw webidl.errors.invalidArgument({
            prefix: "Headers.delete",
            value: name4,
            type: "header name"
          });
        }
        if (this.#guard === "immutable") {
          throw new TypeError("immutable");
        }
        if (!this.#headersList.contains(name4, false)) {
          return;
        }
        this.#headersList.delete(name4, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-get
      get(name4) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.get");
        const prefix = "Headers.get";
        name4 = webidl.converters.ByteString(name4, prefix, "name");
        if (!isValidHeaderName2(name4)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name4,
            type: "header name"
          });
        }
        return this.#headersList.get(name4, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-has
      has(name4) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.has");
        const prefix = "Headers.has";
        name4 = webidl.converters.ByteString(name4, prefix, "name");
        if (!isValidHeaderName2(name4)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name4,
            type: "header name"
          });
        }
        return this.#headersList.contains(name4, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-set
      set(name4, value) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 2, "Headers.set");
        const prefix = "Headers.set";
        name4 = webidl.converters.ByteString(name4, prefix, "name");
        value = webidl.converters.ByteString(value, prefix, "value");
        value = headerValueNormalize(value);
        if (!isValidHeaderName2(name4)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name4,
            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(name4, 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 i4 = 0; i4 < names.length; ++i4) {
          const { 0: name4, 1: value } = names[i4];
          if (name4 === "set-cookie") {
            for (let j2 = 0; j2 < cookies.length; ++j2) {
              headers.push([name4, cookies[j2]]);
            }
          } else {
            headers.push([name4, value]);
          }
        }
        return this.#headersList[kHeadersSortedMap] = headers;
      }
      [util5.inspect.custom](depth, options2) {
        options2.depth ??= depth;
        return `Headers ${util5.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
      },
      [util5.inspect.custom]: {
        enumerable: false
      }
    });
    webidl.converters.HeadersInit = function(V3, prefix, argument) {
      if (webidl.util.Type(V3) === "Object") {
        const iterator2 = Reflect.get(V3, Symbol.iterator);
        if (!util5.types.isProxy(V3) && iterator2 === Headers6.prototype.entries) {
          try {
            return getHeadersList(V3).entriesList;
          } catch {
          }
        }
        if (typeof iterator2 === "function") {
          return webidl.converters["sequence<sequence<ByteString>>"](V3, prefix, argument, iterator2.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 util5 = require_util();
    var nodeUtil = __require("node:util");
    var { kEnumerableProperty } = util5;
    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: FormData7 } = require_formdata();
    var { URLSerializer } = require_data_url();
    var { kConstruct } = require_symbols();
    var assert4 = __require("node:assert");
    var { types: types7 } = __require("node:util");
    var textEncoder2 = 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, init2 = {}) {
        webidl.argumentLengthCheck(arguments, 1, "Response.json");
        if (init2 !== null) {
          init2 = webidl.converters.ResponseInit(init2);
        }
        const bytes = textEncoder2.encode(
          serializeJavascriptValueToJSONString(data)
        );
        const body2 = extractBody(bytes);
        const responseObject = fromInnerResponse(makeResponse({}), "response");
        initializeResponse(responseObject, init2, { body: body2[0], type: "application/json" });
        return responseObject;
      }
      // Creates a redirect Response that redirects to url with status status.
      static redirect(url3, status = 302) {
        webidl.argumentLengthCheck(arguments, 1, "Response.redirect");
        url3 = webidl.converters.USVString(url3);
        status = webidl.converters["unsigned short"](status);
        let parsedURL;
        try {
          parsedURL = new URL(url3, relevantRealm.settingsObject.baseUrl);
        } catch (err2) {
          throw new TypeError(`Failed to parse URL from ${url3}`, { cause: err2 });
        }
        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(body2 = null, init2 = {}) {
        webidl.util.markAsUncloneable(this);
        if (body2 === kConstruct) {
          return;
        }
        if (body2 !== null) {
          body2 = webidl.converters.BodyInit(body2);
        }
        init2 = webidl.converters.ResponseInit(init2);
        this[kState] = makeResponse({});
        this[kHeaders] = new Headers6(kConstruct);
        setHeadersGuard(this[kHeaders], "response");
        setHeadersList(this[kHeaders], this[kState].headersList);
        let bodyWithType = null;
        if (body2 != null) {
          const [extractedBody, type] = extractBody(body2);
          bodyWithType = { body: extractedBody, type };
        }
        initializeResponse(this, init2, 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 url3 = urlList[urlList.length - 1] ?? null;
        if (url3 === null) {
          return "";
        }
        return URLSerializer(url3, 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 && util5.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(init2) {
      return {
        aborted: false,
        rangeRequested: false,
        timingAllowPassed: false,
        requestIncludesCredentials: false,
        type: "default",
        status: 200,
        timingInfo: null,
        cacheState: "",
        statusText: "",
        ...init2,
        headersList: init2?.headersList ? new HeadersList(init2?.headersList) : new HeadersList(),
        urlList: init2?.urlList ? [...init2.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, err2 = null) {
      assert4(isCancelled(fetchParams));
      return isAborted2(fetchParams) ? makeNetworkError(Object.assign(new DOMException("The operation was aborted.", "AbortError"), { cause: err2 })) : makeNetworkError(Object.assign(new DOMException("Request was cancelled."), { cause: err2 }));
    }
    __name(makeAppropriateNetworkError, "makeAppropriateNetworkError");
    function initializeResponse(response, init2, body2) {
      if (init2.status !== null && (init2.status < 200 || init2.status > 599)) {
        throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');
      }
      if ("statusText" in init2 && init2.statusText != null) {
        if (!isValidReasonPhrase(String(init2.statusText))) {
          throw new TypeError("Invalid statusText");
        }
      }
      if ("status" in init2 && init2.status != null) {
        response[kState].status = init2.status;
      }
      if ("statusText" in init2 && init2.statusText != null) {
        response[kState].statusText = init2.statusText;
      }
      if ("headers" in init2 && init2.headers != null) {
        fill(response[kHeaders], init2.headers);
      }
      if (body2) {
        if (nullBodyStatus.includes(response.status)) {
          throw webidl.errors.exception({
            header: "Response constructor",
            message: `Invalid response status code ${response.status}`
          });
        }
        response[kState].body = body2.body;
        if (body2.type != null && !response[kState].headersList.contains("content-type", true)) {
          response[kState].headersList.append("content-type", body2.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(
      FormData7
    );
    webidl.converters.URLSearchParams = webidl.interfaceConverter(
      URLSearchParams
    );
    webidl.converters.XMLHttpRequestBodyInit = function(V3, prefix, name4) {
      if (typeof V3 === "string") {
        return webidl.converters.USVString(V3, prefix, name4);
      }
      if (isBlobLike3(V3)) {
        return webidl.converters.Blob(V3, prefix, name4, { strict: false });
      }
      if (ArrayBuffer.isView(V3) || types7.isArrayBuffer(V3)) {
        return webidl.converters.BufferSource(V3, prefix, name4);
      }
      if (util5.isFormDataLike(V3)) {
        return webidl.converters.FormData(V3, prefix, name4, { strict: false });
      }
      if (V3 instanceof URLSearchParams) {
        return webidl.converters.URLSearchParams(V3, prefix, name4);
      }
      return webidl.converters.DOMString(V3, prefix, name4);
    };
    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 util5 = 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 } = util5;
    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: setMaxListeners2, getEventListeners, defaultMaxListeners } = __require("node:events");
    var kAbortController = Symbol("abortController");
    var requestFinalizer = new FinalizationRegistry2(({ signal, abort: abort2 }) => {
      signal.removeEventListener("abort", abort2);
    });
    var dependentControllerMap = /* @__PURE__ */ new WeakMap();
    function buildAbort(acRef) {
      return abort2;
      function abort2() {
        const ac = acRef.deref();
        if (ac !== void 0) {
          requestFinalizer.unregister(abort2);
          this.removeEventListener("abort", abort2);
          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(abort2, "abort");
    }
    __name(buildAbort, "buildAbort");
    var patchMethodWarning = false;
    var Request6 = class _Request {
      static {
        __name(this, "Request");
      }
      // https://fetch.spec.whatwg.org/#dom-request
      constructor(input, init2 = {}) {
        webidl.util.markAsUncloneable(this);
        if (input === kConstruct) {
          return;
        }
        const prefix = "Request constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        input = webidl.converters.RequestInfo(input, prefix, "input");
        init2 = webidl.converters.RequestInit(init2, prefix, "init");
        let request4 = null;
        let fallbackMode = null;
        const baseUrl = environmentSettingsObject.settingsObject.baseUrl;
        let signal = null;
        if (typeof input === "string") {
          this[kDispatcher] = init2.dispatcher;
          let parsedURL;
          try {
            parsedURL = new URL(input, baseUrl);
          } catch (err2) {
            throw new TypeError("Failed to parse URL from " + input, { cause: err2 });
          }
          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] = init2.dispatcher || input[kDispatcher];
          assert4(input instanceof _Request);
          request4 = input[kState];
          signal = input[kSignal];
        }
        const origin2 = environmentSettingsObject.settingsObject.origin;
        let window2 = "client";
        if (request4.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin(request4.window, origin2)) {
          window2 = request4.window;
        }
        if (init2.window != null) {
          throw new TypeError(`'window' option '${window2}' must be null`);
        }
        if ("window" in init2) {
          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(init2).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 (init2.referrer !== void 0) {
          const referrer = init2.referrer;
          if (referrer === "") {
            request4.referrer = "no-referrer";
          } else {
            let parsedReferrer;
            try {
              parsedReferrer = new URL(referrer, baseUrl);
            } catch (err2) {
              throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err2 });
            }
            if (parsedReferrer.protocol === "about:" && parsedReferrer.hostname === "client" || origin2 && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) {
              request4.referrer = "client";
            } else {
              request4.referrer = parsedReferrer;
            }
          }
        }
        if (init2.referrerPolicy !== void 0) {
          request4.referrerPolicy = init2.referrerPolicy;
        }
        let mode;
        if (init2.mode !== void 0) {
          mode = init2.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 (init2.credentials !== void 0) {
          request4.credentials = init2.credentials;
        }
        if (init2.cache !== void 0) {
          request4.cache = init2.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 (init2.redirect !== void 0) {
          request4.redirect = init2.redirect;
        }
        if (init2.integrity != null) {
          request4.integrity = String(init2.integrity);
        }
        if (init2.keepalive !== void 0) {
          request4.keepalive = Boolean(init2.keepalive);
        }
        if (init2.method !== void 0) {
          let method = init2.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 (init2.signal !== void 0) {
          signal = init2.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 abort2 = buildAbort(acRef);
            try {
              if (typeof getMaxListeners === "function" && getMaxListeners(signal) === defaultMaxListeners) {
                setMaxListeners2(1500, signal);
              } else if (getEventListeners(signal, "abort").length >= defaultMaxListeners) {
                setMaxListeners2(1500, signal);
              }
            } catch {
            }
            util5.addAbortListener(signal, abort2);
            requestFinalizer.register(ac, { signal, abort: abort2 }, abort2);
          }
        }
        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 = init2.headers !== void 0 ? init2.headers : new HeadersList(headersList);
          headersList.clear();
          if (headers instanceof HeadersList) {
            for (const { name: name4, value } of headers.rawValues()) {
              headersList.append(name4, value, false);
            }
            headersList.cookies = headers.cookies;
          } else {
            fillHeaders(this[kHeaders], headers);
          }
        }
        const inputBody = input instanceof _Request ? input[kState].body : null;
        if ((init2.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 (init2.body != null) {
          const [extractedBody, contentType] = extractBody(
            init2.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 && init2.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 && util5.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);
          util5.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(init2) {
      return {
        method: init2.method ?? "GET",
        localURLsOnly: init2.localURLsOnly ?? false,
        unsafeRequest: init2.unsafeRequest ?? false,
        body: init2.body ?? null,
        client: init2.client ?? null,
        reservedClient: init2.reservedClient ?? null,
        replacesClientId: init2.replacesClientId ?? "",
        window: init2.window ?? "client",
        keepalive: init2.keepalive ?? false,
        serviceWorkers: init2.serviceWorkers ?? "all",
        initiator: init2.initiator ?? "",
        destination: init2.destination ?? "",
        priority: init2.priority ?? null,
        origin: init2.origin ?? "client",
        policyContainer: init2.policyContainer ?? "client",
        referrer: init2.referrer ?? "client",
        referrerPolicy: init2.referrerPolicy ?? "",
        mode: init2.mode ?? "no-cors",
        useCORSPreflightFlag: init2.useCORSPreflightFlag ?? false,
        credentials: init2.credentials ?? "same-origin",
        useCredentials: init2.useCredentials ?? false,
        cache: init2.cache ?? "default",
        redirect: init2.redirect ?? "follow",
        integrity: init2.integrity ?? "",
        cryptoGraphicsNonceMetadata: init2.cryptoGraphicsNonceMetadata ?? "",
        parserMetadata: init2.parserMetadata ?? "",
        reloadNavigation: init2.reloadNavigation ?? false,
        historyNavigation: init2.historyNavigation ?? false,
        userActivation: init2.userActivation ?? false,
        taintedOrigin: init2.taintedOrigin ?? false,
        redirectCount: init2.redirectCount ?? 0,
        responseTainting: init2.responseTainting ?? "basic",
        preventNoCacheCacheControlHeaderModification: init2.preventNoCacheCacheControlHeaderModification ?? false,
        done: init2.done ?? false,
        timingAllowFailed: init2.timingAllowFailed ?? false,
        urlList: init2.urlList,
        url: init2.urlList[0],
        headersList: init2.headersList ? new HeadersList(init2.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 zlib5 = __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: Readable8, 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(error40) {
        if (this.state !== "ongoing") {
          return;
        }
        this.state = "aborted";
        if (!error40) {
          error40 = new DOMException("The operation was aborted.", "AbortError");
        }
        this.serializedAbortReason = error40;
        this.connection?.destroy(error40);
        this.emit("terminated", error40);
      }
    };
    function handleFetchDone(response) {
      finalizeAndReportTiming(response, "fetch");
    }
    __name(handleFetchDone, "handleFetchDone");
    function fetch5(input, init2 = void 0) {
      webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch");
      let p2 = createDeferredPromise();
      let requestObject;
      try {
        requestObject = new Request6(input, init2);
      } 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, error40) {
      if (p2) {
        p2.reject(error40);
      }
      if (request4.body != null && isReadable2(request4.body?.stream)) {
        request4.body.stream.cancel(error40).catch((err2) => {
          if (err2.code === "ERR_INVALID_STATE") {
            return;
          }
          throw err2;
        });
      }
      if (responseObject == null) {
        return;
      }
      const response = responseObject[kState];
      if (response.body != null && isReadable2(response.body?.stream)) {
        response.body.stream.cancel(error40).catch((err2) => {
          if (err2.code === "ERR_INVALID_STATE") {
            return;
          }
          throw err2;
        });
      }
    }
    __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((err2) => {
        fetchParams.controller.terminate(err2);
      });
      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((err2) => makeNetworkError(err2));
        }
        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 (err2) {
        return Promise.resolve(makeNetworkError(err2));
      }
      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(err2, abort2 = true) {
          if (!this.destroyed) {
            this.destroyed = true;
            if (abort2) {
              this.abort?.(err2 ?? 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 (err2) {
            processBodyError(err2);
          }
        }();
      }
      try {
        const { body: body2, status, statusText, headersList, socket } = await dispatch({ body: requestBody });
        if (socket) {
          response = makeResponse({ status, statusText, headersList, socket });
        } else {
          const iterator2 = body2[Symbol.asyncIterator]();
          fetchParams.controller.next = () => iterator2.next();
          response = makeResponse({ status, statusText, headersList });
        }
      } catch (err2) {
        if (err2.name === "AbortError") {
          fetchParams.controller.connection.destroy();
          return makeAppropriateNetworkError(fetchParams, err2);
        }
        return makeNetworkError(err2);
      }
      const pullAlgorithm = /* @__PURE__ */ __name(async () => {
        await fetchParams.controller.resume();
      }, "pullAlgorithm");
      const cancelAlgorithm = /* @__PURE__ */ __name((reason) => {
        if (!isCancelled(fetchParams)) {
          fetchParams.controller.abort(reason);
        }
      }, "cancelAlgorithm");
      const stream5 = 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: stream5, 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 (err2) {
            if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
              bytes = void 0;
            } else {
              bytes = err2;
              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(stream5)) {
            fetchParams.controller.terminate();
            return;
          }
          if (fetchParams.controller.controller.desiredSize <= 0) {
            return;
          }
        }
      };
      function onAborted(reason) {
        if (isAborted2(fetchParams)) {
          response.aborted = true;
          if (isReadable2(stream5)) {
            fetchParams.controller.controller.error(
              fetchParams.controller.serializedAbortReason
            );
          }
        } else {
          if (isReadable2(stream5)) {
            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: body2 }) {
        const url3 = requestCurrentURL(request4);
        const agent = fetchParams.controller.dispatcher;
        return new Promise((resolve42, reject) => agent.dispatch(
          {
            path: url3.pathname + url3.search,
            origin: url3.origin,
            method: request4.method,
            body: agent.isMockActive ? request4.body && (request4.body.source || request4.body.stream) : body2,
            headers: request4.headersList.entries,
            maxRedirections: 0,
            upgrade: request4.mode === "websocket" ? "websocket" : void 0
          },
          {
            body: null,
            abort: null,
            onConnect(abort2) {
              const { connection } = fetchParams.controller;
              timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability);
              if (connection.destroyed) {
                abort2(new DOMException("The operation was aborted.", "AbortError"));
              } else {
                fetchParams.controller.on("terminated", abort2);
                this.abort = connection.abort = abort2;
              }
              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 i4 = 0; i4 < rawHeaders.length; i4 += 2) {
                headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i4]), rawHeaders[i4 + 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 Readable8({ 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 i4 = codings.length - 1; i4 >= 0; --i4) {
                  const coding = codings[i4];
                  if (coding === "x-gzip" || coding === "gzip") {
                    decoders.push(zlib5.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: zlib5.constants.Z_SYNC_FLUSH,
                      finishFlush: zlib5.constants.Z_SYNC_FLUSH
                    }));
                  } else if (coding === "deflate") {
                    decoders.push(createInflate({
                      flush: zlib5.constants.Z_SYNC_FLUSH,
                      finishFlush: zlib5.constants.Z_SYNC_FLUSH
                    }));
                  } else if (coding === "br") {
                    decoders.push(zlib5.createBrotliDecompress({
                      flush: zlib5.constants.BROTLI_OPERATION_FLUSH,
                      finishFlush: zlib5.constants.BROTLI_OPERATION_FLUSH
                    }));
                  } else {
                    decoders.length = 0;
                    break;
                  }
                }
              }
              const onError2 = this.onError.bind(this);
              resolve42({
                status,
                statusText,
                headersList,
                body: decoders.length ? pipeline3(this.body, ...decoders, (err2) => {
                  if (err2) {
                    this.onError(err2);
                  }
                }).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(error40) {
              if (this.abort) {
                fetchParams.controller.off("terminated", this.abort);
              }
              this.body?.destroy(error40);
              fetchParams.controller.terminate(error40);
              reject(error40);
            },
            onUpgrade(status, rawHeaders, socket) {
              if (status !== 101) {
                return;
              }
              const headersList = new HeadersList();
              for (let i4 = 0; i4 < rawHeaders.length; i4 += 2) {
                headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i4]), rawHeaders[i4 + 1].toString("latin1"), true);
              }
              resolve42({
                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 stream5 = blob.stream();
      const reader = stream5.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 (error40) {
                  fr2[kError] = error40;
                  fireAProgressEvent("error", fr2);
                }
                if (fr2[kState] !== "loading") {
                  fireAProgressEvent("loadend", fr2);
                }
              });
              break;
            }
          } catch (error40) {
            if (fr2[kAborted]) {
              return;
            }
            queueMicrotask(() => {
              fr2[kState] = "done";
              fr2[kError] = error40;
              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: isValidHeaderName2 } = 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 (isValidHeaderName2(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 stream5 = innerResponse.body.stream;
          const reader = stream5.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 promise2 = 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);
          }
          promise2.resolve(Object.freeze(requestList));
        });
        return promise2.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 i4 = 0; i4 < value.length; ++i4) {
        const code2 = value.charCodeAt(i4);
        if (code2 >= 0 && code2 <= 8 || code2 >= 10 && code2 <= 31 || code2 === 127) {
          return true;
        }
      }
      return false;
    }
    __name(isCTLExcludingHtab, "isCTLExcludingHtab");
    function validateCookieName(name4) {
      for (let i4 = 0; i4 < name4.length; ++i4) {
        const code2 = name4.charCodeAt(i4);
        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 i4 = 0;
      if (value[0] === '"') {
        if (len === 1 || value[len - 1] !== '"') {
          throw new Error("Invalid cookie value");
        }
        --len;
        ++i4;
      }
      while (i4 < len) {
        const code2 = value.charCodeAt(i4++);
        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(path150) {
      for (let i4 = 0; i4 < path150.length; ++i4) {
        const code2 = path150.charCodeAt(i4);
        if (code2 < 32 || // exclude CTLs (0-31)
        code2 === 127 || // DEL
        code2 === 59) {
          throw new Error("Invalid cookie path");
        }
      }
    }
    __name(validateCookiePath, "validateCookiePath");
    function validateCookieDomain(domain2) {
      if (domain2.startsWith("-") || domain2.endsWith(".") || domain2.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, i4) => i4.toString().padStart(2, "0"));
    function toIMFDate(date5) {
      if (typeof date5 === "number") {
        date5 = new Date(date5);
      }
      return `${IMFDays[date5.getUTCDay()]}, ${IMFPaddedNumbers[date5.getUTCDate()]} ${IMFMonths[date5.getUTCMonth()]} ${date5.getUTCFullYear()} ${IMFPaddedNumbers[date5.getUTCHours()]}:${IMFPaddedNumbers[date5.getUTCMinutes()]}:${IMFPaddedNumbers[date5.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 out2 = [`${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) {
        out2.push("Secure");
      }
      if (cookie.httpOnly) {
        out2.push("HttpOnly");
      }
      if (typeof cookie.maxAge === "number") {
        validateCookieMaxAge(cookie.maxAge);
        out2.push(`Max-Age=${cookie.maxAge}`);
      }
      if (cookie.domain) {
        validateCookieDomain(cookie.domain);
        out2.push(`Domain=${cookie.domain}`);
      }
      if (cookie.path) {
        validateCookiePath(cookie.path);
        out2.push(`Path=${cookie.path}`);
      }
      if (cookie.expires && cookie.expires.toString() !== "Invalid Date") {
        out2.push(`Expires=${toIMFDate(cookie.expires)}`);
      }
      if (cookie.sameSite) {
        out2.push(`SameSite=${cookie.sameSite}`);
      }
      for (const part of cookie.unparsed) {
        if (!part.includes("=")) {
          throw new Error("Invalid unparsed");
        }
        const [key, ...value] = part.split("=");
        out2.push(`${key.trim()}=${value.join("=")}`);
      }
      return out2.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 name4 = "";
      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 };
        name4 = collectASequenceOfCodePointsFast(
          "=",
          nameValuePair,
          position
        );
        value = nameValuePair.slice(position.position + 1);
      }
      name4 = name4.trim();
      value = value.trim();
      if (name4.length + value.length > maxNameValuePairSize) {
        return null;
      }
      return {
        name: name4,
        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 out2 = {};
      if (!cookie) {
        return out2;
      }
      for (const piece of cookie.split(";")) {
        const [name4, ...value] = piece.split("=");
        out2[name4.trim()] = value.join("=");
      }
      return out2;
    }
    __name(getCookies, "getCookies");
    function deleteCookie(headers, name4, attributes) {
      webidl.brandCheck(headers, Headers6, { strict: false });
      const prefix = "deleteCookie";
      webidl.argumentLengthCheck(arguments, 2, prefix);
      name4 = webidl.converters.DOMString(name4, prefix, "name");
      attributes = webidl.converters.DeleteCookieAttributes(attributes);
      setCookie(headers, {
        name: name4,
        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, origin2 = "", lastEventId = "", source2 = null, ports2 = []) {
        webidl.brandCheck(this, _MessageEvent);
        webidl.argumentLengthCheck(arguments, 1, "MessageEvent.initMessageEvent");
        return new _MessageEvent(type, {
          bubbles,
          cancelable,
          data,
          origin: origin2,
          lastEventId,
          source: source2,
          ports: ports2
        });
      }
      static createFastMessageEvent(type, init2) {
        const messageEvent = new _MessageEvent(kConstruct, type, init2);
        messageEvent.#eventInit = init2;
        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: isUtf82 } = __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, init2) => new Event(type, init2), 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 i4 = 0; i4 < protocol.length; ++i4) {
        const code2 = protocol.charCodeAt(i4);
        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, init2) => new ErrorEvent2(type, init2), {
          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 [name4, value = ""] = pair.split("=");
        extensionList.set(
          removeHTTPWhitespace(name4, true, false),
          removeHTTPWhitespace(value, false, true)
        );
        position.position++;
      }
      return extensionList;
    }
    __name(parseExtensions, "parseExtensions");
    function isValidClientWindowBits(value) {
      for (let i4 = 0; i4 < value.length; i4++) {
        const byte = value.charCodeAt(i4);
        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 (isUtf82(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 crypto18;
    var buffer = null;
    var bufIdx = BUFFER_SIZE;
    try {
      crypto18 = __require("node:crypto");
    } catch {
      crypto18 = {
        // not full compatibility, but minimum.
        randomFillSync: /* @__PURE__ */ __name(function randomFillSync(buffer2, _offset, _size3) {
          for (let i4 = 0; i4 < buffer2.length; ++i4) {
            buffer2[i4] = Math.random() * 255 | 0;
          }
          return buffer2;
        }, "randomFillSync")
      };
    }
    function generateMask() {
      if (bufIdx === BUFFER_SIZE) {
        bufIdx = 0;
        crypto18.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 i4 = 0; i4 < bodyLength; ++i4) {
          buffer2[offset + i4] = frameData[i4] ^ maskKey[i4 & 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 crypto18;
    try {
      crypto18 = __require("node:crypto");
    } catch {
    }
    function establishWebSocketConnection(url3, protocols, client, ws2, onEstablish, options2) {
      const requestURL = url3;
      requestURL.protocol = url3.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 = crypto18.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 = crypto18.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, init2) => new CloseEvent(type, init2), {
        wasClean,
        code: code2,
        reason
      });
      if (channels.close.hasSubscribers) {
        channels.close.publish({
          websocket: ws2,
          code: code2,
          reason
        });
      }
    }
    __name(onSocketClose, "onSocketClose");
    function onSocketError(error40) {
      const { ws: ws2 } = this;
      ws2[kReadyState] = states.CLOSING;
      if (channels.socketError.hasSubscribers) {
        channels.socketError.publish(error40);
      }
      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", (err2) => {
            this.#inflate = null;
            callback(err2);
          });
        }
        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: Writable4 } = __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 Writable4 {
      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 body2 = this.consume(this.#info.payloadLength);
            if (isControlFrame(this.#info.opcode)) {
              this.#loop = this.parseControlFrame(body2);
              this.#state = parserStates.INFO;
            } else {
              if (!this.#info.compressed) {
                this.#fragments.push(body2);
                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(body2, this.#info.fin, (error40, data) => {
                  if (error40) {
                    closeWebSocketConnection(this.ws, 1007, error40.message, error40.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(body2) {
        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(body2);
          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 body3 = emptyBuffer;
            if (this.#info.closeInfo.code) {
              body3 = Buffer.allocUnsafe(2);
              body3.writeUInt16BE(this.#info.closeInfo.code, 0);
            }
            const closeFrame = new WebsocketFrameSend(body3);
            this.ws[kResponse].socket.write(
              closeFrame.createFrame(opcodes.CLOSE),
              (err2) => {
                if (!err2) {
                  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(body2);
            this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG));
            if (channels.ping.hasSubscribers) {
              channels.ping.publish({
                payload: body2
              });
            }
          }
        } else if (opcode === opcodes.PONG) {
          if (channels.pong.hasSubscribers) {
            channels.pong.publish({
              payload: body2
            });
          }
        }
        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(url3, 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");
        url3 = webidl.converters.USVString(url3, prefix, "url");
        protocols = options2.protocols;
        const baseURL = environmentSettingsObject.settingsObject.baseUrl;
        let urlRecord;
        try {
          urlRecord = new URL(url3, 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(err2) {
      let message;
      let code2;
      if (err2 instanceof CloseEvent) {
        message = err2.reason;
        code2 = err2.code;
      } else {
        message = err2.message;
      }
      fireEvent("error", this, () => new ErrorEvent2("error", { error: err2, 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 i4 = 0; i4 < value.length; i4++) {
        if (value.charCodeAt(i4) < 48 || value.charCodeAt(i4) > 57) return false;
      }
      return true;
    }
    __name(isASCIINumber, "isASCIINumber");
    function delay5(ms) {
      return new Promise((resolve42) => {
        setTimeout(resolve42, ms).unref();
      });
    }
    __name(delay5, "delay");
    module2.exports = {
      isValidLastEventId,
      isASCIINumber,
      delay: delay5
    };
  }
});

// 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: delay5 } = 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(url3, 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"
          });
        }
        url3 = webidl.converters.USVString(url3, 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(url3, 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,
            (error40) => {
              if (error40?.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 delay5(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 util5 = 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: util5.parseHeaders,
      headerNameToString: util5.headerNameToString
    };
    function makeDispatcher(fn) {
      return (url3, opts, handler) => {
        if (typeof opts === "function") {
          handler = opts;
          opts = null;
        }
        if (!url3 || typeof url3 !== "string" && typeof url3 !== "object" && !(url3 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 path150 = opts.path;
          if (!opts.path.startsWith("/")) {
            path150 = `/${path150}`;
          }
          url3 = new URL(util5.parseOrigin(url3).origin + path150);
        } else {
          if (!opts) {
            opts = typeof url3 === "object" ? url3 : {};
          }
          url3 = util5.parseURL(url3);
        }
        const { agent, dispatcher = getGlobalDispatcher() } = opts;
        if (agent) {
          throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?");
        }
        return fn.call(dispatcher, {
          ...opts,
          origin: url3.origin,
          path: url3.search ? `${url3.pathname}${url3.search}` : url3.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(init2, options2 = void 0) {
      try {
        return await fetchImpl(init2, options2);
      } catch (err2) {
        if (err2 && typeof err2 === "object") {
          Error.captureStackTrace(err2);
        }
        throw err2;
      }
    }, "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(error40) {
  return error40 instanceof Error && "code" in error40;
}
function isAbortError(error40) {
  if (!error40 || typeof error40 !== "object") {
    return false;
  }
  if (error40 instanceof Error && error40.name === "AbortError") {
    return true;
  }
  if (isNodeError(error40) && error40.code === "ABORT_ERR") {
    return true;
  }
  return false;
}
function getErrorMessage(error40) {
  if (error40 instanceof Error) {
    const cause = error40.cause;
    if (cause instanceof Error && cause.message !== error40.message) {
      return `${error40.message} (cause: ${cause.message})`;
    }
    return error40.message;
  }
  try {
    return String(error40);
  } catch {
    return "Failed to get error details";
  }
}
function getErrorStatus(error40) {
  if (typeof error40 !== "object" || error40 === null) {
    return void 0;
  }
  const err2 = error40;
  const value = err2.status ?? err2.statusCode ?? err2.response?.status ?? err2.error?.code;
  if (typeof value === "number" && value >= 100 && value <= 599) {
    return value;
  }
  if (typeof err2.message === "string") {
    const match2 = err2.message.match(/HTTP_STATUS\/(\d{3})\b/);
    if (match2) {
      const parsed = Number(match2[1]);
      if (parsed >= 100 && parsed <= 599) {
        return parsed;
      }
    }
  }
  return void 0;
}
function getErrorType(error40) {
  if (typeof error40 !== "object" || error40 === null) {
    return "unknown";
  }
  const constructorName = error40 instanceof Error && error40.constructor.name !== "Error" ? error40.constructor.name : void 0;
  const sdkType = error40.type;
  const baseType = constructorName ?? sdkType ?? (error40 instanceof Error ? error40.name : "unknown");
  const cause = error40 instanceof Error ? error40.cause : void 0;
  const causeCode = cause && typeof cause === "object" && "code" in cause ? cause.code : void 0;
  return causeCode ? `${baseType}:${causeCode}` : baseType;
}
function toFriendlyError(error40) {
  if (error40 && typeof error40 === "object" && "response" in error40) {
    const gaxiosError = error40;
    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 error40;
}
function parseResponseData(error40) {
  if (typeof error40.response?.data === "string") {
    return JSON.parse(error40.response?.data);
  }
  return error40.response?.data;
}
var FatalError, FatalAuthenticationError, FatalInputError, FatalSandboxError, FatalConfigError, FatalTurnLimitedError, FatalToolExecutionError, FatalCancellationError, ForbiddenError, UnauthorizedError, BadRequestError;
var init_errors = __esm({
  "packages/core/dist/src/utils/errors.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isNodeError, "isNodeError");
    __name(isAbortError, "isAbortError");
    __name(getErrorMessage, "getErrorMessage");
    __name(getErrorStatus, "getErrorStatus");
    __name(getErrorType, "getErrorType");
    FatalError = class extends Error {
      static {
        __name(this, "FatalError");
      }
      exitCode;
      constructor(message, exitCode) {
        super(message);
        this.exitCode = exitCode;
      }
    };
    FatalAuthenticationError = class extends FatalError {
      static {
        __name(this, "FatalAuthenticationError");
      }
      constructor(message) {
        super(message, 41);
      }
    };
    FatalInputError = class extends FatalError {
      static {
        __name(this, "FatalInputError");
      }
      constructor(message) {
        super(message, 42);
      }
    };
    FatalSandboxError = class extends FatalError {
      static {
        __name(this, "FatalSandboxError");
      }
      constructor(message) {
        super(message, 44);
      }
    };
    FatalConfigError = class extends FatalError {
      static {
        __name(this, "FatalConfigError");
      }
      constructor(message) {
        super(message, 52);
      }
    };
    FatalTurnLimitedError = class extends FatalError {
      static {
        __name(this, "FatalTurnLimitedError");
      }
      constructor(message) {
        super(message, 53);
      }
    };
    FatalToolExecutionError = class extends FatalError {
      static {
        __name(this, "FatalToolExecutionError");
      }
      constructor(message) {
        super(message, 54);
      }
    };
    FatalCancellationError = class extends FatalError {
      static {
        __name(this, "FatalCancellationError");
      }
      constructor(message) {
        super(message, 130);
      }
    };
    ForbiddenError = class extends Error {
      static {
        __name(this, "ForbiddenError");
      }
    };
    UnauthorizedError = class extends Error {
      static {
        __name(this, "UnauthorizedError");
      }
    };
    BadRequestError = class extends Error {
      static {
        __name(this, "BadRequestError");
      }
    };
    __name(toFriendlyError, "toFriendlyError");
    __name(parseResponseData, "parseResponseData");
  }
});

// packages/core/dist/src/utils/paths.js
import fs3 from "node:fs";
import path2 from "node:path";
import os2 from "node:os";
import * as crypto2 from "node:crypto";
function _resetValidatePathCacheForTest() {
  isDirectoryCache.clear();
}
function tildeifyPath(path150) {
  const homeDir = os2.homedir();
  if (path150.startsWith(homeDir)) {
    return path150.replace(homeDir, "~");
  }
  return path150;
}
function shortenPath(filePath, maxLen = 80) {
  if (filePath.length <= maxLen) {
    return filePath;
  }
  const separator = path2.sep;
  const ellipsis = "...";
  if (maxLen < 10) {
    return filePath.substring(0, maxLen - 3) + ellipsis;
  }
  const parsedPath = path2.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 start2 = full.substring(0, keepLen);
    const end = full.substring(full.length - keepLen);
    return `${start2}${ellipsis}${end}`;
  }
  const startPart = root + segments[0];
  const endSegments = [];
  for (let i4 = segments.length - 1; i4 >= 1; i4--) {
    const segment = segments[i4];
    const endPart = [segment, ...endSegments].join(separator);
    const needsEllipsis = i4 > 1;
    let candidateResult;
    if (needsEllipsis) {
      candidateResult = startPart + separator + ellipsis + separator + endPart;
    } else {
      candidateResult = startPart + separator + endPart;
    }
    if (candidateResult.length <= maxLen) {
      endSegments.unshift(segment);
      if (i4 === 1) {
        return candidateResult;
      }
    } else {
      break;
    }
  }
  if (endSegments.length === 0) {
    const keepLen = Math.floor((maxLen - 3) / 2);
    const start2 = filePath.substring(0, keepLen);
    const end = filePath.substring(filePath.length - keepLen);
    return `${start2}${ellipsis}${end}`;
  }
  return startPart + separator + ellipsis + separator + endSegments.join(separator);
}
function makeRelative(targetPath, rootDirectory) {
  const resolvedTargetPath = path2.resolve(targetPath);
  const resolvedRootDirectory = path2.resolve(rootDirectory);
  if (!isSubpath(resolvedRootDirectory, resolvedTargetPath)) {
    return resolvedTargetPath;
  }
  const relativePath = path2.relative(resolvedRootDirectory, resolvedTargetPath);
  return relativePath || ".";
}
function escapePath(filePath) {
  let result = "";
  for (let i4 = 0; i4 < filePath.length; i4++) {
    const char = filePath[i4];
    let backslashCount = 0;
    for (let j2 = i4 - 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 = os2.platform() === "win32" ? projectRoot.toLowerCase() : projectRoot;
  return crypto2.createHash("sha256").update(normalizedPath).digest("hex");
}
function sanitizeCwd(cwd6) {
  const normalizedCwd = os2.platform() === "win32" ? cwd6.toLowerCase() : cwd6;
  return normalizedCwd.replace(/[^a-zA-Z0-9]/g, "-");
}
function isSubpath(parentPath, childPath) {
  const isWindows9 = os2.platform() === "win32";
  const pathModule2 = isWindows9 ? path2.win32 : path2;
  const relative14 = pathModule2.relative(parentPath, childPath);
  return !relative14.startsWith(`..${pathModule2.sep}`) && relative14 !== ".." && !pathModule2.isAbsolute(relative14);
}
function isSubpaths(parentPath, childPath) {
  return parentPath.some((p2) => isSubpath(p2, childPath));
}
function resolvePath(baseDir = process.cwd(), relativePath) {
  const homeDir = os2.homedir();
  if (relativePath === "~") {
    return homeDir;
  } else if (relativePath.startsWith("~/")) {
    return path2.join(homeDir, relativePath.slice(2));
  } else if (path2.isAbsolute(relativePath)) {
    return relativePath;
  } else {
    return path2.resolve(baseDir, relativePath);
  }
}
function validatePath(config2, resolvedPath, options2 = {}) {
  const { allowFiles = false, allowExternalPaths = false } = options2;
  const workspaceContext = config2.getWorkspaceContext();
  const isWithinWorkspace = workspaceContext.isPathWithinWorkspace(resolvedPath);
  if (!allowExternalPaths && !isWithinWorkspace) {
    throw new Error("Path is not within workspace");
  }
  if (allowExternalPaths && !isWithinWorkspace) {
    return;
  }
  let isDirectory = isDirectoryCache.get(resolvedPath);
  if (isDirectory === void 0) {
    try {
      isDirectory = fs3.statSync(resolvedPath).isDirectory();
    } catch (error40) {
      if (isNodeError(error40) && error40.code === "ENOENT") {
        throw new Error(`Path does not exist: ${resolvedPath}`);
      }
      throw error40;
    }
    if (isDirectoryCache.size >= VALIDATE_PATH_CACHE_MAX) {
      const oldest = isDirectoryCache.keys().next().value;
      if (oldest !== void 0)
        isDirectoryCache.delete(oldest);
    }
    isDirectoryCache.set(resolvedPath, isDirectory);
  }
  if (!allowFiles && !isDirectory) {
    throw new Error(`Path is not a directory: ${resolvedPath}`);
  }
}
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, GOOGLE_ACCOUNTS_FILENAME, isDirectoryCache, VALIDATE_PATH_CACHE_MAX, SHELL_SPECIAL_CHARS;
var init_paths = __esm({
  "packages/core/dist/src/utils/paths.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    QWEN_DIR = ".qwen";
    GOOGLE_ACCOUNTS_FILENAME = "google_accounts.json";
    isDirectoryCache = /* @__PURE__ */ new Map();
    VALIDATE_PATH_CACHE_MAX = 1024;
    __name(_resetValidatePathCacheForTest, "_resetValidatePathCacheForTest");
    SHELL_SPECIAL_CHARS = /[ \t()[\]{};|*?$`'"#&<>!~]/;
    __name(tildeifyPath, "tildeifyPath");
    __name(shortenPath, "shortenPath");
    __name(makeRelative, "makeRelative");
    __name(escapePath, "escapePath");
    __name(unescapePath, "unescapePath");
    __name(getProjectHash, "getProjectHash");
    __name(sanitizeCwd, "sanitizeCwd");
    __name(isSubpath, "isSubpath");
    __name(isSubpaths, "isSubpaths");
    __name(resolvePath, "resolvePath");
    __name(validatePath, "validatePath");
    __name(resolveAndValidatePath, "resolveAndValidatePath");
  }
});

// packages/core/dist/src/config/storage.js
import * as path3 from "node:path";
import * as os3 from "node:os";
import * as fs4 from "node:fs";
import { AsyncLocalStorage } from "node:async_hooks";
var QWEN_DIR2, GOOGLE_ACCOUNTS_FILENAME2, OAUTH_FILE, SKILL_PROVIDER_CONFIG_DIRS, TMP_DIR_NAME, BIN_DIR_NAME, PROJECT_DIR_NAME, IDE_DIR_NAME, PLANS_DIR_NAME, DEBUG_DIR_NAME, ARENA_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_FILENAME2 = "google_accounts.json";
    OAUTH_FILE = "oauth_creds.json";
    SKILL_PROVIDER_CONFIG_DIRS = [".qwen", ".agents"];
    TMP_DIR_NAME = "tmp";
    BIN_DIR_NAME = "bin";
    PROJECT_DIR_NAME = "projects";
    IDE_DIR_NAME = "ide";
    PLANS_DIR_NAME = "plans";
    DEBUG_DIR_NAME = "debug";
    ARENA_DIR_NAME = "arena";
    Storage = class _Storage {
      static {
        __name(this, "Storage");
      }
      targetDir;
      /**
       * Custom runtime output base directory set via settings.
       * When null, falls back to getGlobalQwenDir().
       */
      static runtimeBaseDir = null;
      static runtimeBaseDirContext = new AsyncLocalStorage();
      constructor(targetDir) {
        this.targetDir = targetDir;
      }
      static resolveRuntimeBaseDir(dir, cwd6) {
        if (!dir) {
          return null;
        }
        let resolved = dir;
        if (resolved === "~" || resolved.startsWith("~/") || resolved.startsWith("~\\")) {
          const relativeSegments = resolved === "~" ? [] : resolved.slice(2).split(/[/\\]+/).filter(Boolean);
          resolved = path3.join(os3.homedir(), ...relativeSegments);
        }
        if (!path3.isAbsolute(resolved)) {
          resolved = cwd6 ? path3.resolve(cwd6, resolved) : path3.resolve(resolved);
        }
        return resolved;
      }
      /**
       * Sets the custom runtime output base directory.
       * Handles tilde (~) expansion and resolves relative paths to absolute.
       * Pass null/undefined/empty string to reset to default (getGlobalQwenDir()).
       * @param dir - The directory path, or null/undefined to reset
       * @param cwd - Base directory for resolving relative paths (defaults to process.cwd()).
       *              Pass the project root so that relative values like ".qwen" resolve
       *              per-project, enabling a single global config to work across all projects.
       */
      static setRuntimeBaseDir(dir, cwd6) {
        _Storage.runtimeBaseDir = _Storage.resolveRuntimeBaseDir(dir, cwd6);
      }
      /**
       * Runs function execution in an async context with a specific runtime output dir.
       * This is used to isolate runtime output paths between concurrent sessions.
       */
      static runWithRuntimeBaseDir(dir, cwd6, fn) {
        const resolved = _Storage.resolveRuntimeBaseDir(dir, cwd6);
        return _Storage.runtimeBaseDirContext.run(resolved, fn);
      }
      /**
       * Returns the base directory for all runtime output (temp files, debug logs,
       * session data, todos, insights, etc.).
       *
       * Priority: QWEN_RUNTIME_DIR env var > setRuntimeBaseDir() value > getGlobalQwenDir()
       * @returns Absolute path to the runtime output base directory
       */
      static getRuntimeBaseDir() {
        const envDir = process.env["QWEN_RUNTIME_DIR"];
        if (envDir) {
          return _Storage.resolveRuntimeBaseDir(envDir) ?? _Storage.getGlobalQwenDir();
        }
        const contextualDir = _Storage.runtimeBaseDirContext.getStore();
        if (contextualDir !== void 0) {
          return contextualDir ?? _Storage.getGlobalQwenDir();
        }
        if (_Storage.runtimeBaseDir) {
          return _Storage.runtimeBaseDir;
        }
        return _Storage.getGlobalQwenDir();
      }
      static getGlobalQwenDir() {
        const homeDir = os3.homedir();
        if (!homeDir) {
          return path3.join(os3.tmpdir(), ".qwen");
        }
        return path3.join(homeDir, QWEN_DIR2);
      }
      static getMcpOAuthTokensPath() {
        return path3.join(_Storage.getGlobalQwenDir(), "mcp-oauth-tokens.json");
      }
      static getGlobalSettingsPath() {
        return path3.join(_Storage.getGlobalQwenDir(), "settings.json");
      }
      static getInstallationIdPath() {
        return path3.join(_Storage.getGlobalQwenDir(), "installation_id");
      }
      static getGoogleAccountsPath() {
        return path3.join(_Storage.getGlobalQwenDir(), GOOGLE_ACCOUNTS_FILENAME2);
      }
      static getUserCommandsDir() {
        return path3.join(_Storage.getGlobalQwenDir(), "commands");
      }
      static getGlobalMemoryFilePath() {
        return path3.join(_Storage.getGlobalQwenDir(), "memory.md");
      }
      static getGlobalTempDir() {
        return path3.join(_Storage.getRuntimeBaseDir(), TMP_DIR_NAME);
      }
      static getGlobalDebugDir() {
        return path3.join(_Storage.getRuntimeBaseDir(), DEBUG_DIR_NAME);
      }
      static getDebugLogPath(sessionId) {
        return path3.join(_Storage.getGlobalDebugDir(), `${sessionId}.txt`);
      }
      static getGlobalIdeDir() {
        return path3.join(_Storage.getRuntimeBaseDir(), IDE_DIR_NAME);
      }
      static getPlansDir() {
        return path3.join(_Storage.getGlobalQwenDir(), PLANS_DIR_NAME);
      }
      static getPlanFilePath(sessionId) {
        return path3.join(_Storage.getPlansDir(), `${sessionId}.md`);
      }
      static getGlobalBinDir() {
        return path3.join(_Storage.getGlobalQwenDir(), BIN_DIR_NAME);
      }
      static getGlobalArenaDir() {
        return path3.join(_Storage.getGlobalQwenDir(), ARENA_DIR_NAME);
      }
      getQwenDir() {
        return path3.join(this.targetDir, QWEN_DIR2);
      }
      getProjectDir() {
        const projectId = sanitizeCwd(this.getProjectRoot());
        const projectsDir = path3.join(_Storage.getRuntimeBaseDir(), PROJECT_DIR_NAME);
        return path3.join(projectsDir, projectId);
      }
      getProjectTempDir() {
        const hash = getProjectHash(this.getProjectRoot());
        const tempDir = _Storage.getGlobalTempDir();
        const targetDir = path3.join(tempDir, hash);
        return targetDir;
      }
      ensureProjectTempDirExists() {
        fs4.mkdirSync(this.getProjectTempDir(), { recursive: true });
      }
      static getOAuthCredsPath() {
        return path3.join(_Storage.getGlobalQwenDir(), OAUTH_FILE);
      }
      getProjectRoot() {
        return this.targetDir;
      }
      getHistoryDir() {
        const hash = getProjectHash(this.getProjectRoot());
        const historyDir = path3.join(_Storage.getRuntimeBaseDir(), "history");
        const targetDir = path3.join(historyDir, hash);
        return targetDir;
      }
      getWorkspaceSettingsPath() {
        return path3.join(this.getQwenDir(), "settings.json");
      }
      getProjectCommandsDir() {
        return path3.join(this.getQwenDir(), "commands");
      }
      getProjectTempCheckpointsDir() {
        return path3.join(this.getProjectTempDir(), "checkpoints");
      }
      getExtensionsDir() {
        return path3.join(this.getQwenDir(), "extensions");
      }
      getExtensionsConfigPath() {
        return path3.join(this.getExtensionsDir(), "qwen-extension.json");
      }
      getUserSkillsDirs() {
        const homeDir = os3.homedir() || os3.tmpdir();
        return SKILL_PROVIDER_CONFIG_DIRS.map((dir) => path3.join(homeDir, dir, "skills"));
      }
      /**
       * Returns the user-level extensions directory (~/.qwen/extensions/).
       * Extensions installed at user scope are stored here, as opposed to
       * project-level extensions which live in <project>/.qwen/extensions/.
       */
      static getUserExtensionsDir() {
        return path3.join(_Storage.getGlobalQwenDir(), "extensions");
      }
      getHistoryFilePath() {
        return path3.join(this.getProjectTempDir(), "shell_history");
      }
    };
  }
});

// packages/core/dist/src/utils/symlink.js
import { promises as fs5 } from "node:fs";
import path4 from "node:path";
async function updateSymlink(linkPath, targetPath, options2) {
  const { fallbackCopy = true } = options2 ?? {};
  const linkDir = path4.dirname(linkPath);
  const relativeTarget = path4.relative(linkDir, targetPath);
  try {
    await fs5.unlink(linkPath);
  } catch {
  }
  try {
    await fs5.symlink(relativeTarget, linkPath);
    return;
  } catch {
  }
  if (fallbackCopy) {
    try {
      await fs5.copyFile(targetPath, linkPath);
    } catch {
    }
  }
}
var init_symlink = __esm({
  "packages/core/dist/src/utils/symlink.js"() {
    "use strict";
    init_esbuild_shims();
    __name(updateSymlink, "updateSymlink");
  }
});

// packages/core/dist/src/utils/debugLogger.js
import { promises as fs6 } from "node:fs";
import path5 from "node:path";
import { AsyncLocalStorage as AsyncLocalStorage2 } 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() {
  const debugDirPath = Storage.getGlobalDebugDir();
  if (!ensureDebugDirPromise || ensuredDebugDirPath !== debugDirPath) {
    ensuredDebugDirPath = debugDirPath;
    ensureDebugDirPromise = fs6.mkdir(debugDirPath, { recursive: true }).then(() => void 0).catch(() => {
      hasWriteFailure = true;
      ensureDebugDirPromise = null;
      ensuredDebugDirPath = null;
    });
  }
  return ensureDebugDirPromise ?? Promise.resolve();
}
function formatArgs(args2) {
  return args2.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, args2) {
  if (!isDebugLogFileEnabled()) {
    return;
  }
  const sessionId = session.getSessionId();
  const logFilePath = Storage.getDebugLogPath(sessionId);
  const message = formatArgs(args2);
  const line = buildLogLine(level, message, tag2);
  void ensureDebugDirExists().then(() => fs6.appendFile(logFilePath, line, "utf8")).catch(() => {
    hasWriteFailure = true;
  });
}
function isDebugLoggingDegraded() {
  return hasWriteFailure;
}
function resetDebugLoggingState() {
  hasWriteFailure = false;
  ensureDebugDirPromise = null;
  ensuredDebugDirPath = null;
}
function updateLatestDebugLogAlias(sessionId) {
  if (!isDebugLogFileEnabled()) {
    return;
  }
  const aliasPath = path5.join(Storage.getGlobalDebugDir(), DEBUG_LATEST_ALIAS);
  const targetPath = Storage.getDebugLogPath(sessionId);
  void ensureDebugDirExists().then(() => updateSymlink(aliasPath, targetPath, { fallbackCopy: false })).catch(() => {
  });
}
function setDebugLogSession(session) {
  globalSession = session ?? null;
  if (session) {
    updateLatestDebugLogAlias(session.getSessionId());
  }
}
function runWithDebugLogSession(session, fn) {
  return sessionContext.run(session, fn);
}
function createDebugLogger(tag2) {
  return {
    debug: /* @__PURE__ */ __name((...args2) => {
      const session = getActiveSession();
      if (!session)
        return;
      writeLog(session, "DEBUG", tag2, args2);
    }, "debug"),
    info: /* @__PURE__ */ __name((...args2) => {
      const session = getActiveSession();
      if (!session)
        return;
      writeLog(session, "INFO", tag2, args2);
    }, "info"),
    warn: /* @__PURE__ */ __name((...args2) => {
      const session = getActiveSession();
      if (!session)
        return;
      writeLog(session, "WARN", tag2, args2);
    }, "warn"),
    error: /* @__PURE__ */ __name((...args2) => {
      const session = getActiveSession();
      if (!session)
        return;
      writeLog(session, "ERROR", tag2, args2);
    }, "error")
  };
}
var ensureDebugDirPromise, ensuredDebugDirPath, hasWriteFailure, globalSession, sessionContext, DEBUG_LATEST_ALIAS;
var init_debugLogger = __esm({
  "packages/core/dist/src/utils/debugLogger.js"() {
    "use strict";
    init_esbuild_shims();
    init_storage();
    init_symlink();
    ensureDebugDirPromise = null;
    ensuredDebugDirPath = null;
    hasWriteFailure = false;
    globalSession = null;
    sessionContext = new AsyncLocalStorage2();
    __name(isDebugLogFileEnabled, "isDebugLogFileEnabled");
    __name(getActiveSession, "getActiveSession");
    __name(ensureDebugDirExists, "ensureDebugDirExists");
    __name(formatArgs, "formatArgs");
    __name(buildLogLine, "buildLogLine");
    __name(writeLog, "writeLog");
    __name(isDebugLoggingDegraded, "isDebugLoggingDegraded");
    __name(resetDebugLoggingState, "resetDebugLoggingState");
    DEBUG_LATEST_ALIAS = "latest";
    __name(updateLatestDebugLogAlias, "updateLatestDebugLogAlias");
    __name(setDebugLogSession, "setDebugLogSession");
    __name(runWithDebugLogSession, "runWithDebugLogSession");
    __name(createDebugLogger, "createDebugLogger");
  }
});

// packages/core/dist/src/utils/atomicFileWrite.js
import * as crypto3 from "node:crypto";
import * as fs7 from "node:fs/promises";
async function atomicWriteJSON(filePath, data, options2) {
  const retries = options2?.retries ?? 3;
  const delayMs = options2?.delayMs ?? 50;
  const tmpPath = `${filePath}.${crypto3.randomBytes(4).toString("hex")}.tmp`;
  try {
    await fs7.writeFile(tmpPath, JSON.stringify(data, null, 2), "utf-8");
    await renameWithRetry(tmpPath, filePath, retries, delayMs);
  } catch (error40) {
    try {
      await fs7.unlink(tmpPath);
    } catch {
    }
    throw error40;
  }
}
async function renameWithRetry(src, dest, retries, delayMs) {
  for (let attempt = 0; attempt <= retries; attempt++) {
    try {
      await fs7.rename(src, dest);
      return;
    } catch (error40) {
      const isRetryable = isNodeError(error40) && (error40.code === "EPERM" || error40.code === "EACCES");
      if (!isRetryable || attempt === retries) {
        throw error40;
      }
      await new Promise((resolve42) => setTimeout(resolve42, delayMs * 2 ** attempt));
    }
  }
}
var init_atomicFileWrite = __esm({
  "packages/core/dist/src/utils/atomicFileWrite.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    __name(atomicWriteJSON, "atomicWriteJSON");
    __name(renameWithRetry, "renameWithRetry");
  }
});

// packages/core/dist/src/telemetry/constants.js
var SERVICE_NAME, EVENT_USER_PROMPT, EVENT_USER_RETRY, 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_FLASH_FALLBACK, EVENT_RIPGREP_FALLBACK, EVENT_NEXT_SPEAKER_CHECK, EVENT_SLASH_COMMAND, EVENT_IDE_CONNECTION, EVENT_CHAT_COMPRESSION, EVENT_CONTENT_RETRY, EVENT_CONTENT_RETRY_FAILURE, EVENT_CONVERSATION_FINISHED, EVENT_FILE_OPERATION, EVENT_MODEL_SLASH_COMMAND, EVENT_SUBAGENT_EXECUTION, EVENT_SKILL_LAUNCH, EVENT_AUTH, EVENT_USER_FEEDBACK, EVENT_PROMPT_SUGGESTION, EVENT_SPECULATION, EVENT_ARENA_SESSION_STARTED, EVENT_ARENA_AGENT_COMPLETED, EVENT_ARENA_SESSION_ENDED, EVENT_MEMORY_EXTRACT, EVENT_MEMORY_DREAM, EVENT_MEMORY_RECALL;
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_USER_RETRY = "qwen-code.user_retry";
    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_FLASH_FALLBACK = "qwen-code.flash_fallback";
    EVENT_RIPGREP_FALLBACK = "qwen-code.ripgrep_fallback";
    EVENT_NEXT_SPEAKER_CHECK = "qwen-code.next_speaker_check";
    EVENT_SLASH_COMMAND = "qwen-code.slash_command";
    EVENT_IDE_CONNECTION = "qwen-code.ide_connection";
    EVENT_CHAT_COMPRESSION = "qwen-code.chat_compression";
    EVENT_CONTENT_RETRY = "qwen-code.chat.content_retry";
    EVENT_CONTENT_RETRY_FAILURE = "qwen-code.chat.content_retry_failure";
    EVENT_CONVERSATION_FINISHED = "qwen-code.conversation_finished";
    EVENT_FILE_OPERATION = "qwen-code.file_operation";
    EVENT_MODEL_SLASH_COMMAND = "qwen-code.slash_command.model";
    EVENT_SUBAGENT_EXECUTION = "qwen-code.subagent_execution";
    EVENT_SKILL_LAUNCH = "qwen-code.skill_launch";
    EVENT_AUTH = "qwen-code.auth";
    EVENT_USER_FEEDBACK = "qwen-code.user_feedback";
    EVENT_PROMPT_SUGGESTION = "qwen-code.prompt_suggestion";
    EVENT_SPECULATION = "qwen-code.speculation";
    EVENT_ARENA_SESSION_STARTED = "qwen-code.arena_session_started";
    EVENT_ARENA_AGENT_COMPLETED = "qwen-code.arena_agent_completed";
    EVENT_ARENA_SESSION_ENDED = "qwen-code.arena_session_ended";
    EVENT_MEMORY_EXTRACT = "qwen-code.memory.extract";
    EVENT_MEMORY_DREAM = "qwen-code.memory.dream";
    EVENT_MEMORY_RECALL = "qwen-code.memory.recall";
  }
});

// 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["OUTPUT_TRUNCATED"] = "output_truncated";
      ToolErrorType2["TASK_STOP_NOT_FOUND"] = "task_stop_not_found";
      ToolErrorType2["TASK_STOP_NOT_RUNNING"] = "task_stop_not_running";
      ToolErrorType2["SEND_MESSAGE_NOT_FOUND"] = "send_message_not_found";
      ToolErrorType2["SEND_MESSAGE_NOT_RUNNING"] = "send_message_not_running";
    })(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, ...args2) {
      const code2 = [strs[0]];
      let i4 = 0;
      while (i4 < args2.length) {
        addCodeArg(code2, args2[i4]);
        code2.push(strs[++i4]);
      }
      return new _Code(code2);
    }
    __name(_2, "_");
    exports2._ = _2;
    var plus = new _Code("+");
    function str2(strs, ...args2) {
      const expr = [safeStringify(strs[0])];
      let i4 = 0;
      while (i4 < args2.length) {
        expr.push(plus);
        addCodeArg(expr, args2[i4]);
        expr.push(plus, safeStringify(strs[++i4]));
      }
      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 i4 = 1;
      while (i4 < expr.length - 1) {
        if (expr[i4] === plus) {
          const res = mergeExprItems(expr[i4 - 1], expr[i4 + 1]);
          if (res !== void 0) {
            expr.splice(i4 - 1, 3, res);
            continue;
          }
          expr[i4++] = "+";
        }
        i4++;
      }
    }
    __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(name4) {
        super(`CodeGen: "code" for ${name4} not defined`);
        this.value = name4.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 name4 = this.toName(nameOrPrefix);
        const { prefix } = name4;
        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, name4);
        const s5 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s5.length;
        s5[itemIndex] = value.ref;
        name4.setValue(value, { property: prefix, itemIndex });
        return name4;
      }
      getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
          return;
        return vs.get(keyOrRef);
      }
      scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name4) => {
          if (name4.scopePath === void 0)
            throw new Error(`CodeGen: name "${name4}" has no value`);
          return (0, code_1._)`${scopeName}${name4.scopePath}`;
        });
      }
      scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name4) => {
          if (name4.value === void 0)
            throw new Error(`CodeGen: name "${name4}" has no value`);
          return name4.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((name4) => {
            if (nameSet.has(name4))
              return;
            nameSet.set(name4, UsedValueState.Started);
            let c4 = valueCode(name4);
            if (c4) {
              const def2 = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const;
              code2 = (0, code_1._)`${code2}${def2} ${name4} = ${c4};${this.opts._n}`;
            } else if (c4 = getCode === null || getCode === void 0 ? void 0 : getCode(name4)) {
              code2 = (0, code_1._)`${code2}${c4}${this.opts._n}`;
            } else {
              throw new ValueError(name4);
            }
            nameSet.set(name4, 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, name4, rhs) {
        super();
        this.varKind = varKind;
        this.name = name4;
        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, constants5) {
        if (!names[this.name.str])
          return;
        if (this.rhs)
          this.rhs = optimizeExpr(this.rhs, names, constants5);
        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, constants5) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
          return;
        this.rhs = optimizeExpr(this.rhs, names, constants5);
        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(error40) {
        super();
        this.error = error40;
      }
      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, constants5) {
        this.code = optimizeExpr(this.code, names, constants5);
        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 i4 = nodes.length;
        while (i4--) {
          const n3 = nodes[i4].optimizeNodes();
          if (Array.isArray(n3))
            nodes.splice(i4, 1, ...n3);
          else if (n3)
            nodes[i4] = n3;
          else
            nodes.splice(i4, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants5) {
        const { nodes } = this;
        let i4 = nodes.length;
        while (i4--) {
          const n3 = nodes[i4];
          if (n3.optimizeNames(names, constants5))
            continue;
          subtractNames(names, n3.names);
          nodes.splice(i4, 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, constants5) {
        var _a7;
        this.else = (_a7 = this.else) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names, constants5);
        if (!(super.optimizeNames(names, constants5) || this.else))
          return;
        this.condition = optimizeExpr(this.condition, names, constants5);
        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, constants5) {
        if (!super.optimizeNames(names, constants5))
          return;
        this.iteration = optimizeExpr(this.iteration, names, constants5);
        return this;
      }
      get names() {
        return addNames(super.names, this.iteration.names);
      }
    };
    var ForRange = class extends For {
      static {
        __name(this, "ForRange");
      }
      constructor(varKind, name4, from, to) {
        super();
        this.varKind = varKind;
        this.name = name4;
        this.from = from;
        this.to = to;
      }
      render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name: name4, from, to } = this;
        return `for(${varKind} ${name4}=${from}; ${name4}<${to}; ${name4}++)` + 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, name4, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name4;
        this.iterable = iterable;
      }
      render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
      }
      optimizeNames(names, constants5) {
        if (!super.optimizeNames(names, constants5))
          return;
        this.iterable = optimizeExpr(this.iterable, names, constants5);
        return this;
      }
      get names() {
        return addNames(super.names, this.iterable.names);
      }
    };
    var Func = class extends BlockNode {
      static {
        __name(this, "Func");
      }
      constructor(name4, args2, async) {
        super();
        this.name = name4;
        this.args = args2;
        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, constants5) {
        var _a7, _b2;
        super.optimizeNames(names, constants5);
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names, constants5);
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNames(names, constants5);
        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(error40) {
        super();
        this.error = error40;
      }
      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 name4 = this._extScope.value(prefixOrName, value);
        const vs = this._values[name4.prefix] || (this._values[name4.prefix] = /* @__PURE__ */ new Set());
        vs.add(name4);
        return name4;
      }
      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 name4 = this._scope.toName(nameOrPrefix);
        if (rhs !== void 0 && constant)
          this._constants[name4.str] = rhs;
        this._leafNode(new Def(varKind, name4, rhs));
        return name4;
      }
      // `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 name4 = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name4, from, to), () => forBody(name4));
      }
      // `for-of` statement (in es5 mode replace with a normal for loop)
      forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name4 = 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`, (i4) => {
            this.var(name4, (0, code_1._)`${arr}[${i4}]`);
            forBody(name4);
          });
        }
        return this._for(new ForIter("of", varKind, name4, iterable), () => forBody(name4));
      }
      // `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 name4 = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name4, obj), () => forBody(name4));
      }
      // 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 error40 = this.name("e");
          this._currNode = node.catch = new Catch(error40);
          catchCode(error40);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error40) {
        return this._leafNode(new Throw(error40));
      }
      // start self-balancing block
      block(body2, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body2)
          this.code(body2).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(name4, args2 = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name4, args2, 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, constants5) {
      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 = constants5[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 && constants5[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(...args2) {
      return args2.reduce(andCode);
    }
    __name(and, "and");
    exports2.and = and;
    var orCode = mappend(exports2.operators.OR);
    function or2(...args2) {
      return args2.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_util9 = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.checkStrictMode = exports2.getErrorPath = exports2.Type = exports2.useFunc = exports2.setEvaluated = exports2.evaluatedPropsToName = exports2.mergeEvaluated = exports2.eachItem = exports2.unescapeJsonPointer = exports2.escapeJsonPointer = exports2.escapeFragment = exports2.unescapeFragment = exports2.schemaRefOrVal = exports2.schemaHasRulesButRef = exports2.schemaHasRules = exports2.checkUnknownRules = exports2.alwaysValidSchema = exports2.toHash = void 0;
    var codegen_1 = require_codegen();
    var code_1 = require_code();
    function toHash(arr) {
      const hash = {};
      for (const item of arr)
        hash[item] = true;
      return hash;
    }
    __name(toHash, "toHash");
    exports2.toHash = toHash;
    function alwaysValidSchema(it3, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it3, schema);
      return !schemaHasRules(schema, it3.self.RULES.all);
    }
    __name(alwaysValidSchema, "alwaysValidSchema");
    exports2.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it3, schema = it3.schema) {
      const { opts, self: self2 } = it3;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules[key])
          checkStrictMode(it3, `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 isNumber4 = dataPropType === Type3.Num;
        return jsPropertySyntax ? isNumber4 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber4 ? (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(it3, msg, mode = it3.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it3.self.logger.warn(msg);
    }
    __name(checkStrictMode, "checkStrictMode");
    exports2.checkStrictMode = checkStrictMode;
  }
});

// packages/core/node_modules/ajv/dist/compile/names.js
var require_names = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/names.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var names = {
      // validation function arguments
      data: new codegen_1.Name("data"),
      // data passed to validation function
      // args passed from referencing schema
      valCxt: new codegen_1.Name("valCxt"),
      // validation/data context - should not be used directly, it is destructured to the names below
      instancePath: new codegen_1.Name("instancePath"),
      parentData: new codegen_1.Name("parentData"),
      parentDataProperty: new codegen_1.Name("parentDataProperty"),
      rootData: new codegen_1.Name("rootData"),
      // root data - same as the data passed to the first/top validation function
      dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
      // used to support recursiveRef and dynamicRef
      // function scoped variables
      vErrors: new codegen_1.Name("vErrors"),
      // null or array of validation errors
      errors: new codegen_1.Name("errors"),
      // counter of validation errors
      this: new codegen_1.Name("this"),
      // "globals"
      self: new codegen_1.Name("self"),
      scope: new codegen_1.Name("scope"),
      // JTD serialize/parse name for JSON string and position
      json: new codegen_1.Name("json"),
      jsonPos: new codegen_1.Name("jsonPos"),
      jsonLen: new codegen_1.Name("jsonLen"),
      jsonPart: new codegen_1.Name("jsonPart")
    };
    exports2.default = names;
  }
});

// packages/core/node_modules/ajv/dist/compile/errors.js
var require_errors2 = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/errors.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.extendErrors = exports2.resetErrorsCount = exports2.reportExtraError = exports2.reportError = exports2.keyword$DataError = exports2.keywordError = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var names_1 = require_names();
    exports2.keywordError = {
      message: /* @__PURE__ */ __name(({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`, "message")
    };
    exports2.keyword$DataError = {
      message: /* @__PURE__ */ __name(({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`, "message")
    };
    function reportError3(cxt, error40 = exports2.keywordError, errorPaths, overrideAllErrors) {
      const { it: it3 } = cxt;
      const { gen, compositeRule, allErrors } = it3;
      const errObj = errorObjectCode(cxt, error40, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it3, (0, codegen_1._)`[${errObj}]`);
      }
    }
    __name(reportError3, "reportError");
    exports2.reportError = reportError3;
    function reportExtraError(cxt, error40 = exports2.keywordError, errorPaths) {
      const { it: it3 } = cxt;
      const { gen, compositeRule, allErrors } = it3;
      const errObj = errorObjectCode(cxt, error40, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it3, 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: it3 }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err2 = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i4) => {
        gen.const(err2, (0, codegen_1._)`${names_1.default.vErrors}[${i4}]`);
        gen.if((0, codegen_1._)`${err2}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err2}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it3.errorPath)));
        gen.assign((0, codegen_1._)`${err2}.schemaPath`, (0, codegen_1.str)`${it3.errSchemaPath}/${keyword}`);
        if (it3.opts.verbose) {
          gen.assign((0, codegen_1._)`${err2}.schema`, schemaValue);
          gen.assign((0, codegen_1._)`${err2}.data`, data);
        }
      });
    }
    __name(extendErrors, "extendErrors");
    exports2.extendErrors = extendErrors;
    function addError(gen, errObj) {
      const err2 = gen.const("err", errObj);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err2}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err2})`);
      gen.code((0, codegen_1._)`${names_1.default.errors}++`);
    }
    __name(addError, "addError");
    function returnErrors(it3, errs) {
      const { gen, validateName: validateName2, schemaEnv } = it3;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it3.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, error40, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error40, errorPaths);
    }
    __name(errorObjectCode, "errorObjectCode");
    function errorObject(cxt, error40, errorPaths = {}) {
      const { gen, it: it3 } = cxt;
      const keyValues = [
        errorInstancePath(it3, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error40, 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: it3 } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it3;
      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(it3) {
      const { gen, schema, validateName: validateName2 } = it3;
      if (schema === false) {
        falseSchemaError(it3, 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(it3, valid) {
      const { gen, schema } = it3;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it3);
      } else {
        gen.var(valid, true);
      }
    }
    __name(boolOrEmptySchema, "boolOrEmptySchema");
    exports2.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it3, overrideAllErrors) {
      const { gen, data } = it3;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it: it3
      };
      (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_util9();
    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(it3, types7) {
      const { gen, data, opts } = it3;
      const coerceTo = coerceToTypes(types7, opts.coerceTypes);
      const checkTypes = types7.length > 0 && !(coerceTo.length === 0 && types7.length === 1 && (0, applicability_1.schemaHasRulesForType)(it3, types7[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types7, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it3, types7, coerceTo);
          else
            reportTypeError(it3);
        });
      }
      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(it3, types7, coerceTo) {
      const { gen, data, opts } = it3;
      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(it3);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it3, 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(it3) {
      const cxt = getTypeErrorContext(it3);
      (0, errors_1.reportError)(cxt, typeError);
    }
    __name(reportTypeError, "reportTypeError");
    exports2.reportTypeError = reportTypeError;
    function getTypeErrorContext(it3) {
      const { gen, data, schema } = it3;
      const schemaCode = (0, util_1.schemaRefOrVal)(it3, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it: it3
      };
    }
    __name(getTypeErrorContext, "getTypeErrorContext");
  }
});

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

// packages/core/node_modules/ajv/dist/vocabularies/code.js
var require_code2 = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/code.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateUnion = exports2.validateArray = exports2.usePattern = exports2.callValidateCode = exports2.schemaProperties = exports2.allSchemaProperties = exports2.noPropertyInData = exports2.propertyInData = exports2.isOwnProperty = exports2.hasPropFunc = exports2.reportMissingProp = exports2.checkMissingProp = exports2.checkReportMissingProp = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var names_1 = require_names();
    var util_2 = require_util9();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it: it3 } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it3.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(it3, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it3, schemaMap[p2]));
    }
    __name(schemaProperties, "schemaProperties");
    exports2.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it: it3 }, func2, 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, it3.parentData],
        [names_1.default.parentDataProperty, it3.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it3.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args2 = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return context2 !== codegen_1.nil ? (0, codegen_1._)`${func2}.call(${context2}, ${args2})` : (0, codegen_1._)`${func2}(${args2})`;
    }
    __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: it3 } = cxt;
      const valid = gen.name("valid");
      if (it3.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, (i4) => {
          cxt.subschema({
            keyword,
            dataProp: i4,
            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: it3 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it3, sch));
      if (alwaysValid && !it3.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i4) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i4,
          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: it3 } = cxt;
      const macroSchema = def2.macro.call(it3.self, schema, parentSchema, it3);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it3.opts.validateSchema !== false)
        it3.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it3.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: it3 } = cxt;
      checkAsyncKeyword(it3, def2);
      const validate3 = !$data && def2.compile ? def2.compile.call(it3.self, schema, parentSchema, it3) : 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 ${it3.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 = it3.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: it3 } = cxt;
      gen.if(it3.parentData, () => gen.assign(data, (0, codegen_1._)`${it3.parentData}[${it3.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_util9();
    function getSubschema(it3, { 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 = it3.schema[keyword];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it3.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
          errSchemaPath: `${it3.errSchemaPath}/${keyword}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it3.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it3.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, it3, { 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 } = it3;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it3;
        const nextData = gen.let("data", (0, codegen_1._)`${it3.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 = it3.dataLevel + 1;
        subschema.dataTypes = [];
        it3.definedProperties = /* @__PURE__ */ new Set();
        subschema.parentData = it3.data;
        subschema.dataNames = [...it3.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, i4, keys;
        if (Array.isArray(a2)) {
          length = a2.length;
          if (length != b2.length) return false;
          for (i4 = length; i4-- !== 0; )
            if (!equal(a2[i4], b2[i4])) 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 (i4 = length; i4-- !== 0; )
          if (!Object.prototype.hasOwnProperty.call(b2, keys[i4])) return false;
        for (i4 = length; i4-- !== 0; ) {
          var key = keys[i4];
          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 post2 = cb.post || function() {
      };
      _traverse(opts, pre, post2, 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, post2, 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 i4 = 0; i4 < sch.length; i4++)
                _traverse(opts, pre, post2, sch[i4], jsonPtr + "/" + key + "/" + i4, rootSchema, jsonPtr, key, schema, i4);
            }
          } else if (key in traverse.propsKeywords) {
            if (sch && typeof sch == "object") {
              for (var prop in sch)
                _traverse(opts, pre, post2, 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, post2, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
          }
        }
        post2(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
      }
    }
    __name(_traverse, "_traverse");
    function escapeJsonPtr(str2) {
      return str2.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    __name(escapeJsonPtr, "escapeJsonPtr");
  }
});

// packages/core/node_modules/ajv/dist/compile/resolve.js
var require_resolve = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/resolve.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSchemaRefs = exports2.resolveUrl = exports2.normalizeId = exports2._getFullPath = exports2.getFullPath = exports2.inlineRef = void 0;
    var util_1 = require_util9();
    var equal = require_fast_deep_equal();
    var traverse = require_json_schema_traverse();
    var SIMPLE_INLINED = /* @__PURE__ */ new Set([
      "type",
      "format",
      "pattern",
      "maxLength",
      "minLength",
      "maxProperties",
      "minProperties",
      "maxItems",
      "minItems",
      "maximum",
      "minimum",
      "uniqueItems",
      "multipleOf",
      "required",
      "enum",
      "const"
    ]);
    function inlineRef(schema, limit2 = true) {
      if (typeof schema == "boolean")
        return true;
      if (limit2 === true)
        return !hasRef(schema);
      if (!limit2)
        return false;
      return countKeys(schema) <= limit2;
    }
    __name(inlineRef, "inlineRef");
    exports2.inlineRef = inlineRef;
    var REF_KEYWORDS = /* @__PURE__ */ new Set([
      "$ref",
      "$recursiveRef",
      "$recursiveAnchor",
      "$dynamicRef",
      "$dynamicAnchor"
    ]);
    function hasRef(schema) {
      for (const key in schema) {
        if (REF_KEYWORDS.has(key))
          return true;
        const sch = schema[key];
        if (Array.isArray(sch) && sch.some(hasRef))
          return true;
        if (typeof sch == "object" && hasRef(sch))
          return true;
      }
      return false;
    }
    __name(hasRef, "hasRef");
    function countKeys(schema) {
      let count = 0;
      for (const key in schema) {
        if (key === "$ref")
          return Infinity;
        count++;
        if (SIMPLE_INLINED.has(key))
          continue;
        if (typeof schema[key] == "object") {
          (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
        }
        if (count === Infinity)
          return Infinity;
      }
      return count;
    }
    __name(countKeys, "countKeys");
    function getFullPath(resolver, id = "", normalize13) {
      if (normalize13 !== 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_util9();
    var errors_1 = require_errors2();
    function validateFunctionCode(it3) {
      if (isSchemaObj(it3)) {
        checkKeywords(it3);
        if (schemaCxtHasRules(it3)) {
          topSchemaObjCode(it3);
          return;
        }
      }
      validateFunction(it3, () => (0, boolSchema_1.topBoolOrEmptySchema)(it3));
    }
    __name(validateFunctionCode, "validateFunctionCode");
    exports2.validateFunctionCode = validateFunctionCode;
    function validateFunction({ gen, validateName: validateName2, schema, schemaEnv, opts }, body2) {
      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(body2);
        });
      } else {
        gen.func(validateName2, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body2));
      }
    }
    __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(it3) {
      const { schema, opts, gen } = it3;
      validateFunction(it3, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it3);
        checkNoDefault(it3);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it3);
        typeAndKeywords(it3);
        returnResults(it3);
      });
      return;
    }
    __name(topSchemaObjCode, "topSchemaObjCode");
    function resetEvaluated(it3) {
      const { gen, validateName: validateName2 } = it3;
      it3.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName2}.evaluated`);
      gen.if((0, codegen_1._)`${it3.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it3.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it3.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it3.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(it3, valid) {
      if (isSchemaObj(it3)) {
        checkKeywords(it3);
        if (schemaCxtHasRules(it3)) {
          subSchemaObjCode(it3, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it3, 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(it3) {
      return typeof it3.schema != "boolean";
    }
    __name(isSchemaObj, "isSchemaObj");
    function subSchemaObjCode(it3, valid) {
      const { schema, gen, opts } = it3;
      if (opts.$comment && schema.$comment)
        commentKeyword(it3);
      updateContext(it3);
      checkAsyncSchema(it3);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it3, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    __name(subSchemaObjCode, "subSchemaObjCode");
    function checkKeywords(it3) {
      (0, util_1.checkUnknownRules)(it3);
      checkRefsAndKeywords(it3);
    }
    __name(checkKeywords, "checkKeywords");
    function typeAndKeywords(it3, errsCount) {
      if (it3.opts.jtd)
        return schemaKeywords(it3, [], false, errsCount);
      const types7 = (0, dataType_1.getSchemaTypes)(it3.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it3, types7);
      schemaKeywords(it3, types7, !checkedTypes, errsCount);
    }
    __name(typeAndKeywords, "typeAndKeywords");
    function checkRefsAndKeywords(it3) {
      const { schema, errSchemaPath, opts, self: self2 } = it3;
      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(it3) {
      const { schema, opts } = it3;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it3, "default is ignored in the schema root");
      }
    }
    __name(checkNoDefault, "checkNoDefault");
    function updateContext(it3) {
      const schId = it3.schema[it3.opts.schemaId];
      if (schId)
        it3.baseId = (0, resolve_1.resolveUrl)(it3.opts.uriResolver, it3.baseId, schId);
    }
    __name(updateContext, "updateContext");
    function checkAsyncSchema(it3) {
      if (it3.schema.$async && !it3.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(it3) {
      const { gen, schemaEnv, validateName: validateName2, ValidationError, opts } = it3;
      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(it3);
        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(it3, types7, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it3;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it3, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it3, 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(it3, group);
          if (types7.length === 1 && types7[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it3);
          }
          gen.endIf();
        } else {
          iterateKeywords(it3, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
      __name(groupKeywords, "groupKeywords");
    }
    __name(schemaKeywords, "schemaKeywords");
    function iterateKeywords(it3, group) {
      const { gen, schema, opts: { useDefaults } } = it3;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it3, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it3, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    __name(iterateKeywords, "iterateKeywords");
    function checkStrictTypes(it3, types7) {
      if (it3.schemaEnv.meta || !it3.opts.strictTypes)
        return;
      checkContextTypes(it3, types7);
      if (!it3.opts.allowUnionTypes)
        checkMultipleTypes(it3, types7);
      checkKeywordTypes(it3, it3.dataTypes);
    }
    __name(checkStrictTypes, "checkStrictTypes");
    function checkContextTypes(it3, types7) {
      if (!types7.length)
        return;
      if (!it3.dataTypes.length) {
        it3.dataTypes = types7;
        return;
      }
      types7.forEach((t5) => {
        if (!includesType(it3.dataTypes, t5)) {
          strictTypesError(it3, `type "${t5}" not allowed by context "${it3.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it3, types7);
    }
    __name(checkContextTypes, "checkContextTypes");
    function checkMultipleTypes(it3, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it3, "use allowUnionTypes to allow union type keyword");
      }
    }
    __name(checkMultipleTypes, "checkMultipleTypes");
    function checkKeywordTypes(it3, ts) {
      const rules = it3.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it3.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t5) => hasApplicableType(ts, t5))) {
            strictTypesError(it3, `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(it3, withTypes) {
      const ts = [];
      for (const t5 of it3.dataTypes) {
        if (includesType(withTypes, t5))
          ts.push(t5);
        else if (withTypes.includes("integer") && t5 === "number")
          ts.push("integer");
      }
      it3.dataTypes = ts;
    }
    __name(narrowSchemaTypes, "narrowSchemaTypes");
    function strictTypesError(it3, msg) {
      const schemaPath = it3.schemaEnv.baseId + it3.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it3, msg, it3.opts.strictTypes);
    }
    __name(strictTypesError, "strictTypesError");
    var KeywordCxt = class {
      static {
        __name(this, "KeywordCxt");
      }
      constructor(it3, def2, keyword) {
        (0, keyword_1.validateKeywordUsage)(it3, def2, keyword);
        this.gen = it3.gen;
        this.allErrors = it3.allErrors;
        this.keyword = keyword;
        this.data = it3.data;
        this.schema = it3.schema[keyword];
        this.$data = def2.$data && it3.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it3, this.schema, keyword, this.$data);
        this.schemaType = def2.schemaType;
        this.parentSchema = it3.schema;
        this.params = {};
        this.it = it3;
        this.def = def2;
        if (this.$data) {
          this.schemaCode = it3.gen.const("vSchema", getData(this.$data, it3));
        } 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 = it3.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(append3, errorParams, errorPaths) {
        if (errorParams) {
          this.setParams(errorParams);
          this._error(append3, errorPaths);
          this.setParams({});
          return;
        }
        this._error(append3, errorPaths);
      }
      _error(append3, errorPaths) {
        ;
        (append3 ? 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: it3 } = 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, it3.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: it3, gen } = this;
        if (!it3.opts.unevaluated)
          return;
        if (it3.props !== true && schemaCxt.props !== void 0) {
          it3.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it3.props, toName);
        }
        if (it3.items !== true && schemaCxt.items !== void 0) {
          it3.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it3.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it: it3, gen } = this;
        if (it3.opts.unevaluated && (it3.props !== true || it3.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports2.KeywordCxt = KeywordCxt;
    function keywordCode(it3, keyword, def2, ruleType) {
      const cxt = new KeywordCxt(it3, 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 matches2 = RELATIVE_JSON_POINTER.exec($data);
        if (!matches2)
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches2[1];
        jsonPointer = matches2[2];
        if (jsonPointer === "#") {
          if (up >= dataLevel)
            throw new Error(errorMsg("property/index", up));
          return dataPathArr[dataLevel - up];
        }
        if (up > dataLevel)
          throw new Error(errorMsg("data", up));
        data = dataNames[dataLevel - up];
        if (!jsonPointer)
          return data;
      }
      let expr = data;
      const segments = jsonPointer.split("/");
      for (const segment of segments) {
        if (segment) {
          data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
          expr = (0, codegen_1._)`${expr} && ${data}`;
        }
      }
      return expr;
      function errorMsg(pointerType, up) {
        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
      }
      __name(errorMsg, "errorMsg");
    }
    __name(getData, "getData");
    exports2.getData = getData;
  }
});

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

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

// packages/core/node_modules/ajv/dist/compile/index.js
var require_compile = __commonJS({
  "packages/core/node_modules/ajv/dist/compile/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveSchema = exports2.getCompilingSchema = exports2.resolveRef = exports2.compileSchema = exports2.SchemaEnv = void 0;
    var codegen_1 = require_codegen();
    var validation_error_1 = require_validation_error();
    var names_1 = require_names();
    var resolve_1 = require_resolve();
    var util_1 = require_util9();
    var validate_1 = require_validate();
    var SchemaEnv = class {
      static {
        __name(this, "SchemaEnv");
      }
      constructor(env6) {
        var _a7;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env6.schema == "object")
          schema = env6.schema;
        this.schema = env6.schema;
        this.schemaId = env6.schemaId;
        this.root = env6.root || this;
        this.baseId = (_a7 = env6.baseId) !== null && _a7 !== void 0 ? _a7 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env6.schemaId || "$id"]);
        this.schemaPath = env6.schemaPath;
        this.localRefs = env6.localRefs;
        this.meta = env6.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 = resolve42.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 resolve42(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    __name(resolve42, "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 env6;
      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);
        env6 = resolveSchema.call(this, root, $ref);
      }
      const { schemaId } = this.opts;
      env6 = env6 || new SchemaEnv({ schema, schemaId, root, baseId });
      if (env6.schema !== env6.root.schema)
        return env6;
      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 matches2 = host.match(IPV4_REG) || [];
      const [address] = matches2;
      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 i4 = 0; i4 < input.length; i4++) {
        const cursor = input[i4];
        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 (i4 - 1 >= 0 && input[i4 - 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 ipv63 = getIPV6(host);
      if (!ipv63.error) {
        let newHost = ipv63.address;
        let escapedHost = ipv63.address;
        if (ipv63.zone) {
          newHost += "%" + ipv63.zone;
          escapedHost += "%25" + ipv63.zone;
        }
        return { host: newHost, escapedHost, isIPV6: true };
      } else {
        return { host, isIPV6: false };
      }
    }
    __name(normalizeIPv6, "normalizeIPv6");
    function stripLeadingZeros(str2, token2) {
      let out2 = "";
      let skip = true;
      const l3 = str2.length;
      for (let i4 = 0; i4 < l3; i4++) {
        const c4 = str2[i4];
        if (c4 === "0" && skip) {
          if (i4 + 1 <= l3 && str2[i4 + 1] === token2 || i4 + 1 === l3) {
            out2 += c4;
            skip = false;
          }
        } else {
          if (c4 === token2) {
            skip = true;
          } else {
            skip = false;
          }
          out2 += c4;
        }
      }
      return out2;
    }
    __name(stripLeadingZeros, "stripLeadingZeros");
    function findToken(str2, token2) {
      let ind = 0;
      for (let i4 = 0; i4 < str2.length; i4++) {
        if (str2[i4] === 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 func2 = esc2 !== true ? escape : unescape;
      if (components.scheme !== void 0) {
        components.scheme = func2(components.scheme);
      }
      if (components.userinfo !== void 0) {
        components.userinfo = func2(components.userinfo);
      }
      if (components.host !== void 0) {
        components.host = func2(components.host);
      }
      if (components.path !== void 0) {
        components.path = func2(components.path);
      }
      if (components.query !== void 0) {
        components.query = func2(components.query);
      }
      if (components.fragment !== void 0) {
        components.fragment = func2(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 [path150, query] = wsComponents.resourceName.split("?");
        wsComponents.path = path150 && path150 !== "/" ? path150 : 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 matches2 = urnComponents.path.match(URN_REG);
      if (matches2) {
        const scheme = options2.scheme || urnComponents.scheme || "urn";
        urnComponents.nid = matches2[1].toLowerCase();
        urnComponents.nss = matches2[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 http9 = {
      scheme: "http",
      domainHost: true,
      parse: httpParse,
      serialize: httpSerialize
    };
    var https9 = {
      scheme: "https",
      domainHost: http9.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: http9,
      https: https9,
      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 normalize13(uri, options2) {
      if (typeof uri === "string") {
        uri = serialize2(parse17(uri, options2), options2);
      } else if (typeof uri === "object") {
        uri = parse17(serialize2(uri, options2), options2);
      }
      return uri;
    }
    __name(normalize13, "normalize");
    function resolve42(baseURI, relativeURI, options2) {
      const schemelessOptions = Object.assign({ scheme: "null" }, options2);
      const resolved = resolveComponents(parse17(baseURI, schemelessOptions), parse17(relativeURI, schemelessOptions), schemelessOptions, true);
      return serialize2(resolved, { ...schemelessOptions, skipEscape: true });
    }
    __name(resolve42, "resolve");
    function resolveComponents(base, relative14, options2, skipNormalization) {
      const target = {};
      if (!skipNormalization) {
        base = parse17(serialize2(base, options2), options2);
        relative14 = parse17(serialize2(relative14, options2), options2);
      }
      options2 = options2 || {};
      if (!options2.tolerant && relative14.scheme) {
        target.scheme = relative14.scheme;
        target.userinfo = relative14.userinfo;
        target.host = relative14.host;
        target.port = relative14.port;
        target.path = removeDotSegments(relative14.path || "");
        target.query = relative14.query;
      } else {
        if (relative14.userinfo !== void 0 || relative14.host !== void 0 || relative14.port !== void 0) {
          target.userinfo = relative14.userinfo;
          target.host = relative14.host;
          target.port = relative14.port;
          target.path = removeDotSegments(relative14.path || "");
          target.query = relative14.query;
        } else {
          if (!relative14.path) {
            target.path = base.path;
            if (relative14.query !== void 0) {
              target.query = relative14.query;
            } else {
              target.query = base.query;
            }
          } else {
            if (relative14.path.charAt(0) === "/") {
              target.path = removeDotSegments(relative14.path);
            } else {
              if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
                target.path = "/" + relative14.path;
              } else if (!base.path) {
                target.path = relative14.path;
              } else {
                target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative14.path;
              }
              target.path = removeDotSegments(target.path);
            }
            target.query = relative14.query;
          }
          target.userinfo = base.userinfo;
          target.host = base.host;
          target.port = base.port;
        }
        target.scheme = base.scheme;
      }
      target.fragment = relative14.fragment;
      return target;
    }
    __name(resolveComponents, "resolveComponents");
    function equal(uriA, uriB, options2) {
      if (typeof uriA === "string") {
        uriA = unescape(uriA);
        uriA = serialize2(normalizeComponentEncoding(parse17(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(parse17(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 i4 = 0, len = value.length; i4 < len; ++i4) {
        code2 = value.charCodeAt(i4);
        if (code2 > 126 || hexLookUp[code2]) {
          return true;
        }
      }
      return false;
    }
    __name(nonSimpleDomain, "nonSimpleDomain");
    var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
    function parse17(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 isIP4 = false;
      if (options2.reference === "suffix") uri = (options2.scheme ? options2.scheme + ":" : "") + "//" + uri;
      const matches2 = uri.match(URI_PARSE);
      if (matches2) {
        parsed.scheme = matches2[1];
        parsed.userinfo = matches2[3];
        parsed.host = matches2[4];
        parsed.port = parseInt(matches2[5], 10);
        parsed.path = matches2[6] || "";
        parsed.query = matches2[7];
        parsed.fragment = matches2[8];
        if (isNaN(parsed.port)) {
          parsed.port = matches2[5];
        }
        if (parsed.host) {
          const ipv4result = normalizeIPv4(parsed.host);
          if (ipv4result.isIPV4 === false) {
            const ipv6result = normalizeIPv6(ipv4result.host);
            parsed.host = ipv6result.host.toLowerCase();
            isIP4 = ipv6result.isIPV6;
          } else {
            parsed.host = ipv4result.host;
            isIP4 = 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) && isIP4 === 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(parse17, "parse");
    var fastUri = {
      SCHEMES,
      normalize: normalize13,
      resolve: resolve42,
      resolveComponents,
      equal,
      serialize: serialize2,
      parse: parse17
    };
    module2.exports = fastUri;
    module2.exports.default = fastUri;
    module2.exports.fastUri = fastUri;
  }
});

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

// packages/core/node_modules/ajv/dist/core.js
var require_core = __commonJS({
  "packages/core/node_modules/ajv/dist/core.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = void 0;
    var validate_1 = require_validate();
    Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return validate_1.KeywordCxt;
    }, "get") });
    var codegen_1 = require_codegen();
    Object.defineProperty(exports2, "_", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1._;
    }, "get") });
    Object.defineProperty(exports2, "str", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.str;
    }, "get") });
    Object.defineProperty(exports2, "stringify", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.stringify;
    }, "get") });
    Object.defineProperty(exports2, "nil", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.nil;
    }, "get") });
    Object.defineProperty(exports2, "Name", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.Name;
    }, "get") });
    Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return codegen_1.CodeGen;
    }, "get") });
    var validation_error_1 = require_validation_error();
    var ref_error_1 = require_ref_error();
    var rules_1 = require_rules();
    var compile_1 = require_compile();
    var codegen_2 = require_codegen();
    var resolve_1 = require_resolve();
    var dataType_1 = require_dataType();
    var util_1 = require_util9();
    var $dataRefSchema = require_data();
    var uri_1 = require_uri();
    var defaultRegExp = /* @__PURE__ */ __name((str2, flags2) => new RegExp(str2, flags2), "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 i4 = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i4 >= 0)
            group.rules.splice(i4, 1);
        }
        return this;
      }
      // Add format
      addFormat(name4, format4) {
        if (typeof format4 == "string")
          format4 = new RegExp(format4);
        this.formats[name4] = 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 name4 in this.opts.formats) {
        const format4 = this.opts.formats[name4];
        if (format4)
          this.addFormat(name4, 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 post2 = definition === null || definition === void 0 ? void 0 : definition.post;
      if (dataType && post2)
        throw new Error('keyword with "post" flag cannot have "type"');
      const { RULES } = this;
      let ruleGroup = post2 ? 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 i4 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i4 >= 0) {
        ruleGroup.rules.splice(i4, 0, rule);
      } else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
      }
    }
    __name(addBeforeRule, "addBeforeRule");
    function keywordMetaschema(def2) {
      let { metaSchema } = def2;
      if (metaSchema === void 0)
        return;
      if (def2.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
      def2.validateSchema = this.compile(metaSchema, true);
    }
    __name(keywordMetaschema, "keywordMetaschema");
    var $dataRef = {
      $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
    };
    function schemaOrData(schema) {
      return { anyOf: [schema, $dataRef] };
    }
    __name(schemaOrData, "schemaOrData");
  }
});

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

// packages/core/node_modules/ajv/dist/vocabularies/core/ref.js
var require_ref = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/core/ref.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.callRef = exports2.getValidate = void 0;
    var ref_error_1 = require_ref_error();
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var compile_1 = require_compile();
    var util_1 = require_util9();
    var def2 = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it: it3 } = cxt;
        const { baseId, schemaEnv: env6, validateName: validateName2, opts, self: self2 } = it3;
        const { root } = env6;
        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(it3.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
          return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
          if (env6 === root)
            return callRef(cxt, validateName2, env6, env6.$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: it3 } = cxt;
      const { allErrors, schemaEnv: env6, opts } = it3;
      const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
      if ($async)
        callAsyncRef();
      else
        callSyncRef();
      function callAsyncRef() {
        if (!env6.$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 ${it3.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 (!it3.opts.unevaluated)
          return;
        const schEvaluated = (_a7 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a7 === void 0 ? void 0 : _a7.evaluated;
        if (it3.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it3.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it3.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source2}.evaluated.props`);
            it3.props = util_1.mergeEvaluated.props(gen, props, it3.props, codegen_1.Name);
          }
        }
        if (it3.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it3.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it3.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source2}.evaluated.items`);
            it3.items = util_1.mergeEvaluated.items(gen, items, it3.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 error40 = {
      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: error40,
      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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, data, schemaCode, it: it3 } = cxt;
        const prec = it3.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
      }
    };
    exports2.default = def2;
  }
});

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

// packages/core/node_modules/ajv/dist/vocabularies/validation/limitLength.js
var require_limitLength = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var ucs2length_1 = require_ucs2length();
    var error40 = {
      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: error40,
      code(cxt) {
        const { keyword, data, schemaCode, it: it3 } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it3.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 error40 = {
      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: error40,
      code(cxt) {
        const { data, $data, schema, schemaCode, it: it3 } = cxt;
        const u2 = it3.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 error40 = {
      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: error40,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/required.js
var require_required = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/required.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it: it3 } = cxt;
        const { opts } = it3;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it3.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 = it3.schemaEnv.baseId + it3.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it3, msg, it3.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 error40 = {
      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: error40,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

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

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

// packages/core/node_modules/ajv/dist/vocabularies/validation/enum.js
var require_enum = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var equal_1 = require_equal();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it: it3 } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it3.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, i4) => equalCode(vSchema, i4)));
        }
        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, i4) {
          const sch = schema[i4];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i4}])` : (0, codegen_1._)`${data} === ${sch}`;
        }
        __name(equalCode, "equalCode");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/validation/index.js
var require_validation = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/validation/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var limitNumber_1 = require_limitNumber();
    var multipleOf_1 = require_multipleOf();
    var limitLength_1 = require_limitLength();
    var pattern_1 = require_pattern();
    var limitProperties_1 = require_limitProperties();
    var required_1 = require_required();
    var limitItems_1 = require_limitItems();
    var uniqueItems_1 = require_uniqueItems();
    var const_1 = require_const();
    var enum_1 = require_enum();
    var validation2 = [
      // number
      limitNumber_1.default,
      multipleOf_1.default,
      // string
      limitLength_1.default,
      pattern_1.default,
      // object
      limitProperties_1.default,
      required_1.default,
      // array
      limitItems_1.default,
      uniqueItems_1.default,
      // any
      { keyword: "type", schemaType: ["string", "array"] },
      { keyword: "nullable", schemaType: "boolean" },
      const_1.default,
      enum_1.default
    ];
    exports2.default = validation2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
var require_additionalItems = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateAdditionalItems = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error40 = {
      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: error40,
      code(cxt) {
        const { parentSchema, it: it3 } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
          (0, util_1.checkStrictMode)(it3, '"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: it3 } = cxt;
      it3.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)(it3, 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, (i4) => {
          cxt.subschema({ keyword, dataProp: i4, dataPropType: util_1.Type.Num }, valid);
          if (!it3.allErrors)
            gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
      }
      __name(validateItems, "validateItems");
    }
    __name(validateAdditionalItems, "validateAdditionalItems");
    exports2.validateAdditionalItems = validateAdditionalItems;
    exports2.default = def2;
  }
});

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

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

// packages/core/node_modules/ajv/dist/vocabularies/applicator/items2020.js
var require_items2020 = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var code_1 = require_code2();
    var additionalItems_1 = require_additionalItems();
    var error40 = {
      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: error40,
      code(cxt) {
        const { schema, parentSchema, it: it3 } = cxt;
        const { prefixItems } = parentSchema;
        it3.items = true;
        if ((0, util_1.alwaysValidSchema)(it3, schema))
          return;
        if (prefixItems)
          (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
          cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/contains.js
var require_contains = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it3 } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it3.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)(it3, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it3, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it3, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it3.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, (i4) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i4,
              dataPropType: util_1.Type.Num,
              compositeRule: true
            }, _valid);
            block2();
          });
        }
        __name(validateItems, "validateItems");
        function checkLimits(count) {
          gen.code((0, codegen_1._)`${count}++`);
          if (max === void 0) {
            gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
          } else {
            gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
            if (min === 1)
              gen.assign(valid, true);
            else
              gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
          }
        }
        __name(checkLimits, "checkLimits");
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/dependencies.js
var require_dependencies = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateSchemaDeps = exports2.validatePropertyDeps = exports2.error = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var code_1 = require_code2();
    exports2.error = {
      message: /* @__PURE__ */ __name(({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
      }, "message"),
      params: /* @__PURE__ */ __name(({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, "params")
      // TODO change to reference
    };
    var def2 = {
      keyword: "dependencies",
      type: "object",
      schemaType: "object",
      error: exports2.error,
      code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
      }
    };
    function splitDependencies({ schema }) {
      const propertyDeps = {};
      const schemaDeps = {};
      for (const key in schema) {
        if (key === "__proto__")
          continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
      }
      return [propertyDeps, schemaDeps];
    }
    __name(splitDependencies, "splitDependencies");
    function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
      const { gen, data, it: it3 } = 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, it3.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it3.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: it3 } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it3, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it3.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
          },
          () => gen.var(valid, true)
          // TODO var
        );
        cxt.ok(valid);
      }
    }
    __name(validateSchemaDeps, "validateSchemaDeps");
    exports2.validateSchemaDeps = validateSchemaDeps;
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
var require_propertyNames = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, data, it: it3 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it3, 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 (!it3.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
var require_additionalProperties = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var util_1 = require_util9();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it: it3 } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it3;
        it3.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it3, 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)(it3, 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)(it3, schema)) {
            const valid = gen.name("valid");
            if (opts.removeAdditional === "failing") {
              applyAdditionalSchema(key, valid, false);
              gen.if((0, codegen_1.not)(valid), () => {
                cxt.reset();
                deleteAdditional(key);
              });
            } else {
              applyAdditionalSchema(key, valid);
              if (!allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          }
        }
        __name(additionalPropertyCode, "additionalPropertyCode");
        function applyAdditionalSchema(key, valid, errors) {
          const subschema = {
            keyword: "additionalProperties",
            dataProp: key,
            dataPropType: util_1.Type.Str
          };
          if (errors === false) {
            Object.assign(subschema, {
              compositeRule: true,
              createErrors: false,
              allErrors: false
            });
          }
          cxt.subschema(subschema, valid);
        }
        __name(applyAdditionalSchema, "applyAdditionalSchema");
      }
    };
    exports2.default = def2;
  }
});

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

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

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

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

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

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

// packages/core/node_modules/ajv/dist/vocabularies/applicator/if.js
var require_if = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util9();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, parentSchema, it: it3 } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it3, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it3, "then");
        const hasElse = hasSchema(it3, "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(it3, keyword) {
      const schema = it3.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it3, schema);
    }
    __name(hasSchema, "hasSchema");
    exports2.default = def2;
  }
});

// packages/core/node_modules/ajv/dist/vocabularies/applicator/thenElse.js
var require_thenElse = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util9();
    var def2 = {
      keyword: ["then", "else"],
      schemaType: ["object", "boolean"],
      code({ keyword, parentSchema, it: it3 }) {
        if (parentSchema.if === void 0)
          (0, util_1.checkStrictMode)(it3, `"${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 error40 = {
      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: error40,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it: it3 } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it3;
        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_validation();
    var applicator_1 = require_applicator();
    var format_1 = require_format2();
    var metadata_1 = require_metadata();
    var draft7Vocabularies = [
      core_1.default,
      validation_1.default,
      (0, applicator_1.default)(),
      format_1.default,
      metadata_1.metadataVocabulary,
      metadata_1.contentVocabulary
    ];
    exports2.default = draft7Vocabularies;
  }
});

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

// packages/core/node_modules/ajv/dist/vocabularies/discriminator/index.js
var require_discriminator = __commonJS({
  "packages/core/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var types_1 = require_types();
    var compile_1 = require_compile();
    var ref_error_1 = require_ref_error();
    var util_1 = require_util9();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, data, schema, parentSchema, it: it3 } = cxt;
        const { oneOf } = parentSchema;
        if (!it3.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 i4 = 0; i4 < oneOf.length; i4++) {
            let sch = oneOf[i4];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it3.self.RULES)) {
              const ref = sch.$ref;
              sch = compile_1.resolveRef.call(it3.self, it3.schemaEnv.root, it3.baseId, ref);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it3.opts.uriResolver, it3.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, i4);
          }
          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, i4) {
            if (sch.const) {
              addMapping(sch.const, i4);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i4);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          __name(addMappings, "addMappings");
          function addMapping(tagValue, i4) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i4;
          }
          __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: it3 } = cxt;
      it3.schemaEnv.root.dynamicAnchors[anchor] = true;
      const v2 = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`;
      const validate3 = it3.errSchemaPath === "#" ? it3.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: it3 } = cxt;
      if (ref[0] !== "#")
        throw new Error(`"${keyword}" only supports hash fragment reference`);
      const anchor = ref.slice(1);
      if (it3.allErrors) {
        _dynamicRef();
      } else {
        const valid = gen.let("valid", false);
        _dynamicRef(valid);
        cxt.ok(valid);
      }
      function _dynamicRef(valid) {
        if (it3.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(it3.validateName, valid));
        } else {
          _callRef(it3.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_util9();
    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_util9();
    var def2 = {
      keyword: ["maxContains", "minContains"],
      type: "array",
      schemaType: "number",
      code({ keyword, parentSchema, it: it3 }) {
        if (parentSchema.contains === void 0) {
          (0, util_1.checkStrictMode)(it3, `"${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_util9();
    var names_1 = require_names();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, data, errsCount, it: it3 } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, props } = it3;
        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)));
        }
        it3.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)(it3, 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_util9();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, data, it: it3 } = cxt;
        const items = it3.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)(it3, schema)) {
          const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`);
          gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items));
          cxt.ok(valid);
        }
        it3.items = true;
        function validateItems(valid, from) {
          gen.forRange("i", from, len, (i4) => {
            cxt.subschema({ keyword: "unevaluatedItems", dataProp: i4, dataPropType: util_1.Type.Num }, valid);
            if (!it3.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_validation();
    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_validation2 = __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 metadata2 = require_meta_data();
    var validation2 = require_validation2();
    var META_SUPPORT_DATA = ["/properties"];
    function addMetaSchema2020($data) {
      ;
      [
        metaSchema,
        applicator,
        unevaluated,
        content,
        core,
        with$data(this, format4),
        metadata2,
        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(date5, 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 date5(str2) {
      const matches2 = DATE.exec(str2);
      if (!matches2)
        return false;
      const year = +matches2[1];
      const month = +matches2[2];
      const day = +matches2[3];
      return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
    }
    __name(date5, "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 matches2 = TIME.exec(str2);
        if (!matches2)
          return false;
        const hr3 = +matches2[1];
        const min = +matches2[2];
        const sec = +matches2[3];
        const tz = matches2[4];
        const tzSign = matches2[5] === "-" ? -1 : 1;
        const tzH = +(matches2[6] || 0);
        const tzM = +(matches2[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 && date5(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, ...args2) {
      const code2 = [strs[0]];
      let i4 = 0;
      while (i4 < args2.length) {
        addCodeArg(code2, args2[i4]);
        code2.push(strs[++i4]);
      }
      return new _Code(code2);
    }
    __name(_2, "_");
    exports2._ = _2;
    var plus = new _Code("+");
    function str2(strs, ...args2) {
      const expr = [safeStringify(strs[0])];
      let i4 = 0;
      while (i4 < args2.length) {
        expr.push(plus);
        addCodeArg(expr, args2[i4]);
        expr.push(plus, safeStringify(strs[++i4]));
      }
      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 i4 = 1;
      while (i4 < expr.length - 1) {
        if (expr[i4] === plus) {
          const res = mergeExprItems(expr[i4 - 1], expr[i4 + 1]);
          if (res !== void 0) {
            expr.splice(i4 - 1, 3, res);
            continue;
          }
          expr[i4++] = "+";
        }
        i4++;
      }
    }
    __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(name4) {
        super(`CodeGen: "code" for ${name4} not defined`);
        this.value = name4.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 name4 = this.toName(nameOrPrefix);
        const { prefix } = name4;
        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, name4);
        const s5 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s5.length;
        s5[itemIndex] = value.ref;
        name4.setValue(value, { property: prefix, itemIndex });
        return name4;
      }
      getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
          return;
        return vs.get(keyOrRef);
      }
      scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name4) => {
          if (name4.scopePath === void 0)
            throw new Error(`CodeGen: name "${name4}" has no value`);
          return (0, code_1._)`${scopeName}${name4.scopePath}`;
        });
      }
      scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name4) => {
          if (name4.value === void 0)
            throw new Error(`CodeGen: name "${name4}" has no value`);
          return name4.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((name4) => {
            if (nameSet.has(name4))
              return;
            nameSet.set(name4, UsedValueState.Started);
            let c4 = valueCode(name4);
            if (c4) {
              const def2 = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const;
              code2 = (0, code_1._)`${code2}${def2} ${name4} = ${c4};${this.opts._n}`;
            } else if (c4 = getCode === null || getCode === void 0 ? void 0 : getCode(name4)) {
              code2 = (0, code_1._)`${code2}${c4}${this.opts._n}`;
            } else {
              throw new ValueError(name4);
            }
            nameSet.set(name4, 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, name4, rhs) {
        super();
        this.varKind = varKind;
        this.name = name4;
        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, constants5) {
        if (!names[this.name.str])
          return;
        if (this.rhs)
          this.rhs = optimizeExpr(this.rhs, names, constants5);
        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, constants5) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
          return;
        this.rhs = optimizeExpr(this.rhs, names, constants5);
        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(error40) {
        super();
        this.error = error40;
      }
      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, constants5) {
        this.code = optimizeExpr(this.code, names, constants5);
        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 i4 = nodes.length;
        while (i4--) {
          const n3 = nodes[i4].optimizeNodes();
          if (Array.isArray(n3))
            nodes.splice(i4, 1, ...n3);
          else if (n3)
            nodes[i4] = n3;
          else
            nodes.splice(i4, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants5) {
        const { nodes } = this;
        let i4 = nodes.length;
        while (i4--) {
          const n3 = nodes[i4];
          if (n3.optimizeNames(names, constants5))
            continue;
          subtractNames(names, n3.names);
          nodes.splice(i4, 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, constants5) {
        var _a7;
        this.else = (_a7 = this.else) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names, constants5);
        if (!(super.optimizeNames(names, constants5) || this.else))
          return;
        this.condition = optimizeExpr(this.condition, names, constants5);
        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, constants5) {
        if (!super.optimizeNames(names, constants5))
          return;
        this.iteration = optimizeExpr(this.iteration, names, constants5);
        return this;
      }
      get names() {
        return addNames(super.names, this.iteration.names);
      }
    };
    var ForRange = class extends For {
      static {
        __name(this, "ForRange");
      }
      constructor(varKind, name4, from, to) {
        super();
        this.varKind = varKind;
        this.name = name4;
        this.from = from;
        this.to = to;
      }
      render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name: name4, from, to } = this;
        return `for(${varKind} ${name4}=${from}; ${name4}<${to}; ${name4}++)` + 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, name4, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name4;
        this.iterable = iterable;
      }
      render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
      }
      optimizeNames(names, constants5) {
        if (!super.optimizeNames(names, constants5))
          return;
        this.iterable = optimizeExpr(this.iterable, names, constants5);
        return this;
      }
      get names() {
        return addNames(super.names, this.iterable.names);
      }
    };
    var Func = class extends BlockNode {
      static {
        __name(this, "Func");
      }
      constructor(name4, args2, async) {
        super();
        this.name = name4;
        this.args = args2;
        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, constants5) {
        var _a7, _b2;
        super.optimizeNames(names, constants5);
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names, constants5);
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNames(names, constants5);
        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(error40) {
        super();
        this.error = error40;
      }
      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 name4 = this._extScope.value(prefixOrName, value);
        const vs = this._values[name4.prefix] || (this._values[name4.prefix] = /* @__PURE__ */ new Set());
        vs.add(name4);
        return name4;
      }
      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 name4 = this._scope.toName(nameOrPrefix);
        if (rhs !== void 0 && constant)
          this._constants[name4.str] = rhs;
        this._leafNode(new Def(varKind, name4, rhs));
        return name4;
      }
      // `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 name4 = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name4, from, to), () => forBody(name4));
      }
      // `for-of` statement (in es5 mode replace with a normal for loop)
      forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name4 = 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`, (i4) => {
            this.var(name4, (0, code_1._)`${arr}[${i4}]`);
            forBody(name4);
          });
        }
        return this._for(new ForIter("of", varKind, name4, iterable), () => forBody(name4));
      }
      // `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 name4 = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name4, obj), () => forBody(name4));
      }
      // 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 error40 = this.name("e");
          this._currNode = node.catch = new Catch(error40);
          catchCode(error40);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error40) {
        return this._leafNode(new Throw(error40));
      }
      // start self-balancing block
      block(body2, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body2)
          this.code(body2).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(name4, args2 = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name4, args2, 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, constants5) {
      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 = constants5[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 && constants5[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(...args2) {
      return args2.reduce(andCode);
    }
    __name(and, "and");
    exports2.and = and;
    var orCode = mappend(exports2.operators.OR);
    function or2(...args2) {
      return args2.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_util10 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.checkStrictMode = exports2.getErrorPath = exports2.Type = exports2.useFunc = exports2.setEvaluated = exports2.evaluatedPropsToName = exports2.mergeEvaluated = exports2.eachItem = exports2.unescapeJsonPointer = exports2.escapeJsonPointer = exports2.escapeFragment = exports2.unescapeFragment = exports2.schemaRefOrVal = exports2.schemaHasRulesButRef = exports2.schemaHasRules = exports2.checkUnknownRules = exports2.alwaysValidSchema = exports2.toHash = void 0;
    var codegen_1 = require_codegen2();
    var code_1 = require_code3();
    function toHash(arr) {
      const hash = {};
      for (const item of arr)
        hash[item] = true;
      return hash;
    }
    __name(toHash, "toHash");
    exports2.toHash = toHash;
    function alwaysValidSchema(it3, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it3, schema);
      return !schemaHasRules(schema, it3.self.RULES.all);
    }
    __name(alwaysValidSchema, "alwaysValidSchema");
    exports2.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it3, schema = it3.schema) {
      const { opts, self: self2 } = it3;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules[key])
          checkStrictMode(it3, `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 isNumber4 = dataPropType === Type3.Num;
        return jsPropertySyntax ? isNumber4 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber4 ? (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(it3, msg, mode = it3.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it3.self.logger.warn(msg);
    }
    __name(checkStrictMode, "checkStrictMode");
    exports2.checkStrictMode = checkStrictMode;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js
var require_names2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var names = {
      // validation function arguments
      data: new codegen_1.Name("data"),
      // data passed to validation function
      // args passed from referencing schema
      valCxt: new codegen_1.Name("valCxt"),
      // validation/data context - should not be used directly, it is destructured to the names below
      instancePath: new codegen_1.Name("instancePath"),
      parentData: new codegen_1.Name("parentData"),
      parentDataProperty: new codegen_1.Name("parentDataProperty"),
      rootData: new codegen_1.Name("rootData"),
      // root data - same as the data passed to the first/top validation function
      dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
      // used to support recursiveRef and dynamicRef
      // function scoped variables
      vErrors: new codegen_1.Name("vErrors"),
      // null or array of validation errors
      errors: new codegen_1.Name("errors"),
      // counter of validation errors
      this: new codegen_1.Name("this"),
      // "globals"
      self: new codegen_1.Name("self"),
      scope: new codegen_1.Name("scope"),
      // JTD serialize/parse name for JSON string and position
      json: new codegen_1.Name("json"),
      jsonPos: new codegen_1.Name("jsonPos"),
      jsonLen: new codegen_1.Name("jsonLen"),
      jsonPart: new codegen_1.Name("jsonPart")
    };
    exports2.default = names;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js
var require_errors3 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.extendErrors = exports2.resetErrorsCount = exports2.reportExtraError = exports2.reportError = exports2.keyword$DataError = exports2.keywordError = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var names_1 = require_names2();
    exports2.keywordError = {
      message: /* @__PURE__ */ __name(({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`, "message")
    };
    exports2.keyword$DataError = {
      message: /* @__PURE__ */ __name(({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`, "message")
    };
    function reportError3(cxt, error40 = exports2.keywordError, errorPaths, overrideAllErrors) {
      const { it: it3 } = cxt;
      const { gen, compositeRule, allErrors } = it3;
      const errObj = errorObjectCode(cxt, error40, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it3, (0, codegen_1._)`[${errObj}]`);
      }
    }
    __name(reportError3, "reportError");
    exports2.reportError = reportError3;
    function reportExtraError(cxt, error40 = exports2.keywordError, errorPaths) {
      const { it: it3 } = cxt;
      const { gen, compositeRule, allErrors } = it3;
      const errObj = errorObjectCode(cxt, error40, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it3, 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: it3 }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err2 = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i4) => {
        gen.const(err2, (0, codegen_1._)`${names_1.default.vErrors}[${i4}]`);
        gen.if((0, codegen_1._)`${err2}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err2}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it3.errorPath)));
        gen.assign((0, codegen_1._)`${err2}.schemaPath`, (0, codegen_1.str)`${it3.errSchemaPath}/${keyword}`);
        if (it3.opts.verbose) {
          gen.assign((0, codegen_1._)`${err2}.schema`, schemaValue);
          gen.assign((0, codegen_1._)`${err2}.data`, data);
        }
      });
    }
    __name(extendErrors, "extendErrors");
    exports2.extendErrors = extendErrors;
    function addError(gen, errObj) {
      const err2 = gen.const("err", errObj);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err2}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err2})`);
      gen.code((0, codegen_1._)`${names_1.default.errors}++`);
    }
    __name(addError, "addError");
    function returnErrors(it3, errs) {
      const { gen, validateName: validateName2, schemaEnv } = it3;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it3.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, error40, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error40, errorPaths);
    }
    __name(errorObjectCode, "errorObjectCode");
    function errorObject(cxt, error40, errorPaths = {}) {
      const { gen, it: it3 } = cxt;
      const keyValues = [
        errorInstancePath(it3, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error40, 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: it3 } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it3;
      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(it3) {
      const { gen, schema, validateName: validateName2 } = it3;
      if (schema === false) {
        falseSchemaError(it3, 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(it3, valid) {
      const { gen, schema } = it3;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it3);
      } else {
        gen.var(valid, true);
      }
    }
    __name(boolOrEmptySchema, "boolOrEmptySchema");
    exports2.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it3, overrideAllErrors) {
      const { gen, data } = it3;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it: it3
      };
      (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_util10();
    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(it3, types7) {
      const { gen, data, opts } = it3;
      const coerceTo = coerceToTypes(types7, opts.coerceTypes);
      const checkTypes = types7.length > 0 && !(coerceTo.length === 0 && types7.length === 1 && (0, applicability_1.schemaHasRulesForType)(it3, types7[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types7, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it3, types7, coerceTo);
          else
            reportTypeError(it3);
        });
      }
      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(it3, types7, coerceTo) {
      const { gen, data, opts } = it3;
      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(it3);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it3, 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(it3) {
      const cxt = getTypeErrorContext(it3);
      (0, errors_1.reportError)(cxt, typeError);
    }
    __name(reportTypeError, "reportTypeError");
    exports2.reportTypeError = reportTypeError;
    function getTypeErrorContext(it3) {
      const { gen, data, schema } = it3;
      const schemaCode = (0, util_1.schemaRefOrVal)(it3, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it: it3
      };
    }
    __name(getTypeErrorContext, "getTypeErrorContext");
  }
});

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

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js
var require_code4 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateUnion = exports2.validateArray = exports2.usePattern = exports2.callValidateCode = exports2.schemaProperties = exports2.allSchemaProperties = exports2.noPropertyInData = exports2.propertyInData = exports2.isOwnProperty = exports2.hasPropFunc = exports2.reportMissingProp = exports2.checkMissingProp = exports2.checkReportMissingProp = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var names_1 = require_names2();
    var util_2 = require_util10();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it: it3 } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it3.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(it3, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it3, schemaMap[p2]));
    }
    __name(schemaProperties, "schemaProperties");
    exports2.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it: it3 }, func2, 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, it3.parentData],
        [names_1.default.parentDataProperty, it3.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it3.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args2 = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return context2 !== codegen_1.nil ? (0, codegen_1._)`${func2}.call(${context2}, ${args2})` : (0, codegen_1._)`${func2}(${args2})`;
    }
    __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: it3 } = cxt;
      const valid = gen.name("valid");
      if (it3.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, (i4) => {
          cxt.subschema({
            keyword,
            dataProp: i4,
            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: it3 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it3, sch));
      if (alwaysValid && !it3.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i4) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i4,
          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: it3 } = cxt;
      const macroSchema = def2.macro.call(it3.self, schema, parentSchema, it3);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it3.opts.validateSchema !== false)
        it3.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it3.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: it3 } = cxt;
      checkAsyncKeyword(it3, def2);
      const validate3 = !$data && def2.compile ? def2.compile.call(it3.self, schema, parentSchema, it3) : 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 ${it3.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 = it3.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: it3 } = cxt;
      gen.if(it3.parentData, () => gen.assign(data, (0, codegen_1._)`${it3.parentData}[${it3.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_util10();
    function getSubschema(it3, { 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 = it3.schema[keyword];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it3.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
          errSchemaPath: `${it3.errSchemaPath}/${keyword}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it3.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it3.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, it3, { 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 } = it3;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it3;
        const nextData = gen.let("data", (0, codegen_1._)`${it3.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 = it3.dataLevel + 1;
        subschema.dataTypes = [];
        it3.definedProperties = /* @__PURE__ */ new Set();
        subschema.parentData = it3.data;
        subschema.dataNames = [...it3.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 post2 = cb.post || function() {
      };
      _traverse(opts, pre, post2, 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, post2, 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 i4 = 0; i4 < sch.length; i4++)
                _traverse(opts, pre, post2, sch[i4], jsonPtr + "/" + key + "/" + i4, rootSchema, jsonPtr, key, schema, i4);
            }
          } else if (key in traverse.propsKeywords) {
            if (sch && typeof sch == "object") {
              for (var prop in sch)
                _traverse(opts, pre, post2, 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, post2, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
          }
        }
        post2(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
      }
    }
    __name(_traverse, "_traverse");
    function escapeJsonPtr(str2) {
      return str2.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    __name(escapeJsonPtr, "escapeJsonPtr");
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js
var require_resolve2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getSchemaRefs = exports2.resolveUrl = exports2.normalizeId = exports2._getFullPath = exports2.getFullPath = exports2.inlineRef = void 0;
    var util_1 = require_util10();
    var equal = require_fast_deep_equal();
    var traverse = require_json_schema_traverse2();
    var SIMPLE_INLINED = /* @__PURE__ */ new Set([
      "type",
      "format",
      "pattern",
      "maxLength",
      "minLength",
      "maxProperties",
      "minProperties",
      "maxItems",
      "minItems",
      "maximum",
      "minimum",
      "uniqueItems",
      "multipleOf",
      "required",
      "enum",
      "const"
    ]);
    function inlineRef(schema, limit2 = true) {
      if (typeof schema == "boolean")
        return true;
      if (limit2 === true)
        return !hasRef(schema);
      if (!limit2)
        return false;
      return countKeys(schema) <= limit2;
    }
    __name(inlineRef, "inlineRef");
    exports2.inlineRef = inlineRef;
    var REF_KEYWORDS = /* @__PURE__ */ new Set([
      "$ref",
      "$recursiveRef",
      "$recursiveAnchor",
      "$dynamicRef",
      "$dynamicAnchor"
    ]);
    function hasRef(schema) {
      for (const key in schema) {
        if (REF_KEYWORDS.has(key))
          return true;
        const sch = schema[key];
        if (Array.isArray(sch) && sch.some(hasRef))
          return true;
        if (typeof sch == "object" && hasRef(sch))
          return true;
      }
      return false;
    }
    __name(hasRef, "hasRef");
    function countKeys(schema) {
      let count = 0;
      for (const key in schema) {
        if (key === "$ref")
          return Infinity;
        count++;
        if (SIMPLE_INLINED.has(key))
          continue;
        if (typeof schema[key] == "object") {
          (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
        }
        if (count === Infinity)
          return Infinity;
      }
      return count;
    }
    __name(countKeys, "countKeys");
    function getFullPath(resolver, id = "", normalize13) {
      if (normalize13 !== 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_util10();
    var errors_1 = require_errors3();
    function validateFunctionCode(it3) {
      if (isSchemaObj(it3)) {
        checkKeywords(it3);
        if (schemaCxtHasRules(it3)) {
          topSchemaObjCode(it3);
          return;
        }
      }
      validateFunction(it3, () => (0, boolSchema_1.topBoolOrEmptySchema)(it3));
    }
    __name(validateFunctionCode, "validateFunctionCode");
    exports2.validateFunctionCode = validateFunctionCode;
    function validateFunction({ gen, validateName: validateName2, schema, schemaEnv, opts }, body2) {
      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(body2);
        });
      } else {
        gen.func(validateName2, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body2));
      }
    }
    __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(it3) {
      const { schema, opts, gen } = it3;
      validateFunction(it3, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it3);
        checkNoDefault(it3);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it3);
        typeAndKeywords(it3);
        returnResults(it3);
      });
      return;
    }
    __name(topSchemaObjCode, "topSchemaObjCode");
    function resetEvaluated(it3) {
      const { gen, validateName: validateName2 } = it3;
      it3.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName2}.evaluated`);
      gen.if((0, codegen_1._)`${it3.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it3.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it3.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it3.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(it3, valid) {
      if (isSchemaObj(it3)) {
        checkKeywords(it3);
        if (schemaCxtHasRules(it3)) {
          subSchemaObjCode(it3, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it3, 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(it3) {
      return typeof it3.schema != "boolean";
    }
    __name(isSchemaObj, "isSchemaObj");
    function subSchemaObjCode(it3, valid) {
      const { schema, gen, opts } = it3;
      if (opts.$comment && schema.$comment)
        commentKeyword(it3);
      updateContext(it3);
      checkAsyncSchema(it3);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it3, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    __name(subSchemaObjCode, "subSchemaObjCode");
    function checkKeywords(it3) {
      (0, util_1.checkUnknownRules)(it3);
      checkRefsAndKeywords(it3);
    }
    __name(checkKeywords, "checkKeywords");
    function typeAndKeywords(it3, errsCount) {
      if (it3.opts.jtd)
        return schemaKeywords(it3, [], false, errsCount);
      const types7 = (0, dataType_1.getSchemaTypes)(it3.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it3, types7);
      schemaKeywords(it3, types7, !checkedTypes, errsCount);
    }
    __name(typeAndKeywords, "typeAndKeywords");
    function checkRefsAndKeywords(it3) {
      const { schema, errSchemaPath, opts, self: self2 } = it3;
      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(it3) {
      const { schema, opts } = it3;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it3, "default is ignored in the schema root");
      }
    }
    __name(checkNoDefault, "checkNoDefault");
    function updateContext(it3) {
      const schId = it3.schema[it3.opts.schemaId];
      if (schId)
        it3.baseId = (0, resolve_1.resolveUrl)(it3.opts.uriResolver, it3.baseId, schId);
    }
    __name(updateContext, "updateContext");
    function checkAsyncSchema(it3) {
      if (it3.schema.$async && !it3.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(it3) {
      const { gen, schemaEnv, validateName: validateName2, ValidationError, opts } = it3;
      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(it3);
        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(it3, types7, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it3;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it3, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it3, 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(it3, group);
          if (types7.length === 1 && types7[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it3);
          }
          gen.endIf();
        } else {
          iterateKeywords(it3, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
      __name(groupKeywords, "groupKeywords");
    }
    __name(schemaKeywords, "schemaKeywords");
    function iterateKeywords(it3, group) {
      const { gen, schema, opts: { useDefaults } } = it3;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it3, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it3, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    __name(iterateKeywords, "iterateKeywords");
    function checkStrictTypes(it3, types7) {
      if (it3.schemaEnv.meta || !it3.opts.strictTypes)
        return;
      checkContextTypes(it3, types7);
      if (!it3.opts.allowUnionTypes)
        checkMultipleTypes(it3, types7);
      checkKeywordTypes(it3, it3.dataTypes);
    }
    __name(checkStrictTypes, "checkStrictTypes");
    function checkContextTypes(it3, types7) {
      if (!types7.length)
        return;
      if (!it3.dataTypes.length) {
        it3.dataTypes = types7;
        return;
      }
      types7.forEach((t5) => {
        if (!includesType(it3.dataTypes, t5)) {
          strictTypesError(it3, `type "${t5}" not allowed by context "${it3.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it3, types7);
    }
    __name(checkContextTypes, "checkContextTypes");
    function checkMultipleTypes(it3, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it3, "use allowUnionTypes to allow union type keyword");
      }
    }
    __name(checkMultipleTypes, "checkMultipleTypes");
    function checkKeywordTypes(it3, ts) {
      const rules = it3.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it3.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t5) => hasApplicableType(ts, t5))) {
            strictTypesError(it3, `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(it3, withTypes) {
      const ts = [];
      for (const t5 of it3.dataTypes) {
        if (includesType(withTypes, t5))
          ts.push(t5);
        else if (withTypes.includes("integer") && t5 === "number")
          ts.push("integer");
      }
      it3.dataTypes = ts;
    }
    __name(narrowSchemaTypes, "narrowSchemaTypes");
    function strictTypesError(it3, msg) {
      const schemaPath = it3.schemaEnv.baseId + it3.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it3, msg, it3.opts.strictTypes);
    }
    __name(strictTypesError, "strictTypesError");
    var KeywordCxt = class {
      static {
        __name(this, "KeywordCxt");
      }
      constructor(it3, def2, keyword) {
        (0, keyword_1.validateKeywordUsage)(it3, def2, keyword);
        this.gen = it3.gen;
        this.allErrors = it3.allErrors;
        this.keyword = keyword;
        this.data = it3.data;
        this.schema = it3.schema[keyword];
        this.$data = def2.$data && it3.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it3, this.schema, keyword, this.$data);
        this.schemaType = def2.schemaType;
        this.parentSchema = it3.schema;
        this.params = {};
        this.it = it3;
        this.def = def2;
        if (this.$data) {
          this.schemaCode = it3.gen.const("vSchema", getData(this.$data, it3));
        } 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 = it3.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(append3, errorParams, errorPaths) {
        if (errorParams) {
          this.setParams(errorParams);
          this._error(append3, errorPaths);
          this.setParams({});
          return;
        }
        this._error(append3, errorPaths);
      }
      _error(append3, errorPaths) {
        ;
        (append3 ? 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: it3 } = 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, it3.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: it3, gen } = this;
        if (!it3.opts.unevaluated)
          return;
        if (it3.props !== true && schemaCxt.props !== void 0) {
          it3.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it3.props, toName);
        }
        if (it3.items !== true && schemaCxt.items !== void 0) {
          it3.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it3.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it: it3, gen } = this;
        if (it3.opts.unevaluated && (it3.props !== true || it3.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports2.KeywordCxt = KeywordCxt;
    function keywordCode(it3, keyword, def2, ruleType) {
      const cxt = new KeywordCxt(it3, 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 matches2 = RELATIVE_JSON_POINTER.exec($data);
        if (!matches2)
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches2[1];
        jsonPointer = matches2[2];
        if (jsonPointer === "#") {
          if (up >= dataLevel)
            throw new Error(errorMsg("property/index", up));
          return dataPathArr[dataLevel - up];
        }
        if (up > dataLevel)
          throw new Error(errorMsg("data", up));
        data = dataNames[dataLevel - up];
        if (!jsonPointer)
          return data;
      }
      let expr = data;
      const segments = jsonPointer.split("/");
      for (const segment of segments) {
        if (segment) {
          data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
          expr = (0, codegen_1._)`${expr} && ${data}`;
        }
      }
      return expr;
      function errorMsg(pointerType, up) {
        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
      }
      __name(errorMsg, "errorMsg");
    }
    __name(getData, "getData");
    exports2.getData = getData;
  }
});

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

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

// node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js
var require_compile2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.resolveSchema = exports2.getCompilingSchema = exports2.resolveRef = exports2.compileSchema = exports2.SchemaEnv = void 0;
    var codegen_1 = require_codegen2();
    var validation_error_1 = require_validation_error2();
    var names_1 = require_names2();
    var resolve_1 = require_resolve2();
    var util_1 = require_util10();
    var validate_1 = require_validate2();
    var SchemaEnv = class {
      static {
        __name(this, "SchemaEnv");
      }
      constructor(env6) {
        var _a7;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env6.schema == "object")
          schema = env6.schema;
        this.schema = env6.schema;
        this.schemaId = env6.schemaId;
        this.root = env6.root || this;
        this.baseId = (_a7 = env6.baseId) !== null && _a7 !== void 0 ? _a7 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env6.schemaId || "$id"]);
        this.schemaPath = env6.schemaPath;
        this.localRefs = env6.localRefs;
        this.meta = env6.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 = resolve42.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 resolve42(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    __name(resolve42, "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 env6;
      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);
        env6 = resolveSchema.call(this, root, $ref);
      }
      const { schemaId } = this.opts;
      env6 = env6 || new SchemaEnv({ schema, schemaId, root, baseId });
      if (env6.schema !== env6.root.schema)
        return env6;
      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_util10();
    var $dataRefSchema = require_data2();
    var uri_1 = require_uri2();
    var defaultRegExp = /* @__PURE__ */ __name((str2, flags2) => new RegExp(str2, flags2), "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 i4 = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i4 >= 0)
            group.rules.splice(i4, 1);
        }
        return this;
      }
      // Add format
      addFormat(name4, format4) {
        if (typeof format4 == "string")
          format4 = new RegExp(format4);
        this.formats[name4] = 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 name4 in this.opts.formats) {
        const format4 = this.opts.formats[name4];
        if (format4)
          this.addFormat(name4, 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 post2 = definition === null || definition === void 0 ? void 0 : definition.post;
      if (dataType && post2)
        throw new Error('keyword with "post" flag cannot have "type"');
      const { RULES } = this;
      let ruleGroup = post2 ? 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 i4 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i4 >= 0) {
        ruleGroup.rules.splice(i4, 0, rule);
      } else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
      }
    }
    __name(addBeforeRule, "addBeforeRule");
    function keywordMetaschema(def2) {
      let { metaSchema } = def2;
      if (metaSchema === void 0)
        return;
      if (def2.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
      def2.validateSchema = this.compile(metaSchema, true);
    }
    __name(keywordMetaschema, "keywordMetaschema");
    var $dataRef = {
      $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
    };
    function schemaOrData(schema) {
      return { anyOf: [schema, $dataRef] };
    }
    __name(schemaOrData, "schemaOrData");
  }
});

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

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js
var require_ref2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.callRef = exports2.getValidate = void 0;
    var ref_error_1 = require_ref_error2();
    var code_1 = require_code4();
    var codegen_1 = require_codegen2();
    var names_1 = require_names2();
    var compile_1 = require_compile2();
    var util_1 = require_util10();
    var def2 = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it: it3 } = cxt;
        const { baseId, schemaEnv: env6, validateName: validateName2, opts, self: self2 } = it3;
        const { root } = env6;
        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(it3.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
          return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
          if (env6 === root)
            return callRef(cxt, validateName2, env6, env6.$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: it3 } = cxt;
      const { allErrors, schemaEnv: env6, opts } = it3;
      const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
      if ($async)
        callAsyncRef();
      else
        callSyncRef();
      function callAsyncRef() {
        if (!env6.$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 ${it3.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 (!it3.opts.unevaluated)
          return;
        const schEvaluated = (_a7 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a7 === void 0 ? void 0 : _a7.evaluated;
        if (it3.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it3.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it3.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source2}.evaluated.props`);
            it3.props = util_1.mergeEvaluated.props(gen, props, it3.props, codegen_1.Name);
          }
        }
        if (it3.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it3.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it3.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source2}.evaluated.items`);
            it3.items = util_1.mergeEvaluated.items(gen, items, it3.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 error40 = {
      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: error40,
      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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, data, schemaCode, it: it3 } = cxt;
        const prec = it3.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
      }
    };
    exports2.default = def2;
  }
});

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

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js
var require_limitLength2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var ucs2length_1 = require_ucs2length2();
    var error40 = {
      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: error40,
      code(cxt) {
        const { keyword, data, schemaCode, it: it3 } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it3.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 error40 = {
      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: error40,
      code(cxt) {
        const { data, $data, schema, schemaCode, it: it3 } = cxt;
        const u2 = it3.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 error40 = {
      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: error40,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js
var require_required2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code4();
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it: it3 } = cxt;
        const { opts } = it3;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it3.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 = it3.schemaEnv.baseId + it3.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it3, msg, it3.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 error40 = {
      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: error40,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);
      }
    };
    exports2.default = def2;
  }
});

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

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

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js
var require_enum2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var equal_1 = require_equal2();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it: it3 } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it3.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, i4) => equalCode(vSchema, i4)));
        }
        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, i4) {
          const sch = schema[i4];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i4}])` : (0, codegen_1._)`${data} === ${sch}`;
        }
        __name(equalCode, "equalCode");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js
var require_validation3 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var limitNumber_1 = require_limitNumber2();
    var multipleOf_1 = require_multipleOf2();
    var limitLength_1 = require_limitLength2();
    var pattern_1 = require_pattern2();
    var limitProperties_1 = require_limitProperties2();
    var required_1 = require_required2();
    var limitItems_1 = require_limitItems2();
    var uniqueItems_1 = require_uniqueItems2();
    var const_1 = require_const2();
    var enum_1 = require_enum2();
    var validation2 = [
      // number
      limitNumber_1.default,
      multipleOf_1.default,
      // string
      limitLength_1.default,
      pattern_1.default,
      // object
      limitProperties_1.default,
      required_1.default,
      // array
      limitItems_1.default,
      uniqueItems_1.default,
      // any
      { keyword: "type", schemaType: ["string", "array"] },
      { keyword: "nullable", schemaType: "boolean" },
      const_1.default,
      enum_1.default
    ];
    exports2.default = validation2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
var require_additionalItems2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateAdditionalItems = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error40 = {
      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: error40,
      code(cxt) {
        const { parentSchema, it: it3 } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
          (0, util_1.checkStrictMode)(it3, '"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: it3 } = cxt;
      it3.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)(it3, 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, (i4) => {
          cxt.subschema({ keyword, dataProp: i4, dataPropType: util_1.Type.Num }, valid);
          if (!it3.allErrors)
            gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
      }
      __name(validateItems, "validateItems");
    }
    __name(validateAdditionalItems, "validateAdditionalItems");
    exports2.validateAdditionalItems = validateAdditionalItems;
    exports2.default = def2;
  }
});

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

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

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js
var require_items20202 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var code_1 = require_code4();
    var additionalItems_1 = require_additionalItems2();
    var error40 = {
      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: error40,
      code(cxt) {
        const { schema, parentSchema, it: it3 } = cxt;
        const { prefixItems } = parentSchema;
        it3.items = true;
        if ((0, util_1.alwaysValidSchema)(it3, schema))
          return;
        if (prefixItems)
          (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
          cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js
var require_contains2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it3 } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it3.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)(it3, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it3, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it3, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it3.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, (i4) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i4,
              dataPropType: util_1.Type.Num,
              compositeRule: true
            }, _valid);
            block2();
          });
        }
        __name(validateItems, "validateItems");
        function checkLimits(count) {
          gen.code((0, codegen_1._)`${count}++`);
          if (max === void 0) {
            gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
          } else {
            gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
            if (min === 1)
              gen.assign(valid, true);
            else
              gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
          }
        }
        __name(checkLimits, "checkLimits");
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js
var require_dependencies2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.validateSchemaDeps = exports2.validatePropertyDeps = exports2.error = void 0;
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var code_1 = require_code4();
    exports2.error = {
      message: /* @__PURE__ */ __name(({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
      }, "message"),
      params: /* @__PURE__ */ __name(({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, "params")
      // TODO change to reference
    };
    var def2 = {
      keyword: "dependencies",
      type: "object",
      schemaType: "object",
      error: exports2.error,
      code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
      }
    };
    function splitDependencies({ schema }) {
      const propertyDeps = {};
      const schemaDeps = {};
      for (const key in schema) {
        if (key === "__proto__")
          continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
      }
      return [propertyDeps, schemaDeps];
    }
    __name(splitDependencies, "splitDependencies");
    function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
      const { gen, data, it: it3 } = 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, it3.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it3.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: it3 } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it3, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it3.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
          },
          () => gen.var(valid, true)
          // TODO var
        );
        cxt.ok(valid);
      }
    }
    __name(validateSchemaDeps, "validateSchemaDeps");
    exports2.validateSchemaDeps = validateSchemaDeps;
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
var require_propertyNames2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, data, it: it3 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it3, 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 (!it3.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
var require_additionalProperties2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var code_1 = require_code4();
    var codegen_1 = require_codegen2();
    var names_1 = require_names2();
    var util_1 = require_util10();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it: it3 } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it3;
        it3.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it3, 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)(it3, 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)(it3, schema)) {
            const valid = gen.name("valid");
            if (opts.removeAdditional === "failing") {
              applyAdditionalSchema(key, valid, false);
              gen.if((0, codegen_1.not)(valid), () => {
                cxt.reset();
                deleteAdditional(key);
              });
            } else {
              applyAdditionalSchema(key, valid);
              if (!allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          }
        }
        __name(additionalPropertyCode, "additionalPropertyCode");
        function applyAdditionalSchema(key, valid, errors) {
          const subschema = {
            keyword: "additionalProperties",
            dataProp: key,
            dataPropType: util_1.Type.Str
          };
          if (errors === false) {
            Object.assign(subschema, {
              compositeRule: true,
              createErrors: false,
              allErrors: false
            });
          }
          cxt.subschema(subschema, valid);
        }
        __name(applyAdditionalSchema, "applyAdditionalSchema");
      }
    };
    exports2.default = def2;
  }
});

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

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

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

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

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

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

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js
var require_if2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var codegen_1 = require_codegen2();
    var util_1 = require_util10();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, parentSchema, it: it3 } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it3, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it3, "then");
        const hasElse = hasSchema(it3, "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(it3, keyword) {
      const schema = it3.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it3, schema);
    }
    __name(hasSchema, "hasSchema");
    exports2.default = def2;
  }
});

// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js
var require_thenElse2 = __commonJS({
  "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util10();
    var def2 = {
      keyword: ["then", "else"],
      schemaType: ["object", "boolean"],
      code({ keyword, parentSchema, it: it3 }) {
        if (parentSchema.if === void 0)
          (0, util_1.checkStrictMode)(it3, `"${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 error40 = {
      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: error40,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it: it3 } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it3;
        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_validation3();
    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_util10();
    var error40 = {
      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: error40,
      code(cxt) {
        const { gen, data, schema, parentSchema, it: it3 } = cxt;
        const { oneOf } = parentSchema;
        if (!it3.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 i4 = 0; i4 < oneOf.length; i4++) {
            let sch = oneOf[i4];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it3.self.RULES)) {
              const ref = sch.$ref;
              sch = compile_1.resolveRef.call(it3.self, it3.schemaEnv.root, it3.baseId, ref);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it3.opts.uriResolver, it3.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, i4);
          }
          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, i4) {
            if (sch.const) {
              addMapping(sch.const, i4);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i4);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          __name(addMappings, "addMappings");
          function addMapping(tagValue, i4) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i4;
          }
          __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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, data, schemaCode, keyword, it: it3 } = cxt;
        const { opts, self: self2 } = it3;
        if (!opts.validateFormats)
          return;
        const fCxt = new ajv_1.KeywordCxt(it3, 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_dist = __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 = (name4, mode = "full") => {
      const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
      const f5 = formats[name4];
      if (!f5)
        throw new Error(`Unknown format "${name4}"`);
      return f5;
    };
    function addFormats2(ajv, list3, fs142, 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, fs142[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 getAcceptedTypes(propSchema) {
  const types7 = /* @__PURE__ */ new Set();
  if (typeof propSchema["type"] === "string") {
    types7.add(propSchema["type"]);
  } else if (Array.isArray(propSchema["type"])) {
    for (const t5 of propSchema["type"]) {
      types7.add(t5);
    }
  }
  for (const keyword of ["anyOf", "oneOf"]) {
    const variants = propSchema[keyword];
    if (Array.isArray(variants)) {
      for (const variant of variants) {
        if (typeof variant["type"] === "string") {
          types7.add(variant["type"]);
        } else if (Array.isArray(variant["type"])) {
          for (const t5 of variant["type"]) {
            types7.add(t5);
          }
        }
      }
    }
  }
  return types7.size > 0 ? types7 : null;
}
function fixStringifiedJsonValues(data, schema) {
  const properties = schema["properties"];
  if (!properties)
    return;
  for (const key of Object.keys(data)) {
    const value = data[key];
    const propSchema = properties[key];
    if (!propSchema || typeof value !== "string")
      continue;
    const trimmed2 = value.trim();
    if (trimmed2.startsWith("[") && trimmed2.endsWith("]") || trimmed2.startsWith("{") && trimmed2.endsWith("}")) {
      const accepted = getAcceptedTypes(propSchema);
      if (!accepted)
        continue;
      if (accepted.has("string"))
        continue;
      if (!accepted.has("array") && !accepted.has("object"))
        continue;
      try {
        const parsed = JSON.parse(trimmed2);
        const parsedType4 = Array.isArray(parsed) ? "array" : typeof parsed;
        if (accepted.has(parsedType4)) {
          data[key] = parsed;
        }
      } catch {
      }
    }
  }
}
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, debugLogger, 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_dist(), 1);
    init_debugLogger();
    AjvClass = import_ajv.default.default || import_ajv.default;
    Ajv2020Class = import__.default.default || import__.default;
    debugLogger = 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 (error40) {
          debugLogger.warn(`Failed to compile schema (${schema?.["$schema"] ?? "<no $schema>"}): ${error40 instanceof Error ? error40.message : String(error40)}. Skipping parameter validation.`);
          return null;
        }
        let valid = validate3(data);
        if (!valid && validate3.errors) {
          fixBooleanValues(data);
          fixStringifiedJsonValues(data, anySchema);
          valid = validate3(data);
          if (!valid && validate3.errors) {
            return validator.errorsText(validate3.errors, { dataVar: "params" });
          }
        }
        return null;
      }
    };
    __name(getAcceptedTypes, "getAcceptedTypes");
    __name(fixStringifiedJsonValues, "fixStringifiedJsonValues");
    __name(fixBooleanValues, "fixBooleanValues");
  }
});

// packages/core/dist/src/agents/runtime/agent-statistics.js
var AgentStatistics;
var init_agent_statistics = __esm({
  "packages/core/dist/src/agents/runtime/agent-statistics.js"() {
    "use strict";
    init_esbuild_shims();
    AgentStatistics = class {
      static {
        __name(this, "AgentStatistics");
      }
      startTimeMs = 0;
      rounds = 0;
      totalToolCalls = 0;
      successfulToolCalls = 0;
      failedToolCalls = 0;
      inputTokens = 0;
      outputTokens = 0;
      thoughtTokens = 0;
      cachedTokens = 0;
      apiTotalTokens = 0;
      toolUsage = /* @__PURE__ */ new Map();
      start(now = Date.now()) {
        this.startTimeMs = now;
      }
      setRounds(rounds) {
        this.rounds = rounds;
      }
      recordToolCall(name4, success2, durationMs, lastError) {
        this.totalToolCalls += 1;
        if (success2)
          this.successfulToolCalls += 1;
        else
          this.failedToolCalls += 1;
        const tu = this.toolUsage.get(name4) || {
          name: name4,
          count: 0,
          success: 0,
          failure: 0,
          lastError: void 0,
          totalDurationMs: 0,
          averageDurationMs: 0
        };
        tu.count += 1;
        if (success2)
          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(name4, tu);
      }
      recordTokens(input, output, thought = 0, cached2 = 0, total = 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);
        this.apiTotalTokens += Math.max(0, total || 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.apiTotalTokens > 0 ? this.apiTotalTokens : this.inputTokens + this.outputTokens + this.thoughtTokens;
        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,
          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 parts2 = [
            `in ${stats.inputTokens ?? 0}`,
            `out ${stats.outputTokens ?? 0}`
          ];
          lines.push(`\u{1F522} Tokens: ${stats.totalTokens.toLocaleString()}${parts2.length ? ` (${parts2.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 parts2 = [
            `in ${stats.inputTokens ?? 0}`,
            `out ${stats.outputTokens ?? 0}`
          ];
          lines.push(`\u{1F522} Tokens: ${stats.totalTokens.toLocaleString()} (${parts2.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((name4) => /web|fetch|search/i.test(name4), "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 path150 = ref.substring(2).split("/");
    let current = schema;
    for (const segment of path150) {
      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, CONCURRENCY_SAFE_KINDS;
var init_tools = __esm({
  "packages/core/dist/src/tools/tools.js"() {
    "use strict";
    init_esbuild_shims();
    init_tool_error();
    init_schemaValidator();
    init_agent_statistics();
    BaseToolInvocation = class {
      static {
        __name(this, "BaseToolInvocation");
      }
      params;
      constructor(params) {
        this.params = params;
      }
      toolLocations() {
        return [];
      }
      /**
       * Default: read-only tools return 'allow'. Override in subclasses for
       * tools with side effects.
       */
      getDefaultPermission() {
        return Promise.resolve("allow");
      }
      /**
       * Default fallback: returns a generic 'info' confirmation dialog using the
       * tool's getDescription(). This ensures that even tools whose
       * getDefaultPermission() returns 'allow' can still be prompted when PM
       * rules override the decision to 'ask' at L4.
       *
       * Tools with richer confirmation UIs (Shell, Edit, MCP, etc.) override this.
       */
      getConfirmationDetails(_abortSignal) {
        const details = {
          type: "info",
          title: `Confirm ${this.constructor.name.replace(/Invocation$/, "")}`,
          prompt: this.getDescription(),
          onConfirm: /* @__PURE__ */ __name(async (_outcome, _payload) => {
          }, "onConfirm")
        };
        return Promise.resolve(details);
      }
    };
    DeclarativeTool = class {
      static {
        __name(this, "DeclarativeTool");
      }
      name;
      displayName;
      description;
      kind;
      parameterSchema;
      isOutputMarkdown;
      canUpdateOutput;
      constructor(name4, displayName, description, kind2, parameterSchema, isOutputMarkdown = true, canUpdateOutput = false) {
        this.name = name4;
        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 (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          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["ProceedAlwaysProject"] = "proceed_always_project";
      ToolConfirmationOutcome2["ProceedAlwaysUser"] = "proceed_always_user";
      ToolConfirmationOutcome2["ModifyWithEditor"] = "modify_with_editor";
      ToolConfirmationOutcome2["RestorePrevious"] = "restore_previous";
      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
    ];
    CONCURRENCY_SAFE_KINDS = /* @__PURE__ */ new Set([
      Kind.Read,
      Kind.Search,
      Kind.Fetch
    ]);
  }
});

// packages/core/dist/src/telemetry/tool-call-decision.js
function getDecisionFromOutcome(outcome) {
  switch (outcome) {
    case ToolConfirmationOutcome.ProceedOnce:
    case ToolConfirmationOutcome.RestorePrevious:
      return ToolCallDecision.ACCEPT;
    case ToolConfirmationOutcome.ProceedAlways:
    case ToolConfirmationOutcome.ProceedAlwaysServer:
    case ToolConfirmationOutcome.ProceedAlwaysTool:
    case ToolConfirmationOutcome.ProceedAlwaysProject:
    case ToolConfirmationOutcome.ProceedAlwaysUser:
      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/utils/subagentNameContext.js
import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
var MAIN_SOURCE, subagentNameContext;
var init_subagentNameContext = __esm({
  "packages/core/dist/src/utils/subagentNameContext.js"() {
    "use strict";
    init_esbuild_shims();
    MAIN_SOURCE = "main";
    subagentNameContext = new AsyncLocalStorage3();
  }
});

// packages/core/dist/src/telemetry/uiTelemetry.js
import { EventEmitter } from "node:events";
var createInitialModelMetricsCore, 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_subagentNameContext();
    init_subagentNameContext();
    init_constants();
    createInitialModelMetricsCore = /* @__PURE__ */ __name(() => ({
      api: {
        totalRequests: 0,
        totalErrors: 0,
        totalLatencyMs: 0
      },
      tokens: {
        prompt: 0,
        candidates: 0,
        total: 0,
        cached: 0,
        thoughts: 0
      }
    }), "createInitialModelMetricsCore");
    createInitialModelMetrics = /* @__PURE__ */ __name(() => ({
      ...createInitialModelMetricsCore(),
      bySource: /* @__PURE__ */ Object.create(null)
    }), "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;
      #lastCachedContentTokenCount = 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
        });
      }
      getLastCachedContentTokenCount() {
        return this.#lastCachedContentTokenCount;
      }
      setLastCachedContentTokenCount(count) {
        this.#lastCachedContentTokenCount = count;
      }
      /**
       * Resets metrics to the initial state (used when resuming a session).
       */
      reset() {
        this.#metrics = createInitialMetrics();
        this.#lastPromptTokenCount = 0;
        this.#lastCachedContentTokenCount = 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];
      }
      getOrCreateSourceMetrics(modelMetrics, source2) {
        if (!modelMetrics.bySource[source2]) {
          modelMetrics.bySource[source2] = createInitialModelMetricsCore();
        }
        return modelMetrics.bySource[source2];
      }
      processApiResponse(event) {
        const modelMetrics = this.getOrCreateModelMetrics(event.model);
        const sourceMetrics = this.getOrCreateSourceMetrics(modelMetrics, event.subagent_name ?? MAIN_SOURCE);
        for (const bucket of [modelMetrics, sourceMetrics]) {
          bucket.api.totalRequests++;
          bucket.api.totalLatencyMs += event.duration_ms;
          bucket.tokens.prompt += event.input_token_count;
          bucket.tokens.candidates += event.output_token_count;
          bucket.tokens.total += event.total_token_count;
          bucket.tokens.cached += event.cached_content_token_count;
          bucket.tokens.thoughts += event.thoughts_token_count;
        }
      }
      processApiError(event) {
        const modelMetrics = this.getOrCreateModelMetrics(event.model);
        const sourceMetrics = this.getOrCreateSourceMetrics(modelMetrics, event.subagent_name ?? MAIN_SOURCE);
        for (const bucket of [modelMetrics, sourceMetrics]) {
          bucket.api.totalRequests++;
          bucket.api.totalErrors++;
          bucket.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/agents/arena/types.js
function safeAgentId(agentId) {
  return agentId.replace(/[/\\:*?"<>|]/g, "--");
}
var ARENA_MAX_AGENTS, ArenaSessionStatus;
var init_types = __esm({
  "packages/core/dist/src/agents/arena/types.js"() {
    "use strict";
    init_esbuild_shims();
    ARENA_MAX_AGENTS = 5;
    (function(ArenaSessionStatus2) {
      ArenaSessionStatus2["INITIALIZING"] = "initializing";
      ArenaSessionStatus2["RUNNING"] = "running";
      ArenaSessionStatus2["IDLE"] = "idle";
      ArenaSessionStatus2["COMPLETED"] = "completed";
      ArenaSessionStatus2["CANCELLED"] = "cancelled";
      ArenaSessionStatus2["FAILED"] = "failed";
    })(ArenaSessionStatus || (ArenaSessionStatus = {}));
    __name(safeAgentId, "safeAgentId");
  }
});

// packages/core/dist/src/agents/runtime/agent-types.js
var AgentTerminateMode, AgentStatus, isTerminalStatus, isSuccessStatus, isSettledStatus;
var init_agent_types = __esm({
  "packages/core/dist/src/agents/runtime/agent-types.js"() {
    "use strict";
    init_esbuild_shims();
    (function(AgentTerminateMode2) {
      AgentTerminateMode2["ERROR"] = "ERROR";
      AgentTerminateMode2["TIMEOUT"] = "TIMEOUT";
      AgentTerminateMode2["GOAL"] = "GOAL";
      AgentTerminateMode2["MAX_TURNS"] = "MAX_TURNS";
      AgentTerminateMode2["CANCELLED"] = "CANCELLED";
      AgentTerminateMode2["SHUTDOWN"] = "SHUTDOWN";
    })(AgentTerminateMode || (AgentTerminateMode = {}));
    (function(AgentStatus2) {
      AgentStatus2["INITIALIZING"] = "initializing";
      AgentStatus2["RUNNING"] = "running";
      AgentStatus2["IDLE"] = "idle";
      AgentStatus2["COMPLETED"] = "completed";
      AgentStatus2["FAILED"] = "failed";
      AgentStatus2["CANCELLED"] = "cancelled";
    })(AgentStatus || (AgentStatus = {}));
    isTerminalStatus = /* @__PURE__ */ __name((s5) => s5 === AgentStatus.COMPLETED || s5 === AgentStatus.FAILED || s5 === AgentStatus.CANCELLED, "isTerminalStatus");
    isSuccessStatus = /* @__PURE__ */ __name((s5) => s5 === AgentStatus.IDLE || s5 === AgentStatus.COMPLETED, "isSuccessStatus");
    isSettledStatus = /* @__PURE__ */ __name((s5) => s5 === AgentStatus.IDLE || isTerminalStatus(s5), "isSettledStatus");
  }
});

// packages/core/dist/src/agents/arena/ArenaAgentClient.js
import * as fs8 from "node:fs/promises";
import * as path6 from "node:path";
var debugLogger2, AGENTS_SUBDIR, CONTROL_SUBDIR, ArenaAgentClient;
var init_ArenaAgentClient = __esm({
  "packages/core/dist/src/agents/arena/ArenaAgentClient.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_errors();
    init_atomicFileWrite();
    init_uiTelemetry();
    init_types();
    init_agent_types();
    debugLogger2 = createDebugLogger("ARENA_AGENT_CLIENT");
    AGENTS_SUBDIR = "agents";
    CONTROL_SUBDIR = "control";
    ArenaAgentClient = class _ArenaAgentClient {
      static {
        __name(this, "ArenaAgentClient");
      }
      agentId;
      agentsDir;
      controlDir;
      statusFilePath;
      controlFilePath;
      startTimeMs;
      initialized = false;
      /**
       * Static factory - returns an instance if ARENA_AGENT_ID, ARENA_SESSION_ID,
       * and ARENA_SESSION_DIR env vars are present, null otherwise.
       */
      static create() {
        const agentId = process.env["ARENA_AGENT_ID"];
        const sessionId = process.env["ARENA_SESSION_ID"];
        const sessionDir = process.env["ARENA_SESSION_DIR"];
        if (!agentId || !sessionId || !sessionDir) {
          return null;
        }
        return new _ArenaAgentClient(agentId, sessionDir);
      }
      constructor(agentId, arenaSessionDir) {
        this.agentId = agentId;
        const safe = safeAgentId(agentId);
        this.agentsDir = path6.join(arenaSessionDir, AGENTS_SUBDIR);
        this.controlDir = path6.join(arenaSessionDir, CONTROL_SUBDIR);
        this.statusFilePath = path6.join(this.agentsDir, `${safe}.json`);
        this.controlFilePath = path6.join(this.controlDir, `${safe}.json`);
        this.startTimeMs = Date.now();
      }
      /**
       * Initialize the agents/ and control/ directories under the arena session
       * dir. Called automatically on first use if not invoked explicitly.
       */
      async init() {
        await fs8.mkdir(this.agentsDir, { recursive: true });
        await fs8.mkdir(this.controlDir, { recursive: true });
        this.initialized = true;
        debugLogger2.info(`ArenaAgentClient initialized for agent ${this.agentId} at ${this.agentsDir}`);
      }
      /**
       * Write current status to the per-agent status file using atomic write
       * (write to temp file then rename).
       *
       * Stats are derived automatically from uiTelemetryService which is the
       * canonical source for token counts, tool calls, and API request counts.
       */
      async updateStatus(currentActivity) {
        await this.ensureInitialized();
        const stats = this.getStatsFromTelemetry();
        const statusFile = {
          agentId: this.agentId,
          status: AgentStatus.RUNNING,
          updatedAt: Date.now(),
          rounds: stats.rounds,
          currentActivity,
          stats,
          finalSummary: null,
          error: null
        };
        await atomicWriteJSON(this.statusFilePath, statusFile);
      }
      /**
       * Read and delete control.json (consume-once pattern).
       * Returns null if no control signal is pending.
       */
      async checkControlSignal() {
        await this.ensureInitialized();
        try {
          const content = await fs8.readFile(this.controlFilePath, "utf-8");
          const signal = JSON.parse(content);
          await fs8.unlink(this.controlFilePath);
          return signal;
        } catch (error40) {
          if (isNodeError(error40) && error40.code === "ENOENT") {
            return null;
          }
          if (isNodeError(error40) && error40.code === "EACCES") {
            throw error40;
          }
          debugLogger2.error("Error reading control signal:", error40);
          return null;
        }
      }
      /**
       * Report that the agent has completed the current task successfully.
       * This is the primary signal to the main process that the agent is done working.
       */
      async reportCompleted(finalSummary) {
        await this.ensureInitialized();
        const stats = this.getStatsFromTelemetry();
        const statusFile = {
          agentId: this.agentId,
          status: AgentStatus.COMPLETED,
          updatedAt: Date.now(),
          rounds: stats.rounds,
          stats,
          finalSummary: finalSummary ?? null,
          error: null
        };
        await atomicWriteJSON(this.statusFilePath, statusFile);
      }
      /**
       * Report that the agent hit an error (API/auth/rate-limit, loop, etc.).
       */
      async reportError(errorMessage) {
        await this.ensureInitialized();
        const stats = this.getStatsFromTelemetry();
        const statusFile = {
          agentId: this.agentId,
          status: AgentStatus.FAILED,
          updatedAt: Date.now(),
          rounds: stats.rounds,
          stats,
          finalSummary: null,
          error: errorMessage
        };
        await atomicWriteJSON(this.statusFilePath, statusFile);
      }
      /**
       * Report that the agent's current request was cancelled by the user.
       */
      async reportCancelled() {
        await this.ensureInitialized();
        const stats = this.getStatsFromTelemetry();
        const statusFile = {
          agentId: this.agentId,
          status: AgentStatus.CANCELLED,
          updatedAt: Date.now(),
          rounds: stats.rounds,
          stats,
          finalSummary: null,
          error: null
        };
        await atomicWriteJSON(this.statusFilePath, statusFile);
      }
      /**
       * Build ArenaAgentStats from uiTelemetryService metrics
       */
      getStatsFromTelemetry() {
        const metrics2 = uiTelemetryService.getMetrics();
        let rounds = 0;
        let totalTokens = 0;
        let inputTokens = 0;
        let outputTokens = 0;
        for (const model of Object.values(metrics2.models)) {
          rounds += model.api.totalRequests;
          totalTokens += model.tokens.total;
          inputTokens += model.tokens.prompt;
          outputTokens += model.tokens.candidates;
        }
        return {
          rounds,
          totalTokens,
          inputTokens,
          outputTokens,
          durationMs: Date.now() - this.startTimeMs,
          toolCalls: metrics2.tools.totalCalls,
          successfulToolCalls: metrics2.tools.totalSuccess,
          failedToolCalls: metrics2.tools.totalFail
        };
      }
      async ensureInitialized() {
        if (!this.initialized) {
          await this.init();
        }
      }
    };
  }
});

// packages/core/dist/src/utils/errorReporting.js
async function reportError2(error40, baseMessage, context2, type = "general") {
  let errorToReport;
  if (error40 instanceof Error) {
    errorToReport = { message: error40.message, stack: error40.stack };
  } else if (typeof error40 === "object" && error40 !== null && "message" in error40) {
    errorToReport = {
      message: String(error40.message)
    };
  } else {
    errorToReport = { message: String(error40) };
  }
  const reportContent = { error: errorToReport };
  if (context2) {
    reportContent.context = context2;
  }
  const reportLabel = `${baseMessage} [${type}]`;
  let stringifiedReportContent;
  try {
    stringifiedReportContent = JSON.stringify(reportContent, null, 2);
  } catch (stringifyError) {
    debugLogger3.error(`${reportLabel} Could not stringify report content (likely due to context):`, stringifyError, error40);
    try {
      const minimalReportContent = { error: errorToReport };
      stringifiedReportContent = JSON.stringify(minimalReportContent, null, 2);
      debugLogger3.error(reportLabel, stringifiedReportContent);
    } catch (minimalStringifyError) {
      debugLogger3.error(`${reportLabel} Failed to stringify minimal error report:`, minimalStringifyError, error40);
    }
    return;
  }
  debugLogger3.error(reportLabel, stringifiedReportContent);
}
var debugLogger3;
var init_errorReporting = __esm({
  "packages/core/dist/src/utils/errorReporting.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger3 = 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 isArray3 = /* @__PURE__ */ __name(function isArray4(arr) {
      if (typeof Array.isArray === "function") {
        return Array.isArray(arr);
      }
      return toStr.call(arr) === "[object Array]";
    }, "isArray");
    var isPlainObject9 = /* @__PURE__ */ __name(function isPlainObject10(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, name4) {
      if (name4 === "__proto__") {
        if (!hasOwn3.call(obj, name4)) {
          return void 0;
        } else if (gOPD) {
          return gOPD(obj, name4).value;
        }
      }
      return obj[name4];
    }, "getProperty");
    module2.exports = /* @__PURE__ */ __name(function extend3() {
      var options2, name4, src, copy, copyIsArray, clone4;
      var target = arguments[0];
      var i4 = 1;
      var length = arguments.length;
      var deep = false;
      if (typeof target === "boolean") {
        deep = target;
        target = arguments[1] || {};
        i4 = 2;
      }
      if (target == null || typeof target !== "object" && typeof target !== "function") {
        target = {};
      }
      for (; i4 < length; ++i4) {
        options2 = arguments[i4];
        if (options2 != null) {
          for (name4 in options2) {
            src = getProperty2(target, name4);
            copy = getProperty2(options2, name4);
            if (target !== copy) {
              if (deep && copy && (isPlainObject9(copy) || (copyIsArray = isArray3(copy)))) {
                if (copyIsArray) {
                  copyIsArray = false;
                  clone4 = src && isArray3(src) ? src : [];
                } else {
                  clone4 = src && isPlainObject9(src) ? src : {};
                }
                setProperty2(target, { name: name4, newValue: extend3(deep, clone4, copy) });
              } else if (typeof copy !== "undefined") {
                setProperty2(target, { name: name4, 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_util11 = __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_util11());
    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](instance2) {
        if (instance2 && typeof instance2 === "object" && exports2.GAXIOS_ERROR_SYMBOL in instance2 && instance2[exports2.GAXIOS_ERROR_SYMBOL] === pkg2.version) {
          return true;
        }
        return Function.prototype[Symbol.hasInstance].call(_GaxiosError, instance2);
      }
      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(err2) {
      let config2 = getConfig2(err2);
      if (!err2 || !err2.config || !config2 && !err2.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;
      err2.config.retryConfig = config2;
      const shouldRetryFn = config2.shouldRetry || shouldRetryRequest;
      if (!await shouldRetryFn(err2)) {
        return { shouldRetry: false, config: err2.config };
      }
      const delay5 = getNextRetryDelay(config2);
      err2.config.retryConfig.currentRetryAttempt += 1;
      const backoff = config2.retryBackoff ? config2.retryBackoff(err2, delay5) : new Promise((resolve42) => {
        setTimeout(resolve42, delay5);
      });
      if (config2.onRetryAttempt) {
        await config2.onRetryAttempt(err2);
      }
      await backoff;
      return { shouldRetry: true, config: err2.config };
    }
    __name(getRetryConfig, "getRetryConfig");
    function shouldRetryRequest(err2) {
      const config2 = getConfig2(err2);
      if (err2.config.signal?.aborted && err2.code !== "TimeoutError" || err2.code === "AbortError") {
        return false;
      }
      if (!config2 || config2.retry === 0) {
        return false;
      }
      if (!err2.response && (config2.currentRetryAttempt || 0) >= config2.noResponseRetries) {
        return false;
      }
      if (!config2.httpMethodsToRetry || !config2.httpMethodsToRetry.includes(err2.config.method?.toUpperCase() || "GET")) {
        return false;
      }
      if (err2.response && err2.response.status) {
        let isInRange = false;
        for (const [min, max] of config2.statusCodesToRetry) {
          const status = err2.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 getConfig2(err2) {
      if (err2 && err2.config && err2.config.retryConfig) {
        return err2.config.retryConfig;
      }
      return;
    }
    __name(getConfig2, "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 parse17(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 parse17(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(parse17, "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, name4) {
      var isPlural = msAbs >= n3 * 1.5;
      return Math.round(ms / n3) + " " + name4 + (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(env6) {
      createDebug.debug = createDebug;
      createDebug.default = createDebug;
      createDebug.coerce = coerce2;
      createDebug.disable = disable;
      createDebug.enable = enable;
      createDebug.enabled = enabled2;
      createDebug.humanize = require_ms();
      createDebug.destroy = destroy;
      Object.keys(env6).forEach((key) => {
        createDebug[key] = env6[key];
      });
      createDebug.names = [];
      createDebug.skips = [];
      createDebug.formatters = {};
      function selectColor(namespace) {
        let hash = 0;
        for (let i4 = 0; i4 < namespace.length; i4++) {
          hash = (hash << 5) - hash + namespace.charCodeAt(i4);
          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(...args2) {
          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;
          args2[0] = createDebug.coerce(args2[0]);
          if (typeof args2[0] !== "string") {
            args2.unshift("%O");
          }
          let index = 0;
          args2[0] = args2[0].replace(/%([a-zA-Z%])/g, (match2, format4) => {
            if (match2 === "%%") {
              return "%";
            }
            index++;
            const formatter = createDebug.formatters[format4];
            if (typeof formatter === "function") {
              const val = args2[index];
              match2 = formatter.call(self2, val);
              args2.splice(index, 1);
              index--;
            }
            return match2;
          });
          createDebug.formatArgs.call(self2, args2);
          const logFn = self2.log || createDebug.log;
          logFn.apply(self2, args2);
        }
        __name(debug3, "debug");
        debug3.namespace = namespace;
        debug3.useColors = createDebug.useColors();
        debug3.color = createDebug.selectColor(namespace);
        debug3.extend = extend3;
        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 extend3(namespace, delimiter2) {
        const newDebug = createDebug(this.namespace + (typeof delimiter2 === "undefined" ? ":" : delimiter2) + namespace);
        newDebug.log = this.log;
        return newDebug;
      }
      __name(extend3, "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 enabled2(name4) {
        for (const skip of createDebug.skips) {
          if (matchesTemplate(name4, skip)) {
            return false;
          }
        }
        for (const ns of createDebug.names) {
          if (matchesTemplate(name4, ns)) {
            return true;
          }
        }
        return false;
      }
      __name(enabled2, "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(args2) {
      args2[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args2[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
      if (!this.useColors) {
        return;
      }
      const c4 = "color: " + this.color;
      args2.splice(1, 0, c4, "color: inherit");
      let index = 0;
      let lastC = 0;
      args2[0].replace(/%[a-zA-Z%]/g, (match2) => {
        if (match2 === "%%") {
          return;
        }
        index++;
        if (match2 === "%c") {
          lastC = index;
        }
      });
      args2.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 (error40) {
      }
    }
    __name(save, "save");
    function load() {
      let r5;
      try {
        r5 = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
      } catch (error40) {
      }
      if (!r5 && typeof process !== "undefined" && "env" in process) {
        r5 = process.env.DEBUG;
      }
      return r5;
    }
    __name(load, "load");
    function localstorage() {
      try {
        return localStorage;
      } catch (error40) {
      }
    }
    __name(localstorage, "localstorage");
    module2.exports = require_common2()(exports2);
    var { formatters: formatters2 } = module2.exports;
    formatters2.j = function(v2) {
      try {
        return JSON.stringify(v2);
      } catch (error40) {
        return "[UnexpectedJSONParseError]: " + error40.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 os59 = __require("os");
    var hasFlag3 = require_has_flag();
    var env6 = 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 env6) {
      forceColor = env6.FORCE_COLOR.length === 0 || parseInt(env6.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(stream5) {
      if (forceColor === false) {
        return 0;
      }
      if (hasFlag3("color=16m") || hasFlag3("color=full") || hasFlag3("color=truecolor")) {
        return 3;
      }
      if (hasFlag3("color=256")) {
        return 2;
      }
      if (stream5 && !stream5.isTTY && forceColor !== true) {
        return 0;
      }
      const min = forceColor ? 1 : 0;
      if (process.platform === "win32") {
        const osRelease = os59.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 env6) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].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 ("TERM_PROGRAM" in env6) {
        const version2 = 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;
      }
      if (env6.TERM === "dumb") {
        return min;
      }
      return min;
    }
    __name(supportsColor3, "supportsColor");
    function getSupportLevel(stream5) {
      const level = supportsColor3(stream5);
      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 util5 = __require("util");
    exports2.init = init2;
    exports2.log = log;
    exports2.formatArgs = formatArgs2;
    exports2.save = save;
    exports2.load = load;
    exports2.useColors = useColors;
    exports2.destroy = util5.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 (error40) {
    }
    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(args2) {
      const { namespace: name4, useColors: useColors2 } = this;
      if (useColors2) {
        const c4 = this.color;
        const colorCode = "\x1B[3" + (c4 < 8 ? c4 : "8;5;" + c4);
        const prefix = `  ${colorCode};1m${name4} \x1B[0m`;
        args2[0] = prefix + args2[0].split("\n").join("\n" + prefix);
        args2.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
      } else {
        args2[0] = getDate() + name4 + " " + args2[0];
      }
    }
    __name(formatArgs2, "formatArgs");
    function getDate() {
      if (exports2.inspectOpts.hideDate) {
        return "";
      }
      return (/* @__PURE__ */ new Date()).toISOString() + " ";
    }
    __name(getDate, "getDate");
    function log(...args2) {
      return process.stderr.write(util5.formatWithOptions(exports2.inspectOpts, ...args2) + "\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 init2(debug3) {
      debug3.inspectOpts = {};
      const keys = Object.keys(exports2.inspectOpts);
      for (let i4 = 0; i4 < keys.length; i4++) {
        debug3.inspectOpts[keys[i4]] = exports2.inspectOpts[keys[i4]];
      }
    }
    __name(init2, "init");
    module2.exports = require_common2()(exports2);
    var { formatters: formatters2 } = module2.exports;
    formatters2.o = function(v2) {
      this.inspectOpts.colors = this.useColors;
      return util5.inspect(v2, this.inspectOpts).split("\n").map((str2) => str2.trim()).join(" ");
    };
    formatters2.O = function(v2) {
      this.inspectOpts.colors = this.useColors;
      return util5.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 http9 = __importStar(__require("http"));
    var https9 = __importStar(__require("https"));
    async function toBuffer(stream5) {
      let length = 0;
      const chunks = [];
      for await (const chunk of stream5) {
        length += chunk.length;
        chunks.push(chunk);
      }
      return Buffer.concat(chunks, length);
    }
    __name(toBuffer, "toBuffer");
    exports2.toBuffer = toBuffer;
    async function json3(stream5) {
      const buf = await toBuffer(stream5);
      const str2 = buf.toString("utf8");
      try {
        return JSON.parse(str2);
      } catch (_err) {
        const err2 = _err;
        err2.message += ` (input: ${str2})`;
        throw err2;
      }
    }
    __name(json3, "json");
    exports2.json = json3;
    function req(url3, opts = {}) {
      const href = typeof url3 === "string" ? url3 : url3.href;
      const req2 = (href.startsWith("https:") ? https9 : http9).request(url3, opts);
      const promise2 = new Promise((resolve42, reject) => {
        req2.once("response", resolve42).once("error", reject).end();
      });
      req2.then = promise2.then.bind(promise2);
      return req2;
    }
    __name(req, "req");
    exports2.req = req;
  }
});

// node_modules/agent-base/dist/index.js
var require_dist2 = __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 http9 = __importStar(__require("http"));
    var https_1 = __require("https");
    __exportStar(require_helpers(), exports2);
    var INTERNAL2 = Symbol("AgentBaseInternalState");
    var Agent4 = class extends http9.Agent {
      static {
        __name(this, "Agent");
      }
      constructor(opts) {
        super(opts);
        this[INTERNAL2] = {};
      }
      /**
       * 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(name4) {
        if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
          return null;
        }
        if (!this.sockets[name4]) {
          this.sockets[name4] = [];
        }
        const fakeSocket = new net2.Socket({ writable: false });
        this.sockets[name4].push(fakeSocket);
        this.totalSocketCount++;
        return fakeSocket;
      }
      decrementSockets(name4, socket) {
        if (!this.sockets[name4] || socket === null) {
          return;
        }
        const sockets = this.sockets[name4];
        const index = sockets.indexOf(socket);
        if (index !== -1) {
          sockets.splice(index, 1);
          this.totalSocketCount--;
          if (sockets.length === 0) {
            delete this.sockets[name4];
          }
        }
      }
      // 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 name4 = this.getName(connectOpts);
        const fakeSocket = this.incrementSockets(name4);
        Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
          this.decrementSockets(name4, fakeSocket);
          if (socket instanceof http9.Agent) {
            try {
              return socket.addRequest(req, connectOpts);
            } catch (err2) {
              return cb(err2);
            }
          }
          this[INTERNAL2].currentSocket = socket;
          super.createSocket(req, options2, cb);
        }, (err2) => {
          this.decrementSockets(name4, fakeSocket);
          cb(err2);
        });
      }
      createConnection() {
        const socket = this[INTERNAL2].currentSocket;
        this[INTERNAL2].currentSocket = void 0;
        if (!socket) {
          throw new Error("No socket was returned in the `connect()` function");
        }
        return socket;
      }
      get defaultPort() {
        return this[INTERNAL2].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
      }
      set defaultPort(v2) {
        if (this[INTERNAL2]) {
          this[INTERNAL2].defaultPort = v2;
        }
      }
      get protocol() {
        return this[INTERNAL2].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
      }
      set protocol(v2) {
        if (this[INTERNAL2]) {
          this[INTERNAL2].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((resolve42, 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(err2) {
          cleanup();
          debug3("onerror %o", err2);
          reject(err2);
        }
        __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();
          resolve42({
            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_dist3 = __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_dist2();
    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 HttpsProxyAgent3 = class extends agent_base_1.Agent {
      static {
        __name(this, "HttpsProxyAgent");
      }
      constructor(proxy2, opts) {
        super(opts);
        this.options = { path: void 0 };
        this.proxy = typeof proxy2 === "string" ? new url_1.URL(proxy2) : proxy2;
        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: proxy2 } = this;
        if (!opts.host) {
          throw new TypeError('No "host" provided');
        }
        let socket;
        if (proxy2.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 (proxy2.username || proxy2.password) {
          const auth2 = `${decodeURIComponent(proxy2.username)}:${decodeURIComponent(proxy2.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 name4 of Object.keys(headers)) {
          payload += `${name4}: ${headers[name4]}\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;
      }
    };
    HttpsProxyAgent3.protocols = ["http", "https"];
    exports2.HttpsProxyAgent = HttpsProxyAgent3;
    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 base643 = false;
  const type = meta[0] || "text/plain";
  let typeFull = type;
  for (let i4 = 1; i4 < meta.length; i4++) {
    if (meta[i4] === "base64") {
      base643 = true;
    } else if (meta[i4]) {
      typeFull += `;${meta[i4]}`;
      if (meta[i4].indexOf("charset=") === 0) {
        charset = meta[i4].substring(8);
      }
    }
  }
  if (!meta[0] && !charset.length) {
    typeFull += ";charset=US-ASCII";
    charset = "US-ASCII";
  }
  const encoding = base643 ? "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, factory2) {
      typeof exports2 === "object" && typeof module2 !== "undefined" ? factory2(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory2) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory2(global2.WebStreamsPolyfill = {}));
    })(exports2, function(exports3) {
      "use strict";
      function noop11() {
        return void 0;
      }
      __name(noop11, "noop");
      function typeIsObject(x3) {
        return typeof x3 === "object" && x3 !== null || typeof x3 === "function";
      }
      __name(typeIsObject, "typeIsObject");
      const rethrowAssertionErrorRejection = noop11;
      function setFunctionName(fn, name4) {
        try {
          Object.defineProperty(fn, "name", {
            value: name4,
            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((resolve42) => resolve42(value));
      }
      __name(promiseResolvedWith, "promiseResolvedWith");
      function promiseRejectedWith(reason) {
        return originalPromiseReject(reason);
      }
      __name(promiseRejectedWith, "promiseRejectedWith");
      function PerformPromiseThen(promise2, onFulfilled, onRejected) {
        return originalPromiseThen.call(promise2, onFulfilled, onRejected);
      }
      __name(PerformPromiseThen, "PerformPromiseThen");
      function uponPromise(promise2, onFulfilled, onRejected) {
        PerformPromiseThen(PerformPromiseThen(promise2, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection);
      }
      __name(uponPromise, "uponPromise");
      function uponFulfillment(promise2, onFulfilled) {
        uponPromise(promise2, onFulfilled);
      }
      __name(uponFulfillment, "uponFulfillment");
      function uponRejection(promise2, onRejected) {
        uponPromise(promise2, void 0, onRejected);
      }
      __name(uponRejection, "uponRejection");
      function transformPromiseWith(promise2, fulfillmentHandler, rejectionHandler) {
        return PerformPromiseThen(promise2, fulfillmentHandler, rejectionHandler);
      }
      __name(transformPromiseWith, "transformPromiseWith");
      function setPromiseIsHandledToTrue(promise2) {
        PerformPromiseThen(promise2, 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, args2) {
        if (typeof F4 !== "function") {
          throw new TypeError("Argument is not a function");
        }
        return Function.prototype.apply.call(F4, V3, args2);
      }
      __name(reflectCall, "reflectCall");
      function promiseCall(F4, V3, args2) {
        try {
          return promiseResolvedWith(reflectCall(F4, V3, args2));
        } 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 i4 = this._cursor;
          let node = this._front;
          let elements = node._elements;
          while (i4 !== elements.length || node._next !== void 0) {
            if (i4 === elements.length) {
              node = node._next;
              elements = node._elements;
              i4 = 0;
              if (elements.length === 0) {
                break;
              }
            }
            callback(elements[i4]);
            ++i4;
          }
        }
        // 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, stream5) {
        reader._ownerReadableStream = stream5;
        stream5._reader = reader;
        if (stream5._state === "readable") {
          defaultReaderClosedPromiseInitialize(reader);
        } else if (stream5._state === "closed") {
          defaultReaderClosedPromiseInitializeAsResolved(reader);
        } else {
          defaultReaderClosedPromiseInitializeAsRejected(reader, stream5._storedError);
        }
      }
      __name(ReadableStreamReaderGenericInitialize, "ReadableStreamReaderGenericInitialize");
      function ReadableStreamReaderGenericCancel(reader, reason) {
        const stream5 = reader._ownerReadableStream;
        return ReadableStreamCancel(stream5, reason);
      }
      __name(ReadableStreamReaderGenericCancel, "ReadableStreamReaderGenericCancel");
      function ReadableStreamReaderGenericRelease(reader) {
        const stream5 = reader._ownerReadableStream;
        if (stream5._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`));
        }
        stream5._readableStreamController[ReleaseSteps]();
        stream5._reader = void 0;
        reader._ownerReadableStream = void 0;
      }
      __name(ReadableStreamReaderGenericRelease, "ReadableStreamReaderGenericRelease");
      function readerLockException(name4) {
        return new TypeError("Cannot " + name4 + " a stream using a released reader");
      }
      __name(readerLockException, "readerLockException");
      function defaultReaderClosedPromiseInitialize(reader) {
        reader._closedPromise = newPromise((resolve42, reject) => {
          reader._closedPromise_resolve = resolve42;
          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 isObject5(x3) {
        return typeof x3 === "object" && x3 !== null || typeof x3 === "function";
      }
      __name(isObject5, "isObject");
      function assertObject(x3, context2) {
        if (!isObject5(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(stream5) {
        return new ReadableStreamDefaultReader2(stream5);
      }
      __name(AcquireReadableStreamDefaultReader, "AcquireReadableStreamDefaultReader");
      function ReadableStreamAddReadRequest(stream5, readRequest) {
        stream5._reader._readRequests.push(readRequest);
      }
      __name(ReadableStreamAddReadRequest, "ReadableStreamAddReadRequest");
      function ReadableStreamFulfillReadRequest(stream5, chunk, done) {
        const reader = stream5._reader;
        const readRequest = reader._readRequests.shift();
        if (done) {
          readRequest._closeSteps();
        } else {
          readRequest._chunkSteps(chunk);
        }
      }
      __name(ReadableStreamFulfillReadRequest, "ReadableStreamFulfillReadRequest");
      function ReadableStreamGetNumReadRequests(stream5) {
        return stream5._reader._readRequests.length;
      }
      __name(ReadableStreamGetNumReadRequests, "ReadableStreamGetNumReadRequests");
      function ReadableStreamHasDefaultReader(stream5) {
        const reader = stream5._reader;
        if (reader === void 0) {
          return false;
        }
        if (!IsReadableStreamDefaultReader(reader)) {
          return false;
        }
        return true;
      }
      __name(ReadableStreamHasDefaultReader, "ReadableStreamHasDefaultReader");
      class ReadableStreamDefaultReader2 {
        static {
          __name(this, "ReadableStreamDefaultReader");
        }
        constructor(stream5) {
          assertRequiredArgument(stream5, 1, "ReadableStreamDefaultReader");
          assertReadableStream(stream5, "First parameter");
          if (IsReadableStreamLocked(stream5)) {
            throw new TypeError("This stream has already been locked for exclusive reading by another reader");
          }
          ReadableStreamReaderGenericInitialize(this, stream5);
          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 promise2 = newPromise((resolve42, reject) => {
            resolvePromise = resolve42;
            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 promise2;
        }
        /**
         * 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 stream5 = reader._ownerReadableStream;
        stream5._disturbed = true;
        if (stream5._state === "closed") {
          readRequest._closeSteps();
        } else if (stream5._state === "errored") {
          readRequest._errorSteps(stream5._storedError);
        } else {
          stream5._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(name4) {
        return new TypeError(`ReadableStreamDefaultReader.prototype.${name4} 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 promise2 = newPromise((resolve42, reject) => {
            resolvePromise = resolve42;
            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 promise2;
        }
        _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(stream5, preventCancel) {
        const reader = AcquireReadableStreamDefaultReader(stream5);
        const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
        const iterator2 = Object.create(ReadableStreamAsyncIteratorPrototype);
        iterator2._asyncIteratorImpl = impl;
        return iterator2;
      }
      __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(name4) {
        return new TypeError(`ReadableStreamAsyncIterator.${name4} 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 func2 = receiver[prop];
        if (func2 === void 0 || func2 === null) {
          return void 0;
        }
        if (typeof func2 !== "function") {
          throw new TypeError(`${String(prop)} is not a function`);
        }
        return func2;
      }
      __name(GetMethod, "GetMethod");
      function CreateAsyncFromSyncIterator(syncIteratorRecord) {
        const syncIterable = {
          [Symbol.iterator]: () => syncIteratorRecord.iterator
        };
        const asyncIterator2 = async function* () {
          return yield* syncIterable;
        }();
        const nextMethod = asyncIterator2.next;
        return { iterator: asyncIterator2, 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 iterator2 = reflectCall(method, obj, []);
        if (!typeIsObject(iterator2)) {
          throw new TypeError("The iterator method must return an object");
        }
        const nextMethod = iterator2.next;
        return { iterator: iterator2, 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 stream5 = 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(stream5, 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(stream5, pullIntoDescriptor) {
        let done = false;
        if (stream5._state === "closed") {
          done = true;
        }
        const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
        if (pullIntoDescriptor.readerType === "default") {
          ReadableStreamFulfillReadRequest(stream5, filledView, done);
        } else {
          ReadableStreamFulfillReadIntoRequest(stream5, 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 stream5 = 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(stream5, readIntoRequest);
          return;
        }
        if (stream5._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(stream5, readIntoRequest);
        ReadableByteStreamControllerCallPullIfNeeded(controller);
      }
      __name(ReadableByteStreamControllerPullInto, "ReadableByteStreamControllerPullInto");
      function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
        if (firstDescriptor.readerType === "none") {
          ReadableByteStreamControllerShiftPendingPullInto(controller);
        }
        const stream5 = controller._controlledReadableByteStream;
        if (ReadableStreamHasBYOBReader(stream5)) {
          while (ReadableStreamGetNumReadIntoRequests(stream5) > 0) {
            const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
            ReadableByteStreamControllerCommitPullIntoDescriptor(stream5, 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 stream5 = controller._controlledReadableByteStream;
        if (stream5._state !== "readable") {
          return false;
        }
        if (controller._closeRequested) {
          return false;
        }
        if (!controller._started) {
          return false;
        }
        if (ReadableStreamHasDefaultReader(stream5) && ReadableStreamGetNumReadRequests(stream5) > 0) {
          return true;
        }
        if (ReadableStreamHasBYOBReader(stream5) && ReadableStreamGetNumReadIntoRequests(stream5) > 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 stream5 = controller._controlledReadableByteStream;
        if (controller._closeRequested || stream5._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(stream5);
      }
      __name(ReadableByteStreamControllerClose, "ReadableByteStreamControllerClose");
      function ReadableByteStreamControllerEnqueue(controller, chunk) {
        const stream5 = controller._controlledReadableByteStream;
        if (controller._closeRequested || stream5._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(stream5)) {
          ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
          if (ReadableStreamGetNumReadRequests(stream5) === 0) {
            ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
          } else {
            if (controller._pendingPullIntos.length > 0) {
              ReadableByteStreamControllerShiftPendingPullInto(controller);
            }
            const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
            ReadableStreamFulfillReadRequest(stream5, transferredView, false);
          }
        } else if (ReadableStreamHasBYOBReader(stream5)) {
          ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
          ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
        } else {
          ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
        }
        ReadableByteStreamControllerCallPullIfNeeded(controller);
      }
      __name(ReadableByteStreamControllerEnqueue, "ReadableByteStreamControllerEnqueue");
      function ReadableByteStreamControllerError(controller, e4) {
        const stream5 = controller._controlledReadableByteStream;
        if (stream5._state !== "readable") {
          return;
        }
        ReadableByteStreamControllerClearPendingPullIntos(controller);
        ResetQueue(controller);
        ReadableByteStreamControllerClearAlgorithms(controller);
        ReadableStreamError(stream5, 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(stream5, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
        controller._controlledReadableByteStream = stream5;
        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();
        stream5._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(stream5, 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(stream5, 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(name4) {
        return new TypeError(`ReadableStreamBYOBRequest.prototype.${name4} can only be used on a ReadableStreamBYOBRequest`);
      }
      __name(byobRequestBrandCheckException, "byobRequestBrandCheckException");
      function byteStreamControllerBrandCheckException(name4) {
        return new TypeError(`ReadableByteStreamController.prototype.${name4} 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(stream5) {
        return new ReadableStreamBYOBReader2(stream5);
      }
      __name(AcquireReadableStreamBYOBReader, "AcquireReadableStreamBYOBReader");
      function ReadableStreamAddReadIntoRequest(stream5, readIntoRequest) {
        stream5._reader._readIntoRequests.push(readIntoRequest);
      }
      __name(ReadableStreamAddReadIntoRequest, "ReadableStreamAddReadIntoRequest");
      function ReadableStreamFulfillReadIntoRequest(stream5, chunk, done) {
        const reader = stream5._reader;
        const readIntoRequest = reader._readIntoRequests.shift();
        if (done) {
          readIntoRequest._closeSteps(chunk);
        } else {
          readIntoRequest._chunkSteps(chunk);
        }
      }
      __name(ReadableStreamFulfillReadIntoRequest, "ReadableStreamFulfillReadIntoRequest");
      function ReadableStreamGetNumReadIntoRequests(stream5) {
        return stream5._reader._readIntoRequests.length;
      }
      __name(ReadableStreamGetNumReadIntoRequests, "ReadableStreamGetNumReadIntoRequests");
      function ReadableStreamHasBYOBReader(stream5) {
        const reader = stream5._reader;
        if (reader === void 0) {
          return false;
        }
        if (!IsReadableStreamBYOBReader(reader)) {
          return false;
        }
        return true;
      }
      __name(ReadableStreamHasBYOBReader, "ReadableStreamHasBYOBReader");
      class ReadableStreamBYOBReader2 {
        static {
          __name(this, "ReadableStreamBYOBReader");
        }
        constructor(stream5) {
          assertRequiredArgument(stream5, 1, "ReadableStreamBYOBReader");
          assertReadableStream(stream5, "First parameter");
          if (IsReadableStreamLocked(stream5)) {
            throw new TypeError("This stream has already been locked for exclusive reading by another reader");
          }
          if (!IsReadableByteStreamController(stream5._readableStreamController)) {
            throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");
          }
          ReadableStreamReaderGenericInitialize(this, stream5);
          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 promise2 = newPromise((resolve42, reject) => {
            resolvePromise = resolve42;
            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 promise2;
        }
        /**
         * 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 stream5 = reader._ownerReadableStream;
        stream5._disturbed = true;
        if (stream5._state === "errored") {
          readIntoRequest._errorSteps(stream5._storedError);
        } else {
          ReadableByteStreamControllerPullInto(stream5._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(name4) {
        return new TypeError(`ReadableStreamBYOBReader.prototype.${name4} 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(init2, context2) {
        assertDictionary(init2, context2);
        const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.highWaterMark;
        const size = init2 === null || init2 === void 0 ? void 0 : init2.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 abort2 = original === null || original === void 0 ? void 0 : original.abort;
        const close = original === null || original === void 0 ? void 0 : original.close;
        const start2 = original === null || original === void 0 ? void 0 : original.start;
        const type = original === null || original === void 0 ? void 0 : original.type;
        const write3 = original === null || original === void 0 ? void 0 : original.write;
        return {
          abort: abort2 === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort2, original, `${context2} has member 'abort' that`),
          close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context2} has member 'close' that`),
          start: start2 === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start2, original, `${context2} has member 'start' that`),
          write: write3 === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write3, 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 WritableStream3 {
        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(WritableStream3.prototype, {
        abort: { enumerable: true },
        close: { enumerable: true },
        getWriter: { enumerable: true },
        locked: { enumerable: true }
      });
      setFunctionName(WritableStream3.prototype.abort, "abort");
      setFunctionName(WritableStream3.prototype.close, "close");
      setFunctionName(WritableStream3.prototype.getWriter, "getWriter");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(WritableStream3.prototype, Symbol.toStringTag, {
          value: "WritableStream",
          configurable: true
        });
      }
      function AcquireWritableStreamDefaultWriter(stream5) {
        return new WritableStreamDefaultWriter2(stream5);
      }
      __name(AcquireWritableStreamDefaultWriter, "AcquireWritableStreamDefaultWriter");
      function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
        const stream5 = Object.create(WritableStream3.prototype);
        InitializeWritableStream(stream5);
        const controller = Object.create(WritableStreamDefaultController2.prototype);
        SetUpWritableStreamDefaultController(stream5, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
        return stream5;
      }
      __name(CreateWritableStream, "CreateWritableStream");
      function InitializeWritableStream(stream5) {
        stream5._state = "writable";
        stream5._storedError = void 0;
        stream5._writer = void 0;
        stream5._writableStreamController = void 0;
        stream5._writeRequests = new SimpleQueue();
        stream5._inFlightWriteRequest = void 0;
        stream5._closeRequest = void 0;
        stream5._inFlightCloseRequest = void 0;
        stream5._pendingAbortRequest = void 0;
        stream5._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 WritableStream3;
      }
      __name(IsWritableStream, "IsWritableStream");
      function IsWritableStreamLocked(stream5) {
        if (stream5._writer === void 0) {
          return false;
        }
        return true;
      }
      __name(IsWritableStreamLocked, "IsWritableStreamLocked");
      function WritableStreamAbort(stream5, reason) {
        var _a8;
        if (stream5._state === "closed" || stream5._state === "errored") {
          return promiseResolvedWith(void 0);
        }
        stream5._writableStreamController._abortReason = reason;
        (_a8 = stream5._writableStreamController._abortController) === null || _a8 === void 0 ? void 0 : _a8.abort(reason);
        const state = stream5._state;
        if (state === "closed" || state === "errored") {
          return promiseResolvedWith(void 0);
        }
        if (stream5._pendingAbortRequest !== void 0) {
          return stream5._pendingAbortRequest._promise;
        }
        let wasAlreadyErroring = false;
        if (state === "erroring") {
          wasAlreadyErroring = true;
          reason = void 0;
        }
        const promise2 = newPromise((resolve42, reject) => {
          stream5._pendingAbortRequest = {
            _promise: void 0,
            _resolve: resolve42,
            _reject: reject,
            _reason: reason,
            _wasAlreadyErroring: wasAlreadyErroring
          };
        });
        stream5._pendingAbortRequest._promise = promise2;
        if (!wasAlreadyErroring) {
          WritableStreamStartErroring(stream5, reason);
        }
        return promise2;
      }
      __name(WritableStreamAbort, "WritableStreamAbort");
      function WritableStreamClose(stream5) {
        const state = stream5._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 promise2 = newPromise((resolve42, reject) => {
          const closeRequest = {
            _resolve: resolve42,
            _reject: reject
          };
          stream5._closeRequest = closeRequest;
        });
        const writer = stream5._writer;
        if (writer !== void 0 && stream5._backpressure && state === "writable") {
          defaultWriterReadyPromiseResolve(writer);
        }
        WritableStreamDefaultControllerClose(stream5._writableStreamController);
        return promise2;
      }
      __name(WritableStreamClose, "WritableStreamClose");
      function WritableStreamAddWriteRequest(stream5) {
        const promise2 = newPromise((resolve42, reject) => {
          const writeRequest = {
            _resolve: resolve42,
            _reject: reject
          };
          stream5._writeRequests.push(writeRequest);
        });
        return promise2;
      }
      __name(WritableStreamAddWriteRequest, "WritableStreamAddWriteRequest");
      function WritableStreamDealWithRejection(stream5, error40) {
        const state = stream5._state;
        if (state === "writable") {
          WritableStreamStartErroring(stream5, error40);
          return;
        }
        WritableStreamFinishErroring(stream5);
      }
      __name(WritableStreamDealWithRejection, "WritableStreamDealWithRejection");
      function WritableStreamStartErroring(stream5, reason) {
        const controller = stream5._writableStreamController;
        stream5._state = "erroring";
        stream5._storedError = reason;
        const writer = stream5._writer;
        if (writer !== void 0) {
          WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
        }
        if (!WritableStreamHasOperationMarkedInFlight(stream5) && controller._started) {
          WritableStreamFinishErroring(stream5);
        }
      }
      __name(WritableStreamStartErroring, "WritableStreamStartErroring");
      function WritableStreamFinishErroring(stream5) {
        stream5._state = "errored";
        stream5._writableStreamController[ErrorSteps]();
        const storedError = stream5._storedError;
        stream5._writeRequests.forEach((writeRequest) => {
          writeRequest._reject(storedError);
        });
        stream5._writeRequests = new SimpleQueue();
        if (stream5._pendingAbortRequest === void 0) {
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream5);
          return;
        }
        const abortRequest = stream5._pendingAbortRequest;
        stream5._pendingAbortRequest = void 0;
        if (abortRequest._wasAlreadyErroring) {
          abortRequest._reject(storedError);
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream5);
          return;
        }
        const promise2 = stream5._writableStreamController[AbortSteps](abortRequest._reason);
        uponPromise(promise2, () => {
          abortRequest._resolve();
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream5);
          return null;
        }, (reason) => {
          abortRequest._reject(reason);
          WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream5);
          return null;
        });
      }
      __name(WritableStreamFinishErroring, "WritableStreamFinishErroring");
      function WritableStreamFinishInFlightWrite(stream5) {
        stream5._inFlightWriteRequest._resolve(void 0);
        stream5._inFlightWriteRequest = void 0;
      }
      __name(WritableStreamFinishInFlightWrite, "WritableStreamFinishInFlightWrite");
      function WritableStreamFinishInFlightWriteWithError(stream5, error40) {
        stream5._inFlightWriteRequest._reject(error40);
        stream5._inFlightWriteRequest = void 0;
        WritableStreamDealWithRejection(stream5, error40);
      }
      __name(WritableStreamFinishInFlightWriteWithError, "WritableStreamFinishInFlightWriteWithError");
      function WritableStreamFinishInFlightClose(stream5) {
        stream5._inFlightCloseRequest._resolve(void 0);
        stream5._inFlightCloseRequest = void 0;
        const state = stream5._state;
        if (state === "erroring") {
          stream5._storedError = void 0;
          if (stream5._pendingAbortRequest !== void 0) {
            stream5._pendingAbortRequest._resolve();
            stream5._pendingAbortRequest = void 0;
          }
        }
        stream5._state = "closed";
        const writer = stream5._writer;
        if (writer !== void 0) {
          defaultWriterClosedPromiseResolve(writer);
        }
      }
      __name(WritableStreamFinishInFlightClose, "WritableStreamFinishInFlightClose");
      function WritableStreamFinishInFlightCloseWithError(stream5, error40) {
        stream5._inFlightCloseRequest._reject(error40);
        stream5._inFlightCloseRequest = void 0;
        if (stream5._pendingAbortRequest !== void 0) {
          stream5._pendingAbortRequest._reject(error40);
          stream5._pendingAbortRequest = void 0;
        }
        WritableStreamDealWithRejection(stream5, error40);
      }
      __name(WritableStreamFinishInFlightCloseWithError, "WritableStreamFinishInFlightCloseWithError");
      function WritableStreamCloseQueuedOrInFlight(stream5) {
        if (stream5._closeRequest === void 0 && stream5._inFlightCloseRequest === void 0) {
          return false;
        }
        return true;
      }
      __name(WritableStreamCloseQueuedOrInFlight, "WritableStreamCloseQueuedOrInFlight");
      function WritableStreamHasOperationMarkedInFlight(stream5) {
        if (stream5._inFlightWriteRequest === void 0 && stream5._inFlightCloseRequest === void 0) {
          return false;
        }
        return true;
      }
      __name(WritableStreamHasOperationMarkedInFlight, "WritableStreamHasOperationMarkedInFlight");
      function WritableStreamMarkCloseRequestInFlight(stream5) {
        stream5._inFlightCloseRequest = stream5._closeRequest;
        stream5._closeRequest = void 0;
      }
      __name(WritableStreamMarkCloseRequestInFlight, "WritableStreamMarkCloseRequestInFlight");
      function WritableStreamMarkFirstWriteRequestInFlight(stream5) {
        stream5._inFlightWriteRequest = stream5._writeRequests.shift();
      }
      __name(WritableStreamMarkFirstWriteRequestInFlight, "WritableStreamMarkFirstWriteRequestInFlight");
      function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream5) {
        if (stream5._closeRequest !== void 0) {
          stream5._closeRequest._reject(stream5._storedError);
          stream5._closeRequest = void 0;
        }
        const writer = stream5._writer;
        if (writer !== void 0) {
          defaultWriterClosedPromiseReject(writer, stream5._storedError);
        }
      }
      __name(WritableStreamRejectCloseAndClosedPromiseIfNeeded, "WritableStreamRejectCloseAndClosedPromiseIfNeeded");
      function WritableStreamUpdateBackpressure(stream5, backpressure) {
        const writer = stream5._writer;
        if (writer !== void 0 && backpressure !== stream5._backpressure) {
          if (backpressure) {
            defaultWriterReadyPromiseReset(writer);
          } else {
            defaultWriterReadyPromiseResolve(writer);
          }
        }
        stream5._backpressure = backpressure;
      }
      __name(WritableStreamUpdateBackpressure, "WritableStreamUpdateBackpressure");
      class WritableStreamDefaultWriter2 {
        static {
          __name(this, "WritableStreamDefaultWriter");
        }
        constructor(stream5) {
          assertRequiredArgument(stream5, 1, "WritableStreamDefaultWriter");
          assertWritableStream(stream5, "First parameter");
          if (IsWritableStreamLocked(stream5)) {
            throw new TypeError("This stream has already been locked for exclusive writing by another writer");
          }
          this._ownerWritableStream = stream5;
          stream5._writer = this;
          const state = stream5._state;
          if (state === "writable") {
            if (!WritableStreamCloseQueuedOrInFlight(stream5) && stream5._backpressure) {
              defaultWriterReadyPromiseInitialize(this);
            } else {
              defaultWriterReadyPromiseInitializeAsResolved(this);
            }
            defaultWriterClosedPromiseInitialize(this);
          } else if (state === "erroring") {
            defaultWriterReadyPromiseInitializeAsRejected(this, stream5._storedError);
            defaultWriterClosedPromiseInitialize(this);
          } else if (state === "closed") {
            defaultWriterReadyPromiseInitializeAsResolved(this);
            defaultWriterClosedPromiseInitializeAsResolved(this);
          } else {
            const storedError = stream5._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 stream5 = this._ownerWritableStream;
          if (stream5 === void 0) {
            return promiseRejectedWith(defaultWriterLockException("close"));
          }
          if (WritableStreamCloseQueuedOrInFlight(stream5)) {
            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 stream5 = this._ownerWritableStream;
          if (stream5 === 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 stream5 = writer._ownerWritableStream;
        return WritableStreamAbort(stream5, reason);
      }
      __name(WritableStreamDefaultWriterAbort, "WritableStreamDefaultWriterAbort");
      function WritableStreamDefaultWriterClose(writer) {
        const stream5 = writer._ownerWritableStream;
        return WritableStreamClose(stream5);
      }
      __name(WritableStreamDefaultWriterClose, "WritableStreamDefaultWriterClose");
      function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
        const stream5 = writer._ownerWritableStream;
        const state = stream5._state;
        if (WritableStreamCloseQueuedOrInFlight(stream5) || state === "closed") {
          return promiseResolvedWith(void 0);
        }
        if (state === "errored") {
          return promiseRejectedWith(stream5._storedError);
        }
        return WritableStreamDefaultWriterClose(writer);
      }
      __name(WritableStreamDefaultWriterCloseWithErrorPropagation, "WritableStreamDefaultWriterCloseWithErrorPropagation");
      function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error40) {
        if (writer._closedPromiseState === "pending") {
          defaultWriterClosedPromiseReject(writer, error40);
        } else {
          defaultWriterClosedPromiseResetToRejected(writer, error40);
        }
      }
      __name(WritableStreamDefaultWriterEnsureClosedPromiseRejected, "WritableStreamDefaultWriterEnsureClosedPromiseRejected");
      function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error40) {
        if (writer._readyPromiseState === "pending") {
          defaultWriterReadyPromiseReject(writer, error40);
        } else {
          defaultWriterReadyPromiseResetToRejected(writer, error40);
        }
      }
      __name(WritableStreamDefaultWriterEnsureReadyPromiseRejected, "WritableStreamDefaultWriterEnsureReadyPromiseRejected");
      function WritableStreamDefaultWriterGetDesiredSize(writer) {
        const stream5 = writer._ownerWritableStream;
        const state = stream5._state;
        if (state === "errored" || state === "erroring") {
          return null;
        }
        if (state === "closed") {
          return 0;
        }
        return WritableStreamDefaultControllerGetDesiredSize(stream5._writableStreamController);
      }
      __name(WritableStreamDefaultWriterGetDesiredSize, "WritableStreamDefaultWriterGetDesiredSize");
      function WritableStreamDefaultWriterRelease(writer) {
        const stream5 = 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);
        stream5._writer = void 0;
        writer._ownerWritableStream = void 0;
      }
      __name(WritableStreamDefaultWriterRelease, "WritableStreamDefaultWriterRelease");
      function WritableStreamDefaultWriterWrite(writer, chunk) {
        const stream5 = writer._ownerWritableStream;
        const controller = stream5._writableStreamController;
        const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
        if (stream5 !== writer._ownerWritableStream) {
          return promiseRejectedWith(defaultWriterLockException("write to"));
        }
        const state = stream5._state;
        if (state === "errored") {
          return promiseRejectedWith(stream5._storedError);
        }
        if (WritableStreamCloseQueuedOrInFlight(stream5) || state === "closed") {
          return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to"));
        }
        if (state === "erroring") {
          return promiseRejectedWith(stream5._storedError);
        }
        const promise2 = WritableStreamAddWriteRequest(stream5);
        WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
        return promise2;
      }
      __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(stream5, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
        controller._controlledWritableStream = stream5;
        stream5._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(stream5, backpressure);
        const startResult = startAlgorithm();
        const startPromise = promiseResolvedWith(startResult);
        uponPromise(startPromise, () => {
          controller._started = true;
          WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
          return null;
        }, (r5) => {
          controller._started = true;
          WritableStreamDealWithRejection(stream5, r5);
          return null;
        });
      }
      __name(SetUpWritableStreamDefaultController, "SetUpWritableStreamDefaultController");
      function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream5, 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(stream5, 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 stream5 = controller._controlledWritableStream;
        if (!WritableStreamCloseQueuedOrInFlight(stream5) && stream5._state === "writable") {
          const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
          WritableStreamUpdateBackpressure(stream5, backpressure);
        }
        WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
      }
      __name(WritableStreamDefaultControllerWrite, "WritableStreamDefaultControllerWrite");
      function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
        const stream5 = controller._controlledWritableStream;
        if (!controller._started) {
          return;
        }
        if (stream5._inFlightWriteRequest !== void 0) {
          return;
        }
        const state = stream5._state;
        if (state === "erroring") {
          WritableStreamFinishErroring(stream5);
          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, error40) {
        if (controller._controlledWritableStream._state === "writable") {
          WritableStreamDefaultControllerError(controller, error40);
        }
      }
      __name(WritableStreamDefaultControllerErrorIfNeeded, "WritableStreamDefaultControllerErrorIfNeeded");
      function WritableStreamDefaultControllerProcessClose(controller) {
        const stream5 = controller._controlledWritableStream;
        WritableStreamMarkCloseRequestInFlight(stream5);
        DequeueValue(controller);
        const sinkClosePromise = controller._closeAlgorithm();
        WritableStreamDefaultControllerClearAlgorithms(controller);
        uponPromise(sinkClosePromise, () => {
          WritableStreamFinishInFlightClose(stream5);
          return null;
        }, (reason) => {
          WritableStreamFinishInFlightCloseWithError(stream5, reason);
          return null;
        });
      }
      __name(WritableStreamDefaultControllerProcessClose, "WritableStreamDefaultControllerProcessClose");
      function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
        const stream5 = controller._controlledWritableStream;
        WritableStreamMarkFirstWriteRequestInFlight(stream5);
        const sinkWritePromise = controller._writeAlgorithm(chunk);
        uponPromise(sinkWritePromise, () => {
          WritableStreamFinishInFlightWrite(stream5);
          const state = stream5._state;
          DequeueValue(controller);
          if (!WritableStreamCloseQueuedOrInFlight(stream5) && state === "writable") {
            const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
            WritableStreamUpdateBackpressure(stream5, backpressure);
          }
          WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
          return null;
        }, (reason) => {
          if (stream5._state === "writable") {
            WritableStreamDefaultControllerClearAlgorithms(controller);
          }
          WritableStreamFinishInFlightWriteWithError(stream5, reason);
          return null;
        });
      }
      __name(WritableStreamDefaultControllerProcessWrite, "WritableStreamDefaultControllerProcessWrite");
      function WritableStreamDefaultControllerGetBackpressure(controller) {
        const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
        return desiredSize <= 0;
      }
      __name(WritableStreamDefaultControllerGetBackpressure, "WritableStreamDefaultControllerGetBackpressure");
      function WritableStreamDefaultControllerError(controller, error40) {
        const stream5 = controller._controlledWritableStream;
        WritableStreamDefaultControllerClearAlgorithms(controller);
        WritableStreamStartErroring(stream5, error40);
      }
      __name(WritableStreamDefaultControllerError, "WritableStreamDefaultControllerError");
      function streamBrandCheckException$2(name4) {
        return new TypeError(`WritableStream.prototype.${name4} can only be used on a WritableStream`);
      }
      __name(streamBrandCheckException$2, "streamBrandCheckException$2");
      function defaultControllerBrandCheckException$2(name4) {
        return new TypeError(`WritableStreamDefaultController.prototype.${name4} can only be used on a WritableStreamDefaultController`);
      }
      __name(defaultControllerBrandCheckException$2, "defaultControllerBrandCheckException$2");
      function defaultWriterBrandCheckException(name4) {
        return new TypeError(`WritableStreamDefaultWriter.prototype.${name4} can only be used on a WritableStreamDefaultWriter`);
      }
      __name(defaultWriterBrandCheckException, "defaultWriterBrandCheckException");
      function defaultWriterLockException(name4) {
        return new TypeError("Cannot " + name4 + " a stream using a released writer");
      }
      __name(defaultWriterLockException, "defaultWriterLockException");
      function defaultWriterClosedPromiseInitialize(writer) {
        writer._closedPromise = newPromise((resolve42, reject) => {
          writer._closedPromise_resolve = resolve42;
          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((resolve42, reject) => {
          writer._readyPromise_resolve = resolve42;
          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, name4) {
          this.message = message || "";
          this.name = name4 || "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((resolve42, reject) => {
          let abortAlgorithm;
          if (signal !== void 0) {
            abortAlgorithm = /* @__PURE__ */ __name(() => {
              const error40 = signal.reason !== void 0 ? signal.reason : new DOMException4("Aborted", "AbortError");
              const actions = [];
              if (!preventAbort) {
                actions.push(() => {
                  if (dest._state === "writable") {
                    return WritableStreamAbort(dest, error40);
                  }
                  return promiseResolvedWith(void 0);
                });
              }
              if (!preventCancel) {
                actions.push(() => {
                  if (source2._state === "readable") {
                    return ReadableStreamCancel(source2, error40);
                  }
                  return promiseResolvedWith(void 0);
                });
              }
              shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error40);
            }, "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, noop11);
                    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(stream5, promise2, action) {
            if (stream5._state === "errored") {
              action(stream5._storedError);
            } else {
              uponRejection(promise2, action);
            }
          }
          __name(isOrBecomesErrored, "isOrBecomesErrored");
          function isOrBecomesClosed(stream5, promise2, action) {
            if (stream5._state === "closed") {
              action();
            } else {
              uponFulfillment(promise2, 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, error40) {
            if (shuttingDown) {
              return;
            }
            shuttingDown = true;
            if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) {
              uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error40));
            } else {
              finalize(isError, error40);
            }
          }
          __name(shutdown, "shutdown");
          function finalize(isError, error40) {
            WritableStreamDefaultWriterRelease(writer);
            ReadableStreamReaderGenericRelease(reader);
            if (signal !== void 0) {
              signal.removeEventListener("abort", abortAlgorithm);
            }
            if (isError) {
              reject(error40);
            } else {
              resolve42(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 stream5 = this._controlledReadableStream;
          if (this._queue.length > 0) {
            const chunk = DequeueValue(this);
            if (this._closeRequested && this._queue.length === 0) {
              ReadableStreamDefaultControllerClearAlgorithms(this);
              ReadableStreamClose(stream5);
            } else {
              ReadableStreamDefaultControllerCallPullIfNeeded(this);
            }
            readRequest._chunkSteps(chunk);
          } else {
            ReadableStreamAddReadRequest(stream5, 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 stream5 = controller._controlledReadableStream;
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return false;
        }
        if (!controller._started) {
          return false;
        }
        if (IsReadableStreamLocked(stream5) && ReadableStreamGetNumReadRequests(stream5) > 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 stream5 = controller._controlledReadableStream;
        controller._closeRequested = true;
        if (controller._queue.length === 0) {
          ReadableStreamDefaultControllerClearAlgorithms(controller);
          ReadableStreamClose(stream5);
        }
      }
      __name(ReadableStreamDefaultControllerClose, "ReadableStreamDefaultControllerClose");
      function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
        if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
          return;
        }
        const stream5 = controller._controlledReadableStream;
        if (IsReadableStreamLocked(stream5) && ReadableStreamGetNumReadRequests(stream5) > 0) {
          ReadableStreamFulfillReadRequest(stream5, 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 stream5 = controller._controlledReadableStream;
        if (stream5._state !== "readable") {
          return;
        }
        ResetQueue(controller);
        ReadableStreamDefaultControllerClearAlgorithms(controller);
        ReadableStreamError(stream5, 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(stream5, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
        controller._controlledReadableStream = stream5;
        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;
        stream5._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(stream5, 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(stream5, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
      }
      __name(SetUpReadableStreamDefaultControllerFromUnderlyingSource, "SetUpReadableStreamDefaultControllerFromUnderlyingSource");
      function defaultControllerBrandCheckException$1(name4) {
        return new TypeError(`ReadableStreamDefaultController.prototype.${name4} can only be used on a ReadableStreamDefaultController`);
      }
      __name(defaultControllerBrandCheckException$1, "defaultControllerBrandCheckException$1");
      function ReadableStreamTee(stream5, cloneForBranch2) {
        if (IsReadableByteStreamController(stream5._readableStreamController)) {
          return ReadableByteStreamTee(stream5);
        }
        return ReadableStreamDefaultTee(stream5);
      }
      __name(ReadableStreamTee, "ReadableStreamTee");
      function ReadableStreamDefaultTee(stream5, cloneForBranch2) {
        const reader = AcquireReadableStreamDefaultReader(stream5);
        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((resolve42) => {
          resolveCancelPromise = resolve42;
        });
        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(stream5, 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(stream5, 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(stream5) {
        let reader = AcquireReadableStreamDefaultReader(stream5);
        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((resolve42) => {
          resolveCancelPromise = resolve42;
        });
        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(stream5);
            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(stream5, 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(stream5);
            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(stream5, 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(stream5, 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(stream5, 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(stream5) {
        return typeIsObject(stream5) && typeof stream5.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 stream5;
        const iteratorRecord = GetIterator(asyncIterable, "async");
        const startAlgorithm = noop11;
        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(stream5._readableStreamController);
            } else {
              const value = IteratorValue(iterResult);
              ReadableStreamDefaultControllerEnqueue(stream5._readableStreamController, value);
            }
          });
        }
        __name(pullAlgorithm, "pullAlgorithm");
        function cancelAlgorithm(reason) {
          const iterator2 = iteratorRecord.iterator;
          let returnMethod;
          try {
            returnMethod = GetMethod(iterator2, "return");
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
          if (returnMethod === void 0) {
            return promiseResolvedWith(void 0);
          }
          let returnResult;
          try {
            returnResult = reflectCall(returnMethod, iterator2, [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");
        stream5 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
        return stream5;
      }
      __name(ReadableStreamFromIterable, "ReadableStreamFromIterable");
      function ReadableStreamFromDefaultReader(reader) {
        let stream5;
        const startAlgorithm = noop11;
        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(stream5._readableStreamController);
            } else {
              const value = readResult.value;
              ReadableStreamDefaultControllerEnqueue(stream5._readableStreamController, value);
            }
          });
        }
        __name(pullAlgorithm, "pullAlgorithm");
        function cancelAlgorithm(reason) {
          try {
            return promiseResolvedWith(reader.cancel(reason));
          } catch (e4) {
            return promiseRejectedWith(e4);
          }
        }
        __name(cancelAlgorithm, "cancelAlgorithm");
        stream5 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
        return stream5;
      }
      __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 start2 = 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: start2 === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start2, 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 ReadableStream6 {
        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 promise2 = ReadableStreamPipeTo(this, transform2.writable, options2.preventClose, options2.preventAbort, options2.preventCancel, options2.signal);
          setPromiseIsHandledToTrue(promise2);
          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(ReadableStream6, {
        from: { enumerable: true }
      });
      Object.defineProperties(ReadableStream6.prototype, {
        cancel: { enumerable: true },
        getReader: { enumerable: true },
        pipeThrough: { enumerable: true },
        pipeTo: { enumerable: true },
        tee: { enumerable: true },
        values: { enumerable: true },
        locked: { enumerable: true }
      });
      setFunctionName(ReadableStream6.from, "from");
      setFunctionName(ReadableStream6.prototype.cancel, "cancel");
      setFunctionName(ReadableStream6.prototype.getReader, "getReader");
      setFunctionName(ReadableStream6.prototype.pipeThrough, "pipeThrough");
      setFunctionName(ReadableStream6.prototype.pipeTo, "pipeTo");
      setFunctionName(ReadableStream6.prototype.tee, "tee");
      setFunctionName(ReadableStream6.prototype.values, "values");
      if (typeof Symbol.toStringTag === "symbol") {
        Object.defineProperty(ReadableStream6.prototype, Symbol.toStringTag, {
          value: "ReadableStream",
          configurable: true
        });
      }
      Object.defineProperty(ReadableStream6.prototype, SymbolAsyncIterator, {
        value: ReadableStream6.prototype.values,
        writable: true,
        configurable: true
      });
      function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
        const stream5 = Object.create(ReadableStream6.prototype);
        InitializeReadableStream(stream5);
        const controller = Object.create(ReadableStreamDefaultController2.prototype);
        SetUpReadableStreamDefaultController(stream5, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
        return stream5;
      }
      __name(CreateReadableStream, "CreateReadableStream");
      function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
        const stream5 = Object.create(ReadableStream6.prototype);
        InitializeReadableStream(stream5);
        const controller = Object.create(ReadableByteStreamController2.prototype);
        SetUpReadableByteStreamController(stream5, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0);
        return stream5;
      }
      __name(CreateReadableByteStream, "CreateReadableByteStream");
      function InitializeReadableStream(stream5) {
        stream5._state = "readable";
        stream5._reader = void 0;
        stream5._storedError = void 0;
        stream5._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 ReadableStream6;
      }
      __name(IsReadableStream, "IsReadableStream");
      function IsReadableStreamLocked(stream5) {
        if (stream5._reader === void 0) {
          return false;
        }
        return true;
      }
      __name(IsReadableStreamLocked, "IsReadableStreamLocked");
      function ReadableStreamCancel(stream5, reason) {
        stream5._disturbed = true;
        if (stream5._state === "closed") {
          return promiseResolvedWith(void 0);
        }
        if (stream5._state === "errored") {
          return promiseRejectedWith(stream5._storedError);
        }
        ReadableStreamClose(stream5);
        const reader = stream5._reader;
        if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) {
          const readIntoRequests = reader._readIntoRequests;
          reader._readIntoRequests = new SimpleQueue();
          readIntoRequests.forEach((readIntoRequest) => {
            readIntoRequest._closeSteps(void 0);
          });
        }
        const sourceCancelPromise = stream5._readableStreamController[CancelSteps](reason);
        return transformPromiseWith(sourceCancelPromise, noop11);
      }
      __name(ReadableStreamCancel, "ReadableStreamCancel");
      function ReadableStreamClose(stream5) {
        stream5._state = "closed";
        const reader = stream5._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(stream5, e4) {
        stream5._state = "errored";
        stream5._storedError = e4;
        const reader = stream5._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(name4) {
        return new TypeError(`ReadableStream.prototype.${name4} can only be used on a ReadableStream`);
      }
      __name(streamBrandCheckException$1, "streamBrandCheckException$1");
      function convertQueuingStrategyInit(init2, context2) {
        assertDictionary(init2, context2);
        const highWaterMark = init2 === null || init2 === void 0 ? void 0 : init2.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(name4) {
        return new TypeError(`ByteLengthQueuingStrategy.prototype.${name4} 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(name4) {
        return new TypeError(`CountQueuingStrategy.prototype.${name4} 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 start2 = 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: start2 === void 0 ? void 0 : convertTransformerStartCallback(start2, 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((resolve42) => {
            startPromise_resolve = resolve42;
          });
          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(stream5, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
        function startAlgorithm() {
          return startPromise;
        }
        __name(startAlgorithm, "startAlgorithm");
        function writeAlgorithm(chunk) {
          return TransformStreamDefaultSinkWriteAlgorithm(stream5, chunk);
        }
        __name(writeAlgorithm, "writeAlgorithm");
        function abortAlgorithm(reason) {
          return TransformStreamDefaultSinkAbortAlgorithm(stream5, reason);
        }
        __name(abortAlgorithm, "abortAlgorithm");
        function closeAlgorithm() {
          return TransformStreamDefaultSinkCloseAlgorithm(stream5);
        }
        __name(closeAlgorithm, "closeAlgorithm");
        stream5._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
        function pullAlgorithm() {
          return TransformStreamDefaultSourcePullAlgorithm(stream5);
        }
        __name(pullAlgorithm, "pullAlgorithm");
        function cancelAlgorithm(reason) {
          return TransformStreamDefaultSourceCancelAlgorithm(stream5, reason);
        }
        __name(cancelAlgorithm, "cancelAlgorithm");
        stream5._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
        stream5._backpressure = void 0;
        stream5._backpressureChangePromise = void 0;
        stream5._backpressureChangePromise_resolve = void 0;
        TransformStreamSetBackpressure(stream5, true);
        stream5._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(stream5, e4) {
        ReadableStreamDefaultControllerError(stream5._readable._readableStreamController, e4);
        TransformStreamErrorWritableAndUnblockWrite(stream5, e4);
      }
      __name(TransformStreamError, "TransformStreamError");
      function TransformStreamErrorWritableAndUnblockWrite(stream5, e4) {
        TransformStreamDefaultControllerClearAlgorithms(stream5._transformStreamController);
        WritableStreamDefaultControllerErrorIfNeeded(stream5._writable._writableStreamController, e4);
        TransformStreamUnblockWrite(stream5);
      }
      __name(TransformStreamErrorWritableAndUnblockWrite, "TransformStreamErrorWritableAndUnblockWrite");
      function TransformStreamUnblockWrite(stream5) {
        if (stream5._backpressure) {
          TransformStreamSetBackpressure(stream5, false);
        }
      }
      __name(TransformStreamUnblockWrite, "TransformStreamUnblockWrite");
      function TransformStreamSetBackpressure(stream5, backpressure) {
        if (stream5._backpressureChangePromise !== void 0) {
          stream5._backpressureChangePromise_resolve();
        }
        stream5._backpressureChangePromise = newPromise((resolve42) => {
          stream5._backpressureChangePromise_resolve = resolve42;
        });
        stream5._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(stream5, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
        controller._controlledTransformStream = stream5;
        stream5._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(stream5, 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(stream5, 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 stream5 = controller._controlledTransformStream;
        const readableController = stream5._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(stream5, e4);
          throw stream5._readable._storedError;
        }
        const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
        if (backpressure !== stream5._backpressure) {
          TransformStreamSetBackpressure(stream5, 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 stream5 = controller._controlledTransformStream;
        const readableController = stream5._readable._readableStreamController;
        ReadableStreamDefaultControllerClose(readableController);
        const error40 = new TypeError("TransformStream terminated");
        TransformStreamErrorWritableAndUnblockWrite(stream5, error40);
      }
      __name(TransformStreamDefaultControllerTerminate, "TransformStreamDefaultControllerTerminate");
      function TransformStreamDefaultSinkWriteAlgorithm(stream5, chunk) {
        const controller = stream5._transformStreamController;
        if (stream5._backpressure) {
          const backpressureChangePromise = stream5._backpressureChangePromise;
          return transformPromiseWith(backpressureChangePromise, () => {
            const writable = stream5._writable;
            const state = writable._state;
            if (state === "erroring") {
              throw writable._storedError;
            }
            return TransformStreamDefaultControllerPerformTransform(controller, chunk);
          });
        }
        return TransformStreamDefaultControllerPerformTransform(controller, chunk);
      }
      __name(TransformStreamDefaultSinkWriteAlgorithm, "TransformStreamDefaultSinkWriteAlgorithm");
      function TransformStreamDefaultSinkAbortAlgorithm(stream5, reason) {
        const controller = stream5._transformStreamController;
        if (controller._finishPromise !== void 0) {
          return controller._finishPromise;
        }
        const readable = stream5._readable;
        controller._finishPromise = newPromise((resolve42, reject) => {
          controller._finishPromise_resolve = resolve42;
          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(stream5) {
        const controller = stream5._transformStreamController;
        if (controller._finishPromise !== void 0) {
          return controller._finishPromise;
        }
        const readable = stream5._readable;
        controller._finishPromise = newPromise((resolve42, reject) => {
          controller._finishPromise_resolve = resolve42;
          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(stream5) {
        TransformStreamSetBackpressure(stream5, false);
        return stream5._backpressureChangePromise;
      }
      __name(TransformStreamDefaultSourcePullAlgorithm, "TransformStreamDefaultSourcePullAlgorithm");
      function TransformStreamDefaultSourceCancelAlgorithm(stream5, reason) {
        const controller = stream5._transformStreamController;
        if (controller._finishPromise !== void 0) {
          return controller._finishPromise;
        }
        const writable = stream5._writable;
        controller._finishPromise = newPromise((resolve42, reject) => {
          controller._finishPromise_resolve = resolve42;
          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(stream5);
            defaultControllerFinishPromiseResolve(controller);
          }
          return null;
        }, (r5) => {
          WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r5);
          TransformStreamUnblockWrite(stream5);
          defaultControllerFinishPromiseReject(controller, r5);
          return null;
        });
        return controller._finishPromise;
      }
      __name(TransformStreamDefaultSourceCancelAlgorithm, "TransformStreamDefaultSourceCancelAlgorithm");
      function defaultControllerBrandCheckException(name4) {
        return new TypeError(`TransformStreamDefaultController.prototype.${name4} 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(name4) {
        return new TypeError(`TransformStream.prototype.${name4} can only be used on a TransformStream`);
      }
      __name(streamBrandCheckException, "streamBrandCheckException");
      exports3.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy2;
      exports3.CountQueuingStrategy = CountQueuingStrategy2;
      exports3.ReadableByteStreamController = ReadableByteStreamController2;
      exports3.ReadableStream = ReadableStream6;
      exports3.ReadableStreamBYOBReader = ReadableStreamBYOBReader2;
      exports3.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest2;
      exports3.ReadableStreamDefaultController = ReadableStreamDefaultController2;
      exports3.ReadableStreamDefaultReader = ReadableStreamDefaultReader2;
      exports3.TransformStream = TransformStream3;
      exports3.TransformStreamDefaultController = TransformStreamDefaultController2;
      exports3.WritableStream = WritableStream3;
      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 process51 = __require("node:process");
        const { emitWarning: emitWarning2 } = process51;
        try {
          process51.emitWarning = () => {
          };
          Object.assign(globalThis, __require("node:stream/web"));
          process51.emitWarning = emitWarning2;
        } catch (error40) {
          process51.emitWarning = emitWarning2;
          throw error40;
        }
      } catch (error40) {
        Object.assign(globalThis, require_ponyfill_es2018());
      }
    }
    try {
      const { Blob: Blob6 } = __require("buffer");
      if (Blob6 && !Blob6.prototype.stream) {
        Blob6.prototype.stream = /* @__PURE__ */ __name(function name4(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 (error40) {
    }
  }
});

// node_modules/fetch-blob/index.js
async function* toIterator(parts2, clone4 = true) {
  for (const part of parts2) {
    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 it3 = toIterator(this.#parts, true);
        return new globalThis.ReadableStream({
          // @ts-ignore
          type: "bytes",
          async pull(ctrl) {
            const chunk = await it3.next();
            chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value);
          },
          async cancel() {
            await it3.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(start2 = 0, end = this.size, type = "") {
        const { size } = this;
        let relativeStart = start2 < 0 ? Math.max(size + start2, 0) : Math.min(start2, size);
        let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size);
        const span = Math.max(relativeEnd - relativeStart, 0);
        const parts2 = this.#parts;
        const blobParts = [];
        let added = 0;
        for (const part of parts2) {
          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, i2, 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: i2, 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";
      }
      [i2]() {
        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 (err2) {
        err2.constructor.name === "DOMException" && (globalThis.DOMException = err2.constructor);
      }
    }
    module2.exports = globalThis.DOMException;
  }
});

// node_modules/fetch-blob/from.js
import { statSync, createReadStream, promises as fs9 } 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 } = fs9);
    blobFromSync = /* @__PURE__ */ __name((path150, type) => fromBlob(statSync(path150), path150, type), "blobFromSync");
    blobFrom = /* @__PURE__ */ __name((path150, type) => stat(path150).then((stat14) => fromBlob(stat14, path150, type)), "blobFrom");
    fileFrom = /* @__PURE__ */ __name((path150, type) => stat(path150).then((stat14) => fromFile(stat14, path150, type)), "fileFrom");
    fileFromSync = /* @__PURE__ */ __name((path150, type) => fromFile(statSync(path150), path150, type), "fileFromSync");
    fromBlob = /* @__PURE__ */ __name((stat14, path150, type = "") => new fetch_blob_default([new BlobDataItem({
      path: path150,
      size: stat14.size,
      lastModified: stat14.mtimeMs,
      start: 0
    })], { type }), "fromBlob");
    fromFile = /* @__PURE__ */ __name((stat14, path150, type = "") => new file_default([new BlobDataItem({
      path: path150,
      size: stat14.size,
      lastModified: stat14.mtimeMs,
      start: 0
    })], basename(path150), { type, lastModified: stat14.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(start2, end) {
        return new _BlobDataItem({
          path: this.#path,
          lastModified: this.lastModified,
          size: end - start2,
          start: this.#start + start2
        });
      }
      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 file2 = new file_default(entryChunks, filename, { type: contentType });
    formData.append(entryName, file2);
  }, "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 i4 = 0; i4 < boundary.length; i4++) {
          ui8a[i4] = boundary.charCodeAt(i4);
          this.boundaryChars[ui8a[i4]] = true;
        }
        this.boundary = ui8a;
        this.lookbehind = new Uint8Array(this.boundary.length + 8);
        this.state = S.START_BOUNDARY;
      }
      /**
       * @param {Uint8Array} data
       */
      write(data) {
        let i4 = 0;
        const length_ = data.length;
        let previousIndex = this.index;
        let { lookbehind, boundary, boundaryChars, index, state, flags: flags2 } = this;
        const boundaryLength = this.boundary.length;
        const boundaryEnd = boundaryLength - 1;
        const bufferLength = data.length;
        let c4;
        let cl;
        const mark = /* @__PURE__ */ __name((name4) => {
          this[name4 + "Mark"] = i4;
        }, "mark");
        const clear = /* @__PURE__ */ __name((name4) => {
          delete this[name4 + "Mark"];
        }, "clear");
        const callback = /* @__PURE__ */ __name((callbackSymbol, start2, end, ui8a) => {
          if (start2 === void 0 || start2 !== end) {
            this[callbackSymbol](ui8a && ui8a.subarray(start2, end));
          }
        }, "callback");
        const dataCallback = /* @__PURE__ */ __name((name4, clear2) => {
          const markSymbol = name4 + "Mark";
          if (!(markSymbol in this)) {
            return;
          }
          if (clear2) {
            callback(name4, this[markSymbol], i4, data);
            delete this[markSymbol];
          } else {
            callback(name4, this[markSymbol], data.length, data);
            this[markSymbol] = 0;
          }
        }, "dataCallback");
        for (i4 = 0; i4 < length_; i4++) {
          c4 = data[i4];
          switch (state) {
            case S.START_BOUNDARY:
              if (index === boundary.length - 2) {
                if (c4 === HYPHEN) {
                  flags2 |= F.LAST_BOUNDARY;
                } else if (c4 !== CR) {
                  return;
                }
                index++;
                break;
              } else if (index - 1 === boundary.length - 2) {
                if (flags2 & F.LAST_BOUNDARY && c4 === HYPHEN) {
                  state = S.END;
                  flags2 = 0;
                } else if (!(flags2 & 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) {
                i4 += boundaryEnd;
                while (i4 < bufferLength && !(data[i4] in boundaryChars)) {
                  i4 += boundaryLength;
                }
                i4 -= boundaryEnd;
                c4 = data[i4];
              }
              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) {
                  flags2 |= F.PART_BOUNDARY;
                } else if (c4 === HYPHEN) {
                  flags2 |= F.LAST_BOUNDARY;
                } else {
                  index = 0;
                }
              } else if (index - 1 === boundary.length) {
                if (flags2 & F.PART_BOUNDARY) {
                  index = 0;
                  if (c4 === LF) {
                    flags2 &= ~F.PART_BOUNDARY;
                    callback("onPartEnd");
                    callback("onPartBegin");
                    state = S.HEADER_FIELD_START;
                    break;
                  }
                } else if (flags2 & F.LAST_BOUNDARY) {
                  if (c4 === HYPHEN) {
                    callback("onPartEnd");
                    state = S.END;
                    flags2 = 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");
                i4--;
              }
              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 = flags2;
      }
      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: body2 } = data;
  if (body2 === null) {
    return Buffer2.alloc(0);
  }
  if (!(body2 instanceof Stream)) {
    return Buffer2.alloc(0);
  }
  const accum = [];
  let accumBytes = 0;
  try {
    for await (const chunk of body2) {
      if (data.size > 0 && accumBytes + chunk.length > data.size) {
        const error40 = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size");
        body2.destroy(error40);
        throw error40;
      }
      accumBytes += chunk.length;
      accum.push(chunk);
    }
  } catch (error40) {
    const error_ = error40 instanceof FetchBaseError ? error40 : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error40.message}`, "system", error40);
    throw error_;
  }
  if (body2.readableEnded === true || body2._readableState.ended === true) {
    try {
      if (accum.every((c4) => typeof c4 === "string")) {
        return Buffer2.from(accum.join(""));
      }
      return Buffer2.concat(accum, accumBytes);
    } catch (error40) {
      throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error40.message}`, "system", error40);
    }
  } 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(body2, {
        size = 0
      } = {}) {
        let boundary = null;
        if (body2 === null) {
          body2 = null;
        } else if (isURLSearchParameters(body2)) {
          body2 = Buffer2.from(body2.toString());
        } else if (isBlob(body2)) {
        } else if (Buffer2.isBuffer(body2)) {
        } else if (types.isAnyArrayBuffer(body2)) {
          body2 = Buffer2.from(body2);
        } else if (ArrayBuffer.isView(body2)) {
          body2 = Buffer2.from(body2.buffer, body2.byteOffset, body2.byteLength);
        } else if (body2 instanceof Stream) {
        } else if (body2 instanceof FormData2) {
          body2 = formDataToBlob(body2);
          boundary = body2.type.split("=")[1];
        } else {
          body2 = Buffer2.from(String(body2));
        }
        let stream5 = body2;
        if (Buffer2.isBuffer(body2)) {
          stream5 = Stream.Readable.from(body2);
        } else if (isBlob(body2)) {
          stream5 = Stream.Readable.from(body2.stream());
        }
        this[INTERNALS] = {
          body: body2,
          stream: stream5,
          boundary,
          disturbed: false,
          error: null
        };
        this.size = size;
        if (body2 instanceof Stream) {
          body2.on("error", (error_) => {
            const error40 = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
            this[INTERNALS].error = error40;
          });
        }
      }
      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 [name4, value] of parameters) {
            formData.append(name4, value);
          }
          return formData;
        }
        const { toFormData: toFormData5 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports));
        return toFormData5(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((instance2, highWaterMark) => {
      let p1;
      let p2;
      let { body: body2 } = instance2[INTERNALS];
      if (instance2.bodyUsed) {
        throw new Error("cannot clone body after it is used");
      }
      if (body2 instanceof Stream && typeof body2.getBoundary !== "function") {
        p1 = new PassThrough({ highWaterMark });
        p2 = new PassThrough({ highWaterMark });
        body2.pipe(p1);
        body2.pipe(p2);
        instance2[INTERNALS].stream = p1;
        body2 = p2;
      }
      return body2;
    }, "clone");
    getNonSpecFormDataBoundary = deprecate(
      (body2) => body2.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((body2, request4) => {
      if (body2 === null) {
        return null;
      }
      if (typeof body2 === "string") {
        return "text/plain;charset=UTF-8";
      }
      if (isURLSearchParameters(body2)) {
        return "application/x-www-form-urlencoded;charset=UTF-8";
      }
      if (isBlob(body2)) {
        return body2.type || null;
      }
      if (Buffer2.isBuffer(body2) || types.isAnyArrayBuffer(body2) || ArrayBuffer.isView(body2)) {
        return null;
      }
      if (body2 instanceof FormData2) {
        return `multipart/form-data; boundary=${request4[INTERNALS].boundary}`;
      }
      if (body2 && typeof body2.getBoundary === "function") {
        return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body2)}`;
      }
      if (body2 instanceof Stream) {
        return null;
      }
      return "text/plain;charset=UTF-8";
    }, "extractContentType");
    getTotalBytes = /* @__PURE__ */ __name((request4) => {
      const { body: body2 } = request4[INTERNALS];
      if (body2 === null) {
        return 0;
      }
      if (isBlob(body2)) {
        return body2.size;
      }
      if (Buffer2.isBuffer(body2)) {
        return body2.length;
      }
      if (body2 && typeof body2.getLengthSync === "function") {
        return body2.hasKnownLength && body2.hasKnownLength() ? body2.getLengthSync() : null;
      }
      return null;
    }, "getTotalBytes");
    writeToStream = /* @__PURE__ */ __name(async (dest, { body: body2 }) => {
      if (body2 === null) {
        dest.end();
      } else {
        await pipeline(body2, 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(([name4, value]) => {
      try {
        validateHeaderName(name4);
        validateHeaderValue(name4, 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 : (name4) => {
      if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name4)) {
        const error40 = new TypeError(`Header name must be a valid HTTP token [${name4}]`);
        Object.defineProperty(error40, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
        throw error40;
      }
    };
    validateHeaderValue = typeof http.validateHeaderValue === "function" ? http.validateHeaderValue : (name4, value) => {
      if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
        const error40 = new TypeError(`Invalid character in header content ["${name4}"]`);
        Object.defineProperty(error40, "code", { value: "ERR_INVALID_CHAR" });
        throw error40;
      }
    };
    Headers2 = class _Headers extends URLSearchParams {
      static {
        __name(this, "Headers");
      }
      /**
       * Headers class
       *
       * @constructor
       * @param {HeadersInit} [init] - Response headers
       */
      constructor(init2) {
        let result = [];
        if (init2 instanceof _Headers) {
          const raw2 = init2.raw();
          for (const [name4, values] of Object.entries(raw2)) {
            result.push(...values.map((value) => [name4, value]));
          }
        } else if (init2 == null) {
        } else if (typeof init2 === "object" && !types2.isBoxedPrimitive(init2)) {
          const method = init2[Symbol.iterator];
          if (method == null) {
            result.push(...Object.entries(init2));
          } else {
            if (typeof method !== "function") {
              throw new TypeError("Header pairs must be iterable");
            }
            result = [...init2].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(([name4, value]) => {
          validateHeaderName(name4);
          validateHeaderValue(name4, String(value));
          return [String(name4).toLowerCase(), String(value)];
        }) : void 0;
        super(result);
        return new Proxy(this, {
          get(target, p2, receiver) {
            switch (p2) {
              case "append":
              case "set":
                return (name4, value) => {
                  validateHeaderName(name4);
                  validateHeaderValue(name4, String(value));
                  return URLSearchParams.prototype[p2].call(
                    target,
                    String(name4).toLowerCase(),
                    String(value)
                  );
                };
              case "delete":
              case "has":
              case "getAll":
                return (name4) => {
                  validateHeaderName(name4);
                  return URLSearchParams.prototype[p2].call(
                    target,
                    String(name4).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(name4) {
        const values = this.getAll(name4);
        if (values.length === 0) {
          return null;
        }
        let value = values.join(", ");
        if (/^content-encoding$/i.test(name4)) {
          value = value.toLowerCase();
        }
        return value;
      }
      forEach(callback, thisArg = void 0) {
        for (const name4 of this.keys()) {
          Reflect.apply(callback, thisArg, [this.get(name4), name4, this]);
        }
      }
      *values() {
        for (const name4 of this.keys()) {
          yield this.get(name4);
        }
      }
      /**
       * @type {() => IterableIterator<[string, string]>}
       */
      *entries() {
        for (const name4 of this.keys()) {
          yield [name4, this.get(name4)];
        }
      }
      [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(body2 = null, options2 = {}) {
        super(body2, options2);
        const status = options2.status != null ? options2.status : 200;
        const headers = new Headers2(options2.headers);
        if (body2 !== null && !headers.has("Content-Type")) {
          const contentType = extractContentType(body2, 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(url3, 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(url3).toString()
          },
          status
        });
      }
      static error() {
        const response = new _Response(null, { status: 0, statusText: "" });
        response[INTERNALS2].type = "error";
        return response;
      }
      static json(data = void 0, init2 = {}) {
        const body2 = JSON.stringify(data);
        if (body2 === void 0) {
          throw new TypeError("data is not JSON serializable");
        }
        const headers = new Headers2(init2 && init2.headers);
        if (!headers.has("content-type")) {
          headers.set("content-type", "application/json");
        }
        return new _Response(body2, {
          ...init2,
          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(url3, originOnly = false) {
  if (url3 == null) {
    return "no-referrer";
  }
  url3 = new URL(url3);
  if (/^(about|blob|data):$/.test(url3.protocol)) {
    return "no-referrer";
  }
  url3.username = "";
  url3.password = "";
  url3.hash = "";
  if (originOnly) {
    url3.pathname = "";
    url3.search = "";
  }
  return url3;
}
function validateReferrerPolicy(referrerPolicy) {
  if (!ReferrerPolicy.has(referrerPolicy)) {
    throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
  }
  return referrerPolicy;
}
function isOriginPotentiallyTrustworthy(url3) {
  if (/^(http|ws)s:$/.test(url3.protocol)) {
    return true;
  }
  const hostIp = url3.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 (url3.host === "localhost" || url3.host.endsWith(".localhost")) {
    return false;
  }
  if (url3.protocol === "file:") {
    return true;
  }
  return false;
}
function isUrlPotentiallyTrustworthy(url3) {
  if (/^about:(blank|srcdoc)$/.test(url3)) {
    return true;
  }
  if (url3.protocol === "data:") {
    return true;
  }
  if (/^(blob|filesystem):$/.test(url3.protocol)) {
    return true;
  }
  return isOriginPotentiallyTrustworthy(url3);
}
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, init2 = {}) {
        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 = init2.method || input.method || "GET";
        if (/^(delete|get|head|options|post|put)$/i.test(method)) {
          method = method.toUpperCase();
        }
        if (!isRequest(init2) && "data" in init2) {
          doBadDataWarn();
        }
        if ((init2.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body");
        }
        const inputBody = init2.body ? init2.body : isRequest(input) && input.body !== null ? clone(input) : null;
        super(inputBody, {
          size: init2.size || input.size || 0
        });
        const headers = new Headers2(init2.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 init2) {
          signal = init2.signal;
        }
        if (signal != null && !isAbortSignal(signal)) {
          throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");
        }
        let referrer = init2.referrer == null ? input.referrer : init2.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: init2.redirect || input.redirect || "follow",
          headers,
          parsedURL,
          signal,
          referrer
        };
        this.follow = init2.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init2.follow;
        this.compress = init2.compress === void 0 ? input.compress === void 0 ? true : input.compress : init2.compress;
        this.counter = init2.counter || input.counter || 0;
        this.agent = init2.agent || input.agent;
        this.highWaterMark = init2.highWaterMark || input.highWaterMark || 16384;
        this.insecureHTTPParser = init2.insecureHTTPParser || input.insecureHTTPParser || false;
        this.referrerPolicy = init2.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(url3, options_) {
  return new Promise((resolve42, reject) => {
    const request4 = new Request2(url3, options_);
    const { parsedURL, options: options2 } = getNodeRequestOptions(request4);
    if (!supportedSchemas.has(parsedURL.protocol)) {
      throw new TypeError(`node-fetch cannot load ${url3}. 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 } });
      resolve42(response2);
      return;
    }
    const send = (parsedURL.protocol === "https:" ? https : http2).request;
    const { signal } = request4;
    let response = null;
    const abort2 = /* @__PURE__ */ __name(() => {
      const error40 = new AbortError("The operation was aborted.");
      reject(error40);
      if (request4.body && request4.body instanceof Stream2.Readable) {
        request4.body.destroy(error40);
      }
      if (!response || !response.body) {
        return;
      }
      response.body.emit("error", error40);
    }, "abort");
    if (signal && signal.aborted) {
      abort2();
      return;
    }
    const abortAndFinalize = /* @__PURE__ */ __name(() => {
      abort2();
      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", (error40) => {
      reject(new FetchError(`request to ${request4.url} failed, reason: ${error40.message}`, "system", error40));
      finalize();
    });
    fixResponseChunkedTransferBadEnding(request_, (error40) => {
      if (response && response.body) {
        response.body.destroy(error40);
      }
    });
    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 error40 = new Error("Premature close");
            error40.code = "ERR_STREAM_PREMATURE_CLOSE";
            response.body.emit("error", error40);
          }
        });
      });
    }
    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 name4 of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                requestOptions.headers.delete(name4);
              }
            }
            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;
            }
            resolve42(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 body2 = pump(response_, new PassThrough2(), (error40) => {
        if (error40) {
          reject(error40);
        }
      });
      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(body2, responseOptions);
        resolve42(response);
        return;
      }
      const zlibOptions2 = {
        flush: zlib.Z_SYNC_FLUSH,
        finishFlush: zlib.Z_SYNC_FLUSH
      };
      if (codings === "gzip" || codings === "x-gzip") {
        body2 = pump(body2, zlib.createGunzip(zlibOptions2), (error40) => {
          if (error40) {
            reject(error40);
          }
        });
        response = new Response2(body2, responseOptions);
        resolve42(response);
        return;
      }
      if (codings === "deflate" || codings === "x-deflate") {
        const raw2 = pump(response_, new PassThrough2(), (error40) => {
          if (error40) {
            reject(error40);
          }
        });
        raw2.once("data", (chunk) => {
          if ((chunk[0] & 15) === 8) {
            body2 = pump(body2, zlib.createInflate(), (error40) => {
              if (error40) {
                reject(error40);
              }
            });
          } else {
            body2 = pump(body2, zlib.createInflateRaw(), (error40) => {
              if (error40) {
                reject(error40);
              }
            });
          }
          response = new Response2(body2, responseOptions);
          resolve42(response);
        });
        raw2.once("end", () => {
          if (!response) {
            response = new Response2(body2, responseOptions);
            resolve42(response);
          }
        });
        return;
      }
      if (codings === "br") {
        body2 = pump(body2, zlib.createBrotliDecompress(), (error40) => {
          if (error40) {
            reject(error40);
          }
        });
        response = new Response2(body2, responseOptions);
        resolve42(response);
        return;
      }
      response = new Response2(body2, responseOptions);
      resolve42(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 error40 = new Error("Premature close");
        error40.code = "ERR_STREAM_PREMATURE_CLOSE";
        errorCallback(error40);
      }
    }, "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 randomUUID21 = /* @__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(defaults4) {
        this.defaults = defaults4 || {};
        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(...args2) {
        const input = args2[0];
        const init2 = args2[1];
        let url3 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url3 = new URL(input);
        } else if (input instanceof URL) {
          url3 = input;
        } else if (input && input.url) {
          url3 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          _a7.mergeHeaders(headers, input.headers);
        }
        if (init2) {
          _a7.mergeHeaders(headers, new Headers(init2.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init2, ...input, headers, url: url3 });
        } else {
          return this.request({ ...init2, headers, url: url3 });
        }
      }
      /**
       * 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 err2;
          if (e4 instanceof common_js_1.GaxiosError) {
            err2 = e4;
          } else if (e4 instanceof Error) {
            err2 = new common_js_1.GaxiosError(e4.message, opts, void 0, e4);
          } else {
            err2 = new common_js_1.GaxiosError("Unexpected Gaxios Error", opts, void 0, e4);
          }
          const { shouldRetry, config: config2 } = await (0, retry_js_1.getRetryConfig)(err2);
          if (shouldRetry && config2) {
            err2.config.retryConfig.currentRetryAttempt = config2.retryConfig.currentRetryAttempt;
            opts.retryConfig = err2.config?.retryConfig;
            this.#appendTimeoutToSignal(opts);
            return this._request(opts);
          }
          if (opts.errorRedactor) {
            opts.errorRedactor(err2);
          }
          throw err2;
        }
      }
      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(url3, noProxy = []) {
        const candidate = new URL(url3);
        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 url3 = opts.url instanceof URL ? opts.url : new URL(opts.url);
            for (const [key, value] of new URLSearchParams(opts.params)) {
              url3.searchParams.append(key, value);
            }
            opts.url = url3;
          }
        }
        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 randomUUID21();
          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 proxy2 = opts.proxy || process?.env?.HTTPS_PROXY || process?.env?.https_proxy || process?.env?.HTTP_PROXY || process?.env?.http_proxy;
        if (opts.agent) {
        } else if (proxy2 && this.#urlMayUseProxy(opts.url, opts.noProxy)) {
          const HttpsProxyAgent3 = await _a7.#getProxyAgent();
          if (this.agentCache.has(proxy2)) {
            opts.agent = this.agentCache.get(proxy2);
          } else {
            opts.agent = new HttpsProxyAgent3(proxy2, {
              cert: opts.cert,
              key: opts.key
            });
            this.agentCache.set(proxy2, 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_dist3()))).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, ...append3) {
        base = base instanceof Headers ? base : new Headers(base);
        for (const headers of append3) {
          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: ""
        }, ALPHABET2 = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true;
        function BigNumber2(v2, b2) {
          var alphabet2, c4, caseChanged, e4, i4, 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, i4 = v2; i4 >= 10; i4 /= 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 ((i4 = str2.search(/e/i)) > 0) {
              if (e4 < 0) e4 = i4;
              e4 += +str2.slice(i4 + 1);
              str2 = str2.substring(0, i4);
            } else if (e4 < 0) {
              e4 = str2.length;
            }
          } else {
            intCheck(b2, 2, ALPHABET2.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 = ALPHABET2.slice(0, b2);
            e4 = i4 = 0;
            for (len = str2.length; i4 < len; i4++) {
              if (alphabet2.indexOf(c4 = str2.charAt(i4)) < 0) {
                if (c4 == ".") {
                  if (i4 > e4) {
                    e4 = len;
                    continue;
                  }
                } else if (!caseChanged) {
                  if (str2 == str2.toUpperCase() && (str2 = str2.toLowerCase()) || str2 == str2.toLowerCase() && (str2 = str2.toUpperCase())) {
                    caseChanged = true;
                    i4 = -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 (i4 = 0; str2.charCodeAt(i4) === 48; i4++) ;
          for (len = str2.length; str2.charCodeAt(--len) === 48; ) ;
          if (str2 = str2.slice(i4, ++len)) {
            len -= i4;
            if (isNum && BigNumber2.DEBUG && len > 15 && (v2 > MAX_SAFE_INTEGER || v2 !== mathfloor(v2))) {
              throw Error(tooManyDigits + x3.s * v2);
            }
            if ((e4 = e4 - i4 - 1) > MAX_EXP) {
              x3.c = x3.e = null;
            } else if (e4 < MIN_EXP) {
              x3.c = [x3.e = 0];
            } else {
              x3.e = e4;
              x3.c = [];
              i4 = (e4 + 1) % LOG_BASE;
              if (e4 < 0) i4 += LOG_BASE;
              if (i4 < len) {
                if (i4) x3.c.push(+str2.slice(0, i4));
                for (len -= LOG_BASE; i4 < len; ) {
                  x3.c.push(+str2.slice(i4, i4 += LOG_BASE));
                }
                i4 = LOG_BASE - (str2 = str2.slice(i4)).length;
              } else {
                i4 -= len;
              }
              for (; i4--; 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";
                  ALPHABET2 = 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: ALPHABET2
          };
        };
        BigNumber2.isBigNumber = function(v2) {
          if (!v2 || v2._isBigNumber !== true) return false;
          if (!BigNumber2.DEBUG) return true;
          var i4, 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;
              }
              i4 = (e4 + 1) % LOG_BASE;
              if (i4 < 1) i4 += LOG_BASE;
              if (String(c4[0]).length == i4) {
                for (i4 = 0; i4 < c4.length; i4++) {
                  n3 = c4[i4];
                  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, i4 = 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 (; i4 < k2; ) {
                  v2 = a2[i4] * 131072 + (a2[i4 + 1] >>> 11);
                  if (v2 >= 9e15) {
                    b2 = crypto.getRandomValues(new Uint32Array(2));
                    a2[i4] = b2[0];
                    a2[i4 + 1] = b2[1];
                  } else {
                    c4.push(v2 % 1e14);
                    i4 += 2;
                  }
                }
                i4 = k2 / 2;
              } else if (crypto.randomBytes) {
                a2 = crypto.randomBytes(k2 *= 7);
                for (; i4 < k2; ) {
                  v2 = (a2[i4] & 31) * 281474976710656 + a2[i4 + 1] * 1099511627776 + a2[i4 + 2] * 4294967296 + a2[i4 + 3] * 16777216 + (a2[i4 + 4] << 16) + (a2[i4 + 5] << 8) + a2[i4 + 6];
                  if (v2 >= 9e15) {
                    crypto.randomBytes(7).copy(a2, i4);
                  } else {
                    c4.push(v2 % 1e14);
                    i4 += 7;
                  }
                }
                i4 = k2 / 7;
              } else {
                CRYPTO = false;
                throw Error(bignumberError + "crypto unavailable");
              }
            }
            if (!CRYPTO) {
              for (; i4 < k2; ) {
                v2 = random53bitInt();
                if (v2 < 9e15) c4[i4++] = v2 % 1e14;
              }
            }
            k2 = c4[--i4];
            dp %= LOG_BASE;
            if (k2 && dp) {
              v2 = POWS_TEN[LOG_BASE - dp];
              c4[i4] = mathfloor(k2 / v2) * v2;
            }
            for (; c4[i4] === 0; c4.pop(), i4--) ;
            if (i4 < 0) {
              c4 = [e4 = 0];
            } else {
              for (e4 = -1; c4[0] === 0; c4.splice(0, 1), e4 -= LOG_BASE) ;
              for (i4 = 1, v2 = c4[0]; v2 >= 10; v2 /= 10, i4++) ;
              if (i4 < LOG_BASE) e4 -= LOG_BASE - i4;
            }
            rand.e = e4;
            rand.c = c4;
            return rand;
          };
        }();
        BigNumber2.sum = function() {
          var i4 = 1, args2 = arguments, sum = new BigNumber2(args2[0]);
          for (; i4 < args2.length; ) sum = sum.plus(args2[i4++]);
          return sum;
        };
        convertBase = /* @__PURE__ */ function() {
          var decimal = "0123456789";
          function toBaseOut(str2, baseIn, baseOut, alphabet2) {
            var j2, arr = [0], arrL, i4 = 0, len = str2.length;
            for (; i4 < len; ) {
              for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) ;
              arr[0] += alphabet2.indexOf(str2.charAt(i4++));
              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, i4 = str2.indexOf("."), dp = DECIMAL_PLACES, rm7 = ROUNDING_MODE;
            if (i4 >= 0) {
              k2 = POW_PRECISION;
              POW_PRECISION = 0;
              str2 = str2.replace(".", "");
              y2 = new BigNumber2(baseIn);
              x3 = y2.pow(str2.length - i4);
              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 = ALPHABET2, decimal) : (alphabet2 = decimal, ALPHABET2));
            e4 = k2 = xc.length;
            for (; xc[--k2] == 0; xc.pop()) ;
            if (!xc[0]) return alphabet2.charAt(0);
            if (i4 < 0) {
              --e4;
            } else {
              x3.c = xc;
              x3.e = e4;
              x3.s = sign;
              x3 = div(x3, y2, dp, rm7, baseOut);
              xc = x3.c;
              r5 = x3.r;
              e4 = x3.e;
            }
            d2 = e4 + dp + 1;
            i4 = xc[d2];
            k2 = baseOut / 2;
            r5 = r5 || d2 < 0 || xc[d2 + 1] != null;
            r5 = rm7 < 4 ? (i4 != null || r5) && (rm7 == 0 || rm7 == (x3.s < 0 ? 3 : 2)) : i4 > k2 || i4 == k2 && (rm7 == 4 || r5 || rm7 == 6 && xc[d2 - 1] & 1 || rm7 == (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 (i4 = 0, str2 = ""; i4 <= k2; str2 += alphabet2.charAt(xc[i4++])) ;
              str2 = toFixedPoint(str2, e4, alphabet2.charAt(0));
            }
            return str2;
          };
        }();
        div = /* @__PURE__ */ function() {
          function multiply(x3, k2, base) {
            var m3, temp, xlo, xhi, carry = 0, i4 = x3.length, klo = k2 % SQRT_BASE, khi = k2 / SQRT_BASE | 0;
            for (x3 = x3.slice(); i4--; ) {
              xlo = x3[i4] % SQRT_BASE;
              xhi = x3[i4] / 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[i4] = temp % base;
            }
            if (carry) x3 = [carry].concat(x3);
            return x3;
          }
          __name(multiply, "multiply");
          function compare2(a2, b2, aL, bL) {
            var i4, cmp;
            if (aL != bL) {
              cmp = aL > bL ? 1 : -1;
            } else {
              for (i4 = cmp = 0; i4 < aL; i4++) {
                if (a2[i4] != b2[i4]) {
                  cmp = a2[i4] > b2[i4] ? 1 : -1;
                  break;
                }
              }
            }
            return cmp;
          }
          __name(compare2, "compare");
          function subtract(a2, b2, aL, base) {
            var i4 = 0;
            for (; aL--; ) {
              a2[aL] -= i4;
              i4 = a2[aL] < b2[aL] ? 1 : 0;
              a2[aL] = i4 * base + a2[aL] - b2[aL];
            }
            for (; !a2[0] && a2.length > 1; a2.splice(0, 1)) ;
          }
          __name(subtract, "subtract");
          return function(x3, y2, dp, rm7, base) {
            var cmp, e4, i4, 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 (i4 = 0; yc[i4] == (xc[i4] || 0); i4++) ;
            if (yc[i4] > (xc[i4] || 0)) e4--;
            if (s5 < 0) {
              qc.push(1);
              more = true;
            } else {
              xL = xc.length;
              yL = yc.length;
              i4 = 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[i4++] = 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 (i4 = 1, s5 = qc[0]; s5 >= 10; s5 /= 10, i4++) ;
              round(q2, dp + (q2.e = i4 + e4 * LOG_BASE - 1) + 1, rm7, more);
            } else {
              q2.e = e4;
              q2.r = +more;
            }
            return q2;
          };
        }();
        function format4(n3, i4, rm7, id) {
          var c0, e4, ne2, len, str2;
          if (rm7 == null) rm7 = ROUNDING_MODE;
          else intCheck(rm7, 0, 8);
          if (!n3.c) return n3.toString();
          c0 = n3.c[0];
          ne2 = n3.e;
          if (i4 == 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), i4, rm7);
            e4 = n3.e;
            str2 = coeffToString(n3.c);
            len = str2.length;
            if (id == 1 || id == 2 && (i4 <= e4 || e4 <= TO_EXP_NEG)) {
              for (; len < i4; str2 += "0", len++) ;
              str2 = toExponential(str2, e4);
            } else {
              i4 -= ne2;
              str2 = toFixedPoint(str2, e4, "0");
              if (e4 + 1 > len) {
                if (--i4 > 0) for (str2 += "."; i4--; str2 += "0") ;
              } else {
                i4 += e4 - len;
                if (i4 > 0) {
                  if (e4 + 1 == len) str2 += ".";
                  for (; i4--; str2 += "0") ;
                }
              }
            }
          }
          return n3.s < 0 && c0 ? "-" + str2 : str2;
        }
        __name(format4, "format");
        function maxOrMin(args2, n3) {
          var k2, y2, i4 = 1, x3 = new BigNumber2(args2[0]);
          for (; i4 < args2.length; i4++) {
            y2 = new BigNumber2(args2[i4]);
            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 i4 = 1, j2 = c4.length;
          for (; !c4[--j2]; c4.pop()) ;
          for (j2 = c4[0]; j2 >= 10; j2 /= 10, i4++) ;
          if ((e4 = i4 + 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, rm7, r5) {
          var d2, i4, 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++) ;
              i4 = sd - d2;
              if (i4 < 0) {
                i4 += LOG_BASE;
                j2 = sd;
                n3 = xc[ni = 0];
                rd = mathfloor(n3 / pows10[d2 - j2 - 1] % 10);
              } else {
                ni = mathceil((i4 + 1) / LOG_BASE);
                if (ni >= xc.length) {
                  if (r5) {
                    for (; xc.length <= ni; xc.push(0)) ;
                    n3 = rd = 0;
                    d2 = 1;
                    i4 %= LOG_BASE;
                    j2 = i4 - LOG_BASE + 1;
                  } else {
                    break out;
                  }
                } else {
                  n3 = k2 = xc[ni];
                  for (d2 = 1; k2 >= 10; k2 /= 10, d2++) ;
                  i4 %= LOG_BASE;
                  j2 = i4 - 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 = rm7 < 4 ? (rd || r5) && (rm7 == 0 || rm7 == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm7 == 4 || r5 || rm7 == 6 && // Check whether the digit to the left of the rounding digit is odd.
              (i4 > 0 ? j2 > 0 ? n3 / pows10[d2 - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm7 == (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 (i4 == 0) {
                xc.length = ni;
                k2 = 1;
                ni--;
              } else {
                xc.length = ni + 1;
                k2 = pows10[LOG_BASE - i4];
                xc[ni] = j2 > 0 ? mathfloor(n3 / pows10[d2 - j2] % pows10[j2]) * k2 : 0;
              }
              if (r5) {
                for (; ; ) {
                  if (ni == 0) {
                    for (i4 = 1, j2 = xc[0]; j2 >= 10; j2 /= 10, i4++) ;
                    j2 = xc[0] += k2;
                    for (k2 = 1; j2 >= 10; j2 /= 10, k2++) ;
                    if (i4 != 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 (i4 = xc.length; xc[--i4] === 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, rm7) {
          var c4, n3, v2, x3 = this;
          if (dp != null) {
            intCheck(dp, 0, MAX2);
            if (rm7 == null) rm7 = ROUNDING_MODE;
            else intCheck(rm7, 0, 8);
            return round(new BigNumber2(x3), dp + x3.e + 1, rm7);
          }
          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, i4, 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 {
            i4 = Math.abs(+valueOf(n3));
            nIsOdd = i4 % 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 (i4) {
              i4 = mathfloor(i4 / 2);
              if (i4 === 0) break;
              nIsOdd = i4 % 2;
            } else {
              n3 = n3.times(half);
              round(n3, n3.e + 1, 1);
              if (n3.e > 14) {
                nIsOdd = isOdd(n3);
              } else {
                i4 = +valueOf(n3);
                if (i4 === 0) break;
                nIsOdd = i4 % 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(rm7) {
          var n3 = new BigNumber2(this);
          if (rm7 == null) rm7 = ROUNDING_MODE;
          else intCheck(rm7, 0, 8);
          return round(n3, n3.e + 1, rm7);
        };
        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 i4, 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) - (i4 = xc.length);
          if (b2 > 0) for (; b2--; xc[i4++] = 0) ;
          b2 = BASE - 1;
          for (; j2 > a2; ) {
            if (xc[--j2] < yc[j2]) {
              for (i4 = j2; i4 && !xc[--i4]; xc[i4] = b2) ;
              --xc[i4];
              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, i4, 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;
            i4 = xcL;
            xcL = ycL;
            ycL = i4;
          }
          for (i4 = xcL + ycL, zc = []; i4--; zc.push(0)) ;
          base = BASE;
          sqrtBase = SQRT_BASE;
          for (i4 = ycL; --i4 >= 0; ) {
            c4 = 0;
            ylo = yc[i4] % sqrtBase;
            yhi = yc[i4] / sqrtBase | 0;
            for (k2 = xcL, j2 = i4 + k2; j2 > i4; ) {
              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, rm7) {
          var c4, n3, v2, x3 = this;
          if (sd != null && sd !== !!sd) {
            intCheck(sd, 1, MAX2);
            if (rm7 == null) rm7 = ROUNDING_MODE;
            else intCheck(rm7, 0, 8);
            return round(new BigNumber2(x3), sd, rm7);
          }
          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, rm7) {
          if (dp != null) {
            intCheck(dp, 0, MAX2);
            dp++;
          }
          return format4(this, dp, rm7, 1);
        };
        P2.toFixed = function(dp, rm7) {
          if (dp != null) {
            intCheck(dp, 0, MAX2);
            dp = dp + this.e + 1;
          }
          return format4(this, dp, rm7);
        };
        P2.toFormat = function(dp, rm7, format5) {
          var str2, x3 = this;
          if (format5 == null) {
            if (dp != null && rm7 && typeof rm7 == "object") {
              format5 = rm7;
              rm7 = null;
            } else if (dp && typeof dp == "object") {
              format5 = dp;
              dp = rm7 = null;
            } else {
              format5 = FORMAT;
            }
          } else if (typeof format5 != "object") {
            throw Error(bignumberError + "Argument not an object: " + format5);
          }
          str2 = x3.toFixed(dp, rm7);
          if (x3.c) {
            var i4, 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) {
              i4 = g1;
              g1 = g2;
              g2 = i4;
              len -= i4;
            }
            if (g1 > 0 && len > 0) {
              i4 = len % g1 || g1;
              intPart = intDigits.substr(0, i4);
              for (; i4 < len; i4 += g1) intPart += groupSeparator + intDigits.substr(i4, g1);
              if (g2 > 0) intPart += groupSeparator + intDigits.slice(i4);
              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, rm7) {
          if (sd != null) intCheck(sd, 1, MAX2);
          return format4(this, sd, rm7, 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, ALPHABET2.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 i4 = n3 | 0;
        return n3 > 0 || n3 === i4 ? i4 : i4 - 1;
      }
      __name(bitFloor, "bitFloor");
      function coeffToString(a2) {
        var s5, z2, i4 = 1, j2 = a2.length, r5 = a2[0] + "";
        for (; i4 < j2; ) {
          s5 = a2[i4++] + "";
          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, i4 = x3.s, j2 = y2.s, k2 = x3.e, l3 = y2.e;
        if (!i4 || !j2) return null;
        a2 = xc && !xc[0];
        b2 = yc && !yc[0];
        if (a2 || b2) return a2 ? b2 ? 0 : -j2 : i4;
        if (i4 != j2) return i4;
        a2 = i4 < 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 (i4 = 0; i4 < j2; i4++) if (xc[i4] != yc[i4]) return xc[i4] > yc[i4] ^ a2 ? 1 : -1;
        return k2 == l3 ? 0 : k2 > l3 ^ a2 ? 1 : -1;
      }
      __name(compare, "compare");
      function intCheck(n3, min, max, name4) {
        if (n3 < min || n3 > max || n3 !== mathfloor(n3)) {
          throw Error(bignumberError + (name4 || "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 i4, 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 (i4 = 0; i4 < length; i4 += 1) {
                partial2[i4] = str2(i4, 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 (i4 = 0; i4 < length; i4 += 1) {
                if (typeof rep[i4] === "string") {
                  k2 = rep[i4];
                  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 i4;
          gap = "";
          indent = "";
          if (typeof space === "number") {
            for (i4 = 0; i4 < space; i4 += 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, error40 = /* @__PURE__ */ __name(function(m3) {
        throw {
          name: "SyntaxError",
          message: m3,
          at: at2,
          text
        };
      }, "error"), next = /* @__PURE__ */ __name(function(c4) {
        if (c4 && c4 !== ch) {
          error40("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)) {
          error40("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, i4, 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 (i4 = 0; i4 < 4; i4 += 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;
            }
          }
        }
        error40("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;
        }
        error40("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();
          }
        }
        error40("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)) {
              error40('Duplicate key "' + key + '"');
            }
            if (suspectProtoRx.test(key) === true) {
              if (_options.protoAction === "error") {
                error40("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") {
                error40("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();
          }
        }
        error40("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) {
          error40("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(stream5) {
        return stream5 && // May happen in browsers.
        stream5.isTTY && (typeof stream5.getColorDepth === "function" ? stream5.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), i4 = 0; i4 < k2.length; i4++) if (k2[i4] !== "default") __createBinding(result, mod2, k2[i4]);
        }
        __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 process51 = __importStar(__require("process"));
    var util5 = __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 = (...args2) => this.invokeSeverity(LogSeverity.DEBUG, ...args2);
        this.func.info = (...args2) => this.invokeSeverity(LogSeverity.INFO, ...args2);
        this.func.warn = (...args2) => this.invokeSeverity(LogSeverity.WARNING, ...args2);
        this.func.error = (...args2) => this.invokeSeverity(LogSeverity.ERROR, ...args2);
        this.func.sublog = (namespace2) => log(namespace2, this.func);
      }
      invoke(fields, ...args2) {
        if (this.upstream) {
          try {
            this.upstream(fields, ...args2);
          } catch (e4) {
          }
        }
        try {
          this.emit("log", fields, args2);
        } catch (e4) {
        }
      }
      invokeSeverity(severity, ...args2) {
        this.invoke({ severity }, ...args2);
      }
    };
    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 = process51.env[exports2.env.nodeEnables]) !== null && _a7 !== void 0 ? _a7 : "*";
        if (nodeFlag === "all") {
          nodeFlag = "*";
        }
        this.filters = nodeFlag.split(",");
      }
      log(namespace, fields, ...args2) {
        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, ...args2);
        } 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, ...args2) => {
          var _a7;
          const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`;
          const pid = `${colours_1.Colours.yellow}${process51.pid}${colours_1.Colours.reset}`;
          let level;
          switch (fields.severity) {
            case LogSeverity.ERROR:
              level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`;
              break;
            case LogSeverity.INFO:
              level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`;
              break;
            case LogSeverity.WARNING:
              level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`;
              break;
            default:
              level = (_a7 = fields.severity) !== null && _a7 !== void 0 ? _a7 : LogSeverity.DEFAULT;
              break;
          }
          const msg = util5.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args2);
          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 debugLogger174 = this.debugPkg(namespace);
        return (fields, ...args2) => {
          debugLogger174(args2[0], ...args2.slice(1));
        };
      }
      setFilters() {
        var _a7;
        const existingFilters = (_a7 = process51.env["NODE_DEBUG"]) !== null && _a7 !== void 0 ? _a7 : "";
        process51.env["NODE_DEBUG"] = `${existingFilters}${existingFilters ? "," : ""}${this.filters.join(",")}`;
      }
    };
    function getDebugBackend(debugPkg) {
      return new DebugBackend(debugPkg);
    }
    __name(getDebugBackend, "getDebugBackend");
    var StructuredBackend = class extends DebugLogBackendBase {
      static {
        __name(this, "StructuredBackend");
      }
      constructor(upstream) {
        var _a7;
        super();
        this.upstream = (_a7 = upstream) !== null && _a7 !== void 0 ? _a7 : void 0;
      }
      makeLogger(namespace) {
        var _a7;
        const debugLogger174 = (_a7 = this.upstream) === null || _a7 === void 0 ? void 0 : _a7.makeLogger(namespace);
        return (fields, ...args2) => {
          var _a8;
          const severity = (_a8 = fields.severity) !== null && _a8 !== void 0 ? _a8 : LogSeverity.INFO;
          const json3 = Object.assign({
            severity,
            message: util5.format(...args2)
          }, fields);
          const jsonString = JSON.stringify(json3);
          if (debugLogger174) {
            debugLogger174(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 = process51.env[exports2.env.nodeEnables];
        if (!enablesFlag) {
          return exports2.placeholder;
        }
      }
      if (!namespace) {
        return exports2.placeholder;
      }
      if (parent) {
        namespace = `${parent.instance.namespace}:${namespace}`;
      }
      const existing = loggerCache.get(namespace);
      if (existing) {
        return existing.func;
      }
      if (cachedBackend === null) {
        return exports2.placeholder;
      } else if (cachedBackend === void 0) {
        cachedBackend = getNodeBackend();
      }
      const logger6 = (() => {
        let previousBackend = void 0;
        const newLogger = new AdhocDebugLogger(namespace, (fields, ...args2) => {
          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, ...args2);
        });
        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), i4 = 0; i4 < k2.length; i4++) if (k2[i4] !== "default") __createBinding(result, mod2, k2[i4]);
        }
        __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 = instance2;
    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 instance2(options2) {
      return metadataAccessor("instance", options2);
    }
    __name(instance2, "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 err2 = e4;
        if (process.env.DEBUG_AUTH) {
          console.info(err2);
        }
        if (err2.type === "request-timeout") {
          return false;
        }
        if (err2.response && err2.response.status === 404) {
          return false;
        } else {
          if (!(err2.response && err2.response.status === 404) && // A warning is emitted if we see an unexpected err.code, or err.code
          // is not populated:
          (!err2.code || ![
            "EHOSTDOWN",
            "EHOSTUNREACH",
            "ENETUNREACH",
            "ENOENT",
            "ENOTFOUND",
            "ECONNREFUSED"
          ].includes(err2.code.toString()))) {
            let code2 = "UNKNOWN";
            if (err2.code)
              code2 = err2.code.toString();
            process.emitWarning(`received unexpected error = ${err2.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 lookup2 = [];
    var revLookup = [];
    var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
    var code2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for (i4 = 0, len = code2.length; i4 < len; ++i4) {
      lookup2[i4] = code2[i4];
      revLookup[code2.charCodeAt(i4)] = i4;
    }
    var i4;
    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 i5;
      for (i5 = 0; i5 < len2; i5 += 4) {
        tmp = revLookup[b64.charCodeAt(i5)] << 18 | revLookup[b64.charCodeAt(i5 + 1)] << 12 | revLookup[b64.charCodeAt(i5 + 2)] << 6 | revLookup[b64.charCodeAt(i5 + 3)];
        arr[curByte++] = tmp >> 16 & 255;
        arr[curByte++] = tmp >> 8 & 255;
        arr[curByte++] = tmp & 255;
      }
      if (placeHoldersLen === 2) {
        tmp = revLookup[b64.charCodeAt(i5)] << 2 | revLookup[b64.charCodeAt(i5 + 1)] >> 4;
        arr[curByte++] = tmp & 255;
      }
      if (placeHoldersLen === 1) {
        tmp = revLookup[b64.charCodeAt(i5)] << 10 | revLookup[b64.charCodeAt(i5 + 1)] << 4 | revLookup[b64.charCodeAt(i5 + 2)] >> 2;
        arr[curByte++] = tmp >> 8 & 255;
        arr[curByte++] = tmp & 255;
      }
      return arr;
    }
    __name(toByteArray, "toByteArray");
    function tripletToBase64(num) {
      return lookup2[num >> 18 & 63] + lookup2[num >> 12 & 63] + lookup2[num >> 6 & 63] + lookup2[num & 63];
    }
    __name(tripletToBase64, "tripletToBase64");
    function encodeChunk(uint8, start2, end) {
      var tmp;
      var output = [];
      for (var i5 = start2; i5 < end; i5 += 3) {
        tmp = (uint8[i5] << 16 & 16711680) + (uint8[i5 + 1] << 8 & 65280) + (uint8[i5 + 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 parts2 = [];
      var maxChunkLength = 16383;
      for (var i5 = 0, len22 = len2 - extraBytes; i5 < len22; i5 += maxChunkLength) {
        parts2.push(encodeChunk(uint8, i5, i5 + maxChunkLength > len22 ? len22 : i5 + maxChunkLength));
      }
      if (extraBytes === 1) {
        tmp = uint8[len2 - 1];
        parts2.push(
          lookup2[tmp >> 2] + lookup2[tmp << 4 & 63] + "=="
        );
      } else if (extraBytes === 2) {
        tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
        parts2.push(
          lookup2[tmp >> 10] + lookup2[tmp >> 4 & 63] + lookup2[tmp << 2 & 63] + "="
        );
      }
      return parts2.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 inputBuffer2 = new TextEncoder().encode(str2);
        const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer2);
        return base64js.fromByteArray(new Uint8Array(outputBuffer));
      }
      randomBytesBase64(count) {
        const array2 = new Uint8Array(count);
        window.crypto.getRandomValues(array2);
        return base64js.fromByteArray(array2);
      }
      static padBase64(base643) {
        while (base643.length % 4 !== 0) {
          base643 += "=";
        }
        return base643;
      }
      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(base643) {
        const uint8array = base64js.toByteArray(_BrowserCrypto.padBase64(base643));
        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 inputBuffer2 = new TextEncoder().encode(str2);
        const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer2);
        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 crypto18 = __require("crypto");
    var NodeCrypto = class {
      static {
        __name(this, "NodeCrypto");
      }
      async sha256DigestBase64(str2) {
        return crypto18.createHash("sha256").update(str2).digest("base64");
      }
      randomBytesBase64(count) {
        return crypto18.randomBytes(count).toString("base64");
      }
      async verify(pubkey, data, signature) {
        const verifier = crypto18.createVerify("RSA-SHA256");
        verifier.update(data);
        verifier.end();
        return verifier.verify(pubkey, signature, "base64");
      }
      async sign(privateKey, data) {
        const signer = crypto18.createSign("RSA-SHA256");
        signer.update(data);
        signer.end();
        return signer.sign(privateKey, "base64");
      }
      decodeBase64StringUtf8(base643) {
        return Buffer.from(base643, "base64").toString("utf-8");
      }
      encodeBase64StringUtf8(text) {
        return Buffer.from(text, "utf-8").toString("base64");
      }
      /**
       * Computes the SHA-256 hash of the provided string.
       * @param str The plain text string to hash.
       * @return A promise that resolves with the SHA-256 hash of the provided
       *   string in hexadecimal encoding.
       */
      async sha256DigestHex(str2) {
        return crypto18.createHash("sha256").update(str2).digest("hex");
      }
      /**
       * Computes the HMAC hash of a message using the provided crypto key and the
       * SHA-256 algorithm.
       * @param key The secret crypto key in utf-8 or ArrayBuffer format.
       * @param msg The plain text message.
       * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
       *   format.
       */
      async signWithHmacSha256(key, msg) {
        const cryptoKey = typeof key === "string" ? key : toBuffer(key);
        return toArrayBuffer(crypto18.createHmac("sha256", cryptoKey).update(msg).digest());
      }
    };
    exports2.NodeCrypto = NodeCrypto;
    function toArrayBuffer(buffer) {
      return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
    }
    __name(toArrayBuffer, "toArrayBuffer");
    function toBuffer(arrayBuffer) {
      return Buffer.from(arrayBuffer);
    }
    __name(toBuffer, "toBuffer");
  }
});

// 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(base643) {
      return base643.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, start2, stop3) {
      var padding = 0;
      while (start2 + padding < stop3 && buf[start2 + padding] === 0) {
        ++padding;
      }
      var needsSign = buf[start2 + 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_util12 = __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 fs142 = __require("fs");
    var os59 = __require("os");
    var path150 = __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 fs142.promises.lstat(filePath);
        return stats.isFile();
      } catch (e4) {
        return false;
      }
    }
    __name(isValidFile, "isValidFile");
    function getWellKnownCertificateConfigFileLocation() {
      const configDir = process.env.CLOUDSDK_CONFIG || (_isWindows() ? path150.join(process.env.APPDATA || "", CLOUDSDK_CONFIG_DIRECTORY) : path150.join(process.env.HOME || "", ".config", CLOUDSDK_CONFIG_DIRECTORY));
      return path150.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);
    }
    __name(getWellKnownCertificateConfigFileLocation, "getWellKnownCertificateConfigFileLocation");
    function _isWindows() {
      return os59.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_util12();
    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(...args2) {
        const input = args2[0];
        const init2 = args2[1];
        let url3 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url3 = new URL(input);
        } else if (input instanceof URL) {
          url3 = input;
        } else if (input && input.url) {
          url3 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          gaxios_1.Gaxios.mergeHeaders(headers, input.headers);
        }
        if (init2) {
          gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init2.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init2, ...input, headers, url: url3 });
        } else {
          return this.request({ ...init2, headers, url: url3 });
        }
      }
      /**
       * 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 (error40) => {
          try {
            const symbols = error40.config;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = symbols[_AuthClient.RequestLogIdSymbol];
            if (methodName) {
              _AuthClient.log.info("%s [%s] error %j", methodName, logId, error40.response?.data);
            } else {
              _AuthClient.log.error("[%s] error %j", logId, error40.response?.data);
            }
          } catch (e4) {
          }
          throw error40;
        }, "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(env6, pay) {
        this.envelope = env6;
        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 stream5 = __require("stream");
    var formatEcdsa = require_ecdsa_sig_formatter();
    var util_1 = require_util12();
    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 crypto18 = (0, crypto_1.createCrypto)();
        const randomString2 = crypto18.randomBytesBase64(96);
        const codeVerifier = randomString2.replace(/\+/g, "~").replace(/=/g, "_").replace(/\//g, "-");
        const unencodedCodeChallenge = await crypto18.sha256DigestBase64(codeVerifier);
        const codeChallenge = unencodedCodeChallenge.split("=")[0].replace(/\+/g, "-").replace(/\//g, "_");
        return { codeVerifier, codeChallenge };
      }
      getToken(codeOrOptions, callback) {
        const options2 = typeof codeOrOptions === "string" ? { code: codeOrOptions } : codeOrOptions;
        if (callback) {
          this.getTokenAsync(options2).then((r5) => callback(null, r5.tokens, r5.res), (e4) => callback(e4, null, e4.response));
        } else {
          return this.getTokenAsync(options2);
        }
      }
      async getTokenAsync(options2) {
        const url3 = 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: url3,
          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 url3 = 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: url3,
            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(url3) {
        const headers = (await this.getRequestMetadataAsync(url3)).headers;
        return headers;
      }
      async getRequestMetadataAsync(url3) {
        url3;
        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 (err2) {
          const e4 = err2;
          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 url3 = new URL(this.endpoints.oauth2RevokeUrl);
        url3.searchParams.append("token", token2);
        return url3;
      }
      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 isReadableStream2 = res.config.data instanceof stream5.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream2 && mayRequireRefresh) {
              await this.refreshAccessTokenAsync();
              return this.requestAsync(opts, true);
            } else if (!reAuthRetried && isAuthErr && !isReadableStream2 && 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 info2 = Object.assign({
          expiry_date: (/* @__PURE__ */ new Date()).getTime() + data.expires_in * 1e3,
          scopes: data.scope.split(" ")
        }, data);
        delete info2.expires_in;
        delete info2.scope;
        return info2;
      }
      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 url3;
        switch (format4) {
          case CertificateFormat.PEM:
            url3 = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();
            break;
          case CertificateFormat.JWK:
            url3 = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();
            break;
          default:
            throw new Error(`Unsupported certificate format ${format4}`);
        }
        try {
          const opts = {
            ..._OAuth2Client.RETRY_CONFIG,
            url: url3
          };
          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 url3 = this.endpoints.oauth2IapPublicKeyUrl.toString();
        try {
          const opts = {
            ..._OAuth2Client.RETRY_CONFIG,
            url: url3
          };
          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(jwt2, certs, requiredAudience, issuers, maxExpiry) {
        const crypto18 = (0, crypto_1.createCrypto)();
        if (!maxExpiry) {
          maxExpiry = _OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;
        }
        const segments = jwt2.split(".");
        if (segments.length !== 3) {
          throw new Error("Wrong number of segments in token: " + jwt2);
        }
        const signed = segments[0] + "." + segments[1];
        let signature = segments[2];
        let envelope;
        let payload;
        try {
          envelope = JSON.parse(crypto18.decodeBase64StringUtf8(segments[0]));
        } catch (err2) {
          if (err2 instanceof Error) {
            err2.message = `Can't parse token envelope: ${segments[0]}': ${err2.message}`;
          }
          throw err2;
        }
        if (!envelope) {
          throw new Error("Can't parse token envelope: " + segments[0]);
        }
        try {
          payload = JSON.parse(crypto18.decodeBase64StringUtf8(segments[1]));
        } catch (err2) {
          if (err2 instanceof Error) {
            err2.message = `Can't parse token payload '${segments[0]}`;
          }
          throw err2;
        }
        if (!payload) {
          throw new Error("Can't parse token payload: " + segments[1]);
        }
        if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {
          throw new Error("No pem found for envelope: " + JSON.stringify(envelope));
        }
        const cert = certs[envelope.kid];
        if (envelope.alg === "ES256") {
          signature = formatEcdsa.joseToDer(signature, "ES256").toString("base64");
        }
        const verified = await crypto18.verify(cert, signed, signature);
        if (!verified) {
          throw new Error("Invalid token signature: " + jwt2);
        }
        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 env6 = GCPEnv.NONE;
      if (isAppEngine()) {
        env6 = GCPEnv.APP_ENGINE;
      } else if (isCloudFunction()) {
        env6 = GCPEnv.CLOUD_FUNCTIONS;
      } else if (await isComputeEngine()) {
        if (await isKubernetesEngine()) {
          env6 = GCPEnv.KUBERNETES_ENGINE;
        } else if (isCloudRun()) {
          env6 = GCPEnv.CLOUD_RUN;
        } else if (isCloudRunJob()) {
          env6 = GCPEnv.CLOUD_RUN_JOBS;
        } else {
          env6 = GCPEnv.COMPUTE_ENGINE;
        }
      } else {
        env6 = GCPEnv.NONE;
      }
      return env6;
    }
    __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 util5 = __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");
    util5.inherits(DataStream, Stream9);
    DataStream.prototype.write = /* @__PURE__ */ __name(function write3(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 i4 = 0; i4 < a2.length; i4++) {
        c4 |= a2[i4] ^ b2[i4];
      }
      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 crypto18 = __require("crypto");
    var formatEcdsa = require_ecdsa_sig_formatter();
    var util5 = __require("util");
    var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n  Supported algorithms are:\n  "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".';
    var MSG_INVALID_SECRET = "secret must be a string or buffer";
    var MSG_INVALID_VERIFIER_KEY = "key must be a string or a buffer";
    var MSG_INVALID_SIGNER_KEY = "key must be a string, a buffer or an object";
    var supportsKeyObjects = typeof crypto18.createPublicKey === "function";
    if (supportsKeyObjects) {
      MSG_INVALID_VERIFIER_KEY += " or a KeyObject";
      MSG_INVALID_SECRET += "or a KeyObject";
    }
    function checkIsPublicKey(key) {
      if (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(base643) {
      return base643.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    __name(fromBase64, "fromBase64");
    function toBase64(base64url3) {
      base64url3 = base64url3.toString();
      var padding = 4 - base64url3.length % 4;
      if (padding !== 4) {
        for (var i4 = 0; i4 < padding; ++i4) {
          base64url3 += "=";
        }
      }
      return base64url3.replace(/\-/g, "+").replace(/_/g, "/");
    }
    __name(toBase64, "toBase64");
    function typeError(template) {
      var args2 = [].slice.call(arguments, 1);
      var errMsg = util5.format.bind(util5, template).apply(null, args2);
      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 = crypto18.createHmac("sha" + bits, secret);
        var sig = (hmac.update(thing), hmac.digest("base64"));
        return fromBase64(sig);
      }, "sign");
    }
    __name(createHmacSigner, "createHmacSigner");
    var bufferEqual;
    var timingSafeEqual = "timingSafeEqual" in crypto18 ? /* @__PURE__ */ __name(function timingSafeEqual2(a2, b2) {
      if (a2.byteLength !== b2.byteLength) {
        return false;
      }
      return crypto18.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 = crypto18.createSign("RSA-SHA" + bits);
        var sig = (signer.update(thing), signer.sign(privateKey, "base64"));
        return fromBase64(sig);
      }, "sign");
    }
    __name(createKeySigner, "createKeySigner");
    function createKeyVerifier(bits) {
      return /* @__PURE__ */ __name(function verify(thing, signature, publicKey) {
        checkIsPublicKey(publicKey);
        thing = normalizeInput(thing);
        signature = toBase64(signature);
        var verifier = crypto18.createVerify("RSA-SHA" + bits);
        verifier.update(thing);
        return verifier.verify(publicKey, signature, "base64");
      }, "verify");
    }
    __name(createKeyVerifier, "createKeyVerifier");
    function createPSSKeySigner(bits) {
      return /* @__PURE__ */ __name(function sign(thing, privateKey) {
        checkIsPrivateKey(privateKey);
        thing = normalizeInput(thing);
        var signer = crypto18.createSign("RSA-SHA" + bits);
        var sig = (signer.update(thing), signer.sign({
          key: privateKey,
          padding: crypto18.constants.RSA_PKCS1_PSS_PADDING,
          saltLength: crypto18.constants.RSA_PSS_SALTLEN_DIGEST
        }, "base64"));
        return fromBase64(sig);
      }, "sign");
    }
    __name(createPSSKeySigner, "createPSSKeySigner");
    function createPSSKeyVerifier(bits) {
      return /* @__PURE__ */ __name(function verify(thing, signature, publicKey) {
        checkIsPublicKey(publicKey);
        thing = normalizeInput(thing);
        signature = toBase64(signature);
        var verifier = crypto18.createVerify("RSA-SHA" + bits);
        verifier.update(thing);
        return verifier.verify({
          key: publicKey,
          padding: crypto18.constants.RSA_PKCS1_PSS_PADDING,
          saltLength: crypto18.constants.RSA_PSS_SALTLEN_DIGEST
        }, signature, "base64");
      }, "verify");
    }
    __name(createPSSKeyVerifier, "createPSSKeyVerifier");
    function createECDSASigner(bits) {
      var inner = createKeySigner(bits);
      return /* @__PURE__ */ __name(function sign() {
        var signature = inner.apply(null, arguments);
        signature = formatEcdsa.derToJose(signature, "ES" + bits);
        return signature;
      }, "sign");
    }
    __name(createECDSASigner, "createECDSASigner");
    function createECDSAVerifer(bits) {
      var inner = createKeyVerifier(bits);
      return /* @__PURE__ */ __name(function verify(thing, signature, publicKey) {
        signature = formatEcdsa.joseToDer(signature, "ES" + bits).toString("base64");
        var result = inner(thing, signature, publicKey);
        return result;
      }, "verify");
    }
    __name(createECDSAVerifer, "createECDSAVerifer");
    function createNoneSigner() {
      return /* @__PURE__ */ __name(function sign() {
        return "";
      }, "sign");
    }
    __name(createNoneSigner, "createNoneSigner");
    function createNoneVerifier() {
      return /* @__PURE__ */ __name(function verify(thing, signature) {
        return signature === "";
      }, "verify");
    }
    __name(createNoneVerifier, "createNoneVerifier");
    module2.exports = /* @__PURE__ */ __name(function jwa(algorithm) {
      var signerFactories = {
        hs: createHmacSigner,
        rs: createKeySigner,
        ps: createPSSKeySigner,
        es: createECDSASigner,
        none: createNoneSigner
      };
      var verifierFactories = {
        hs: createHmacVerifier,
        rs: createKeyVerifier,
        ps: createPSSKeyVerifier,
        es: createECDSAVerifer,
        none: createNoneVerifier
      };
      var match2 = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);
      if (!match2)
        throw typeError(MSG_INVALID_ALGORITHM, algorithm);
      var algo = (match2[1] || match2[3]).toLowerCase();
      var bits = match2[2];
      return {
        sign: signerFactories[algo](bits),
        verify: verifierFactories[algo](bits)
      };
    }, "jwa");
  }
});

// node_modules/jws/lib/tostring.js
var require_tostring = __commonJS({
  "node_modules/jws/lib/tostring.js"(exports2, module2) {
    init_esbuild_shims();
    var Buffer9 = __require("buffer").Buffer;
    module2.exports = /* @__PURE__ */ __name(function toString3(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 toString3 = require_tostring();
    var util5 = __require("util");
    function base64url3(string4, encoding) {
      return Buffer9.from(string4, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
    }
    __name(base64url3, "base64url");
    function jwsSecuredInput(header, payload, encoding) {
      encoding = encoding || "utf8";
      var encodedHeader = base64url3(toString3(header), "binary");
      var encodedPayload = base64url3(toString3(payload), encoding);
      return util5.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 util5.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");
    util5.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 toString3 = require_tostring();
    var util5 = __require("util");
    var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;
    function isObject5(thing) {
      return Object.prototype.toString.call(thing) === "[object Object]";
    }
    __name(isObject5, "isObject");
    function safeJsonParse2(thing) {
      if (isObject5(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 err2 = new Error("Missing algorithm parameter for jws.verify");
        err2.code = "MISSING_ALGORITHM";
        throw err2;
      }
      jwsSig = toString3(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 = toString3(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");
    util5.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 fs142 = _interopRequireWildcard(__require("fs"));
    var _gaxios = require_src2();
    var jws = _interopRequireWildcard(require_jws());
    var path150 = _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, i4, 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) && ((i4 = (o3 = Object.defineProperty) && Object.getOwnPropertyDescriptor(e5, _t3)) && (i4.get || i4.set) ? o3(f5, _t3, i4) : 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 i4 = _toPrimitive2(t5, "string");
      return "symbol" == _typeof2(i4) ? i4 : i4 + "";
    }
    __name(_toPropertyKey2, "_toPropertyKey");
    function _toPrimitive2(t5, r5) {
      if ("object" != _typeof2(t5) || !t5) return t5;
      var e4 = t5[Symbol.toPrimitive];
      if (void 0 !== e4) {
        var i4 = e4.call(t5, r5 || "default");
        if ("object" != _typeof2(i4)) return i4;
        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 i4(r6, n4, o4, i5) {
        var c5 = n4 && n4.prototype instanceof Generator ? n4 : Generator, u3 = Object.create(c5.prototype);
        return _regeneratorDefine2(u3, "_invoke", function(r7, n5, o5) {
          var i6, c6, u4, f6 = 0, p2 = o5 || [], y2 = false, G3 = { p: 0, n: 0, v: e4, a: d2, f: d2.bind(e4, 4), d: /* @__PURE__ */ __name(function d3(t6, r8) {
            return i6 = t6, c6 = 0, u4 = e4, G3.n = r8, a2;
          }, "d") };
          function d2(r8, n6) {
            for (c6 = r8, u4 = n6, t5 = 0; !y2 && f6 && !o6 && t5 < p2.length; t5++) {
              var o6, i7 = p2[t5], d3 = G3.p, l3 = i7[2];
              r8 > 3 ? (o6 = l3 === n6) && (u4 = i7[(c6 = i7[4]) ? 5 : (c6 = 3, 3)], i7[4] = i7[5] = e4) : i7[0] <= d3 && ((o6 = r8 < 2 && d3 < i7[1]) ? (c6 = 0, G3.v = n6, G3.n = i7[1]) : d3 < l3 && (o6 = r8 < 3 || i7[0] > n6 || n6 > l3) && (i7[4] = r8, i7[5] = n6, G3.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; ) {
              i6 || (c6 ? c6 < 3 ? (c6 > 1 && (G3.n = -1), d2(c6, u4)) : G3.n = u4 : G3.v = u4);
              try {
                if (f6 = 2, i6) {
                  if (c6 || (o6 = "next"), t5 = i6[o6]) {
                    if (!(t5 = t5.call(i6, 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 = i6["return"]) && t5.call(i6), c6 < 2 && (u4 = TypeError("The iterator does not provide a '" + o6 + "' method"), c6 = 1);
                  i6 = e4;
                } else if ((t5 = (y2 = G3.n < 0) ? u4 : r7.call(n5, G3)) !== a2) break;
              } catch (t6) {
                i6 = e4, c6 = 1, u4 = t6;
              } finally {
                f6 = 1;
              }
            }
            return { value: t5, done: y2 };
          };
        }(r6, o4, i5), true), u3;
      }
      __name(i4, "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: i4, m: f5 };
      }, "_regenerator"))();
    }
    __name(_regenerator, "_regenerator");
    function _regeneratorDefine2(e4, r5, n3, t5) {
      var i4 = Object.defineProperty;
      try {
        i4({}, "", {});
      } catch (e5) {
        i4 = 0;
      }
      _regeneratorDefine2 = /* @__PURE__ */ __name(function _regeneratorDefine(e5, r6, n4, t6) {
        if (r6) i4 ? i4(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 i4 = n3[a2](c4), u2 = i4.value;
      } catch (n4) {
        return void e4(n4);
      }
      i4.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 readFile25 = fs142.readFile ? (0, _util.promisify)(fs142.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, body2, privateKey, clientEmail, _privateKey, _t2;
            return _regenerator().w(function(_context2) {
              while (1) switch (_context2.n) {
                case 0:
                  ext2 = path150.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 readFile25(keyFile, "utf8");
                case 2:
                  key = _context2.v;
                  body2 = JSON.parse(key);
                  privateKey = body2.private_key;
                  clientEmail = body2.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 readFile25(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 url3;
        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:
              url3 = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;
              _context5.n = 2;
              return this.transporter.request({
                url: url3,
                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, body2, 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;
              body2 = _t2.response && (_response = _t2.response) !== null && _response !== void 0 && _response.data ? (_response2 = _t2.response) === null || _response2 === void 0 ? void 0 : _response2.data : {};
              if (body2.error) {
                desc2 = body2.error_description ? ": ".concat(body2.error_description) : "";
                _t2.message = "".concat(body2.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_util12();
    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(email3, key, keyId, eagerRefreshThresholdMillis) {
        this.email = email3;
        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(url3, scopes) {
        let cacheKey = url3;
        if (scopes && Array.isArray(scopes) && scopes.length) {
          cacheKey = url3 ? `${url3}_${scopes.join("_")}` : `${scopes.join("_")}`;
        } else if (typeof scopes === "string") {
          cacheKey = url3 ? `${url3}_${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(url3, additionalClaims, scopes) {
        const key = this.getCachedKey(url3, 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: url3,
            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(json3) {
        if (!json3) {
          throw new Error("Must pass in a JSON object containing the service account auth settings.");
        }
        if (!json3.client_email) {
          throw new Error("The incoming JSON object does not contain a client_email field");
        }
        if (!json3.private_key) {
          throw new Error("The incoming JSON object does not contain a private_key field");
        }
        this.email = json3.client_email;
        this.key = json3.private_key;
        this.keyId = json3.private_key_id;
        this.projectId = json3.project_id;
      }
      fromStream(inputStream, callback) {
        if (callback) {
          this.fromStreamAsync(inputStream).then(() => callback(), callback);
        } else {
          return this.fromStreamAsync(inputStream);
        }
      }
      fromStreamAsync(inputStream) {
        return new Promise((resolve42, 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);
              resolve42();
            } catch (err2) {
              reject(err2);
            }
          });
        });
      }
    };
    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 jwt2 = new _JWT(this);
        jwt2.scopes = scopes;
        return jwt2;
      }
      /**
       * Obtains the metadata to be sent with the request.
       *
       * @param url the URI being authorized.
       */
      async getRequestMetadataAsync(url3) {
        url3 = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url3;
        const useSelfSignedJWT = !this.hasUserScopes() && url3 || 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 (!url3) {
              scopes = this.defaultScopes;
            }
            const useScopes = this.useJWTAccessWithScope || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;
            const headers = await this.access.getRequestHeaders(
              url3 ?? 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(url3);
        } 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(json3) {
        if (!json3) {
          throw new Error("Must pass in a JSON object containing the service account auth settings.");
        }
        if (!json3.client_email) {
          throw new Error("The incoming JSON object does not contain a client_email field");
        }
        if (!json3.private_key) {
          throw new Error("The incoming JSON object does not contain a private_key field");
        }
        this.email = json3.client_email;
        this.key = json3.private_key;
        this.keyId = json3.private_key_id;
        this.projectId = json3.project_id;
        this.quotaProjectId = json3.quota_project_id;
        this.universeDomain = json3.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((resolve42, 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);
              resolve42();
            } 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(json3) {
        if (!json3) {
          throw new Error("Must pass in a JSON object containing the user refresh token");
        }
        if (json3.type !== "authorized_user") {
          throw new Error('The incoming JSON object does not have the "authorized_user" type');
        }
        if (!json3.client_id) {
          throw new Error("The incoming JSON object does not contain a client_id field");
        }
        if (!json3.client_secret) {
          throw new Error("The incoming JSON object does not contain a client_secret field");
        }
        if (!json3.refresh_token) {
          throw new Error("The incoming JSON object does not contain a refresh_token field");
        }
        this._clientId = json3.client_id;
        this._clientSecret = json3.client_secret;
        this._refreshToken = json3.refresh_token;
        this.credentials.refresh_token = json3.refresh_token;
        this.quotaProjectId = json3.quota_project_id;
        this.universeDomain = json3.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((resolve42, 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 resolve42();
            } catch (err2) {
              return reject(err2);
            }
          });
        });
      }
      /**
       * Create a UserRefreshClient credentials instance using the given input
       * options.
       * @param json The input object.
       */
      static fromJSON(json3) {
        const client = new _UserRefreshClient();
        client.fromJSON(json3);
        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_util12();
    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 name4 = `projects/-/serviceAccounts/${this.targetPrincipal}`;
        const u2 = `${this.endpoint}/v1/${name4}:signBlob`;
        const body2 = {
          delegates: this.delegates,
          payload: Buffer.from(blobToSign).toString("base64")
        };
        const res = await this.sourceClient.request({
          ..._Impersonated.RETRY_CONFIG,
          url: u2,
          data: body2,
          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 name4 = "projects/-/serviceAccounts/" + this.targetPrincipal;
          const u2 = `${this.endpoint}/v1/${name4}:generateAccessToken`;
          const body2 = {
            delegates: this.delegates,
            scope: this.targetScopes,
            lifetime: this.lifetime + "s"
          };
          const res = await this.sourceClient.request({
            ..._Impersonated.RETRY_CONFIG,
            url: u2,
            data: body2,
            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 (error40) {
          if (!(error40 instanceof Error))
            throw error40;
          let status = 0;
          let message = "";
          if (error40 instanceof gaxios_1.GaxiosError) {
            status = error40?.response?.data?.error?.status;
            message = error40?.response?.data?.error?.message;
          }
          if (status && message) {
            error40.message = `${status}: unable to impersonate: ${message}`;
            throw error40;
          } else {
            error40.message = `unable to impersonate: ${error40}`;
            throw error40;
          }
        }
      }
      /**
       * 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 name4 = `projects/-/serviceAccounts/${this.targetPrincipal}`;
        const u2 = `${this.endpoint}/v1/${name4}:generateIdToken`;
        const body2 = {
          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: body2,
          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, err2) {
      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 (err2) {
        const keys = Object.keys(err2);
        if (err2.stack) {
          keys.push("stack");
        }
        keys.forEach((key) => {
          if (key !== "message") {
            Object.defineProperty(newError, key, {
              value: err2[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_util12();
    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 (error40) {
          if (error40 instanceof gaxios_1.GaxiosError && error40.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error40.response.data,
              // Preserve other fields from the original error.
              error40
            );
          }
          throw error40;
        }
      }
    };
    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 stream5 = __require("stream");
    var authclient_1 = require_authclient();
    var sts = require_stscredentials();
    var util_1 = require_util12();
    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 isReadableStream2 = res.config.data instanceof stream5.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream2 && 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 fs142 = __require("fs");
    var readFile25 = (0, util_1.promisify)(fs142.readFile ?? (() => {
    }));
    var realpath3 = (0, util_1.promisify)(fs142.realpath ?? (() => {
    }));
    var lstat6 = (0, util_1.promisify)(fs142.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 (err2) {
          if (err2 instanceof Error) {
            err2.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err2.message}`;
          }
          throw err2;
        }
        let subjectToken;
        const rawText = await readFile25(parsedFilePath, { encoding: "utf8" });
        if (this.formatType === "text") {
          subjectToken = rawText;
        } else if (this.formatType === "json" && this.subjectTokenFieldName) {
          const json3 = JSON.parse(rawText);
          subjectToken = json3[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_util12();
    var fs142 = __require("fs");
    var crypto_1 = __require("crypto");
    var https9 = __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 https9.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 fs142.promises.readFile(configPath, "utf8");
        } catch (err2) {
          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 fs142.promises.readFile(certPath);
          new crypto_1.X509Certificate(cert);
        } catch (err2) {
          const message = err2 instanceof Error ? err2.message : String(err2);
          throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`);
        }
        try {
          key = await fs142.promises.readFile(keyPath);
          (0, crypto_1.createPrivateKey)(key);
        } catch (err2) {
          const message = err2 instanceof Error ? err2.message : String(err2);
          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 fs142.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 (err2) {
              const message = err2 instanceof Error ? err2.message : String(err2);
              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 (err2) {
          if (err2 instanceof InvalidConfigurationError)
            throw err2;
          const message = err2 instanceof Error ? err2.message : String(err2);
          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_util12();
    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 file2 = credentialSourceOpts.get("file");
          const url3 = credentialSourceOpts.get("url");
          const certificate = credentialSourceOpts.get("certificate");
          const headers = credentialSourceOpts.get("headers");
          if (file2 && url3 || url3 && certificate || file2 && certificate) {
            throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');
          } else if (file2) {
            this.credentialSourceType = "file";
            this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({
              filePath: file2,
              formatType,
              subjectTokenFieldName: formatSubjectTokenFieldName
            });
          } else if (url3) {
            this.credentialSourceType = "url";
            this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({
              url: url3,
              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 url3 = 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(url3);
        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: url3,
          method,
          headers
        };
        if (requestPayload !== void 0) {
          awsSignedReq.body = requestPayload;
        }
        return awsSignedReq;
      }
    };
    exports2.AwsRequestSigner = AwsRequestSigner;
    async function sign(crypto18, key, msg) {
      return await crypto18.signWithHmacSha256(key, msg);
    }
    __name(sign, "sign");
    async function getSigningKey(crypto18, key, dateStamp, region, serviceName) {
      const kDate = await sign(crypto18, `AWS4${key}`, dateStamp);
      const kRegion = await sign(crypto18, kDate, region);
      const kService = await sign(crypto18, kRegion, serviceName);
      const kSigning = await sign(crypto18, kService, "aws4_request");
      return kSigning;
    }
    __name(getSigningKey, "getSigningKey");
    async function generateAuthenticationHeaderMap(options2) {
      const additionalAmzHeaders = 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_util12();
    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 fs142 = __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((resolve42, 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", (err2) => {
            output += err2;
          });
          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 resolve42(response);
              } catch (error40) {
                if (error40 instanceof executable_response_1.ExecutableResponseError) {
                  return reject(error40);
                }
                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 fs142.promises.realpath(this.outputFile);
        } catch {
          return void 0;
        }
        if (!(await fs142.promises.lstat(filePath)).isFile()) {
          return void 0;
        }
        const responseString = await fs142.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 (error40) {
          if (error40 instanceof executable_response_1.ExecutableResponseError) {
            throw error40;
          }
          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 i4 = 0; i4 < components.length; i4++) {
          if (components[i4][0] === '"' && components[i4].slice(-1) === '"') {
            components[i4] = components[i4].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 stream5 = __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 (error40) {
          if (error40 instanceof gaxios_1.GaxiosError && error40.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error40.response.data,
              // Preserve other fields from the original error.
              error40
            );
          }
          throw error40;
        }
      }
    };
    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 isReadableStream2 = res.config.data instanceof stream5.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream2 && 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 fs142 = __require("fs");
    var gaxios_1 = require_src2();
    var gcpMetadata = require_src4();
    var os59 = __require("os");
    var path150 = __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_util12();
    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 = path150.join(home, ".config");
          }
        }
        if (location) {
          location = path150.join(location, "gcloud", "application_default_credentials.json");
          if (!fs142.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 = fs142.realpathSync(filePath);
          if (!fs142.lstatSync(filePath).isFile()) {
            throw new Error();
          }
        } catch (err2) {
          if (err2 instanceof Error) {
            err2.message = `The file at ${filePath} does not exist, or it is not a file. ${err2.message}`;
          }
          throw err2;
        }
        const readStream2 = fs142.createReadStream(filePath);
        return this.fromStream(readStream2, 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(json3) {
        if (!json3) {
          throw new Error("Must pass in a JSON object containing an  impersonated refresh token");
        }
        if (json3.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
          throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);
        }
        if (!json3.source_credentials) {
          throw new Error("The incoming JSON object does not contain a source_credentials field");
        }
        if (!json3.service_account_impersonation_url) {
          throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");
        }
        const sourceClient = this.fromJSON(json3.source_credentials);
        if (json3.service_account_impersonation_url?.length > 256) {
          throw new RangeError(`Target principal is too long: ${json3.service_account_impersonation_url}`);
        }
        const targetPrincipal = /(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(json3.service_account_impersonation_url)?.groups?.target;
        if (!targetPrincipal) {
          throw new RangeError(`Cannot extract target principal from ${json3.service_account_impersonation_url}`);
        }
        const targetScopes = (this.scopes || json3.scopes || this.defaultScopes) ?? [];
        return new impersonated_1.Impersonated({
          ...json3,
          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(json3, options2 = {}) {
        let client;
        const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options2).get("universe_domain");
        if (json3.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) {
          client = new refreshclient_1.UserRefreshClient(options2);
          client.fromJSON(json3);
        } else if (json3.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
          client = this.fromImpersonatedJSON(json3);
        } else if (json3.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
          client = externalclient_1.ExternalAccountClient.fromJSON({
            ...json3,
            ...options2
          });
          client.scopes = this.getAnyScopes();
        } else if (json3.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) {
          client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({
            ...json3,
            ...options2
          });
        } else {
          options2.scopes = this.scopes;
          client = new jwtclient_1.JWT(options2);
          this.setGapicJWTValues(client);
          client.fromJSON(json3);
        }
        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(json3, options2) {
        const client = this.fromJSON(json3, options2);
        this.jsonContent = json3;
        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((resolve42, 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 resolve42(r5);
              } catch (err2) {
                if (!this.keyFilename)
                  throw err2;
                const client = new jwtclient_1.JWT({
                  ...this.clientOptions,
                  keyFile: this.keyFilename
                });
                this.cachedCredential = client;
                this.setGapicJWTValues(client);
                return resolve42(client);
              }
            } catch (err2) {
              return reject(err2);
            }
          });
        });
      }
      /**
       * 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 = os59.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((resolve42) => {
          (0, child_process_1.exec)("gcloud config config-helper --format json", (err2, stdout2) => {
            if (!err2 && stdout2) {
              try {
                const projectId = JSON.parse(stdout2).configuration.properties.core.project;
                resolve42(projectId);
                return;
              } catch (e4) {
              }
            }
            resolve42(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 = path150.resolve(this.keyFilename);
          const stream5 = fs142.createReadStream(filePath);
          return await this.fromStreamAsync(stream5, 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(url3) {
        const client = await this.getClient();
        return client.getRequestHeaders(url3);
      }
      /**
       * 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 url3 = opts.url;
        const client = await this.getClient();
        const headers = await client.getRequestHeaders(url3);
        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(...args2) {
        const client = await this.getClient();
        return client.fetch(...args2);
      }
      /**
       * 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 crypto18 = (0, crypto_1.createCrypto)();
        if (client instanceof jwtclient_1.JWT && client.key) {
          const sign = await crypto18.sign(client.key, data);
          return sign;
        }
        const creds = await this.getCredentials();
        if (!creds.client_email) {
          throw new Error("Cannot sign data without `client_email`.");
        }
        return this.signBlob(crypto18, creds.client_email, data, endpoint);
      }
      async signBlob(crypto18, emailOrUniqueId, data, endpoint) {
        const url3 = new URL(endpoint + `${emailOrUniqueId}:signBlob`);
        const res = await this.request({
          method: "POST",
          url: url3.href,
          data: {
            payload: crypto18.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 stream5 = __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 isReadableStream2 = res.config.data instanceof stream5.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream2 && 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 i4 = 0; i4 < list3.length; i4++) {
        const buf = list3[i4];
        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 i4 = 0; i4 < length; i4++) {
        output[offset + i4] = source2[i4] ^ mask[i4 & 3];
      }
    }
    __name(_mask, "_mask");
    function _unmask(buffer, mask) {
      for (let i4 = 0; i4 < buffer.length; i4++) {
        buffer[i4] ^= mask[i4 & 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 zlib5 = __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, (err2, result) => {
            done();
            callback(err2, 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, (err2, result) => {
            done();
            callback(err2, 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" ? zlib5.Z_DEFAULT_WINDOWBITS : this.params[key];
          this._inflate = zlib5.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 err2 = this._inflate[kError];
          if (err2) {
            this._inflate.close();
            this._inflate = null;
            callback(err2);
            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" ? zlib5.Z_DEFAULT_WINDOWBITS : this.params[key];
          this._deflate = zlib5.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(zlib5.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(err2) {
      this[kPerMessageDeflate]._inflate = null;
      if (this[kError]) {
        this[kCallback](this[kError]);
        return;
      }
      err2[kStatusCode] = 1007;
      this[kCallback](err2);
    }
    __name(inflateOnError, "inflateOnError");
  }
});

// node_modules/ws/lib/validation.js
var require_validation4 = __commonJS({
  "node_modules/ws/lib/validation.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var { isUtf8: isUtf82 } = __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 i4 = 0;
      while (i4 < len) {
        if ((buf[i4] & 128) === 0) {
          i4++;
        } else if ((buf[i4] & 224) === 192) {
          if (i4 + 1 === len || (buf[i4 + 1] & 192) !== 128 || (buf[i4] & 254) === 192) {
            return false;
          }
          i4 += 2;
        } else if ((buf[i4] & 240) === 224) {
          if (i4 + 2 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || buf[i4] === 224 && (buf[i4 + 1] & 224) === 128 || // Overlong
          buf[i4] === 237 && (buf[i4 + 1] & 224) === 160) {
            return false;
          }
          i4 += 3;
        } else if ((buf[i4] & 248) === 240) {
          if (i4 + 3 >= len || (buf[i4 + 1] & 192) !== 128 || (buf[i4 + 2] & 192) !== 128 || (buf[i4 + 3] & 192) !== 128 || buf[i4] === 240 && (buf[i4 + 1] & 240) === 128 || // Overlong
          buf[i4] === 244 && buf[i4 + 1] > 143 || buf[i4] > 244) {
            return false;
          }
          i4 += 4;
        } else {
          return false;
        }
      }
      return true;
    }
    __name(_isValidUTF8, "_isValidUTF8");
    function isBlob5(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(isBlob5, "isBlob");
    module2.exports = {
      isBlob: isBlob5,
      isValidStatusCode,
      isValidUTF8: _isValidUTF8,
      tokenChars
    };
    if (isUtf82) {
      module2.exports.isValidUTF8 = function(buf) {
        return buf.length < 24 ? _isValidUTF8(buf) : isUtf82(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: Writable4 } = __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_validation4();
    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 Writable4 {
      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 error40 = this.createError(
            RangeError,
            "RSV2 and RSV3 must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_RSV_2_3"
          );
          cb(error40);
          return;
        }
        const compressed = (buf[0] & 64) === 64;
        if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
          const error40 = this.createError(
            RangeError,
            "RSV1 must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_RSV_1"
          );
          cb(error40);
          return;
        }
        this._fin = (buf[0] & 128) === 128;
        this._opcode = buf[0] & 15;
        this._payloadLength = buf[1] & 127;
        if (this._opcode === 0) {
          if (compressed) {
            const error40 = this.createError(
              RangeError,
              "RSV1 must be clear",
              true,
              1002,
              "WS_ERR_UNEXPECTED_RSV_1"
            );
            cb(error40);
            return;
          }
          if (!this._fragmented) {
            const error40 = this.createError(
              RangeError,
              "invalid opcode 0",
              true,
              1002,
              "WS_ERR_INVALID_OPCODE"
            );
            cb(error40);
            return;
          }
          this._opcode = this._fragmented;
        } else if (this._opcode === 1 || this._opcode === 2) {
          if (this._fragmented) {
            const error40 = this.createError(
              RangeError,
              `invalid opcode ${this._opcode}`,
              true,
              1002,
              "WS_ERR_INVALID_OPCODE"
            );
            cb(error40);
            return;
          }
          this._compressed = compressed;
        } else if (this._opcode > 7 && this._opcode < 11) {
          if (!this._fin) {
            const error40 = this.createError(
              RangeError,
              "FIN must be set",
              true,
              1002,
              "WS_ERR_EXPECTED_FIN"
            );
            cb(error40);
            return;
          }
          if (compressed) {
            const error40 = this.createError(
              RangeError,
              "RSV1 must be clear",
              true,
              1002,
              "WS_ERR_UNEXPECTED_RSV_1"
            );
            cb(error40);
            return;
          }
          if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
            const error40 = this.createError(
              RangeError,
              `invalid payload length ${this._payloadLength}`,
              true,
              1002,
              "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
            );
            cb(error40);
            return;
          }
        } else {
          const error40 = this.createError(
            RangeError,
            `invalid opcode ${this._opcode}`,
            true,
            1002,
            "WS_ERR_INVALID_OPCODE"
          );
          cb(error40);
          return;
        }
        if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
        this._masked = (buf[1] & 128) === 128;
        if (this._isServer) {
          if (!this._masked) {
            const error40 = this.createError(
              RangeError,
              "MASK must be set",
              true,
              1002,
              "WS_ERR_EXPECTED_MASK"
            );
            cb(error40);
            return;
          }
        } else if (this._masked) {
          const error40 = this.createError(
            RangeError,
            "MASK must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_MASK"
          );
          cb(error40);
          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 error40 = this.createError(
            RangeError,
            "Unsupported WebSocket frame: payload length > 2^53 - 1",
            false,
            1009,
            "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
          );
          cb(error40);
          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 error40 = this.createError(
              RangeError,
              "Max payload size exceeded",
              false,
              1009,
              "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
            );
            cb(error40);
            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, (err2, buf) => {
          if (err2) return cb(err2);
          if (buf.length) {
            this._messageLength += buf.length;
            if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
              const error40 = this.createError(
                RangeError,
                "Max payload size exceeded",
                false,
                1009,
                "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
              );
              cb(error40);
              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 error40 = this.createError(
              Error,
              "invalid UTF-8 sequence",
              true,
              1007,
              "WS_ERR_INVALID_UTF8"
            );
            cb(error40);
            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 error40 = this.createError(
                RangeError,
                `invalid status code ${code2}`,
                true,
                1002,
                "WS_ERR_INVALID_CLOSE_CODE"
              );
              cb(error40);
              return;
            }
            const buf = new FastBuffer(
              data.buffer,
              data.byteOffset + 2,
              data.length - 2
            );
            if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
              const error40 = this.createError(
                Error,
                "invalid UTF-8 sequence",
                true,
                1007,
                "WS_ERR_INVALID_UTF8"
              );
              cb(error40);
              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 err2 = new ErrorCtor(
          prefix ? `Invalid WebSocket frame: ${message}` : message
        );
        Error.captureStackTrace(err2, this.createError);
        err2.code = errorCode;
        err2[kStatusCode] = statusCode;
        return err2;
      }
    };
    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: isBlob5, isValidStatusCode } = require_validation4();
    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 merge5 = 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;
          merge5 = 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(merge5 ? 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 (merge5) {
          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 (isBlob5(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 (isBlob5(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 (isBlob5(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 (isBlob5(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 (isBlob5(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 (isBlob5(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 err2 = new Error(
              "The socket was closed while the blob was being read"
            );
            process.nextTick(callCallbacks, this, err2, 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((err2) => {
          process.nextTick(onError2, this, err2, 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 err2 = new Error(
              "The socket was closed while data was being compressed"
            );
            callCallbacks(this, err2, 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, err2, cb) {
      if (typeof cb === "function") cb(err2);
      for (let i4 = 0; i4 < sender._queue.length; i4++) {
        const params = sender._queue[i4];
        const callback = params[params.length - 1];
        if (typeof callback === "function") callback(err2);
      }
    }
    __name(callCallbacks, "callCallbacks");
    function onError2(sender, err2, cb) {
      callCallbacks(sender, err2, cb);
      sender.onerror(err2);
    }
    __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(error40) {
            const event = new ErrorEvent2("error", {
              error: error40,
              message: error40.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_validation4();
    function push2(dest, name4, elem) {
      if (dest[name4] === void 0) dest[name4] = [elem];
      else dest[name4].push(elem);
    }
    __name(push2, "push");
    function parse17(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 start2 = -1;
      let code2 = -1;
      let end = -1;
      let i4 = 0;
      for (; i4 < header.length; i4++) {
        code2 = header.charCodeAt(i4);
        if (extensionName === void 0) {
          if (end === -1 && tokenChars[code2] === 1) {
            if (start2 === -1) start2 = i4;
          } else if (i4 !== 0 && (code2 === 32 || code2 === 9)) {
            if (end === -1 && start2 !== -1) end = i4;
          } else if (code2 === 59 || code2 === 44) {
            if (start2 === -1) {
              throw new SyntaxError(`Unexpected character at index ${i4}`);
            }
            if (end === -1) end = i4;
            const name4 = header.slice(start2, end);
            if (code2 === 44) {
              push2(offers, name4, params);
              params = /* @__PURE__ */ Object.create(null);
            } else {
              extensionName = name4;
            }
            start2 = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i4}`);
          }
        } else if (paramName === void 0) {
          if (end === -1 && tokenChars[code2] === 1) {
            if (start2 === -1) start2 = i4;
          } else if (code2 === 32 || code2 === 9) {
            if (end === -1 && start2 !== -1) end = i4;
          } else if (code2 === 59 || code2 === 44) {
            if (start2 === -1) {
              throw new SyntaxError(`Unexpected character at index ${i4}`);
            }
            if (end === -1) end = i4;
            push2(params, header.slice(start2, end), true);
            if (code2 === 44) {
              push2(offers, extensionName, params);
              params = /* @__PURE__ */ Object.create(null);
              extensionName = void 0;
            }
            start2 = end = -1;
          } else if (code2 === 61 && start2 !== -1 && end === -1) {
            paramName = header.slice(start2, i4);
            start2 = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i4}`);
          }
        } else {
          if (isEscaping) {
            if (tokenChars[code2] !== 1) {
              throw new SyntaxError(`Unexpected character at index ${i4}`);
            }
            if (start2 === -1) start2 = i4;
            else if (!mustUnescape) mustUnescape = true;
            isEscaping = false;
          } else if (inQuotes) {
            if (tokenChars[code2] === 1) {
              if (start2 === -1) start2 = i4;
            } else if (code2 === 34 && start2 !== -1) {
              inQuotes = false;
              end = i4;
            } else if (code2 === 92) {
              isEscaping = true;
            } else {
              throw new SyntaxError(`Unexpected character at index ${i4}`);
            }
          } else if (code2 === 34 && header.charCodeAt(i4 - 1) === 61) {
            inQuotes = true;
          } else if (end === -1 && tokenChars[code2] === 1) {
            if (start2 === -1) start2 = i4;
          } else if (start2 !== -1 && (code2 === 32 || code2 === 9)) {
            if (end === -1) end = i4;
          } else if (code2 === 59 || code2 === 44) {
            if (start2 === -1) {
              throw new SyntaxError(`Unexpected character at index ${i4}`);
            }
            if (end === -1) end = i4;
            let value = header.slice(start2, 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;
            start2 = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i4}`);
          }
        }
      }
      if (start2 === -1 || inQuotes || code2 === 32 || code2 === 9) {
        throw new SyntaxError("Unexpected end of input");
      }
      if (end === -1) end = i4;
      const token2 = header.slice(start2, 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(parse17, "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: parse17 };
  }
});

// node_modules/ws/lib/websocket.js
var require_websocket2 = __commonJS({
  "node_modules/ws/lib/websocket.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var EventEmitter16 = __require("events");
    var https9 = __require("https");
    var http9 = __require("http");
    var net2 = __require("net");
    var tls = __require("tls");
    var { randomBytes: randomBytes9, createHash: createHash9 } = __require("crypto");
    var { Duplex, Readable: Readable8 } = __require("stream");
    var { URL: URL5 } = __require("url");
    var PerMessageDeflate = require_permessage_deflate2();
    var Receiver2 = require_receiver2();
    var Sender2 = require_sender2();
    var { isBlob: isBlob5 } = require_validation4();
    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: parse17 } = 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 EventEmitter16 {
      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, (err2) => {
          if (err2) 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 err2 = new SyntaxError(invalidUrlMessage);
        if (websocket._redirects === 0) {
          throw err2;
        } else {
          emitErrorAndClose(websocket, err2);
          return;
        }
      }
      const defaultPort = isSecure ? 443 : 80;
      const key = randomBytes9(16).toString("base64");
      const request4 = isSecure ? https9.request : http9.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 parts2 = opts.path.split(":");
        opts.socketPath = parts2[0];
        opts.path = parts2[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", (err2) => {
        if (req === null || req[kAborted]) return;
        req = websocket._req = null;
        emitErrorAndClose(websocket, err2);
      });
      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 addr2;
          try {
            addr2 = new URL5(location, address);
          } catch (e4) {
            const err2 = new SyntaxError(`Invalid URL: ${location}`);
            emitErrorAndClose(websocket, err2);
            return;
          }
          initAsClient(websocket, addr2, 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 = createHash9("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 = parse17(secWebSocketExtensions);
          } catch (err2) {
            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 (err2) {
            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, err2) {
      websocket._readyState = WebSocket2.CLOSING;
      websocket._errorEmitted = true;
      websocket.emit("error", err2);
      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, stream5, message) {
      websocket._readyState = WebSocket2.CLOSING;
      const err2 = new Error(message);
      Error.captureStackTrace(err2, abortHandshake);
      if (stream5.setHeader) {
        stream5[kAborted] = true;
        stream5.abort();
        if (stream5.socket && !stream5.socket.destroyed) {
          stream5.socket.destroy();
        }
        process.nextTick(emitErrorAndClose, websocket, err2);
      } else {
        stream5.destroy(err2);
        stream5.once("error", websocket.emit.bind(websocket, "error"));
        stream5.once("close", websocket.emitClose.bind(websocket));
      }
    }
    __name(abortHandshake, "abortHandshake");
    function sendAfterClose(websocket, data, cb) {
      if (data) {
        const length = isBlob5(data) ? data.size : toBuffer(data).length;
        if (websocket._socket) websocket._sender._bufferedBytes += length;
        else websocket._bufferedAmount += length;
      }
      if (cb) {
        const err2 = new Error(
          `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
        );
        process.nextTick(cb, err2);
      }
    }
    __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(err2) {
      const websocket = this[kWebSocket];
      if (websocket._socket[kWebSocket] !== void 0) {
        websocket._socket.removeListener("data", socketOnData);
        process.nextTick(resume, websocket._socket);
        websocket.close(err2[kStatusCode]);
      }
      if (!websocket._errorEmitted) {
        websocket._errorEmitted = true;
        websocket.emit("error", err2);
      }
    }
    __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(stream5) {
      stream5.resume();
    }
    __name(resume, "resume");
    function senderOnError(err2) {
      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", err2);
      }
    }
    __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(stream5) {
      stream5.emit("close");
    }
    __name(emitClose, "emitClose");
    function duplexOnEnd() {
      if (!this.destroyed && this._writableState.finished) {
        this.destroy();
      }
    }
    __name(duplexOnEnd, "duplexOnEnd");
    function duplexOnError(err2) {
      this.removeListener("error", duplexOnError);
      this.destroy();
      if (this.listenerCount("error") === 0) {
        this.emit("error", err2);
      }
    }
    __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 error40(err2) {
        if (duplex.destroyed) return;
        terminateOnDestroy = false;
        duplex.destroy(err2);
      }, "error"));
      ws2.once("close", /* @__PURE__ */ __name(function close() {
        if (duplex.destroyed) return;
        duplex.push(null);
      }, "close"));
      duplex._destroy = function(err2, callback) {
        if (ws2.readyState === ws2.CLOSED) {
          callback(err2);
          process.nextTick(emitClose, duplex);
          return;
        }
        let called = false;
        ws2.once("error", /* @__PURE__ */ __name(function error40(err3) {
          called = true;
          callback(err3);
        }, "error"));
        ws2.once("close", /* @__PURE__ */ __name(function close() {
          if (!called) callback(err2);
          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_validation4();
    function parse17(header) {
      const protocols = /* @__PURE__ */ new Set();
      let start2 = -1;
      let end = -1;
      let i4 = 0;
      for (i4; i4 < header.length; i4++) {
        const code2 = header.charCodeAt(i4);
        if (end === -1 && tokenChars[code2] === 1) {
          if (start2 === -1) start2 = i4;
        } else if (i4 !== 0 && (code2 === 32 || code2 === 9)) {
          if (end === -1 && start2 !== -1) end = i4;
        } else if (code2 === 44) {
          if (start2 === -1) {
            throw new SyntaxError(`Unexpected character at index ${i4}`);
          }
          if (end === -1) end = i4;
          const protocol2 = header.slice(start2, end);
          if (protocols.has(protocol2)) {
            throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
          }
          protocols.add(protocol2);
          start2 = end = -1;
        } else {
          throw new SyntaxError(`Unexpected character at index ${i4}`);
        }
      }
      if (start2 === -1 || end !== -1) {
        throw new SyntaxError("Unexpected end of input");
      }
      const protocol = header.slice(start2, i4);
      if (protocols.has(protocol)) {
        throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
      }
      protocols.add(protocol);
      return protocols;
    }
    __name(parse17, "parse");
    module2.exports = { parse: parse17 };
  }
});

// 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 EventEmitter16 = __require("events");
    var http9 = __require("http");
    var { Duplex } = __require("stream");
    var { createHash: createHash9 } = __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 EventEmitter16 {
      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 = http9.createServer((req, res) => {
            const body2 = http9.STATUS_CODES[426];
            res.writeHead(426, {
              "Content-Length": body2.length,
              "Content-Type": "text/plain"
            });
            res.end(body2);
          });
          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 (err2) {
            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 (err2) {
            const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
            abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
            return;
          }
        }
        if (this.options.verifyClient) {
          const info2 = {
            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(info2, (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(info2)) 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 = createHash9("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, map3) {
      for (const event of Object.keys(map3)) server.on(event, map3[event]);
      return /* @__PURE__ */ __name(function removeListeners() {
        for (const event of Object.keys(map3)) {
          server.removeListener(event, map3[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 || http9.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} ${http9.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 err2 = new Error(message);
        Error.captureStackTrace(err2, abortHandshakeOrEmitwsClientError);
        server.emit("wsClientError", err2, 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 fs10 from "fs/promises";
import { writeFile as writeFile2 } from "fs/promises";
import { Readable } from "node:stream";
import { finished } from "node:stream/promises";
import * as path7 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 i4 = 0; i4 < keys.length - 1; i4++) {
    const key = keys[i4];
    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(i4 + 1), value[j2]);
          }
        } else {
          for (const d2 of arrayData) {
            setValueByPath(d2, keys.slice(i4 + 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(i4 + 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 i4 = 0; i4 < keys.length; i4++) {
      if (typeof data !== "object" || data === null) {
        return defaultValue;
      }
      const key = keys[i4];
      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(i4 + 1), defaultValue));
        } else {
          return defaultValue;
        }
      } else {
        data = data[key];
      }
    }
    return data;
  } catch (error40) {
    if (error40 instanceof TypeError) {
      return defaultValue;
    }
    throw error40;
  }
}
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 i4 = 0; i4 < sourceKeys.length; i4++) {
      if (sourceKeys[i4] === "*") {
        wildcardIdx = i4;
        break;
      }
    }
    if (wildcardIdx !== -1 && destKeys.length > wildcardIdx) {
      for (let i4 = wildcardIdx; i4 < destKeys.length; i4++) {
        const key = destKeys[i4];
        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 parts2 = [];
  if (typeof partOrString === "string") {
    parts2.push(createPartFromText(partOrString));
  } else if (_isPart(partOrString)) {
    parts2.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") {
        parts2.push(createPartFromText(part));
      } else if (_isPart(part)) {
        parts2.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 parts2;
}
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 parts2 = model.split("/", 2);
      return `publishers/${parts2[0]}/models/${parts2[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(origin2) {
  if (origin2 === null || origin2 === void 0) {
    throw new Error("PartUnion is required");
  }
  if (typeof origin2 === "object") {
    return origin2;
  }
  if (typeof origin2 === "string") {
    return { text: origin2 };
  }
  throw new Error(`Unsupported part type: ${typeof origin2}`);
}
function tParts(origin2) {
  if (origin2 === null || origin2 === void 0 || Array.isArray(origin2) && origin2.length === 0) {
    throw new Error("PartListUnion is required");
  }
  if (Array.isArray(origin2)) {
    return origin2.map((item) => tPart(item));
  }
  return [tPart(origin2)];
}
function _isContent(origin2) {
  return origin2 !== null && origin2 !== void 0 && typeof origin2 === "object" && "parts" in origin2 && Array.isArray(origin2.parts);
}
function _isFunctionCallPart(origin2) {
  return origin2 !== null && origin2 !== void 0 && typeof origin2 === "object" && "functionCall" in origin2;
}
function _isFunctionResponsePart(origin2) {
  return origin2 !== null && origin2 !== void 0 && typeof origin2 === "object" && "functionResponse" in origin2;
}
function tContent(origin2) {
  if (origin2 === null || origin2 === void 0) {
    throw new Error("ContentUnion is required");
  }
  if (_isContent(origin2)) {
    return origin2;
  }
  return {
    role: "user",
    parts: tParts(origin2)
  };
}
function tContentsForEmbed(apiClient, origin2) {
  if (!origin2) {
    return [];
  }
  if (apiClient.isVertexAI() && Array.isArray(origin2)) {
    return origin2.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(origin2);
    if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) {
      return [content.parts[0].text];
    }
    return [];
  }
  if (Array.isArray(origin2)) {
    return origin2.map((item) => tContent(item));
  }
  return [tContent(origin2)];
}
function tContents(origin2) {
  if (origin2 === null || origin2 === void 0 || Array.isArray(origin2) && origin2.length === 0) {
    throw new Error("contents are required");
  }
  if (!Array.isArray(origin2)) {
    if (_isFunctionCallPart(origin2) || _isFunctionResponsePart(origin2)) {
      throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");
    }
    return [tContent(origin2)];
  }
  const result = [];
  const accumulatedParts = [];
  const isContentArray = _isContent(origin2[0]);
  for (const item of origin2) {
    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 i4 of listWithoutNull) {
      resultingSchema["anyOf"].push({
        "type": Object.values(Type).includes(i4.toUpperCase()) ? i4.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, name4) {
  if (typeof name4 !== "string") {
    throw new Error("name must be a string");
  }
  return resourceName(apiClient, name4, "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(origin2) {
  return origin2 !== null && origin2 !== void 0 && typeof origin2 === "object" && "name" in origin2;
}
function isGeneratedVideo(origin2) {
  return origin2 !== null && origin2 !== void 0 && typeof origin2 === "object" && "video" in origin2;
}
function isVideo(origin2) {
  return origin2 !== null && origin2 !== void 0 && typeof origin2 === "object" && "uri" in origin2;
}
function tFileName(fromName) {
  var _a7;
  let name4;
  if (_isFile(fromName)) {
    name4 = fromName.name;
  }
  if (isVideo(fromName)) {
    name4 = fromName.uri;
    if (name4 === void 0) {
      return void 0;
    }
  }
  if (isGeneratedVideo(fromName)) {
    name4 = (_a7 = fromName.video) === null || _a7 === void 0 ? void 0 : _a7.uri;
    if (name4 === void 0) {
      return void 0;
    }
  }
  if (typeof fromName === "string") {
    name4 = fromName;
  }
  if (name4 === void 0) {
    throw new Error("Could not extract file name from the provided input.");
  }
  if (name4.startsWith("https://")) {
    const suffix = name4.split("files/")[1];
    const match2 = suffix.match(/[a-z0-9]+/);
    if (match2 === null) {
      throw new Error(`Could not extract file name from URI ${name4}`);
    }
    name4 = match2[0];
  } else if (name4.startsWith("files/")) {
    name4 = name4.split("files/")[1];
  }
  return name4;
}
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, name4) {
  const nameString = name4;
  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], i4 = 0;
  if (m3) return m3.call(o3);
  if (o3 && typeof o3.length === "number") return {
    next: /* @__PURE__ */ __name(function() {
      if (o3 && i4 >= o3.length) o3 = void 0;
      return { value: o3 && o3[i4++], 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 || []), i4, q2 = [];
  return i4 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i4[Symbol.asyncIterator] = function() {
    return this;
  }, i4;
  function awaitReturn(f5) {
    return function(v2) {
      return Promise.resolve(v2).then(f5, reject);
    };
  }
  __name(awaitReturn, "awaitReturn");
  function verb(n3, f5) {
    if (g2[n3]) {
      i4[n3] = function(v2) {
        return new Promise(function(a2, b2) {
          q2.push([n3, v2, a2, b2]) > 1 || resume(n3, v2);
        });
      };
      if (f5) i4[n3] = f5(i4[n3]);
    }
  }
  __name(verb, "verb");
  function resume(n3, v2) {
    try {
      step(g2[n3](v2));
    } catch (e4) {
      settle2(q2[0][3], e4);
    }
  }
  __name(resume, "resume");
  function step(r5) {
    r5.value instanceof __await ? Promise.resolve(r5.value.v).then(fulfill, reject) : settle2(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 settle2(f5, v2) {
    if (f5(v2), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]);
  }
  __name(settle2, "settle");
}
function __asyncValues(o3) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m3 = o3[Symbol.asyncIterator], i4;
  return m3 ? m3.call(o3) : (o3 = typeof __values === "function" ? __values(o3) : o3[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() {
    return this;
  }, i4);
  function verb(n3) {
    i4[n3] = o3[n3] && function(v2) {
      return new Promise(function(resolve42, reject) {
        v2 = o3[n3](v2), settle2(resolve42, reject, v2.done, v2.value);
      });
    };
  }
  __name(verb, "verb");
  function settle2(resolve42, reject, d2, v2) {
    Promise.resolve(v2).then(function(v3) {
      resolve42({ value: v3, done: d2 });
    }, reject);
  }
  __name(settle2, "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 i4 = 0;
  while (i4 < length) {
    if (comprehensiveHistory[i4].role === "user") {
      curatedHistory.push(comprehensiveHistory[i4]);
      i4++;
    } else {
      const modelOutput = [];
      let isValid2 = true;
      while (i4 < length && comprehensiveHistory[i4].role === "model") {
        modelOutput.push(comprehensiveHistory[i4]);
        if (isValid2 && !isValidContent(comprehensiveHistory[i4])) {
          isValid2 = false;
        }
        i4++;
      }
      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(...args2) {
  hasMcpToolUsageFromMcpToTool = true;
  if (args2.length === 0) {
    throw new Error("No MCP clients provided");
  }
  const maybeConfig = args2[args2.length - 1];
  if (isMcpClient(maybeConfig)) {
    return McpCallableTool.create(args2, {});
  }
  return McpCallableTool.create(args2.slice(0, args2.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(map3) {
  const headers = new Headers();
  for (const [key, value] of Object.entries(map3)) {
    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(map3) {
  const headers = new Headers();
  for (const [key, value] of Object.entries(map3)) {
    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 name4 = tFileName(params.file);
  if (name4 !== void 0) {
    return await apiClient.request({
      path: `files/${name4}: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(file2, uploadUrl, apiClient) {
  var _a7;
  const response = await uploadBlobInternal(file2, 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(file2, uploadUrl, apiClient) {
  var _a7;
  const response = await uploadBlobInternal(file2, 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(file2, uploadUrl, apiClient) {
  var _a7, _b2;
  let fileSize = 0;
  let offset = 0;
  let response = new HttpResponse(new Response());
  let uploadCommand = "upload";
  fileSize = file2.size;
  while (offset < fileSize) {
    const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);
    const chunk = file2.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(file2) {
  const fileStat = { size: file2.size, type: file2.type };
  return fileStat;
}
function sleep(ms) {
  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
}
function getEnv(env6) {
  var _a7, _b2, _c2;
  return (_c2 = (_b2 = (_a7 = process === null || process === void 0 ? void 0 : process.env) === null || _a7 === void 0 ? void 0 : _a7[env6]) === null || _b2 === void 0 ? void 0 : _b2.trim()) !== null && _c2 !== void 0 ? _c2 : void 0;
}
function getBooleanEnv(env6) {
  return stringToBoolean(getEnv(env6));
}
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, Language2, 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(Language4) {
      Language4["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED";
      Language4["PYTHON"] = "PYTHON";
    })(Language2 || (Language2 = {}));
    (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(name4, request4, response, params) {
        this.pageInternal = [];
        this.paramsInternal = {};
        this.requestInternal = request4;
        this.init(name4, response, params);
      }
      init(name4, response, params) {
        var _a7, _b2;
        this.nameInternal = name4;
        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 body2 = createBatchJobParametersToMldev(
          this.apiClient,
          // Use instance apiClient
          params
        );
        const urlParams = body2["_url"];
        const path150 = formatMap("{model}:batchGenerateContent", urlParams);
        const batch = body2["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 body2["config"];
        delete body2["_url"];
        delete body2["_query"];
        return { path: path150, body: body2 };
      }
      // 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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = createBatchJobParametersToVertex(this.apiClient, params);
          path150 = formatMap("batchPredictionJobs", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = createBatchJobParametersToMldev(this.apiClient, params);
          path150 = formatMap("{model}:batchGenerateContent", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = createEmbeddingsBatchJobParametersToMldev(this.apiClient, params);
          path150 = formatMap("{model}:asyncBatchEmbedContent", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = getBatchJobParametersToVertex(this.apiClient, params);
          path150 = formatMap("batchPredictionJobs/{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = getBatchJobParametersToMldev(this.apiClient, params);
          path150 = formatMap("batches/{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = cancelBatchJobParametersToVertex(this.apiClient, params);
          path150 = formatMap("batchPredictionJobs/{name}:cancel", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          await this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = cancelBatchJobParametersToMldev(this.apiClient, params);
          path150 = formatMap("batches/{name}:cancel", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          await this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = listBatchJobsParametersToVertex(params);
          path150 = formatMap("batchPredictionJobs", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = listBatchJobsParametersToMldev(params);
          path150 = formatMap("batches", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = deleteBatchJobParametersToVertex(this.apiClient, params);
          path150 = formatMap("batchPredictionJobs/{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = deleteBatchJobParametersToMldev(this.apiClient, params);
          path150 = formatMap("batches/{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = createCachedContentParametersToVertex(this.apiClient, params);
          path150 = formatMap("cachedContents", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = createCachedContentParametersToMldev(this.apiClient, params);
          path150 = formatMap("cachedContents", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = getCachedContentParametersToVertex(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = getCachedContentParametersToMldev(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = deleteCachedContentParametersToVertex(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = deleteCachedContentParametersToMldev(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = updateCachedContentParametersToVertex(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = updateCachedContentParametersToMldev(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = listCachedContentsParametersToVertex(params);
          path150 = formatMap("cachedContents", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = listCachedContentsParametersToMldev(params);
          path150 = formatMap("cachedContents", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = listFilesParametersToMldev(params);
          path150 = formatMap("files", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = createFileParametersToMldev(params);
          path150 = formatMap("upload/v1beta/files", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = getFileParametersToMldev(params);
          path150 = formatMap("files/{file}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = deleteFileParametersToMldev(params);
          path150 = formatMap("files/{file}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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(url3) {
        if (this.clientOptions.httpOptions) {
          this.clientOptions.httpOptions.baseUrl = url3;
        } else {
          throw new Error("HTTP options are not correctly set.");
        }
      }
      constructUrl(path150, httpOptions, prependProjectLocation) {
        const urlElement = [this.getRequestUrlInternal(httpOptions)];
        if (prependProjectLocation) {
          urlElement.push(this.getBaseResourcePath());
        }
        if (path150 !== "") {
          urlElement.push(path150);
        }
        const url3 = new URL(`${urlElement.join("/")}`);
        return url3;
      }
      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 url3 = this.constructUrl(request4.path, patchedHttpOptions, prependProjectLocation);
        if (request4.queryParams) {
          for (const [key, value] of Object.entries(request4.queryParams)) {
            url3.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, url3.toString(), request4.abortSignal);
        return this.unaryApiCall(url3, 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 url3 = this.constructUrl(request4.path, patchedHttpOptions, prependProjectLocation);
        if (!url3.searchParams.has("alt") || url3.searchParams.get("alt") !== "sse") {
          url3.searchParams.set("alt", "sse");
        }
        let requestInit = {};
        requestInit.body = request4.body;
        requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url3.toString(), request4.abortSignal);
        return this.streamApiCall(url3, requestInit, request4.httpMethod);
      }
      async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, url3, 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, url3);
        return requestInit;
      }
      async unaryApiCall(url3, requestInit, httpMethod) {
        return this.apiCall(url3.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(url3, requestInit, httpMethod) {
        return this.apiCall(url3.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 error40 = e4;
                if (error40.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(url3, requestInit) {
        return fetch(url3, 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, url3) {
        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, url3);
        return headers;
      }
      getFileName(file2) {
        var _a7;
        let fileName = "";
        if (typeof file2 === "string") {
          fileName = file2.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(file2, 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(file2);
        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 body2 = {
          file: fileToUpload
        };
        const fileName = this.getFileName(file2);
        const path150 = formatMap("upload/v1beta/files", body2["_url"]);
        const uploadUrl = await this.fetchUploadUrl(path150, fileToUpload.sizeBytes, fileToUpload.mimeType, fileName, body2, config2 === null || config2 === void 0 ? void 0 : config2.httpOptions);
        return uploader.upload(file2, 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, file2, config2) {
        var _a7;
        const uploader = this.clientOptions.uploader;
        const fileStat = await uploader.stat(file2);
        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 path150 = `upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`;
        const fileName = this.getFileName(file2);
        const body2 = {};
        if (config2 === null || config2 === void 0 ? void 0 : config2.customMetadata) {
          body2["customMetadata"] = config2.customMetadata;
        }
        if (config2 === null || config2 === void 0 ? void 0 : config2.chunkingConfig) {
          body2["chunkingConfig"] = config2.chunkingConfig;
        }
        const uploadUrl = await this.fetchUploadUrl(path150, sizeBytes, mimeType, fileName, body2, config2 === null || config2 === void 0 ? void 0 : config2.httpOptions);
        return uploader.uploadToFileSearchStore(file2, 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(path150, sizeBytes, mimeType, fileName, body2, 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: path150,
          body: JSON.stringify(body2),
          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 url3 = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`;
        let onopenResolve = /* @__PURE__ */ __name(() => {
        }, "onopenResolve");
        const onopenPromise = new Promise((resolve42) => {
          onopenResolve = resolve42;
        });
        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(url3, 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 url3;
        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()) {
          url3 = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`;
          await this.auth.addAuthHeaders(headers, url3);
        } 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";
          }
          url3 = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName2}=${apiKey}`;
        }
        let onopenResolve = /* @__PURE__ */ __name(() => {
        }, "onopenResolve");
        const onopenPromise = new Promise((resolve42) => {
          onopenResolve = resolve42;
        });
        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(url3, 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 parts2 = await callableTool.callTool(response.functionCalls);
                functionResponseParts.push(...parts2);
              }
            }
            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 defaultConfig2 = {
            queryBase: true
          };
          const actualConfig = Object.assign(Object.assign({}, defaultConfig2), 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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = generateContentParametersToVertex(this.apiClient, params);
          path150 = formatMap("{model}:generateContent", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = generateContentParametersToMldev(this.apiClient, params);
          path150 = formatMap("{model}:generateContent", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = generateContentParametersToVertex(this.apiClient, params);
          path150 = formatMap("{model}:streamGenerateContent?alt=sse", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          const apiClient = this.apiClient;
          response = apiClient.requestStream({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = generateContentParametersToMldev(this.apiClient, params);
          path150 = formatMap("{model}:streamGenerateContent?alt=sse", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          const apiClient = this.apiClient;
          response = apiClient.requestStream({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = embedContentParametersToVertex(this.apiClient, params);
          path150 = formatMap("{model}:predict", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = embedContentParametersToMldev(this.apiClient, params);
          path150 = formatMap("{model}:batchEmbedContents", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = generateImagesParametersToVertex(this.apiClient, params);
          path150 = formatMap("{model}:predict", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = generateImagesParametersToMldev(this.apiClient, params);
          path150 = formatMap("{model}:predict", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = editImageParametersInternalToVertex(this.apiClient, params);
          path150 = formatMap("{model}:predict", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = upscaleImageAPIParametersInternalToVertex(this.apiClient, params);
          path150 = formatMap("{model}:predict", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = recontextImageParametersToVertex(this.apiClient, params);
          path150 = formatMap("{model}:predict", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = segmentImageParametersToVertex(this.apiClient, params);
          path150 = formatMap("{model}:predict", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = getModelParametersToVertex(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = getModelParametersToMldev(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = listModelsParametersToVertex(this.apiClient, params);
          path150 = formatMap("{models_url}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = listModelsParametersToMldev(this.apiClient, params);
          path150 = formatMap("{models_url}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = updateModelParametersToVertex(this.apiClient, params);
          path150 = formatMap("{model}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = updateModelParametersToMldev(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = deleteModelParametersToVertex(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = deleteModelParametersToMldev(this.apiClient, params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = countTokensParametersToVertex(this.apiClient, params);
          path150 = formatMap("{model}:countTokens", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = countTokensParametersToMldev(this.apiClient, params);
          path150 = formatMap("{model}:countTokens", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = computeTokensParametersToVertex(this.apiClient, params);
          path150 = formatMap("{model}:computeTokens", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = generateVideosParametersToVertex(this.apiClient, params);
          path150 = formatMap("{model}:predictLongRunning", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = generateVideosParametersToMldev(this.apiClient, params);
          path150 = formatMap("{model}:predictLongRunning", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = getOperationParametersToVertex(params);
          path150 = formatMap("{operationName}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = getOperationParametersToMldev(params);
          path150 = formatMap("{operationName}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = fetchPredictOperationParametersToVertex(params);
          path150 = formatMap("{resourceName}:fetchPredictOperation", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");
        } else {
          const body2 = createAuthTokenParametersToMldev(this.apiClient, params);
          path150 = formatMap("auth_tokens", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["config"];
          delete body2["_url"];
          delete body2["_query"];
          const transformedBody = convertBidiSetupToTokenSetup(body2, params.config);
          response = this.apiClient.request({
            path: path150,
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = getDocumentParametersToMldev(params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = deleteDocumentParametersToMldev(params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          await this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = listDocumentsParametersToMldev(params);
          path150 = formatMap("{parent}/documents", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = createFileSearchStoreParametersToMldev(params);
          path150 = formatMap("fileSearchStores", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = getFileSearchStoreParametersToMldev(params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = deleteFileSearchStoreParametersToMldev(params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          await this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = listFileSearchStoresParametersToMldev(params);
          path150 = formatMap("fileSearchStores", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = uploadToFileSearchStoreParametersToMldev(params);
          path150 = formatMap("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = importFileParametersToMldev(params);
          path150 = formatMap("{file_search_store_name}:importFile", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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, url3) {
        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, url3);
      }
      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, url3) {
        if (this.googleAuth === void 0) {
          throw new Error("Trying to set google-auth headers but googleAuth is unset");
        }
        const authHeaders = await this.googleAuth.getRequestHeaders(url3);
        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 body2 = Readable.fromWeb(response.responseInternal.body);
            body2.pipe(writer);
            await finished(writer);
          } else {
            try {
              await writeFile2(params.downloadPath, response, {
                encoding: "base64"
              });
            } catch (error40) {
              throw new Error(`Failed to write file to ${params.downloadPath}: ${error40}`);
            }
          }
        }
      }
    };
    __name(downloadFile, "downloadFile");
    NodeWebSocketFactory = class {
      static {
        __name(this, "NodeWebSocketFactory");
      }
      create(url3, headers, callbacks) {
        return new NodeWebSocket(url3, headers, callbacks);
      }
    };
    NodeWebSocket = class {
      static {
        __name(this, "NodeWebSocket");
      }
      constructor(url3, headers, callbacks) {
        this.url = url3;
        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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = getTuningJobParametersToVertex(params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = getTuningJobParametersToMldev(params);
          path150 = formatMap("{name}", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = listTuningJobsParametersToVertex(params);
          path150 = formatMap("tuningJobs", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = listTuningJobsParametersToMldev(params);
          path150 = formatMap("tunedModels", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = cancelTuningJobParametersToVertex(params);
          path150 = formatMap("{name}:cancel", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          await this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 body2 = cancelTuningJobParametersToMldev(params);
          path150 = formatMap("{name}:cancel", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          await this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          const body2 = createTuningJobParametersPrivateToVertex(params, params);
          path150 = formatMap("tuningJobs", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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 path150 = "";
        let queryParams = {};
        if (this.apiClient.isVertexAI()) {
          throw new Error("This method is only supported by the Gemini Developer API.");
        } else {
          const body2 = createTuningJobParametersPrivateToMldev(params);
          path150 = formatMap("tunedModels", body2["_url"]);
          queryParams = body2["_query"];
          delete body2["_url"];
          delete body2["_query"];
          response = this.apiClient.request({
            path: path150,
            queryParams,
            body: JSON.stringify(body2),
            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(file2) {
        const fileStat = { size: 0, type: void 0 };
        if (typeof file2 === "string") {
          const originalStat = await fs10.stat(file2);
          fileStat.size = originalStat.size;
          fileStat.type = this.inferMimeType(file2);
          return fileStat;
        } else {
          return await getBlobStat(file2);
        }
      }
      async upload(file2, uploadUrl, apiClient) {
        if (typeof file2 === "string") {
          return await this.uploadFileFromPath(file2, uploadUrl, apiClient);
        } else {
          return uploadBlob(file2, uploadUrl, apiClient);
        }
      }
      async uploadToFileSearchStore(file2, uploadUrl, apiClient) {
        if (typeof file2 === "string") {
          return await this.uploadFileToFileSearchStoreFromPath(file2, uploadUrl, apiClient);
        } else {
          return uploadBlobToFileSearchStore(file2, 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(file2, uploadUrl, apiClient) {
        var _a7;
        const response = await this.uploadFileFromPathInternal(file2, 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(file2, uploadUrl, apiClient) {
        var _a7;
        const response = await this.uploadFileFromPathInternal(file2, 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(file2, uploadUrl, apiClient) {
        var _a7, _b2;
        let fileSize = 0;
        let offset = 0;
        let response = new HttpResponse(new Response());
        let uploadCommand = "upload";
        let fileHandle;
        const fileName = path7.basename(file2);
        try {
          fileHandle = await fs10.open(file2, "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-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",
      AGENT: "agent",
      SKILL: "skill",
      EXIT_PLAN_MODE: "exit_plan_mode",
      WEB_FETCH: "web_fetch",
      LS: "list_directory",
      LSP: "lsp",
      ASK_USER_QUESTION: "ask_user_question",
      CRON_CREATE: "cron_create",
      CRON_LIST: "cron_list",
      CRON_DELETE: "cron_delete",
      TASK_STOP: "task_stop",
      SEND_MESSAGE: "send_message"
    };
    ToolDisplayNames = {
      EDIT: "Edit",
      WRITE_FILE: "WriteFile",
      READ_FILE: "ReadFile",
      GREP: "Grep",
      GLOB: "Glob",
      SHELL: "Shell",
      TODO_WRITE: "TodoWrite",
      MEMORY: "SaveMemory",
      AGENT: "Agent",
      SKILL: "Skill",
      EXIT_PLAN_MODE: "ExitPlanMode",
      WEB_FETCH: "WebFetch",
      LS: "ListFiles",
      LSP: "Lsp",
      ASK_USER_QUESTION: "AskUserQuestion",
      CRON_CREATE: "CronCreate",
      CRON_LIST: "CronList",
      CRON_DELETE: "CronDelete",
      TASK_STOP: "TaskStop",
      SEND_MESSAGE: "SendMessage"
    };
    ToolNamesMigration = {
      search_file_content: ToolNames.GREP,
      // Legacy name from grep tool
      replace: ToolNames.EDIT,
      // Legacy name from edit tool
      task: ToolNames.AGENT
      // Legacy name from agent tool (renamed from task)
    };
    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
      Task: ToolDisplayNames.AGENT
      // Old display name for Agent (renamed from Task)
    };
  }
});

// packages/core/node_modules/mime/dist/types/standard.js
var types3, standard_default;
var init_standard = __esm({
  "packages/core/node_modules/mime/dist/types/standard.js"() {
    init_esbuild_shims();
    types3 = {
      "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(types3);
    standard_default = types3;
  }
});

// packages/core/node_modules/mime/dist/src/Mime.js
var __classPrivateFieldGet, _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();
    __classPrivateFieldGet = 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(...args2) {
        _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 args2) {
          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 (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) {
            __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set());
          }
          const allExtensions = __classPrivateFieldGet(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) {
              __classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
            }
            first2 = false;
            if (starred)
              continue;
            const currentType = __classPrivateFieldGet(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.`);
            }
            __classPrivateFieldGet(this, _Mime_extensionToType, "f").set(extension, type);
          }
        }
        return this;
      }
      getType(path150) {
        if (typeof path150 !== "string")
          return null;
        const last2 = path150.replace(/^.*[/\\]/s, "").toLowerCase();
        const ext2 = last2.replace(/^.*\./s, "").toLowerCase();
        const hasPath = last2.length < path150.length;
        const hasDot = ext2.length < last2.length - 1;
        if (!hasDot && hasPath)
          return null;
        return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext2) ?? null;
      }
      getExtension(type) {
        if (typeof type !== "string")
          return null;
        type = type?.split?.(";")[0];
        return (type && __classPrivateFieldGet(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null;
      }
      getAllExtensions(type) {
        if (typeof type !== "string")
          return null;
        return __classPrivateFieldGet(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 __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) {
          Object.freeze(extensions);
        }
        return this;
      }
      _getTestState() {
        return {
          types: __classPrivateFieldGet(this, _Mime_extensionToType, "f"),
          extensions: __classPrivateFieldGet(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();
  }
});

// node_modules/safer-buffer/safer.js
var require_safer = __commonJS({
  "node_modules/safer-buffer/safer.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var buffer = __require("buffer");
    var Buffer9 = buffer.Buffer;
    var safer = {};
    var key;
    for (key in buffer) {
      if (!buffer.hasOwnProperty(key)) continue;
      if (key === "SlowBuffer" || key === "Buffer") continue;
      safer[key] = buffer[key];
    }
    var Safer = safer.Buffer = {};
    for (key in Buffer9) {
      if (!Buffer9.hasOwnProperty(key)) continue;
      if (key === "allocUnsafe" || key === "allocUnsafeSlow") continue;
      Safer[key] = Buffer9[key];
    }
    safer.Buffer.prototype = Buffer9.prototype;
    if (!Safer.from || Safer.from === Uint8Array.from) {
      Safer.from = function(value, encodingOrOffset, length) {
        if (typeof value === "number") {
          throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value);
        }
        if (value && typeof value.length === "undefined") {
          throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
        }
        return Buffer9(value, encodingOrOffset, length);
      };
    }
    if (!Safer.alloc) {
      Safer.alloc = function(size, fill, encoding) {
        if (typeof size !== "number") {
          throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size);
        }
        if (size < 0 || size >= 2 * (1 << 30)) {
          throw new RangeError('The value "' + size + '" is invalid for option "size"');
        }
        var buf = Buffer9(size);
        if (!fill || fill.length === 0) {
          buf.fill(0);
        } else if (typeof encoding === "string") {
          buf.fill(fill, encoding);
        } else {
          buf.fill(fill);
        }
        return buf;
      };
    }
    if (!safer.kStringMaxLength) {
      try {
        safer.kStringMaxLength = process.binding("buffer").kStringMaxLength;
      } catch (e4) {
      }
    }
    if (!safer.constants) {
      safer.constants = {
        MAX_LENGTH: safer.kMaxLength
      };
      if (safer.kStringMaxLength) {
        safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength;
      }
    }
    module2.exports = safer;
  }
});

// packages/core/node_modules/iconv-lite/lib/bom-handling.js
var require_bom_handling = __commonJS({
  "packages/core/node_modules/iconv-lite/lib/bom-handling.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var BOMChar = "\uFEFF";
    exports2.PrependBOM = PrependBOMWrapper;
    function PrependBOMWrapper(encoder, options2) {
      this.encoder = encoder;
      this.addBOM = true;
    }
    __name(PrependBOMWrapper, "PrependBOMWrapper");
    PrependBOMWrapper.prototype.write = function(str2) {
      if (this.addBOM) {
        str2 = BOMChar + str2;
        this.addBOM = false;
      }
      return this.encoder.write(str2);
    };
    PrependBOMWrapper.prototype.end = function() {
      return this.encoder.end();
    };
    exports2.StripBOM = StripBOMWrapper;
    function StripBOMWrapper(decoder, options2) {
      this.decoder = decoder;
      this.pass = false;
      this.options = options2 || {};
    }
    __name(StripBOMWrapper, "StripBOMWrapper");
    StripBOMWrapper.prototype.write = function(buf) {
      var res = this.decoder.write(buf);
      if (this.pass || !res) {
        return res;
      }
      if (res[0] === BOMChar) {
        res = res.slice(1);
        if (typeof this.options.stripBOM === "function") {
          this.options.stripBOM();
        }
      }
      this.pass = true;
      return res;
    };
    StripBOMWrapper.prototype.end = function() {
      return this.decoder.end();
    };
  }
});

// packages/core/node_modules/iconv-lite/lib/helpers/merge-exports.js
var require_merge_exports = __commonJS({
  "packages/core/node_modules/iconv-lite/lib/helpers/merge-exports.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var hasOwn3 = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn;
    function mergeModules(target, module3) {
      for (var key in module3) {
        if (hasOwn3(module3, key)) {
          target[key] = module3[key];
        }
      }
    }
    __name(mergeModules, "mergeModules");
    module2.exports = mergeModules;
  }
});

// packages/core/node_modules/iconv-lite/encodings/internal.js
var require_internal = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/internal.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Buffer9 = require_safer().Buffer;
    module2.exports = {
      // Encodings
      utf8: { type: "_internal", bomAware: true },
      cesu8: { type: "_internal", bomAware: true },
      unicode11utf8: "utf8",
      ucs2: { type: "_internal", bomAware: true },
      utf16le: "ucs2",
      binary: { type: "_internal" },
      base64: { type: "_internal" },
      hex: { type: "_internal" },
      // Codec.
      _internal: InternalCodec
    };
    function InternalCodec(codecOptions, iconv) {
      this.enc = codecOptions.encodingName;
      this.bomAware = codecOptions.bomAware;
      if (this.enc === "base64") {
        this.encoder = InternalEncoderBase64;
      } else if (this.enc === "utf8") {
        this.encoder = InternalEncoderUtf8;
      } else if (this.enc === "cesu8") {
        this.enc = "utf8";
        this.encoder = InternalEncoderCesu8;
        if (Buffer9.from("eda0bdedb2a9", "hex").toString() !== "\u{1F4A9}") {
          this.decoder = InternalDecoderCesu8;
          this.defaultCharUnicode = iconv.defaultCharUnicode;
        }
      }
    }
    __name(InternalCodec, "InternalCodec");
    InternalCodec.prototype.encoder = InternalEncoder;
    InternalCodec.prototype.decoder = InternalDecoder;
    var StringDecoder3 = __require("string_decoder").StringDecoder;
    function InternalDecoder(options2, codec) {
      this.decoder = new StringDecoder3(codec.enc);
    }
    __name(InternalDecoder, "InternalDecoder");
    InternalDecoder.prototype.write = function(buf) {
      if (!Buffer9.isBuffer(buf)) {
        buf = Buffer9.from(buf);
      }
      return this.decoder.write(buf);
    };
    InternalDecoder.prototype.end = function() {
      return this.decoder.end();
    };
    function InternalEncoder(options2, codec) {
      this.enc = codec.enc;
    }
    __name(InternalEncoder, "InternalEncoder");
    InternalEncoder.prototype.write = function(str2) {
      return Buffer9.from(str2, this.enc);
    };
    InternalEncoder.prototype.end = function() {
    };
    function InternalEncoderBase64(options2, codec) {
      this.prevStr = "";
    }
    __name(InternalEncoderBase64, "InternalEncoderBase64");
    InternalEncoderBase64.prototype.write = function(str2) {
      str2 = this.prevStr + str2;
      var completeQuads = str2.length - str2.length % 4;
      this.prevStr = str2.slice(completeQuads);
      str2 = str2.slice(0, completeQuads);
      return Buffer9.from(str2, "base64");
    };
    InternalEncoderBase64.prototype.end = function() {
      return Buffer9.from(this.prevStr, "base64");
    };
    function InternalEncoderCesu8(options2, codec) {
    }
    __name(InternalEncoderCesu8, "InternalEncoderCesu8");
    InternalEncoderCesu8.prototype.write = function(str2) {
      var buf = Buffer9.alloc(str2.length * 3);
      var bufIdx = 0;
      for (var i4 = 0; i4 < str2.length; i4++) {
        var charCode = str2.charCodeAt(i4);
        if (charCode < 128) {
          buf[bufIdx++] = charCode;
        } else if (charCode < 2048) {
          buf[bufIdx++] = 192 + (charCode >>> 6);
          buf[bufIdx++] = 128 + (charCode & 63);
        } else {
          buf[bufIdx++] = 224 + (charCode >>> 12);
          buf[bufIdx++] = 128 + (charCode >>> 6 & 63);
          buf[bufIdx++] = 128 + (charCode & 63);
        }
      }
      return buf.slice(0, bufIdx);
    };
    InternalEncoderCesu8.prototype.end = function() {
    };
    function InternalDecoderCesu8(options2, codec) {
      this.acc = 0;
      this.contBytes = 0;
      this.accBytes = 0;
      this.defaultCharUnicode = codec.defaultCharUnicode;
    }
    __name(InternalDecoderCesu8, "InternalDecoderCesu8");
    InternalDecoderCesu8.prototype.write = function(buf) {
      var acc = this.acc;
      var contBytes = this.contBytes;
      var accBytes = this.accBytes;
      var res = "";
      for (var i4 = 0; i4 < buf.length; i4++) {
        var curByte = buf[i4];
        if ((curByte & 192) !== 128) {
          if (contBytes > 0) {
            res += this.defaultCharUnicode;
            contBytes = 0;
          }
          if (curByte < 128) {
            res += String.fromCharCode(curByte);
          } else if (curByte < 224) {
            acc = curByte & 31;
            contBytes = 1;
            accBytes = 1;
          } else if (curByte < 240) {
            acc = curByte & 15;
            contBytes = 2;
            accBytes = 1;
          } else {
            res += this.defaultCharUnicode;
          }
        } else {
          if (contBytes > 0) {
            acc = acc << 6 | curByte & 63;
            contBytes--;
            accBytes++;
            if (contBytes === 0) {
              if (accBytes === 2 && acc < 128 && acc > 0) {
                res += this.defaultCharUnicode;
              } else if (accBytes === 3 && acc < 2048) {
                res += this.defaultCharUnicode;
              } else {
                res += String.fromCharCode(acc);
              }
            }
          } else {
            res += this.defaultCharUnicode;
          }
        }
      }
      this.acc = acc;
      this.contBytes = contBytes;
      this.accBytes = accBytes;
      return res;
    };
    InternalDecoderCesu8.prototype.end = function() {
      var res = 0;
      if (this.contBytes > 0) {
        res += this.defaultCharUnicode;
      }
      return res;
    };
    function InternalEncoderUtf8(options2, codec) {
      this.highSurrogate = "";
    }
    __name(InternalEncoderUtf8, "InternalEncoderUtf8");
    InternalEncoderUtf8.prototype.write = function(str2) {
      if (this.highSurrogate) {
        str2 = this.highSurrogate + str2;
        this.highSurrogate = "";
      }
      if (str2.length > 0) {
        var charCode = str2.charCodeAt(str2.length - 1);
        if (charCode >= 55296 && charCode < 56320) {
          this.highSurrogate = str2[str2.length - 1];
          str2 = str2.slice(0, str2.length - 1);
        }
      }
      return Buffer9.from(str2, this.enc);
    };
    InternalEncoderUtf8.prototype.end = function() {
      if (this.highSurrogate) {
        var str2 = this.highSurrogate;
        this.highSurrogate = "";
        return Buffer9.from(str2, this.enc);
      }
    };
  }
});

// packages/core/node_modules/iconv-lite/encodings/utf32.js
var require_utf32 = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/utf32.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Buffer9 = require_safer().Buffer;
    exports2._utf32 = Utf32Codec;
    function Utf32Codec(codecOptions, iconv) {
      this.iconv = iconv;
      this.bomAware = true;
      this.isLE = codecOptions.isLE;
    }
    __name(Utf32Codec, "Utf32Codec");
    exports2.utf32le = { type: "_utf32", isLE: true };
    exports2.utf32be = { type: "_utf32", isLE: false };
    exports2.ucs4le = "utf32le";
    exports2.ucs4be = "utf32be";
    Utf32Codec.prototype.encoder = Utf32Encoder;
    Utf32Codec.prototype.decoder = Utf32Decoder;
    function Utf32Encoder(options2, codec) {
      this.isLE = codec.isLE;
      this.highSurrogate = 0;
    }
    __name(Utf32Encoder, "Utf32Encoder");
    Utf32Encoder.prototype.write = function(str2) {
      var src = Buffer9.from(str2, "ucs2");
      var dst = Buffer9.alloc(src.length * 2);
      var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE;
      var offset = 0;
      for (var i4 = 0; i4 < src.length; i4 += 2) {
        var code2 = src.readUInt16LE(i4);
        var isHighSurrogate = code2 >= 55296 && code2 < 56320;
        var isLowSurrogate = code2 >= 56320 && code2 < 57344;
        if (this.highSurrogate) {
          if (isHighSurrogate || !isLowSurrogate) {
            write32.call(dst, this.highSurrogate, offset);
            offset += 4;
          } else {
            var codepoint = (this.highSurrogate - 55296 << 10 | code2 - 56320) + 65536;
            write32.call(dst, codepoint, offset);
            offset += 4;
            this.highSurrogate = 0;
            continue;
          }
        }
        if (isHighSurrogate) {
          this.highSurrogate = code2;
        } else {
          write32.call(dst, code2, offset);
          offset += 4;
          this.highSurrogate = 0;
        }
      }
      if (offset < dst.length) {
        dst = dst.slice(0, offset);
      }
      return dst;
    };
    Utf32Encoder.prototype.end = function() {
      if (!this.highSurrogate) {
        return;
      }
      var buf = Buffer9.alloc(4);
      if (this.isLE) {
        buf.writeUInt32LE(this.highSurrogate, 0);
      } else {
        buf.writeUInt32BE(this.highSurrogate, 0);
      }
      this.highSurrogate = 0;
      return buf;
    };
    function Utf32Decoder(options2, codec) {
      this.isLE = codec.isLE;
      this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0);
      this.overflow = [];
    }
    __name(Utf32Decoder, "Utf32Decoder");
    Utf32Decoder.prototype.write = function(src) {
      if (src.length === 0) {
        return "";
      }
      var i4 = 0;
      var codepoint = 0;
      var dst = Buffer9.alloc(src.length + 4);
      var offset = 0;
      var isLE = this.isLE;
      var overflow = this.overflow;
      var badChar = this.badChar;
      if (overflow.length > 0) {
        for (; i4 < src.length && overflow.length < 4; i4++) {
          overflow.push(src[i4]);
        }
        if (overflow.length === 4) {
          if (isLE) {
            codepoint = overflow[i4] | overflow[i4 + 1] << 8 | overflow[i4 + 2] << 16 | overflow[i4 + 3] << 24;
          } else {
            codepoint = overflow[i4 + 3] | overflow[i4 + 2] << 8 | overflow[i4 + 1] << 16 | overflow[i4] << 24;
          }
          overflow.length = 0;
          offset = _writeCodepoint(dst, offset, codepoint, badChar);
        }
      }
      for (; i4 < src.length - 3; i4 += 4) {
        if (isLE) {
          codepoint = src[i4] | src[i4 + 1] << 8 | src[i4 + 2] << 16 | src[i4 + 3] << 24;
        } else {
          codepoint = src[i4 + 3] | src[i4 + 2] << 8 | src[i4 + 1] << 16 | src[i4] << 24;
        }
        offset = _writeCodepoint(dst, offset, codepoint, badChar);
      }
      for (; i4 < src.length; i4++) {
        overflow.push(src[i4]);
      }
      return dst.slice(0, offset).toString("ucs2");
    };
    function _writeCodepoint(dst, offset, codepoint, badChar) {
      if (codepoint < 0 || codepoint > 1114111) {
        codepoint = badChar;
      }
      if (codepoint >= 65536) {
        codepoint -= 65536;
        var high = 55296 | codepoint >> 10;
        dst[offset++] = high & 255;
        dst[offset++] = high >> 8;
        var codepoint = 56320 | codepoint & 1023;
      }
      dst[offset++] = codepoint & 255;
      dst[offset++] = codepoint >> 8;
      return offset;
    }
    __name(_writeCodepoint, "_writeCodepoint");
    Utf32Decoder.prototype.end = function() {
      this.overflow.length = 0;
    };
    exports2.utf32 = Utf32AutoCodec;
    exports2.ucs4 = "utf32";
    function Utf32AutoCodec(options2, iconv) {
      this.iconv = iconv;
    }
    __name(Utf32AutoCodec, "Utf32AutoCodec");
    Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder;
    Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder;
    function Utf32AutoEncoder(options2, codec) {
      options2 = options2 || {};
      if (options2.addBOM === void 0) {
        options2.addBOM = true;
      }
      this.encoder = codec.iconv.getEncoder(options2.defaultEncoding || "utf-32le", options2);
    }
    __name(Utf32AutoEncoder, "Utf32AutoEncoder");
    Utf32AutoEncoder.prototype.write = function(str2) {
      return this.encoder.write(str2);
    };
    Utf32AutoEncoder.prototype.end = function() {
      return this.encoder.end();
    };
    function Utf32AutoDecoder(options2, codec) {
      this.decoder = null;
      this.initialBufs = [];
      this.initialBufsLen = 0;
      this.options = options2 || {};
      this.iconv = codec.iconv;
    }
    __name(Utf32AutoDecoder, "Utf32AutoDecoder");
    Utf32AutoDecoder.prototype.write = function(buf) {
      if (!this.decoder) {
        this.initialBufs.push(buf);
        this.initialBufsLen += buf.length;
        if (this.initialBufsLen < 32) {
          return "";
        }
        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
        this.decoder = this.iconv.getDecoder(encoding, this.options);
        var resStr = "";
        for (var i4 = 0; i4 < this.initialBufs.length; i4++) {
          resStr += this.decoder.write(this.initialBufs[i4]);
        }
        this.initialBufs.length = this.initialBufsLen = 0;
        return resStr;
      }
      return this.decoder.write(buf);
    };
    Utf32AutoDecoder.prototype.end = function() {
      if (!this.decoder) {
        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
        this.decoder = this.iconv.getDecoder(encoding, this.options);
        var resStr = "";
        for (var i4 = 0; i4 < this.initialBufs.length; i4++) {
          resStr += this.decoder.write(this.initialBufs[i4]);
        }
        var trail = this.decoder.end();
        if (trail) {
          resStr += trail;
        }
        this.initialBufs.length = this.initialBufsLen = 0;
        return resStr;
      }
      return this.decoder.end();
    };
    function detectEncoding(bufs, defaultEncoding) {
      var b2 = [];
      var charsProcessed = 0;
      var invalidLE = 0;
      var invalidBE = 0;
      var bmpCharsLE = 0;
      var bmpCharsBE = 0;
      outerLoop:
        for (var i4 = 0; i4 < bufs.length; i4++) {
          var buf = bufs[i4];
          for (var j2 = 0; j2 < buf.length; j2++) {
            b2.push(buf[j2]);
            if (b2.length === 4) {
              if (charsProcessed === 0) {
                if (b2[0] === 255 && b2[1] === 254 && b2[2] === 0 && b2[3] === 0) {
                  return "utf-32le";
                }
                if (b2[0] === 0 && b2[1] === 0 && b2[2] === 254 && b2[3] === 255) {
                  return "utf-32be";
                }
              }
              if (b2[0] !== 0 || b2[1] > 16) invalidBE++;
              if (b2[3] !== 0 || b2[2] > 16) invalidLE++;
              if (b2[0] === 0 && b2[1] === 0 && (b2[2] !== 0 || b2[3] !== 0)) bmpCharsBE++;
              if ((b2[0] !== 0 || b2[1] !== 0) && b2[2] === 0 && b2[3] === 0) bmpCharsLE++;
              b2.length = 0;
              charsProcessed++;
              if (charsProcessed >= 100) {
                break outerLoop;
              }
            }
          }
        }
      if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return "utf-32be";
      if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return "utf-32le";
      return defaultEncoding || "utf-32le";
    }
    __name(detectEncoding, "detectEncoding");
  }
});

// packages/core/node_modules/iconv-lite/encodings/utf16.js
var require_utf16 = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/utf16.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Buffer9 = require_safer().Buffer;
    exports2.utf16be = Utf16BECodec;
    function Utf16BECodec() {
    }
    __name(Utf16BECodec, "Utf16BECodec");
    Utf16BECodec.prototype.encoder = Utf16BEEncoder;
    Utf16BECodec.prototype.decoder = Utf16BEDecoder;
    Utf16BECodec.prototype.bomAware = true;
    function Utf16BEEncoder() {
    }
    __name(Utf16BEEncoder, "Utf16BEEncoder");
    Utf16BEEncoder.prototype.write = function(str2) {
      var buf = Buffer9.from(str2, "ucs2");
      for (var i4 = 0; i4 < buf.length; i4 += 2) {
        var tmp = buf[i4];
        buf[i4] = buf[i4 + 1];
        buf[i4 + 1] = tmp;
      }
      return buf;
    };
    Utf16BEEncoder.prototype.end = function() {
    };
    function Utf16BEDecoder() {
      this.overflowByte = -1;
    }
    __name(Utf16BEDecoder, "Utf16BEDecoder");
    Utf16BEDecoder.prototype.write = function(buf) {
      if (buf.length == 0) {
        return "";
      }
      var buf2 = Buffer9.alloc(buf.length + 1);
      var i4 = 0;
      var j2 = 0;
      if (this.overflowByte !== -1) {
        buf2[0] = buf[0];
        buf2[1] = this.overflowByte;
        i4 = 1;
        j2 = 2;
      }
      for (; i4 < buf.length - 1; i4 += 2, j2 += 2) {
        buf2[j2] = buf[i4 + 1];
        buf2[j2 + 1] = buf[i4];
      }
      this.overflowByte = i4 == buf.length - 1 ? buf[buf.length - 1] : -1;
      return buf2.slice(0, j2).toString("ucs2");
    };
    Utf16BEDecoder.prototype.end = function() {
      this.overflowByte = -1;
    };
    exports2.utf16 = Utf16Codec;
    function Utf16Codec(codecOptions, iconv) {
      this.iconv = iconv;
    }
    __name(Utf16Codec, "Utf16Codec");
    Utf16Codec.prototype.encoder = Utf16Encoder;
    Utf16Codec.prototype.decoder = Utf16Decoder;
    function Utf16Encoder(options2, codec) {
      options2 = options2 || {};
      if (options2.addBOM === void 0) {
        options2.addBOM = true;
      }
      this.encoder = codec.iconv.getEncoder("utf-16le", options2);
    }
    __name(Utf16Encoder, "Utf16Encoder");
    Utf16Encoder.prototype.write = function(str2) {
      return this.encoder.write(str2);
    };
    Utf16Encoder.prototype.end = function() {
      return this.encoder.end();
    };
    function Utf16Decoder(options2, codec) {
      this.decoder = null;
      this.initialBufs = [];
      this.initialBufsLen = 0;
      this.options = options2 || {};
      this.iconv = codec.iconv;
    }
    __name(Utf16Decoder, "Utf16Decoder");
    Utf16Decoder.prototype.write = function(buf) {
      if (!this.decoder) {
        this.initialBufs.push(buf);
        this.initialBufsLen += buf.length;
        if (this.initialBufsLen < 16) {
          return "";
        }
        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
        this.decoder = this.iconv.getDecoder(encoding, this.options);
        var resStr = "";
        for (var i4 = 0; i4 < this.initialBufs.length; i4++) {
          resStr += this.decoder.write(this.initialBufs[i4]);
        }
        this.initialBufs.length = this.initialBufsLen = 0;
        return resStr;
      }
      return this.decoder.write(buf);
    };
    Utf16Decoder.prototype.end = function() {
      if (!this.decoder) {
        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
        this.decoder = this.iconv.getDecoder(encoding, this.options);
        var resStr = "";
        for (var i4 = 0; i4 < this.initialBufs.length; i4++) {
          resStr += this.decoder.write(this.initialBufs[i4]);
        }
        var trail = this.decoder.end();
        if (trail) {
          resStr += trail;
        }
        this.initialBufs.length = this.initialBufsLen = 0;
        return resStr;
      }
      return this.decoder.end();
    };
    function detectEncoding(bufs, defaultEncoding) {
      var b2 = [];
      var charsProcessed = 0;
      var asciiCharsLE = 0;
      var asciiCharsBE = 0;
      outerLoop:
        for (var i4 = 0; i4 < bufs.length; i4++) {
          var buf = bufs[i4];
          for (var j2 = 0; j2 < buf.length; j2++) {
            b2.push(buf[j2]);
            if (b2.length === 2) {
              if (charsProcessed === 0) {
                if (b2[0] === 255 && b2[1] === 254) return "utf-16le";
                if (b2[0] === 254 && b2[1] === 255) return "utf-16be";
              }
              if (b2[0] === 0 && b2[1] !== 0) asciiCharsBE++;
              if (b2[0] !== 0 && b2[1] === 0) asciiCharsLE++;
              b2.length = 0;
              charsProcessed++;
              if (charsProcessed >= 100) {
                break outerLoop;
              }
            }
          }
        }
      if (asciiCharsBE > asciiCharsLE) return "utf-16be";
      if (asciiCharsBE < asciiCharsLE) return "utf-16le";
      return defaultEncoding || "utf-16le";
    }
    __name(detectEncoding, "detectEncoding");
  }
});

// packages/core/node_modules/iconv-lite/encodings/utf7.js
var require_utf7 = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/utf7.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Buffer9 = require_safer().Buffer;
    exports2.utf7 = Utf7Codec;
    exports2.unicode11utf7 = "utf7";
    function Utf7Codec(codecOptions, iconv) {
      this.iconv = iconv;
    }
    __name(Utf7Codec, "Utf7Codec");
    Utf7Codec.prototype.encoder = Utf7Encoder;
    Utf7Codec.prototype.decoder = Utf7Decoder;
    Utf7Codec.prototype.bomAware = true;
    var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;
    function Utf7Encoder(options2, codec) {
      this.iconv = codec.iconv;
    }
    __name(Utf7Encoder, "Utf7Encoder");
    Utf7Encoder.prototype.write = function(str2) {
      return Buffer9.from(str2.replace(nonDirectChars, function(chunk) {
        return "+" + (chunk === "+" ? "" : this.iconv.encode(chunk, "utf16-be").toString("base64").replace(/=+$/, "")) + "-";
      }.bind(this)));
    };
    Utf7Encoder.prototype.end = function() {
    };
    function Utf7Decoder(options2, codec) {
      this.iconv = codec.iconv;
      this.inBase64 = false;
      this.base64Accum = "";
    }
    __name(Utf7Decoder, "Utf7Decoder");
    var base64Regex2 = /[A-Za-z0-9\/+]/;
    var base64Chars = [];
    for (i4 = 0; i4 < 256; i4++) {
      base64Chars[i4] = base64Regex2.test(String.fromCharCode(i4));
    }
    var i4;
    var plusChar = "+".charCodeAt(0);
    var minusChar = "-".charCodeAt(0);
    var andChar = "&".charCodeAt(0);
    Utf7Decoder.prototype.write = function(buf) {
      var res = "";
      var lastI = 0;
      var inBase64 = this.inBase64;
      var base64Accum = this.base64Accum;
      for (var i5 = 0; i5 < buf.length; i5++) {
        if (!inBase64) {
          if (buf[i5] == plusChar) {
            res += this.iconv.decode(buf.slice(lastI, i5), "ascii");
            lastI = i5 + 1;
            inBase64 = true;
          }
        } else {
          if (!base64Chars[buf[i5]]) {
            if (i5 == lastI && buf[i5] == minusChar) {
              res += "+";
            } else {
              var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i5), "ascii");
              res += this.iconv.decode(Buffer9.from(b64str, "base64"), "utf16-be");
            }
            if (buf[i5] != minusChar) {
              i5--;
            }
            lastI = i5 + 1;
            inBase64 = false;
            base64Accum = "";
          }
        }
      }
      if (!inBase64) {
        res += this.iconv.decode(buf.slice(lastI), "ascii");
      } else {
        var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii");
        var canBeDecoded = b64str.length - b64str.length % 8;
        base64Accum = b64str.slice(canBeDecoded);
        b64str = b64str.slice(0, canBeDecoded);
        res += this.iconv.decode(Buffer9.from(b64str, "base64"), "utf16-be");
      }
      this.inBase64 = inBase64;
      this.base64Accum = base64Accum;
      return res;
    };
    Utf7Decoder.prototype.end = function() {
      var res = "";
      if (this.inBase64 && this.base64Accum.length > 0) {
        res = this.iconv.decode(Buffer9.from(this.base64Accum, "base64"), "utf16-be");
      }
      this.inBase64 = false;
      this.base64Accum = "";
      return res;
    };
    exports2.utf7imap = Utf7IMAPCodec;
    function Utf7IMAPCodec(codecOptions, iconv) {
      this.iconv = iconv;
    }
    __name(Utf7IMAPCodec, "Utf7IMAPCodec");
    Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;
    Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;
    Utf7IMAPCodec.prototype.bomAware = true;
    function Utf7IMAPEncoder(options2, codec) {
      this.iconv = codec.iconv;
      this.inBase64 = false;
      this.base64Accum = Buffer9.alloc(6);
      this.base64AccumIdx = 0;
    }
    __name(Utf7IMAPEncoder, "Utf7IMAPEncoder");
    Utf7IMAPEncoder.prototype.write = function(str2) {
      var inBase64 = this.inBase64;
      var base64Accum = this.base64Accum;
      var base64AccumIdx = this.base64AccumIdx;
      var buf = Buffer9.alloc(str2.length * 5 + 10);
      var bufIdx = 0;
      for (var i5 = 0; i5 < str2.length; i5++) {
        var uChar = str2.charCodeAt(i5);
        if (uChar >= 32 && uChar <= 126) {
          if (inBase64) {
            if (base64AccumIdx > 0) {
              bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString("base64").replace(/\//g, ",").replace(/=+$/, ""), bufIdx);
              base64AccumIdx = 0;
            }
            buf[bufIdx++] = minusChar;
            inBase64 = false;
          }
          if (!inBase64) {
            buf[bufIdx++] = uChar;
            if (uChar === andChar) {
              buf[bufIdx++] = minusChar;
            }
          }
        } else {
          if (!inBase64) {
            buf[bufIdx++] = andChar;
            inBase64 = true;
          }
          if (inBase64) {
            base64Accum[base64AccumIdx++] = uChar >> 8;
            base64Accum[base64AccumIdx++] = uChar & 255;
            if (base64AccumIdx == base64Accum.length) {
              bufIdx += buf.write(base64Accum.toString("base64").replace(/\//g, ","), bufIdx);
              base64AccumIdx = 0;
            }
          }
        }
      }
      this.inBase64 = inBase64;
      this.base64AccumIdx = base64AccumIdx;
      return buf.slice(0, bufIdx);
    };
    Utf7IMAPEncoder.prototype.end = function() {
      var buf = Buffer9.alloc(10);
      var bufIdx = 0;
      if (this.inBase64) {
        if (this.base64AccumIdx > 0) {
          bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString("base64").replace(/\//g, ",").replace(/=+$/, ""), bufIdx);
          this.base64AccumIdx = 0;
        }
        buf[bufIdx++] = minusChar;
        this.inBase64 = false;
      }
      return buf.slice(0, bufIdx);
    };
    function Utf7IMAPDecoder(options2, codec) {
      this.iconv = codec.iconv;
      this.inBase64 = false;
      this.base64Accum = "";
    }
    __name(Utf7IMAPDecoder, "Utf7IMAPDecoder");
    var base64IMAPChars = base64Chars.slice();
    base64IMAPChars[",".charCodeAt(0)] = true;
    Utf7IMAPDecoder.prototype.write = function(buf) {
      var res = "";
      var lastI = 0;
      var inBase64 = this.inBase64;
      var base64Accum = this.base64Accum;
      for (var i5 = 0; i5 < buf.length; i5++) {
        if (!inBase64) {
          if (buf[i5] == andChar) {
            res += this.iconv.decode(buf.slice(lastI, i5), "ascii");
            lastI = i5 + 1;
            inBase64 = true;
          }
        } else {
          if (!base64IMAPChars[buf[i5]]) {
            if (i5 == lastI && buf[i5] == minusChar) {
              res += "&";
            } else {
              var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i5), "ascii").replace(/,/g, "/");
              res += this.iconv.decode(Buffer9.from(b64str, "base64"), "utf16-be");
            }
            if (buf[i5] != minusChar) {
              i5--;
            }
            lastI = i5 + 1;
            inBase64 = false;
            base64Accum = "";
          }
        }
      }
      if (!inBase64) {
        res += this.iconv.decode(buf.slice(lastI), "ascii");
      } else {
        var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, "/");
        var canBeDecoded = b64str.length - b64str.length % 8;
        base64Accum = b64str.slice(canBeDecoded);
        b64str = b64str.slice(0, canBeDecoded);
        res += this.iconv.decode(Buffer9.from(b64str, "base64"), "utf16-be");
      }
      this.inBase64 = inBase64;
      this.base64Accum = base64Accum;
      return res;
    };
    Utf7IMAPDecoder.prototype.end = function() {
      var res = "";
      if (this.inBase64 && this.base64Accum.length > 0) {
        res = this.iconv.decode(Buffer9.from(this.base64Accum, "base64"), "utf16-be");
      }
      this.inBase64 = false;
      this.base64Accum = "";
      return res;
    };
  }
});

// packages/core/node_modules/iconv-lite/encodings/sbcs-codec.js
var require_sbcs_codec = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/sbcs-codec.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Buffer9 = require_safer().Buffer;
    exports2._sbcs = SBCSCodec;
    function SBCSCodec(codecOptions, iconv) {
      if (!codecOptions) {
        throw new Error("SBCS codec is called without the data.");
      }
      if (!codecOptions.chars || codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256) {
        throw new Error("Encoding '" + codecOptions.type + "' has incorrect 'chars' (must be of len 128 or 256)");
      }
      if (codecOptions.chars.length === 128) {
        var asciiString = "";
        for (var i4 = 0; i4 < 128; i4++) {
          asciiString += String.fromCharCode(i4);
        }
        codecOptions.chars = asciiString + codecOptions.chars;
      }
      this.decodeBuf = Buffer9.from(codecOptions.chars, "ucs2");
      var encodeBuf = Buffer9.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
      for (var i4 = 0; i4 < codecOptions.chars.length; i4++) {
        encodeBuf[codecOptions.chars.charCodeAt(i4)] = i4;
      }
      this.encodeBuf = encodeBuf;
    }
    __name(SBCSCodec, "SBCSCodec");
    SBCSCodec.prototype.encoder = SBCSEncoder;
    SBCSCodec.prototype.decoder = SBCSDecoder;
    function SBCSEncoder(options2, codec) {
      this.encodeBuf = codec.encodeBuf;
    }
    __name(SBCSEncoder, "SBCSEncoder");
    SBCSEncoder.prototype.write = function(str2) {
      var buf = Buffer9.alloc(str2.length);
      for (var i4 = 0; i4 < str2.length; i4++) {
        buf[i4] = this.encodeBuf[str2.charCodeAt(i4)];
      }
      return buf;
    };
    SBCSEncoder.prototype.end = function() {
    };
    function SBCSDecoder(options2, codec) {
      this.decodeBuf = codec.decodeBuf;
    }
    __name(SBCSDecoder, "SBCSDecoder");
    SBCSDecoder.prototype.write = function(buf) {
      var decodeBuf = this.decodeBuf;
      var newBuf = Buffer9.alloc(buf.length * 2);
      var idx1 = 0;
      var idx2 = 0;
      for (var i4 = 0; i4 < buf.length; i4++) {
        idx1 = buf[i4] * 2;
        idx2 = i4 * 2;
        newBuf[idx2] = decodeBuf[idx1];
        newBuf[idx2 + 1] = decodeBuf[idx1 + 1];
      }
      return newBuf.toString("ucs2");
    };
    SBCSDecoder.prototype.end = function() {
    };
  }
});

// packages/core/node_modules/iconv-lite/encodings/sbcs-data.js
var require_sbcs_data = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/sbcs-data.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      // Not supported by iconv, not sure why.
      10029: "maccenteuro",
      maccenteuro: {
        type: "_sbcs",
        chars: "\xC4\u0100\u0101\xC9\u0104\xD6\xDC\xE1\u0105\u010C\xE4\u010D\u0106\u0107\xE9\u0179\u017A\u010E\xED\u010F\u0112\u0113\u0116\xF3\u0117\xF4\xF6\xF5\xFA\u011A\u011B\xFC\u2020\xB0\u0118\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\u0119\xA8\u2260\u0123\u012E\u012F\u012A\u2264\u2265\u012B\u0136\u2202\u2211\u0142\u013B\u013C\u013D\u013E\u0139\u013A\u0145\u0146\u0143\xAC\u221A\u0144\u0147\u2206\xAB\xBB\u2026\xA0\u0148\u0150\xD5\u0151\u014C\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\u014D\u0154\u0155\u0158\u2039\u203A\u0159\u0156\u0157\u0160\u201A\u201E\u0161\u015A\u015B\xC1\u0164\u0165\xCD\u017D\u017E\u016A\xD3\xD4\u016B\u016E\xDA\u016F\u0170\u0171\u0172\u0173\xDD\xFD\u0137\u017B\u0141\u017C\u0122\u02C7"
      },
      808: "cp808",
      ibm808: "cp808",
      cp808: {
        type: "_sbcs",
        chars: "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\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\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0404\u0454\u0407\u0457\u040E\u045E\xB0\u2219\xB7\u221A\u2116\u20AC\u25A0\xA0"
      },
      mik: {
        type: "_sbcs",
        chars: "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2514\u2534\u252C\u251C\u2500\u253C\u2563\u2551\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2510\u2591\u2592\u2593\u2502\u2524\u2116\xA7\u2557\u255D\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"
      },
      cp720: {
        type: "_sbcs",
        chars: "\x80\x81\xE9\xE2\x84\xE0\x86\xE7\xEA\xEB\xE8\xEF\xEE\x8D\x8E\x8F\x90\u0651\u0652\xF4\xA4\u0640\xFB\xF9\u0621\u0622\u0623\u0624\xA3\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\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\u0636\u0637\u0638\u0639\u063A\u0641\xB5\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u2261\u064B\u064C\u064D\u064E\u064F\u0650\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"
      },
      // Aliases of generated encodings.
      ascii8bit: "ascii",
      usascii: "ascii",
      ansix34: "ascii",
      ansix341968: "ascii",
      ansix341986: "ascii",
      csascii: "ascii",
      cp367: "ascii",
      ibm367: "ascii",
      isoir6: "ascii",
      iso646us: "ascii",
      iso646irv: "ascii",
      us: "ascii",
      latin1: "iso88591",
      latin2: "iso88592",
      latin3: "iso88593",
      latin4: "iso88594",
      latin5: "iso88599",
      latin6: "iso885910",
      latin7: "iso885913",
      latin8: "iso885914",
      latin9: "iso885915",
      latin10: "iso885916",
      csisolatin1: "iso88591",
      csisolatin2: "iso88592",
      csisolatin3: "iso88593",
      csisolatin4: "iso88594",
      csisolatincyrillic: "iso88595",
      csisolatinarabic: "iso88596",
      csisolatingreek: "iso88597",
      csisolatinhebrew: "iso88598",
      csisolatin5: "iso88599",
      csisolatin6: "iso885910",
      l1: "iso88591",
      l2: "iso88592",
      l3: "iso88593",
      l4: "iso88594",
      l5: "iso88599",
      l6: "iso885910",
      l7: "iso885913",
      l8: "iso885914",
      l9: "iso885915",
      l10: "iso885916",
      isoir14: "iso646jp",
      isoir57: "iso646cn",
      isoir100: "iso88591",
      isoir101: "iso88592",
      isoir109: "iso88593",
      isoir110: "iso88594",
      isoir144: "iso88595",
      isoir127: "iso88596",
      isoir126: "iso88597",
      isoir138: "iso88598",
      isoir148: "iso88599",
      isoir157: "iso885910",
      isoir166: "tis620",
      isoir179: "iso885913",
      isoir199: "iso885914",
      isoir203: "iso885915",
      isoir226: "iso885916",
      cp819: "iso88591",
      ibm819: "iso88591",
      cyrillic: "iso88595",
      arabic: "iso88596",
      arabic8: "iso88596",
      ecma114: "iso88596",
      asmo708: "iso88596",
      greek: "iso88597",
      greek8: "iso88597",
      ecma118: "iso88597",
      elot928: "iso88597",
      hebrew: "iso88598",
      hebrew8: "iso88598",
      turkish: "iso88599",
      turkish8: "iso88599",
      thai: "iso885911",
      thai8: "iso885911",
      celtic: "iso885914",
      celtic8: "iso885914",
      isoceltic: "iso885914",
      tis6200: "tis620",
      tis62025291: "tis620",
      tis62025330: "tis620",
      1e4: "macroman",
      10006: "macgreek",
      10007: "maccyrillic",
      10079: "maciceland",
      10081: "macturkish",
      cspc8codepage437: "cp437",
      cspc775baltic: "cp775",
      cspc850multilingual: "cp850",
      cspcp852: "cp852",
      cspc862latinhebrew: "cp862",
      cpgr: "cp869",
      msee: "cp1250",
      mscyrl: "cp1251",
      msansi: "cp1252",
      msgreek: "cp1253",
      msturk: "cp1254",
      mshebr: "cp1255",
      msarab: "cp1256",
      winbaltrim: "cp1257",
      cp20866: "koi8r",
      20866: "koi8r",
      ibm878: "koi8r",
      cskoi8r: "koi8r",
      cp21866: "koi8u",
      21866: "koi8u",
      ibm1168: "koi8u",
      strk10482002: "rk1048",
      tcvn5712: "tcvn",
      tcvn57121: "tcvn",
      gb198880: "iso646cn",
      cn: "iso646cn",
      csiso14jisc6220ro: "iso646jp",
      jisc62201969ro: "iso646jp",
      jp: "iso646jp",
      cshproman8: "hproman8",
      r8: "hproman8",
      roman8: "hproman8",
      xroman8: "hproman8",
      ibm1051: "hproman8",
      mac: "macintosh",
      csmacintosh: "macintosh"
    };
  }
});

// packages/core/node_modules/iconv-lite/encodings/sbcs-data-generated.js
var require_sbcs_data_generated = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/sbcs-data-generated.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      "437": "cp437",
      "737": "cp737",
      "775": "cp775",
      "850": "cp850",
      "852": "cp852",
      "855": "cp855",
      "856": "cp856",
      "857": "cp857",
      "858": "cp858",
      "860": "cp860",
      "861": "cp861",
      "862": "cp862",
      "863": "cp863",
      "864": "cp864",
      "865": "cp865",
      "866": "cp866",
      "869": "cp869",
      "874": "windows874",
      "922": "cp922",
      "1046": "cp1046",
      "1124": "cp1124",
      "1125": "cp1125",
      "1129": "cp1129",
      "1133": "cp1133",
      "1161": "cp1161",
      "1162": "cp1162",
      "1163": "cp1163",
      "1250": "windows1250",
      "1251": "windows1251",
      "1252": "windows1252",
      "1253": "windows1253",
      "1254": "windows1254",
      "1255": "windows1255",
      "1256": "windows1256",
      "1257": "windows1257",
      "1258": "windows1258",
      "28591": "iso88591",
      "28592": "iso88592",
      "28593": "iso88593",
      "28594": "iso88594",
      "28595": "iso88595",
      "28596": "iso88596",
      "28597": "iso88597",
      "28598": "iso88598",
      "28599": "iso88599",
      "28600": "iso885910",
      "28601": "iso885911",
      "28603": "iso885913",
      "28604": "iso885914",
      "28605": "iso885915",
      "28606": "iso885916",
      "windows874": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\uFFFD\uFFFD\uFFFD\u2026\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "win874": "windows874",
      "cp874": "windows874",
      "windows1250": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\uFFFD\u201E\u2026\u2020\u2021\uFFFD\u2030\u0160\u2039\u015A\u0164\u017D\u0179\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0161\u203A\u015B\u0165\u017E\u017A\xA0\u02C7\u02D8\u0141\xA4\u0104\xA6\xA7\xA8\xA9\u015E\xAB\xAC\xAD\xAE\u017B\xB0\xB1\u02DB\u0142\xB4\xB5\xB6\xB7\xB8\u0105\u015F\xBB\u013D\u02DD\u013E\u017C\u0154\xC1\xC2\u0102\xC4\u0139\u0106\xC7\u010C\xC9\u0118\xCB\u011A\xCD\xCE\u010E\u0110\u0143\u0147\xD3\xD4\u0150\xD6\xD7\u0158\u016E\xDA\u0170\xDC\xDD\u0162\xDF\u0155\xE1\xE2\u0103\xE4\u013A\u0107\xE7\u010D\xE9\u0119\xEB\u011B\xED\xEE\u010F\u0111\u0144\u0148\xF3\xF4\u0151\xF6\xF7\u0159\u016F\xFA\u0171\xFC\xFD\u0163\u02D9"
      },
      "win1250": "windows1250",
      "cp1250": "windows1250",
      "windows1251": {
        "type": "_sbcs",
        "chars": "\u0402\u0403\u201A\u0453\u201E\u2026\u2020\u2021\u20AC\u2030\u0409\u2039\u040A\u040C\u040B\u040F\u0452\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0459\u203A\u045A\u045C\u045B\u045F\xA0\u040E\u045E\u0408\xA4\u0490\xA6\xA7\u0401\xA9\u0404\xAB\xAC\xAD\xAE\u0407\xB0\xB1\u0406\u0456\u0491\xB5\xB6\xB7\u0451\u2116\u0454\xBB\u0458\u0405\u0455\u0457\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F"
      },
      "win1251": "windows1251",
      "cp1251": "windows1251",
      "windows1252": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\uFFFD\u017D\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\uFFFD\u017E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"
      },
      "win1252": "windows1252",
      "cp1252": "windows1252",
      "windows1253": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\uFFFD\u2030\uFFFD\u2039\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\xA0\u0385\u0386\xA3\xA4\xA5\xA6\xA7\xA8\xA9\uFFFD\xAB\xAC\xAD\xAE\u2015\xB0\xB1\xB2\xB3\u0384\xB5\xB6\xB7\u0388\u0389\u038A\xBB\u038C\xBD\u038E\u038F\u0390\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\uFFFD\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\uFFFD"
      },
      "win1253": "windows1253",
      "cp1253": "windows1253",
      "windows1254": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\uFFFD\uFFFD\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u011E\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u0130\u015E\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u011F\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u0131\u015F\xFF"
      },
      "win1254": "windows1254",
      "cp1254": "windows1254",
      "windows1255": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\uFFFD\u2039\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\xA0\xA1\xA2\xA3\u20AA\xA5\xA6\xA7\xA8\xA9\xD7\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xF7\xBB\xBC\xBD\xBE\xBF\u05B0\u05B1\u05B2\u05B3\u05B4\u05B5\u05B6\u05B7\u05B8\u05B9\u05BA\u05BB\u05BC\u05BD\u05BE\u05BF\u05C0\u05C1\u05C2\u05C3\u05F0\u05F1\u05F2\u05F3\u05F4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\uFFFD\u200E\u200F\uFFFD"
      },
      "win1255": "windows1255",
      "cp1255": "windows1255",
      "windows1256": {
        "type": "_sbcs",
        "chars": "\u20AC\u067E\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0679\u2039\u0152\u0686\u0698\u0688\u06AF\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u06A9\u2122\u0691\u203A\u0153\u200C\u200D\u06BA\xA0\u060C\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\u06BE\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\u061B\xBB\xBC\xBD\xBE\u061F\u06C1\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\xD7\u0637\u0638\u0639\u063A\u0640\u0641\u0642\u0643\xE0\u0644\xE2\u0645\u0646\u0647\u0648\xE7\xE8\xE9\xEA\xEB\u0649\u064A\xEE\xEF\u064B\u064C\u064D\u064E\xF4\u064F\u0650\xF7\u0651\xF9\u0652\xFB\xFC\u200E\u200F\u06D2"
      },
      "win1256": "windows1256",
      "cp1256": "windows1256",
      "windows1257": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\uFFFD\u201E\u2026\u2020\u2021\uFFFD\u2030\uFFFD\u2039\uFFFD\xA8\u02C7\xB8\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\xAF\u02DB\uFFFD\xA0\uFFFD\xA2\xA3\xA4\uFFFD\xA6\xA7\xD8\xA9\u0156\xAB\xAC\xAD\xAE\xC6\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xF8\xB9\u0157\xBB\xBC\xBD\xBE\xE6\u0104\u012E\u0100\u0106\xC4\xC5\u0118\u0112\u010C\xC9\u0179\u0116\u0122\u0136\u012A\u013B\u0160\u0143\u0145\xD3\u014C\xD5\xD6\xD7\u0172\u0141\u015A\u016A\xDC\u017B\u017D\xDF\u0105\u012F\u0101\u0107\xE4\xE5\u0119\u0113\u010D\xE9\u017A\u0117\u0123\u0137\u012B\u013C\u0161\u0144\u0146\xF3\u014D\xF5\xF6\xF7\u0173\u0142\u015B\u016B\xFC\u017C\u017E\u02D9"
      },
      "win1257": "windows1257",
      "cp1257": "windows1257",
      "windows1258": {
        "type": "_sbcs",
        "chars": "\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\uFFFD\u2039\u0152\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\uFFFD\u203A\u0153\uFFFD\uFFFD\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF"
      },
      "win1258": "windows1258",
      "cp1258": "windows1258",
      "iso88591": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"
      },
      "cp28591": "iso88591",
      "iso88592": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u02D8\u0141\xA4\u013D\u015A\xA7\xA8\u0160\u015E\u0164\u0179\xAD\u017D\u017B\xB0\u0105\u02DB\u0142\xB4\u013E\u015B\u02C7\xB8\u0161\u015F\u0165\u017A\u02DD\u017E\u017C\u0154\xC1\xC2\u0102\xC4\u0139\u0106\xC7\u010C\xC9\u0118\xCB\u011A\xCD\xCE\u010E\u0110\u0143\u0147\xD3\xD4\u0150\xD6\xD7\u0158\u016E\xDA\u0170\xDC\xDD\u0162\xDF\u0155\xE1\xE2\u0103\xE4\u013A\u0107\xE7\u010D\xE9\u0119\xEB\u011B\xED\xEE\u010F\u0111\u0144\u0148\xF3\xF4\u0151\xF6\xF7\u0159\u016F\xFA\u0171\xFC\xFD\u0163\u02D9"
      },
      "cp28592": "iso88592",
      "iso88593": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0126\u02D8\xA3\xA4\uFFFD\u0124\xA7\xA8\u0130\u015E\u011E\u0134\xAD\uFFFD\u017B\xB0\u0127\xB2\xB3\xB4\xB5\u0125\xB7\xB8\u0131\u015F\u011F\u0135\xBD\uFFFD\u017C\xC0\xC1\xC2\uFFFD\xC4\u010A\u0108\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\uFFFD\xD1\xD2\xD3\xD4\u0120\xD6\xD7\u011C\xD9\xDA\xDB\xDC\u016C\u015C\xDF\xE0\xE1\xE2\uFFFD\xE4\u010B\u0109\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\uFFFD\xF1\xF2\xF3\xF4\u0121\xF6\xF7\u011D\xF9\xFA\xFB\xFC\u016D\u015D\u02D9"
      },
      "cp28593": "iso88593",
      "iso88594": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0138\u0156\xA4\u0128\u013B\xA7\xA8\u0160\u0112\u0122\u0166\xAD\u017D\xAF\xB0\u0105\u02DB\u0157\xB4\u0129\u013C\u02C7\xB8\u0161\u0113\u0123\u0167\u014A\u017E\u014B\u0100\xC1\xC2\xC3\xC4\xC5\xC6\u012E\u010C\xC9\u0118\xCB\u0116\xCD\xCE\u012A\u0110\u0145\u014C\u0136\xD4\xD5\xD6\xD7\xD8\u0172\xDA\xDB\xDC\u0168\u016A\xDF\u0101\xE1\xE2\xE3\xE4\xE5\xE6\u012F\u010D\xE9\u0119\xEB\u0117\xED\xEE\u012B\u0111\u0146\u014D\u0137\xF4\xF5\xF6\xF7\xF8\u0173\xFA\xFB\xFC\u0169\u016B\u02D9"
      },
      "cp28594": "iso88594",
      "iso88595": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0401\u0402\u0403\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\xAD\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2116\u0451\u0452\u0453\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\xA7\u045E\u045F"
      },
      "cp28595": "iso88595",
      "iso88596": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\uFFFD\uFFFD\xA4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u060C\xAD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u061B\uFFFD\uFFFD\uFFFD\u061F\uFFFD\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "cp28596": "iso88596",
      "iso88597": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u2018\u2019\xA3\u20AC\u20AF\xA6\xA7\xA8\xA9\u037A\xAB\xAC\xAD\uFFFD\u2015\xB0\xB1\xB2\xB3\u0384\u0385\u0386\xB7\u0388\u0389\u038A\xBB\u038C\xBD\u038E\u038F\u0390\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\uFFFD\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\uFFFD"
      },
      "cp28597": "iso88597",
      "iso88598": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xD7\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xF7\xBB\xBC\xBD\xBE\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2017\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\uFFFD\u200E\u200F\uFFFD"
      },
      "cp28598": "iso88598",
      "iso88599": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u011E\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u0130\u015E\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u011F\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u0131\u015F\xFF"
      },
      "cp28599": "iso88599",
      "iso885910": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0112\u0122\u012A\u0128\u0136\xA7\u013B\u0110\u0160\u0166\u017D\xAD\u016A\u014A\xB0\u0105\u0113\u0123\u012B\u0129\u0137\xB7\u013C\u0111\u0161\u0167\u017E\u2015\u016B\u014B\u0100\xC1\xC2\xC3\xC4\xC5\xC6\u012E\u010C\xC9\u0118\xCB\u0116\xCD\xCE\xCF\xD0\u0145\u014C\xD3\xD4\xD5\xD6\u0168\xD8\u0172\xDA\xDB\xDC\xDD\xDE\xDF\u0101\xE1\xE2\xE3\xE4\xE5\xE6\u012F\u010D\xE9\u0119\xEB\u0117\xED\xEE\xEF\xF0\u0146\u014D\xF3\xF4\xF5\xF6\u0169\xF8\u0173\xFA\xFB\xFC\xFD\xFE\u0138"
      },
      "cp28600": "iso885910",
      "iso885911": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "cp28601": "iso885911",
      "iso885913": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u201D\xA2\xA3\xA4\u201E\xA6\xA7\xD8\xA9\u0156\xAB\xAC\xAD\xAE\xC6\xB0\xB1\xB2\xB3\u201C\xB5\xB6\xB7\xF8\xB9\u0157\xBB\xBC\xBD\xBE\xE6\u0104\u012E\u0100\u0106\xC4\xC5\u0118\u0112\u010C\xC9\u0179\u0116\u0122\u0136\u012A\u013B\u0160\u0143\u0145\xD3\u014C\xD5\xD6\xD7\u0172\u0141\u015A\u016A\xDC\u017B\u017D\xDF\u0105\u012F\u0101\u0107\xE4\xE5\u0119\u0113\u010D\xE9\u017A\u0117\u0123\u0137\u012B\u013C\u0161\u0144\u0146\xF3\u014D\xF5\xF6\xF7\u0173\u0142\u015B\u016B\xFC\u017C\u017E\u2019"
      },
      "cp28603": "iso885913",
      "iso885914": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u1E02\u1E03\xA3\u010A\u010B\u1E0A\xA7\u1E80\xA9\u1E82\u1E0B\u1EF2\xAD\xAE\u0178\u1E1E\u1E1F\u0120\u0121\u1E40\u1E41\xB6\u1E56\u1E81\u1E57\u1E83\u1E60\u1EF3\u1E84\u1E85\u1E61\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0174\xD1\xD2\xD3\xD4\xD5\xD6\u1E6A\xD8\xD9\xDA\xDB\xDC\xDD\u0176\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0175\xF1\xF2\xF3\xF4\xF5\xF6\u1E6B\xF8\xF9\xFA\xFB\xFC\xFD\u0177\xFF"
      },
      "cp28604": "iso885914",
      "iso885915": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\u20AC\xA5\u0160\xA7\u0161\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u017D\xB5\xB6\xB7\u017E\xB9\xBA\xBB\u0152\u0153\u0178\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"
      },
      "cp28605": "iso885915",
      "iso885916": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0105\u0141\u20AC\u201E\u0160\xA7\u0161\xA9\u0218\xAB\u0179\xAD\u017A\u017B\xB0\xB1\u010C\u0142\u017D\u201D\xB6\xB7\u017E\u010D\u0219\xBB\u0152\u0153\u0178\u017C\xC0\xC1\xC2\u0102\xC4\u0106\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0110\u0143\xD2\xD3\xD4\u0150\xD6\u015A\u0170\xD9\xDA\xDB\xDC\u0118\u021A\xDF\xE0\xE1\xE2\u0103\xE4\u0107\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0111\u0144\xF2\xF3\xF4\u0151\xF6\u015B\u0171\xF9\xFA\xFB\xFC\u0119\u021B\xFF"
      },
      "cp28606": "iso885916",
      "cp437": {
        "type": "_sbcs",
        "chars": "\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"
      },
      "ibm437": "cp437",
      "csibm437": "cp437",
      "cp737": {
        "type": "_sbcs",
        "chars": "\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u03C5\u03C6\u03C7\u03C8\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\u03C9\u03AC\u03AD\u03AE\u03CA\u03AF\u03CC\u03CD\u03CB\u03CE\u0386\u0388\u0389\u038A\u038C\u038E\u038F\xB1\u2265\u2264\u03AA\u03AB\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"
      },
      "ibm737": "cp737",
      "csibm737": "cp737",
      "cp775": {
        "type": "_sbcs",
        "chars": "\u0106\xFC\xE9\u0101\xE4\u0123\xE5\u0107\u0142\u0113\u0156\u0157\u012B\u0179\xC4\xC5\xC9\xE6\xC6\u014D\xF6\u0122\xA2\u015A\u015B\xD6\xDC\xF8\xA3\xD8\xD7\xA4\u0100\u012A\xF3\u017B\u017C\u017A\u201D\xA6\xA9\xAE\xAC\xBD\xBC\u0141\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u0104\u010C\u0118\u0116\u2563\u2551\u2557\u255D\u012E\u0160\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u0172\u016A\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u017D\u0105\u010D\u0119\u0117\u012F\u0161\u0173\u016B\u017E\u2518\u250C\u2588\u2584\u258C\u2590\u2580\xD3\xDF\u014C\u0143\xF5\xD5\xB5\u0144\u0136\u0137\u013B\u013C\u0146\u0112\u0145\u2019\xAD\xB1\u201C\xBE\xB6\xA7\xF7\u201E\xB0\u2219\xB7\xB9\xB3\xB2\u25A0\xA0"
      },
      "ibm775": "cp775",
      "csibm775": "cp775",
      "cp850": {
        "type": "_sbcs",
        "chars": "\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\xF8\xA3\xD8\xD7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xF0\xD0\xCA\xCB\xC8\u0131\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\xFE\xDE\xDA\xDB\xD9\xFD\xDD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"
      },
      "ibm850": "cp850",
      "csibm850": "cp850",
      "cp852": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE4\u016F\u0107\xE7\u0142\xEB\u0150\u0151\xEE\u0179\xC4\u0106\xC9\u0139\u013A\xF4\xF6\u013D\u013E\u015A\u015B\xD6\xDC\u0164\u0165\u0141\xD7\u010D\xE1\xED\xF3\xFA\u0104\u0105\u017D\u017E\u0118\u0119\xAC\u017A\u010C\u015F\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\u011A\u015E\u2563\u2551\u2557\u255D\u017B\u017C\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u0102\u0103\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\u0111\u0110\u010E\xCB\u010F\u0147\xCD\xCE\u011B\u2518\u250C\u2588\u2584\u0162\u016E\u2580\xD3\xDF\xD4\u0143\u0144\u0148\u0160\u0161\u0154\xDA\u0155\u0170\xFD\xDD\u0163\xB4\xAD\u02DD\u02DB\u02C7\u02D8\xA7\xF7\xB8\xB0\xA8\u02D9\u0171\u0158\u0159\u25A0\xA0"
      },
      "ibm852": "cp852",
      "csibm852": "cp852",
      "cp855": {
        "type": "_sbcs",
        "chars": "\u0452\u0402\u0453\u0403\u0451\u0401\u0454\u0404\u0455\u0405\u0456\u0406\u0457\u0407\u0458\u0408\u0459\u0409\u045A\u040A\u045B\u040B\u045C\u040C\u045E\u040E\u045F\u040F\u044E\u042E\u044A\u042A\u0430\u0410\u0431\u0411\u0446\u0426\u0434\u0414\u0435\u0415\u0444\u0424\u0433\u0413\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u0445\u0425\u0438\u0418\u2563\u2551\u2557\u255D\u0439\u0419\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u043A\u041A\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\u043B\u041B\u043C\u041C\u043D\u041D\u043E\u041E\u043F\u2518\u250C\u2588\u2584\u041F\u044F\u2580\u042F\u0440\u0420\u0441\u0421\u0442\u0422\u0443\u0423\u0436\u0416\u0432\u0412\u044C\u042C\u2116\xAD\u044B\u042B\u0437\u0417\u0448\u0428\u044D\u042D\u0449\u0429\u0447\u0427\xA7\u25A0\xA0"
      },
      "ibm855": "cp855",
      "csibm855": "cp855",
      "cp856": {
        "type": "_sbcs",
        "chars": "\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\xA3\uFFFD\xD7\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xAE\xAC\xBD\xBC\uFFFD\xAB\xBB\u2591\u2592\u2593\u2502\u2524\uFFFD\uFFFD\uFFFD\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\uFFFD\uFFFD\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2518\u250C\u2588\u2584\xA6\uFFFD\u2580\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xB5\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"
      },
      "ibm856": "cp856",
      "csibm856": "cp856",
      "cp857": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\u0131\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\u0130\xD6\xDC\xF8\xA3\xD8\u015E\u015F\xE1\xED\xF3\xFA\xF1\xD1\u011E\u011F\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xBA\xAA\xCA\xCB\xC8\uFFFD\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\uFFFD\xD7\xDA\xDB\xD9\xEC\xFF\xAF\xB4\xAD\xB1\uFFFD\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"
      },
      "ibm857": "cp857",
      "csibm857": "cp857",
      "cp858": {
        "type": "_sbcs",
        "chars": "\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\xF8\xA3\xD8\xD7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xF0\xD0\xCA\xCB\xC8\u20AC\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\xFE\xDE\xDA\xDB\xD9\xFD\xDD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"
      },
      "ibm858": "cp858",
      "csibm858": "cp858",
      "cp860": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE3\xE0\xC1\xE7\xEA\xCA\xE8\xCD\xD4\xEC\xC3\xC2\xC9\xC0\xC8\xF4\xF5\xF2\xDA\xF9\xCC\xD5\xDC\xA2\xA3\xD9\u20A7\xD3\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xD2\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"
      },
      "ibm860": "cp860",
      "csibm860": "cp860",
      "cp861": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xD0\xF0\xDE\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xFE\xFB\xDD\xFD\xD6\xDC\xF8\xA3\xD8\u20A7\u0192\xE1\xED\xF3\xFA\xC1\xCD\xD3\xDA\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"
      },
      "ibm861": "cp861",
      "csibm861": "cp861",
      "cp862": {
        "type": "_sbcs",
        "chars": "\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\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"
      },
      "ibm862": "cp862",
      "csibm862": "cp862",
      "cp863": {
        "type": "_sbcs",
        "chars": "\xC7\xFC\xE9\xE2\xC2\xE0\xB6\xE7\xEA\xEB\xE8\xEF\xEE\u2017\xC0\xA7\xC9\xC8\xCA\xF4\xCB\xCF\xFB\xF9\xA4\xD4\xDC\xA2\xA3\xD9\xDB\u0192\xA6\xB4\xF3\xFA\xA8\xB8\xB3\xAF\xCE\u2310\xAC\xBD\xBC\xBE\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"
      },
      "ibm863": "cp863",
      "csibm863": "cp863",
      "cp864": {
        "type": "_sbcs",
        "chars": "\0\x07\b	\n\v\f\r\x1B !\"#$\u066A&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xB0\xB7\u2219\u221A\u2592\u2500\u2502\u253C\u2524\u252C\u251C\u2534\u2510\u250C\u2514\u2518\u03B2\u221E\u03C6\xB1\xBD\xBC\u2248\xAB\xBB\uFEF7\uFEF8\uFFFD\uFFFD\uFEFB\uFEFC\uFFFD\xA0\xAD\uFE82\xA3\xA4\uFE84\uFFFD\uFFFD\uFE8E\uFE8F\uFE95\uFE99\u060C\uFE9D\uFEA1\uFEA5\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFED1\u061B\uFEB1\uFEB5\uFEB9\u061F\xA2\uFE80\uFE81\uFE83\uFE85\uFECA\uFE8B\uFE8D\uFE91\uFE93\uFE97\uFE9B\uFE9F\uFEA3\uFEA7\uFEA9\uFEAB\uFEAD\uFEAF\uFEB3\uFEB7\uFEBB\uFEBF\uFEC1\uFEC5\uFECB\uFECF\xA6\xAC\xF7\xD7\uFEC9\u0640\uFED3\uFED7\uFEDB\uFEDF\uFEE3\uFEE7\uFEEB\uFEED\uFEEF\uFEF3\uFEBD\uFECC\uFECE\uFECD\uFEE1\uFE7D\u0651\uFEE5\uFEE9\uFEEC\uFEF0\uFEF2\uFED0\uFED5\uFEF5\uFEF6\uFEDD\uFED9\uFEF1\u25A0\uFFFD"
      },
      "ibm864": "cp864",
      "csibm864": "cp864",
      "cp865": {
        "type": "_sbcs",
        "chars": "\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\xF8\xA3\xD8\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xA4\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"
      },
      "ibm865": "cp865",
      "csibm865": "cp865",
      "cp866": {
        "type": "_sbcs",
        "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\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\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0404\u0454\u0407\u0457\u040E\u045E\xB0\u2219\xB7\u221A\u2116\xA4\u25A0\xA0"
      },
      "ibm866": "cp866",
      "csibm866": "cp866",
      "cp869": {
        "type": "_sbcs",
        "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0386\uFFFD\xB7\xAC\xA6\u2018\u2019\u0388\u2015\u0389\u038A\u03AA\u038C\uFFFD\uFFFD\u038E\u03AB\xA9\u038F\xB2\xB3\u03AC\xA3\u03AD\u03AE\u03AF\u03CA\u0390\u03CC\u03CD\u0391\u0392\u0393\u0394\u0395\u0396\u0397\xBD\u0398\u0399\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u039A\u039B\u039C\u039D\u2563\u2551\u2557\u255D\u039E\u039F\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u03A0\u03A1\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03B1\u03B2\u03B3\u2518\u250C\u2588\u2584\u03B4\u03B5\u2580\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u0384\xAD\xB1\u03C5\u03C6\u03C7\xA7\u03C8\u0385\xB0\xA8\u03C9\u03CB\u03B0\u03CE\u25A0\xA0"
      },
      "ibm869": "cp869",
      "csibm869": "cp869",
      "cp922": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\u203E\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0160\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\u017D\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0161\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\u017E\xFF"
      },
      "ibm922": "cp922",
      "csibm922": "cp922",
      "cp1046": {
        "type": "_sbcs",
        "chars": "\uFE88\xD7\xF7\uF8F6\uF8F5\uF8F4\uF8F7\uFE71\x88\u25A0\u2502\u2500\u2510\u250C\u2514\u2518\uFE79\uFE7B\uFE7D\uFE7F\uFE77\uFE8A\uFEF0\uFEF3\uFEF2\uFECE\uFECF\uFED0\uFEF6\uFEF8\uFEFA\uFEFC\xA0\uF8FA\uF8F9\uF8F8\xA4\uF8FB\uFE8B\uFE91\uFE97\uFE9B\uFE9F\uFEA3\u060C\xAD\uFEA7\uFEB3\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFEB7\u061B\uFEBB\uFEBF\uFECA\u061F\uFECB\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\uFEC7\u0639\u063A\uFECC\uFE82\uFE84\uFE8E\uFED3\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\uFED7\uFEDB\uFEDF\uF8FC\uFEF5\uFEF7\uFEF9\uFEFB\uFEE3\uFEE7\uFEEC\uFEE9\uFFFD"
      },
      "ibm1046": "cp1046",
      "csibm1046": "cp1046",
      "cp1124": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0401\u0402\u0490\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\xAD\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2116\u0451\u0452\u0491\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\xA7\u045E\u045F"
      },
      "ibm1124": "cp1124",
      "csibm1124": "cp1124",
      "cp1125": {
        "type": "_sbcs",
        "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\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\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0490\u0491\u0404\u0454\u0406\u0456\u0407\u0457\xB7\u221A\u2116\xA4\u25A0\xA0"
      },
      "ibm1125": "cp1125",
      "csibm1125": "cp1125",
      "cp1129": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\u0153\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u0178\xB5\xB6\xB7\u0152\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF"
      },
      "ibm1129": "cp1129",
      "csibm1129": "cp1129",
      "cp1133": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E81\u0E82\u0E84\u0E87\u0E88\u0EAA\u0E8A\u0E8D\u0E94\u0E95\u0E96\u0E97\u0E99\u0E9A\u0E9B\u0E9C\u0E9D\u0E9E\u0E9F\u0EA1\u0EA2\u0EA3\u0EA5\u0EA7\u0EAB\u0EAD\u0EAE\uFFFD\uFFFD\uFFFD\u0EAF\u0EB0\u0EB2\u0EB3\u0EB4\u0EB5\u0EB6\u0EB7\u0EB8\u0EB9\u0EBC\u0EB1\u0EBB\u0EBD\uFFFD\uFFFD\uFFFD\u0EC0\u0EC1\u0EC2\u0EC3\u0EC4\u0EC8\u0EC9\u0ECA\u0ECB\u0ECC\u0ECD\u0EC6\uFFFD\u0EDC\u0EDD\u20AD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0ED0\u0ED1\u0ED2\u0ED3\u0ED4\u0ED5\u0ED6\u0ED7\u0ED8\u0ED9\uFFFD\uFFFD\xA2\xAC\xA6\uFFFD"
      },
      "ibm1133": "cp1133",
      "csibm1133": "cp1133",
      "cp1161": {
        "type": "_sbcs",
        "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0E48\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\u0E49\u0E4A\u0E4B\u20AC\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\xA2\xAC\xA6\xA0"
      },
      "ibm1161": "cp1161",
      "csibm1161": "cp1161",
      "cp1162": {
        "type": "_sbcs",
        "chars": "\u20AC\x81\x82\x83\x84\u2026\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "ibm1162": "cp1162",
      "csibm1162": "cp1162",
      "cp1163": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\u20AC\xA5\xA6\xA7\u0153\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u0178\xB5\xB6\xB7\u0152\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF"
      },
      "ibm1163": "cp1163",
      "csibm1163": "cp1163",
      "maccroatian": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\u0160\u2122\xB4\xA8\u2260\u017D\xD8\u221E\xB1\u2264\u2265\u2206\xB5\u2202\u2211\u220F\u0161\u222B\xAA\xBA\u2126\u017E\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u0106\xAB\u010C\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u0110\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\uFFFD\xA9\u2044\xA4\u2039\u203A\xC6\xBB\u2013\xB7\u201A\u201E\u2030\xC2\u0107\xC1\u010D\xC8\xCD\xCE\xCF\xCC\xD3\xD4\u0111\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u03C0\xCB\u02DA\xB8\xCA\xE6\u02C7"
      },
      "maccyrillic": {
        "type": "_sbcs",
        "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u2020\xB0\xA2\xA3\xA7\u2022\xB6\u0406\xAE\xA9\u2122\u0402\u0452\u2260\u0403\u0453\u221E\xB1\u2264\u2265\u0456\xB5\u2202\u0408\u0404\u0454\u0407\u0457\u0409\u0459\u040A\u045A\u0458\u0405\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\u040B\u045B\u040C\u045C\u0455\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u201E\u040E\u045E\u040F\u045F\u2116\u0401\u0451\u044F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\xA4"
      },
      "macgreek": {
        "type": "_sbcs",
        "chars": "\xC4\xB9\xB2\xC9\xB3\xD6\xDC\u0385\xE0\xE2\xE4\u0384\xA8\xE7\xE9\xE8\xEA\xEB\xA3\u2122\xEE\xEF\u2022\xBD\u2030\xF4\xF6\xA6\xAD\xF9\xFB\xFC\u2020\u0393\u0394\u0398\u039B\u039E\u03A0\xDF\xAE\xA9\u03A3\u03AA\xA7\u2260\xB0\u0387\u0391\xB1\u2264\u2265\xA5\u0392\u0395\u0396\u0397\u0399\u039A\u039C\u03A6\u03AB\u03A8\u03A9\u03AC\u039D\xAC\u039F\u03A1\u2248\u03A4\xAB\xBB\u2026\xA0\u03A5\u03A7\u0386\u0388\u0153\u2013\u2015\u201C\u201D\u2018\u2019\xF7\u0389\u038A\u038C\u038E\u03AD\u03AE\u03AF\u03CC\u038F\u03CD\u03B1\u03B2\u03C8\u03B4\u03B5\u03C6\u03B3\u03B7\u03B9\u03BE\u03BA\u03BB\u03BC\u03BD\u03BF\u03C0\u03CE\u03C1\u03C3\u03C4\u03B8\u03C9\u03C2\u03C7\u03C5\u03B6\u03CA\u03CB\u0390\u03B0\uFFFD"
      },
      "maciceland": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\xDD\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\xD0\xF0\xDE\xFE\xFD\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
      },
      "macroman": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\uFB01\uFB02\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
      },
      "macromania": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\u0102\u015E\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\u0103\u015F\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\u0162\u0163\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
      },
      "macthai": {
        "type": "_sbcs",
        "chars": "\xAB\xBB\u2026\uF88C\uF88F\uF892\uF895\uF898\uF88B\uF88E\uF891\uF894\uF897\u201C\u201D\uF899\uFFFD\u2022\uF884\uF889\uF885\uF886\uF887\uF888\uF88A\uF88D\uF890\uF893\uF896\u2018\u2019\uFFFD\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFEFF\u200B\u2013\u2014\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u2122\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\xAE\xA9\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "macturkish": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u011E\u011F\u0130\u0131\u015E\u015F\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\uFFFD\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
      },
      "macukraine": {
        "type": "_sbcs",
        "chars": "\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u2020\xB0\u0490\xA3\xA7\u2022\xB6\u0406\xAE\xA9\u2122\u0402\u0452\u2260\u0403\u0453\u221E\xB1\u2264\u2265\u0456\xB5\u0491\u0408\u0404\u0454\u0407\u0457\u0409\u0459\u040A\u045A\u0458\u0405\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\u040B\u045B\u040C\u045C\u0455\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u201E\u040E\u045E\u040F\u045F\u2116\u0401\u0451\u044F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\xA4"
      },
      "koi8r": {
        "type": "_sbcs",
        "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u2553\u2554\u2555\u2556\u2557\u2558\u2559\u255A\u255B\u255C\u255D\u255E\u255F\u2560\u2561\u0401\u2562\u2563\u2564\u2565\u2566\u2567\u2568\u2569\u256A\u256B\u256C\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"
      },
      "koi8u": {
        "type": "_sbcs",
        "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u0454\u2554\u0456\u0457\u2557\u2558\u2559\u255A\u255B\u0491\u255D\u255E\u255F\u2560\u2561\u0401\u0404\u2563\u0406\u0407\u2566\u2567\u2568\u2569\u256A\u0490\u256C\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"
      },
      "koi8ru": {
        "type": "_sbcs",
        "chars": "\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u0454\u2554\u0456\u0457\u2557\u2558\u2559\u255A\u255B\u0491\u045E\u255E\u255F\u2560\u2561\u0401\u0404\u2563\u0406\u0407\u2566\u2567\u2568\u2569\u256A\u0490\u040E\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"
      },
      "koi8t": {
        "type": "_sbcs",
        "chars": "\u049B\u0493\u201A\u0492\u201E\u2026\u2020\u2021\uFFFD\u2030\u04B3\u2039\u04B2\u04B7\u04B6\uFFFD\u049A\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u04EF\u04EE\u0451\xA4\u04E3\xA6\xA7\uFFFD\uFFFD\uFFFD\xAB\xAC\xAD\xAE\uFFFD\xB0\xB1\xB2\u0401\uFFFD\u04E2\xB6\xB7\uFFFD\u2116\uFFFD\xBB\uFFFD\uFFFD\uFFFD\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"
      },
      "armscii8": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\u0587\u0589)(\xBB\xAB\u2014.\u055D,-\u058A\u2026\u055C\u055B\u055E\u0531\u0561\u0532\u0562\u0533\u0563\u0534\u0564\u0535\u0565\u0536\u0566\u0537\u0567\u0538\u0568\u0539\u0569\u053A\u056A\u053B\u056B\u053C\u056C\u053D\u056D\u053E\u056E\u053F\u056F\u0540\u0570\u0541\u0571\u0542\u0572\u0543\u0573\u0544\u0574\u0545\u0575\u0546\u0576\u0547\u0577\u0548\u0578\u0549\u0579\u054A\u057A\u054B\u057B\u054C\u057C\u054D\u057D\u054E\u057E\u054F\u057F\u0550\u0580\u0551\u0581\u0552\u0582\u0553\u0583\u0554\u0584\u0555\u0585\u0556\u0586\u055A\uFFFD"
      },
      "rk1048": {
        "type": "_sbcs",
        "chars": "\u0402\u0403\u201A\u0453\u201E\u2026\u2020\u2021\u20AC\u2030\u0409\u2039\u040A\u049A\u04BA\u040F\u0452\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0459\u203A\u045A\u049B\u04BB\u045F\xA0\u04B0\u04B1\u04D8\xA4\u04E8\xA6\xA7\u0401\xA9\u0492\xAB\xAC\xAD\xAE\u04AE\xB0\xB1\u0406\u0456\u04E9\xB5\xB6\xB7\u0451\u2116\u0493\xBB\u04D9\u04A2\u04A3\u04AF\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F"
      },
      "tcvn": {
        "type": "_sbcs",
        "chars": "\0\xDA\u1EE4\u1EEA\u1EEC\u1EEE\x07\b	\n\v\f\r\u1EE8\u1EF0\u1EF2\u1EF6\u1EF8\xDD\u1EF4\x1B !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xC0\u1EA2\xC3\xC1\u1EA0\u1EB6\u1EAC\xC8\u1EBA\u1EBC\xC9\u1EB8\u1EC6\xCC\u1EC8\u0128\xCD\u1ECA\xD2\u1ECE\xD5\xD3\u1ECC\u1ED8\u1EDC\u1EDE\u1EE0\u1EDA\u1EE2\xD9\u1EE6\u0168\xA0\u0102\xC2\xCA\xD4\u01A0\u01AF\u0110\u0103\xE2\xEA\xF4\u01A1\u01B0\u0111\u1EB0\u0300\u0309\u0303\u0301\u0323\xE0\u1EA3\xE3\xE1\u1EA1\u1EB2\u1EB1\u1EB3\u1EB5\u1EAF\u1EB4\u1EAE\u1EA6\u1EA8\u1EAA\u1EA4\u1EC0\u1EB7\u1EA7\u1EA9\u1EAB\u1EA5\u1EAD\xE8\u1EC2\u1EBB\u1EBD\xE9\u1EB9\u1EC1\u1EC3\u1EC5\u1EBF\u1EC7\xEC\u1EC9\u1EC4\u1EBE\u1ED2\u0129\xED\u1ECB\xF2\u1ED4\u1ECF\xF5\xF3\u1ECD\u1ED3\u1ED5\u1ED7\u1ED1\u1ED9\u1EDD\u1EDF\u1EE1\u1EDB\u1EE3\xF9\u1ED6\u1EE7\u0169\xFA\u1EE5\u1EEB\u1EED\u1EEF\u1EE9\u1EF1\u1EF3\u1EF7\u1EF9\xFD\u1EF5\u1ED0"
      },
      "georgianacademy": {
        "type": "_sbcs",
        "chars": "\x80\x81\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\x9D\x9E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\u10D0\u10D1\u10D2\u10D3\u10D4\u10D5\u10D6\u10D7\u10D8\u10D9\u10DA\u10DB\u10DC\u10DD\u10DE\u10DF\u10E0\u10E1\u10E2\u10E3\u10E4\u10E5\u10E6\u10E7\u10E8\u10E9\u10EA\u10EB\u10EC\u10ED\u10EE\u10EF\u10F0\u10F1\u10F2\u10F3\u10F4\u10F5\u10F6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"
      },
      "georgianps": {
        "type": "_sbcs",
        "chars": "\x80\x81\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\x9D\x9E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\u10D0\u10D1\u10D2\u10D3\u10D4\u10D5\u10D6\u10F1\u10D7\u10D8\u10D9\u10DA\u10DB\u10DC\u10F2\u10DD\u10DE\u10DF\u10E0\u10E1\u10E2\u10F3\u10E3\u10E4\u10E5\u10E6\u10E7\u10E8\u10E9\u10EA\u10EB\u10EC\u10ED\u10EE\u10F4\u10EF\u10F0\u10F5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"
      },
      "pt154": {
        "type": "_sbcs",
        "chars": "\u0496\u0492\u04EE\u0493\u201E\u2026\u04B6\u04AE\u04B2\u04AF\u04A0\u04E2\u04A2\u049A\u04BA\u04B8\u0497\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u04B3\u04B7\u04A1\u04E3\u04A3\u049B\u04BB\u04B9\xA0\u040E\u045E\u0408\u04E8\u0498\u04B0\xA7\u0401\xA9\u04D8\xAB\xAC\u04EF\xAE\u049C\xB0\u04B1\u0406\u0456\u0499\u04E9\xB6\xB7\u0451\u2116\u04D9\xBB\u0458\u04AA\u04AB\u049D\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F"
      },
      "viscii": {
        "type": "_sbcs",
        "chars": "\0\u1EB2\u1EB4\u1EAA\x07\b	\n\v\f\r\u1EF6\u1EF8\x1B\u1EF4 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\u1EA0\u1EAE\u1EB0\u1EB6\u1EA4\u1EA6\u1EA8\u1EAC\u1EBC\u1EB8\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EE2\u1EDA\u1EDC\u1EDE\u1ECA\u1ECE\u1ECC\u1EC8\u1EE6\u0168\u1EE4\u1EF2\xD5\u1EAF\u1EB1\u1EB7\u1EA5\u1EA7\u1EA9\u1EAD\u1EBD\u1EB9\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1ED1\u1ED3\u1ED5\u1ED7\u1EE0\u01A0\u1ED9\u1EDD\u1EDF\u1ECB\u1EF0\u1EE8\u1EEA\u1EEC\u01A1\u1EDB\u01AF\xC0\xC1\xC2\xC3\u1EA2\u0102\u1EB3\u1EB5\xC8\xC9\xCA\u1EBA\xCC\xCD\u0128\u1EF3\u0110\u1EE9\xD2\xD3\xD4\u1EA1\u1EF7\u1EEB\u1EED\xD9\xDA\u1EF9\u1EF5\xDD\u1EE1\u01B0\xE0\xE1\xE2\xE3\u1EA3\u0103\u1EEF\u1EAB\xE8\xE9\xEA\u1EBB\xEC\xED\u0129\u1EC9\u0111\u1EF1\xF2\xF3\xF4\xF5\u1ECF\u1ECD\u1EE5\xF9\xFA\u0169\u1EE7\xFD\u1EE3\u1EEE"
      },
      "iso646cn": {
        "type": "_sbcs",
        "chars": "\0\x07\b	\n\v\f\r\x1B !\"#\xA5%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}\u203E\x7F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "iso646jp": {
        "type": "_sbcs",
        "chars": "\0\x07\b	\n\v\f\r\x1B !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\xA5]^_`abcdefghijklmnopqrstuvwxyz{|}\u203E\x7F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "hproman8": {
        "type": "_sbcs",
        "chars": "\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xC0\xC2\xC8\xCA\xCB\xCE\xCF\xB4\u02CB\u02C6\xA8\u02DC\xD9\xDB\u20A4\xAF\xDD\xFD\xB0\xC7\xE7\xD1\xF1\xA1\xBF\xA4\xA3\xA5\xA7\u0192\xA2\xE2\xEA\xF4\xFB\xE1\xE9\xF3\xFA\xE0\xE8\xF2\xF9\xE4\xEB\xF6\xFC\xC5\xEE\xD8\xC6\xE5\xED\xF8\xE6\xC4\xEC\xD6\xDC\xC9\xEF\xDF\xD4\xC1\xC3\xE3\xD0\xF0\xCD\xCC\xD3\xD2\xD5\xF5\u0160\u0161\xDA\u0178\xFF\xDE\xFE\xB7\xB5\xB6\xBE\u2014\xBC\xBD\xAA\xBA\xAB\u25A0\xBB\xB1\uFFFD"
      },
      "macintosh": {
        "type": "_sbcs",
        "chars": "\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\uFB01\uFB02\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"
      },
      "ascii": {
        "type": "_sbcs",
        "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"
      },
      "tis620": {
        "type": "_sbcs",
        "chars": "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"
      }
    };
  }
});

// packages/core/node_modules/iconv-lite/encodings/dbcs-codec.js
var require_dbcs_codec = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/dbcs-codec.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Buffer9 = require_safer().Buffer;
    exports2._dbcs = DBCSCodec;
    var UNASSIGNED = -1;
    var GB18030_CODE = -2;
    var SEQ_START = -10;
    var NODE_START = -1e3;
    var UNASSIGNED_NODE = new Array(256);
    var DEF_CHAR = -1;
    for (i4 = 0; i4 < 256; i4++) {
      UNASSIGNED_NODE[i4] = UNASSIGNED;
    }
    var i4;
    function DBCSCodec(codecOptions, iconv) {
      this.encodingName = codecOptions.encodingName;
      if (!codecOptions) {
        throw new Error("DBCS codec is called without the data.");
      }
      if (!codecOptions.table) {
        throw new Error("Encoding '" + this.encodingName + "' has no data.");
      }
      var mappingTable = codecOptions.table();
      this.decodeTables = [];
      this.decodeTables[0] = UNASSIGNED_NODE.slice(0);
      this.decodeTableSeq = [];
      for (var i5 = 0; i5 < mappingTable.length; i5++) {
        this._addDecodeChunk(mappingTable[i5]);
      }
      if (typeof codecOptions.gb18030 === "function") {
        this.gb18030 = codecOptions.gb18030();
        var commonThirdByteNodeIdx = this.decodeTables.length;
        this.decodeTables.push(UNASSIGNED_NODE.slice(0));
        var commonFourthByteNodeIdx = this.decodeTables.length;
        this.decodeTables.push(UNASSIGNED_NODE.slice(0));
        var firstByteNode = this.decodeTables[0];
        for (var i5 = 129; i5 <= 254; i5++) {
          var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i5]];
          for (var j2 = 48; j2 <= 57; j2++) {
            if (secondByteNode[j2] === UNASSIGNED) {
              secondByteNode[j2] = NODE_START - commonThirdByteNodeIdx;
            } else if (secondByteNode[j2] > NODE_START) {
              throw new Error("gb18030 decode tables conflict at byte 2");
            }
            var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j2]];
            for (var k2 = 129; k2 <= 254; k2++) {
              if (thirdByteNode[k2] === UNASSIGNED) {
                thirdByteNode[k2] = NODE_START - commonFourthByteNodeIdx;
              } else if (thirdByteNode[k2] === NODE_START - commonFourthByteNodeIdx) {
                continue;
              } else if (thirdByteNode[k2] > NODE_START) {
                throw new Error("gb18030 decode tables conflict at byte 3");
              }
              var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k2]];
              for (var l3 = 48; l3 <= 57; l3++) {
                if (fourthByteNode[l3] === UNASSIGNED) {
                  fourthByteNode[l3] = GB18030_CODE;
                }
              }
            }
          }
        }
      }
      this.defaultCharUnicode = iconv.defaultCharUnicode;
      this.encodeTable = [];
      this.encodeTableSeq = [];
      var skipEncodeChars = {};
      if (codecOptions.encodeSkipVals) {
        for (var i5 = 0; i5 < codecOptions.encodeSkipVals.length; i5++) {
          var val = codecOptions.encodeSkipVals[i5];
          if (typeof val === "number") {
            skipEncodeChars[val] = true;
          } else {
            for (var j2 = val.from; j2 <= val.to; j2++) {
              skipEncodeChars[j2] = true;
            }
          }
        }
      }
      this._fillEncodeTable(0, 0, skipEncodeChars);
      if (codecOptions.encodeAdd) {
        for (var uChar in codecOptions.encodeAdd) {
          if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) {
            this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
          }
        }
      }
      this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
      if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]["?"];
      if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
    }
    __name(DBCSCodec, "DBCSCodec");
    DBCSCodec.prototype.encoder = DBCSEncoder;
    DBCSCodec.prototype.decoder = DBCSDecoder;
    DBCSCodec.prototype._getDecodeTrieNode = function(addr2) {
      var bytes = [];
      for (; addr2 > 0; addr2 >>>= 8) {
        bytes.push(addr2 & 255);
      }
      if (bytes.length == 0) {
        bytes.push(0);
      }
      var node = this.decodeTables[0];
      for (var i5 = bytes.length - 1; i5 > 0; i5--) {
        var val = node[bytes[i5]];
        if (val == UNASSIGNED) {
          node[bytes[i5]] = NODE_START - this.decodeTables.length;
          this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
        } else if (val <= NODE_START) {
          node = this.decodeTables[NODE_START - val];
        } else {
          throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr2.toString(16));
        }
      }
      return node;
    };
    DBCSCodec.prototype._addDecodeChunk = function(chunk) {
      var curAddr = parseInt(chunk[0], 16);
      var writeTable = this._getDecodeTrieNode(curAddr);
      curAddr = curAddr & 255;
      for (var k2 = 1; k2 < chunk.length; k2++) {
        var part = chunk[k2];
        if (typeof part === "string") {
          for (var l3 = 0; l3 < part.length; ) {
            var code2 = part.charCodeAt(l3++);
            if (code2 >= 55296 && code2 < 56320) {
              var codeTrail = part.charCodeAt(l3++);
              if (codeTrail >= 56320 && codeTrail < 57344) {
                writeTable[curAddr++] = 65536 + (code2 - 55296) * 1024 + (codeTrail - 56320);
              } else {
                throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]);
              }
            } else if (code2 > 4080 && code2 <= 4095) {
              var len = 4095 - code2 + 2;
              var seq = [];
              for (var m3 = 0; m3 < len; m3++) {
                seq.push(part.charCodeAt(l3++));
              }
              writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
              this.decodeTableSeq.push(seq);
            } else {
              writeTable[curAddr++] = code2;
            }
          }
        } else if (typeof part === "number") {
          var charCode = writeTable[curAddr - 1] + 1;
          for (var l3 = 0; l3 < part; l3++) {
            writeTable[curAddr++] = charCode++;
          }
        } else {
          throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]);
        }
      }
      if (curAddr > 255) {
        throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
      }
    };
    DBCSCodec.prototype._getEncodeBucket = function(uCode) {
      var high = uCode >> 8;
      if (this.encodeTable[high] === void 0) {
        this.encodeTable[high] = UNASSIGNED_NODE.slice(0);
      }
      return this.encodeTable[high];
    };
    DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
      var bucket = this._getEncodeBucket(uCode);
      var low = uCode & 255;
      if (bucket[low] <= SEQ_START) {
        this.encodeTableSeq[SEQ_START - bucket[low]][DEF_CHAR] = dbcsCode;
      } else if (bucket[low] == UNASSIGNED) {
        bucket[low] = dbcsCode;
      }
    };
    DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
      var uCode = seq[0];
      var bucket = this._getEncodeBucket(uCode);
      var low = uCode & 255;
      var node;
      if (bucket[low] <= SEQ_START) {
        node = this.encodeTableSeq[SEQ_START - bucket[low]];
      } else {
        node = {};
        if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low];
        bucket[low] = SEQ_START - this.encodeTableSeq.length;
        this.encodeTableSeq.push(node);
      }
      for (var j2 = 1; j2 < seq.length - 1; j2++) {
        var oldVal = node[uCode];
        if (typeof oldVal === "object") {
          node = oldVal;
        } else {
          node = node[uCode] = {};
          if (oldVal !== void 0) {
            node[DEF_CHAR] = oldVal;
          }
        }
      }
      uCode = seq[seq.length - 1];
      node[uCode] = dbcsCode;
    };
    DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
      var node = this.decodeTables[nodeIdx];
      var hasValues = false;
      var subNodeEmpty = {};
      for (var i5 = 0; i5 < 256; i5++) {
        var uCode = node[i5];
        var mbCode = prefix + i5;
        if (skipEncodeChars[mbCode]) {
          continue;
        }
        if (uCode >= 0) {
          this._setEncodeChar(uCode, mbCode);
          hasValues = true;
        } else if (uCode <= NODE_START) {
          var subNodeIdx = NODE_START - uCode;
          if (!subNodeEmpty[subNodeIdx]) {
            var newPrefix = mbCode << 8 >>> 0;
            if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) {
              hasValues = true;
            } else {
              subNodeEmpty[subNodeIdx] = true;
            }
          }
        } else if (uCode <= SEQ_START) {
          this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
          hasValues = true;
        }
      }
      return hasValues;
    };
    function DBCSEncoder(options2, codec) {
      this.leadSurrogate = -1;
      this.seqObj = void 0;
      this.encodeTable = codec.encodeTable;
      this.encodeTableSeq = codec.encodeTableSeq;
      this.defaultCharSingleByte = codec.defCharSB;
      this.gb18030 = codec.gb18030;
    }
    __name(DBCSEncoder, "DBCSEncoder");
    DBCSEncoder.prototype.write = function(str2) {
      var newBuf = Buffer9.alloc(str2.length * (this.gb18030 ? 4 : 3));
      var leadSurrogate = this.leadSurrogate;
      var seqObj = this.seqObj;
      var nextChar = -1;
      var i5 = 0;
      var j2 = 0;
      while (true) {
        if (nextChar === -1) {
          if (i5 == str2.length) break;
          var uCode = str2.charCodeAt(i5++);
        } else {
          var uCode = nextChar;
          nextChar = -1;
        }
        if (uCode >= 55296 && uCode < 57344) {
          if (uCode < 56320) {
            if (leadSurrogate === -1) {
              leadSurrogate = uCode;
              continue;
            } else {
              leadSurrogate = uCode;
              uCode = UNASSIGNED;
            }
          } else {
            if (leadSurrogate !== -1) {
              uCode = 65536 + (leadSurrogate - 55296) * 1024 + (uCode - 56320);
              leadSurrogate = -1;
            } else {
              uCode = UNASSIGNED;
            }
          }
        } else if (leadSurrogate !== -1) {
          nextChar = uCode;
          uCode = UNASSIGNED;
          leadSurrogate = -1;
        }
        var dbcsCode = UNASSIGNED;
        if (seqObj !== void 0 && uCode != UNASSIGNED) {
          var resCode = seqObj[uCode];
          if (typeof resCode === "object") {
            seqObj = resCode;
            continue;
          } else if (typeof resCode === "number") {
            dbcsCode = resCode;
          } else if (resCode == void 0) {
            resCode = seqObj[DEF_CHAR];
            if (resCode !== void 0) {
              dbcsCode = resCode;
              nextChar = uCode;
            } else {
            }
          }
          seqObj = void 0;
        } else if (uCode >= 0) {
          var subtable = this.encodeTable[uCode >> 8];
          if (subtable !== void 0) {
            dbcsCode = subtable[uCode & 255];
          }
          if (dbcsCode <= SEQ_START) {
            seqObj = this.encodeTableSeq[SEQ_START - dbcsCode];
            continue;
          }
          if (dbcsCode == UNASSIGNED && this.gb18030) {
            var idx = findIdx(this.gb18030.uChars, uCode);
            if (idx != -1) {
              var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
              newBuf[j2++] = 129 + Math.floor(dbcsCode / 12600);
              dbcsCode = dbcsCode % 12600;
              newBuf[j2++] = 48 + Math.floor(dbcsCode / 1260);
              dbcsCode = dbcsCode % 1260;
              newBuf[j2++] = 129 + Math.floor(dbcsCode / 10);
              dbcsCode = dbcsCode % 10;
              newBuf[j2++] = 48 + dbcsCode;
              continue;
            }
          }
        }
        if (dbcsCode === UNASSIGNED) {
          dbcsCode = this.defaultCharSingleByte;
        }
        if (dbcsCode < 256) {
          newBuf[j2++] = dbcsCode;
        } else if (dbcsCode < 65536) {
          newBuf[j2++] = dbcsCode >> 8;
          newBuf[j2++] = dbcsCode & 255;
        } else if (dbcsCode < 16777216) {
          newBuf[j2++] = dbcsCode >> 16;
          newBuf[j2++] = dbcsCode >> 8 & 255;
          newBuf[j2++] = dbcsCode & 255;
        } else {
          newBuf[j2++] = dbcsCode >>> 24;
          newBuf[j2++] = dbcsCode >>> 16 & 255;
          newBuf[j2++] = dbcsCode >>> 8 & 255;
          newBuf[j2++] = dbcsCode & 255;
        }
      }
      this.seqObj = seqObj;
      this.leadSurrogate = leadSurrogate;
      return newBuf.slice(0, j2);
    };
    DBCSEncoder.prototype.end = function() {
      if (this.leadSurrogate === -1 && this.seqObj === void 0) {
        return;
      }
      var newBuf = Buffer9.alloc(10);
      var j2 = 0;
      if (this.seqObj) {
        var dbcsCode = this.seqObj[DEF_CHAR];
        if (dbcsCode !== void 0) {
          if (dbcsCode < 256) {
            newBuf[j2++] = dbcsCode;
          } else {
            newBuf[j2++] = dbcsCode >> 8;
            newBuf[j2++] = dbcsCode & 255;
          }
        } else {
        }
        this.seqObj = void 0;
      }
      if (this.leadSurrogate !== -1) {
        newBuf[j2++] = this.defaultCharSingleByte;
        this.leadSurrogate = -1;
      }
      return newBuf.slice(0, j2);
    };
    DBCSEncoder.prototype.findIdx = findIdx;
    function DBCSDecoder(options2, codec) {
      this.nodeIdx = 0;
      this.prevBytes = [];
      this.decodeTables = codec.decodeTables;
      this.decodeTableSeq = codec.decodeTableSeq;
      this.defaultCharUnicode = codec.defaultCharUnicode;
      this.gb18030 = codec.gb18030;
    }
    __name(DBCSDecoder, "DBCSDecoder");
    DBCSDecoder.prototype.write = function(buf) {
      var newBuf = Buffer9.alloc(buf.length * 2);
      var nodeIdx = this.nodeIdx;
      var prevBytes = this.prevBytes;
      var prevOffset = this.prevBytes.length;
      var seqStart = -this.prevBytes.length;
      var uCode;
      for (var i5 = 0, j2 = 0; i5 < buf.length; i5++) {
        var curByte = i5 >= 0 ? buf[i5] : prevBytes[i5 + prevOffset];
        var uCode = this.decodeTables[nodeIdx][curByte];
        if (uCode >= 0) {
        } else if (uCode === UNASSIGNED) {
          uCode = this.defaultCharUnicode.charCodeAt(0);
          i5 = seqStart;
        } else if (uCode === GB18030_CODE) {
          if (i5 >= 3) {
            var ptr = (buf[i5 - 3] - 129) * 12600 + (buf[i5 - 2] - 48) * 1260 + (buf[i5 - 1] - 129) * 10 + (curByte - 48);
          } else {
            var ptr = (prevBytes[i5 - 3 + prevOffset] - 129) * 12600 + ((i5 - 2 >= 0 ? buf[i5 - 2] : prevBytes[i5 - 2 + prevOffset]) - 48) * 1260 + ((i5 - 1 >= 0 ? buf[i5 - 1] : prevBytes[i5 - 1 + prevOffset]) - 129) * 10 + (curByte - 48);
          }
          var idx = findIdx(this.gb18030.gbChars, ptr);
          uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
        } else if (uCode <= NODE_START) {
          nodeIdx = NODE_START - uCode;
          continue;
        } else if (uCode <= SEQ_START) {
          var seq = this.decodeTableSeq[SEQ_START - uCode];
          for (var k2 = 0; k2 < seq.length - 1; k2++) {
            uCode = seq[k2];
            newBuf[j2++] = uCode & 255;
            newBuf[j2++] = uCode >> 8;
          }
          uCode = seq[seq.length - 1];
        } else {
          throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
        }
        if (uCode >= 65536) {
          uCode -= 65536;
          var uCodeLead = 55296 | uCode >> 10;
          newBuf[j2++] = uCodeLead & 255;
          newBuf[j2++] = uCodeLead >> 8;
          uCode = 56320 | uCode & 1023;
        }
        newBuf[j2++] = uCode & 255;
        newBuf[j2++] = uCode >> 8;
        nodeIdx = 0;
        seqStart = i5 + 1;
      }
      this.nodeIdx = nodeIdx;
      this.prevBytes = seqStart >= 0 ? Array.prototype.slice.call(buf, seqStart) : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf));
      return newBuf.slice(0, j2).toString("ucs2");
    };
    DBCSDecoder.prototype.end = function() {
      var ret = "";
      while (this.prevBytes.length > 0) {
        ret += this.defaultCharUnicode;
        var bytesArr = this.prevBytes.slice(1);
        this.prevBytes = [];
        this.nodeIdx = 0;
        if (bytesArr.length > 0) {
          ret += this.write(bytesArr);
        }
      }
      this.prevBytes = [];
      this.nodeIdx = 0;
      return ret;
    };
    function findIdx(table, val) {
      if (table[0] > val) {
        return -1;
      }
      var l3 = 0;
      var r5 = table.length;
      while (l3 < r5 - 1) {
        var mid = l3 + (r5 - l3 + 1 >> 1);
        if (table[mid] <= val) {
          l3 = mid;
        } else {
          r5 = mid;
        }
      }
      return l3;
    }
    __name(findIdx, "findIdx");
  }
});

// packages/core/node_modules/iconv-lite/encodings/tables/shiftjis.json
var require_shiftjis = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/tables/shiftjis.json"(exports2, module2) {
    module2.exports = [
      ["0", "\0", 128],
      ["a1", "\uFF61", 62],
      ["8140", "\u3000\u3001\u3002\uFF0C\uFF0E\u30FB\uFF1A\uFF1B\uFF1F\uFF01\u309B\u309C\xB4\uFF40\xA8\uFF3E\uFFE3\uFF3F\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\u2015\u2010\uFF0F\uFF3C\uFF5E\u2225\uFF5C\u2026\u2025\u2018\u2019\u201C\u201D\uFF08\uFF09\u3014\u3015\uFF3B\uFF3D\uFF5B\uFF5D\u3008", 9, "\uFF0B\uFF0D\xB1\xD7"],
      ["8180", "\xF7\uFF1D\u2260\uFF1C\uFF1E\u2266\u2267\u221E\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFFE5\uFF04\uFFE0\uFFE1\uFF05\uFF03\uFF06\uFF0A\uFF20\xA7\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u203B\u3012\u2192\u2190\u2191\u2193\u3013"],
      ["81b8", "\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229"],
      ["81c8", "\u2227\u2228\uFFE2\u21D2\u21D4\u2200\u2203"],
      ["81da", "\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C"],
      ["81f0", "\u212B\u2030\u266F\u266D\u266A\u2020\u2021\xB6"],
      ["81fc", "\u25EF"],
      ["824f", "\uFF10", 9],
      ["8260", "\uFF21", 25],
      ["8281", "\uFF41", 25],
      ["829f", "\u3041", 82],
      ["8340", "\u30A1", 62],
      ["8380", "\u30E0", 22],
      ["839f", "\u0391", 16, "\u03A3", 6],
      ["83bf", "\u03B1", 16, "\u03C3", 6],
      ["8440", "\u0410", 5, "\u0401\u0416", 25],
      ["8470", "\u0430", 5, "\u0451\u0436", 7],
      ["8480", "\u043E", 17],
      ["849f", "\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542"],
      ["8740", "\u2460", 19, "\u2160", 9],
      ["875f", "\u3349\u3314\u3322\u334D\u3318\u3327\u3303\u3336\u3351\u3357\u330D\u3326\u3323\u332B\u334A\u333B\u339C\u339D\u339E\u338E\u338F\u33C4\u33A1"],
      ["877e", "\u337B"],
      ["8780", "\u301D\u301F\u2116\u33CD\u2121\u32A4", 4, "\u3231\u3232\u3239\u337E\u337D\u337C\u2252\u2261\u222B\u222E\u2211\u221A\u22A5\u2220\u221F\u22BF\u2235\u2229\u222A"],
      ["889f", "\u4E9C\u5516\u5A03\u963F\u54C0\u611B\u6328\u59F6\u9022\u8475\u831C\u7A50\u60AA\u63E1\u6E25\u65ED\u8466\u82A6\u9BF5\u6893\u5727\u65A1\u6271\u5B9B\u59D0\u867B\u98F4\u7D62\u7DBE\u9B8E\u6216\u7C9F\u88B7\u5B89\u5EB5\u6309\u6697\u6848\u95C7\u978D\u674F\u4EE5\u4F0A\u4F4D\u4F9D\u5049\u56F2\u5937\u59D4\u5A01\u5C09\u60DF\u610F\u6170\u6613\u6905\u70BA\u754F\u7570\u79FB\u7DAD\u7DEF\u80C3\u840E\u8863\u8B02\u9055\u907A\u533B\u4E95\u4EA5\u57DF\u80B2\u90C1\u78EF\u4E00\u58F1\u6EA2\u9038\u7A32\u8328\u828B\u9C2F\u5141\u5370\u54BD\u54E1\u56E0\u59FB\u5F15\u98F2\u6DEB\u80E4\u852D"],
      ["8940", "\u9662\u9670\u96A0\u97FB\u540B\u53F3\u5B87\u70CF\u7FBD\u8FC2\u96E8\u536F\u9D5C\u7ABA\u4E11\u7893\u81FC\u6E26\u5618\u5504\u6B1D\u851A\u9C3B\u59E5\u53A9\u6D66\u74DC\u958F\u5642\u4E91\u904B\u96F2\u834F\u990C\u53E1\u55B6\u5B30\u5F71\u6620\u66F3\u6804\u6C38\u6CF3\u6D29\u745B\u76C8\u7A4E\u9834\u82F1\u885B\u8A60\u92ED\u6DB2\u75AB\u76CA\u99C5\u60A6\u8B01\u8D8A\u95B2\u698E\u53AD\u5186"],
      ["8980", "\u5712\u5830\u5944\u5BB4\u5EF6\u6028\u63A9\u63F4\u6CBF\u6F14\u708E\u7114\u7159\u71D5\u733F\u7E01\u8276\u82D1\u8597\u9060\u925B\u9D1B\u5869\u65BC\u6C5A\u7525\u51F9\u592E\u5965\u5F80\u5FDC\u62BC\u65FA\u6A2A\u6B27\u6BB4\u738B\u7FC1\u8956\u9D2C\u9D0E\u9EC4\u5CA1\u6C96\u837B\u5104\u5C4B\u61B6\u81C6\u6876\u7261\u4E59\u4FFA\u5378\u6069\u6E29\u7A4F\u97F3\u4E0B\u5316\u4EEE\u4F55\u4F3D\u4FA1\u4F73\u52A0\u53EF\u5609\u590F\u5AC1\u5BB6\u5BE1\u79D1\u6687\u679C\u67B6\u6B4C\u6CB3\u706B\u73C2\u798D\u79BE\u7A3C\u7B87\u82B1\u82DB\u8304\u8377\u83EF\u83D3\u8766\u8AB2\u5629\u8CA8\u8FE6\u904E\u971E\u868A\u4FC4\u5CE8\u6211\u7259\u753B\u81E5\u82BD\u86FE\u8CC0\u96C5\u9913\u99D5\u4ECB\u4F1A\u89E3\u56DE\u584A\u58CA\u5EFB\u5FEB\u602A\u6094\u6062\u61D0\u6212\u62D0\u6539"],
      ["8a40", "\u9B41\u6666\u68B0\u6D77\u7070\u754C\u7686\u7D75\u82A5\u87F9\u958B\u968E\u8C9D\u51F1\u52BE\u5916\u54B3\u5BB3\u5D16\u6168\u6982\u6DAF\u788D\u84CB\u8857\u8A72\u93A7\u9AB8\u6D6C\u99A8\u86D9\u57A3\u67FF\u86CE\u920E\u5283\u5687\u5404\u5ED3\u62E1\u64B9\u683C\u6838\u6BBB\u7372\u78BA\u7A6B\u899A\u89D2\u8D6B\u8F03\u90ED\u95A3\u9694\u9769\u5B66\u5CB3\u697D\u984D\u984E\u639B\u7B20\u6A2B"],
      ["8a80", "\u6A7F\u68B6\u9C0D\u6F5F\u5272\u559D\u6070\u62EC\u6D3B\u6E07\u6ED1\u845B\u8910\u8F44\u4E14\u9C39\u53F6\u691B\u6A3A\u9784\u682A\u515C\u7AC3\u84B2\u91DC\u938C\u565B\u9D28\u6822\u8305\u8431\u7CA5\u5208\u82C5\u74E6\u4E7E\u4F83\u51A0\u5BD2\u520A\u52D8\u52E7\u5DFB\u559A\u582A\u59E6\u5B8C\u5B98\u5BDB\u5E72\u5E79\u60A3\u611F\u6163\u61BE\u63DB\u6562\u67D1\u6853\u68FA\u6B3E\u6B53\u6C57\u6F22\u6F97\u6F45\u74B0\u7518\u76E3\u770B\u7AFF\u7BA1\u7C21\u7DE9\u7F36\u7FF0\u809D\u8266\u839E\u89B3\u8ACC\u8CAB\u9084\u9451\u9593\u9591\u95A2\u9665\u97D3\u9928\u8218\u4E38\u542B\u5CB8\u5DCC\u73A9\u764C\u773C\u5CA9\u7FEB\u8D0B\u96C1\u9811\u9854\u9858\u4F01\u4F0E\u5371\u559C\u5668\u57FA\u5947\u5B09\u5BC4\u5C90\u5E0C\u5E7E\u5FCC\u63EE\u673A\u65D7\u65E2\u671F\u68CB\u68C4"],
      ["8b40", "\u6A5F\u5E30\u6BC5\u6C17\u6C7D\u757F\u7948\u5B63\u7A00\u7D00\u5FBD\u898F\u8A18\u8CB4\u8D77\u8ECC\u8F1D\u98E2\u9A0E\u9B3C\u4E80\u507D\u5100\u5993\u5B9C\u622F\u6280\u64EC\u6B3A\u72A0\u7591\u7947\u7FA9\u87FB\u8ABC\u8B70\u63AC\u83CA\u97A0\u5409\u5403\u55AB\u6854\u6A58\u8A70\u7827\u6775\u9ECD\u5374\u5BA2\u811A\u8650\u9006\u4E18\u4E45\u4EC7\u4F11\u53CA\u5438\u5BAE\u5F13\u6025\u6551"],
      ["8b80", "\u673D\u6C42\u6C72\u6CE3\u7078\u7403\u7A76\u7AAE\u7B08\u7D1A\u7CFE\u7D66\u65E7\u725B\u53BB\u5C45\u5DE8\u62D2\u62E0\u6319\u6E20\u865A\u8A31\u8DDD\u92F8\u6F01\u79A6\u9B5A\u4EA8\u4EAB\u4EAC\u4F9B\u4FA0\u50D1\u5147\u7AF6\u5171\u51F6\u5354\u5321\u537F\u53EB\u55AC\u5883\u5CE1\u5F37\u5F4A\u602F\u6050\u606D\u631F\u6559\u6A4B\u6CC1\u72C2\u72ED\u77EF\u80F8\u8105\u8208\u854E\u90F7\u93E1\u97FF\u9957\u9A5A\u4EF0\u51DD\u5C2D\u6681\u696D\u5C40\u66F2\u6975\u7389\u6850\u7C81\u50C5\u52E4\u5747\u5DFE\u9326\u65A4\u6B23\u6B3D\u7434\u7981\u79BD\u7B4B\u7DCA\u82B9\u83CC\u887F\u895F\u8B39\u8FD1\u91D1\u541F\u9280\u4E5D\u5036\u53E5\u533A\u72D7\u7396\u77E9\u82E6\u8EAF\u99C6\u99C8\u99D2\u5177\u611A\u865E\u55B0\u7A7A\u5076\u5BD3\u9047\u9685\u4E32\u6ADB\u91E7\u5C51\u5C48"],
      ["8c40", "\u6398\u7A9F\u6C93\u9774\u8F61\u7AAA\u718A\u9688\u7C82\u6817\u7E70\u6851\u936C\u52F2\u541B\u85AB\u8A13\u7FA4\u8ECD\u90E1\u5366\u8888\u7941\u4FC2\u50BE\u5211\u5144\u5553\u572D\u73EA\u578B\u5951\u5F62\u5F84\u6075\u6176\u6167\u61A9\u63B2\u643A\u656C\u666F\u6842\u6E13\u7566\u7A3D\u7CFB\u7D4C\u7D99\u7E4B\u7F6B\u830E\u834A\u86CD\u8A08\u8A63\u8B66\u8EFD\u981A\u9D8F\u82B8\u8FCE\u9BE8"],
      ["8c80", "\u5287\u621F\u6483\u6FC0\u9699\u6841\u5091\u6B20\u6C7A\u6F54\u7A74\u7D50\u8840\u8A23\u6708\u4EF6\u5039\u5026\u5065\u517C\u5238\u5263\u55A7\u570F\u5805\u5ACC\u5EFA\u61B2\u61F8\u62F3\u6372\u691C\u6A29\u727D\u72AC\u732E\u7814\u786F\u7D79\u770C\u80A9\u898B\u8B19\u8CE2\u8ED2\u9063\u9375\u967A\u9855\u9A13\u9E78\u5143\u539F\u53B3\u5E7B\u5F26\u6E1B\u6E90\u7384\u73FE\u7D43\u8237\u8A00\u8AFA\u9650\u4E4E\u500B\u53E4\u547C\u56FA\u59D1\u5B64\u5DF1\u5EAB\u5F27\u6238\u6545\u67AF\u6E56\u72D0\u7CCA\u88B4\u80A1\u80E1\u83F0\u864E\u8A87\u8DE8\u9237\u96C7\u9867\u9F13\u4E94\u4E92\u4F0D\u5348\u5449\u543E\u5A2F\u5F8C\u5FA1\u609F\u68A7\u6A8E\u745A\u7881\u8A9E\u8AA4\u8B77\u9190\u4E5E\u9BC9\u4EA4\u4F7C\u4FAF\u5019\u5016\u5149\u516C\u529F\u52B9\u52FE\u539A\u53E3\u5411"],
      ["8d40", "\u540E\u5589\u5751\u57A2\u597D\u5B54\u5B5D\u5B8F\u5DE5\u5DE7\u5DF7\u5E78\u5E83\u5E9A\u5EB7\u5F18\u6052\u614C\u6297\u62D8\u63A7\u653B\u6602\u6643\u66F4\u676D\u6821\u6897\u69CB\u6C5F\u6D2A\u6D69\u6E2F\u6E9D\u7532\u7687\u786C\u7A3F\u7CE0\u7D05\u7D18\u7D5E\u7DB1\u8015\u8003\u80AF\u80B1\u8154\u818F\u822A\u8352\u884C\u8861\u8B1B\u8CA2\u8CFC\u90CA\u9175\u9271\u783F\u92FC\u95A4\u964D"],
      ["8d80", "\u9805\u9999\u9AD8\u9D3B\u525B\u52AB\u53F7\u5408\u58D5\u62F7\u6FE0\u8C6A\u8F5F\u9EB9\u514B\u523B\u544A\u56FD\u7A40\u9177\u9D60\u9ED2\u7344\u6F09\u8170\u7511\u5FFD\u60DA\u9AA8\u72DB\u8FBC\u6B64\u9803\u4ECA\u56F0\u5764\u58BE\u5A5A\u6068\u61C7\u660F\u6606\u6839\u68B1\u6DF7\u75D5\u7D3A\u826E\u9B42\u4E9B\u4F50\u53C9\u5506\u5D6F\u5DE6\u5DEE\u67FB\u6C99\u7473\u7802\u8A50\u9396\u88DF\u5750\u5EA7\u632B\u50B5\u50AC\u518D\u6700\u54C9\u585E\u59BB\u5BB0\u5F69\u624D\u63A1\u683D\u6B73\u6E08\u707D\u91C7\u7280\u7815\u7826\u796D\u658E\u7D30\u83DC\u88C1\u8F09\u969B\u5264\u5728\u6750\u7F6A\u8CA1\u51B4\u5742\u962A\u583A\u698A\u80B4\u54B2\u5D0E\u57FC\u7895\u9DFA\u4F5C\u524A\u548B\u643E\u6628\u6714\u67F5\u7A84\u7B56\u7D22\u932F\u685C\u9BAD\u7B39\u5319\u518A\u5237"],
      ["8e40", "\u5BDF\u62F6\u64AE\u64E6\u672D\u6BBA\u85A9\u96D1\u7690\u9BD6\u634C\u9306\u9BAB\u76BF\u6652\u4E09\u5098\u53C2\u5C71\u60E8\u6492\u6563\u685F\u71E6\u73CA\u7523\u7B97\u7E82\u8695\u8B83\u8CDB\u9178\u9910\u65AC\u66AB\u6B8B\u4ED5\u4ED4\u4F3A\u4F7F\u523A\u53F8\u53F2\u55E3\u56DB\u58EB\u59CB\u59C9\u59FF\u5B50\u5C4D\u5E02\u5E2B\u5FD7\u601D\u6307\u652F\u5B5C\u65AF\u65BD\u65E8\u679D\u6B62"],
      ["8e80", "\u6B7B\u6C0F\u7345\u7949\u79C1\u7CF8\u7D19\u7D2B\u80A2\u8102\u81F3\u8996\u8A5E\u8A69\u8A66\u8A8C\u8AEE\u8CC7\u8CDC\u96CC\u98FC\u6B6F\u4E8B\u4F3C\u4F8D\u5150\u5B57\u5BFA\u6148\u6301\u6642\u6B21\u6ECB\u6CBB\u723E\u74BD\u75D4\u78C1\u793A\u800C\u8033\u81EA\u8494\u8F9E\u6C50\u9E7F\u5F0F\u8B58\u9D2B\u7AFA\u8EF8\u5B8D\u96EB\u4E03\u53F1\u57F7\u5931\u5AC9\u5BA4\u6089\u6E7F\u6F06\u75BE\u8CEA\u5B9F\u8500\u7BE0\u5072\u67F4\u829D\u5C61\u854A\u7E1E\u820E\u5199\u5C04\u6368\u8D66\u659C\u716E\u793E\u7D17\u8005\u8B1D\u8ECA\u906E\u86C7\u90AA\u501F\u52FA\u5C3A\u6753\u707C\u7235\u914C\u91C8\u932B\u82E5\u5BC2\u5F31\u60F9\u4E3B\u53D6\u5B88\u624B\u6731\u6B8A\u72E9\u73E0\u7A2E\u816B\u8DA3\u9152\u9996\u5112\u53D7\u546A\u5BFF\u6388\u6A39\u7DAC\u9700\u56DA\u53CE\u5468"],
      ["8f40", "\u5B97\u5C31\u5DDE\u4FEE\u6101\u62FE\u6D32\u79C0\u79CB\u7D42\u7E4D\u7FD2\u81ED\u821F\u8490\u8846\u8972\u8B90\u8E74\u8F2F\u9031\u914B\u916C\u96C6\u919C\u4EC0\u4F4F\u5145\u5341\u5F93\u620E\u67D4\u6C41\u6E0B\u7363\u7E26\u91CD\u9283\u53D4\u5919\u5BBF\u6DD1\u795D\u7E2E\u7C9B\u587E\u719F\u51FA\u8853\u8FF0\u4FCA\u5CFB\u6625\u77AC\u7AE3\u821C\u99FF\u51C6\u5FAA\u65EC\u696F\u6B89\u6DF3"],
      ["8f80", "\u6E96\u6F64\u76FE\u7D14\u5DE1\u9075\u9187\u9806\u51E6\u521D\u6240\u6691\u66D9\u6E1A\u5EB6\u7DD2\u7F72\u66F8\u85AF\u85F7\u8AF8\u52A9\u53D9\u5973\u5E8F\u5F90\u6055\u92E4\u9664\u50B7\u511F\u52DD\u5320\u5347\u53EC\u54E8\u5546\u5531\u5617\u5968\u59BE\u5A3C\u5BB5\u5C06\u5C0F\u5C11\u5C1A\u5E84\u5E8A\u5EE0\u5F70\u627F\u6284\u62DB\u638C\u6377\u6607\u660C\u662D\u6676\u677E\u68A2\u6A1F\u6A35\u6CBC\u6D88\u6E09\u6E58\u713C\u7126\u7167\u75C7\u7701\u785D\u7901\u7965\u79F0\u7AE0\u7B11\u7CA7\u7D39\u8096\u83D6\u848B\u8549\u885D\u88F3\u8A1F\u8A3C\u8A54\u8A73\u8C61\u8CDE\u91A4\u9266\u937E\u9418\u969C\u9798\u4E0A\u4E08\u4E1E\u4E57\u5197\u5270\u57CE\u5834\u58CC\u5B22\u5E38\u60C5\u64FE\u6761\u6756\u6D44\u72B6\u7573\u7A63\u84B8\u8B72\u91B8\u9320\u5631\u57F4\u98FE"],
      ["9040", "\u62ED\u690D\u6B96\u71ED\u7E54\u8077\u8272\u89E6\u98DF\u8755\u8FB1\u5C3B\u4F38\u4FE1\u4FB5\u5507\u5A20\u5BDD\u5BE9\u5FC3\u614E\u632F\u65B0\u664B\u68EE\u699B\u6D78\u6DF1\u7533\u75B9\u771F\u795E\u79E6\u7D33\u81E3\u82AF\u85AA\u89AA\u8A3A\u8EAB\u8F9B\u9032\u91DD\u9707\u4EBA\u4EC1\u5203\u5875\u58EC\u5C0B\u751A\u5C3D\u814E\u8A0A\u8FC5\u9663\u976D\u7B25\u8ACF\u9808\u9162\u56F3\u53A8"],
      ["9080", "\u9017\u5439\u5782\u5E25\u63A8\u6C34\u708A\u7761\u7C8B\u7FE0\u8870\u9042\u9154\u9310\u9318\u968F\u745E\u9AC4\u5D07\u5D69\u6570\u67A2\u8DA8\u96DB\u636E\u6749\u6919\u83C5\u9817\u96C0\u88FE\u6F84\u647A\u5BF8\u4E16\u702C\u755D\u662F\u51C4\u5236\u52E2\u59D3\u5F81\u6027\u6210\u653F\u6574\u661F\u6674\u68F2\u6816\u6B63\u6E05\u7272\u751F\u76DB\u7CBE\u8056\u58F0\u88FD\u897F\u8AA0\u8A93\u8ACB\u901D\u9192\u9752\u9759\u6589\u7A0E\u8106\u96BB\u5E2D\u60DC\u621A\u65A5\u6614\u6790\u77F3\u7A4D\u7C4D\u7E3E\u810A\u8CAC\u8D64\u8DE1\u8E5F\u78A9\u5207\u62D9\u63A5\u6442\u6298\u8A2D\u7A83\u7BC0\u8AAC\u96EA\u7D76\u820C\u8749\u4ED9\u5148\u5343\u5360\u5BA3\u5C02\u5C16\u5DDD\u6226\u6247\u64B0\u6813\u6834\u6CC9\u6D45\u6D17\u67D3\u6F5C\u714E\u717D\u65CB\u7A7F\u7BAD\u7DDA"],
      ["9140", "\u7E4A\u7FA8\u817A\u821B\u8239\u85A6\u8A6E\u8CCE\u8DF5\u9078\u9077\u92AD\u9291\u9583\u9BAE\u524D\u5584\u6F38\u7136\u5168\u7985\u7E55\u81B3\u7CCE\u564C\u5851\u5CA8\u63AA\u66FE\u66FD\u695A\u72D9\u758F\u758E\u790E\u7956\u79DF\u7C97\u7D20\u7D44\u8607\u8A34\u963B\u9061\u9F20\u50E7\u5275\u53CC\u53E2\u5009\u55AA\u58EE\u594F\u723D\u5B8B\u5C64\u531D\u60E3\u60F3\u635C\u6383\u633F\u63BB"],
      ["9180", "\u64CD\u65E9\u66F9\u5DE3\u69CD\u69FD\u6F15\u71E5\u4E89\u75E9\u76F8\u7A93\u7CDF\u7DCF\u7D9C\u8061\u8349\u8358\u846C\u84BC\u85FB\u88C5\u8D70\u9001\u906D\u9397\u971C\u9A12\u50CF\u5897\u618E\u81D3\u8535\u8D08\u9020\u4FC3\u5074\u5247\u5373\u606F\u6349\u675F\u6E2C\u8DB3\u901F\u4FD7\u5C5E\u8CCA\u65CF\u7D9A\u5352\u8896\u5176\u63C3\u5B58\u5B6B\u5C0A\u640D\u6751\u905C\u4ED6\u591A\u592A\u6C70\u8A51\u553E\u5815\u59A5\u60F0\u6253\u67C1\u8235\u6955\u9640\u99C4\u9A28\u4F53\u5806\u5BFE\u8010\u5CB1\u5E2F\u5F85\u6020\u614B\u6234\u66FF\u6CF0\u6EDE\u80CE\u817F\u82D4\u888B\u8CB8\u9000\u902E\u968A\u9EDB\u9BDB\u4EE3\u53F0\u5927\u7B2C\u918D\u984C\u9DF9\u6EDD\u7027\u5353\u5544\u5B85\u6258\u629E\u62D3\u6CA2\u6FEF\u7422\u8A17\u9438\u6FC1\u8AFE\u8338\u51E7\u86F8\u53EA"],
      ["9240", "\u53E9\u4F46\u9054\u8FB0\u596A\u8131\u5DFD\u7AEA\u8FBF\u68DA\u8C37\u72F8\u9C48\u6A3D\u8AB0\u4E39\u5358\u5606\u5766\u62C5\u63A2\u65E6\u6B4E\u6DE1\u6E5B\u70AD\u77ED\u7AEF\u7BAA\u7DBB\u803D\u80C6\u86CB\u8A95\u935B\u56E3\u58C7\u5F3E\u65AD\u6696\u6A80\u6BB5\u7537\u8AC7\u5024\u77E5\u5730\u5F1B\u6065\u667A\u6C60\u75F4\u7A1A\u7F6E\u81F4\u8718\u9045\u99B3\u7BC9\u755C\u7AF9\u7B51\u84C4"],
      ["9280", "\u9010\u79E9\u7A92\u8336\u5AE1\u7740\u4E2D\u4EF2\u5B99\u5FE0\u62BD\u663C\u67F1\u6CE8\u866B\u8877\u8A3B\u914E\u92F3\u99D0\u6A17\u7026\u732A\u82E7\u8457\u8CAF\u4E01\u5146\u51CB\u558B\u5BF5\u5E16\u5E33\u5E81\u5F14\u5F35\u5F6B\u5FB4\u61F2\u6311\u66A2\u671D\u6F6E\u7252\u753A\u773A\u8074\u8139\u8178\u8776\u8ABF\u8ADC\u8D85\u8DF3\u929A\u9577\u9802\u9CE5\u52C5\u6357\u76F4\u6715\u6C88\u73CD\u8CC3\u93AE\u9673\u6D25\u589C\u690E\u69CC\u8FFD\u939A\u75DB\u901A\u585A\u6802\u63B4\u69FB\u4F43\u6F2C\u67D8\u8FBB\u8526\u7DB4\u9354\u693F\u6F70\u576A\u58F7\u5B2C\u7D2C\u722A\u540A\u91E3\u9DB4\u4EAD\u4F4E\u505C\u5075\u5243\u8C9E\u5448\u5824\u5B9A\u5E1D\u5E95\u5EAD\u5EF7\u5F1F\u608C\u62B5\u633A\u63D0\u68AF\u6C40\u7887\u798E\u7A0B\u7DE0\u8247\u8A02\u8AE6\u8E44\u9013"],
      ["9340", "\u90B8\u912D\u91D8\u9F0E\u6CE5\u6458\u64E2\u6575\u6EF4\u7684\u7B1B\u9069\u93D1\u6EBA\u54F2\u5FB9\u64A4\u8F4D\u8FED\u9244\u5178\u586B\u5929\u5C55\u5E97\u6DFB\u7E8F\u751C\u8CBC\u8EE2\u985B\u70B9\u4F1D\u6BBF\u6FB1\u7530\u96FB\u514E\u5410\u5835\u5857\u59AC\u5C60\u5F92\u6597\u675C\u6E21\u767B\u83DF\u8CED\u9014\u90FD\u934D\u7825\u783A\u52AA\u5EA6\u571F\u5974\u6012\u5012\u515A\u51AC"],
      ["9380", "\u51CD\u5200\u5510\u5854\u5858\u5957\u5B95\u5CF6\u5D8B\u60BC\u6295\u642D\u6771\u6843\u68BC\u68DF\u76D7\u6DD8\u6E6F\u6D9B\u706F\u71C8\u5F53\u75D8\u7977\u7B49\u7B54\u7B52\u7CD6\u7D71\u5230\u8463\u8569\u85E4\u8A0E\u8B04\u8C46\u8E0F\u9003\u900F\u9419\u9676\u982D\u9A30\u95D8\u50CD\u52D5\u540C\u5802\u5C0E\u61A7\u649E\u6D1E\u77B3\u7AE5\u80F4\u8404\u9053\u9285\u5CE0\u9D07\u533F\u5F97\u5FB3\u6D9C\u7279\u7763\u79BF\u7BE4\u6BD2\u72EC\u8AAD\u6803\u6A61\u51F8\u7A81\u6934\u5C4A\u9CF6\u82EB\u5BC5\u9149\u701E\u5678\u5C6F\u60C7\u6566\u6C8C\u8C5A\u9041\u9813\u5451\u66C7\u920D\u5948\u90A3\u5185\u4E4D\u51EA\u8599\u8B0E\u7058\u637A\u934B\u6962\u99B4\u7E04\u7577\u5357\u6960\u8EDF\u96E3\u6C5D\u4E8C\u5C3C\u5F10\u8FE9\u5302\u8CD1\u8089\u8679\u5EFF\u65E5\u4E73\u5165"],
      ["9440", "\u5982\u5C3F\u97EE\u4EFB\u598A\u5FCD\u8A8D\u6FE1\u79B0\u7962\u5BE7\u8471\u732B\u71B1\u5E74\u5FF5\u637B\u649A\u71C3\u7C98\u4E43\u5EFC\u4E4B\u57DC\u56A2\u60A9\u6FC3\u7D0D\u80FD\u8133\u81BF\u8FB2\u8997\u86A4\u5DF4\u628A\u64AD\u8987\u6777\u6CE2\u6D3E\u7436\u7834\u5A46\u7F75\u82AD\u99AC\u4FF3\u5EC3\u62DD\u6392\u6557\u676F\u76C3\u724C\u80CC\u80BA\u8F29\u914D\u500D\u57F9\u5A92\u6885"],
      ["9480", "\u6973\u7164\u72FD\u8CB7\u58F2\u8CE0\u966A\u9019\u877F\u79E4\u77E7\u8429\u4F2F\u5265\u535A\u62CD\u67CF\u6CCA\u767D\u7B94\u7C95\u8236\u8584\u8FEB\u66DD\u6F20\u7206\u7E1B\u83AB\u99C1\u9EA6\u51FD\u7BB1\u7872\u7BB8\u8087\u7B48\u6AE8\u5E61\u808C\u7551\u7560\u516B\u9262\u6E8C\u767A\u9197\u9AEA\u4F10\u7F70\u629C\u7B4F\u95A5\u9CE9\u567A\u5859\u86E4\u96BC\u4F34\u5224\u534A\u53CD\u53DB\u5E06\u642C\u6591\u677F\u6C3E\u6C4E\u7248\u72AF\u73ED\u7554\u7E41\u822C\u85E9\u8CA9\u7BC4\u91C6\u7169\u9812\u98EF\u633D\u6669\u756A\u76E4\u78D0\u8543\u86EE\u532A\u5351\u5426\u5983\u5E87\u5F7C\u60B2\u6249\u6279\u62AB\u6590\u6BD4\u6CCC\u75B2\u76AE\u7891\u79D8\u7DCB\u7F77\u80A5\u88AB\u8AB9\u8CBB\u907F\u975E\u98DB\u6A0B\u7C38\u5099\u5C3E\u5FAE\u6787\u6BD8\u7435\u7709\u7F8E"],
      ["9540", "\u9F3B\u67CA\u7A17\u5339\u758B\u9AED\u5F66\u819D\u83F1\u8098\u5F3C\u5FC5\u7562\u7B46\u903C\u6867\u59EB\u5A9B\u7D10\u767E\u8B2C\u4FF5\u5F6A\u6A19\u6C37\u6F02\u74E2\u7968\u8868\u8A55\u8C79\u5EDF\u63CF\u75C5\u79D2\u82D7\u9328\u92F2\u849C\u86ED\u9C2D\u54C1\u5F6C\u658C\u6D5C\u7015\u8CA7\u8CD3\u983B\u654F\u74F6\u4E0D\u4ED8\u57E0\u592B\u5A66\u5BCC\u51A8\u5E03\u5E9C\u6016\u6276\u6577"],
      ["9580", "\u65A7\u666E\u6D6E\u7236\u7B26\u8150\u819A\u8299\u8B5C\u8CA0\u8CE6\u8D74\u961C\u9644\u4FAE\u64AB\u6B66\u821E\u8461\u856A\u90E8\u5C01\u6953\u98A8\u847A\u8557\u4F0F\u526F\u5FA9\u5E45\u670D\u798F\u8179\u8907\u8986\u6DF5\u5F17\u6255\u6CB8\u4ECF\u7269\u9B92\u5206\u543B\u5674\u58B3\u61A4\u626E\u711A\u596E\u7C89\u7CDE\u7D1B\u96F0\u6587\u805E\u4E19\u4F75\u5175\u5840\u5E63\u5E73\u5F0A\u67C4\u4E26\u853D\u9589\u965B\u7C73\u9801\u50FB\u58C1\u7656\u78A7\u5225\u77A5\u8511\u7B86\u504F\u5909\u7247\u7BC7\u7DE8\u8FBA\u8FD4\u904D\u4FBF\u52C9\u5A29\u5F01\u97AD\u4FDD\u8217\u92EA\u5703\u6355\u6B69\u752B\u88DC\u8F14\u7A42\u52DF\u5893\u6155\u620A\u66AE\u6BCD\u7C3F\u83E9\u5023\u4FF8\u5305\u5446\u5831\u5949\u5B9D\u5CF0\u5CEF\u5D29\u5E96\u62B1\u6367\u653E\u65B9\u670B"],
      ["9640", "\u6CD5\u6CE1\u70F9\u7832\u7E2B\u80DE\u82B3\u840C\u84EC\u8702\u8912\u8A2A\u8C4A\u90A6\u92D2\u98FD\u9CF3\u9D6C\u4E4F\u4EA1\u508D\u5256\u574A\u59A8\u5E3D\u5FD8\u5FD9\u623F\u66B4\u671B\u67D0\u68D2\u5192\u7D21\u80AA\u81A8\u8B00\u8C8C\u8CBF\u927E\u9632\u5420\u982C\u5317\u50D5\u535C\u58A8\u64B2\u6734\u7267\u7766\u7A46\u91E6\u52C3\u6CA1\u6B86\u5800\u5E4C\u5954\u672C\u7FFB\u51E1\u76C6"],
      ["9680", "\u6469\u78E8\u9B54\u9EBB\u57CB\u59B9\u6627\u679A\u6BCE\u54E9\u69D9\u5E55\u819C\u6795\u9BAA\u67FE\u9C52\u685D\u4EA6\u4FE3\u53C8\u62B9\u672B\u6CAB\u8FC4\u4FAD\u7E6D\u9EBF\u4E07\u6162\u6E80\u6F2B\u8513\u5473\u672A\u9B45\u5DF3\u7B95\u5CAC\u5BC6\u871C\u6E4A\u84D1\u7A14\u8108\u5999\u7C8D\u6C11\u7720\u52D9\u5922\u7121\u725F\u77DB\u9727\u9D61\u690B\u5A7F\u5A18\u51A5\u540D\u547D\u660E\u76DF\u8FF7\u9298\u9CF4\u59EA\u725D\u6EC5\u514D\u68C9\u7DBF\u7DEC\u9762\u9EBA\u6478\u6A21\u8302\u5984\u5B5F\u6BDB\u731B\u76F2\u7DB2\u8017\u8499\u5132\u6728\u9ED9\u76EE\u6762\u52FF\u9905\u5C24\u623B\u7C7E\u8CB0\u554F\u60B6\u7D0B\u9580\u5301\u4E5F\u51B6\u591C\u723A\u8036\u91CE\u5F25\u77E2\u5384\u5F79\u7D04\u85AC\u8A33\u8E8D\u9756\u67F3\u85AE\u9453\u6109\u6108\u6CB9\u7652"],
      ["9740", "\u8AED\u8F38\u552F\u4F51\u512A\u52C7\u53CB\u5BA5\u5E7D\u60A0\u6182\u63D6\u6709\u67DA\u6E67\u6D8C\u7336\u7337\u7531\u7950\u88D5\u8A98\u904A\u9091\u90F5\u96C4\u878D\u5915\u4E88\u4F59\u4E0E\u8A89\u8F3F\u9810\u50AD\u5E7C\u5996\u5BB9\u5EB8\u63DA\u63FA\u64C1\u66DC\u694A\u69D8\u6D0B\u6EB6\u7194\u7528\u7AAF\u7F8A\u8000\u8449\u84C9\u8981\u8B21\u8E0A\u9065\u967D\u990A\u617E\u6291\u6B32"],
      ["9780", "\u6C83\u6D74\u7FCC\u7FFC\u6DC0\u7F85\u87BA\u88F8\u6765\u83B1\u983C\u96F7\u6D1B\u7D61\u843D\u916A\u4E71\u5375\u5D50\u6B04\u6FEB\u85CD\u862D\u89A7\u5229\u540F\u5C65\u674E\u68A8\u7406\u7483\u75E2\u88CF\u88E1\u91CC\u96E2\u9678\u5F8B\u7387\u7ACB\u844E\u63A0\u7565\u5289\u6D41\u6E9C\u7409\u7559\u786B\u7C92\u9686\u7ADC\u9F8D\u4FB6\u616E\u65C5\u865C\u4E86\u4EAE\u50DA\u4E21\u51CC\u5BEE\u6599\u6881\u6DBC\u731F\u7642\u77AD\u7A1C\u7CE7\u826F\u8AD2\u907C\u91CF\u9675\u9818\u529B\u7DD1\u502B\u5398\u6797\u6DCB\u71D0\u7433\u81E8\u8F2A\u96A3\u9C57\u9E9F\u7460\u5841\u6D99\u7D2F\u985E\u4EE4\u4F36\u4F8B\u51B7\u52B1\u5DBA\u601C\u73B2\u793C\u82D3\u9234\u96B7\u96F6\u970A\u9E97\u9F62\u66A6\u6B74\u5217\u52A3\u70C8\u88C2\u5EC9\u604B\u6190\u6F23\u7149\u7C3E\u7DF4\u806F"],
      ["9840", "\u84EE\u9023\u932C\u5442\u9B6F\u6AD3\u7089\u8CC2\u8DEF\u9732\u52B4\u5A41\u5ECA\u5F04\u6717\u697C\u6994\u6D6A\u6F0F\u7262\u72FC\u7BED\u8001\u807E\u874B\u90CE\u516D\u9E93\u7984\u808B\u9332\u8AD6\u502D\u548C\u8A71\u6B6A\u8CC4\u8107\u60D1\u67A0\u9DF2\u4E99\u4E98\u9C10\u8A6B\u85C1\u8568\u6900\u6E7E\u7897\u8155"],
      ["989f", "\u5F0C\u4E10\u4E15\u4E2A\u4E31\u4E36\u4E3C\u4E3F\u4E42\u4E56\u4E58\u4E82\u4E85\u8C6B\u4E8A\u8212\u5F0D\u4E8E\u4E9E\u4E9F\u4EA0\u4EA2\u4EB0\u4EB3\u4EB6\u4ECE\u4ECD\u4EC4\u4EC6\u4EC2\u4ED7\u4EDE\u4EED\u4EDF\u4EF7\u4F09\u4F5A\u4F30\u4F5B\u4F5D\u4F57\u4F47\u4F76\u4F88\u4F8F\u4F98\u4F7B\u4F69\u4F70\u4F91\u4F6F\u4F86\u4F96\u5118\u4FD4\u4FDF\u4FCE\u4FD8\u4FDB\u4FD1\u4FDA\u4FD0\u4FE4\u4FE5\u501A\u5028\u5014\u502A\u5025\u5005\u4F1C\u4FF6\u5021\u5029\u502C\u4FFE\u4FEF\u5011\u5006\u5043\u5047\u6703\u5055\u5050\u5048\u505A\u5056\u506C\u5078\u5080\u509A\u5085\u50B4\u50B2"],
      ["9940", "\u50C9\u50CA\u50B3\u50C2\u50D6\u50DE\u50E5\u50ED\u50E3\u50EE\u50F9\u50F5\u5109\u5101\u5102\u5116\u5115\u5114\u511A\u5121\u513A\u5137\u513C\u513B\u513F\u5140\u5152\u514C\u5154\u5162\u7AF8\u5169\u516A\u516E\u5180\u5182\u56D8\u518C\u5189\u518F\u5191\u5193\u5195\u5196\u51A4\u51A6\u51A2\u51A9\u51AA\u51AB\u51B3\u51B1\u51B2\u51B0\u51B5\u51BD\u51C5\u51C9\u51DB\u51E0\u8655\u51E9\u51ED"],
      ["9980", "\u51F0\u51F5\u51FE\u5204\u520B\u5214\u520E\u5227\u522A\u522E\u5233\u5239\u524F\u5244\u524B\u524C\u525E\u5254\u526A\u5274\u5269\u5273\u527F\u527D\u528D\u5294\u5292\u5271\u5288\u5291\u8FA8\u8FA7\u52AC\u52AD\u52BC\u52B5\u52C1\u52CD\u52D7\u52DE\u52E3\u52E6\u98ED\u52E0\u52F3\u52F5\u52F8\u52F9\u5306\u5308\u7538\u530D\u5310\u530F\u5315\u531A\u5323\u532F\u5331\u5333\u5338\u5340\u5346\u5345\u4E17\u5349\u534D\u51D6\u535E\u5369\u536E\u5918\u537B\u5377\u5382\u5396\u53A0\u53A6\u53A5\u53AE\u53B0\u53B6\u53C3\u7C12\u96D9\u53DF\u66FC\u71EE\u53EE\u53E8\u53ED\u53FA\u5401\u543D\u5440\u542C\u542D\u543C\u542E\u5436\u5429\u541D\u544E\u548F\u5475\u548E\u545F\u5471\u5477\u5470\u5492\u547B\u5480\u5476\u5484\u5490\u5486\u54C7\u54A2\u54B8\u54A5\u54AC\u54C4\u54C8\u54A8"],
      ["9a40", "\u54AB\u54C2\u54A4\u54BE\u54BC\u54D8\u54E5\u54E6\u550F\u5514\u54FD\u54EE\u54ED\u54FA\u54E2\u5539\u5540\u5563\u554C\u552E\u555C\u5545\u5556\u5557\u5538\u5533\u555D\u5599\u5580\u54AF\u558A\u559F\u557B\u557E\u5598\u559E\u55AE\u557C\u5583\u55A9\u5587\u55A8\u55DA\u55C5\u55DF\u55C4\u55DC\u55E4\u55D4\u5614\u55F7\u5616\u55FE\u55FD\u561B\u55F9\u564E\u5650\u71DF\u5634\u5636\u5632\u5638"],
      ["9a80", "\u566B\u5664\u562F\u566C\u566A\u5686\u5680\u568A\u56A0\u5694\u568F\u56A5\u56AE\u56B6\u56B4\u56C2\u56BC\u56C1\u56C3\u56C0\u56C8\u56CE\u56D1\u56D3\u56D7\u56EE\u56F9\u5700\u56FF\u5704\u5709\u5708\u570B\u570D\u5713\u5718\u5716\u55C7\u571C\u5726\u5737\u5738\u574E\u573B\u5740\u574F\u5769\u57C0\u5788\u5761\u577F\u5789\u5793\u57A0\u57B3\u57A4\u57AA\u57B0\u57C3\u57C6\u57D4\u57D2\u57D3\u580A\u57D6\u57E3\u580B\u5819\u581D\u5872\u5821\u5862\u584B\u5870\u6BC0\u5852\u583D\u5879\u5885\u58B9\u589F\u58AB\u58BA\u58DE\u58BB\u58B8\u58AE\u58C5\u58D3\u58D1\u58D7\u58D9\u58D8\u58E5\u58DC\u58E4\u58DF\u58EF\u58FA\u58F9\u58FB\u58FC\u58FD\u5902\u590A\u5910\u591B\u68A6\u5925\u592C\u592D\u5932\u5938\u593E\u7AD2\u5955\u5950\u594E\u595A\u5958\u5962\u5960\u5967\u596C\u5969"],
      ["9b40", "\u5978\u5981\u599D\u4F5E\u4FAB\u59A3\u59B2\u59C6\u59E8\u59DC\u598D\u59D9\u59DA\u5A25\u5A1F\u5A11\u5A1C\u5A09\u5A1A\u5A40\u5A6C\u5A49\u5A35\u5A36\u5A62\u5A6A\u5A9A\u5ABC\u5ABE\u5ACB\u5AC2\u5ABD\u5AE3\u5AD7\u5AE6\u5AE9\u5AD6\u5AFA\u5AFB\u5B0C\u5B0B\u5B16\u5B32\u5AD0\u5B2A\u5B36\u5B3E\u5B43\u5B45\u5B40\u5B51\u5B55\u5B5A\u5B5B\u5B65\u5B69\u5B70\u5B73\u5B75\u5B78\u6588\u5B7A\u5B80"],
      ["9b80", "\u5B83\u5BA6\u5BB8\u5BC3\u5BC7\u5BC9\u5BD4\u5BD0\u5BE4\u5BE6\u5BE2\u5BDE\u5BE5\u5BEB\u5BF0\u5BF6\u5BF3\u5C05\u5C07\u5C08\u5C0D\u5C13\u5C20\u5C22\u5C28\u5C38\u5C39\u5C41\u5C46\u5C4E\u5C53\u5C50\u5C4F\u5B71\u5C6C\u5C6E\u4E62\u5C76\u5C79\u5C8C\u5C91\u5C94\u599B\u5CAB\u5CBB\u5CB6\u5CBC\u5CB7\u5CC5\u5CBE\u5CC7\u5CD9\u5CE9\u5CFD\u5CFA\u5CED\u5D8C\u5CEA\u5D0B\u5D15\u5D17\u5D5C\u5D1F\u5D1B\u5D11\u5D14\u5D22\u5D1A\u5D19\u5D18\u5D4C\u5D52\u5D4E\u5D4B\u5D6C\u5D73\u5D76\u5D87\u5D84\u5D82\u5DA2\u5D9D\u5DAC\u5DAE\u5DBD\u5D90\u5DB7\u5DBC\u5DC9\u5DCD\u5DD3\u5DD2\u5DD6\u5DDB\u5DEB\u5DF2\u5DF5\u5E0B\u5E1A\u5E19\u5E11\u5E1B\u5E36\u5E37\u5E44\u5E43\u5E40\u5E4E\u5E57\u5E54\u5E5F\u5E62\u5E64\u5E47\u5E75\u5E76\u5E7A\u9EBC\u5E7F\u5EA0\u5EC1\u5EC2\u5EC8\u5ED0\u5ECF"],
      ["9c40", "\u5ED6\u5EE3\u5EDD\u5EDA\u5EDB\u5EE2\u5EE1\u5EE8\u5EE9\u5EEC\u5EF1\u5EF3\u5EF0\u5EF4\u5EF8\u5EFE\u5F03\u5F09\u5F5D\u5F5C\u5F0B\u5F11\u5F16\u5F29\u5F2D\u5F38\u5F41\u5F48\u5F4C\u5F4E\u5F2F\u5F51\u5F56\u5F57\u5F59\u5F61\u5F6D\u5F73\u5F77\u5F83\u5F82\u5F7F\u5F8A\u5F88\u5F91\u5F87\u5F9E\u5F99\u5F98\u5FA0\u5FA8\u5FAD\u5FBC\u5FD6\u5FFB\u5FE4\u5FF8\u5FF1\u5FDD\u60B3\u5FFF\u6021\u6060"],
      ["9c80", "\u6019\u6010\u6029\u600E\u6031\u601B\u6015\u602B\u6026\u600F\u603A\u605A\u6041\u606A\u6077\u605F\u604A\u6046\u604D\u6063\u6043\u6064\u6042\u606C\u606B\u6059\u6081\u608D\u60E7\u6083\u609A\u6084\u609B\u6096\u6097\u6092\u60A7\u608B\u60E1\u60B8\u60E0\u60D3\u60B4\u5FF0\u60BD\u60C6\u60B5\u60D8\u614D\u6115\u6106\u60F6\u60F7\u6100\u60F4\u60FA\u6103\u6121\u60FB\u60F1\u610D\u610E\u6147\u613E\u6128\u6127\u614A\u613F\u613C\u612C\u6134\u613D\u6142\u6144\u6173\u6177\u6158\u6159\u615A\u616B\u6174\u616F\u6165\u6171\u615F\u615D\u6153\u6175\u6199\u6196\u6187\u61AC\u6194\u619A\u618A\u6191\u61AB\u61AE\u61CC\u61CA\u61C9\u61F7\u61C8\u61C3\u61C6\u61BA\u61CB\u7F79\u61CD\u61E6\u61E3\u61F6\u61FA\u61F4\u61FF\u61FD\u61FC\u61FE\u6200\u6208\u6209\u620D\u620C\u6214\u621B"],
      ["9d40", "\u621E\u6221\u622A\u622E\u6230\u6232\u6233\u6241\u624E\u625E\u6263\u625B\u6260\u6268\u627C\u6282\u6289\u627E\u6292\u6293\u6296\u62D4\u6283\u6294\u62D7\u62D1\u62BB\u62CF\u62FF\u62C6\u64D4\u62C8\u62DC\u62CC\u62CA\u62C2\u62C7\u629B\u62C9\u630C\u62EE\u62F1\u6327\u6302\u6308\u62EF\u62F5\u6350\u633E\u634D\u641C\u634F\u6396\u638E\u6380\u63AB\u6376\u63A3\u638F\u6389\u639F\u63B5\u636B"],
      ["9d80", "\u6369\u63BE\u63E9\u63C0\u63C6\u63E3\u63C9\u63D2\u63F6\u63C4\u6416\u6434\u6406\u6413\u6426\u6436\u651D\u6417\u6428\u640F\u6467\u646F\u6476\u644E\u652A\u6495\u6493\u64A5\u64A9\u6488\u64BC\u64DA\u64D2\u64C5\u64C7\u64BB\u64D8\u64C2\u64F1\u64E7\u8209\u64E0\u64E1\u62AC\u64E3\u64EF\u652C\u64F6\u64F4\u64F2\u64FA\u6500\u64FD\u6518\u651C\u6505\u6524\u6523\u652B\u6534\u6535\u6537\u6536\u6538\u754B\u6548\u6556\u6555\u654D\u6558\u655E\u655D\u6572\u6578\u6582\u6583\u8B8A\u659B\u659F\u65AB\u65B7\u65C3\u65C6\u65C1\u65C4\u65CC\u65D2\u65DB\u65D9\u65E0\u65E1\u65F1\u6772\u660A\u6603\u65FB\u6773\u6635\u6636\u6634\u661C\u664F\u6644\u6649\u6641\u665E\u665D\u6664\u6667\u6668\u665F\u6662\u6670\u6683\u6688\u668E\u6689\u6684\u6698\u669D\u66C1\u66B9\u66C9\u66BE\u66BC"],
      ["9e40", "\u66C4\u66B8\u66D6\u66DA\u66E0\u663F\u66E6\u66E9\u66F0\u66F5\u66F7\u670F\u6716\u671E\u6726\u6727\u9738\u672E\u673F\u6736\u6741\u6738\u6737\u6746\u675E\u6760\u6759\u6763\u6764\u6789\u6770\u67A9\u677C\u676A\u678C\u678B\u67A6\u67A1\u6785\u67B7\u67EF\u67B4\u67EC\u67B3\u67E9\u67B8\u67E4\u67DE\u67DD\u67E2\u67EE\u67B9\u67CE\u67C6\u67E7\u6A9C\u681E\u6846\u6829\u6840\u684D\u6832\u684E"],
      ["9e80", "\u68B3\u682B\u6859\u6863\u6877\u687F\u689F\u688F\u68AD\u6894\u689D\u689B\u6883\u6AAE\u68B9\u6874\u68B5\u68A0\u68BA\u690F\u688D\u687E\u6901\u68CA\u6908\u68D8\u6922\u6926\u68E1\u690C\u68CD\u68D4\u68E7\u68D5\u6936\u6912\u6904\u68D7\u68E3\u6925\u68F9\u68E0\u68EF\u6928\u692A\u691A\u6923\u6921\u68C6\u6979\u6977\u695C\u6978\u696B\u6954\u697E\u696E\u6939\u6974\u693D\u6959\u6930\u6961\u695E\u695D\u6981\u696A\u69B2\u69AE\u69D0\u69BF\u69C1\u69D3\u69BE\u69CE\u5BE8\u69CA\u69DD\u69BB\u69C3\u69A7\u6A2E\u6991\u69A0\u699C\u6995\u69B4\u69DE\u69E8\u6A02\u6A1B\u69FF\u6B0A\u69F9\u69F2\u69E7\u6A05\u69B1\u6A1E\u69ED\u6A14\u69EB\u6A0A\u6A12\u6AC1\u6A23\u6A13\u6A44\u6A0C\u6A72\u6A36\u6A78\u6A47\u6A62\u6A59\u6A66\u6A48\u6A38\u6A22\u6A90\u6A8D\u6AA0\u6A84\u6AA2\u6AA3"],
      ["9f40", "\u6A97\u8617\u6ABB\u6AC3\u6AC2\u6AB8\u6AB3\u6AAC\u6ADE\u6AD1\u6ADF\u6AAA\u6ADA\u6AEA\u6AFB\u6B05\u8616\u6AFA\u6B12\u6B16\u9B31\u6B1F\u6B38\u6B37\u76DC\u6B39\u98EE\u6B47\u6B43\u6B49\u6B50\u6B59\u6B54\u6B5B\u6B5F\u6B61\u6B78\u6B79\u6B7F\u6B80\u6B84\u6B83\u6B8D\u6B98\u6B95\u6B9E\u6BA4\u6BAA\u6BAB\u6BAF\u6BB2\u6BB1\u6BB3\u6BB7\u6BBC\u6BC6\u6BCB\u6BD3\u6BDF\u6BEC\u6BEB\u6BF3\u6BEF"],
      ["9f80", "\u9EBE\u6C08\u6C13\u6C14\u6C1B\u6C24\u6C23\u6C5E\u6C55\u6C62\u6C6A\u6C82\u6C8D\u6C9A\u6C81\u6C9B\u6C7E\u6C68\u6C73\u6C92\u6C90\u6CC4\u6CF1\u6CD3\u6CBD\u6CD7\u6CC5\u6CDD\u6CAE\u6CB1\u6CBE\u6CBA\u6CDB\u6CEF\u6CD9\u6CEA\u6D1F\u884D\u6D36\u6D2B\u6D3D\u6D38\u6D19\u6D35\u6D33\u6D12\u6D0C\u6D63\u6D93\u6D64\u6D5A\u6D79\u6D59\u6D8E\u6D95\u6FE4\u6D85\u6DF9\u6E15\u6E0A\u6DB5\u6DC7\u6DE6\u6DB8\u6DC6\u6DEC\u6DDE\u6DCC\u6DE8\u6DD2\u6DC5\u6DFA\u6DD9\u6DE4\u6DD5\u6DEA\u6DEE\u6E2D\u6E6E\u6E2E\u6E19\u6E72\u6E5F\u6E3E\u6E23\u6E6B\u6E2B\u6E76\u6E4D\u6E1F\u6E43\u6E3A\u6E4E\u6E24\u6EFF\u6E1D\u6E38\u6E82\u6EAA\u6E98\u6EC9\u6EB7\u6ED3\u6EBD\u6EAF\u6EC4\u6EB2\u6ED4\u6ED5\u6E8F\u6EA5\u6EC2\u6E9F\u6F41\u6F11\u704C\u6EEC\u6EF8\u6EFE\u6F3F\u6EF2\u6F31\u6EEF\u6F32\u6ECC"],
      ["e040", "\u6F3E\u6F13\u6EF7\u6F86\u6F7A\u6F78\u6F81\u6F80\u6F6F\u6F5B\u6FF3\u6F6D\u6F82\u6F7C\u6F58\u6F8E\u6F91\u6FC2\u6F66\u6FB3\u6FA3\u6FA1\u6FA4\u6FB9\u6FC6\u6FAA\u6FDF\u6FD5\u6FEC\u6FD4\u6FD8\u6FF1\u6FEE\u6FDB\u7009\u700B\u6FFA\u7011\u7001\u700F\u6FFE\u701B\u701A\u6F74\u701D\u7018\u701F\u7030\u703E\u7032\u7051\u7063\u7099\u7092\u70AF\u70F1\u70AC\u70B8\u70B3\u70AE\u70DF\u70CB\u70DD"],
      ["e080", "\u70D9\u7109\u70FD\u711C\u7119\u7165\u7155\u7188\u7166\u7162\u714C\u7156\u716C\u718F\u71FB\u7184\u7195\u71A8\u71AC\u71D7\u71B9\u71BE\u71D2\u71C9\u71D4\u71CE\u71E0\u71EC\u71E7\u71F5\u71FC\u71F9\u71FF\u720D\u7210\u721B\u7228\u722D\u722C\u7230\u7232\u723B\u723C\u723F\u7240\u7246\u724B\u7258\u7274\u727E\u7282\u7281\u7287\u7292\u7296\u72A2\u72A7\u72B9\u72B2\u72C3\u72C6\u72C4\u72CE\u72D2\u72E2\u72E0\u72E1\u72F9\u72F7\u500F\u7317\u730A\u731C\u7316\u731D\u7334\u732F\u7329\u7325\u733E\u734E\u734F\u9ED8\u7357\u736A\u7368\u7370\u7378\u7375\u737B\u737A\u73C8\u73B3\u73CE\u73BB\u73C0\u73E5\u73EE\u73DE\u74A2\u7405\u746F\u7425\u73F8\u7432\u743A\u7455\u743F\u745F\u7459\u7441\u745C\u7469\u7470\u7463\u746A\u7476\u747E\u748B\u749E\u74A7\u74CA\u74CF\u74D4\u73F1"],
      ["e140", "\u74E0\u74E3\u74E7\u74E9\u74EE\u74F2\u74F0\u74F1\u74F8\u74F7\u7504\u7503\u7505\u750C\u750E\u750D\u7515\u7513\u751E\u7526\u752C\u753C\u7544\u754D\u754A\u7549\u755B\u7546\u755A\u7569\u7564\u7567\u756B\u756D\u7578\u7576\u7586\u7587\u7574\u758A\u7589\u7582\u7594\u759A\u759D\u75A5\u75A3\u75C2\u75B3\u75C3\u75B5\u75BD\u75B8\u75BC\u75B1\u75CD\u75CA\u75D2\u75D9\u75E3\u75DE\u75FE\u75FF"],
      ["e180", "\u75FC\u7601\u75F0\u75FA\u75F2\u75F3\u760B\u760D\u7609\u761F\u7627\u7620\u7621\u7622\u7624\u7634\u7630\u763B\u7647\u7648\u7646\u765C\u7658\u7661\u7662\u7668\u7669\u766A\u7667\u766C\u7670\u7672\u7676\u7678\u767C\u7680\u7683\u7688\u768B\u768E\u7696\u7693\u7699\u769A\u76B0\u76B4\u76B8\u76B9\u76BA\u76C2\u76CD\u76D6\u76D2\u76DE\u76E1\u76E5\u76E7\u76EA\u862F\u76FB\u7708\u7707\u7704\u7729\u7724\u771E\u7725\u7726\u771B\u7737\u7738\u7747\u775A\u7768\u776B\u775B\u7765\u777F\u777E\u7779\u778E\u778B\u7791\u77A0\u779E\u77B0\u77B6\u77B9\u77BF\u77BC\u77BD\u77BB\u77C7\u77CD\u77D7\u77DA\u77DC\u77E3\u77EE\u77FC\u780C\u7812\u7926\u7820\u792A\u7845\u788E\u7874\u7886\u787C\u789A\u788C\u78A3\u78B5\u78AA\u78AF\u78D1\u78C6\u78CB\u78D4\u78BE\u78BC\u78C5\u78CA\u78EC"],
      ["e240", "\u78E7\u78DA\u78FD\u78F4\u7907\u7912\u7911\u7919\u792C\u792B\u7940\u7960\u7957\u795F\u795A\u7955\u7953\u797A\u797F\u798A\u799D\u79A7\u9F4B\u79AA\u79AE\u79B3\u79B9\u79BA\u79C9\u79D5\u79E7\u79EC\u79E1\u79E3\u7A08\u7A0D\u7A18\u7A19\u7A20\u7A1F\u7980\u7A31\u7A3B\u7A3E\u7A37\u7A43\u7A57\u7A49\u7A61\u7A62\u7A69\u9F9D\u7A70\u7A79\u7A7D\u7A88\u7A97\u7A95\u7A98\u7A96\u7AA9\u7AC8\u7AB0"],
      ["e280", "\u7AB6\u7AC5\u7AC4\u7ABF\u9083\u7AC7\u7ACA\u7ACD\u7ACF\u7AD5\u7AD3\u7AD9\u7ADA\u7ADD\u7AE1\u7AE2\u7AE6\u7AED\u7AF0\u7B02\u7B0F\u7B0A\u7B06\u7B33\u7B18\u7B19\u7B1E\u7B35\u7B28\u7B36\u7B50\u7B7A\u7B04\u7B4D\u7B0B\u7B4C\u7B45\u7B75\u7B65\u7B74\u7B67\u7B70\u7B71\u7B6C\u7B6E\u7B9D\u7B98\u7B9F\u7B8D\u7B9C\u7B9A\u7B8B\u7B92\u7B8F\u7B5D\u7B99\u7BCB\u7BC1\u7BCC\u7BCF\u7BB4\u7BC6\u7BDD\u7BE9\u7C11\u7C14\u7BE6\u7BE5\u7C60\u7C00\u7C07\u7C13\u7BF3\u7BF7\u7C17\u7C0D\u7BF6\u7C23\u7C27\u7C2A\u7C1F\u7C37\u7C2B\u7C3D\u7C4C\u7C43\u7C54\u7C4F\u7C40\u7C50\u7C58\u7C5F\u7C64\u7C56\u7C65\u7C6C\u7C75\u7C83\u7C90\u7CA4\u7CAD\u7CA2\u7CAB\u7CA1\u7CA8\u7CB3\u7CB2\u7CB1\u7CAE\u7CB9\u7CBD\u7CC0\u7CC5\u7CC2\u7CD8\u7CD2\u7CDC\u7CE2\u9B3B\u7CEF\u7CF2\u7CF4\u7CF6\u7CFA\u7D06"],
      ["e340", "\u7D02\u7D1C\u7D15\u7D0A\u7D45\u7D4B\u7D2E\u7D32\u7D3F\u7D35\u7D46\u7D73\u7D56\u7D4E\u7D72\u7D68\u7D6E\u7D4F\u7D63\u7D93\u7D89\u7D5B\u7D8F\u7D7D\u7D9B\u7DBA\u7DAE\u7DA3\u7DB5\u7DC7\u7DBD\u7DAB\u7E3D\u7DA2\u7DAF\u7DDC\u7DB8\u7D9F\u7DB0\u7DD8\u7DDD\u7DE4\u7DDE\u7DFB\u7DF2\u7DE1\u7E05\u7E0A\u7E23\u7E21\u7E12\u7E31\u7E1F\u7E09\u7E0B\u7E22\u7E46\u7E66\u7E3B\u7E35\u7E39\u7E43\u7E37"],
      ["e380", "\u7E32\u7E3A\u7E67\u7E5D\u7E56\u7E5E\u7E59\u7E5A\u7E79\u7E6A\u7E69\u7E7C\u7E7B\u7E83\u7DD5\u7E7D\u8FAE\u7E7F\u7E88\u7E89\u7E8C\u7E92\u7E90\u7E93\u7E94\u7E96\u7E8E\u7E9B\u7E9C\u7F38\u7F3A\u7F45\u7F4C\u7F4D\u7F4E\u7F50\u7F51\u7F55\u7F54\u7F58\u7F5F\u7F60\u7F68\u7F69\u7F67\u7F78\u7F82\u7F86\u7F83\u7F88\u7F87\u7F8C\u7F94\u7F9E\u7F9D\u7F9A\u7FA3\u7FAF\u7FB2\u7FB9\u7FAE\u7FB6\u7FB8\u8B71\u7FC5\u7FC6\u7FCA\u7FD5\u7FD4\u7FE1\u7FE6\u7FE9\u7FF3\u7FF9\u98DC\u8006\u8004\u800B\u8012\u8018\u8019\u801C\u8021\u8028\u803F\u803B\u804A\u8046\u8052\u8058\u805A\u805F\u8062\u8068\u8073\u8072\u8070\u8076\u8079\u807D\u807F\u8084\u8086\u8085\u809B\u8093\u809A\u80AD\u5190\u80AC\u80DB\u80E5\u80D9\u80DD\u80C4\u80DA\u80D6\u8109\u80EF\u80F1\u811B\u8129\u8123\u812F\u814B"],
      ["e440", "\u968B\u8146\u813E\u8153\u8151\u80FC\u8171\u816E\u8165\u8166\u8174\u8183\u8188\u818A\u8180\u8182\u81A0\u8195\u81A4\u81A3\u815F\u8193\u81A9\u81B0\u81B5\u81BE\u81B8\u81BD\u81C0\u81C2\u81BA\u81C9\u81CD\u81D1\u81D9\u81D8\u81C8\u81DA\u81DF\u81E0\u81E7\u81FA\u81FB\u81FE\u8201\u8202\u8205\u8207\u820A\u820D\u8210\u8216\u8229\u822B\u8238\u8233\u8240\u8259\u8258\u825D\u825A\u825F\u8264"],
      ["e480", "\u8262\u8268\u826A\u826B\u822E\u8271\u8277\u8278\u827E\u828D\u8292\u82AB\u829F\u82BB\u82AC\u82E1\u82E3\u82DF\u82D2\u82F4\u82F3\u82FA\u8393\u8303\u82FB\u82F9\u82DE\u8306\u82DC\u8309\u82D9\u8335\u8334\u8316\u8332\u8331\u8340\u8339\u8350\u8345\u832F\u832B\u8317\u8318\u8385\u839A\u83AA\u839F\u83A2\u8396\u8323\u838E\u8387\u838A\u837C\u83B5\u8373\u8375\u83A0\u8389\u83A8\u83F4\u8413\u83EB\u83CE\u83FD\u8403\u83D8\u840B\u83C1\u83F7\u8407\u83E0\u83F2\u840D\u8422\u8420\u83BD\u8438\u8506\u83FB\u846D\u842A\u843C\u855A\u8484\u8477\u846B\u84AD\u846E\u8482\u8469\u8446\u842C\u846F\u8479\u8435\u84CA\u8462\u84B9\u84BF\u849F\u84D9\u84CD\u84BB\u84DA\u84D0\u84C1\u84C6\u84D6\u84A1\u8521\u84FF\u84F4\u8517\u8518\u852C\u851F\u8515\u8514\u84FC\u8540\u8563\u8558\u8548"],
      ["e540", "\u8541\u8602\u854B\u8555\u8580\u85A4\u8588\u8591\u858A\u85A8\u856D\u8594\u859B\u85EA\u8587\u859C\u8577\u857E\u8590\u85C9\u85BA\u85CF\u85B9\u85D0\u85D5\u85DD\u85E5\u85DC\u85F9\u860A\u8613\u860B\u85FE\u85FA\u8606\u8622\u861A\u8630\u863F\u864D\u4E55\u8654\u865F\u8667\u8671\u8693\u86A3\u86A9\u86AA\u868B\u868C\u86B6\u86AF\u86C4\u86C6\u86B0\u86C9\u8823\u86AB\u86D4\u86DE\u86E9\u86EC"],
      ["e580", "\u86DF\u86DB\u86EF\u8712\u8706\u8708\u8700\u8703\u86FB\u8711\u8709\u870D\u86F9\u870A\u8734\u873F\u8737\u873B\u8725\u8729\u871A\u8760\u875F\u8778\u874C\u874E\u8774\u8757\u8768\u876E\u8759\u8753\u8763\u876A\u8805\u87A2\u879F\u8782\u87AF\u87CB\u87BD\u87C0\u87D0\u96D6\u87AB\u87C4\u87B3\u87C7\u87C6\u87BB\u87EF\u87F2\u87E0\u880F\u880D\u87FE\u87F6\u87F7\u880E\u87D2\u8811\u8816\u8815\u8822\u8821\u8831\u8836\u8839\u8827\u883B\u8844\u8842\u8852\u8859\u885E\u8862\u886B\u8881\u887E\u889E\u8875\u887D\u88B5\u8872\u8882\u8897\u8892\u88AE\u8899\u88A2\u888D\u88A4\u88B0\u88BF\u88B1\u88C3\u88C4\u88D4\u88D8\u88D9\u88DD\u88F9\u8902\u88FC\u88F4\u88E8\u88F2\u8904\u890C\u890A\u8913\u8943\u891E\u8925\u892A\u892B\u8941\u8944\u893B\u8936\u8938\u894C\u891D\u8960\u895E"],
      ["e640", "\u8966\u8964\u896D\u896A\u896F\u8974\u8977\u897E\u8983\u8988\u898A\u8993\u8998\u89A1\u89A9\u89A6\u89AC\u89AF\u89B2\u89BA\u89BD\u89BF\u89C0\u89DA\u89DC\u89DD\u89E7\u89F4\u89F8\u8A03\u8A16\u8A10\u8A0C\u8A1B\u8A1D\u8A25\u8A36\u8A41\u8A5B\u8A52\u8A46\u8A48\u8A7C\u8A6D\u8A6C\u8A62\u8A85\u8A82\u8A84\u8AA8\u8AA1\u8A91\u8AA5\u8AA6\u8A9A\u8AA3\u8AC4\u8ACD\u8AC2\u8ADA\u8AEB\u8AF3\u8AE7"],
      ["e680", "\u8AE4\u8AF1\u8B14\u8AE0\u8AE2\u8AF7\u8ADE\u8ADB\u8B0C\u8B07\u8B1A\u8AE1\u8B16\u8B10\u8B17\u8B20\u8B33\u97AB\u8B26\u8B2B\u8B3E\u8B28\u8B41\u8B4C\u8B4F\u8B4E\u8B49\u8B56\u8B5B\u8B5A\u8B6B\u8B5F\u8B6C\u8B6F\u8B74\u8B7D\u8B80\u8B8C\u8B8E\u8B92\u8B93\u8B96\u8B99\u8B9A\u8C3A\u8C41\u8C3F\u8C48\u8C4C\u8C4E\u8C50\u8C55\u8C62\u8C6C\u8C78\u8C7A\u8C82\u8C89\u8C85\u8C8A\u8C8D\u8C8E\u8C94\u8C7C\u8C98\u621D\u8CAD\u8CAA\u8CBD\u8CB2\u8CB3\u8CAE\u8CB6\u8CC8\u8CC1\u8CE4\u8CE3\u8CDA\u8CFD\u8CFA\u8CFB\u8D04\u8D05\u8D0A\u8D07\u8D0F\u8D0D\u8D10\u9F4E\u8D13\u8CCD\u8D14\u8D16\u8D67\u8D6D\u8D71\u8D73\u8D81\u8D99\u8DC2\u8DBE\u8DBA\u8DCF\u8DDA\u8DD6\u8DCC\u8DDB\u8DCB\u8DEA\u8DEB\u8DDF\u8DE3\u8DFC\u8E08\u8E09\u8DFF\u8E1D\u8E1E\u8E10\u8E1F\u8E42\u8E35\u8E30\u8E34\u8E4A"],
      ["e740", "\u8E47\u8E49\u8E4C\u8E50\u8E48\u8E59\u8E64\u8E60\u8E2A\u8E63\u8E55\u8E76\u8E72\u8E7C\u8E81\u8E87\u8E85\u8E84\u8E8B\u8E8A\u8E93\u8E91\u8E94\u8E99\u8EAA\u8EA1\u8EAC\u8EB0\u8EC6\u8EB1\u8EBE\u8EC5\u8EC8\u8ECB\u8EDB\u8EE3\u8EFC\u8EFB\u8EEB\u8EFE\u8F0A\u8F05\u8F15\u8F12\u8F19\u8F13\u8F1C\u8F1F\u8F1B\u8F0C\u8F26\u8F33\u8F3B\u8F39\u8F45\u8F42\u8F3E\u8F4C\u8F49\u8F46\u8F4E\u8F57\u8F5C"],
      ["e780", "\u8F62\u8F63\u8F64\u8F9C\u8F9F\u8FA3\u8FAD\u8FAF\u8FB7\u8FDA\u8FE5\u8FE2\u8FEA\u8FEF\u9087\u8FF4\u9005\u8FF9\u8FFA\u9011\u9015\u9021\u900D\u901E\u9016\u900B\u9027\u9036\u9035\u9039\u8FF8\u904F\u9050\u9051\u9052\u900E\u9049\u903E\u9056\u9058\u905E\u9068\u906F\u9076\u96A8\u9072\u9082\u907D\u9081\u9080\u908A\u9089\u908F\u90A8\u90AF\u90B1\u90B5\u90E2\u90E4\u6248\u90DB\u9102\u9112\u9119\u9132\u9130\u914A\u9156\u9158\u9163\u9165\u9169\u9173\u9172\u918B\u9189\u9182\u91A2\u91AB\u91AF\u91AA\u91B5\u91B4\u91BA\u91C0\u91C1\u91C9\u91CB\u91D0\u91D6\u91DF\u91E1\u91DB\u91FC\u91F5\u91F6\u921E\u91FF\u9214\u922C\u9215\u9211\u925E\u9257\u9245\u9249\u9264\u9248\u9295\u923F\u924B\u9250\u929C\u9296\u9293\u929B\u925A\u92CF\u92B9\u92B7\u92E9\u930F\u92FA\u9344\u932E"],
      ["e840", "\u9319\u9322\u931A\u9323\u933A\u9335\u933B\u935C\u9360\u937C\u936E\u9356\u93B0\u93AC\u93AD\u9394\u93B9\u93D6\u93D7\u93E8\u93E5\u93D8\u93C3\u93DD\u93D0\u93C8\u93E4\u941A\u9414\u9413\u9403\u9407\u9410\u9436\u942B\u9435\u9421\u943A\u9441\u9452\u9444\u945B\u9460\u9462\u945E\u946A\u9229\u9470\u9475\u9477\u947D\u945A\u947C\u947E\u9481\u947F\u9582\u9587\u958A\u9594\u9596\u9598\u9599"],
      ["e880", "\u95A0\u95A8\u95A7\u95AD\u95BC\u95BB\u95B9\u95BE\u95CA\u6FF6\u95C3\u95CD\u95CC\u95D5\u95D4\u95D6\u95DC\u95E1\u95E5\u95E2\u9621\u9628\u962E\u962F\u9642\u964C\u964F\u964B\u9677\u965C\u965E\u965D\u965F\u9666\u9672\u966C\u968D\u9698\u9695\u9697\u96AA\u96A7\u96B1\u96B2\u96B0\u96B4\u96B6\u96B8\u96B9\u96CE\u96CB\u96C9\u96CD\u894D\u96DC\u970D\u96D5\u96F9\u9704\u9706\u9708\u9713\u970E\u9711\u970F\u9716\u9719\u9724\u972A\u9730\u9739\u973D\u973E\u9744\u9746\u9748\u9742\u9749\u975C\u9760\u9764\u9766\u9768\u52D2\u976B\u9771\u9779\u9785\u977C\u9781\u977A\u9786\u978B\u978F\u9790\u979C\u97A8\u97A6\u97A3\u97B3\u97B4\u97C3\u97C6\u97C8\u97CB\u97DC\u97ED\u9F4F\u97F2\u7ADF\u97F6\u97F5\u980F\u980C\u9838\u9824\u9821\u9837\u983D\u9846\u984F\u984B\u986B\u986F\u9870"],
      ["e940", "\u9871\u9874\u9873\u98AA\u98AF\u98B1\u98B6\u98C4\u98C3\u98C6\u98E9\u98EB\u9903\u9909\u9912\u9914\u9918\u9921\u991D\u991E\u9924\u9920\u992C\u992E\u993D\u993E\u9942\u9949\u9945\u9950\u994B\u9951\u9952\u994C\u9955\u9997\u9998\u99A5\u99AD\u99AE\u99BC\u99DF\u99DB\u99DD\u99D8\u99D1\u99ED\u99EE\u99F1\u99F2\u99FB\u99F8\u9A01\u9A0F\u9A05\u99E2\u9A19\u9A2B\u9A37\u9A45\u9A42\u9A40\u9A43"],
      ["e980", "\u9A3E\u9A55\u9A4D\u9A5B\u9A57\u9A5F\u9A62\u9A65\u9A64\u9A69\u9A6B\u9A6A\u9AAD\u9AB0\u9ABC\u9AC0\u9ACF\u9AD1\u9AD3\u9AD4\u9ADE\u9ADF\u9AE2\u9AE3\u9AE6\u9AEF\u9AEB\u9AEE\u9AF4\u9AF1\u9AF7\u9AFB\u9B06\u9B18\u9B1A\u9B1F\u9B22\u9B23\u9B25\u9B27\u9B28\u9B29\u9B2A\u9B2E\u9B2F\u9B32\u9B44\u9B43\u9B4F\u9B4D\u9B4E\u9B51\u9B58\u9B74\u9B93\u9B83\u9B91\u9B96\u9B97\u9B9F\u9BA0\u9BA8\u9BB4\u9BC0\u9BCA\u9BB9\u9BC6\u9BCF\u9BD1\u9BD2\u9BE3\u9BE2\u9BE4\u9BD4\u9BE1\u9C3A\u9BF2\u9BF1\u9BF0\u9C15\u9C14\u9C09\u9C13\u9C0C\u9C06\u9C08\u9C12\u9C0A\u9C04\u9C2E\u9C1B\u9C25\u9C24\u9C21\u9C30\u9C47\u9C32\u9C46\u9C3E\u9C5A\u9C60\u9C67\u9C76\u9C78\u9CE7\u9CEC\u9CF0\u9D09\u9D08\u9CEB\u9D03\u9D06\u9D2A\u9D26\u9DAF\u9D23\u9D1F\u9D44\u9D15\u9D12\u9D41\u9D3F\u9D3E\u9D46\u9D48"],
      ["ea40", "\u9D5D\u9D5E\u9D64\u9D51\u9D50\u9D59\u9D72\u9D89\u9D87\u9DAB\u9D6F\u9D7A\u9D9A\u9DA4\u9DA9\u9DB2\u9DC4\u9DC1\u9DBB\u9DB8\u9DBA\u9DC6\u9DCF\u9DC2\u9DD9\u9DD3\u9DF8\u9DE6\u9DED\u9DEF\u9DFD\u9E1A\u9E1B\u9E1E\u9E75\u9E79\u9E7D\u9E81\u9E88\u9E8B\u9E8C\u9E92\u9E95\u9E91\u9E9D\u9EA5\u9EA9\u9EB8\u9EAA\u9EAD\u9761\u9ECC\u9ECE\u9ECF\u9ED0\u9ED4\u9EDC\u9EDE\u9EDD\u9EE0\u9EE5\u9EE8\u9EEF"],
      ["ea80", "\u9EF4\u9EF6\u9EF7\u9EF9\u9EFB\u9EFC\u9EFD\u9F07\u9F08\u76B7\u9F15\u9F21\u9F2C\u9F3E\u9F4A\u9F52\u9F54\u9F63\u9F5F\u9F60\u9F61\u9F66\u9F67\u9F6C\u9F6A\u9F77\u9F72\u9F76\u9F95\u9F9C\u9FA0\u582F\u69C7\u9059\u7464\u51DC\u7199"],
      ["ed40", "\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F"],
      ["ed80", "\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1"],
      ["ee40", "\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559"],
      ["ee80", "\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"],
      ["eeef", "\u2170", 9, "\uFFE2\uFFE4\uFF07\uFF02"],
      ["f040", "\uE000", 62],
      ["f080", "\uE03F", 124],
      ["f140", "\uE0BC", 62],
      ["f180", "\uE0FB", 124],
      ["f240", "\uE178", 62],
      ["f280", "\uE1B7", 124],
      ["f340", "\uE234", 62],
      ["f380", "\uE273", 124],
      ["f440", "\uE2F0", 62],
      ["f480", "\uE32F", 124],
      ["f540", "\uE3AC", 62],
      ["f580", "\uE3EB", 124],
      ["f640", "\uE468", 62],
      ["f680", "\uE4A7", 124],
      ["f740", "\uE524", 62],
      ["f780", "\uE563", 124],
      ["f840", "\uE5E0", 62],
      ["f880", "\uE61F", 124],
      ["f940", "\uE69C"],
      ["fa40", "\u2170", 9, "\u2160", 9, "\uFFE2\uFFE4\uFF07\uFF02\u3231\u2116\u2121\u2235\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A"],
      ["fa80", "\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F"],
      ["fb40", "\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19"],
      ["fb80", "\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9"],
      ["fc40", "\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"]
    ];
  }
});

// packages/core/node_modules/iconv-lite/encodings/tables/eucjp.json
var require_eucjp = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/tables/eucjp.json"(exports2, module2) {
    module2.exports = [
      ["0", "\0", 127],
      ["8ea1", "\uFF61", 62],
      ["a1a1", "\u3000\u3001\u3002\uFF0C\uFF0E\u30FB\uFF1A\uFF1B\uFF1F\uFF01\u309B\u309C\xB4\uFF40\xA8\uFF3E\uFFE3\uFF3F\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\u2015\u2010\uFF0F\uFF3C\uFF5E\u2225\uFF5C\u2026\u2025\u2018\u2019\u201C\u201D\uFF08\uFF09\u3014\u3015\uFF3B\uFF3D\uFF5B\uFF5D\u3008", 9, "\uFF0B\uFF0D\xB1\xD7\xF7\uFF1D\u2260\uFF1C\uFF1E\u2266\u2267\u221E\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFFE5\uFF04\uFFE0\uFFE1\uFF05\uFF03\uFF06\uFF0A\uFF20\xA7\u2606\u2605\u25CB\u25CF\u25CE\u25C7"],
      ["a2a1", "\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u203B\u3012\u2192\u2190\u2191\u2193\u3013"],
      ["a2ba", "\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229"],
      ["a2ca", "\u2227\u2228\uFFE2\u21D2\u21D4\u2200\u2203"],
      ["a2dc", "\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C"],
      ["a2f2", "\u212B\u2030\u266F\u266D\u266A\u2020\u2021\xB6"],
      ["a2fe", "\u25EF"],
      ["a3b0", "\uFF10", 9],
      ["a3c1", "\uFF21", 25],
      ["a3e1", "\uFF41", 25],
      ["a4a1", "\u3041", 82],
      ["a5a1", "\u30A1", 85],
      ["a6a1", "\u0391", 16, "\u03A3", 6],
      ["a6c1", "\u03B1", 16, "\u03C3", 6],
      ["a7a1", "\u0410", 5, "\u0401\u0416", 25],
      ["a7d1", "\u0430", 5, "\u0451\u0436", 25],
      ["a8a1", "\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542"],
      ["ada1", "\u2460", 19, "\u2160", 9],
      ["adc0", "\u3349\u3314\u3322\u334D\u3318\u3327\u3303\u3336\u3351\u3357\u330D\u3326\u3323\u332B\u334A\u333B\u339C\u339D\u339E\u338E\u338F\u33C4\u33A1"],
      ["addf", "\u337B\u301D\u301F\u2116\u33CD\u2121\u32A4", 4, "\u3231\u3232\u3239\u337E\u337D\u337C\u2252\u2261\u222B\u222E\u2211\u221A\u22A5\u2220\u221F\u22BF\u2235\u2229\u222A"],
      ["b0a1", "\u4E9C\u5516\u5A03\u963F\u54C0\u611B\u6328\u59F6\u9022\u8475\u831C\u7A50\u60AA\u63E1\u6E25\u65ED\u8466\u82A6\u9BF5\u6893\u5727\u65A1\u6271\u5B9B\u59D0\u867B\u98F4\u7D62\u7DBE\u9B8E\u6216\u7C9F\u88B7\u5B89\u5EB5\u6309\u6697\u6848\u95C7\u978D\u674F\u4EE5\u4F0A\u4F4D\u4F9D\u5049\u56F2\u5937\u59D4\u5A01\u5C09\u60DF\u610F\u6170\u6613\u6905\u70BA\u754F\u7570\u79FB\u7DAD\u7DEF\u80C3\u840E\u8863\u8B02\u9055\u907A\u533B\u4E95\u4EA5\u57DF\u80B2\u90C1\u78EF\u4E00\u58F1\u6EA2\u9038\u7A32\u8328\u828B\u9C2F\u5141\u5370\u54BD\u54E1\u56E0\u59FB\u5F15\u98F2\u6DEB\u80E4\u852D"],
      ["b1a1", "\u9662\u9670\u96A0\u97FB\u540B\u53F3\u5B87\u70CF\u7FBD\u8FC2\u96E8\u536F\u9D5C\u7ABA\u4E11\u7893\u81FC\u6E26\u5618\u5504\u6B1D\u851A\u9C3B\u59E5\u53A9\u6D66\u74DC\u958F\u5642\u4E91\u904B\u96F2\u834F\u990C\u53E1\u55B6\u5B30\u5F71\u6620\u66F3\u6804\u6C38\u6CF3\u6D29\u745B\u76C8\u7A4E\u9834\u82F1\u885B\u8A60\u92ED\u6DB2\u75AB\u76CA\u99C5\u60A6\u8B01\u8D8A\u95B2\u698E\u53AD\u5186\u5712\u5830\u5944\u5BB4\u5EF6\u6028\u63A9\u63F4\u6CBF\u6F14\u708E\u7114\u7159\u71D5\u733F\u7E01\u8276\u82D1\u8597\u9060\u925B\u9D1B\u5869\u65BC\u6C5A\u7525\u51F9\u592E\u5965\u5F80\u5FDC"],
      ["b2a1", "\u62BC\u65FA\u6A2A\u6B27\u6BB4\u738B\u7FC1\u8956\u9D2C\u9D0E\u9EC4\u5CA1\u6C96\u837B\u5104\u5C4B\u61B6\u81C6\u6876\u7261\u4E59\u4FFA\u5378\u6069\u6E29\u7A4F\u97F3\u4E0B\u5316\u4EEE\u4F55\u4F3D\u4FA1\u4F73\u52A0\u53EF\u5609\u590F\u5AC1\u5BB6\u5BE1\u79D1\u6687\u679C\u67B6\u6B4C\u6CB3\u706B\u73C2\u798D\u79BE\u7A3C\u7B87\u82B1\u82DB\u8304\u8377\u83EF\u83D3\u8766\u8AB2\u5629\u8CA8\u8FE6\u904E\u971E\u868A\u4FC4\u5CE8\u6211\u7259\u753B\u81E5\u82BD\u86FE\u8CC0\u96C5\u9913\u99D5\u4ECB\u4F1A\u89E3\u56DE\u584A\u58CA\u5EFB\u5FEB\u602A\u6094\u6062\u61D0\u6212\u62D0\u6539"],
      ["b3a1", "\u9B41\u6666\u68B0\u6D77\u7070\u754C\u7686\u7D75\u82A5\u87F9\u958B\u968E\u8C9D\u51F1\u52BE\u5916\u54B3\u5BB3\u5D16\u6168\u6982\u6DAF\u788D\u84CB\u8857\u8A72\u93A7\u9AB8\u6D6C\u99A8\u86D9\u57A3\u67FF\u86CE\u920E\u5283\u5687\u5404\u5ED3\u62E1\u64B9\u683C\u6838\u6BBB\u7372\u78BA\u7A6B\u899A\u89D2\u8D6B\u8F03\u90ED\u95A3\u9694\u9769\u5B66\u5CB3\u697D\u984D\u984E\u639B\u7B20\u6A2B\u6A7F\u68B6\u9C0D\u6F5F\u5272\u559D\u6070\u62EC\u6D3B\u6E07\u6ED1\u845B\u8910\u8F44\u4E14\u9C39\u53F6\u691B\u6A3A\u9784\u682A\u515C\u7AC3\u84B2\u91DC\u938C\u565B\u9D28\u6822\u8305\u8431"],
      ["b4a1", "\u7CA5\u5208\u82C5\u74E6\u4E7E\u4F83\u51A0\u5BD2\u520A\u52D8\u52E7\u5DFB\u559A\u582A\u59E6\u5B8C\u5B98\u5BDB\u5E72\u5E79\u60A3\u611F\u6163\u61BE\u63DB\u6562\u67D1\u6853\u68FA\u6B3E\u6B53\u6C57\u6F22\u6F97\u6F45\u74B0\u7518\u76E3\u770B\u7AFF\u7BA1\u7C21\u7DE9\u7F36\u7FF0\u809D\u8266\u839E\u89B3\u8ACC\u8CAB\u9084\u9451\u9593\u9591\u95A2\u9665\u97D3\u9928\u8218\u4E38\u542B\u5CB8\u5DCC\u73A9\u764C\u773C\u5CA9\u7FEB\u8D0B\u96C1\u9811\u9854\u9858\u4F01\u4F0E\u5371\u559C\u5668\u57FA\u5947\u5B09\u5BC4\u5C90\u5E0C\u5E7E\u5FCC\u63EE\u673A\u65D7\u65E2\u671F\u68CB\u68C4"],
      ["b5a1", "\u6A5F\u5E30\u6BC5\u6C17\u6C7D\u757F\u7948\u5B63\u7A00\u7D00\u5FBD\u898F\u8A18\u8CB4\u8D77\u8ECC\u8F1D\u98E2\u9A0E\u9B3C\u4E80\u507D\u5100\u5993\u5B9C\u622F\u6280\u64EC\u6B3A\u72A0\u7591\u7947\u7FA9\u87FB\u8ABC\u8B70\u63AC\u83CA\u97A0\u5409\u5403\u55AB\u6854\u6A58\u8A70\u7827\u6775\u9ECD\u5374\u5BA2\u811A\u8650\u9006\u4E18\u4E45\u4EC7\u4F11\u53CA\u5438\u5BAE\u5F13\u6025\u6551\u673D\u6C42\u6C72\u6CE3\u7078\u7403\u7A76\u7AAE\u7B08\u7D1A\u7CFE\u7D66\u65E7\u725B\u53BB\u5C45\u5DE8\u62D2\u62E0\u6319\u6E20\u865A\u8A31\u8DDD\u92F8\u6F01\u79A6\u9B5A\u4EA8\u4EAB\u4EAC"],
      ["b6a1", "\u4F9B\u4FA0\u50D1\u5147\u7AF6\u5171\u51F6\u5354\u5321\u537F\u53EB\u55AC\u5883\u5CE1\u5F37\u5F4A\u602F\u6050\u606D\u631F\u6559\u6A4B\u6CC1\u72C2\u72ED\u77EF\u80F8\u8105\u8208\u854E\u90F7\u93E1\u97FF\u9957\u9A5A\u4EF0\u51DD\u5C2D\u6681\u696D\u5C40\u66F2\u6975\u7389\u6850\u7C81\u50C5\u52E4\u5747\u5DFE\u9326\u65A4\u6B23\u6B3D\u7434\u7981\u79BD\u7B4B\u7DCA\u82B9\u83CC\u887F\u895F\u8B39\u8FD1\u91D1\u541F\u9280\u4E5D\u5036\u53E5\u533A\u72D7\u7396\u77E9\u82E6\u8EAF\u99C6\u99C8\u99D2\u5177\u611A\u865E\u55B0\u7A7A\u5076\u5BD3\u9047\u9685\u4E32\u6ADB\u91E7\u5C51\u5C48"],
      ["b7a1", "\u6398\u7A9F\u6C93\u9774\u8F61\u7AAA\u718A\u9688\u7C82\u6817\u7E70\u6851\u936C\u52F2\u541B\u85AB\u8A13\u7FA4\u8ECD\u90E1\u5366\u8888\u7941\u4FC2\u50BE\u5211\u5144\u5553\u572D\u73EA\u578B\u5951\u5F62\u5F84\u6075\u6176\u6167\u61A9\u63B2\u643A\u656C\u666F\u6842\u6E13\u7566\u7A3D\u7CFB\u7D4C\u7D99\u7E4B\u7F6B\u830E\u834A\u86CD\u8A08\u8A63\u8B66\u8EFD\u981A\u9D8F\u82B8\u8FCE\u9BE8\u5287\u621F\u6483\u6FC0\u9699\u6841\u5091\u6B20\u6C7A\u6F54\u7A74\u7D50\u8840\u8A23\u6708\u4EF6\u5039\u5026\u5065\u517C\u5238\u5263\u55A7\u570F\u5805\u5ACC\u5EFA\u61B2\u61F8\u62F3\u6372"],
      ["b8a1", "\u691C\u6A29\u727D\u72AC\u732E\u7814\u786F\u7D79\u770C\u80A9\u898B\u8B19\u8CE2\u8ED2\u9063\u9375\u967A\u9855\u9A13\u9E78\u5143\u539F\u53B3\u5E7B\u5F26\u6E1B\u6E90\u7384\u73FE\u7D43\u8237\u8A00\u8AFA\u9650\u4E4E\u500B\u53E4\u547C\u56FA\u59D1\u5B64\u5DF1\u5EAB\u5F27\u6238\u6545\u67AF\u6E56\u72D0\u7CCA\u88B4\u80A1\u80E1\u83F0\u864E\u8A87\u8DE8\u9237\u96C7\u9867\u9F13\u4E94\u4E92\u4F0D\u5348\u5449\u543E\u5A2F\u5F8C\u5FA1\u609F\u68A7\u6A8E\u745A\u7881\u8A9E\u8AA4\u8B77\u9190\u4E5E\u9BC9\u4EA4\u4F7C\u4FAF\u5019\u5016\u5149\u516C\u529F\u52B9\u52FE\u539A\u53E3\u5411"],
      ["b9a1", "\u540E\u5589\u5751\u57A2\u597D\u5B54\u5B5D\u5B8F\u5DE5\u5DE7\u5DF7\u5E78\u5E83\u5E9A\u5EB7\u5F18\u6052\u614C\u6297\u62D8\u63A7\u653B\u6602\u6643\u66F4\u676D\u6821\u6897\u69CB\u6C5F\u6D2A\u6D69\u6E2F\u6E9D\u7532\u7687\u786C\u7A3F\u7CE0\u7D05\u7D18\u7D5E\u7DB1\u8015\u8003\u80AF\u80B1\u8154\u818F\u822A\u8352\u884C\u8861\u8B1B\u8CA2\u8CFC\u90CA\u9175\u9271\u783F\u92FC\u95A4\u964D\u9805\u9999\u9AD8\u9D3B\u525B\u52AB\u53F7\u5408\u58D5\u62F7\u6FE0\u8C6A\u8F5F\u9EB9\u514B\u523B\u544A\u56FD\u7A40\u9177\u9D60\u9ED2\u7344\u6F09\u8170\u7511\u5FFD\u60DA\u9AA8\u72DB\u8FBC"],
      ["baa1", "\u6B64\u9803\u4ECA\u56F0\u5764\u58BE\u5A5A\u6068\u61C7\u660F\u6606\u6839\u68B1\u6DF7\u75D5\u7D3A\u826E\u9B42\u4E9B\u4F50\u53C9\u5506\u5D6F\u5DE6\u5DEE\u67FB\u6C99\u7473\u7802\u8A50\u9396\u88DF\u5750\u5EA7\u632B\u50B5\u50AC\u518D\u6700\u54C9\u585E\u59BB\u5BB0\u5F69\u624D\u63A1\u683D\u6B73\u6E08\u707D\u91C7\u7280\u7815\u7826\u796D\u658E\u7D30\u83DC\u88C1\u8F09\u969B\u5264\u5728\u6750\u7F6A\u8CA1\u51B4\u5742\u962A\u583A\u698A\u80B4\u54B2\u5D0E\u57FC\u7895\u9DFA\u4F5C\u524A\u548B\u643E\u6628\u6714\u67F5\u7A84\u7B56\u7D22\u932F\u685C\u9BAD\u7B39\u5319\u518A\u5237"],
      ["bba1", "\u5BDF\u62F6\u64AE\u64E6\u672D\u6BBA\u85A9\u96D1\u7690\u9BD6\u634C\u9306\u9BAB\u76BF\u6652\u4E09\u5098\u53C2\u5C71\u60E8\u6492\u6563\u685F\u71E6\u73CA\u7523\u7B97\u7E82\u8695\u8B83\u8CDB\u9178\u9910\u65AC\u66AB\u6B8B\u4ED5\u4ED4\u4F3A\u4F7F\u523A\u53F8\u53F2\u55E3\u56DB\u58EB\u59CB\u59C9\u59FF\u5B50\u5C4D\u5E02\u5E2B\u5FD7\u601D\u6307\u652F\u5B5C\u65AF\u65BD\u65E8\u679D\u6B62\u6B7B\u6C0F\u7345\u7949\u79C1\u7CF8\u7D19\u7D2B\u80A2\u8102\u81F3\u8996\u8A5E\u8A69\u8A66\u8A8C\u8AEE\u8CC7\u8CDC\u96CC\u98FC\u6B6F\u4E8B\u4F3C\u4F8D\u5150\u5B57\u5BFA\u6148\u6301\u6642"],
      ["bca1", "\u6B21\u6ECB\u6CBB\u723E\u74BD\u75D4\u78C1\u793A\u800C\u8033\u81EA\u8494\u8F9E\u6C50\u9E7F\u5F0F\u8B58\u9D2B\u7AFA\u8EF8\u5B8D\u96EB\u4E03\u53F1\u57F7\u5931\u5AC9\u5BA4\u6089\u6E7F\u6F06\u75BE\u8CEA\u5B9F\u8500\u7BE0\u5072\u67F4\u829D\u5C61\u854A\u7E1E\u820E\u5199\u5C04\u6368\u8D66\u659C\u716E\u793E\u7D17\u8005\u8B1D\u8ECA\u906E\u86C7\u90AA\u501F\u52FA\u5C3A\u6753\u707C\u7235\u914C\u91C8\u932B\u82E5\u5BC2\u5F31\u60F9\u4E3B\u53D6\u5B88\u624B\u6731\u6B8A\u72E9\u73E0\u7A2E\u816B\u8DA3\u9152\u9996\u5112\u53D7\u546A\u5BFF\u6388\u6A39\u7DAC\u9700\u56DA\u53CE\u5468"],
      ["bda1", "\u5B97\u5C31\u5DDE\u4FEE\u6101\u62FE\u6D32\u79C0\u79CB\u7D42\u7E4D\u7FD2\u81ED\u821F\u8490\u8846\u8972\u8B90\u8E74\u8F2F\u9031\u914B\u916C\u96C6\u919C\u4EC0\u4F4F\u5145\u5341\u5F93\u620E\u67D4\u6C41\u6E0B\u7363\u7E26\u91CD\u9283\u53D4\u5919\u5BBF\u6DD1\u795D\u7E2E\u7C9B\u587E\u719F\u51FA\u8853\u8FF0\u4FCA\u5CFB\u6625\u77AC\u7AE3\u821C\u99FF\u51C6\u5FAA\u65EC\u696F\u6B89\u6DF3\u6E96\u6F64\u76FE\u7D14\u5DE1\u9075\u9187\u9806\u51E6\u521D\u6240\u6691\u66D9\u6E1A\u5EB6\u7DD2\u7F72\u66F8\u85AF\u85F7\u8AF8\u52A9\u53D9\u5973\u5E8F\u5F90\u6055\u92E4\u9664\u50B7\u511F"],
      ["bea1", "\u52DD\u5320\u5347\u53EC\u54E8\u5546\u5531\u5617\u5968\u59BE\u5A3C\u5BB5\u5C06\u5C0F\u5C11\u5C1A\u5E84\u5E8A\u5EE0\u5F70\u627F\u6284\u62DB\u638C\u6377\u6607\u660C\u662D\u6676\u677E\u68A2\u6A1F\u6A35\u6CBC\u6D88\u6E09\u6E58\u713C\u7126\u7167\u75C7\u7701\u785D\u7901\u7965\u79F0\u7AE0\u7B11\u7CA7\u7D39\u8096\u83D6\u848B\u8549\u885D\u88F3\u8A1F\u8A3C\u8A54\u8A73\u8C61\u8CDE\u91A4\u9266\u937E\u9418\u969C\u9798\u4E0A\u4E08\u4E1E\u4E57\u5197\u5270\u57CE\u5834\u58CC\u5B22\u5E38\u60C5\u64FE\u6761\u6756\u6D44\u72B6\u7573\u7A63\u84B8\u8B72\u91B8\u9320\u5631\u57F4\u98FE"],
      ["bfa1", "\u62ED\u690D\u6B96\u71ED\u7E54\u8077\u8272\u89E6\u98DF\u8755\u8FB1\u5C3B\u4F38\u4FE1\u4FB5\u5507\u5A20\u5BDD\u5BE9\u5FC3\u614E\u632F\u65B0\u664B\u68EE\u699B\u6D78\u6DF1\u7533\u75B9\u771F\u795E\u79E6\u7D33\u81E3\u82AF\u85AA\u89AA\u8A3A\u8EAB\u8F9B\u9032\u91DD\u9707\u4EBA\u4EC1\u5203\u5875\u58EC\u5C0B\u751A\u5C3D\u814E\u8A0A\u8FC5\u9663\u976D\u7B25\u8ACF\u9808\u9162\u56F3\u53A8\u9017\u5439\u5782\u5E25\u63A8\u6C34\u708A\u7761\u7C8B\u7FE0\u8870\u9042\u9154\u9310\u9318\u968F\u745E\u9AC4\u5D07\u5D69\u6570\u67A2\u8DA8\u96DB\u636E\u6749\u6919\u83C5\u9817\u96C0\u88FE"],
      ["c0a1", "\u6F84\u647A\u5BF8\u4E16\u702C\u755D\u662F\u51C4\u5236\u52E2\u59D3\u5F81\u6027\u6210\u653F\u6574\u661F\u6674\u68F2\u6816\u6B63\u6E05\u7272\u751F\u76DB\u7CBE\u8056\u58F0\u88FD\u897F\u8AA0\u8A93\u8ACB\u901D\u9192\u9752\u9759\u6589\u7A0E\u8106\u96BB\u5E2D\u60DC\u621A\u65A5\u6614\u6790\u77F3\u7A4D\u7C4D\u7E3E\u810A\u8CAC\u8D64\u8DE1\u8E5F\u78A9\u5207\u62D9\u63A5\u6442\u6298\u8A2D\u7A83\u7BC0\u8AAC\u96EA\u7D76\u820C\u8749\u4ED9\u5148\u5343\u5360\u5BA3\u5C02\u5C16\u5DDD\u6226\u6247\u64B0\u6813\u6834\u6CC9\u6D45\u6D17\u67D3\u6F5C\u714E\u717D\u65CB\u7A7F\u7BAD\u7DDA"],
      ["c1a1", "\u7E4A\u7FA8\u817A\u821B\u8239\u85A6\u8A6E\u8CCE\u8DF5\u9078\u9077\u92AD\u9291\u9583\u9BAE\u524D\u5584\u6F38\u7136\u5168\u7985\u7E55\u81B3\u7CCE\u564C\u5851\u5CA8\u63AA\u66FE\u66FD\u695A\u72D9\u758F\u758E\u790E\u7956\u79DF\u7C97\u7D20\u7D44\u8607\u8A34\u963B\u9061\u9F20\u50E7\u5275\u53CC\u53E2\u5009\u55AA\u58EE\u594F\u723D\u5B8B\u5C64\u531D\u60E3\u60F3\u635C\u6383\u633F\u63BB\u64CD\u65E9\u66F9\u5DE3\u69CD\u69FD\u6F15\u71E5\u4E89\u75E9\u76F8\u7A93\u7CDF\u7DCF\u7D9C\u8061\u8349\u8358\u846C\u84BC\u85FB\u88C5\u8D70\u9001\u906D\u9397\u971C\u9A12\u50CF\u5897\u618E"],
      ["c2a1", "\u81D3\u8535\u8D08\u9020\u4FC3\u5074\u5247\u5373\u606F\u6349\u675F\u6E2C\u8DB3\u901F\u4FD7\u5C5E\u8CCA\u65CF\u7D9A\u5352\u8896\u5176\u63C3\u5B58\u5B6B\u5C0A\u640D\u6751\u905C\u4ED6\u591A\u592A\u6C70\u8A51\u553E\u5815\u59A5\u60F0\u6253\u67C1\u8235\u6955\u9640\u99C4\u9A28\u4F53\u5806\u5BFE\u8010\u5CB1\u5E2F\u5F85\u6020\u614B\u6234\u66FF\u6CF0\u6EDE\u80CE\u817F\u82D4\u888B\u8CB8\u9000\u902E\u968A\u9EDB\u9BDB\u4EE3\u53F0\u5927\u7B2C\u918D\u984C\u9DF9\u6EDD\u7027\u5353\u5544\u5B85\u6258\u629E\u62D3\u6CA2\u6FEF\u7422\u8A17\u9438\u6FC1\u8AFE\u8338\u51E7\u86F8\u53EA"],
      ["c3a1", "\u53E9\u4F46\u9054\u8FB0\u596A\u8131\u5DFD\u7AEA\u8FBF\u68DA\u8C37\u72F8\u9C48\u6A3D\u8AB0\u4E39\u5358\u5606\u5766\u62C5\u63A2\u65E6\u6B4E\u6DE1\u6E5B\u70AD\u77ED\u7AEF\u7BAA\u7DBB\u803D\u80C6\u86CB\u8A95\u935B\u56E3\u58C7\u5F3E\u65AD\u6696\u6A80\u6BB5\u7537\u8AC7\u5024\u77E5\u5730\u5F1B\u6065\u667A\u6C60\u75F4\u7A1A\u7F6E\u81F4\u8718\u9045\u99B3\u7BC9\u755C\u7AF9\u7B51\u84C4\u9010\u79E9\u7A92\u8336\u5AE1\u7740\u4E2D\u4EF2\u5B99\u5FE0\u62BD\u663C\u67F1\u6CE8\u866B\u8877\u8A3B\u914E\u92F3\u99D0\u6A17\u7026\u732A\u82E7\u8457\u8CAF\u4E01\u5146\u51CB\u558B\u5BF5"],
      ["c4a1", "\u5E16\u5E33\u5E81\u5F14\u5F35\u5F6B\u5FB4\u61F2\u6311\u66A2\u671D\u6F6E\u7252\u753A\u773A\u8074\u8139\u8178\u8776\u8ABF\u8ADC\u8D85\u8DF3\u929A\u9577\u9802\u9CE5\u52C5\u6357\u76F4\u6715\u6C88\u73CD\u8CC3\u93AE\u9673\u6D25\u589C\u690E\u69CC\u8FFD\u939A\u75DB\u901A\u585A\u6802\u63B4\u69FB\u4F43\u6F2C\u67D8\u8FBB\u8526\u7DB4\u9354\u693F\u6F70\u576A\u58F7\u5B2C\u7D2C\u722A\u540A\u91E3\u9DB4\u4EAD\u4F4E\u505C\u5075\u5243\u8C9E\u5448\u5824\u5B9A\u5E1D\u5E95\u5EAD\u5EF7\u5F1F\u608C\u62B5\u633A\u63D0\u68AF\u6C40\u7887\u798E\u7A0B\u7DE0\u8247\u8A02\u8AE6\u8E44\u9013"],
      ["c5a1", "\u90B8\u912D\u91D8\u9F0E\u6CE5\u6458\u64E2\u6575\u6EF4\u7684\u7B1B\u9069\u93D1\u6EBA\u54F2\u5FB9\u64A4\u8F4D\u8FED\u9244\u5178\u586B\u5929\u5C55\u5E97\u6DFB\u7E8F\u751C\u8CBC\u8EE2\u985B\u70B9\u4F1D\u6BBF\u6FB1\u7530\u96FB\u514E\u5410\u5835\u5857\u59AC\u5C60\u5F92\u6597\u675C\u6E21\u767B\u83DF\u8CED\u9014\u90FD\u934D\u7825\u783A\u52AA\u5EA6\u571F\u5974\u6012\u5012\u515A\u51AC\u51CD\u5200\u5510\u5854\u5858\u5957\u5B95\u5CF6\u5D8B\u60BC\u6295\u642D\u6771\u6843\u68BC\u68DF\u76D7\u6DD8\u6E6F\u6D9B\u706F\u71C8\u5F53\u75D8\u7977\u7B49\u7B54\u7B52\u7CD6\u7D71\u5230"],
      ["c6a1", "\u8463\u8569\u85E4\u8A0E\u8B04\u8C46\u8E0F\u9003\u900F\u9419\u9676\u982D\u9A30\u95D8\u50CD\u52D5\u540C\u5802\u5C0E\u61A7\u649E\u6D1E\u77B3\u7AE5\u80F4\u8404\u9053\u9285\u5CE0\u9D07\u533F\u5F97\u5FB3\u6D9C\u7279\u7763\u79BF\u7BE4\u6BD2\u72EC\u8AAD\u6803\u6A61\u51F8\u7A81\u6934\u5C4A\u9CF6\u82EB\u5BC5\u9149\u701E\u5678\u5C6F\u60C7\u6566\u6C8C\u8C5A\u9041\u9813\u5451\u66C7\u920D\u5948\u90A3\u5185\u4E4D\u51EA\u8599\u8B0E\u7058\u637A\u934B\u6962\u99B4\u7E04\u7577\u5357\u6960\u8EDF\u96E3\u6C5D\u4E8C\u5C3C\u5F10\u8FE9\u5302\u8CD1\u8089\u8679\u5EFF\u65E5\u4E73\u5165"],
      ["c7a1", "\u5982\u5C3F\u97EE\u4EFB\u598A\u5FCD\u8A8D\u6FE1\u79B0\u7962\u5BE7\u8471\u732B\u71B1\u5E74\u5FF5\u637B\u649A\u71C3\u7C98\u4E43\u5EFC\u4E4B\u57DC\u56A2\u60A9\u6FC3\u7D0D\u80FD\u8133\u81BF\u8FB2\u8997\u86A4\u5DF4\u628A\u64AD\u8987\u6777\u6CE2\u6D3E\u7436\u7834\u5A46\u7F75\u82AD\u99AC\u4FF3\u5EC3\u62DD\u6392\u6557\u676F\u76C3\u724C\u80CC\u80BA\u8F29\u914D\u500D\u57F9\u5A92\u6885\u6973\u7164\u72FD\u8CB7\u58F2\u8CE0\u966A\u9019\u877F\u79E4\u77E7\u8429\u4F2F\u5265\u535A\u62CD\u67CF\u6CCA\u767D\u7B94\u7C95\u8236\u8584\u8FEB\u66DD\u6F20\u7206\u7E1B\u83AB\u99C1\u9EA6"],
      ["c8a1", "\u51FD\u7BB1\u7872\u7BB8\u8087\u7B48\u6AE8\u5E61\u808C\u7551\u7560\u516B\u9262\u6E8C\u767A\u9197\u9AEA\u4F10\u7F70\u629C\u7B4F\u95A5\u9CE9\u567A\u5859\u86E4\u96BC\u4F34\u5224\u534A\u53CD\u53DB\u5E06\u642C\u6591\u677F\u6C3E\u6C4E\u7248\u72AF\u73ED\u7554\u7E41\u822C\u85E9\u8CA9\u7BC4\u91C6\u7169\u9812\u98EF\u633D\u6669\u756A\u76E4\u78D0\u8543\u86EE\u532A\u5351\u5426\u5983\u5E87\u5F7C\u60B2\u6249\u6279\u62AB\u6590\u6BD4\u6CCC\u75B2\u76AE\u7891\u79D8\u7DCB\u7F77\u80A5\u88AB\u8AB9\u8CBB\u907F\u975E\u98DB\u6A0B\u7C38\u5099\u5C3E\u5FAE\u6787\u6BD8\u7435\u7709\u7F8E"],
      ["c9a1", "\u9F3B\u67CA\u7A17\u5339\u758B\u9AED\u5F66\u819D\u83F1\u8098\u5F3C\u5FC5\u7562\u7B46\u903C\u6867\u59EB\u5A9B\u7D10\u767E\u8B2C\u4FF5\u5F6A\u6A19\u6C37\u6F02\u74E2\u7968\u8868\u8A55\u8C79\u5EDF\u63CF\u75C5\u79D2\u82D7\u9328\u92F2\u849C\u86ED\u9C2D\u54C1\u5F6C\u658C\u6D5C\u7015\u8CA7\u8CD3\u983B\u654F\u74F6\u4E0D\u4ED8\u57E0\u592B\u5A66\u5BCC\u51A8\u5E03\u5E9C\u6016\u6276\u6577\u65A7\u666E\u6D6E\u7236\u7B26\u8150\u819A\u8299\u8B5C\u8CA0\u8CE6\u8D74\u961C\u9644\u4FAE\u64AB\u6B66\u821E\u8461\u856A\u90E8\u5C01\u6953\u98A8\u847A\u8557\u4F0F\u526F\u5FA9\u5E45\u670D"],
      ["caa1", "\u798F\u8179\u8907\u8986\u6DF5\u5F17\u6255\u6CB8\u4ECF\u7269\u9B92\u5206\u543B\u5674\u58B3\u61A4\u626E\u711A\u596E\u7C89\u7CDE\u7D1B\u96F0\u6587\u805E\u4E19\u4F75\u5175\u5840\u5E63\u5E73\u5F0A\u67C4\u4E26\u853D\u9589\u965B\u7C73\u9801\u50FB\u58C1\u7656\u78A7\u5225\u77A5\u8511\u7B86\u504F\u5909\u7247\u7BC7\u7DE8\u8FBA\u8FD4\u904D\u4FBF\u52C9\u5A29\u5F01\u97AD\u4FDD\u8217\u92EA\u5703\u6355\u6B69\u752B\u88DC\u8F14\u7A42\u52DF\u5893\u6155\u620A\u66AE\u6BCD\u7C3F\u83E9\u5023\u4FF8\u5305\u5446\u5831\u5949\u5B9D\u5CF0\u5CEF\u5D29\u5E96\u62B1\u6367\u653E\u65B9\u670B"],
      ["cba1", "\u6CD5\u6CE1\u70F9\u7832\u7E2B\u80DE\u82B3\u840C\u84EC\u8702\u8912\u8A2A\u8C4A\u90A6\u92D2\u98FD\u9CF3\u9D6C\u4E4F\u4EA1\u508D\u5256\u574A\u59A8\u5E3D\u5FD8\u5FD9\u623F\u66B4\u671B\u67D0\u68D2\u5192\u7D21\u80AA\u81A8\u8B00\u8C8C\u8CBF\u927E\u9632\u5420\u982C\u5317\u50D5\u535C\u58A8\u64B2\u6734\u7267\u7766\u7A46\u91E6\u52C3\u6CA1\u6B86\u5800\u5E4C\u5954\u672C\u7FFB\u51E1\u76C6\u6469\u78E8\u9B54\u9EBB\u57CB\u59B9\u6627\u679A\u6BCE\u54E9\u69D9\u5E55\u819C\u6795\u9BAA\u67FE\u9C52\u685D\u4EA6\u4FE3\u53C8\u62B9\u672B\u6CAB\u8FC4\u4FAD\u7E6D\u9EBF\u4E07\u6162\u6E80"],
      ["cca1", "\u6F2B\u8513\u5473\u672A\u9B45\u5DF3\u7B95\u5CAC\u5BC6\u871C\u6E4A\u84D1\u7A14\u8108\u5999\u7C8D\u6C11\u7720\u52D9\u5922\u7121\u725F\u77DB\u9727\u9D61\u690B\u5A7F\u5A18\u51A5\u540D\u547D\u660E\u76DF\u8FF7\u9298\u9CF4\u59EA\u725D\u6EC5\u514D\u68C9\u7DBF\u7DEC\u9762\u9EBA\u6478\u6A21\u8302\u5984\u5B5F\u6BDB\u731B\u76F2\u7DB2\u8017\u8499\u5132\u6728\u9ED9\u76EE\u6762\u52FF\u9905\u5C24\u623B\u7C7E\u8CB0\u554F\u60B6\u7D0B\u9580\u5301\u4E5F\u51B6\u591C\u723A\u8036\u91CE\u5F25\u77E2\u5384\u5F79\u7D04\u85AC\u8A33\u8E8D\u9756\u67F3\u85AE\u9453\u6109\u6108\u6CB9\u7652"],
      ["cda1", "\u8AED\u8F38\u552F\u4F51\u512A\u52C7\u53CB\u5BA5\u5E7D\u60A0\u6182\u63D6\u6709\u67DA\u6E67\u6D8C\u7336\u7337\u7531\u7950\u88D5\u8A98\u904A\u9091\u90F5\u96C4\u878D\u5915\u4E88\u4F59\u4E0E\u8A89\u8F3F\u9810\u50AD\u5E7C\u5996\u5BB9\u5EB8\u63DA\u63FA\u64C1\u66DC\u694A\u69D8\u6D0B\u6EB6\u7194\u7528\u7AAF\u7F8A\u8000\u8449\u84C9\u8981\u8B21\u8E0A\u9065\u967D\u990A\u617E\u6291\u6B32\u6C83\u6D74\u7FCC\u7FFC\u6DC0\u7F85\u87BA\u88F8\u6765\u83B1\u983C\u96F7\u6D1B\u7D61\u843D\u916A\u4E71\u5375\u5D50\u6B04\u6FEB\u85CD\u862D\u89A7\u5229\u540F\u5C65\u674E\u68A8\u7406\u7483"],
      ["cea1", "\u75E2\u88CF\u88E1\u91CC\u96E2\u9678\u5F8B\u7387\u7ACB\u844E\u63A0\u7565\u5289\u6D41\u6E9C\u7409\u7559\u786B\u7C92\u9686\u7ADC\u9F8D\u4FB6\u616E\u65C5\u865C\u4E86\u4EAE\u50DA\u4E21\u51CC\u5BEE\u6599\u6881\u6DBC\u731F\u7642\u77AD\u7A1C\u7CE7\u826F\u8AD2\u907C\u91CF\u9675\u9818\u529B\u7DD1\u502B\u5398\u6797\u6DCB\u71D0\u7433\u81E8\u8F2A\u96A3\u9C57\u9E9F\u7460\u5841\u6D99\u7D2F\u985E\u4EE4\u4F36\u4F8B\u51B7\u52B1\u5DBA\u601C\u73B2\u793C\u82D3\u9234\u96B7\u96F6\u970A\u9E97\u9F62\u66A6\u6B74\u5217\u52A3\u70C8\u88C2\u5EC9\u604B\u6190\u6F23\u7149\u7C3E\u7DF4\u806F"],
      ["cfa1", "\u84EE\u9023\u932C\u5442\u9B6F\u6AD3\u7089\u8CC2\u8DEF\u9732\u52B4\u5A41\u5ECA\u5F04\u6717\u697C\u6994\u6D6A\u6F0F\u7262\u72FC\u7BED\u8001\u807E\u874B\u90CE\u516D\u9E93\u7984\u808B\u9332\u8AD6\u502D\u548C\u8A71\u6B6A\u8CC4\u8107\u60D1\u67A0\u9DF2\u4E99\u4E98\u9C10\u8A6B\u85C1\u8568\u6900\u6E7E\u7897\u8155"],
      ["d0a1", "\u5F0C\u4E10\u4E15\u4E2A\u4E31\u4E36\u4E3C\u4E3F\u4E42\u4E56\u4E58\u4E82\u4E85\u8C6B\u4E8A\u8212\u5F0D\u4E8E\u4E9E\u4E9F\u4EA0\u4EA2\u4EB0\u4EB3\u4EB6\u4ECE\u4ECD\u4EC4\u4EC6\u4EC2\u4ED7\u4EDE\u4EED\u4EDF\u4EF7\u4F09\u4F5A\u4F30\u4F5B\u4F5D\u4F57\u4F47\u4F76\u4F88\u4F8F\u4F98\u4F7B\u4F69\u4F70\u4F91\u4F6F\u4F86\u4F96\u5118\u4FD4\u4FDF\u4FCE\u4FD8\u4FDB\u4FD1\u4FDA\u4FD0\u4FE4\u4FE5\u501A\u5028\u5014\u502A\u5025\u5005\u4F1C\u4FF6\u5021\u5029\u502C\u4FFE\u4FEF\u5011\u5006\u5043\u5047\u6703\u5055\u5050\u5048\u505A\u5056\u506C\u5078\u5080\u509A\u5085\u50B4\u50B2"],
      ["d1a1", "\u50C9\u50CA\u50B3\u50C2\u50D6\u50DE\u50E5\u50ED\u50E3\u50EE\u50F9\u50F5\u5109\u5101\u5102\u5116\u5115\u5114\u511A\u5121\u513A\u5137\u513C\u513B\u513F\u5140\u5152\u514C\u5154\u5162\u7AF8\u5169\u516A\u516E\u5180\u5182\u56D8\u518C\u5189\u518F\u5191\u5193\u5195\u5196\u51A4\u51A6\u51A2\u51A9\u51AA\u51AB\u51B3\u51B1\u51B2\u51B0\u51B5\u51BD\u51C5\u51C9\u51DB\u51E0\u8655\u51E9\u51ED\u51F0\u51F5\u51FE\u5204\u520B\u5214\u520E\u5227\u522A\u522E\u5233\u5239\u524F\u5244\u524B\u524C\u525E\u5254\u526A\u5274\u5269\u5273\u527F\u527D\u528D\u5294\u5292\u5271\u5288\u5291\u8FA8"],
      ["d2a1", "\u8FA7\u52AC\u52AD\u52BC\u52B5\u52C1\u52CD\u52D7\u52DE\u52E3\u52E6\u98ED\u52E0\u52F3\u52F5\u52F8\u52F9\u5306\u5308\u7538\u530D\u5310\u530F\u5315\u531A\u5323\u532F\u5331\u5333\u5338\u5340\u5346\u5345\u4E17\u5349\u534D\u51D6\u535E\u5369\u536E\u5918\u537B\u5377\u5382\u5396\u53A0\u53A6\u53A5\u53AE\u53B0\u53B6\u53C3\u7C12\u96D9\u53DF\u66FC\u71EE\u53EE\u53E8\u53ED\u53FA\u5401\u543D\u5440\u542C\u542D\u543C\u542E\u5436\u5429\u541D\u544E\u548F\u5475\u548E\u545F\u5471\u5477\u5470\u5492\u547B\u5480\u5476\u5484\u5490\u5486\u54C7\u54A2\u54B8\u54A5\u54AC\u54C4\u54C8\u54A8"],
      ["d3a1", "\u54AB\u54C2\u54A4\u54BE\u54BC\u54D8\u54E5\u54E6\u550F\u5514\u54FD\u54EE\u54ED\u54FA\u54E2\u5539\u5540\u5563\u554C\u552E\u555C\u5545\u5556\u5557\u5538\u5533\u555D\u5599\u5580\u54AF\u558A\u559F\u557B\u557E\u5598\u559E\u55AE\u557C\u5583\u55A9\u5587\u55A8\u55DA\u55C5\u55DF\u55C4\u55DC\u55E4\u55D4\u5614\u55F7\u5616\u55FE\u55FD\u561B\u55F9\u564E\u5650\u71DF\u5634\u5636\u5632\u5638\u566B\u5664\u562F\u566C\u566A\u5686\u5680\u568A\u56A0\u5694\u568F\u56A5\u56AE\u56B6\u56B4\u56C2\u56BC\u56C1\u56C3\u56C0\u56C8\u56CE\u56D1\u56D3\u56D7\u56EE\u56F9\u5700\u56FF\u5704\u5709"],
      ["d4a1", "\u5708\u570B\u570D\u5713\u5718\u5716\u55C7\u571C\u5726\u5737\u5738\u574E\u573B\u5740\u574F\u5769\u57C0\u5788\u5761\u577F\u5789\u5793\u57A0\u57B3\u57A4\u57AA\u57B0\u57C3\u57C6\u57D4\u57D2\u57D3\u580A\u57D6\u57E3\u580B\u5819\u581D\u5872\u5821\u5862\u584B\u5870\u6BC0\u5852\u583D\u5879\u5885\u58B9\u589F\u58AB\u58BA\u58DE\u58BB\u58B8\u58AE\u58C5\u58D3\u58D1\u58D7\u58D9\u58D8\u58E5\u58DC\u58E4\u58DF\u58EF\u58FA\u58F9\u58FB\u58FC\u58FD\u5902\u590A\u5910\u591B\u68A6\u5925\u592C\u592D\u5932\u5938\u593E\u7AD2\u5955\u5950\u594E\u595A\u5958\u5962\u5960\u5967\u596C\u5969"],
      ["d5a1", "\u5978\u5981\u599D\u4F5E\u4FAB\u59A3\u59B2\u59C6\u59E8\u59DC\u598D\u59D9\u59DA\u5A25\u5A1F\u5A11\u5A1C\u5A09\u5A1A\u5A40\u5A6C\u5A49\u5A35\u5A36\u5A62\u5A6A\u5A9A\u5ABC\u5ABE\u5ACB\u5AC2\u5ABD\u5AE3\u5AD7\u5AE6\u5AE9\u5AD6\u5AFA\u5AFB\u5B0C\u5B0B\u5B16\u5B32\u5AD0\u5B2A\u5B36\u5B3E\u5B43\u5B45\u5B40\u5B51\u5B55\u5B5A\u5B5B\u5B65\u5B69\u5B70\u5B73\u5B75\u5B78\u6588\u5B7A\u5B80\u5B83\u5BA6\u5BB8\u5BC3\u5BC7\u5BC9\u5BD4\u5BD0\u5BE4\u5BE6\u5BE2\u5BDE\u5BE5\u5BEB\u5BF0\u5BF6\u5BF3\u5C05\u5C07\u5C08\u5C0D\u5C13\u5C20\u5C22\u5C28\u5C38\u5C39\u5C41\u5C46\u5C4E\u5C53"],
      ["d6a1", "\u5C50\u5C4F\u5B71\u5C6C\u5C6E\u4E62\u5C76\u5C79\u5C8C\u5C91\u5C94\u599B\u5CAB\u5CBB\u5CB6\u5CBC\u5CB7\u5CC5\u5CBE\u5CC7\u5CD9\u5CE9\u5CFD\u5CFA\u5CED\u5D8C\u5CEA\u5D0B\u5D15\u5D17\u5D5C\u5D1F\u5D1B\u5D11\u5D14\u5D22\u5D1A\u5D19\u5D18\u5D4C\u5D52\u5D4E\u5D4B\u5D6C\u5D73\u5D76\u5D87\u5D84\u5D82\u5DA2\u5D9D\u5DAC\u5DAE\u5DBD\u5D90\u5DB7\u5DBC\u5DC9\u5DCD\u5DD3\u5DD2\u5DD6\u5DDB\u5DEB\u5DF2\u5DF5\u5E0B\u5E1A\u5E19\u5E11\u5E1B\u5E36\u5E37\u5E44\u5E43\u5E40\u5E4E\u5E57\u5E54\u5E5F\u5E62\u5E64\u5E47\u5E75\u5E76\u5E7A\u9EBC\u5E7F\u5EA0\u5EC1\u5EC2\u5EC8\u5ED0\u5ECF"],
      ["d7a1", "\u5ED6\u5EE3\u5EDD\u5EDA\u5EDB\u5EE2\u5EE1\u5EE8\u5EE9\u5EEC\u5EF1\u5EF3\u5EF0\u5EF4\u5EF8\u5EFE\u5F03\u5F09\u5F5D\u5F5C\u5F0B\u5F11\u5F16\u5F29\u5F2D\u5F38\u5F41\u5F48\u5F4C\u5F4E\u5F2F\u5F51\u5F56\u5F57\u5F59\u5F61\u5F6D\u5F73\u5F77\u5F83\u5F82\u5F7F\u5F8A\u5F88\u5F91\u5F87\u5F9E\u5F99\u5F98\u5FA0\u5FA8\u5FAD\u5FBC\u5FD6\u5FFB\u5FE4\u5FF8\u5FF1\u5FDD\u60B3\u5FFF\u6021\u6060\u6019\u6010\u6029\u600E\u6031\u601B\u6015\u602B\u6026\u600F\u603A\u605A\u6041\u606A\u6077\u605F\u604A\u6046\u604D\u6063\u6043\u6064\u6042\u606C\u606B\u6059\u6081\u608D\u60E7\u6083\u609A"],
      ["d8a1", "\u6084\u609B\u6096\u6097\u6092\u60A7\u608B\u60E1\u60B8\u60E0\u60D3\u60B4\u5FF0\u60BD\u60C6\u60B5\u60D8\u614D\u6115\u6106\u60F6\u60F7\u6100\u60F4\u60FA\u6103\u6121\u60FB\u60F1\u610D\u610E\u6147\u613E\u6128\u6127\u614A\u613F\u613C\u612C\u6134\u613D\u6142\u6144\u6173\u6177\u6158\u6159\u615A\u616B\u6174\u616F\u6165\u6171\u615F\u615D\u6153\u6175\u6199\u6196\u6187\u61AC\u6194\u619A\u618A\u6191\u61AB\u61AE\u61CC\u61CA\u61C9\u61F7\u61C8\u61C3\u61C6\u61BA\u61CB\u7F79\u61CD\u61E6\u61E3\u61F6\u61FA\u61F4\u61FF\u61FD\u61FC\u61FE\u6200\u6208\u6209\u620D\u620C\u6214\u621B"],
      ["d9a1", "\u621E\u6221\u622A\u622E\u6230\u6232\u6233\u6241\u624E\u625E\u6263\u625B\u6260\u6268\u627C\u6282\u6289\u627E\u6292\u6293\u6296\u62D4\u6283\u6294\u62D7\u62D1\u62BB\u62CF\u62FF\u62C6\u64D4\u62C8\u62DC\u62CC\u62CA\u62C2\u62C7\u629B\u62C9\u630C\u62EE\u62F1\u6327\u6302\u6308\u62EF\u62F5\u6350\u633E\u634D\u641C\u634F\u6396\u638E\u6380\u63AB\u6376\u63A3\u638F\u6389\u639F\u63B5\u636B\u6369\u63BE\u63E9\u63C0\u63C6\u63E3\u63C9\u63D2\u63F6\u63C4\u6416\u6434\u6406\u6413\u6426\u6436\u651D\u6417\u6428\u640F\u6467\u646F\u6476\u644E\u652A\u6495\u6493\u64A5\u64A9\u6488\u64BC"],
      ["daa1", "\u64DA\u64D2\u64C5\u64C7\u64BB\u64D8\u64C2\u64F1\u64E7\u8209\u64E0\u64E1\u62AC\u64E3\u64EF\u652C\u64F6\u64F4\u64F2\u64FA\u6500\u64FD\u6518\u651C\u6505\u6524\u6523\u652B\u6534\u6535\u6537\u6536\u6538\u754B\u6548\u6556\u6555\u654D\u6558\u655E\u655D\u6572\u6578\u6582\u6583\u8B8A\u659B\u659F\u65AB\u65B7\u65C3\u65C6\u65C1\u65C4\u65CC\u65D2\u65DB\u65D9\u65E0\u65E1\u65F1\u6772\u660A\u6603\u65FB\u6773\u6635\u6636\u6634\u661C\u664F\u6644\u6649\u6641\u665E\u665D\u6664\u6667\u6668\u665F\u6662\u6670\u6683\u6688\u668E\u6689\u6684\u6698\u669D\u66C1\u66B9\u66C9\u66BE\u66BC"],
      ["dba1", "\u66C4\u66B8\u66D6\u66DA\u66E0\u663F\u66E6\u66E9\u66F0\u66F5\u66F7\u670F\u6716\u671E\u6726\u6727\u9738\u672E\u673F\u6736\u6741\u6738\u6737\u6746\u675E\u6760\u6759\u6763\u6764\u6789\u6770\u67A9\u677C\u676A\u678C\u678B\u67A6\u67A1\u6785\u67B7\u67EF\u67B4\u67EC\u67B3\u67E9\u67B8\u67E4\u67DE\u67DD\u67E2\u67EE\u67B9\u67CE\u67C6\u67E7\u6A9C\u681E\u6846\u6829\u6840\u684D\u6832\u684E\u68B3\u682B\u6859\u6863\u6877\u687F\u689F\u688F\u68AD\u6894\u689D\u689B\u6883\u6AAE\u68B9\u6874\u68B5\u68A0\u68BA\u690F\u688D\u687E\u6901\u68CA\u6908\u68D8\u6922\u6926\u68E1\u690C\u68CD"],
      ["dca1", "\u68D4\u68E7\u68D5\u6936\u6912\u6904\u68D7\u68E3\u6925\u68F9\u68E0\u68EF\u6928\u692A\u691A\u6923\u6921\u68C6\u6979\u6977\u695C\u6978\u696B\u6954\u697E\u696E\u6939\u6974\u693D\u6959\u6930\u6961\u695E\u695D\u6981\u696A\u69B2\u69AE\u69D0\u69BF\u69C1\u69D3\u69BE\u69CE\u5BE8\u69CA\u69DD\u69BB\u69C3\u69A7\u6A2E\u6991\u69A0\u699C\u6995\u69B4\u69DE\u69E8\u6A02\u6A1B\u69FF\u6B0A\u69F9\u69F2\u69E7\u6A05\u69B1\u6A1E\u69ED\u6A14\u69EB\u6A0A\u6A12\u6AC1\u6A23\u6A13\u6A44\u6A0C\u6A72\u6A36\u6A78\u6A47\u6A62\u6A59\u6A66\u6A48\u6A38\u6A22\u6A90\u6A8D\u6AA0\u6A84\u6AA2\u6AA3"],
      ["dda1", "\u6A97\u8617\u6ABB\u6AC3\u6AC2\u6AB8\u6AB3\u6AAC\u6ADE\u6AD1\u6ADF\u6AAA\u6ADA\u6AEA\u6AFB\u6B05\u8616\u6AFA\u6B12\u6B16\u9B31\u6B1F\u6B38\u6B37\u76DC\u6B39\u98EE\u6B47\u6B43\u6B49\u6B50\u6B59\u6B54\u6B5B\u6B5F\u6B61\u6B78\u6B79\u6B7F\u6B80\u6B84\u6B83\u6B8D\u6B98\u6B95\u6B9E\u6BA4\u6BAA\u6BAB\u6BAF\u6BB2\u6BB1\u6BB3\u6BB7\u6BBC\u6BC6\u6BCB\u6BD3\u6BDF\u6BEC\u6BEB\u6BF3\u6BEF\u9EBE\u6C08\u6C13\u6C14\u6C1B\u6C24\u6C23\u6C5E\u6C55\u6C62\u6C6A\u6C82\u6C8D\u6C9A\u6C81\u6C9B\u6C7E\u6C68\u6C73\u6C92\u6C90\u6CC4\u6CF1\u6CD3\u6CBD\u6CD7\u6CC5\u6CDD\u6CAE\u6CB1\u6CBE"],
      ["dea1", "\u6CBA\u6CDB\u6CEF\u6CD9\u6CEA\u6D1F\u884D\u6D36\u6D2B\u6D3D\u6D38\u6D19\u6D35\u6D33\u6D12\u6D0C\u6D63\u6D93\u6D64\u6D5A\u6D79\u6D59\u6D8E\u6D95\u6FE4\u6D85\u6DF9\u6E15\u6E0A\u6DB5\u6DC7\u6DE6\u6DB8\u6DC6\u6DEC\u6DDE\u6DCC\u6DE8\u6DD2\u6DC5\u6DFA\u6DD9\u6DE4\u6DD5\u6DEA\u6DEE\u6E2D\u6E6E\u6E2E\u6E19\u6E72\u6E5F\u6E3E\u6E23\u6E6B\u6E2B\u6E76\u6E4D\u6E1F\u6E43\u6E3A\u6E4E\u6E24\u6EFF\u6E1D\u6E38\u6E82\u6EAA\u6E98\u6EC9\u6EB7\u6ED3\u6EBD\u6EAF\u6EC4\u6EB2\u6ED4\u6ED5\u6E8F\u6EA5\u6EC2\u6E9F\u6F41\u6F11\u704C\u6EEC\u6EF8\u6EFE\u6F3F\u6EF2\u6F31\u6EEF\u6F32\u6ECC"],
      ["dfa1", "\u6F3E\u6F13\u6EF7\u6F86\u6F7A\u6F78\u6F81\u6F80\u6F6F\u6F5B\u6FF3\u6F6D\u6F82\u6F7C\u6F58\u6F8E\u6F91\u6FC2\u6F66\u6FB3\u6FA3\u6FA1\u6FA4\u6FB9\u6FC6\u6FAA\u6FDF\u6FD5\u6FEC\u6FD4\u6FD8\u6FF1\u6FEE\u6FDB\u7009\u700B\u6FFA\u7011\u7001\u700F\u6FFE\u701B\u701A\u6F74\u701D\u7018\u701F\u7030\u703E\u7032\u7051\u7063\u7099\u7092\u70AF\u70F1\u70AC\u70B8\u70B3\u70AE\u70DF\u70CB\u70DD\u70D9\u7109\u70FD\u711C\u7119\u7165\u7155\u7188\u7166\u7162\u714C\u7156\u716C\u718F\u71FB\u7184\u7195\u71A8\u71AC\u71D7\u71B9\u71BE\u71D2\u71C9\u71D4\u71CE\u71E0\u71EC\u71E7\u71F5\u71FC"],
      ["e0a1", "\u71F9\u71FF\u720D\u7210\u721B\u7228\u722D\u722C\u7230\u7232\u723B\u723C\u723F\u7240\u7246\u724B\u7258\u7274\u727E\u7282\u7281\u7287\u7292\u7296\u72A2\u72A7\u72B9\u72B2\u72C3\u72C6\u72C4\u72CE\u72D2\u72E2\u72E0\u72E1\u72F9\u72F7\u500F\u7317\u730A\u731C\u7316\u731D\u7334\u732F\u7329\u7325\u733E\u734E\u734F\u9ED8\u7357\u736A\u7368\u7370\u7378\u7375\u737B\u737A\u73C8\u73B3\u73CE\u73BB\u73C0\u73E5\u73EE\u73DE\u74A2\u7405\u746F\u7425\u73F8\u7432\u743A\u7455\u743F\u745F\u7459\u7441\u745C\u7469\u7470\u7463\u746A\u7476\u747E\u748B\u749E\u74A7\u74CA\u74CF\u74D4\u73F1"],
      ["e1a1", "\u74E0\u74E3\u74E7\u74E9\u74EE\u74F2\u74F0\u74F1\u74F8\u74F7\u7504\u7503\u7505\u750C\u750E\u750D\u7515\u7513\u751E\u7526\u752C\u753C\u7544\u754D\u754A\u7549\u755B\u7546\u755A\u7569\u7564\u7567\u756B\u756D\u7578\u7576\u7586\u7587\u7574\u758A\u7589\u7582\u7594\u759A\u759D\u75A5\u75A3\u75C2\u75B3\u75C3\u75B5\u75BD\u75B8\u75BC\u75B1\u75CD\u75CA\u75D2\u75D9\u75E3\u75DE\u75FE\u75FF\u75FC\u7601\u75F0\u75FA\u75F2\u75F3\u760B\u760D\u7609\u761F\u7627\u7620\u7621\u7622\u7624\u7634\u7630\u763B\u7647\u7648\u7646\u765C\u7658\u7661\u7662\u7668\u7669\u766A\u7667\u766C\u7670"],
      ["e2a1", "\u7672\u7676\u7678\u767C\u7680\u7683\u7688\u768B\u768E\u7696\u7693\u7699\u769A\u76B0\u76B4\u76B8\u76B9\u76BA\u76C2\u76CD\u76D6\u76D2\u76DE\u76E1\u76E5\u76E7\u76EA\u862F\u76FB\u7708\u7707\u7704\u7729\u7724\u771E\u7725\u7726\u771B\u7737\u7738\u7747\u775A\u7768\u776B\u775B\u7765\u777F\u777E\u7779\u778E\u778B\u7791\u77A0\u779E\u77B0\u77B6\u77B9\u77BF\u77BC\u77BD\u77BB\u77C7\u77CD\u77D7\u77DA\u77DC\u77E3\u77EE\u77FC\u780C\u7812\u7926\u7820\u792A\u7845\u788E\u7874\u7886\u787C\u789A\u788C\u78A3\u78B5\u78AA\u78AF\u78D1\u78C6\u78CB\u78D4\u78BE\u78BC\u78C5\u78CA\u78EC"],
      ["e3a1", "\u78E7\u78DA\u78FD\u78F4\u7907\u7912\u7911\u7919\u792C\u792B\u7940\u7960\u7957\u795F\u795A\u7955\u7953\u797A\u797F\u798A\u799D\u79A7\u9F4B\u79AA\u79AE\u79B3\u79B9\u79BA\u79C9\u79D5\u79E7\u79EC\u79E1\u79E3\u7A08\u7A0D\u7A18\u7A19\u7A20\u7A1F\u7980\u7A31\u7A3B\u7A3E\u7A37\u7A43\u7A57\u7A49\u7A61\u7A62\u7A69\u9F9D\u7A70\u7A79\u7A7D\u7A88\u7A97\u7A95\u7A98\u7A96\u7AA9\u7AC8\u7AB0\u7AB6\u7AC5\u7AC4\u7ABF\u9083\u7AC7\u7ACA\u7ACD\u7ACF\u7AD5\u7AD3\u7AD9\u7ADA\u7ADD\u7AE1\u7AE2\u7AE6\u7AED\u7AF0\u7B02\u7B0F\u7B0A\u7B06\u7B33\u7B18\u7B19\u7B1E\u7B35\u7B28\u7B36\u7B50"],
      ["e4a1", "\u7B7A\u7B04\u7B4D\u7B0B\u7B4C\u7B45\u7B75\u7B65\u7B74\u7B67\u7B70\u7B71\u7B6C\u7B6E\u7B9D\u7B98\u7B9F\u7B8D\u7B9C\u7B9A\u7B8B\u7B92\u7B8F\u7B5D\u7B99\u7BCB\u7BC1\u7BCC\u7BCF\u7BB4\u7BC6\u7BDD\u7BE9\u7C11\u7C14\u7BE6\u7BE5\u7C60\u7C00\u7C07\u7C13\u7BF3\u7BF7\u7C17\u7C0D\u7BF6\u7C23\u7C27\u7C2A\u7C1F\u7C37\u7C2B\u7C3D\u7C4C\u7C43\u7C54\u7C4F\u7C40\u7C50\u7C58\u7C5F\u7C64\u7C56\u7C65\u7C6C\u7C75\u7C83\u7C90\u7CA4\u7CAD\u7CA2\u7CAB\u7CA1\u7CA8\u7CB3\u7CB2\u7CB1\u7CAE\u7CB9\u7CBD\u7CC0\u7CC5\u7CC2\u7CD8\u7CD2\u7CDC\u7CE2\u9B3B\u7CEF\u7CF2\u7CF4\u7CF6\u7CFA\u7D06"],
      ["e5a1", "\u7D02\u7D1C\u7D15\u7D0A\u7D45\u7D4B\u7D2E\u7D32\u7D3F\u7D35\u7D46\u7D73\u7D56\u7D4E\u7D72\u7D68\u7D6E\u7D4F\u7D63\u7D93\u7D89\u7D5B\u7D8F\u7D7D\u7D9B\u7DBA\u7DAE\u7DA3\u7DB5\u7DC7\u7DBD\u7DAB\u7E3D\u7DA2\u7DAF\u7DDC\u7DB8\u7D9F\u7DB0\u7DD8\u7DDD\u7DE4\u7DDE\u7DFB\u7DF2\u7DE1\u7E05\u7E0A\u7E23\u7E21\u7E12\u7E31\u7E1F\u7E09\u7E0B\u7E22\u7E46\u7E66\u7E3B\u7E35\u7E39\u7E43\u7E37\u7E32\u7E3A\u7E67\u7E5D\u7E56\u7E5E\u7E59\u7E5A\u7E79\u7E6A\u7E69\u7E7C\u7E7B\u7E83\u7DD5\u7E7D\u8FAE\u7E7F\u7E88\u7E89\u7E8C\u7E92\u7E90\u7E93\u7E94\u7E96\u7E8E\u7E9B\u7E9C\u7F38\u7F3A"],
      ["e6a1", "\u7F45\u7F4C\u7F4D\u7F4E\u7F50\u7F51\u7F55\u7F54\u7F58\u7F5F\u7F60\u7F68\u7F69\u7F67\u7F78\u7F82\u7F86\u7F83\u7F88\u7F87\u7F8C\u7F94\u7F9E\u7F9D\u7F9A\u7FA3\u7FAF\u7FB2\u7FB9\u7FAE\u7FB6\u7FB8\u8B71\u7FC5\u7FC6\u7FCA\u7FD5\u7FD4\u7FE1\u7FE6\u7FE9\u7FF3\u7FF9\u98DC\u8006\u8004\u800B\u8012\u8018\u8019\u801C\u8021\u8028\u803F\u803B\u804A\u8046\u8052\u8058\u805A\u805F\u8062\u8068\u8073\u8072\u8070\u8076\u8079\u807D\u807F\u8084\u8086\u8085\u809B\u8093\u809A\u80AD\u5190\u80AC\u80DB\u80E5\u80D9\u80DD\u80C4\u80DA\u80D6\u8109\u80EF\u80F1\u811B\u8129\u8123\u812F\u814B"],
      ["e7a1", "\u968B\u8146\u813E\u8153\u8151\u80FC\u8171\u816E\u8165\u8166\u8174\u8183\u8188\u818A\u8180\u8182\u81A0\u8195\u81A4\u81A3\u815F\u8193\u81A9\u81B0\u81B5\u81BE\u81B8\u81BD\u81C0\u81C2\u81BA\u81C9\u81CD\u81D1\u81D9\u81D8\u81C8\u81DA\u81DF\u81E0\u81E7\u81FA\u81FB\u81FE\u8201\u8202\u8205\u8207\u820A\u820D\u8210\u8216\u8229\u822B\u8238\u8233\u8240\u8259\u8258\u825D\u825A\u825F\u8264\u8262\u8268\u826A\u826B\u822E\u8271\u8277\u8278\u827E\u828D\u8292\u82AB\u829F\u82BB\u82AC\u82E1\u82E3\u82DF\u82D2\u82F4\u82F3\u82FA\u8393\u8303\u82FB\u82F9\u82DE\u8306\u82DC\u8309\u82D9"],
      ["e8a1", "\u8335\u8334\u8316\u8332\u8331\u8340\u8339\u8350\u8345\u832F\u832B\u8317\u8318\u8385\u839A\u83AA\u839F\u83A2\u8396\u8323\u838E\u8387\u838A\u837C\u83B5\u8373\u8375\u83A0\u8389\u83A8\u83F4\u8413\u83EB\u83CE\u83FD\u8403\u83D8\u840B\u83C1\u83F7\u8407\u83E0\u83F2\u840D\u8422\u8420\u83BD\u8438\u8506\u83FB\u846D\u842A\u843C\u855A\u8484\u8477\u846B\u84AD\u846E\u8482\u8469\u8446\u842C\u846F\u8479\u8435\u84CA\u8462\u84B9\u84BF\u849F\u84D9\u84CD\u84BB\u84DA\u84D0\u84C1\u84C6\u84D6\u84A1\u8521\u84FF\u84F4\u8517\u8518\u852C\u851F\u8515\u8514\u84FC\u8540\u8563\u8558\u8548"],
      ["e9a1", "\u8541\u8602\u854B\u8555\u8580\u85A4\u8588\u8591\u858A\u85A8\u856D\u8594\u859B\u85EA\u8587\u859C\u8577\u857E\u8590\u85C9\u85BA\u85CF\u85B9\u85D0\u85D5\u85DD\u85E5\u85DC\u85F9\u860A\u8613\u860B\u85FE\u85FA\u8606\u8622\u861A\u8630\u863F\u864D\u4E55\u8654\u865F\u8667\u8671\u8693\u86A3\u86A9\u86AA\u868B\u868C\u86B6\u86AF\u86C4\u86C6\u86B0\u86C9\u8823\u86AB\u86D4\u86DE\u86E9\u86EC\u86DF\u86DB\u86EF\u8712\u8706\u8708\u8700\u8703\u86FB\u8711\u8709\u870D\u86F9\u870A\u8734\u873F\u8737\u873B\u8725\u8729\u871A\u8760\u875F\u8778\u874C\u874E\u8774\u8757\u8768\u876E\u8759"],
      ["eaa1", "\u8753\u8763\u876A\u8805\u87A2\u879F\u8782\u87AF\u87CB\u87BD\u87C0\u87D0\u96D6\u87AB\u87C4\u87B3\u87C7\u87C6\u87BB\u87EF\u87F2\u87E0\u880F\u880D\u87FE\u87F6\u87F7\u880E\u87D2\u8811\u8816\u8815\u8822\u8821\u8831\u8836\u8839\u8827\u883B\u8844\u8842\u8852\u8859\u885E\u8862\u886B\u8881\u887E\u889E\u8875\u887D\u88B5\u8872\u8882\u8897\u8892\u88AE\u8899\u88A2\u888D\u88A4\u88B0\u88BF\u88B1\u88C3\u88C4\u88D4\u88D8\u88D9\u88DD\u88F9\u8902\u88FC\u88F4\u88E8\u88F2\u8904\u890C\u890A\u8913\u8943\u891E\u8925\u892A\u892B\u8941\u8944\u893B\u8936\u8938\u894C\u891D\u8960\u895E"],
      ["eba1", "\u8966\u8964\u896D\u896A\u896F\u8974\u8977\u897E\u8983\u8988\u898A\u8993\u8998\u89A1\u89A9\u89A6\u89AC\u89AF\u89B2\u89BA\u89BD\u89BF\u89C0\u89DA\u89DC\u89DD\u89E7\u89F4\u89F8\u8A03\u8A16\u8A10\u8A0C\u8A1B\u8A1D\u8A25\u8A36\u8A41\u8A5B\u8A52\u8A46\u8A48\u8A7C\u8A6D\u8A6C\u8A62\u8A85\u8A82\u8A84\u8AA8\u8AA1\u8A91\u8AA5\u8AA6\u8A9A\u8AA3\u8AC4\u8ACD\u8AC2\u8ADA\u8AEB\u8AF3\u8AE7\u8AE4\u8AF1\u8B14\u8AE0\u8AE2\u8AF7\u8ADE\u8ADB\u8B0C\u8B07\u8B1A\u8AE1\u8B16\u8B10\u8B17\u8B20\u8B33\u97AB\u8B26\u8B2B\u8B3E\u8B28\u8B41\u8B4C\u8B4F\u8B4E\u8B49\u8B56\u8B5B\u8B5A\u8B6B"],
      ["eca1", "\u8B5F\u8B6C\u8B6F\u8B74\u8B7D\u8B80\u8B8C\u8B8E\u8B92\u8B93\u8B96\u8B99\u8B9A\u8C3A\u8C41\u8C3F\u8C48\u8C4C\u8C4E\u8C50\u8C55\u8C62\u8C6C\u8C78\u8C7A\u8C82\u8C89\u8C85\u8C8A\u8C8D\u8C8E\u8C94\u8C7C\u8C98\u621D\u8CAD\u8CAA\u8CBD\u8CB2\u8CB3\u8CAE\u8CB6\u8CC8\u8CC1\u8CE4\u8CE3\u8CDA\u8CFD\u8CFA\u8CFB\u8D04\u8D05\u8D0A\u8D07\u8D0F\u8D0D\u8D10\u9F4E\u8D13\u8CCD\u8D14\u8D16\u8D67\u8D6D\u8D71\u8D73\u8D81\u8D99\u8DC2\u8DBE\u8DBA\u8DCF\u8DDA\u8DD6\u8DCC\u8DDB\u8DCB\u8DEA\u8DEB\u8DDF\u8DE3\u8DFC\u8E08\u8E09\u8DFF\u8E1D\u8E1E\u8E10\u8E1F\u8E42\u8E35\u8E30\u8E34\u8E4A"],
      ["eda1", "\u8E47\u8E49\u8E4C\u8E50\u8E48\u8E59\u8E64\u8E60\u8E2A\u8E63\u8E55\u8E76\u8E72\u8E7C\u8E81\u8E87\u8E85\u8E84\u8E8B\u8E8A\u8E93\u8E91\u8E94\u8E99\u8EAA\u8EA1\u8EAC\u8EB0\u8EC6\u8EB1\u8EBE\u8EC5\u8EC8\u8ECB\u8EDB\u8EE3\u8EFC\u8EFB\u8EEB\u8EFE\u8F0A\u8F05\u8F15\u8F12\u8F19\u8F13\u8F1C\u8F1F\u8F1B\u8F0C\u8F26\u8F33\u8F3B\u8F39\u8F45\u8F42\u8F3E\u8F4C\u8F49\u8F46\u8F4E\u8F57\u8F5C\u8F62\u8F63\u8F64\u8F9C\u8F9F\u8FA3\u8FAD\u8FAF\u8FB7\u8FDA\u8FE5\u8FE2\u8FEA\u8FEF\u9087\u8FF4\u9005\u8FF9\u8FFA\u9011\u9015\u9021\u900D\u901E\u9016\u900B\u9027\u9036\u9035\u9039\u8FF8"],
      ["eea1", "\u904F\u9050\u9051\u9052\u900E\u9049\u903E\u9056\u9058\u905E\u9068\u906F\u9076\u96A8\u9072\u9082\u907D\u9081\u9080\u908A\u9089\u908F\u90A8\u90AF\u90B1\u90B5\u90E2\u90E4\u6248\u90DB\u9102\u9112\u9119\u9132\u9130\u914A\u9156\u9158\u9163\u9165\u9169\u9173\u9172\u918B\u9189\u9182\u91A2\u91AB\u91AF\u91AA\u91B5\u91B4\u91BA\u91C0\u91C1\u91C9\u91CB\u91D0\u91D6\u91DF\u91E1\u91DB\u91FC\u91F5\u91F6\u921E\u91FF\u9214\u922C\u9215\u9211\u925E\u9257\u9245\u9249\u9264\u9248\u9295\u923F\u924B\u9250\u929C\u9296\u9293\u929B\u925A\u92CF\u92B9\u92B7\u92E9\u930F\u92FA\u9344\u932E"],
      ["efa1", "\u9319\u9322\u931A\u9323\u933A\u9335\u933B\u935C\u9360\u937C\u936E\u9356\u93B0\u93AC\u93AD\u9394\u93B9\u93D6\u93D7\u93E8\u93E5\u93D8\u93C3\u93DD\u93D0\u93C8\u93E4\u941A\u9414\u9413\u9403\u9407\u9410\u9436\u942B\u9435\u9421\u943A\u9441\u9452\u9444\u945B\u9460\u9462\u945E\u946A\u9229\u9470\u9475\u9477\u947D\u945A\u947C\u947E\u9481\u947F\u9582\u9587\u958A\u9594\u9596\u9598\u9599\u95A0\u95A8\u95A7\u95AD\u95BC\u95BB\u95B9\u95BE\u95CA\u6FF6\u95C3\u95CD\u95CC\u95D5\u95D4\u95D6\u95DC\u95E1\u95E5\u95E2\u9621\u9628\u962E\u962F\u9642\u964C\u964F\u964B\u9677\u965C\u965E"],
      ["f0a1", "\u965D\u965F\u9666\u9672\u966C\u968D\u9698\u9695\u9697\u96AA\u96A7\u96B1\u96B2\u96B0\u96B4\u96B6\u96B8\u96B9\u96CE\u96CB\u96C9\u96CD\u894D\u96DC\u970D\u96D5\u96F9\u9704\u9706\u9708\u9713\u970E\u9711\u970F\u9716\u9719\u9724\u972A\u9730\u9739\u973D\u973E\u9744\u9746\u9748\u9742\u9749\u975C\u9760\u9764\u9766\u9768\u52D2\u976B\u9771\u9779\u9785\u977C\u9781\u977A\u9786\u978B\u978F\u9790\u979C\u97A8\u97A6\u97A3\u97B3\u97B4\u97C3\u97C6\u97C8\u97CB\u97DC\u97ED\u9F4F\u97F2\u7ADF\u97F6\u97F5\u980F\u980C\u9838\u9824\u9821\u9837\u983D\u9846\u984F\u984B\u986B\u986F\u9870"],
      ["f1a1", "\u9871\u9874\u9873\u98AA\u98AF\u98B1\u98B6\u98C4\u98C3\u98C6\u98E9\u98EB\u9903\u9909\u9912\u9914\u9918\u9921\u991D\u991E\u9924\u9920\u992C\u992E\u993D\u993E\u9942\u9949\u9945\u9950\u994B\u9951\u9952\u994C\u9955\u9997\u9998\u99A5\u99AD\u99AE\u99BC\u99DF\u99DB\u99DD\u99D8\u99D1\u99ED\u99EE\u99F1\u99F2\u99FB\u99F8\u9A01\u9A0F\u9A05\u99E2\u9A19\u9A2B\u9A37\u9A45\u9A42\u9A40\u9A43\u9A3E\u9A55\u9A4D\u9A5B\u9A57\u9A5F\u9A62\u9A65\u9A64\u9A69\u9A6B\u9A6A\u9AAD\u9AB0\u9ABC\u9AC0\u9ACF\u9AD1\u9AD3\u9AD4\u9ADE\u9ADF\u9AE2\u9AE3\u9AE6\u9AEF\u9AEB\u9AEE\u9AF4\u9AF1\u9AF7"],
      ["f2a1", "\u9AFB\u9B06\u9B18\u9B1A\u9B1F\u9B22\u9B23\u9B25\u9B27\u9B28\u9B29\u9B2A\u9B2E\u9B2F\u9B32\u9B44\u9B43\u9B4F\u9B4D\u9B4E\u9B51\u9B58\u9B74\u9B93\u9B83\u9B91\u9B96\u9B97\u9B9F\u9BA0\u9BA8\u9BB4\u9BC0\u9BCA\u9BB9\u9BC6\u9BCF\u9BD1\u9BD2\u9BE3\u9BE2\u9BE4\u9BD4\u9BE1\u9C3A\u9BF2\u9BF1\u9BF0\u9C15\u9C14\u9C09\u9C13\u9C0C\u9C06\u9C08\u9C12\u9C0A\u9C04\u9C2E\u9C1B\u9C25\u9C24\u9C21\u9C30\u9C47\u9C32\u9C46\u9C3E\u9C5A\u9C60\u9C67\u9C76\u9C78\u9CE7\u9CEC\u9CF0\u9D09\u9D08\u9CEB\u9D03\u9D06\u9D2A\u9D26\u9DAF\u9D23\u9D1F\u9D44\u9D15\u9D12\u9D41\u9D3F\u9D3E\u9D46\u9D48"],
      ["f3a1", "\u9D5D\u9D5E\u9D64\u9D51\u9D50\u9D59\u9D72\u9D89\u9D87\u9DAB\u9D6F\u9D7A\u9D9A\u9DA4\u9DA9\u9DB2\u9DC4\u9DC1\u9DBB\u9DB8\u9DBA\u9DC6\u9DCF\u9DC2\u9DD9\u9DD3\u9DF8\u9DE6\u9DED\u9DEF\u9DFD\u9E1A\u9E1B\u9E1E\u9E75\u9E79\u9E7D\u9E81\u9E88\u9E8B\u9E8C\u9E92\u9E95\u9E91\u9E9D\u9EA5\u9EA9\u9EB8\u9EAA\u9EAD\u9761\u9ECC\u9ECE\u9ECF\u9ED0\u9ED4\u9EDC\u9EDE\u9EDD\u9EE0\u9EE5\u9EE8\u9EEF\u9EF4\u9EF6\u9EF7\u9EF9\u9EFB\u9EFC\u9EFD\u9F07\u9F08\u76B7\u9F15\u9F21\u9F2C\u9F3E\u9F4A\u9F52\u9F54\u9F63\u9F5F\u9F60\u9F61\u9F66\u9F67\u9F6C\u9F6A\u9F77\u9F72\u9F76\u9F95\u9F9C\u9FA0"],
      ["f4a1", "\u582F\u69C7\u9059\u7464\u51DC\u7199"],
      ["f9a1", "\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A\u5164\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F\uFA10\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7"],
      ["faa1", "\u5FDE\u605D\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1"],
      ["fba1", "\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19\uFA1A\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559\u856B\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115\u9127\u91DA"],
      ["fca1", "\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"],
      ["fcf1", "\u2170", 9, "\uFFE2\uFFE4\uFF07\uFF02"],
      ["8fa2af", "\u02D8\u02C7\xB8\u02D9\u02DD\xAF\u02DB\u02DA\uFF5E\u0384\u0385"],
      ["8fa2c2", "\xA1\xA6\xBF"],
      ["8fa2eb", "\xBA\xAA\xA9\xAE\u2122\xA4\u2116"],
      ["8fa6e1", "\u0386\u0388\u0389\u038A\u03AA"],
      ["8fa6e7", "\u038C"],
      ["8fa6e9", "\u038E\u03AB"],
      ["8fa6ec", "\u038F"],
      ["8fa6f1", "\u03AC\u03AD\u03AE\u03AF\u03CA\u0390\u03CC\u03C2\u03CD\u03CB\u03B0\u03CE"],
      ["8fa7c2", "\u0402", 10, "\u040E\u040F"],
      ["8fa7f2", "\u0452", 10, "\u045E\u045F"],
      ["8fa9a1", "\xC6\u0110"],
      ["8fa9a4", "\u0126"],
      ["8fa9a6", "\u0132"],
      ["8fa9a8", "\u0141\u013F"],
      ["8fa9ab", "\u014A\xD8\u0152"],
      ["8fa9af", "\u0166\xDE"],
      ["8fa9c1", "\xE6\u0111\xF0\u0127\u0131\u0133\u0138\u0142\u0140\u0149\u014B\xF8\u0153\xDF\u0167\xFE"],
      ["8faaa1", "\xC1\xC0\xC4\xC2\u0102\u01CD\u0100\u0104\xC5\xC3\u0106\u0108\u010C\xC7\u010A\u010E\xC9\xC8\xCB\xCA\u011A\u0116\u0112\u0118"],
      ["8faaba", "\u011C\u011E\u0122\u0120\u0124\xCD\xCC\xCF\xCE\u01CF\u0130\u012A\u012E\u0128\u0134\u0136\u0139\u013D\u013B\u0143\u0147\u0145\xD1\xD3\xD2\xD6\xD4\u01D1\u0150\u014C\xD5\u0154\u0158\u0156\u015A\u015C\u0160\u015E\u0164\u0162\xDA\xD9\xDC\xDB\u016C\u01D3\u0170\u016A\u0172\u016E\u0168\u01D7\u01DB\u01D9\u01D5\u0174\xDD\u0178\u0176\u0179\u017D\u017B"],
      ["8faba1", "\xE1\xE0\xE4\xE2\u0103\u01CE\u0101\u0105\xE5\xE3\u0107\u0109\u010D\xE7\u010B\u010F\xE9\xE8\xEB\xEA\u011B\u0117\u0113\u0119\u01F5\u011D\u011F"],
      ["8fabbd", "\u0121\u0125\xED\xEC\xEF\xEE\u01D0"],
      ["8fabc5", "\u012B\u012F\u0129\u0135\u0137\u013A\u013E\u013C\u0144\u0148\u0146\xF1\xF3\xF2\xF6\xF4\u01D2\u0151\u014D\xF5\u0155\u0159\u0157\u015B\u015D\u0161\u015F\u0165\u0163\xFA\xF9\xFC\xFB\u016D\u01D4\u0171\u016B\u0173\u016F\u0169\u01D8\u01DC\u01DA\u01D6\u0175\xFD\xFF\u0177\u017A\u017E\u017C"],
      ["8fb0a1", "\u4E02\u4E04\u4E05\u4E0C\u4E12\u4E1F\u4E23\u4E24\u4E28\u4E2B\u4E2E\u4E2F\u4E30\u4E35\u4E40\u4E41\u4E44\u4E47\u4E51\u4E5A\u4E5C\u4E63\u4E68\u4E69\u4E74\u4E75\u4E79\u4E7F\u4E8D\u4E96\u4E97\u4E9D\u4EAF\u4EB9\u4EC3\u4ED0\u4EDA\u4EDB\u4EE0\u4EE1\u4EE2\u4EE8\u4EEF\u4EF1\u4EF3\u4EF5\u4EFD\u4EFE\u4EFF\u4F00\u4F02\u4F03\u4F08\u4F0B\u4F0C\u4F12\u4F15\u4F16\u4F17\u4F19\u4F2E\u4F31\u4F60\u4F33\u4F35\u4F37\u4F39\u4F3B\u4F3E\u4F40\u4F42\u4F48\u4F49\u4F4B\u4F4C\u4F52\u4F54\u4F56\u4F58\u4F5F\u4F63\u4F6A\u4F6C\u4F6E\u4F71\u4F77\u4F78\u4F79\u4F7A\u4F7D\u4F7E\u4F81\u4F82\u4F84"],
      ["8fb1a1", "\u4F85\u4F89\u4F8A\u4F8C\u4F8E\u4F90\u4F92\u4F93\u4F94\u4F97\u4F99\u4F9A\u4F9E\u4F9F\u4FB2\u4FB7\u4FB9\u4FBB\u4FBC\u4FBD\u4FBE\u4FC0\u4FC1\u4FC5\u4FC6\u4FC8\u4FC9\u4FCB\u4FCC\u4FCD\u4FCF\u4FD2\u4FDC\u4FE0\u4FE2\u4FF0\u4FF2\u4FFC\u4FFD\u4FFF\u5000\u5001\u5004\u5007\u500A\u500C\u500E\u5010\u5013\u5017\u5018\u501B\u501C\u501D\u501E\u5022\u5027\u502E\u5030\u5032\u5033\u5035\u5040\u5041\u5042\u5045\u5046\u504A\u504C\u504E\u5051\u5052\u5053\u5057\u5059\u505F\u5060\u5062\u5063\u5066\u5067\u506A\u506D\u5070\u5071\u503B\u5081\u5083\u5084\u5086\u508A\u508E\u508F\u5090"],
      ["8fb2a1", "\u5092\u5093\u5094\u5096\u509B\u509C\u509E", 4, "\u50AA\u50AF\u50B0\u50B9\u50BA\u50BD\u50C0\u50C3\u50C4\u50C7\u50CC\u50CE\u50D0\u50D3\u50D4\u50D8\u50DC\u50DD\u50DF\u50E2\u50E4\u50E6\u50E8\u50E9\u50EF\u50F1\u50F6\u50FA\u50FE\u5103\u5106\u5107\u5108\u510B\u510C\u510D\u510E\u50F2\u5110\u5117\u5119\u511B\u511C\u511D\u511E\u5123\u5127\u5128\u512C\u512D\u512F\u5131\u5133\u5134\u5135\u5138\u5139\u5142\u514A\u514F\u5153\u5155\u5157\u5158\u515F\u5164\u5166\u517E\u5183\u5184\u518B\u518E\u5198\u519D\u51A1\u51A3\u51AD\u51B8\u51BA\u51BC\u51BE\u51BF\u51C2"],
      ["8fb3a1", "\u51C8\u51CF\u51D1\u51D2\u51D3\u51D5\u51D8\u51DE\u51E2\u51E5\u51EE\u51F2\u51F3\u51F4\u51F7\u5201\u5202\u5205\u5212\u5213\u5215\u5216\u5218\u5222\u5228\u5231\u5232\u5235\u523C\u5245\u5249\u5255\u5257\u5258\u525A\u525C\u525F\u5260\u5261\u5266\u526E\u5277\u5278\u5279\u5280\u5282\u5285\u528A\u528C\u5293\u5295\u5296\u5297\u5298\u529A\u529C\u52A4\u52A5\u52A6\u52A7\u52AF\u52B0\u52B6\u52B7\u52B8\u52BA\u52BB\u52BD\u52C0\u52C4\u52C6\u52C8\u52CC\u52CF\u52D1\u52D4\u52D6\u52DB\u52DC\u52E1\u52E5\u52E8\u52E9\u52EA\u52EC\u52F0\u52F1\u52F4\u52F6\u52F7\u5300\u5303\u530A\u530B"],
      ["8fb4a1", "\u530C\u5311\u5313\u5318\u531B\u531C\u531E\u531F\u5325\u5327\u5328\u5329\u532B\u532C\u532D\u5330\u5332\u5335\u533C\u533D\u533E\u5342\u534C\u534B\u5359\u535B\u5361\u5363\u5365\u536C\u536D\u5372\u5379\u537E\u5383\u5387\u5388\u538E\u5393\u5394\u5399\u539D\u53A1\u53A4\u53AA\u53AB\u53AF\u53B2\u53B4\u53B5\u53B7\u53B8\u53BA\u53BD\u53C0\u53C5\u53CF\u53D2\u53D3\u53D5\u53DA\u53DD\u53DE\u53E0\u53E6\u53E7\u53F5\u5402\u5413\u541A\u5421\u5427\u5428\u542A\u542F\u5431\u5434\u5435\u5443\u5444\u5447\u544D\u544F\u545E\u5462\u5464\u5466\u5467\u5469\u546B\u546D\u546E\u5474\u547F"],
      ["8fb5a1", "\u5481\u5483\u5485\u5488\u5489\u548D\u5491\u5495\u5496\u549C\u549F\u54A1\u54A6\u54A7\u54A9\u54AA\u54AD\u54AE\u54B1\u54B7\u54B9\u54BA\u54BB\u54BF\u54C6\u54CA\u54CD\u54CE\u54E0\u54EA\u54EC\u54EF\u54F6\u54FC\u54FE\u54FF\u5500\u5501\u5505\u5508\u5509\u550C\u550D\u550E\u5515\u552A\u552B\u5532\u5535\u5536\u553B\u553C\u553D\u5541\u5547\u5549\u554A\u554D\u5550\u5551\u5558\u555A\u555B\u555E\u5560\u5561\u5564\u5566\u557F\u5581\u5582\u5586\u5588\u558E\u558F\u5591\u5592\u5593\u5594\u5597\u55A3\u55A4\u55AD\u55B2\u55BF\u55C1\u55C3\u55C6\u55C9\u55CB\u55CC\u55CE\u55D1\u55D2"],
      ["8fb6a1", "\u55D3\u55D7\u55D8\u55DB\u55DE\u55E2\u55E9\u55F6\u55FF\u5605\u5608\u560A\u560D", 5, "\u5619\u562C\u5630\u5633\u5635\u5637\u5639\u563B\u563C\u563D\u563F\u5640\u5641\u5643\u5644\u5646\u5649\u564B\u564D\u564F\u5654\u565E\u5660\u5661\u5662\u5663\u5666\u5669\u566D\u566F\u5671\u5672\u5675\u5684\u5685\u5688\u568B\u568C\u5695\u5699\u569A\u569D\u569E\u569F\u56A6\u56A7\u56A8\u56A9\u56AB\u56AC\u56AD\u56B1\u56B3\u56B7\u56BE\u56C5\u56C9\u56CA\u56CB\u56CF\u56D0\u56CC\u56CD\u56D9\u56DC\u56DD\u56DF\u56E1\u56E4", 4, "\u56F1\u56EB\u56ED"],
      ["8fb7a1", "\u56F6\u56F7\u5701\u5702\u5707\u570A\u570C\u5711\u5715\u571A\u571B\u571D\u5720\u5722\u5723\u5724\u5725\u5729\u572A\u572C\u572E\u572F\u5733\u5734\u573D\u573E\u573F\u5745\u5746\u574C\u574D\u5752\u5762\u5765\u5767\u5768\u576B\u576D", 4, "\u5773\u5774\u5775\u5777\u5779\u577A\u577B\u577C\u577E\u5781\u5783\u578C\u5794\u5797\u5799\u579A\u579C\u579D\u579E\u579F\u57A1\u5795\u57A7\u57A8\u57A9\u57AC\u57B8\u57BD\u57C7\u57C8\u57CC\u57CF\u57D5\u57DD\u57DE\u57E4\u57E6\u57E7\u57E9\u57ED\u57F0\u57F5\u57F6\u57F8\u57FD\u57FE\u57FF\u5803\u5804\u5808\u5809\u57E1"],
      ["8fb8a1", "\u580C\u580D\u581B\u581E\u581F\u5820\u5826\u5827\u582D\u5832\u5839\u583F\u5849\u584C\u584D\u584F\u5850\u5855\u585F\u5861\u5864\u5867\u5868\u5878\u587C\u587F\u5880\u5881\u5887\u5888\u5889\u588A\u588C\u588D\u588F\u5890\u5894\u5896\u589D\u58A0\u58A1\u58A2\u58A6\u58A9\u58B1\u58B2\u58C4\u58BC\u58C2\u58C8\u58CD\u58CE\u58D0\u58D2\u58D4\u58D6\u58DA\u58DD\u58E1\u58E2\u58E9\u58F3\u5905\u5906\u590B\u590C\u5912\u5913\u5914\u8641\u591D\u5921\u5923\u5924\u5928\u592F\u5930\u5933\u5935\u5936\u593F\u5943\u5946\u5952\u5953\u5959\u595B\u595D\u595E\u595F\u5961\u5963\u596B\u596D"],
      ["8fb9a1", "\u596F\u5972\u5975\u5976\u5979\u597B\u597C\u598B\u598C\u598E\u5992\u5995\u5997\u599F\u59A4\u59A7\u59AD\u59AE\u59AF\u59B0\u59B3\u59B7\u59BA\u59BC\u59C1\u59C3\u59C4\u59C8\u59CA\u59CD\u59D2\u59DD\u59DE\u59DF\u59E3\u59E4\u59E7\u59EE\u59EF\u59F1\u59F2\u59F4\u59F7\u5A00\u5A04\u5A0C\u5A0D\u5A0E\u5A12\u5A13\u5A1E\u5A23\u5A24\u5A27\u5A28\u5A2A\u5A2D\u5A30\u5A44\u5A45\u5A47\u5A48\u5A4C\u5A50\u5A55\u5A5E\u5A63\u5A65\u5A67\u5A6D\u5A77\u5A7A\u5A7B\u5A7E\u5A8B\u5A90\u5A93\u5A96\u5A99\u5A9C\u5A9E\u5A9F\u5AA0\u5AA2\u5AA7\u5AAC\u5AB1\u5AB2\u5AB3\u5AB5\u5AB8\u5ABA\u5ABB\u5ABF"],
      ["8fbaa1", "\u5AC4\u5AC6\u5AC8\u5ACF\u5ADA\u5ADC\u5AE0\u5AE5\u5AEA\u5AEE\u5AF5\u5AF6\u5AFD\u5B00\u5B01\u5B08\u5B17\u5B34\u5B19\u5B1B\u5B1D\u5B21\u5B25\u5B2D\u5B38\u5B41\u5B4B\u5B4C\u5B52\u5B56\u5B5E\u5B68\u5B6E\u5B6F\u5B7C\u5B7D\u5B7E\u5B7F\u5B81\u5B84\u5B86\u5B8A\u5B8E\u5B90\u5B91\u5B93\u5B94\u5B96\u5BA8\u5BA9\u5BAC\u5BAD\u5BAF\u5BB1\u5BB2\u5BB7\u5BBA\u5BBC\u5BC0\u5BC1\u5BCD\u5BCF\u5BD6", 4, "\u5BE0\u5BEF\u5BF1\u5BF4\u5BFD\u5C0C\u5C17\u5C1E\u5C1F\u5C23\u5C26\u5C29\u5C2B\u5C2C\u5C2E\u5C30\u5C32\u5C35\u5C36\u5C59\u5C5A\u5C5C\u5C62\u5C63\u5C67\u5C68\u5C69"],
      ["8fbba1", "\u5C6D\u5C70\u5C74\u5C75\u5C7A\u5C7B\u5C7C\u5C7D\u5C87\u5C88\u5C8A\u5C8F\u5C92\u5C9D\u5C9F\u5CA0\u5CA2\u5CA3\u5CA6\u5CAA\u5CB2\u5CB4\u5CB5\u5CBA\u5CC9\u5CCB\u5CD2\u5CDD\u5CD7\u5CEE\u5CF1\u5CF2\u5CF4\u5D01\u5D06\u5D0D\u5D12\u5D2B\u5D23\u5D24\u5D26\u5D27\u5D31\u5D34\u5D39\u5D3D\u5D3F\u5D42\u5D43\u5D46\u5D48\u5D55\u5D51\u5D59\u5D4A\u5D5F\u5D60\u5D61\u5D62\u5D64\u5D6A\u5D6D\u5D70\u5D79\u5D7A\u5D7E\u5D7F\u5D81\u5D83\u5D88\u5D8A\u5D92\u5D93\u5D94\u5D95\u5D99\u5D9B\u5D9F\u5DA0\u5DA7\u5DAB\u5DB0\u5DB4\u5DB8\u5DB9\u5DC3\u5DC7\u5DCB\u5DD0\u5DCE\u5DD8\u5DD9\u5DE0\u5DE4"],
      ["8fbca1", "\u5DE9\u5DF8\u5DF9\u5E00\u5E07\u5E0D\u5E12\u5E14\u5E15\u5E18\u5E1F\u5E20\u5E2E\u5E28\u5E32\u5E35\u5E3E\u5E4B\u5E50\u5E49\u5E51\u5E56\u5E58\u5E5B\u5E5C\u5E5E\u5E68\u5E6A", 4, "\u5E70\u5E80\u5E8B\u5E8E\u5EA2\u5EA4\u5EA5\u5EA8\u5EAA\u5EAC\u5EB1\u5EB3\u5EBD\u5EBE\u5EBF\u5EC6\u5ECC\u5ECB\u5ECE\u5ED1\u5ED2\u5ED4\u5ED5\u5EDC\u5EDE\u5EE5\u5EEB\u5F02\u5F06\u5F07\u5F08\u5F0E\u5F19\u5F1C\u5F1D\u5F21\u5F22\u5F23\u5F24\u5F28\u5F2B\u5F2C\u5F2E\u5F30\u5F34\u5F36\u5F3B\u5F3D\u5F3F\u5F40\u5F44\u5F45\u5F47\u5F4D\u5F50\u5F54\u5F58\u5F5B\u5F60\u5F63\u5F64\u5F67"],
      ["8fbda1", "\u5F6F\u5F72\u5F74\u5F75\u5F78\u5F7A\u5F7D\u5F7E\u5F89\u5F8D\u5F8F\u5F96\u5F9C\u5F9D\u5FA2\u5FA7\u5FAB\u5FA4\u5FAC\u5FAF\u5FB0\u5FB1\u5FB8\u5FC4\u5FC7\u5FC8\u5FC9\u5FCB\u5FD0", 4, "\u5FDE\u5FE1\u5FE2\u5FE8\u5FE9\u5FEA\u5FEC\u5FED\u5FEE\u5FEF\u5FF2\u5FF3\u5FF6\u5FFA\u5FFC\u6007\u600A\u600D\u6013\u6014\u6017\u6018\u601A\u601F\u6024\u602D\u6033\u6035\u6040\u6047\u6048\u6049\u604C\u6051\u6054\u6056\u6057\u605D\u6061\u6067\u6071\u607E\u607F\u6082\u6086\u6088\u608A\u608E\u6091\u6093\u6095\u6098\u609D\u609E\u60A2\u60A4\u60A5\u60A8\u60B0\u60B1\u60B7"],
      ["8fbea1", "\u60BB\u60BE\u60C2\u60C4\u60C8\u60C9\u60CA\u60CB\u60CE\u60CF\u60D4\u60D5\u60D9\u60DB\u60DD\u60DE\u60E2\u60E5\u60F2\u60F5\u60F8\u60FC\u60FD\u6102\u6107\u610A\u610C\u6110", 4, "\u6116\u6117\u6119\u611C\u611E\u6122\u612A\u612B\u6130\u6131\u6135\u6136\u6137\u6139\u6141\u6145\u6146\u6149\u615E\u6160\u616C\u6172\u6178\u617B\u617C\u617F\u6180\u6181\u6183\u6184\u618B\u618D\u6192\u6193\u6197\u6198\u619C\u619D\u619F\u61A0\u61A5\u61A8\u61AA\u61AD\u61B8\u61B9\u61BC\u61C0\u61C1\u61C2\u61CE\u61CF\u61D5\u61DC\u61DD\u61DE\u61DF\u61E1\u61E2\u61E7\u61E9\u61E5"],
      ["8fbfa1", "\u61EC\u61ED\u61EF\u6201\u6203\u6204\u6207\u6213\u6215\u621C\u6220\u6222\u6223\u6227\u6229\u622B\u6239\u623D\u6242\u6243\u6244\u6246\u624C\u6250\u6251\u6252\u6254\u6256\u625A\u625C\u6264\u626D\u626F\u6273\u627A\u627D\u628D\u628E\u628F\u6290\u62A6\u62A8\u62B3\u62B6\u62B7\u62BA\u62BE\u62BF\u62C4\u62CE\u62D5\u62D6\u62DA\u62EA\u62F2\u62F4\u62FC\u62FD\u6303\u6304\u630A\u630B\u630D\u6310\u6313\u6316\u6318\u6329\u632A\u632D\u6335\u6336\u6339\u633C\u6341\u6342\u6343\u6344\u6346\u634A\u634B\u634E\u6352\u6353\u6354\u6358\u635B\u6365\u6366\u636C\u636D\u6371\u6374\u6375"],
      ["8fc0a1", "\u6378\u637C\u637D\u637F\u6382\u6384\u6387\u638A\u6390\u6394\u6395\u6399\u639A\u639E\u63A4\u63A6\u63AD\u63AE\u63AF\u63BD\u63C1\u63C5\u63C8\u63CE\u63D1\u63D3\u63D4\u63D5\u63DC\u63E0\u63E5\u63EA\u63EC\u63F2\u63F3\u63F5\u63F8\u63F9\u6409\u640A\u6410\u6412\u6414\u6418\u641E\u6420\u6422\u6424\u6425\u6429\u642A\u642F\u6430\u6435\u643D\u643F\u644B\u644F\u6451\u6452\u6453\u6454\u645A\u645B\u645C\u645D\u645F\u6460\u6461\u6463\u646D\u6473\u6474\u647B\u647D\u6485\u6487\u648F\u6490\u6491\u6498\u6499\u649B\u649D\u649F\u64A1\u64A3\u64A6\u64A8\u64AC\u64B3\u64BD\u64BE\u64BF"],
      ["8fc1a1", "\u64C4\u64C9\u64CA\u64CB\u64CC\u64CE\u64D0\u64D1\u64D5\u64D7\u64E4\u64E5\u64E9\u64EA\u64ED\u64F0\u64F5\u64F7\u64FB\u64FF\u6501\u6504\u6508\u6509\u650A\u650F\u6513\u6514\u6516\u6519\u651B\u651E\u651F\u6522\u6526\u6529\u652E\u6531\u653A\u653C\u653D\u6543\u6547\u6549\u6550\u6552\u6554\u655F\u6560\u6567\u656B\u657A\u657D\u6581\u6585\u658A\u6592\u6595\u6598\u659D\u65A0\u65A3\u65A6\u65AE\u65B2\u65B3\u65B4\u65BF\u65C2\u65C8\u65C9\u65CE\u65D0\u65D4\u65D6\u65D8\u65DF\u65F0\u65F2\u65F4\u65F5\u65F9\u65FE\u65FF\u6600\u6604\u6608\u6609\u660D\u6611\u6612\u6615\u6616\u661D"],
      ["8fc2a1", "\u661E\u6621\u6622\u6623\u6624\u6626\u6629\u662A\u662B\u662C\u662E\u6630\u6631\u6633\u6639\u6637\u6640\u6645\u6646\u664A\u664C\u6651\u664E\u6657\u6658\u6659\u665B\u665C\u6660\u6661\u66FB\u666A\u666B\u666C\u667E\u6673\u6675\u667F\u6677\u6678\u6679\u667B\u6680\u667C\u668B\u668C\u668D\u6690\u6692\u6699\u669A\u669B\u669C\u669F\u66A0\u66A4\u66AD\u66B1\u66B2\u66B5\u66BB\u66BF\u66C0\u66C2\u66C3\u66C8\u66CC\u66CE\u66CF\u66D4\u66DB\u66DF\u66E8\u66EB\u66EC\u66EE\u66FA\u6705\u6707\u670E\u6713\u6719\u671C\u6720\u6722\u6733\u673E\u6745\u6747\u6748\u674C\u6754\u6755\u675D"],
      ["8fc3a1", "\u6766\u676C\u676E\u6774\u6776\u677B\u6781\u6784\u678E\u678F\u6791\u6793\u6796\u6798\u6799\u679B\u67B0\u67B1\u67B2\u67B5\u67BB\u67BC\u67BD\u67F9\u67C0\u67C2\u67C3\u67C5\u67C8\u67C9\u67D2\u67D7\u67D9\u67DC\u67E1\u67E6\u67F0\u67F2\u67F6\u67F7\u6852\u6814\u6819\u681D\u681F\u6828\u6827\u682C\u682D\u682F\u6830\u6831\u6833\u683B\u683F\u6844\u6845\u684A\u684C\u6855\u6857\u6858\u685B\u686B\u686E", 4, "\u6875\u6879\u687A\u687B\u687C\u6882\u6884\u6886\u6888\u6896\u6898\u689A\u689C\u68A1\u68A3\u68A5\u68A9\u68AA\u68AE\u68B2\u68BB\u68C5\u68C8\u68CC\u68CF"],
      ["8fc4a1", "\u68D0\u68D1\u68D3\u68D6\u68D9\u68DC\u68DD\u68E5\u68E8\u68EA\u68EB\u68EC\u68ED\u68F0\u68F1\u68F5\u68F6\u68FB\u68FC\u68FD\u6906\u6909\u690A\u6910\u6911\u6913\u6916\u6917\u6931\u6933\u6935\u6938\u693B\u6942\u6945\u6949\u694E\u6957\u695B\u6963\u6964\u6965\u6966\u6968\u6969\u696C\u6970\u6971\u6972\u697A\u697B\u697F\u6980\u698D\u6992\u6996\u6998\u69A1\u69A5\u69A6\u69A8\u69AB\u69AD\u69AF\u69B7\u69B8\u69BA\u69BC\u69C5\u69C8\u69D1\u69D6\u69D7\u69E2\u69E5\u69EE\u69EF\u69F1\u69F3\u69F5\u69FE\u6A00\u6A01\u6A03\u6A0F\u6A11\u6A15\u6A1A\u6A1D\u6A20\u6A24\u6A28\u6A30\u6A32"],
      ["8fc5a1", "\u6A34\u6A37\u6A3B\u6A3E\u6A3F\u6A45\u6A46\u6A49\u6A4A\u6A4E\u6A50\u6A51\u6A52\u6A55\u6A56\u6A5B\u6A64\u6A67\u6A6A\u6A71\u6A73\u6A7E\u6A81\u6A83\u6A86\u6A87\u6A89\u6A8B\u6A91\u6A9B\u6A9D\u6A9E\u6A9F\u6AA5\u6AAB\u6AAF\u6AB0\u6AB1\u6AB4\u6ABD\u6ABE\u6ABF\u6AC6\u6AC9\u6AC8\u6ACC\u6AD0\u6AD4\u6AD5\u6AD6\u6ADC\u6ADD\u6AE4\u6AE7\u6AEC\u6AF0\u6AF1\u6AF2\u6AFC\u6AFD\u6B02\u6B03\u6B06\u6B07\u6B09\u6B0F\u6B10\u6B11\u6B17\u6B1B\u6B1E\u6B24\u6B28\u6B2B\u6B2C\u6B2F\u6B35\u6B36\u6B3B\u6B3F\u6B46\u6B4A\u6B4D\u6B52\u6B56\u6B58\u6B5D\u6B60\u6B67\u6B6B\u6B6E\u6B70\u6B75\u6B7D"],
      ["8fc6a1", "\u6B7E\u6B82\u6B85\u6B97\u6B9B\u6B9F\u6BA0\u6BA2\u6BA3\u6BA8\u6BA9\u6BAC\u6BAD\u6BAE\u6BB0\u6BB8\u6BB9\u6BBD\u6BBE\u6BC3\u6BC4\u6BC9\u6BCC\u6BD6\u6BDA\u6BE1\u6BE3\u6BE6\u6BE7\u6BEE\u6BF1\u6BF7\u6BF9\u6BFF\u6C02\u6C04\u6C05\u6C09\u6C0D\u6C0E\u6C10\u6C12\u6C19\u6C1F\u6C26\u6C27\u6C28\u6C2C\u6C2E\u6C33\u6C35\u6C36\u6C3A\u6C3B\u6C3F\u6C4A\u6C4B\u6C4D\u6C4F\u6C52\u6C54\u6C59\u6C5B\u6C5C\u6C6B\u6C6D\u6C6F\u6C74\u6C76\u6C78\u6C79\u6C7B\u6C85\u6C86\u6C87\u6C89\u6C94\u6C95\u6C97\u6C98\u6C9C\u6C9F\u6CB0\u6CB2\u6CB4\u6CC2\u6CC6\u6CCD\u6CCF\u6CD0\u6CD1\u6CD2\u6CD4\u6CD6"],
      ["8fc7a1", "\u6CDA\u6CDC\u6CE0\u6CE7\u6CE9\u6CEB\u6CEC\u6CEE\u6CF2\u6CF4\u6D04\u6D07\u6D0A\u6D0E\u6D0F\u6D11\u6D13\u6D1A\u6D26\u6D27\u6D28\u6C67\u6D2E\u6D2F\u6D31\u6D39\u6D3C\u6D3F\u6D57\u6D5E\u6D5F\u6D61\u6D65\u6D67\u6D6F\u6D70\u6D7C\u6D82\u6D87\u6D91\u6D92\u6D94\u6D96\u6D97\u6D98\u6DAA\u6DAC\u6DB4\u6DB7\u6DB9\u6DBD\u6DBF\u6DC4\u6DC8\u6DCA\u6DCE\u6DCF\u6DD6\u6DDB\u6DDD\u6DDF\u6DE0\u6DE2\u6DE5\u6DE9\u6DEF\u6DF0\u6DF4\u6DF6\u6DFC\u6E00\u6E04\u6E1E\u6E22\u6E27\u6E32\u6E36\u6E39\u6E3B\u6E3C\u6E44\u6E45\u6E48\u6E49\u6E4B\u6E4F\u6E51\u6E52\u6E53\u6E54\u6E57\u6E5C\u6E5D\u6E5E"],
      ["8fc8a1", "\u6E62\u6E63\u6E68\u6E73\u6E7B\u6E7D\u6E8D\u6E93\u6E99\u6EA0\u6EA7\u6EAD\u6EAE\u6EB1\u6EB3\u6EBB\u6EBF\u6EC0\u6EC1\u6EC3\u6EC7\u6EC8\u6ECA\u6ECD\u6ECE\u6ECF\u6EEB\u6EED\u6EEE\u6EF9\u6EFB\u6EFD\u6F04\u6F08\u6F0A\u6F0C\u6F0D\u6F16\u6F18\u6F1A\u6F1B\u6F26\u6F29\u6F2A\u6F2F\u6F30\u6F33\u6F36\u6F3B\u6F3C\u6F2D\u6F4F\u6F51\u6F52\u6F53\u6F57\u6F59\u6F5A\u6F5D\u6F5E\u6F61\u6F62\u6F68\u6F6C\u6F7D\u6F7E\u6F83\u6F87\u6F88\u6F8B\u6F8C\u6F8D\u6F90\u6F92\u6F93\u6F94\u6F96\u6F9A\u6F9F\u6FA0\u6FA5\u6FA6\u6FA7\u6FA8\u6FAE\u6FAF\u6FB0\u6FB5\u6FB6\u6FBC\u6FC5\u6FC7\u6FC8\u6FCA"],
      ["8fc9a1", "\u6FDA\u6FDE\u6FE8\u6FE9\u6FF0\u6FF5\u6FF9\u6FFC\u6FFD\u7000\u7005\u7006\u7007\u700D\u7017\u7020\u7023\u702F\u7034\u7037\u7039\u703C\u7043\u7044\u7048\u7049\u704A\u704B\u7054\u7055\u705D\u705E\u704E\u7064\u7065\u706C\u706E\u7075\u7076\u707E\u7081\u7085\u7086\u7094", 4, "\u709B\u70A4\u70AB\u70B0\u70B1\u70B4\u70B7\u70CA\u70D1\u70D3\u70D4\u70D5\u70D6\u70D8\u70DC\u70E4\u70FA\u7103", 4, "\u710B\u710C\u710F\u711E\u7120\u712B\u712D\u712F\u7130\u7131\u7138\u7141\u7145\u7146\u7147\u714A\u714B\u7150\u7152\u7157\u715A\u715C\u715E\u7160"],
      ["8fcaa1", "\u7168\u7179\u7180\u7185\u7187\u718C\u7192\u719A\u719B\u71A0\u71A2\u71AF\u71B0\u71B2\u71B3\u71BA\u71BF\u71C0\u71C1\u71C4\u71CB\u71CC\u71D3\u71D6\u71D9\u71DA\u71DC\u71F8\u71FE\u7200\u7207\u7208\u7209\u7213\u7217\u721A\u721D\u721F\u7224\u722B\u722F\u7234\u7238\u7239\u7241\u7242\u7243\u7245\u724E\u724F\u7250\u7253\u7255\u7256\u725A\u725C\u725E\u7260\u7263\u7268\u726B\u726E\u726F\u7271\u7277\u7278\u727B\u727C\u727F\u7284\u7289\u728D\u728E\u7293\u729B\u72A8\u72AD\u72AE\u72B1\u72B4\u72BE\u72C1\u72C7\u72C9\u72CC\u72D5\u72D6\u72D8\u72DF\u72E5\u72F3\u72F4\u72FA\u72FB"],
      ["8fcba1", "\u72FE\u7302\u7304\u7305\u7307\u730B\u730D\u7312\u7313\u7318\u7319\u731E\u7322\u7324\u7327\u7328\u732C\u7331\u7332\u7335\u733A\u733B\u733D\u7343\u734D\u7350\u7352\u7356\u7358\u735D\u735E\u735F\u7360\u7366\u7367\u7369\u736B\u736C\u736E\u736F\u7371\u7377\u7379\u737C\u7380\u7381\u7383\u7385\u7386\u738E\u7390\u7393\u7395\u7397\u7398\u739C\u739E\u739F\u73A0\u73A2\u73A5\u73A6\u73AA\u73AB\u73AD\u73B5\u73B7\u73B9\u73BC\u73BD\u73BF\u73C5\u73C6\u73C9\u73CB\u73CC\u73CF\u73D2\u73D3\u73D6\u73D9\u73DD\u73E1\u73E3\u73E6\u73E7\u73E9\u73F4\u73F5\u73F7\u73F9\u73FA\u73FB\u73FD"],
      ["8fcca1", "\u73FF\u7400\u7401\u7404\u7407\u740A\u7411\u741A\u741B\u7424\u7426\u7428", 9, "\u7439\u7440\u7443\u7444\u7446\u7447\u744B\u744D\u7451\u7452\u7457\u745D\u7462\u7466\u7467\u7468\u746B\u746D\u746E\u7471\u7472\u7480\u7481\u7485\u7486\u7487\u7489\u748F\u7490\u7491\u7492\u7498\u7499\u749A\u749C\u749F\u74A0\u74A1\u74A3\u74A6\u74A8\u74A9\u74AA\u74AB\u74AE\u74AF\u74B1\u74B2\u74B5\u74B9\u74BB\u74BF\u74C8\u74C9\u74CC\u74D0\u74D3\u74D8\u74DA\u74DB\u74DE\u74DF\u74E4\u74E8\u74EA\u74EB\u74EF\u74F4\u74FA\u74FB\u74FC\u74FF\u7506"],
      ["8fcda1", "\u7512\u7516\u7517\u7520\u7521\u7524\u7527\u7529\u752A\u752F\u7536\u7539\u753D\u753E\u753F\u7540\u7543\u7547\u7548\u754E\u7550\u7552\u7557\u755E\u755F\u7561\u756F\u7571\u7579", 5, "\u7581\u7585\u7590\u7592\u7593\u7595\u7599\u759C\u75A2\u75A4\u75B4\u75BA\u75BF\u75C0\u75C1\u75C4\u75C6\u75CC\u75CE\u75CF\u75D7\u75DC\u75DF\u75E0\u75E1\u75E4\u75E7\u75EC\u75EE\u75EF\u75F1\u75F9\u7600\u7602\u7603\u7604\u7607\u7608\u760A\u760C\u760F\u7612\u7613\u7615\u7616\u7619\u761B\u761C\u761D\u761E\u7623\u7625\u7626\u7629\u762D\u7632\u7633\u7635\u7638\u7639"],
      ["8fcea1", "\u763A\u763C\u764A\u7640\u7641\u7643\u7644\u7645\u7649\u764B\u7655\u7659\u765F\u7664\u7665\u766D\u766E\u766F\u7671\u7674\u7681\u7685\u768C\u768D\u7695\u769B\u769C\u769D\u769F\u76A0\u76A2", 6, "\u76AA\u76AD\u76BD\u76C1\u76C5\u76C9\u76CB\u76CC\u76CE\u76D4\u76D9\u76E0\u76E6\u76E8\u76EC\u76F0\u76F1\u76F6\u76F9\u76FC\u7700\u7706\u770A\u770E\u7712\u7714\u7715\u7717\u7719\u771A\u771C\u7722\u7728\u772D\u772E\u772F\u7734\u7735\u7736\u7739\u773D\u773E\u7742\u7745\u7746\u774A\u774D\u774E\u774F\u7752\u7756\u7757\u775C\u775E\u775F\u7760\u7762"],
      ["8fcfa1", "\u7764\u7767\u776A\u776C\u7770\u7772\u7773\u7774\u777A\u777D\u7780\u7784\u778C\u778D\u7794\u7795\u7796\u779A\u779F\u77A2\u77A7\u77AA\u77AE\u77AF\u77B1\u77B5\u77BE\u77C3\u77C9\u77D1\u77D2\u77D5\u77D9\u77DE\u77DF\u77E0\u77E4\u77E6\u77EA\u77EC\u77F0\u77F1\u77F4\u77F8\u77FB\u7805\u7806\u7809\u780D\u780E\u7811\u781D\u7821\u7822\u7823\u782D\u782E\u7830\u7835\u7837\u7843\u7844\u7847\u7848\u784C\u784E\u7852\u785C\u785E\u7860\u7861\u7863\u7864\u7868\u786A\u786E\u787A\u787E\u788A\u788F\u7894\u7898\u78A1\u789D\u789E\u789F\u78A4\u78A8\u78AC\u78AD\u78B0\u78B1\u78B2\u78B3"],
      ["8fd0a1", "\u78BB\u78BD\u78BF\u78C7\u78C8\u78C9\u78CC\u78CE\u78D2\u78D3\u78D5\u78D6\u78E4\u78DB\u78DF\u78E0\u78E1\u78E6\u78EA\u78F2\u78F3\u7900\u78F6\u78F7\u78FA\u78FB\u78FF\u7906\u790C\u7910\u791A\u791C\u791E\u791F\u7920\u7925\u7927\u7929\u792D\u7931\u7934\u7935\u793B\u793D\u793F\u7944\u7945\u7946\u794A\u794B\u794F\u7951\u7954\u7958\u795B\u795C\u7967\u7969\u796B\u7972\u7979\u797B\u797C\u797E\u798B\u798C\u7991\u7993\u7994\u7995\u7996\u7998\u799B\u799C\u79A1\u79A8\u79A9\u79AB\u79AF\u79B1\u79B4\u79B8\u79BB\u79C2\u79C4\u79C7\u79C8\u79CA\u79CF\u79D4\u79D6\u79DA\u79DD\u79DE"],
      ["8fd1a1", "\u79E0\u79E2\u79E5\u79EA\u79EB\u79ED\u79F1\u79F8\u79FC\u7A02\u7A03\u7A07\u7A09\u7A0A\u7A0C\u7A11\u7A15\u7A1B\u7A1E\u7A21\u7A27\u7A2B\u7A2D\u7A2F\u7A30\u7A34\u7A35\u7A38\u7A39\u7A3A\u7A44\u7A45\u7A47\u7A48\u7A4C\u7A55\u7A56\u7A59\u7A5C\u7A5D\u7A5F\u7A60\u7A65\u7A67\u7A6A\u7A6D\u7A75\u7A78\u7A7E\u7A80\u7A82\u7A85\u7A86\u7A8A\u7A8B\u7A90\u7A91\u7A94\u7A9E\u7AA0\u7AA3\u7AAC\u7AB3\u7AB5\u7AB9\u7ABB\u7ABC\u7AC6\u7AC9\u7ACC\u7ACE\u7AD1\u7ADB\u7AE8\u7AE9\u7AEB\u7AEC\u7AF1\u7AF4\u7AFB\u7AFD\u7AFE\u7B07\u7B14\u7B1F\u7B23\u7B27\u7B29\u7B2A\u7B2B\u7B2D\u7B2E\u7B2F\u7B30"],
      ["8fd2a1", "\u7B31\u7B34\u7B3D\u7B3F\u7B40\u7B41\u7B47\u7B4E\u7B55\u7B60\u7B64\u7B66\u7B69\u7B6A\u7B6D\u7B6F\u7B72\u7B73\u7B77\u7B84\u7B89\u7B8E\u7B90\u7B91\u7B96\u7B9B\u7B9E\u7BA0\u7BA5\u7BAC\u7BAF\u7BB0\u7BB2\u7BB5\u7BB6\u7BBA\u7BBB\u7BBC\u7BBD\u7BC2\u7BC5\u7BC8\u7BCA\u7BD4\u7BD6\u7BD7\u7BD9\u7BDA\u7BDB\u7BE8\u7BEA\u7BF2\u7BF4\u7BF5\u7BF8\u7BF9\u7BFA\u7BFC\u7BFE\u7C01\u7C02\u7C03\u7C04\u7C06\u7C09\u7C0B\u7C0C\u7C0E\u7C0F\u7C19\u7C1B\u7C20\u7C25\u7C26\u7C28\u7C2C\u7C31\u7C33\u7C34\u7C36\u7C39\u7C3A\u7C46\u7C4A\u7C55\u7C51\u7C52\u7C53\u7C59", 5],
      ["8fd3a1", "\u7C61\u7C63\u7C67\u7C69\u7C6D\u7C6E\u7C70\u7C72\u7C79\u7C7C\u7C7D\u7C86\u7C87\u7C8F\u7C94\u7C9E\u7CA0\u7CA6\u7CB0\u7CB6\u7CB7\u7CBA\u7CBB\u7CBC\u7CBF\u7CC4\u7CC7\u7CC8\u7CC9\u7CCD\u7CCF\u7CD3\u7CD4\u7CD5\u7CD7\u7CD9\u7CDA\u7CDD\u7CE6\u7CE9\u7CEB\u7CF5\u7D03\u7D07\u7D08\u7D09\u7D0F\u7D11\u7D12\u7D13\u7D16\u7D1D\u7D1E\u7D23\u7D26\u7D2A\u7D2D\u7D31\u7D3C\u7D3D\u7D3E\u7D40\u7D41\u7D47\u7D48\u7D4D\u7D51\u7D53\u7D57\u7D59\u7D5A\u7D5C\u7D5D\u7D65\u7D67\u7D6A\u7D70\u7D78\u7D7A\u7D7B\u7D7F\u7D81\u7D82\u7D83\u7D85\u7D86\u7D88\u7D8B\u7D8C\u7D8D\u7D91\u7D96\u7D97\u7D9D"],
      ["8fd4a1", "\u7D9E\u7DA6\u7DA7\u7DAA\u7DB3\u7DB6\u7DB7\u7DB9\u7DC2", 4, "\u7DCC\u7DCD\u7DCE\u7DD7\u7DD9\u7E00\u7DE2\u7DE5\u7DE6\u7DEA\u7DEB\u7DED\u7DF1\u7DF5\u7DF6\u7DF9\u7DFA\u7E08\u7E10\u7E11\u7E15\u7E17\u7E1C\u7E1D\u7E20\u7E27\u7E28\u7E2C\u7E2D\u7E2F\u7E33\u7E36\u7E3F\u7E44\u7E45\u7E47\u7E4E\u7E50\u7E52\u7E58\u7E5F\u7E61\u7E62\u7E65\u7E6B\u7E6E\u7E6F\u7E73\u7E78\u7E7E\u7E81\u7E86\u7E87\u7E8A\u7E8D\u7E91\u7E95\u7E98\u7E9A\u7E9D\u7E9E\u7F3C\u7F3B\u7F3D\u7F3E\u7F3F\u7F43\u7F44\u7F47\u7F4F\u7F52\u7F53\u7F5B\u7F5C\u7F5D\u7F61\u7F63\u7F64\u7F65\u7F66\u7F6D"],
      ["8fd5a1", "\u7F71\u7F7D\u7F7E\u7F7F\u7F80\u7F8B\u7F8D\u7F8F\u7F90\u7F91\u7F96\u7F97\u7F9C\u7FA1\u7FA2\u7FA6\u7FAA\u7FAD\u7FB4\u7FBC\u7FBF\u7FC0\u7FC3\u7FC8\u7FCE\u7FCF\u7FDB\u7FDF\u7FE3\u7FE5\u7FE8\u7FEC\u7FEE\u7FEF\u7FF2\u7FFA\u7FFD\u7FFE\u7FFF\u8007\u8008\u800A\u800D\u800E\u800F\u8011\u8013\u8014\u8016\u801D\u801E\u801F\u8020\u8024\u8026\u802C\u802E\u8030\u8034\u8035\u8037\u8039\u803A\u803C\u803E\u8040\u8044\u8060\u8064\u8066\u806D\u8071\u8075\u8081\u8088\u808E\u809C\u809E\u80A6\u80A7\u80AB\u80B8\u80B9\u80C8\u80CD\u80CF\u80D2\u80D4\u80D5\u80D7\u80D8\u80E0\u80ED\u80EE"],
      ["8fd6a1", "\u80F0\u80F2\u80F3\u80F6\u80F9\u80FA\u80FE\u8103\u810B\u8116\u8117\u8118\u811C\u811E\u8120\u8124\u8127\u812C\u8130\u8135\u813A\u813C\u8145\u8147\u814A\u814C\u8152\u8157\u8160\u8161\u8167\u8168\u8169\u816D\u816F\u8177\u8181\u8190\u8184\u8185\u8186\u818B\u818E\u8196\u8198\u819B\u819E\u81A2\u81AE\u81B2\u81B4\u81BB\u81CB\u81C3\u81C5\u81CA\u81CE\u81CF\u81D5\u81D7\u81DB\u81DD\u81DE\u81E1\u81E4\u81EB\u81EC\u81F0\u81F1\u81F2\u81F5\u81F6\u81F8\u81F9\u81FD\u81FF\u8200\u8203\u820F\u8213\u8214\u8219\u821A\u821D\u8221\u8222\u8228\u8232\u8234\u823A\u8243\u8244\u8245\u8246"],
      ["8fd7a1", "\u824B\u824E\u824F\u8251\u8256\u825C\u8260\u8263\u8267\u826D\u8274\u827B\u827D\u827F\u8280\u8281\u8283\u8284\u8287\u8289\u828A\u828E\u8291\u8294\u8296\u8298\u829A\u829B\u82A0\u82A1\u82A3\u82A4\u82A7\u82A8\u82A9\u82AA\u82AE\u82B0\u82B2\u82B4\u82B7\u82BA\u82BC\u82BE\u82BF\u82C6\u82D0\u82D5\u82DA\u82E0\u82E2\u82E4\u82E8\u82EA\u82ED\u82EF\u82F6\u82F7\u82FD\u82FE\u8300\u8301\u8307\u8308\u830A\u830B\u8354\u831B\u831D\u831E\u831F\u8321\u8322\u832C\u832D\u832E\u8330\u8333\u8337\u833A\u833C\u833D\u8342\u8343\u8344\u8347\u834D\u834E\u8351\u8355\u8356\u8357\u8370\u8378"],
      ["8fd8a1", "\u837D\u837F\u8380\u8382\u8384\u8386\u838D\u8392\u8394\u8395\u8398\u8399\u839B\u839C\u839D\u83A6\u83A7\u83A9\u83AC\u83BE\u83BF\u83C0\u83C7\u83C9\u83CF\u83D0\u83D1\u83D4\u83DD\u8353\u83E8\u83EA\u83F6\u83F8\u83F9\u83FC\u8401\u8406\u840A\u840F\u8411\u8415\u8419\u83AD\u842F\u8439\u8445\u8447\u8448\u844A\u844D\u844F\u8451\u8452\u8456\u8458\u8459\u845A\u845C\u8460\u8464\u8465\u8467\u846A\u8470\u8473\u8474\u8476\u8478\u847C\u847D\u8481\u8485\u8492\u8493\u8495\u849E\u84A6\u84A8\u84A9\u84AA\u84AF\u84B1\u84B4\u84BA\u84BD\u84BE\u84C0\u84C2\u84C7\u84C8\u84CC\u84CF\u84D3"],
      ["8fd9a1", "\u84DC\u84E7\u84EA\u84EF\u84F0\u84F1\u84F2\u84F7\u8532\u84FA\u84FB\u84FD\u8502\u8503\u8507\u850C\u850E\u8510\u851C\u851E\u8522\u8523\u8524\u8525\u8527\u852A\u852B\u852F\u8533\u8534\u8536\u853F\u8546\u854F", 4, "\u8556\u8559\u855C", 6, "\u8564\u856B\u856F\u8579\u857A\u857B\u857D\u857F\u8581\u8585\u8586\u8589\u858B\u858C\u858F\u8593\u8598\u859D\u859F\u85A0\u85A2\u85A5\u85A7\u85B4\u85B6\u85B7\u85B8\u85BC\u85BD\u85BE\u85BF\u85C2\u85C7\u85CA\u85CB\u85CE\u85AD\u85D8\u85DA\u85DF\u85E0\u85E6\u85E8\u85ED\u85F3\u85F6\u85FC"],
      ["8fdaa1", "\u85FF\u8600\u8604\u8605\u860D\u860E\u8610\u8611\u8612\u8618\u8619\u861B\u861E\u8621\u8627\u8629\u8636\u8638\u863A\u863C\u863D\u8640\u8642\u8646\u8652\u8653\u8656\u8657\u8658\u8659\u865D\u8660", 4, "\u8669\u866C\u866F\u8675\u8676\u8677\u867A\u868D\u8691\u8696\u8698\u869A\u869C\u86A1\u86A6\u86A7\u86A8\u86AD\u86B1\u86B3\u86B4\u86B5\u86B7\u86B8\u86B9\u86BF\u86C0\u86C1\u86C3\u86C5\u86D1\u86D2\u86D5\u86D7\u86DA\u86DC\u86E0\u86E3\u86E5\u86E7\u8688\u86FA\u86FC\u86FD\u8704\u8705\u8707\u870B\u870E\u870F\u8710\u8713\u8714\u8719\u871E\u871F\u8721\u8723"],
      ["8fdba1", "\u8728\u872E\u872F\u8731\u8732\u8739\u873A\u873C\u873D\u873E\u8740\u8743\u8745\u874D\u8758\u875D\u8761\u8764\u8765\u876F\u8771\u8772\u877B\u8783", 6, "\u878B\u878C\u8790\u8793\u8795\u8797\u8798\u8799\u879E\u87A0\u87A3\u87A7\u87AC\u87AD\u87AE\u87B1\u87B5\u87BE\u87BF\u87C1\u87C8\u87C9\u87CA\u87CE\u87D5\u87D6\u87D9\u87DA\u87DC\u87DF\u87E2\u87E3\u87E4\u87EA\u87EB\u87ED\u87F1\u87F3\u87F8\u87FA\u87FF\u8801\u8803\u8806\u8809\u880A\u880B\u8810\u8819\u8812\u8813\u8814\u8818\u881A\u881B\u881C\u881E\u881F\u8828\u882D\u882E\u8830\u8832\u8835"],
      ["8fdca1", "\u883A\u883C\u8841\u8843\u8845\u8848\u8849\u884A\u884B\u884E\u8851\u8855\u8856\u8858\u885A\u885C\u885F\u8860\u8864\u8869\u8871\u8879\u887B\u8880\u8898\u889A\u889B\u889C\u889F\u88A0\u88A8\u88AA\u88BA\u88BD\u88BE\u88C0\u88CA", 4, "\u88D1\u88D2\u88D3\u88DB\u88DE\u88E7\u88EF\u88F0\u88F1\u88F5\u88F7\u8901\u8906\u890D\u890E\u890F\u8915\u8916\u8918\u8919\u891A\u891C\u8920\u8926\u8927\u8928\u8930\u8931\u8932\u8935\u8939\u893A\u893E\u8940\u8942\u8945\u8946\u8949\u894F\u8952\u8957\u895A\u895B\u895C\u8961\u8962\u8963\u896B\u896E\u8970\u8973\u8975\u897A"],
      ["8fdda1", "\u897B\u897C\u897D\u8989\u898D\u8990\u8994\u8995\u899B\u899C\u899F\u89A0\u89A5\u89B0\u89B4\u89B5\u89B6\u89B7\u89BC\u89D4", 4, "\u89E5\u89E9\u89EB\u89ED\u89F1\u89F3\u89F6\u89F9\u89FD\u89FF\u8A04\u8A05\u8A07\u8A0F\u8A11\u8A12\u8A14\u8A15\u8A1E\u8A20\u8A22\u8A24\u8A26\u8A2B\u8A2C\u8A2F\u8A35\u8A37\u8A3D\u8A3E\u8A40\u8A43\u8A45\u8A47\u8A49\u8A4D\u8A4E\u8A53\u8A56\u8A57\u8A58\u8A5C\u8A5D\u8A61\u8A65\u8A67\u8A75\u8A76\u8A77\u8A79\u8A7A\u8A7B\u8A7E\u8A7F\u8A80\u8A83\u8A86\u8A8B\u8A8F\u8A90\u8A92\u8A96\u8A97\u8A99\u8A9F\u8AA7\u8AA9\u8AAE\u8AAF\u8AB3"],
      ["8fdea1", "\u8AB6\u8AB7\u8ABB\u8ABE\u8AC3\u8AC6\u8AC8\u8AC9\u8ACA\u8AD1\u8AD3\u8AD4\u8AD5\u8AD7\u8ADD\u8ADF\u8AEC\u8AF0\u8AF4\u8AF5\u8AF6\u8AFC\u8AFF\u8B05\u8B06\u8B0B\u8B11\u8B1C\u8B1E\u8B1F\u8B0A\u8B2D\u8B30\u8B37\u8B3C\u8B42", 4, "\u8B48\u8B52\u8B53\u8B54\u8B59\u8B4D\u8B5E\u8B63\u8B6D\u8B76\u8B78\u8B79\u8B7C\u8B7E\u8B81\u8B84\u8B85\u8B8B\u8B8D\u8B8F\u8B94\u8B95\u8B9C\u8B9E\u8B9F\u8C38\u8C39\u8C3D\u8C3E\u8C45\u8C47\u8C49\u8C4B\u8C4F\u8C51\u8C53\u8C54\u8C57\u8C58\u8C5B\u8C5D\u8C59\u8C63\u8C64\u8C66\u8C68\u8C69\u8C6D\u8C73\u8C75\u8C76\u8C7B\u8C7E\u8C86"],
      ["8fdfa1", "\u8C87\u8C8B\u8C90\u8C92\u8C93\u8C99\u8C9B\u8C9C\u8CA4\u8CB9\u8CBA\u8CC5\u8CC6\u8CC9\u8CCB\u8CCF\u8CD6\u8CD5\u8CD9\u8CDD\u8CE1\u8CE8\u8CEC\u8CEF\u8CF0\u8CF2\u8CF5\u8CF7\u8CF8\u8CFE\u8CFF\u8D01\u8D03\u8D09\u8D12\u8D17\u8D1B\u8D65\u8D69\u8D6C\u8D6E\u8D7F\u8D82\u8D84\u8D88\u8D8D\u8D90\u8D91\u8D95\u8D9E\u8D9F\u8DA0\u8DA6\u8DAB\u8DAC\u8DAF\u8DB2\u8DB5\u8DB7\u8DB9\u8DBB\u8DC0\u8DC5\u8DC6\u8DC7\u8DC8\u8DCA\u8DCE\u8DD1\u8DD4\u8DD5\u8DD7\u8DD9\u8DE4\u8DE5\u8DE7\u8DEC\u8DF0\u8DBC\u8DF1\u8DF2\u8DF4\u8DFD\u8E01\u8E04\u8E05\u8E06\u8E0B\u8E11\u8E14\u8E16\u8E20\u8E21\u8E22"],
      ["8fe0a1", "\u8E23\u8E26\u8E27\u8E31\u8E33\u8E36\u8E37\u8E38\u8E39\u8E3D\u8E40\u8E41\u8E4B\u8E4D\u8E4E\u8E4F\u8E54\u8E5B\u8E5C\u8E5D\u8E5E\u8E61\u8E62\u8E69\u8E6C\u8E6D\u8E6F\u8E70\u8E71\u8E79\u8E7A\u8E7B\u8E82\u8E83\u8E89\u8E90\u8E92\u8E95\u8E9A\u8E9B\u8E9D\u8E9E\u8EA2\u8EA7\u8EA9\u8EAD\u8EAE\u8EB3\u8EB5\u8EBA\u8EBB\u8EC0\u8EC1\u8EC3\u8EC4\u8EC7\u8ECF\u8ED1\u8ED4\u8EDC\u8EE8\u8EEE\u8EF0\u8EF1\u8EF7\u8EF9\u8EFA\u8EED\u8F00\u8F02\u8F07\u8F08\u8F0F\u8F10\u8F16\u8F17\u8F18\u8F1E\u8F20\u8F21\u8F23\u8F25\u8F27\u8F28\u8F2C\u8F2D\u8F2E\u8F34\u8F35\u8F36\u8F37\u8F3A\u8F40\u8F41"],
      ["8fe1a1", "\u8F43\u8F47\u8F4F\u8F51", 4, "\u8F58\u8F5D\u8F5E\u8F65\u8F9D\u8FA0\u8FA1\u8FA4\u8FA5\u8FA6\u8FB5\u8FB6\u8FB8\u8FBE\u8FC0\u8FC1\u8FC6\u8FCA\u8FCB\u8FCD\u8FD0\u8FD2\u8FD3\u8FD5\u8FE0\u8FE3\u8FE4\u8FE8\u8FEE\u8FF1\u8FF5\u8FF6\u8FFB\u8FFE\u9002\u9004\u9008\u900C\u9018\u901B\u9028\u9029\u902F\u902A\u902C\u902D\u9033\u9034\u9037\u903F\u9043\u9044\u904C\u905B\u905D\u9062\u9066\u9067\u906C\u9070\u9074\u9079\u9085\u9088\u908B\u908C\u908E\u9090\u9095\u9097\u9098\u9099\u909B\u90A0\u90A1\u90A2\u90A5\u90B0\u90B2\u90B3\u90B4\u90B6\u90BD\u90CC\u90BE\u90C3"],
      ["8fe2a1", "\u90C4\u90C5\u90C7\u90C8\u90D5\u90D7\u90D8\u90D9\u90DC\u90DD\u90DF\u90E5\u90D2\u90F6\u90EB\u90EF\u90F0\u90F4\u90FE\u90FF\u9100\u9104\u9105\u9106\u9108\u910D\u9110\u9114\u9116\u9117\u9118\u911A\u911C\u911E\u9120\u9125\u9122\u9123\u9127\u9129\u912E\u912F\u9131\u9134\u9136\u9137\u9139\u913A\u913C\u913D\u9143\u9147\u9148\u914F\u9153\u9157\u9159\u915A\u915B\u9161\u9164\u9167\u916D\u9174\u9179\u917A\u917B\u9181\u9183\u9185\u9186\u918A\u918E\u9191\u9193\u9194\u9195\u9198\u919E\u91A1\u91A6\u91A8\u91AC\u91AD\u91AE\u91B0\u91B1\u91B2\u91B3\u91B6\u91BB\u91BC\u91BD\u91BF"],
      ["8fe3a1", "\u91C2\u91C3\u91C5\u91D3\u91D4\u91D7\u91D9\u91DA\u91DE\u91E4\u91E5\u91E9\u91EA\u91EC", 5, "\u91F7\u91F9\u91FB\u91FD\u9200\u9201\u9204\u9205\u9206\u9207\u9209\u920A\u920C\u9210\u9212\u9213\u9216\u9218\u921C\u921D\u9223\u9224\u9225\u9226\u9228\u922E\u922F\u9230\u9233\u9235\u9236\u9238\u9239\u923A\u923C\u923E\u9240\u9242\u9243\u9246\u9247\u924A\u924D\u924E\u924F\u9251\u9258\u9259\u925C\u925D\u9260\u9261\u9265\u9267\u9268\u9269\u926E\u926F\u9270\u9275", 4, "\u927B\u927C\u927D\u927F\u9288\u9289\u928A\u928D\u928E\u9292\u9297"],
      ["8fe4a1", "\u9299\u929F\u92A0\u92A4\u92A5\u92A7\u92A8\u92AB\u92AF\u92B2\u92B6\u92B8\u92BA\u92BB\u92BC\u92BD\u92BF", 4, "\u92C5\u92C6\u92C7\u92C8\u92CB\u92CC\u92CD\u92CE\u92D0\u92D3\u92D5\u92D7\u92D8\u92D9\u92DC\u92DD\u92DF\u92E0\u92E1\u92E3\u92E5\u92E7\u92E8\u92EC\u92EE\u92F0\u92F9\u92FB\u92FF\u9300\u9302\u9308\u930D\u9311\u9314\u9315\u931C\u931D\u931E\u931F\u9321\u9324\u9325\u9327\u9329\u932A\u9333\u9334\u9336\u9337\u9347\u9348\u9349\u9350\u9351\u9352\u9355\u9357\u9358\u935A\u935E\u9364\u9365\u9367\u9369\u936A\u936D\u936F\u9370\u9371\u9373\u9374\u9376"],
      ["8fe5a1", "\u937A\u937D\u937F\u9380\u9381\u9382\u9388\u938A\u938B\u938D\u938F\u9392\u9395\u9398\u939B\u939E\u93A1\u93A3\u93A4\u93A6\u93A8\u93AB\u93B4\u93B5\u93B6\u93BA\u93A9\u93C1\u93C4\u93C5\u93C6\u93C7\u93C9", 4, "\u93D3\u93D9\u93DC\u93DE\u93DF\u93E2\u93E6\u93E7\u93F9\u93F7\u93F8\u93FA\u93FB\u93FD\u9401\u9402\u9404\u9408\u9409\u940D\u940E\u940F\u9415\u9416\u9417\u941F\u942E\u942F\u9431\u9432\u9433\u9434\u943B\u943F\u943D\u9443\u9445\u9448\u944A\u944C\u9455\u9459\u945C\u945F\u9461\u9463\u9468\u946B\u946D\u946E\u946F\u9471\u9472\u9484\u9483\u9578\u9579"],
      ["8fe6a1", "\u957E\u9584\u9588\u958C\u958D\u958E\u959D\u959E\u959F\u95A1\u95A6\u95A9\u95AB\u95AC\u95B4\u95B6\u95BA\u95BD\u95BF\u95C6\u95C8\u95C9\u95CB\u95D0\u95D1\u95D2\u95D3\u95D9\u95DA\u95DD\u95DE\u95DF\u95E0\u95E4\u95E6\u961D\u961E\u9622\u9624\u9625\u9626\u962C\u9631\u9633\u9637\u9638\u9639\u963A\u963C\u963D\u9641\u9652\u9654\u9656\u9657\u9658\u9661\u966E\u9674\u967B\u967C\u967E\u967F\u9681\u9682\u9683\u9684\u9689\u9691\u9696\u969A\u969D\u969F\u96A4\u96A5\u96A6\u96A9\u96AE\u96AF\u96B3\u96BA\u96CA\u96D2\u5DB2\u96D8\u96DA\u96DD\u96DE\u96DF\u96E9\u96EF\u96F1\u96FA\u9702"],
      ["8fe7a1", "\u9703\u9705\u9709\u971A\u971B\u971D\u9721\u9722\u9723\u9728\u9731\u9733\u9741\u9743\u974A\u974E\u974F\u9755\u9757\u9758\u975A\u975B\u9763\u9767\u976A\u976E\u9773\u9776\u9777\u9778\u977B\u977D\u977F\u9780\u9789\u9795\u9796\u9797\u9799\u979A\u979E\u979F\u97A2\u97AC\u97AE\u97B1\u97B2\u97B5\u97B6\u97B8\u97B9\u97BA\u97BC\u97BE\u97BF\u97C1\u97C4\u97C5\u97C7\u97C9\u97CA\u97CC\u97CD\u97CE\u97D0\u97D1\u97D4\u97D7\u97D8\u97D9\u97DD\u97DE\u97E0\u97DB\u97E1\u97E4\u97EF\u97F1\u97F4\u97F7\u97F8\u97FA\u9807\u980A\u9819\u980D\u980E\u9814\u9816\u981C\u981E\u9820\u9823\u9826"],
      ["8fe8a1", "\u982B\u982E\u982F\u9830\u9832\u9833\u9835\u9825\u983E\u9844\u9847\u984A\u9851\u9852\u9853\u9856\u9857\u9859\u985A\u9862\u9863\u9865\u9866\u986A\u986C\u98AB\u98AD\u98AE\u98B0\u98B4\u98B7\u98B8\u98BA\u98BB\u98BF\u98C2\u98C5\u98C8\u98CC\u98E1\u98E3\u98E5\u98E6\u98E7\u98EA\u98F3\u98F6\u9902\u9907\u9908\u9911\u9915\u9916\u9917\u991A\u991B\u991C\u991F\u9922\u9926\u9927\u992B\u9931", 4, "\u9939\u993A\u993B\u993C\u9940\u9941\u9946\u9947\u9948\u994D\u994E\u9954\u9958\u9959\u995B\u995C\u995E\u995F\u9960\u999B\u999D\u999F\u99A6\u99B0\u99B1\u99B2\u99B5"],
      ["8fe9a1", "\u99B9\u99BA\u99BD\u99BF\u99C3\u99C9\u99D3\u99D4\u99D9\u99DA\u99DC\u99DE\u99E7\u99EA\u99EB\u99EC\u99F0\u99F4\u99F5\u99F9\u99FD\u99FE\u9A02\u9A03\u9A04\u9A0B\u9A0C\u9A10\u9A11\u9A16\u9A1E\u9A20\u9A22\u9A23\u9A24\u9A27\u9A2D\u9A2E\u9A33\u9A35\u9A36\u9A38\u9A47\u9A41\u9A44\u9A4A\u9A4B\u9A4C\u9A4E\u9A51\u9A54\u9A56\u9A5D\u9AAA\u9AAC\u9AAE\u9AAF\u9AB2\u9AB4\u9AB5\u9AB6\u9AB9\u9ABB\u9ABE\u9ABF\u9AC1\u9AC3\u9AC6\u9AC8\u9ACE\u9AD0\u9AD2\u9AD5\u9AD6\u9AD7\u9ADB\u9ADC\u9AE0\u9AE4\u9AE5\u9AE7\u9AE9\u9AEC\u9AF2\u9AF3\u9AF5\u9AF9\u9AFA\u9AFD\u9AFF", 4],
      ["8feaa1", "\u9B04\u9B05\u9B08\u9B09\u9B0B\u9B0C\u9B0D\u9B0E\u9B10\u9B12\u9B16\u9B19\u9B1B\u9B1C\u9B20\u9B26\u9B2B\u9B2D\u9B33\u9B34\u9B35\u9B37\u9B39\u9B3A\u9B3D\u9B48\u9B4B\u9B4C\u9B55\u9B56\u9B57\u9B5B\u9B5E\u9B61\u9B63\u9B65\u9B66\u9B68\u9B6A", 4, "\u9B73\u9B75\u9B77\u9B78\u9B79\u9B7F\u9B80\u9B84\u9B85\u9B86\u9B87\u9B89\u9B8A\u9B8B\u9B8D\u9B8F\u9B90\u9B94\u9B9A\u9B9D\u9B9E\u9BA6\u9BA7\u9BA9\u9BAC\u9BB0\u9BB1\u9BB2\u9BB7\u9BB8\u9BBB\u9BBC\u9BBE\u9BBF\u9BC1\u9BC7\u9BC8\u9BCE\u9BD0\u9BD7\u9BD8\u9BDD\u9BDF\u9BE5\u9BE7\u9BEA\u9BEB\u9BEF\u9BF3\u9BF7\u9BF8"],
      ["8feba1", "\u9BF9\u9BFA\u9BFD\u9BFF\u9C00\u9C02\u9C0B\u9C0F\u9C11\u9C16\u9C18\u9C19\u9C1A\u9C1C\u9C1E\u9C22\u9C23\u9C26", 4, "\u9C31\u9C35\u9C36\u9C37\u9C3D\u9C41\u9C43\u9C44\u9C45\u9C49\u9C4A\u9C4E\u9C4F\u9C50\u9C53\u9C54\u9C56\u9C58\u9C5B\u9C5D\u9C5E\u9C5F\u9C63\u9C69\u9C6A\u9C5C\u9C6B\u9C68\u9C6E\u9C70\u9C72\u9C75\u9C77\u9C7B\u9CE6\u9CF2\u9CF7\u9CF9\u9D0B\u9D02\u9D11\u9D17\u9D18\u9D1C\u9D1D\u9D1E\u9D2F\u9D30\u9D32\u9D33\u9D34\u9D3A\u9D3C\u9D45\u9D3D\u9D42\u9D43\u9D47\u9D4A\u9D53\u9D54\u9D5F\u9D63\u9D62\u9D65\u9D69\u9D6A\u9D6B\u9D70\u9D76\u9D77\u9D7B"],
      ["8feca1", "\u9D7C\u9D7E\u9D83\u9D84\u9D86\u9D8A\u9D8D\u9D8E\u9D92\u9D93\u9D95\u9D96\u9D97\u9D98\u9DA1\u9DAA\u9DAC\u9DAE\u9DB1\u9DB5\u9DB9\u9DBC\u9DBF\u9DC3\u9DC7\u9DC9\u9DCA\u9DD4\u9DD5\u9DD6\u9DD7\u9DDA\u9DDE\u9DDF\u9DE0\u9DE5\u9DE7\u9DE9\u9DEB\u9DEE\u9DF0\u9DF3\u9DF4\u9DFE\u9E0A\u9E02\u9E07\u9E0E\u9E10\u9E11\u9E12\u9E15\u9E16\u9E19\u9E1C\u9E1D\u9E7A\u9E7B\u9E7C\u9E80\u9E82\u9E83\u9E84\u9E85\u9E87\u9E8E\u9E8F\u9E96\u9E98\u9E9B\u9E9E\u9EA4\u9EA8\u9EAC\u9EAE\u9EAF\u9EB0\u9EB3\u9EB4\u9EB5\u9EC6\u9EC8\u9ECB\u9ED5\u9EDF\u9EE4\u9EE7\u9EEC\u9EED\u9EEE\u9EF0\u9EF1\u9EF2\u9EF5"],
      ["8feda1", "\u9EF8\u9EFF\u9F02\u9F03\u9F09\u9F0F\u9F10\u9F11\u9F12\u9F14\u9F16\u9F17\u9F19\u9F1A\u9F1B\u9F1F\u9F22\u9F26\u9F2A\u9F2B\u9F2F\u9F31\u9F32\u9F34\u9F37\u9F39\u9F3A\u9F3C\u9F3D\u9F3F\u9F41\u9F43", 4, "\u9F53\u9F55\u9F56\u9F57\u9F58\u9F5A\u9F5D\u9F5E\u9F68\u9F69\u9F6D", 4, "\u9F73\u9F75\u9F7A\u9F7D\u9F8F\u9F90\u9F91\u9F92\u9F94\u9F96\u9F97\u9F9E\u9FA1\u9FA2\u9FA3\u9FA5"]
    ];
  }
});

// packages/core/node_modules/iconv-lite/encodings/tables/cp936.json
var require_cp936 = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/tables/cp936.json"(exports2, module2) {
    module2.exports = [
      ["0", "\0", 127, "\u20AC"],
      ["8140", "\u4E02\u4E04\u4E05\u4E06\u4E0F\u4E12\u4E17\u4E1F\u4E20\u4E21\u4E23\u4E26\u4E29\u4E2E\u4E2F\u4E31\u4E33\u4E35\u4E37\u4E3C\u4E40\u4E41\u4E42\u4E44\u4E46\u4E4A\u4E51\u4E55\u4E57\u4E5A\u4E5B\u4E62\u4E63\u4E64\u4E65\u4E67\u4E68\u4E6A", 5, "\u4E72\u4E74", 9, "\u4E7F", 6, "\u4E87\u4E8A"],
      ["8180", "\u4E90\u4E96\u4E97\u4E99\u4E9C\u4E9D\u4E9E\u4EA3\u4EAA\u4EAF\u4EB0\u4EB1\u4EB4\u4EB6\u4EB7\u4EB8\u4EB9\u4EBC\u4EBD\u4EBE\u4EC8\u4ECC\u4ECF\u4ED0\u4ED2\u4EDA\u4EDB\u4EDC\u4EE0\u4EE2\u4EE6\u4EE7\u4EE9\u4EED\u4EEE\u4EEF\u4EF1\u4EF4\u4EF8\u4EF9\u4EFA\u4EFC\u4EFE\u4F00\u4F02", 6, "\u4F0B\u4F0C\u4F12", 4, "\u4F1C\u4F1D\u4F21\u4F23\u4F28\u4F29\u4F2C\u4F2D\u4F2E\u4F31\u4F33\u4F35\u4F37\u4F39\u4F3B\u4F3E", 4, "\u4F44\u4F45\u4F47", 5, "\u4F52\u4F54\u4F56\u4F61\u4F62\u4F66\u4F68\u4F6A\u4F6B\u4F6D\u4F6E\u4F71\u4F72\u4F75\u4F77\u4F78\u4F79\u4F7A\u4F7D\u4F80\u4F81\u4F82\u4F85\u4F86\u4F87\u4F8A\u4F8C\u4F8E\u4F90\u4F92\u4F93\u4F95\u4F96\u4F98\u4F99\u4F9A\u4F9C\u4F9E\u4F9F\u4FA1\u4FA2"],
      ["8240", "\u4FA4\u4FAB\u4FAD\u4FB0", 4, "\u4FB6", 8, "\u4FC0\u4FC1\u4FC2\u4FC6\u4FC7\u4FC8\u4FC9\u4FCB\u4FCC\u4FCD\u4FD2", 4, "\u4FD9\u4FDB\u4FE0\u4FE2\u4FE4\u4FE5\u4FE7\u4FEB\u4FEC\u4FF0\u4FF2\u4FF4\u4FF5\u4FF6\u4FF7\u4FF9\u4FFB\u4FFC\u4FFD\u4FFF", 11],
      ["8280", "\u500B\u500E\u5010\u5011\u5013\u5015\u5016\u5017\u501B\u501D\u501E\u5020\u5022\u5023\u5024\u5027\u502B\u502F", 10, "\u503B\u503D\u503F\u5040\u5041\u5042\u5044\u5045\u5046\u5049\u504A\u504B\u504D\u5050", 4, "\u5056\u5057\u5058\u5059\u505B\u505D", 7, "\u5066", 5, "\u506D", 8, "\u5078\u5079\u507A\u507C\u507D\u5081\u5082\u5083\u5084\u5086\u5087\u5089\u508A\u508B\u508C\u508E", 20, "\u50A4\u50A6\u50AA\u50AB\u50AD", 4, "\u50B3", 6, "\u50BC"],
      ["8340", "\u50BD", 17, "\u50D0", 5, "\u50D7\u50D8\u50D9\u50DB", 10, "\u50E8\u50E9\u50EA\u50EB\u50EF\u50F0\u50F1\u50F2\u50F4\u50F6", 4, "\u50FC", 9, "\u5108"],
      ["8380", "\u5109\u510A\u510C", 5, "\u5113", 13, "\u5122", 28, "\u5142\u5147\u514A\u514C\u514E\u514F\u5150\u5152\u5153\u5157\u5158\u5159\u515B\u515D", 4, "\u5163\u5164\u5166\u5167\u5169\u516A\u516F\u5172\u517A\u517E\u517F\u5183\u5184\u5186\u5187\u518A\u518B\u518E\u518F\u5190\u5191\u5193\u5194\u5198\u519A\u519D\u519E\u519F\u51A1\u51A3\u51A6", 4, "\u51AD\u51AE\u51B4\u51B8\u51B9\u51BA\u51BE\u51BF\u51C1\u51C2\u51C3\u51C5\u51C8\u51CA\u51CD\u51CE\u51D0\u51D2", 5],
      ["8440", "\u51D8\u51D9\u51DA\u51DC\u51DE\u51DF\u51E2\u51E3\u51E5", 5, "\u51EC\u51EE\u51F1\u51F2\u51F4\u51F7\u51FE\u5204\u5205\u5209\u520B\u520C\u520F\u5210\u5213\u5214\u5215\u521C\u521E\u521F\u5221\u5222\u5223\u5225\u5226\u5227\u522A\u522C\u522F\u5231\u5232\u5234\u5235\u523C\u523E\u5244", 5, "\u524B\u524E\u524F\u5252\u5253\u5255\u5257\u5258"],
      ["8480", "\u5259\u525A\u525B\u525D\u525F\u5260\u5262\u5263\u5264\u5266\u5268\u526B\u526C\u526D\u526E\u5270\u5271\u5273", 9, "\u527E\u5280\u5283", 4, "\u5289", 6, "\u5291\u5292\u5294", 6, "\u529C\u52A4\u52A5\u52A6\u52A7\u52AE\u52AF\u52B0\u52B4", 9, "\u52C0\u52C1\u52C2\u52C4\u52C5\u52C6\u52C8\u52CA\u52CC\u52CD\u52CE\u52CF\u52D1\u52D3\u52D4\u52D5\u52D7\u52D9", 5, "\u52E0\u52E1\u52E2\u52E3\u52E5", 10, "\u52F1", 7, "\u52FB\u52FC\u52FD\u5301\u5302\u5303\u5304\u5307\u5309\u530A\u530B\u530C\u530E"],
      ["8540", "\u5311\u5312\u5313\u5314\u5318\u531B\u531C\u531E\u531F\u5322\u5324\u5325\u5327\u5328\u5329\u532B\u532C\u532D\u532F", 9, "\u533C\u533D\u5340\u5342\u5344\u5346\u534B\u534C\u534D\u5350\u5354\u5358\u5359\u535B\u535D\u5365\u5368\u536A\u536C\u536D\u5372\u5376\u5379\u537B\u537C\u537D\u537E\u5380\u5381\u5383\u5387\u5388\u538A\u538E\u538F"],
      ["8580", "\u5390", 4, "\u5396\u5397\u5399\u539B\u539C\u539E\u53A0\u53A1\u53A4\u53A7\u53AA\u53AB\u53AC\u53AD\u53AF", 6, "\u53B7\u53B8\u53B9\u53BA\u53BC\u53BD\u53BE\u53C0\u53C3", 4, "\u53CE\u53CF\u53D0\u53D2\u53D3\u53D5\u53DA\u53DC\u53DD\u53DE\u53E1\u53E2\u53E7\u53F4\u53FA\u53FE\u53FF\u5400\u5402\u5405\u5407\u540B\u5414\u5418\u5419\u541A\u541C\u5422\u5424\u5425\u542A\u5430\u5433\u5436\u5437\u543A\u543D\u543F\u5441\u5442\u5444\u5445\u5447\u5449\u544C\u544D\u544E\u544F\u5451\u545A\u545D", 4, "\u5463\u5465\u5467\u5469", 7, "\u5474\u5479\u547A\u547E\u547F\u5481\u5483\u5485\u5487\u5488\u5489\u548A\u548D\u5491\u5493\u5497\u5498\u549C\u549E\u549F\u54A0\u54A1"],
      ["8640", "\u54A2\u54A5\u54AE\u54B0\u54B2\u54B5\u54B6\u54B7\u54B9\u54BA\u54BC\u54BE\u54C3\u54C5\u54CA\u54CB\u54D6\u54D8\u54DB\u54E0", 4, "\u54EB\u54EC\u54EF\u54F0\u54F1\u54F4", 5, "\u54FB\u54FE\u5500\u5502\u5503\u5504\u5505\u5508\u550A", 4, "\u5512\u5513\u5515", 5, "\u551C\u551D\u551E\u551F\u5521\u5525\u5526"],
      ["8680", "\u5528\u5529\u552B\u552D\u5532\u5534\u5535\u5536\u5538\u5539\u553A\u553B\u553D\u5540\u5542\u5545\u5547\u5548\u554B", 4, "\u5551\u5552\u5553\u5554\u5557", 4, "\u555D\u555E\u555F\u5560\u5562\u5563\u5568\u5569\u556B\u556F", 5, "\u5579\u557A\u557D\u557F\u5585\u5586\u558C\u558D\u558E\u5590\u5592\u5593\u5595\u5596\u5597\u559A\u559B\u559E\u55A0", 6, "\u55A8", 8, "\u55B2\u55B4\u55B6\u55B8\u55BA\u55BC\u55BF", 4, "\u55C6\u55C7\u55C8\u55CA\u55CB\u55CE\u55CF\u55D0\u55D5\u55D7", 4, "\u55DE\u55E0\u55E2\u55E7\u55E9\u55ED\u55EE\u55F0\u55F1\u55F4\u55F6\u55F8", 4, "\u55FF\u5602\u5603\u5604\u5605"],
      ["8740", "\u5606\u5607\u560A\u560B\u560D\u5610", 7, "\u5619\u561A\u561C\u561D\u5620\u5621\u5622\u5625\u5626\u5628\u5629\u562A\u562B\u562E\u562F\u5630\u5633\u5635\u5637\u5638\u563A\u563C\u563D\u563E\u5640", 11, "\u564F", 4, "\u5655\u5656\u565A\u565B\u565D", 4],
      ["8780", "\u5663\u5665\u5666\u5667\u566D\u566E\u566F\u5670\u5672\u5673\u5674\u5675\u5677\u5678\u5679\u567A\u567D", 7, "\u5687", 6, "\u5690\u5691\u5692\u5694", 14, "\u56A4", 10, "\u56B0", 6, "\u56B8\u56B9\u56BA\u56BB\u56BD", 12, "\u56CB", 8, "\u56D5\u56D6\u56D8\u56D9\u56DC\u56E3\u56E5", 5, "\u56EC\u56EE\u56EF\u56F2\u56F3\u56F6\u56F7\u56F8\u56FB\u56FC\u5700\u5701\u5702\u5705\u5707\u570B", 6],
      ["8840", "\u5712", 9, "\u571D\u571E\u5720\u5721\u5722\u5724\u5725\u5726\u5727\u572B\u5731\u5732\u5734", 4, "\u573C\u573D\u573F\u5741\u5743\u5744\u5745\u5746\u5748\u5749\u574B\u5752", 4, "\u5758\u5759\u5762\u5763\u5765\u5767\u576C\u576E\u5770\u5771\u5772\u5774\u5775\u5778\u5779\u577A\u577D\u577E\u577F\u5780"],
      ["8880", "\u5781\u5787\u5788\u5789\u578A\u578D", 4, "\u5794", 6, "\u579C\u579D\u579E\u579F\u57A5\u57A8\u57AA\u57AC\u57AF\u57B0\u57B1\u57B3\u57B5\u57B6\u57B7\u57B9", 8, "\u57C4", 6, "\u57CC\u57CD\u57D0\u57D1\u57D3\u57D6\u57D7\u57DB\u57DC\u57DE\u57E1\u57E2\u57E3\u57E5", 7, "\u57EE\u57F0\u57F1\u57F2\u57F3\u57F5\u57F6\u57F7\u57FB\u57FC\u57FE\u57FF\u5801\u5803\u5804\u5805\u5808\u5809\u580A\u580C\u580E\u580F\u5810\u5812\u5813\u5814\u5816\u5817\u5818\u581A\u581B\u581C\u581D\u581F\u5822\u5823\u5825", 4, "\u582B", 4, "\u5831\u5832\u5833\u5834\u5836", 7],
      ["8940", "\u583E", 5, "\u5845", 6, "\u584E\u584F\u5850\u5852\u5853\u5855\u5856\u5857\u5859", 4, "\u585F", 5, "\u5866", 4, "\u586D", 16, "\u587F\u5882\u5884\u5886\u5887\u5888\u588A\u588B\u588C"],
      ["8980", "\u588D", 4, "\u5894", 4, "\u589B\u589C\u589D\u58A0", 7, "\u58AA", 17, "\u58BD\u58BE\u58BF\u58C0\u58C2\u58C3\u58C4\u58C6", 10, "\u58D2\u58D3\u58D4\u58D6", 13, "\u58E5", 5, "\u58ED\u58EF\u58F1\u58F2\u58F4\u58F5\u58F7\u58F8\u58FA", 7, "\u5903\u5905\u5906\u5908", 4, "\u590E\u5910\u5911\u5912\u5913\u5917\u5918\u591B\u591D\u591E\u5920\u5921\u5922\u5923\u5926\u5928\u592C\u5930\u5932\u5933\u5935\u5936\u593B"],
      ["8a40", "\u593D\u593E\u593F\u5940\u5943\u5945\u5946\u594A\u594C\u594D\u5950\u5952\u5953\u5959\u595B", 4, "\u5961\u5963\u5964\u5966", 12, "\u5975\u5977\u597A\u597B\u597C\u597E\u597F\u5980\u5985\u5989\u598B\u598C\u598E\u598F\u5990\u5991\u5994\u5995\u5998\u599A\u599B\u599C\u599D\u599F\u59A0\u59A1\u59A2\u59A6"],
      ["8a80", "\u59A7\u59AC\u59AD\u59B0\u59B1\u59B3", 5, "\u59BA\u59BC\u59BD\u59BF", 6, "\u59C7\u59C8\u59C9\u59CC\u59CD\u59CE\u59CF\u59D5\u59D6\u59D9\u59DB\u59DE", 4, "\u59E4\u59E6\u59E7\u59E9\u59EA\u59EB\u59ED", 11, "\u59FA\u59FC\u59FD\u59FE\u5A00\u5A02\u5A0A\u5A0B\u5A0D\u5A0E\u5A0F\u5A10\u5A12\u5A14\u5A15\u5A16\u5A17\u5A19\u5A1A\u5A1B\u5A1D\u5A1E\u5A21\u5A22\u5A24\u5A26\u5A27\u5A28\u5A2A", 6, "\u5A33\u5A35\u5A37", 4, "\u5A3D\u5A3E\u5A3F\u5A41", 4, "\u5A47\u5A48\u5A4B", 9, "\u5A56\u5A57\u5A58\u5A59\u5A5B", 5],
      ["8b40", "\u5A61\u5A63\u5A64\u5A65\u5A66\u5A68\u5A69\u5A6B", 8, "\u5A78\u5A79\u5A7B\u5A7C\u5A7D\u5A7E\u5A80", 17, "\u5A93", 6, "\u5A9C", 13, "\u5AAB\u5AAC"],
      ["8b80", "\u5AAD", 4, "\u5AB4\u5AB6\u5AB7\u5AB9", 4, "\u5ABF\u5AC0\u5AC3", 5, "\u5ACA\u5ACB\u5ACD", 4, "\u5AD3\u5AD5\u5AD7\u5AD9\u5ADA\u5ADB\u5ADD\u5ADE\u5ADF\u5AE2\u5AE4\u5AE5\u5AE7\u5AE8\u5AEA\u5AEC", 4, "\u5AF2", 22, "\u5B0A", 11, "\u5B18", 25, "\u5B33\u5B35\u5B36\u5B38", 7, "\u5B41", 6],
      ["8c40", "\u5B48", 7, "\u5B52\u5B56\u5B5E\u5B60\u5B61\u5B67\u5B68\u5B6B\u5B6D\u5B6E\u5B6F\u5B72\u5B74\u5B76\u5B77\u5B78\u5B79\u5B7B\u5B7C\u5B7E\u5B7F\u5B82\u5B86\u5B8A\u5B8D\u5B8E\u5B90\u5B91\u5B92\u5B94\u5B96\u5B9F\u5BA7\u5BA8\u5BA9\u5BAC\u5BAD\u5BAE\u5BAF\u5BB1\u5BB2\u5BB7\u5BBA\u5BBB\u5BBC\u5BC0\u5BC1\u5BC3\u5BC8\u5BC9\u5BCA\u5BCB\u5BCD\u5BCE\u5BCF"],
      ["8c80", "\u5BD1\u5BD4", 8, "\u5BE0\u5BE2\u5BE3\u5BE6\u5BE7\u5BE9", 4, "\u5BEF\u5BF1", 6, "\u5BFD\u5BFE\u5C00\u5C02\u5C03\u5C05\u5C07\u5C08\u5C0B\u5C0C\u5C0D\u5C0E\u5C10\u5C12\u5C13\u5C17\u5C19\u5C1B\u5C1E\u5C1F\u5C20\u5C21\u5C23\u5C26\u5C28\u5C29\u5C2A\u5C2B\u5C2D\u5C2E\u5C2F\u5C30\u5C32\u5C33\u5C35\u5C36\u5C37\u5C43\u5C44\u5C46\u5C47\u5C4C\u5C4D\u5C52\u5C53\u5C54\u5C56\u5C57\u5C58\u5C5A\u5C5B\u5C5C\u5C5D\u5C5F\u5C62\u5C64\u5C67", 6, "\u5C70\u5C72", 6, "\u5C7B\u5C7C\u5C7D\u5C7E\u5C80\u5C83", 4, "\u5C89\u5C8A\u5C8B\u5C8E\u5C8F\u5C92\u5C93\u5C95\u5C9D", 4, "\u5CA4", 4],
      ["8d40", "\u5CAA\u5CAE\u5CAF\u5CB0\u5CB2\u5CB4\u5CB6\u5CB9\u5CBA\u5CBB\u5CBC\u5CBE\u5CC0\u5CC2\u5CC3\u5CC5", 5, "\u5CCC", 5, "\u5CD3", 5, "\u5CDA", 6, "\u5CE2\u5CE3\u5CE7\u5CE9\u5CEB\u5CEC\u5CEE\u5CEF\u5CF1", 9, "\u5CFC", 4],
      ["8d80", "\u5D01\u5D04\u5D05\u5D08", 5, "\u5D0F", 4, "\u5D15\u5D17\u5D18\u5D19\u5D1A\u5D1C\u5D1D\u5D1F", 4, "\u5D25\u5D28\u5D2A\u5D2B\u5D2C\u5D2F", 4, "\u5D35", 7, "\u5D3F", 7, "\u5D48\u5D49\u5D4D", 10, "\u5D59\u5D5A\u5D5C\u5D5E", 10, "\u5D6A\u5D6D\u5D6E\u5D70\u5D71\u5D72\u5D73\u5D75", 12, "\u5D83", 21, "\u5D9A\u5D9B\u5D9C\u5D9E\u5D9F\u5DA0"],
      ["8e40", "\u5DA1", 21, "\u5DB8", 12, "\u5DC6", 6, "\u5DCE", 12, "\u5DDC\u5DDF\u5DE0\u5DE3\u5DE4\u5DEA\u5DEC\u5DED"],
      ["8e80", "\u5DF0\u5DF5\u5DF6\u5DF8", 4, "\u5DFF\u5E00\u5E04\u5E07\u5E09\u5E0A\u5E0B\u5E0D\u5E0E\u5E12\u5E13\u5E17\u5E1E", 7, "\u5E28", 4, "\u5E2F\u5E30\u5E32", 4, "\u5E39\u5E3A\u5E3E\u5E3F\u5E40\u5E41\u5E43\u5E46", 5, "\u5E4D", 6, "\u5E56", 4, "\u5E5C\u5E5D\u5E5F\u5E60\u5E63", 14, "\u5E75\u5E77\u5E79\u5E7E\u5E81\u5E82\u5E83\u5E85\u5E88\u5E89\u5E8C\u5E8D\u5E8E\u5E92\u5E98\u5E9B\u5E9D\u5EA1\u5EA2\u5EA3\u5EA4\u5EA8", 4, "\u5EAE", 4, "\u5EB4\u5EBA\u5EBB\u5EBC\u5EBD\u5EBF", 6],
      ["8f40", "\u5EC6\u5EC7\u5EC8\u5ECB", 5, "\u5ED4\u5ED5\u5ED7\u5ED8\u5ED9\u5EDA\u5EDC", 11, "\u5EE9\u5EEB", 8, "\u5EF5\u5EF8\u5EF9\u5EFB\u5EFC\u5EFD\u5F05\u5F06\u5F07\u5F09\u5F0C\u5F0D\u5F0E\u5F10\u5F12\u5F14\u5F16\u5F19\u5F1A\u5F1C\u5F1D\u5F1E\u5F21\u5F22\u5F23\u5F24"],
      ["8f80", "\u5F28\u5F2B\u5F2C\u5F2E\u5F30\u5F32", 6, "\u5F3B\u5F3D\u5F3E\u5F3F\u5F41", 14, "\u5F51\u5F54\u5F59\u5F5A\u5F5B\u5F5C\u5F5E\u5F5F\u5F60\u5F63\u5F65\u5F67\u5F68\u5F6B\u5F6E\u5F6F\u5F72\u5F74\u5F75\u5F76\u5F78\u5F7A\u5F7D\u5F7E\u5F7F\u5F83\u5F86\u5F8D\u5F8E\u5F8F\u5F91\u5F93\u5F94\u5F96\u5F9A\u5F9B\u5F9D\u5F9E\u5F9F\u5FA0\u5FA2", 5, "\u5FA9\u5FAB\u5FAC\u5FAF", 5, "\u5FB6\u5FB8\u5FB9\u5FBA\u5FBB\u5FBE", 4, "\u5FC7\u5FC8\u5FCA\u5FCB\u5FCE\u5FD3\u5FD4\u5FD5\u5FDA\u5FDB\u5FDC\u5FDE\u5FDF\u5FE2\u5FE3\u5FE5\u5FE6\u5FE8\u5FE9\u5FEC\u5FEF\u5FF0\u5FF2\u5FF3\u5FF4\u5FF6\u5FF7\u5FF9\u5FFA\u5FFC\u6007"],
      ["9040", "\u6008\u6009\u600B\u600C\u6010\u6011\u6013\u6017\u6018\u601A\u601E\u601F\u6022\u6023\u6024\u602C\u602D\u602E\u6030", 4, "\u6036", 4, "\u603D\u603E\u6040\u6044", 6, "\u604C\u604E\u604F\u6051\u6053\u6054\u6056\u6057\u6058\u605B\u605C\u605E\u605F\u6060\u6061\u6065\u6066\u606E\u6071\u6072\u6074\u6075\u6077\u607E\u6080"],
      ["9080", "\u6081\u6082\u6085\u6086\u6087\u6088\u608A\u608B\u608E\u608F\u6090\u6091\u6093\u6095\u6097\u6098\u6099\u609C\u609E\u60A1\u60A2\u60A4\u60A5\u60A7\u60A9\u60AA\u60AE\u60B0\u60B3\u60B5\u60B6\u60B7\u60B9\u60BA\u60BD", 7, "\u60C7\u60C8\u60C9\u60CC", 4, "\u60D2\u60D3\u60D4\u60D6\u60D7\u60D9\u60DB\u60DE\u60E1", 4, "\u60EA\u60F1\u60F2\u60F5\u60F7\u60F8\u60FB", 4, "\u6102\u6103\u6104\u6105\u6107\u610A\u610B\u610C\u6110", 4, "\u6116\u6117\u6118\u6119\u611B\u611C\u611D\u611E\u6121\u6122\u6125\u6128\u6129\u612A\u612C", 18, "\u6140", 6],
      ["9140", "\u6147\u6149\u614B\u614D\u614F\u6150\u6152\u6153\u6154\u6156", 6, "\u615E\u615F\u6160\u6161\u6163\u6164\u6165\u6166\u6169", 6, "\u6171\u6172\u6173\u6174\u6176\u6178", 18, "\u618C\u618D\u618F", 4, "\u6195"],
      ["9180", "\u6196", 6, "\u619E", 8, "\u61AA\u61AB\u61AD", 9, "\u61B8", 5, "\u61BF\u61C0\u61C1\u61C3", 4, "\u61C9\u61CC", 4, "\u61D3\u61D5", 16, "\u61E7", 13, "\u61F6", 8, "\u6200", 5, "\u6207\u6209\u6213\u6214\u6219\u621C\u621D\u621E\u6220\u6223\u6226\u6227\u6228\u6229\u622B\u622D\u622F\u6230\u6231\u6232\u6235\u6236\u6238", 4, "\u6242\u6244\u6245\u6246\u624A"],
      ["9240", "\u624F\u6250\u6255\u6256\u6257\u6259\u625A\u625C", 6, "\u6264\u6265\u6268\u6271\u6272\u6274\u6275\u6277\u6278\u627A\u627B\u627D\u6281\u6282\u6283\u6285\u6286\u6287\u6288\u628B", 5, "\u6294\u6299\u629C\u629D\u629E\u62A3\u62A6\u62A7\u62A9\u62AA\u62AD\u62AE\u62AF\u62B0\u62B2\u62B3\u62B4\u62B6\u62B7\u62B8\u62BA\u62BE\u62C0\u62C1"],
      ["9280", "\u62C3\u62CB\u62CF\u62D1\u62D5\u62DD\u62DE\u62E0\u62E1\u62E4\u62EA\u62EB\u62F0\u62F2\u62F5\u62F8\u62F9\u62FA\u62FB\u6300\u6303\u6304\u6305\u6306\u630A\u630B\u630C\u630D\u630F\u6310\u6312\u6313\u6314\u6315\u6317\u6318\u6319\u631C\u6326\u6327\u6329\u632C\u632D\u632E\u6330\u6331\u6333", 5, "\u633B\u633C\u633E\u633F\u6340\u6341\u6344\u6347\u6348\u634A\u6351\u6352\u6353\u6354\u6356", 7, "\u6360\u6364\u6365\u6366\u6368\u636A\u636B\u636C\u636F\u6370\u6372\u6373\u6374\u6375\u6378\u6379\u637C\u637D\u637E\u637F\u6381\u6383\u6384\u6385\u6386\u638B\u638D\u6391\u6393\u6394\u6395\u6397\u6399", 6, "\u63A1\u63A4\u63A6\u63AB\u63AF\u63B1\u63B2\u63B5\u63B6\u63B9\u63BB\u63BD\u63BF\u63C0"],
      ["9340", "\u63C1\u63C2\u63C3\u63C5\u63C7\u63C8\u63CA\u63CB\u63CC\u63D1\u63D3\u63D4\u63D5\u63D7", 6, "\u63DF\u63E2\u63E4", 4, "\u63EB\u63EC\u63EE\u63EF\u63F0\u63F1\u63F3\u63F5\u63F7\u63F9\u63FA\u63FB\u63FC\u63FE\u6403\u6404\u6406", 4, "\u640D\u640E\u6411\u6412\u6415", 5, "\u641D\u641F\u6422\u6423\u6424"],
      ["9380", "\u6425\u6427\u6428\u6429\u642B\u642E", 5, "\u6435", 4, "\u643B\u643C\u643E\u6440\u6442\u6443\u6449\u644B", 6, "\u6453\u6455\u6456\u6457\u6459", 4, "\u645F", 7, "\u6468\u646A\u646B\u646C\u646E", 9, "\u647B", 6, "\u6483\u6486\u6488", 8, "\u6493\u6494\u6497\u6498\u649A\u649B\u649C\u649D\u649F", 4, "\u64A5\u64A6\u64A7\u64A8\u64AA\u64AB\u64AF\u64B1\u64B2\u64B3\u64B4\u64B6\u64B9\u64BB\u64BD\u64BE\u64BF\u64C1\u64C3\u64C4\u64C6", 6, "\u64CF\u64D1\u64D3\u64D4\u64D5\u64D6\u64D9\u64DA"],
      ["9440", "\u64DB\u64DC\u64DD\u64DF\u64E0\u64E1\u64E3\u64E5\u64E7", 24, "\u6501", 7, "\u650A", 7, "\u6513", 4, "\u6519", 8],
      ["9480", "\u6522\u6523\u6524\u6526", 4, "\u652C\u652D\u6530\u6531\u6532\u6533\u6537\u653A\u653C\u653D\u6540", 4, "\u6546\u6547\u654A\u654B\u654D\u654E\u6550\u6552\u6553\u6554\u6557\u6558\u655A\u655C\u655F\u6560\u6561\u6564\u6565\u6567\u6568\u6569\u656A\u656D\u656E\u656F\u6571\u6573\u6575\u6576\u6578", 14, "\u6588\u6589\u658A\u658D\u658E\u658F\u6592\u6594\u6595\u6596\u6598\u659A\u659D\u659E\u65A0\u65A2\u65A3\u65A6\u65A8\u65AA\u65AC\u65AE\u65B1", 7, "\u65BA\u65BB\u65BE\u65BF\u65C0\u65C2\u65C7\u65C8\u65C9\u65CA\u65CD\u65D0\u65D1\u65D3\u65D4\u65D5\u65D8", 7, "\u65E1\u65E3\u65E4\u65EA\u65EB"],
      ["9540", "\u65F2\u65F3\u65F4\u65F5\u65F8\u65F9\u65FB", 4, "\u6601\u6604\u6605\u6607\u6608\u6609\u660B\u660D\u6610\u6611\u6612\u6616\u6617\u6618\u661A\u661B\u661C\u661E\u6621\u6622\u6623\u6624\u6626\u6629\u662A\u662B\u662C\u662E\u6630\u6632\u6633\u6637", 4, "\u663D\u663F\u6640\u6642\u6644", 6, "\u664D\u664E\u6650\u6651\u6658"],
      ["9580", "\u6659\u665B\u665C\u665D\u665E\u6660\u6662\u6663\u6665\u6667\u6669", 4, "\u6671\u6672\u6673\u6675\u6678\u6679\u667B\u667C\u667D\u667F\u6680\u6681\u6683\u6685\u6686\u6688\u6689\u668A\u668B\u668D\u668E\u668F\u6690\u6692\u6693\u6694\u6695\u6698", 4, "\u669E", 8, "\u66A9", 4, "\u66AF", 4, "\u66B5\u66B6\u66B7\u66B8\u66BA\u66BB\u66BC\u66BD\u66BF", 25, "\u66DA\u66DE", 7, "\u66E7\u66E8\u66EA", 5, "\u66F1\u66F5\u66F6\u66F8\u66FA\u66FB\u66FD\u6701\u6702\u6703"],
      ["9640", "\u6704\u6705\u6706\u6707\u670C\u670E\u670F\u6711\u6712\u6713\u6716\u6718\u6719\u671A\u671C\u671E\u6720", 5, "\u6727\u6729\u672E\u6730\u6732\u6733\u6736\u6737\u6738\u6739\u673B\u673C\u673E\u673F\u6741\u6744\u6745\u6747\u674A\u674B\u674D\u6752\u6754\u6755\u6757", 4, "\u675D\u6762\u6763\u6764\u6766\u6767\u676B\u676C\u676E\u6771\u6774\u6776"],
      ["9680", "\u6778\u6779\u677A\u677B\u677D\u6780\u6782\u6783\u6785\u6786\u6788\u678A\u678C\u678D\u678E\u678F\u6791\u6792\u6793\u6794\u6796\u6799\u679B\u679F\u67A0\u67A1\u67A4\u67A6\u67A9\u67AC\u67AE\u67B1\u67B2\u67B4\u67B9", 7, "\u67C2\u67C5", 9, "\u67D5\u67D6\u67D7\u67DB\u67DF\u67E1\u67E3\u67E4\u67E6\u67E7\u67E8\u67EA\u67EB\u67ED\u67EE\u67F2\u67F5", 7, "\u67FE\u6801\u6802\u6803\u6804\u6806\u680D\u6810\u6812\u6814\u6815\u6818", 4, "\u681E\u681F\u6820\u6822", 6, "\u682B", 6, "\u6834\u6835\u6836\u683A\u683B\u683F\u6847\u684B\u684D\u684F\u6852\u6856", 5],
      ["9740", "\u685C\u685D\u685E\u685F\u686A\u686C", 7, "\u6875\u6878", 8, "\u6882\u6884\u6887", 7, "\u6890\u6891\u6892\u6894\u6895\u6896\u6898", 9, "\u68A3\u68A4\u68A5\u68A9\u68AA\u68AB\u68AC\u68AE\u68B1\u68B2\u68B4\u68B6\u68B7\u68B8"],
      ["9780", "\u68B9", 6, "\u68C1\u68C3", 5, "\u68CA\u68CC\u68CE\u68CF\u68D0\u68D1\u68D3\u68D4\u68D6\u68D7\u68D9\u68DB", 4, "\u68E1\u68E2\u68E4", 9, "\u68EF\u68F2\u68F3\u68F4\u68F6\u68F7\u68F8\u68FB\u68FD\u68FE\u68FF\u6900\u6902\u6903\u6904\u6906", 4, "\u690C\u690F\u6911\u6913", 11, "\u6921\u6922\u6923\u6925", 7, "\u692E\u692F\u6931\u6932\u6933\u6935\u6936\u6937\u6938\u693A\u693B\u693C\u693E\u6940\u6941\u6943", 16, "\u6955\u6956\u6958\u6959\u695B\u695C\u695F"],
      ["9840", "\u6961\u6962\u6964\u6965\u6967\u6968\u6969\u696A\u696C\u696D\u696F\u6970\u6972", 4, "\u697A\u697B\u697D\u697E\u697F\u6981\u6983\u6985\u698A\u698B\u698C\u698E", 5, "\u6996\u6997\u6999\u699A\u699D", 9, "\u69A9\u69AA\u69AC\u69AE\u69AF\u69B0\u69B2\u69B3\u69B5\u69B6\u69B8\u69B9\u69BA\u69BC\u69BD"],
      ["9880", "\u69BE\u69BF\u69C0\u69C2", 7, "\u69CB\u69CD\u69CF\u69D1\u69D2\u69D3\u69D5", 5, "\u69DC\u69DD\u69DE\u69E1", 11, "\u69EE\u69EF\u69F0\u69F1\u69F3", 9, "\u69FE\u6A00", 9, "\u6A0B", 11, "\u6A19", 5, "\u6A20\u6A22", 5, "\u6A29\u6A2B\u6A2C\u6A2D\u6A2E\u6A30\u6A32\u6A33\u6A34\u6A36", 6, "\u6A3F", 4, "\u6A45\u6A46\u6A48", 7, "\u6A51", 6, "\u6A5A"],
      ["9940", "\u6A5C", 4, "\u6A62\u6A63\u6A64\u6A66", 10, "\u6A72", 6, "\u6A7A\u6A7B\u6A7D\u6A7E\u6A7F\u6A81\u6A82\u6A83\u6A85", 8, "\u6A8F\u6A92", 4, "\u6A98", 7, "\u6AA1", 5],
      ["9980", "\u6AA7\u6AA8\u6AAA\u6AAD", 114, "\u6B25\u6B26\u6B28", 6],
      ["9a40", "\u6B2F\u6B30\u6B31\u6B33\u6B34\u6B35\u6B36\u6B38\u6B3B\u6B3C\u6B3D\u6B3F\u6B40\u6B41\u6B42\u6B44\u6B45\u6B48\u6B4A\u6B4B\u6B4D", 11, "\u6B5A", 7, "\u6B68\u6B69\u6B6B", 13, "\u6B7A\u6B7D\u6B7E\u6B7F\u6B80\u6B85\u6B88"],
      ["9a80", "\u6B8C\u6B8E\u6B8F\u6B90\u6B91\u6B94\u6B95\u6B97\u6B98\u6B99\u6B9C", 4, "\u6BA2", 7, "\u6BAB", 7, "\u6BB6\u6BB8", 6, "\u6BC0\u6BC3\u6BC4\u6BC6", 4, "\u6BCC\u6BCE\u6BD0\u6BD1\u6BD8\u6BDA\u6BDC", 4, "\u6BE2", 7, "\u6BEC\u6BED\u6BEE\u6BF0\u6BF1\u6BF2\u6BF4\u6BF6\u6BF7\u6BF8\u6BFA\u6BFB\u6BFC\u6BFE", 6, "\u6C08", 4, "\u6C0E\u6C12\u6C17\u6C1C\u6C1D\u6C1E\u6C20\u6C23\u6C25\u6C2B\u6C2C\u6C2D\u6C31\u6C33\u6C36\u6C37\u6C39\u6C3A\u6C3B\u6C3C\u6C3E\u6C3F\u6C43\u6C44\u6C45\u6C48\u6C4B", 4, "\u6C51\u6C52\u6C53\u6C56\u6C58"],
      ["9b40", "\u6C59\u6C5A\u6C62\u6C63\u6C65\u6C66\u6C67\u6C6B", 4, "\u6C71\u6C73\u6C75\u6C77\u6C78\u6C7A\u6C7B\u6C7C\u6C7F\u6C80\u6C84\u6C87\u6C8A\u6C8B\u6C8D\u6C8E\u6C91\u6C92\u6C95\u6C96\u6C97\u6C98\u6C9A\u6C9C\u6C9D\u6C9E\u6CA0\u6CA2\u6CA8\u6CAC\u6CAF\u6CB0\u6CB4\u6CB5\u6CB6\u6CB7\u6CBA\u6CC0\u6CC1\u6CC2\u6CC3\u6CC6\u6CC7\u6CC8\u6CCB\u6CCD\u6CCE\u6CCF\u6CD1\u6CD2\u6CD8"],
      ["9b80", "\u6CD9\u6CDA\u6CDC\u6CDD\u6CDF\u6CE4\u6CE6\u6CE7\u6CE9\u6CEC\u6CED\u6CF2\u6CF4\u6CF9\u6CFF\u6D00\u6D02\u6D03\u6D05\u6D06\u6D08\u6D09\u6D0A\u6D0D\u6D0F\u6D10\u6D11\u6D13\u6D14\u6D15\u6D16\u6D18\u6D1C\u6D1D\u6D1F", 5, "\u6D26\u6D28\u6D29\u6D2C\u6D2D\u6D2F\u6D30\u6D34\u6D36\u6D37\u6D38\u6D3A\u6D3F\u6D40\u6D42\u6D44\u6D49\u6D4C\u6D50\u6D55\u6D56\u6D57\u6D58\u6D5B\u6D5D\u6D5F\u6D61\u6D62\u6D64\u6D65\u6D67\u6D68\u6D6B\u6D6C\u6D6D\u6D70\u6D71\u6D72\u6D73\u6D75\u6D76\u6D79\u6D7A\u6D7B\u6D7D", 4, "\u6D83\u6D84\u6D86\u6D87\u6D8A\u6D8B\u6D8D\u6D8F\u6D90\u6D92\u6D96", 4, "\u6D9C\u6DA2\u6DA5\u6DAC\u6DAD\u6DB0\u6DB1\u6DB3\u6DB4\u6DB6\u6DB7\u6DB9", 5, "\u6DC1\u6DC2\u6DC3\u6DC8\u6DC9\u6DCA"],
      ["9c40", "\u6DCD\u6DCE\u6DCF\u6DD0\u6DD2\u6DD3\u6DD4\u6DD5\u6DD7\u6DDA\u6DDB\u6DDC\u6DDF\u6DE2\u6DE3\u6DE5\u6DE7\u6DE8\u6DE9\u6DEA\u6DED\u6DEF\u6DF0\u6DF2\u6DF4\u6DF5\u6DF6\u6DF8\u6DFA\u6DFD", 7, "\u6E06\u6E07\u6E08\u6E09\u6E0B\u6E0F\u6E12\u6E13\u6E15\u6E18\u6E19\u6E1B\u6E1C\u6E1E\u6E1F\u6E22\u6E26\u6E27\u6E28\u6E2A\u6E2C\u6E2E\u6E30\u6E31\u6E33\u6E35"],
      ["9c80", "\u6E36\u6E37\u6E39\u6E3B", 7, "\u6E45", 7, "\u6E4F\u6E50\u6E51\u6E52\u6E55\u6E57\u6E59\u6E5A\u6E5C\u6E5D\u6E5E\u6E60", 10, "\u6E6C\u6E6D\u6E6F", 14, "\u6E80\u6E81\u6E82\u6E84\u6E87\u6E88\u6E8A", 4, "\u6E91", 6, "\u6E99\u6E9A\u6E9B\u6E9D\u6E9E\u6EA0\u6EA1\u6EA3\u6EA4\u6EA6\u6EA8\u6EA9\u6EAB\u6EAC\u6EAD\u6EAE\u6EB0\u6EB3\u6EB5\u6EB8\u6EB9\u6EBC\u6EBE\u6EBF\u6EC0\u6EC3\u6EC4\u6EC5\u6EC6\u6EC8\u6EC9\u6ECA\u6ECC\u6ECD\u6ECE\u6ED0\u6ED2\u6ED6\u6ED8\u6ED9\u6EDB\u6EDC\u6EDD\u6EE3\u6EE7\u6EEA", 5],
      ["9d40", "\u6EF0\u6EF1\u6EF2\u6EF3\u6EF5\u6EF6\u6EF7\u6EF8\u6EFA", 7, "\u6F03\u6F04\u6F05\u6F07\u6F08\u6F0A", 4, "\u6F10\u6F11\u6F12\u6F16", 9, "\u6F21\u6F22\u6F23\u6F25\u6F26\u6F27\u6F28\u6F2C\u6F2E\u6F30\u6F32\u6F34\u6F35\u6F37", 6, "\u6F3F\u6F40\u6F41\u6F42"],
      ["9d80", "\u6F43\u6F44\u6F45\u6F48\u6F49\u6F4A\u6F4C\u6F4E", 9, "\u6F59\u6F5A\u6F5B\u6F5D\u6F5F\u6F60\u6F61\u6F63\u6F64\u6F65\u6F67", 5, "\u6F6F\u6F70\u6F71\u6F73\u6F75\u6F76\u6F77\u6F79\u6F7B\u6F7D", 6, "\u6F85\u6F86\u6F87\u6F8A\u6F8B\u6F8F", 12, "\u6F9D\u6F9E\u6F9F\u6FA0\u6FA2", 4, "\u6FA8", 10, "\u6FB4\u6FB5\u6FB7\u6FB8\u6FBA", 5, "\u6FC1\u6FC3", 5, "\u6FCA", 6, "\u6FD3", 10, "\u6FDF\u6FE2\u6FE3\u6FE4\u6FE5"],
      ["9e40", "\u6FE6", 7, "\u6FF0", 32, "\u7012", 7, "\u701C", 6, "\u7024", 6],
      ["9e80", "\u702B", 9, "\u7036\u7037\u7038\u703A", 17, "\u704D\u704E\u7050", 13, "\u705F", 11, "\u706E\u7071\u7072\u7073\u7074\u7077\u7079\u707A\u707B\u707D\u7081\u7082\u7083\u7084\u7086\u7087\u7088\u708B\u708C\u708D\u708F\u7090\u7091\u7093\u7097\u7098\u709A\u709B\u709E", 12, "\u70B0\u70B2\u70B4\u70B5\u70B6\u70BA\u70BE\u70BF\u70C4\u70C5\u70C6\u70C7\u70C9\u70CB", 12, "\u70DA"],
      ["9f40", "\u70DC\u70DD\u70DE\u70E0\u70E1\u70E2\u70E3\u70E5\u70EA\u70EE\u70F0", 6, "\u70F8\u70FA\u70FB\u70FC\u70FE", 10, "\u710B", 4, "\u7111\u7112\u7114\u7117\u711B", 10, "\u7127", 7, "\u7132\u7133\u7134"],
      ["9f80", "\u7135\u7137", 13, "\u7146\u7147\u7148\u7149\u714B\u714D\u714F", 12, "\u715D\u715F", 4, "\u7165\u7169", 4, "\u716F\u7170\u7171\u7174\u7175\u7176\u7177\u7179\u717B\u717C\u717E", 5, "\u7185", 4, "\u718B\u718C\u718D\u718E\u7190\u7191\u7192\u7193\u7195\u7196\u7197\u719A", 4, "\u71A1", 6, "\u71A9\u71AA\u71AB\u71AD", 5, "\u71B4\u71B6\u71B7\u71B8\u71BA", 8, "\u71C4", 9, "\u71CF", 4],
      ["a040", "\u71D6", 9, "\u71E1\u71E2\u71E3\u71E4\u71E6\u71E8", 5, "\u71EF", 9, "\u71FA", 11, "\u7207", 19],
      ["a080", "\u721B\u721C\u721E", 9, "\u7229\u722B\u722D\u722E\u722F\u7232\u7233\u7234\u723A\u723C\u723E\u7240", 6, "\u7249\u724A\u724B\u724E\u724F\u7250\u7251\u7253\u7254\u7255\u7257\u7258\u725A\u725C\u725E\u7260\u7263\u7264\u7265\u7268\u726A\u726B\u726C\u726D\u7270\u7271\u7273\u7274\u7276\u7277\u7278\u727B\u727C\u727D\u7282\u7283\u7285", 4, "\u728C\u728E\u7290\u7291\u7293", 11, "\u72A0", 11, "\u72AE\u72B1\u72B2\u72B3\u72B5\u72BA", 6, "\u72C5\u72C6\u72C7\u72C9\u72CA\u72CB\u72CC\u72CF\u72D1\u72D3\u72D4\u72D5\u72D6\u72D8\u72DA\u72DB"],
      ["a1a1", "\u3000\u3001\u3002\xB7\u02C9\u02C7\xA8\u3003\u3005\u2014\uFF5E\u2016\u2026\u2018\u2019\u201C\u201D\u3014\u3015\u3008", 7, "\u3016\u3017\u3010\u3011\xB1\xD7\xF7\u2236\u2227\u2228\u2211\u220F\u222A\u2229\u2208\u2237\u221A\u22A5\u2225\u2220\u2312\u2299\u222B\u222E\u2261\u224C\u2248\u223D\u221D\u2260\u226E\u226F\u2264\u2265\u221E\u2235\u2234\u2642\u2640\xB0\u2032\u2033\u2103\uFF04\xA4\uFFE0\uFFE1\u2030\xA7\u2116\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u203B\u2192\u2190\u2191\u2193\u3013"],
      ["a2a1", "\u2170", 9],
      ["a2b1", "\u2488", 19, "\u2474", 19, "\u2460", 9],
      ["a2e5", "\u3220", 9],
      ["a2f1", "\u2160", 11],
      ["a3a1", "\uFF01\uFF02\uFF03\uFFE5\uFF05", 88, "\uFFE3"],
      ["a4a1", "\u3041", 82],
      ["a5a1", "\u30A1", 85],
      ["a6a1", "\u0391", 16, "\u03A3", 6],
      ["a6c1", "\u03B1", 16, "\u03C3", 6],
      ["a6e0", "\uFE35\uFE36\uFE39\uFE3A\uFE3F\uFE40\uFE3D\uFE3E\uFE41\uFE42\uFE43\uFE44"],
      ["a6ee", "\uFE3B\uFE3C\uFE37\uFE38\uFE31"],
      ["a6f4", "\uFE33\uFE34"],
      ["a7a1", "\u0410", 5, "\u0401\u0416", 25],
      ["a7d1", "\u0430", 5, "\u0451\u0436", 25],
      ["a840", "\u02CA\u02CB\u02D9\u2013\u2015\u2025\u2035\u2105\u2109\u2196\u2197\u2198\u2199\u2215\u221F\u2223\u2252\u2266\u2267\u22BF\u2550", 35, "\u2581", 6],
      ["a880", "\u2588", 7, "\u2593\u2594\u2595\u25BC\u25BD\u25E2\u25E3\u25E4\u25E5\u2609\u2295\u3012\u301D\u301E"],
      ["a8a1", "\u0101\xE1\u01CE\xE0\u0113\xE9\u011B\xE8\u012B\xED\u01D0\xEC\u014D\xF3\u01D2\xF2\u016B\xFA\u01D4\xF9\u01D6\u01D8\u01DA\u01DC\xFC\xEA\u0251"],
      ["a8bd", "\u0144\u0148"],
      ["a8c0", "\u0261"],
      ["a8c5", "\u3105", 36],
      ["a940", "\u3021", 8, "\u32A3\u338E\u338F\u339C\u339D\u339E\u33A1\u33C4\u33CE\u33D1\u33D2\u33D5\uFE30\uFFE2\uFFE4"],
      ["a959", "\u2121\u3231"],
      ["a95c", "\u2010"],
      ["a960", "\u30FC\u309B\u309C\u30FD\u30FE\u3006\u309D\u309E\uFE49", 9, "\uFE54\uFE55\uFE56\uFE57\uFE59", 8],
      ["a980", "\uFE62", 4, "\uFE68\uFE69\uFE6A\uFE6B"],
      ["a996", "\u3007"],
      ["a9a4", "\u2500", 75],
      ["aa40", "\u72DC\u72DD\u72DF\u72E2", 5, "\u72EA\u72EB\u72F5\u72F6\u72F9\u72FD\u72FE\u72FF\u7300\u7302\u7304", 5, "\u730B\u730C\u730D\u730F\u7310\u7311\u7312\u7314\u7318\u7319\u731A\u731F\u7320\u7323\u7324\u7326\u7327\u7328\u732D\u732F\u7330\u7332\u7333\u7335\u7336\u733A\u733B\u733C\u733D\u7340", 8],
      ["aa80", "\u7349\u734A\u734B\u734C\u734E\u734F\u7351\u7353\u7354\u7355\u7356\u7358", 7, "\u7361", 10, "\u736E\u7370\u7371"],
      ["ab40", "\u7372", 11, "\u737F", 4, "\u7385\u7386\u7388\u738A\u738C\u738D\u738F\u7390\u7392\u7393\u7394\u7395\u7397\u7398\u7399\u739A\u739C\u739D\u739E\u73A0\u73A1\u73A3", 5, "\u73AA\u73AC\u73AD\u73B1\u73B4\u73B5\u73B6\u73B8\u73B9\u73BC\u73BD\u73BE\u73BF\u73C1\u73C3", 4],
      ["ab80", "\u73CB\u73CC\u73CE\u73D2", 6, "\u73DA\u73DB\u73DC\u73DD\u73DF\u73E1\u73E2\u73E3\u73E4\u73E6\u73E8\u73EA\u73EB\u73EC\u73EE\u73EF\u73F0\u73F1\u73F3", 4],
      ["ac40", "\u73F8", 10, "\u7404\u7407\u7408\u740B\u740C\u740D\u740E\u7411", 8, "\u741C", 5, "\u7423\u7424\u7427\u7429\u742B\u742D\u742F\u7431\u7432\u7437", 4, "\u743D\u743E\u743F\u7440\u7442", 11],
      ["ac80", "\u744E", 6, "\u7456\u7458\u745D\u7460", 12, "\u746E\u746F\u7471", 4, "\u7478\u7479\u747A"],
      ["ad40", "\u747B\u747C\u747D\u747F\u7482\u7484\u7485\u7486\u7488\u7489\u748A\u748C\u748D\u748F\u7491", 10, "\u749D\u749F", 7, "\u74AA", 15, "\u74BB", 12],
      ["ad80", "\u74C8", 9, "\u74D3", 8, "\u74DD\u74DF\u74E1\u74E5\u74E7", 6, "\u74F0\u74F1\u74F2"],
      ["ae40", "\u74F3\u74F5\u74F8", 6, "\u7500\u7501\u7502\u7503\u7505", 7, "\u750E\u7510\u7512\u7514\u7515\u7516\u7517\u751B\u751D\u751E\u7520", 4, "\u7526\u7527\u752A\u752E\u7534\u7536\u7539\u753C\u753D\u753F\u7541\u7542\u7543\u7544\u7546\u7547\u7549\u754A\u754D\u7550\u7551\u7552\u7553\u7555\u7556\u7557\u7558"],
      ["ae80", "\u755D", 7, "\u7567\u7568\u7569\u756B", 6, "\u7573\u7575\u7576\u7577\u757A", 4, "\u7580\u7581\u7582\u7584\u7585\u7587"],
      ["af40", "\u7588\u7589\u758A\u758C\u758D\u758E\u7590\u7593\u7595\u7598\u759B\u759C\u759E\u75A2\u75A6", 4, "\u75AD\u75B6\u75B7\u75BA\u75BB\u75BF\u75C0\u75C1\u75C6\u75CB\u75CC\u75CE\u75CF\u75D0\u75D1\u75D3\u75D7\u75D9\u75DA\u75DC\u75DD\u75DF\u75E0\u75E1\u75E5\u75E9\u75EC\u75ED\u75EE\u75EF\u75F2\u75F3\u75F5\u75F6\u75F7\u75F8\u75FA\u75FB\u75FD\u75FE\u7602\u7604\u7606\u7607"],
      ["af80", "\u7608\u7609\u760B\u760D\u760E\u760F\u7611\u7612\u7613\u7614\u7616\u761A\u761C\u761D\u761E\u7621\u7623\u7627\u7628\u762C\u762E\u762F\u7631\u7632\u7636\u7637\u7639\u763A\u763B\u763D\u7641\u7642\u7644"],
      ["b040", "\u7645", 6, "\u764E", 5, "\u7655\u7657", 4, "\u765D\u765F\u7660\u7661\u7662\u7664", 6, "\u766C\u766D\u766E\u7670", 7, "\u7679\u767A\u767C\u767F\u7680\u7681\u7683\u7685\u7689\u768A\u768C\u768D\u768F\u7690\u7692\u7694\u7695\u7697\u7698\u769A\u769B"],
      ["b080", "\u769C", 7, "\u76A5", 8, "\u76AF\u76B0\u76B3\u76B5", 9, "\u76C0\u76C1\u76C3\u554A\u963F\u57C3\u6328\u54CE\u5509\u54C0\u7691\u764C\u853C\u77EE\u827E\u788D\u7231\u9698\u978D\u6C28\u5B89\u4FFA\u6309\u6697\u5CB8\u80FA\u6848\u80AE\u6602\u76CE\u51F9\u6556\u71AC\u7FF1\u8884\u50B2\u5965\u61CA\u6FB3\u82AD\u634C\u6252\u53ED\u5427\u7B06\u516B\u75A4\u5DF4\u62D4\u8DCB\u9776\u628A\u8019\u575D\u9738\u7F62\u7238\u767D\u67CF\u767E\u6446\u4F70\u8D25\u62DC\u7A17\u6591\u73ED\u642C\u6273\u822C\u9881\u677F\u7248\u626E\u62CC\u4F34\u74E3\u534A\u529E\u7ECA\u90A6\u5E2E\u6886\u699C\u8180\u7ED1\u68D2\u78C5\u868C\u9551\u508D\u8C24\u82DE\u80DE\u5305\u8912\u5265"],
      ["b140", "\u76C4\u76C7\u76C9\u76CB\u76CC\u76D3\u76D5\u76D9\u76DA\u76DC\u76DD\u76DE\u76E0", 4, "\u76E6", 7, "\u76F0\u76F3\u76F5\u76F6\u76F7\u76FA\u76FB\u76FD\u76FF\u7700\u7702\u7703\u7705\u7706\u770A\u770C\u770E", 10, "\u771B\u771C\u771D\u771E\u7721\u7723\u7724\u7725\u7727\u772A\u772B"],
      ["b180", "\u772C\u772E\u7730", 4, "\u7739\u773B\u773D\u773E\u773F\u7742\u7744\u7745\u7746\u7748", 7, "\u7752", 7, "\u775C\u8584\u96F9\u4FDD\u5821\u9971\u5B9D\u62B1\u62A5\u66B4\u8C79\u9C8D\u7206\u676F\u7891\u60B2\u5351\u5317\u8F88\u80CC\u8D1D\u94A1\u500D\u72C8\u5907\u60EB\u7119\u88AB\u5954\u82EF\u672C\u7B28\u5D29\u7EF7\u752D\u6CF5\u8E66\u8FF8\u903C\u9F3B\u6BD4\u9119\u7B14\u5F7C\u78A7\u84D6\u853D\u6BD5\u6BD9\u6BD6\u5E01\u5E87\u75F9\u95ED\u655D\u5F0A\u5FC5\u8F9F\u58C1\u81C2\u907F\u965B\u97AD\u8FB9\u7F16\u8D2C\u6241\u4FBF\u53D8\u535E\u8FA8\u8FA9\u8FAB\u904D\u6807\u5F6A\u8198\u8868\u9CD6\u618B\u522B\u762A\u5F6C\u658C\u6FD2\u6EE8\u5BBE\u6448\u5175\u51B0\u67C4\u4E19\u79C9\u997C\u70B3"],
      ["b240", "\u775D\u775E\u775F\u7760\u7764\u7767\u7769\u776A\u776D", 11, "\u777A\u777B\u777C\u7781\u7782\u7783\u7786", 5, "\u778F\u7790\u7793", 11, "\u77A1\u77A3\u77A4\u77A6\u77A8\u77AB\u77AD\u77AE\u77AF\u77B1\u77B2\u77B4\u77B6", 4],
      ["b280", "\u77BC\u77BE\u77C0", 12, "\u77CE", 8, "\u77D8\u77D9\u77DA\u77DD", 4, "\u77E4\u75C5\u5E76\u73BB\u83E0\u64AD\u62E8\u94B5\u6CE2\u535A\u52C3\u640F\u94C2\u7B94\u4F2F\u5E1B\u8236\u8116\u818A\u6E24\u6CCA\u9A73\u6355\u535C\u54FA\u8865\u57E0\u4E0D\u5E03\u6B65\u7C3F\u90E8\u6016\u64E6\u731C\u88C1\u6750\u624D\u8D22\u776C\u8E29\u91C7\u5F69\u83DC\u8521\u9910\u53C2\u8695\u6B8B\u60ED\u60E8\u707F\u82CD\u8231\u4ED3\u6CA7\u85CF\u64CD\u7CD9\u69FD\u66F9\u8349\u5395\u7B56\u4FA7\u518C\u6D4B\u5C42\u8E6D\u63D2\u53C9\u832C\u8336\u67E5\u78B4\u643D\u5BDF\u5C94\u5DEE\u8BE7\u62C6\u67F4\u8C7A\u6400\u63BA\u8749\u998B\u8C17\u7F20\u94F2\u4EA7\u9610\u98A4\u660C\u7316"],
      ["b340", "\u77E6\u77E8\u77EA\u77EF\u77F0\u77F1\u77F2\u77F4\u77F5\u77F7\u77F9\u77FA\u77FB\u77FC\u7803", 5, "\u780A\u780B\u780E\u780F\u7810\u7813\u7815\u7819\u781B\u781E\u7820\u7821\u7822\u7824\u7828\u782A\u782B\u782E\u782F\u7831\u7832\u7833\u7835\u7836\u783D\u783F\u7841\u7842\u7843\u7844\u7846\u7848\u7849\u784A\u784B\u784D\u784F\u7851\u7853\u7854\u7858\u7859\u785A"],
      ["b380", "\u785B\u785C\u785E", 11, "\u786F", 7, "\u7878\u7879\u787A\u787B\u787D", 6, "\u573A\u5C1D\u5E38\u957F\u507F\u80A0\u5382\u655E\u7545\u5531\u5021\u8D85\u6284\u949E\u671D\u5632\u6F6E\u5DE2\u5435\u7092\u8F66\u626F\u64A4\u63A3\u5F7B\u6F88\u90F4\u81E3\u8FB0\u5C18\u6668\u5FF1\u6C89\u9648\u8D81\u886C\u6491\u79F0\u57CE\u6A59\u6210\u5448\u4E58\u7A0B\u60E9\u6F84\u8BDA\u627F\u901E\u9A8B\u79E4\u5403\u75F4\u6301\u5319\u6C60\u8FDF\u5F1B\u9A70\u803B\u9F7F\u4F88\u5C3A\u8D64\u7FC5\u65A5\u70BD\u5145\u51B2\u866B\u5D07\u5BA0\u62BD\u916C\u7574\u8E0C\u7A20\u6101\u7B79\u4EC7\u7EF8\u7785\u4E11\u81ED\u521D\u51FA\u6A71\u53A8\u8E87\u9504\u96CF\u6EC1\u9664\u695A"],
      ["b440", "\u7884\u7885\u7886\u7888\u788A\u788B\u788F\u7890\u7892\u7894\u7895\u7896\u7899\u789D\u789E\u78A0\u78A2\u78A4\u78A6\u78A8", 7, "\u78B5\u78B6\u78B7\u78B8\u78BA\u78BB\u78BC\u78BD\u78BF\u78C0\u78C2\u78C3\u78C4\u78C6\u78C7\u78C8\u78CC\u78CD\u78CE\u78CF\u78D1\u78D2\u78D3\u78D6\u78D7\u78D8\u78DA", 9],
      ["b480", "\u78E4\u78E5\u78E6\u78E7\u78E9\u78EA\u78EB\u78ED", 4, "\u78F3\u78F5\u78F6\u78F8\u78F9\u78FB", 5, "\u7902\u7903\u7904\u7906", 6, "\u7840\u50A8\u77D7\u6410\u89E6\u5904\u63E3\u5DDD\u7A7F\u693D\u4F20\u8239\u5598\u4E32\u75AE\u7A97\u5E62\u5E8A\u95EF\u521B\u5439\u708A\u6376\u9524\u5782\u6625\u693F\u9187\u5507\u6DF3\u7EAF\u8822\u6233\u7EF0\u75B5\u8328\u78C1\u96CC\u8F9E\u6148\u74F7\u8BCD\u6B64\u523A\u8D50\u6B21\u806A\u8471\u56F1\u5306\u4ECE\u4E1B\u51D1\u7C97\u918B\u7C07\u4FC3\u8E7F\u7BE1\u7A9C\u6467\u5D14\u50AC\u8106\u7601\u7CB9\u6DEC\u7FE0\u6751\u5B58\u5BF8\u78CB\u64AE\u6413\u63AA\u632B\u9519\u642D\u8FBE\u7B54\u7629\u6253\u5927\u5446\u6B79\u50A3\u6234\u5E26\u6B86\u4EE3\u8D37\u888B\u5F85\u902E"],
      ["b540", "\u790D", 5, "\u7914", 9, "\u791F", 4, "\u7925", 14, "\u7935", 4, "\u793D\u793F\u7942\u7943\u7944\u7945\u7947\u794A", 8, "\u7954\u7955\u7958\u7959\u7961\u7963"],
      ["b580", "\u7964\u7966\u7969\u796A\u796B\u796C\u796E\u7970", 6, "\u7979\u797B", 4, "\u7982\u7983\u7986\u7987\u7988\u7989\u798B\u798C\u798D\u798E\u7990\u7991\u7992\u6020\u803D\u62C5\u4E39\u5355\u90F8\u63B8\u80C6\u65E6\u6C2E\u4F46\u60EE\u6DE1\u8BDE\u5F39\u86CB\u5F53\u6321\u515A\u8361\u6863\u5200\u6363\u8E48\u5012\u5C9B\u7977\u5BFC\u5230\u7A3B\u60BC\u9053\u76D7\u5FB7\u5F97\u7684\u8E6C\u706F\u767B\u7B49\u77AA\u51F3\u9093\u5824\u4F4E\u6EF4\u8FEA\u654C\u7B1B\u72C4\u6DA4\u7FDF\u5AE1\u62B5\u5E95\u5730\u8482\u7B2C\u5E1D\u5F1F\u9012\u7F14\u98A0\u6382\u6EC7\u7898\u70B9\u5178\u975B\u57AB\u7535\u4F43\u7538\u5E97\u60E6\u5960\u6DC0\u6BBF\u7889\u53FC\u96D5\u51CB\u5201\u6389\u540A\u9493\u8C03\u8DCC\u7239\u789F\u8776\u8FED\u8C0D\u53E0"],
      ["b640", "\u7993", 6, "\u799B", 11, "\u79A8", 10, "\u79B4", 4, "\u79BC\u79BF\u79C2\u79C4\u79C5\u79C7\u79C8\u79CA\u79CC\u79CE\u79CF\u79D0\u79D3\u79D4\u79D6\u79D7\u79D9", 5, "\u79E0\u79E1\u79E2\u79E5\u79E8\u79EA"],
      ["b680", "\u79EC\u79EE\u79F1", 6, "\u79F9\u79FA\u79FC\u79FE\u79FF\u7A01\u7A04\u7A05\u7A07\u7A08\u7A09\u7A0A\u7A0C\u7A0F", 4, "\u7A15\u7A16\u7A18\u7A19\u7A1B\u7A1C\u4E01\u76EF\u53EE\u9489\u9876\u9F0E\u952D\u5B9A\u8BA2\u4E22\u4E1C\u51AC\u8463\u61C2\u52A8\u680B\u4F97\u606B\u51BB\u6D1E\u515C\u6296\u6597\u9661\u8C46\u9017\u75D8\u90FD\u7763\u6BD2\u728A\u72EC\u8BFB\u5835\u7779\u8D4C\u675C\u9540\u809A\u5EA6\u6E21\u5992\u7AEF\u77ED\u953B\u6BB5\u65AD\u7F0E\u5806\u5151\u961F\u5BF9\u58A9\u5428\u8E72\u6566\u987F\u56E4\u949D\u76FE\u9041\u6387\u54C6\u591A\u593A\u579B\u8EB2\u6735\u8DFA\u8235\u5241\u60F0\u5815\u86FE\u5CE8\u9E45\u4FC4\u989D\u8BB9\u5A25\u6076\u5384\u627C\u904F\u9102\u997F\u6069\u800C\u513F\u8033\u5C14\u9975\u6D31\u4E8C"],
      ["b740", "\u7A1D\u7A1F\u7A21\u7A22\u7A24", 14, "\u7A34\u7A35\u7A36\u7A38\u7A3A\u7A3E\u7A40", 5, "\u7A47", 9, "\u7A52", 4, "\u7A58", 16],
      ["b780", "\u7A69", 6, "\u7A71\u7A72\u7A73\u7A75\u7A7B\u7A7C\u7A7D\u7A7E\u7A82\u7A85\u7A87\u7A89\u7A8A\u7A8B\u7A8C\u7A8E\u7A8F\u7A90\u7A93\u7A94\u7A99\u7A9A\u7A9B\u7A9E\u7AA1\u7AA2\u8D30\u53D1\u7F5A\u7B4F\u4F10\u4E4F\u9600\u6CD5\u73D0\u85E9\u5E06\u756A\u7FFB\u6A0A\u77FE\u9492\u7E41\u51E1\u70E6\u53CD\u8FD4\u8303\u8D29\u72AF\u996D\u6CDB\u574A\u82B3\u65B9\u80AA\u623F\u9632\u59A8\u4EFF\u8BBF\u7EBA\u653E\u83F2\u975E\u5561\u98DE\u80A5\u532A\u8BFD\u5420\u80BA\u5E9F\u6CB8\u8D39\u82AC\u915A\u5429\u6C1B\u5206\u7EB7\u575F\u711A\u6C7E\u7C89\u594B\u4EFD\u5FFF\u6124\u7CAA\u4E30\u5C01\u67AB\u8702\u5CF0\u950B\u98CE\u75AF\u70FD\u9022\u51AF\u7F1D\u8BBD\u5949\u51E4\u4F5B\u5426\u592B\u6577\u80A4\u5B75\u6276\u62C2\u8F90\u5E45\u6C1F\u7B26\u4F0F\u4FD8\u670D"],
      ["b840", "\u7AA3\u7AA4\u7AA7\u7AA9\u7AAA\u7AAB\u7AAE", 4, "\u7AB4", 10, "\u7AC0", 10, "\u7ACC", 9, "\u7AD7\u7AD8\u7ADA\u7ADB\u7ADC\u7ADD\u7AE1\u7AE2\u7AE4\u7AE7", 5, "\u7AEE\u7AF0\u7AF1\u7AF2\u7AF3"],
      ["b880", "\u7AF4", 4, "\u7AFB\u7AFC\u7AFE\u7B00\u7B01\u7B02\u7B05\u7B07\u7B09\u7B0C\u7B0D\u7B0E\u7B10\u7B12\u7B13\u7B16\u7B17\u7B18\u7B1A\u7B1C\u7B1D\u7B1F\u7B21\u7B22\u7B23\u7B27\u7B29\u7B2D\u6D6E\u6DAA\u798F\u88B1\u5F17\u752B\u629A\u8F85\u4FEF\u91DC\u65A7\u812F\u8151\u5E9C\u8150\u8D74\u526F\u8986\u8D4B\u590D\u5085\u4ED8\u961C\u7236\u8179\u8D1F\u5BCC\u8BA3\u9644\u5987\u7F1A\u5490\u5676\u560E\u8BE5\u6539\u6982\u9499\u76D6\u6E89\u5E72\u7518\u6746\u67D1\u7AFF\u809D\u8D76\u611F\u79C6\u6562\u8D63\u5188\u521A\u94A2\u7F38\u809B\u7EB2\u5C97\u6E2F\u6760\u7BD9\u768B\u9AD8\u818F\u7F94\u7CD5\u641E\u9550\u7A3F\u544A\u54E5\u6B4C\u6401\u6208\u9E3D\u80F3\u7599\u5272\u9769\u845B\u683C\u86E4\u9601\u9694\u94EC\u4E2A\u5404\u7ED9\u6839\u8DDF\u8015\u66F4\u5E9A\u7FB9"],
      ["b940", "\u7B2F\u7B30\u7B32\u7B34\u7B35\u7B36\u7B37\u7B39\u7B3B\u7B3D\u7B3F", 5, "\u7B46\u7B48\u7B4A\u7B4D\u7B4E\u7B53\u7B55\u7B57\u7B59\u7B5C\u7B5E\u7B5F\u7B61\u7B63", 10, "\u7B6F\u7B70\u7B73\u7B74\u7B76\u7B78\u7B7A\u7B7C\u7B7D\u7B7F\u7B81\u7B82\u7B83\u7B84\u7B86", 6, "\u7B8E\u7B8F"],
      ["b980", "\u7B91\u7B92\u7B93\u7B96\u7B98\u7B99\u7B9A\u7B9B\u7B9E\u7B9F\u7BA0\u7BA3\u7BA4\u7BA5\u7BAE\u7BAF\u7BB0\u7BB2\u7BB3\u7BB5\u7BB6\u7BB7\u7BB9", 7, "\u7BC2\u7BC3\u7BC4\u57C2\u803F\u6897\u5DE5\u653B\u529F\u606D\u9F9A\u4F9B\u8EAC\u516C\u5BAB\u5F13\u5DE9\u6C5E\u62F1\u8D21\u5171\u94A9\u52FE\u6C9F\u82DF\u72D7\u57A2\u6784\u8D2D\u591F\u8F9C\u83C7\u5495\u7B8D\u4F30\u6CBD\u5B64\u59D1\u9F13\u53E4\u86CA\u9AA8\u8C37\u80A1\u6545\u987E\u56FA\u96C7\u522E\u74DC\u5250\u5BE1\u6302\u8902\u4E56\u62D0\u602A\u68FA\u5173\u5B98\u51A0\u89C2\u7BA1\u9986\u7F50\u60EF\u704C\u8D2F\u5149\u5E7F\u901B\u7470\u89C4\u572D\u7845\u5F52\u9F9F\u95FA\u8F68\u9B3C\u8BE1\u7678\u6842\u67DC\u8DEA\u8D35\u523D\u8F8A\u6EDA\u68CD\u9505\u90ED\u56FD\u679C\u88F9\u8FC7\u54C8"],
      ["ba40", "\u7BC5\u7BC8\u7BC9\u7BCA\u7BCB\u7BCD\u7BCE\u7BCF\u7BD0\u7BD2\u7BD4", 4, "\u7BDB\u7BDC\u7BDE\u7BDF\u7BE0\u7BE2\u7BE3\u7BE4\u7BE7\u7BE8\u7BE9\u7BEB\u7BEC\u7BED\u7BEF\u7BF0\u7BF2", 4, "\u7BF8\u7BF9\u7BFA\u7BFB\u7BFD\u7BFF", 7, "\u7C08\u7C09\u7C0A\u7C0D\u7C0E\u7C10", 5, "\u7C17\u7C18\u7C19"],
      ["ba80", "\u7C1A", 4, "\u7C20", 5, "\u7C28\u7C29\u7C2B", 12, "\u7C39", 5, "\u7C42\u9AB8\u5B69\u6D77\u6C26\u4EA5\u5BB3\u9A87\u9163\u61A8\u90AF\u97E9\u542B\u6DB5\u5BD2\u51FD\u558A\u7F55\u7FF0\u64BC\u634D\u65F1\u61BE\u608D\u710A\u6C57\u6C49\u592F\u676D\u822A\u58D5\u568E\u8C6A\u6BEB\u90DD\u597D\u8017\u53F7\u6D69\u5475\u559D\u8377\u83CF\u6838\u79BE\u548C\u4F55\u5408\u76D2\u8C89\u9602\u6CB3\u6DB8\u8D6B\u8910\u9E64\u8D3A\u563F\u9ED1\u75D5\u5F88\u72E0\u6068\u54FC\u4EA8\u6A2A\u8861\u6052\u8F70\u54C4\u70D8\u8679\u9E3F\u6D2A\u5B8F\u5F18\u7EA2\u5589\u4FAF\u7334\u543C\u539A\u5019\u540E\u547C\u4E4E\u5FFD\u745A\u58F6\u846B\u80E1\u8774\u72D0\u7CCA\u6E56"],
      ["bb40", "\u7C43", 9, "\u7C4E", 36, "\u7C75", 5, "\u7C7E", 9],
      ["bb80", "\u7C88\u7C8A", 6, "\u7C93\u7C94\u7C96\u7C99\u7C9A\u7C9B\u7CA0\u7CA1\u7CA3\u7CA6\u7CA7\u7CA8\u7CA9\u7CAB\u7CAC\u7CAD\u7CAF\u7CB0\u7CB4", 4, "\u7CBA\u7CBB\u5F27\u864E\u552C\u62A4\u4E92\u6CAA\u6237\u82B1\u54D7\u534E\u733E\u6ED1\u753B\u5212\u5316\u8BDD\u69D0\u5F8A\u6000\u6DEE\u574F\u6B22\u73AF\u6853\u8FD8\u7F13\u6362\u60A3\u5524\u75EA\u8C62\u7115\u6DA3\u5BA6\u5E7B\u8352\u614C\u9EC4\u78FA\u8757\u7C27\u7687\u51F0\u60F6\u714C\u6643\u5E4C\u604D\u8C0E\u7070\u6325\u8F89\u5FBD\u6062\u86D4\u56DE\u6BC1\u6094\u6167\u5349\u60E0\u6666\u8D3F\u79FD\u4F1A\u70E9\u6C47\u8BB3\u8BF2\u7ED8\u8364\u660F\u5A5A\u9B42\u6D51\u6DF7\u8C41\u6D3B\u4F19\u706B\u83B7\u6216\u60D1\u970D\u8D27\u7978\u51FB\u573E\u57FA\u673A\u7578\u7A3D\u79EF\u7B95"],
      ["bc40", "\u7CBF\u7CC0\u7CC2\u7CC3\u7CC4\u7CC6\u7CC9\u7CCB\u7CCE", 6, "\u7CD8\u7CDA\u7CDB\u7CDD\u7CDE\u7CE1", 6, "\u7CE9", 5, "\u7CF0", 7, "\u7CF9\u7CFA\u7CFC", 13, "\u7D0B", 5],
      ["bc80", "\u7D11", 14, "\u7D21\u7D23\u7D24\u7D25\u7D26\u7D28\u7D29\u7D2A\u7D2C\u7D2D\u7D2E\u7D30", 6, "\u808C\u9965\u8FF9\u6FC0\u8BA5\u9E21\u59EC\u7EE9\u7F09\u5409\u6781\u68D8\u8F91\u7C4D\u96C6\u53CA\u6025\u75BE\u6C72\u5373\u5AC9\u7EA7\u6324\u51E0\u810A\u5DF1\u84DF\u6280\u5180\u5B63\u4F0E\u796D\u5242\u60B8\u6D4E\u5BC4\u5BC2\u8BA1\u8BB0\u65E2\u5FCC\u9645\u5993\u7EE7\u7EAA\u5609\u67B7\u5939\u4F73\u5BB6\u52A0\u835A\u988A\u8D3E\u7532\u94BE\u5047\u7A3C\u4EF7\u67B6\u9A7E\u5AC1\u6B7C\u76D1\u575A\u5C16\u7B3A\u95F4\u714E\u517C\u80A9\u8270\u5978\u7F04\u8327\u68C0\u67EC\u78B1\u7877\u62E3\u6361\u7B80\u4FED\u526A\u51CF\u8350\u69DB\u9274\u8DF5\u8D31\u89C1\u952E\u7BAD\u4EF6"],
      ["bd40", "\u7D37", 54, "\u7D6F", 7],
      ["bd80", "\u7D78", 32, "\u5065\u8230\u5251\u996F\u6E10\u6E85\u6DA7\u5EFA\u50F5\u59DC\u5C06\u6D46\u6C5F\u7586\u848B\u6868\u5956\u8BB2\u5320\u9171\u964D\u8549\u6912\u7901\u7126\u80F6\u4EA4\u90CA\u6D47\u9A84\u5A07\u56BC\u6405\u94F0\u77EB\u4FA5\u811A\u72E1\u89D2\u997A\u7F34\u7EDE\u527F\u6559\u9175\u8F7F\u8F83\u53EB\u7A96\u63ED\u63A5\u7686\u79F8\u8857\u9636\u622A\u52AB\u8282\u6854\u6770\u6377\u776B\u7AED\u6D01\u7ED3\u89E3\u59D0\u6212\u85C9\u82A5\u754C\u501F\u4ECB\u75A5\u8BEB\u5C4A\u5DFE\u7B4B\u65A4\u91D1\u4ECA\u6D25\u895F\u7D27\u9526\u4EC5\u8C28\u8FDB\u9773\u664B\u7981\u8FD1\u70EC\u6D78"],
      ["be40", "\u7D99", 12, "\u7DA7", 6, "\u7DAF", 42],
      ["be80", "\u7DDA", 32, "\u5C3D\u52B2\u8346\u5162\u830E\u775B\u6676\u9CB8\u4EAC\u60CA\u7CBE\u7CB3\u7ECF\u4E95\u8B66\u666F\u9888\u9759\u5883\u656C\u955C\u5F84\u75C9\u9756\u7ADF\u7ADE\u51C0\u70AF\u7A98\u63EA\u7A76\u7EA0\u7396\u97ED\u4E45\u7078\u4E5D\u9152\u53A9\u6551\u65E7\u81FC\u8205\u548E\u5C31\u759A\u97A0\u62D8\u72D9\u75BD\u5C45\u9A79\u83CA\u5C40\u5480\u77E9\u4E3E\u6CAE\u805A\u62D2\u636E\u5DE8\u5177\u8DDD\u8E1E\u952F\u4FF1\u53E5\u60E7\u70AC\u5267\u6350\u9E43\u5A1F\u5026\u7737\u5377\u7EE2\u6485\u652B\u6289\u6398\u5014\u7235\u89C9\u51B3\u8BC0\u7EDD\u5747\u83CC\u94A7\u519B\u541B\u5CFB"],
      ["bf40", "\u7DFB", 62],
      ["bf80", "\u7E3A\u7E3C", 4, "\u7E42", 4, "\u7E48", 21, "\u4FCA\u7AE3\u6D5A\u90E1\u9A8F\u5580\u5496\u5361\u54AF\u5F00\u63E9\u6977\u51EF\u6168\u520A\u582A\u52D8\u574E\u780D\u770B\u5EB7\u6177\u7CE0\u625B\u6297\u4EA2\u7095\u8003\u62F7\u70E4\u9760\u5777\u82DB\u67EF\u68F5\u78D5\u9897\u79D1\u58F3\u54B3\u53EF\u6E34\u514B\u523B\u5BA2\u8BFE\u80AF\u5543\u57A6\u6073\u5751\u542D\u7A7A\u6050\u5B54\u63A7\u62A0\u53E3\u6263\u5BC7\u67AF\u54ED\u7A9F\u82E6\u9177\u5E93\u88E4\u5938\u57AE\u630E\u8DE8\u80EF\u5757\u7B77\u4FA9\u5FEB\u5BBD\u6B3E\u5321\u7B50\u72C2\u6846\u77FF\u7736\u65F7\u51B5\u4E8F\u76D4\u5CBF\u7AA5\u8475\u594E\u9B41\u5080"],
      ["c040", "\u7E5E", 35, "\u7E83", 23, "\u7E9C\u7E9D\u7E9E"],
      ["c080", "\u7EAE\u7EB4\u7EBB\u7EBC\u7ED6\u7EE4\u7EEC\u7EF9\u7F0A\u7F10\u7F1E\u7F37\u7F39\u7F3B", 6, "\u7F43\u7F46", 9, "\u7F52\u7F53\u9988\u6127\u6E83\u5764\u6606\u6346\u56F0\u62EC\u6269\u5ED3\u9614\u5783\u62C9\u5587\u8721\u814A\u8FA3\u5566\u83B1\u6765\u8D56\u84DD\u5A6A\u680F\u62E6\u7BEE\u9611\u5170\u6F9C\u8C30\u63FD\u89C8\u61D2\u7F06\u70C2\u6EE5\u7405\u6994\u72FC\u5ECA\u90CE\u6717\u6D6A\u635E\u52B3\u7262\u8001\u4F6C\u59E5\u916A\u70D9\u6D9D\u52D2\u4E50\u96F7\u956D\u857E\u78CA\u7D2F\u5121\u5792\u64C2\u808B\u7C7B\u6CEA\u68F1\u695E\u51B7\u5398\u68A8\u7281\u9ECE\u7BF1\u72F8\u79BB\u6F13\u7406\u674E\u91CC\u9CA4\u793C\u8389\u8354\u540F\u6817\u4E3D\u5389\u52B1\u783E\u5386\u5229\u5088\u4F8B\u4FD0"],
      ["c140", "\u7F56\u7F59\u7F5B\u7F5C\u7F5D\u7F5E\u7F60\u7F63", 4, "\u7F6B\u7F6C\u7F6D\u7F6F\u7F70\u7F73\u7F75\u7F76\u7F77\u7F78\u7F7A\u7F7B\u7F7C\u7F7D\u7F7F\u7F80\u7F82", 7, "\u7F8B\u7F8D\u7F8F", 4, "\u7F95", 4, "\u7F9B\u7F9C\u7FA0\u7FA2\u7FA3\u7FA5\u7FA6\u7FA8", 6, "\u7FB1"],
      ["c180", "\u7FB3", 4, "\u7FBA\u7FBB\u7FBE\u7FC0\u7FC2\u7FC3\u7FC4\u7FC6\u7FC7\u7FC8\u7FC9\u7FCB\u7FCD\u7FCF", 4, "\u7FD6\u7FD7\u7FD9", 5, "\u7FE2\u7FE3\u75E2\u7ACB\u7C92\u6CA5\u96B6\u529B\u7483\u54E9\u4FE9\u8054\u83B2\u8FDE\u9570\u5EC9\u601C\u6D9F\u5E18\u655B\u8138\u94FE\u604B\u70BC\u7EC3\u7CAE\u51C9\u6881\u7CB1\u826F\u4E24\u8F86\u91CF\u667E\u4EAE\u8C05\u64A9\u804A\u50DA\u7597\u71CE\u5BE5\u8FBD\u6F66\u4E86\u6482\u9563\u5ED6\u6599\u5217\u88C2\u70C8\u52A3\u730E\u7433\u6797\u78F7\u9716\u4E34\u90BB\u9CDE\u6DCB\u51DB\u8D41\u541D\u62CE\u73B2\u83F1\u96F6\u9F84\u94C3\u4F36\u7F9A\u51CC\u7075\u9675\u5CAD\u9886\u53E6\u4EE4\u6E9C\u7409\u69B4\u786B\u998F\u7559\u5218\u7624\u6D41\u67F3\u516D\u9F99\u804B\u5499\u7B3C\u7ABF"],
      ["c240", "\u7FE4\u7FE7\u7FE8\u7FEA\u7FEB\u7FEC\u7FED\u7FEF\u7FF2\u7FF4", 6, "\u7FFD\u7FFE\u7FFF\u8002\u8007\u8008\u8009\u800A\u800E\u800F\u8011\u8013\u801A\u801B\u801D\u801E\u801F\u8021\u8023\u8024\u802B", 5, "\u8032\u8034\u8039\u803A\u803C\u803E\u8040\u8041\u8044\u8045\u8047\u8048\u8049\u804E\u804F\u8050\u8051\u8053\u8055\u8056\u8057"],
      ["c280", "\u8059\u805B", 13, "\u806B", 5, "\u8072", 11, "\u9686\u5784\u62E2\u9647\u697C\u5A04\u6402\u7BD3\u6F0F\u964B\u82A6\u5362\u9885\u5E90\u7089\u63B3\u5364\u864F\u9C81\u9E93\u788C\u9732\u8DEF\u8D42\u9E7F\u6F5E\u7984\u5F55\u9646\u622E\u9A74\u5415\u94DD\u4FA3\u65C5\u5C65\u5C61\u7F15\u8651\u6C2F\u5F8B\u7387\u6EE4\u7EFF\u5CE6\u631B\u5B6A\u6EE6\u5375\u4E71\u63A0\u7565\u62A1\u8F6E\u4F26\u4ED1\u6CA6\u7EB6\u8BBA\u841D\u87BA\u7F57\u903B\u9523\u7BA9\u9AA1\u88F8\u843D\u6D1B\u9A86\u7EDC\u5988\u9EBB\u739B\u7801\u8682\u9A6C\u9A82\u561B\u5417\u57CB\u4E70\u9EA6\u5356\u8FC8\u8109\u7792\u9992\u86EE\u6EE1\u8513\u66FC\u6162\u6F2B"],
      ["c340", "\u807E\u8081\u8082\u8085\u8088\u808A\u808D", 5, "\u8094\u8095\u8097\u8099\u809E\u80A3\u80A6\u80A7\u80A8\u80AC\u80B0\u80B3\u80B5\u80B6\u80B8\u80B9\u80BB\u80C5\u80C7", 4, "\u80CF", 6, "\u80D8\u80DF\u80E0\u80E2\u80E3\u80E6\u80EE\u80F5\u80F7\u80F9\u80FB\u80FE\u80FF\u8100\u8101\u8103\u8104\u8105\u8107\u8108\u810B"],
      ["c380", "\u810C\u8115\u8117\u8119\u811B\u811C\u811D\u811F", 12, "\u812D\u812E\u8130\u8133\u8134\u8135\u8137\u8139", 4, "\u813F\u8C29\u8292\u832B\u76F2\u6C13\u5FD9\u83BD\u732B\u8305\u951A\u6BDB\u77DB\u94C6\u536F\u8302\u5192\u5E3D\u8C8C\u8D38\u4E48\u73AB\u679A\u6885\u9176\u9709\u7164\u6CA1\u7709\u5A92\u9541\u6BCF\u7F8E\u6627\u5BD0\u59B9\u5A9A\u95E8\u95F7\u4EEC\u840C\u8499\u6AAC\u76DF\u9530\u731B\u68A6\u5B5F\u772F\u919A\u9761\u7CDC\u8FF7\u8C1C\u5F25\u7C73\u79D8\u89C5\u6CCC\u871C\u5BC6\u5E42\u68C9\u7720\u7EF5\u5195\u514D\u52C9\u5A29\u7F05\u9762\u82D7\u63CF\u7784\u85D0\u79D2\u6E3A\u5E99\u5999\u8511\u706D\u6C11\u62BF\u76BF\u654F\u60AF\u95FD\u660E\u879F\u9E23\u94ED\u540D\u547D\u8C2C\u6478"],
      ["c440", "\u8140", 5, "\u8147\u8149\u814D\u814E\u814F\u8152\u8156\u8157\u8158\u815B", 4, "\u8161\u8162\u8163\u8164\u8166\u8168\u816A\u816B\u816C\u816F\u8172\u8173\u8175\u8176\u8177\u8178\u8181\u8183", 4, "\u8189\u818B\u818C\u818D\u818E\u8190\u8192", 5, "\u8199\u819A\u819E", 4, "\u81A4\u81A5"],
      ["c480", "\u81A7\u81A9\u81AB", 7, "\u81B4", 5, "\u81BC\u81BD\u81BE\u81BF\u81C4\u81C5\u81C7\u81C8\u81C9\u81CB\u81CD", 6, "\u6479\u8611\u6A21\u819C\u78E8\u6469\u9B54\u62B9\u672B\u83AB\u58A8\u9ED8\u6CAB\u6F20\u5BDE\u964C\u8C0B\u725F\u67D0\u62C7\u7261\u4EA9\u59C6\u6BCD\u5893\u66AE\u5E55\u52DF\u6155\u6728\u76EE\u7766\u7267\u7A46\u62FF\u54EA\u5450\u94A0\u90A3\u5A1C\u7EB3\u6C16\u4E43\u5976\u8010\u5948\u5357\u7537\u96BE\u56CA\u6320\u8111\u607C\u95F9\u6DD6\u5462\u9981\u5185\u5AE9\u80FD\u59AE\u9713\u502A\u6CE5\u5C3C\u62DF\u4F60\u533F\u817B\u9006\u6EBA\u852B\u62C8\u5E74\u78BE\u64B5\u637B\u5FF5\u5A18\u917F\u9E1F\u5C3F\u634F\u8042\u5B7D\u556E\u954A\u954D\u6D85\u60A8\u67E0\u72DE\u51DD\u5B81"],
      ["c540", "\u81D4", 14, "\u81E4\u81E5\u81E6\u81E8\u81E9\u81EB\u81EE", 4, "\u81F5", 5, "\u81FD\u81FF\u8203\u8207", 4, "\u820E\u820F\u8211\u8213\u8215", 5, "\u821D\u8220\u8224\u8225\u8226\u8227\u8229\u822E\u8232\u823A\u823C\u823D\u823F"],
      ["c580", "\u8240\u8241\u8242\u8243\u8245\u8246\u8248\u824A\u824C\u824D\u824E\u8250", 7, "\u8259\u825B\u825C\u825D\u825E\u8260", 7, "\u8269\u62E7\u6CDE\u725B\u626D\u94AE\u7EBD\u8113\u6D53\u519C\u5F04\u5974\u52AA\u6012\u5973\u6696\u8650\u759F\u632A\u61E6\u7CEF\u8BFA\u54E6\u6B27\u9E25\u6BB4\u85D5\u5455\u5076\u6CA4\u556A\u8DB4\u722C\u5E15\u6015\u7436\u62CD\u6392\u724C\u5F98\u6E43\u6D3E\u6500\u6F58\u76D8\u78D0\u76FC\u7554\u5224\u53DB\u4E53\u5E9E\u65C1\u802A\u80D6\u629B\u5486\u5228\u70AE\u888D\u8DD1\u6CE1\u5478\u80DA\u57F9\u88F4\u8D54\u966A\u914D\u4F69\u6C9B\u55B7\u76C6\u7830\u62A8\u70F9\u6F8E\u5F6D\u84EC\u68DA\u787C\u7BF7\u81A8\u670B\u9E4F\u6367\u78B0\u576F\u7812\u9739\u6279\u62AB\u5288\u7435\u6BD7"],
      ["c640", "\u826A\u826B\u826C\u826D\u8271\u8275\u8276\u8277\u8278\u827B\u827C\u8280\u8281\u8283\u8285\u8286\u8287\u8289\u828C\u8290\u8293\u8294\u8295\u8296\u829A\u829B\u829E\u82A0\u82A2\u82A3\u82A7\u82B2\u82B5\u82B6\u82BA\u82BB\u82BC\u82BF\u82C0\u82C2\u82C3\u82C5\u82C6\u82C9\u82D0\u82D6\u82D9\u82DA\u82DD\u82E2\u82E7\u82E8\u82E9\u82EA\u82EC\u82ED\u82EE\u82F0\u82F2\u82F3\u82F5\u82F6\u82F8"],
      ["c680", "\u82FA\u82FC", 4, "\u830A\u830B\u830D\u8310\u8312\u8313\u8316\u8318\u8319\u831D", 9, "\u8329\u832A\u832E\u8330\u8332\u8337\u833B\u833D\u5564\u813E\u75B2\u76AE\u5339\u75DE\u50FB\u5C41\u8B6C\u7BC7\u504F\u7247\u9A97\u98D8\u6F02\u74E2\u7968\u6487\u77A5\u62FC\u9891\u8D2B\u54C1\u8058\u4E52\u576A\u82F9\u840D\u5E73\u51ED\u74F6\u8BC4\u5C4F\u5761\u6CFC\u9887\u5A46\u7834\u9B44\u8FEB\u7C95\u5256\u6251\u94FA\u4EC6\u8386\u8461\u83E9\u84B2\u57D4\u6734\u5703\u666E\u6D66\u8C31\u66DD\u7011\u671F\u6B3A\u6816\u621A\u59BB\u4E03\u51C4\u6F06\u67D2\u6C8F\u5176\u68CB\u5947\u6B67\u7566\u5D0E\u8110\u9F50\u65D7\u7948\u7941\u9A91\u8D77\u5C82\u4E5E\u4F01\u542F\u5951\u780C\u5668\u6C14\u8FC4\u5F03\u6C7D\u6CE3\u8BAB\u6390"],
      ["c740", "\u833E\u833F\u8341\u8342\u8344\u8345\u8348\u834A", 4, "\u8353\u8355", 4, "\u835D\u8362\u8370", 6, "\u8379\u837A\u837E", 6, "\u8387\u8388\u838A\u838B\u838C\u838D\u838F\u8390\u8391\u8394\u8395\u8396\u8397\u8399\u839A\u839D\u839F\u83A1", 6, "\u83AC\u83AD\u83AE"],
      ["c780", "\u83AF\u83B5\u83BB\u83BE\u83BF\u83C2\u83C3\u83C4\u83C6\u83C8\u83C9\u83CB\u83CD\u83CE\u83D0\u83D1\u83D2\u83D3\u83D5\u83D7\u83D9\u83DA\u83DB\u83DE\u83E2\u83E3\u83E4\u83E6\u83E7\u83E8\u83EB\u83EC\u83ED\u6070\u6D3D\u7275\u6266\u948E\u94C5\u5343\u8FC1\u7B7E\u4EDF\u8C26\u4E7E\u9ED4\u94B1\u94B3\u524D\u6F5C\u9063\u6D45\u8C34\u5811\u5D4C\u6B20\u6B49\u67AA\u545B\u8154\u7F8C\u5899\u8537\u5F3A\u62A2\u6A47\u9539\u6572\u6084\u6865\u77A7\u4E54\u4FA8\u5DE7\u9798\u64AC\u7FD8\u5CED\u4FCF\u7A8D\u5207\u8304\u4E14\u602F\u7A83\u94A6\u4FB5\u4EB2\u79E6\u7434\u52E4\u82B9\u64D2\u79BD\u5BDD\u6C81\u9752\u8F7B\u6C22\u503E\u537F\u6E05\u64CE\u6674\u6C30\u60C5\u9877\u8BF7\u5E86\u743C\u7A77\u79CB\u4E18\u90B1\u7403\u6C42\u56DA\u914B\u6CC5\u8D8B\u533A\u86C6\u66F2\u8EAF\u5C48\u9A71\u6E20"],
      ["c840", "\u83EE\u83EF\u83F3", 4, "\u83FA\u83FB\u83FC\u83FE\u83FF\u8400\u8402\u8405\u8407\u8408\u8409\u840A\u8410\u8412", 5, "\u8419\u841A\u841B\u841E", 5, "\u8429", 7, "\u8432", 5, "\u8439\u843A\u843B\u843E", 7, "\u8447\u8448\u8449"],
      ["c880", "\u844A", 6, "\u8452", 4, "\u8458\u845D\u845E\u845F\u8460\u8462\u8464", 4, "\u846A\u846E\u846F\u8470\u8472\u8474\u8477\u8479\u847B\u847C\u53D6\u5A36\u9F8B\u8DA3\u53BB\u5708\u98A7\u6743\u919B\u6CC9\u5168\u75CA\u62F3\u72AC\u5238\u529D\u7F3A\u7094\u7638\u5374\u9E4A\u69B7\u786E\u96C0\u88D9\u7FA4\u7136\u71C3\u5189\u67D3\u74E4\u58E4\u6518\u56B7\u8BA9\u9976\u6270\u7ED5\u60F9\u70ED\u58EC\u4EC1\u4EBA\u5FCD\u97E7\u4EFB\u8BA4\u5203\u598A\u7EAB\u6254\u4ECD\u65E5\u620E\u8338\u84C9\u8363\u878D\u7194\u6EB6\u5BB9\u7ED2\u5197\u63C9\u67D4\u8089\u8339\u8815\u5112\u5B7A\u5982\u8FB1\u4E73\u6C5D\u5165\u8925\u8F6F\u962E\u854A\u745E\u9510\u95F0\u6DA6\u82E5\u5F31\u6492\u6D12\u8428\u816E\u9CC3\u585E\u8D5B\u4E09\u53C1"],
      ["c940", "\u847D", 4, "\u8483\u8484\u8485\u8486\u848A\u848D\u848F", 7, "\u8498\u849A\u849B\u849D\u849E\u849F\u84A0\u84A2", 12, "\u84B0\u84B1\u84B3\u84B5\u84B6\u84B7\u84BB\u84BC\u84BE\u84C0\u84C2\u84C3\u84C5\u84C6\u84C7\u84C8\u84CB\u84CC\u84CE\u84CF\u84D2\u84D4\u84D5\u84D7"],
      ["c980", "\u84D8", 4, "\u84DE\u84E1\u84E2\u84E4\u84E7", 4, "\u84ED\u84EE\u84EF\u84F1", 10, "\u84FD\u84FE\u8500\u8501\u8502\u4F1E\u6563\u6851\u55D3\u4E27\u6414\u9A9A\u626B\u5AC2\u745F\u8272\u6DA9\u68EE\u50E7\u838E\u7802\u6740\u5239\u6C99\u7EB1\u50BB\u5565\u715E\u7B5B\u6652\u73CA\u82EB\u6749\u5C71\u5220\u717D\u886B\u95EA\u9655\u64C5\u8D61\u81B3\u5584\u6C55\u6247\u7F2E\u5892\u4F24\u5546\u8D4F\u664C\u4E0A\u5C1A\u88F3\u68A2\u634E\u7A0D\u70E7\u828D\u52FA\u97F6\u5C11\u54E8\u90B5\u7ECD\u5962\u8D4A\u86C7\u820C\u820D\u8D66\u6444\u5C04\u6151\u6D89\u793E\u8BBE\u7837\u7533\u547B\u4F38\u8EAB\u6DF1\u5A20\u7EC5\u795E\u6C88\u5BA1\u5A76\u751A\u80BE\u614E\u6E17\u58F0\u751F\u7525\u7272\u5347\u7EF3"],
      ["ca40", "\u8503", 8, "\u850D\u850E\u850F\u8510\u8512\u8514\u8515\u8516\u8518\u8519\u851B\u851C\u851D\u851E\u8520\u8522", 8, "\u852D", 9, "\u853E", 4, "\u8544\u8545\u8546\u8547\u854B", 10],
      ["ca80", "\u8557\u8558\u855A\u855B\u855C\u855D\u855F", 4, "\u8565\u8566\u8567\u8569", 8, "\u8573\u8575\u8576\u8577\u8578\u857C\u857D\u857F\u8580\u8581\u7701\u76DB\u5269\u80DC\u5723\u5E08\u5931\u72EE\u65BD\u6E7F\u8BD7\u5C38\u8671\u5341\u77F3\u62FE\u65F6\u4EC0\u98DF\u8680\u5B9E\u8BC6\u53F2\u77E2\u4F7F\u5C4E\u9A76\u59CB\u5F0F\u793A\u58EB\u4E16\u67FF\u4E8B\u62ED\u8A93\u901D\u52BF\u662F\u55DC\u566C\u9002\u4ED5\u4F8D\u91CA\u9970\u6C0F\u5E02\u6043\u5BA4\u89C6\u8BD5\u6536\u624B\u9996\u5B88\u5BFF\u6388\u552E\u53D7\u7626\u517D\u852C\u67A2\u68B3\u6B8A\u6292\u8F93\u53D4\u8212\u6DD1\u758F\u4E66\u8D4E\u5B70\u719F\u85AF\u6691\u66D9\u7F72\u8700\u9ECD\u9F20\u5C5E\u672F\u8FF0\u6811\u675F\u620D\u7AD6\u5885\u5EB6\u6570\u6F31"],
      ["cb40", "\u8582\u8583\u8586\u8588", 6, "\u8590", 10, "\u859D", 6, "\u85A5\u85A6\u85A7\u85A9\u85AB\u85AC\u85AD\u85B1", 5, "\u85B8\u85BA", 6, "\u85C2", 6, "\u85CA", 4, "\u85D1\u85D2"],
      ["cb80", "\u85D4\u85D6", 5, "\u85DD", 6, "\u85E5\u85E6\u85E7\u85E8\u85EA", 14, "\u6055\u5237\u800D\u6454\u8870\u7529\u5E05\u6813\u62F4\u971C\u53CC\u723D\u8C01\u6C34\u7761\u7A0E\u542E\u77AC\u987A\u821C\u8BF4\u7855\u6714\u70C1\u65AF\u6495\u5636\u601D\u79C1\u53F8\u4E1D\u6B7B\u8086\u5BFA\u55E3\u56DB\u4F3A\u4F3C\u9972\u5DF3\u677E\u8038\u6002\u9882\u9001\u5B8B\u8BBC\u8BF5\u641C\u8258\u64DE\u55FD\u82CF\u9165\u4FD7\u7D20\u901F\u7C9F\u50F3\u5851\u6EAF\u5BBF\u8BC9\u8083\u9178\u849C\u7B97\u867D\u968B\u968F\u7EE5\u9AD3\u788E\u5C81\u7A57\u9042\u96A7\u795F\u5B59\u635F\u7B0B\u84D1\u68AD\u5506\u7F29\u7410\u7D22\u9501\u6240\u584C\u4ED6\u5B83\u5979\u5854"],
      ["cc40", "\u85F9\u85FA\u85FC\u85FD\u85FE\u8600", 4, "\u8606", 10, "\u8612\u8613\u8614\u8615\u8617", 15, "\u8628\u862A", 13, "\u8639\u863A\u863B\u863D\u863E\u863F\u8640"],
      ["cc80", "\u8641", 11, "\u8652\u8653\u8655", 4, "\u865B\u865C\u865D\u865F\u8660\u8661\u8663", 7, "\u736D\u631E\u8E4B\u8E0F\u80CE\u82D4\u62AC\u53F0\u6CF0\u915E\u592A\u6001\u6C70\u574D\u644A\u8D2A\u762B\u6EE9\u575B\u6A80\u75F0\u6F6D\u8C2D\u8C08\u5766\u6BEF\u8892\u78B3\u63A2\u53F9\u70AD\u6C64\u5858\u642A\u5802\u68E0\u819B\u5510\u7CD6\u5018\u8EBA\u6DCC\u8D9F\u70EB\u638F\u6D9B\u6ED4\u7EE6\u8404\u6843\u9003\u6DD8\u9676\u8BA8\u5957\u7279\u85E4\u817E\u75BC\u8A8A\u68AF\u5254\u8E22\u9511\u63D0\u9898\u8E44\u557C\u4F53\u66FF\u568F\u60D5\u6D95\u5243\u5C49\u5929\u6DFB\u586B\u7530\u751C\u606C\u8214\u8146\u6311\u6761\u8FE2\u773A\u8DF3\u8D34\u94C1\u5E16\u5385\u542C\u70C3"],
      ["cd40", "\u866D\u866F\u8670\u8672", 6, "\u8683", 6, "\u868E", 4, "\u8694\u8696", 5, "\u869E", 4, "\u86A5\u86A6\u86AB\u86AD\u86AE\u86B2\u86B3\u86B7\u86B8\u86B9\u86BB", 4, "\u86C1\u86C2\u86C3\u86C5\u86C8\u86CC\u86CD\u86D2\u86D3\u86D5\u86D6\u86D7\u86DA\u86DC"],
      ["cd80", "\u86DD\u86E0\u86E1\u86E2\u86E3\u86E5\u86E6\u86E7\u86E8\u86EA\u86EB\u86EC\u86EF\u86F5\u86F6\u86F7\u86FA\u86FB\u86FC\u86FD\u86FF\u8701\u8704\u8705\u8706\u870B\u870C\u870E\u870F\u8710\u8711\u8714\u8716\u6C40\u5EF7\u505C\u4EAD\u5EAD\u633A\u8247\u901A\u6850\u916E\u77B3\u540C\u94DC\u5F64\u7AE5\u6876\u6345\u7B52\u7EDF\u75DB\u5077\u6295\u5934\u900F\u51F8\u79C3\u7A81\u56FE\u5F92\u9014\u6D82\u5C60\u571F\u5410\u5154\u6E4D\u56E2\u63A8\u9893\u817F\u8715\u892A\u9000\u541E\u5C6F\u81C0\u62D6\u6258\u8131\u9E35\u9640\u9A6E\u9A7C\u692D\u59A5\u62D3\u553E\u6316\u54C7\u86D9\u6D3C\u5A03\u74E6\u889C\u6B6A\u5916\u8C4C\u5F2F\u6E7E\u73A9\u987D\u4E38\u70F7\u5B8C\u7897\u633D\u665A\u7696\u60CB\u5B9B\u5A49\u4E07\u8155\u6C6A\u738B\u4EA1\u6789\u7F51\u5F80\u65FA\u671B\u5FD8\u5984\u5A01"],
      ["ce40", "\u8719\u871B\u871D\u871F\u8720\u8724\u8726\u8727\u8728\u872A\u872B\u872C\u872D\u872F\u8730\u8732\u8733\u8735\u8736\u8738\u8739\u873A\u873C\u873D\u8740", 6, "\u874A\u874B\u874D\u874F\u8750\u8751\u8752\u8754\u8755\u8756\u8758\u875A", 5, "\u8761\u8762\u8766", 7, "\u876F\u8771\u8772\u8773\u8775"],
      ["ce80", "\u8777\u8778\u8779\u877A\u877F\u8780\u8781\u8784\u8786\u8787\u8789\u878A\u878C\u878E", 4, "\u8794\u8795\u8796\u8798", 6, "\u87A0", 4, "\u5DCD\u5FAE\u5371\u97E6\u8FDD\u6845\u56F4\u552F\u60DF\u4E3A\u6F4D\u7EF4\u82C7\u840E\u59D4\u4F1F\u4F2A\u5C3E\u7EAC\u672A\u851A\u5473\u754F\u80C3\u5582\u9B4F\u4F4D\u6E2D\u8C13\u5C09\u6170\u536B\u761F\u6E29\u868A\u6587\u95FB\u7EB9\u543B\u7A33\u7D0A\u95EE\u55E1\u7FC1\u74EE\u631D\u8717\u6DA1\u7A9D\u6211\u65A1\u5367\u63E1\u6C83\u5DEB\u545C\u94A8\u4E4C\u6C61\u8BEC\u5C4B\u65E0\u829C\u68A7\u543E\u5434\u6BCB\u6B66\u4E94\u6342\u5348\u821E\u4F0D\u4FAE\u575E\u620A\u96FE\u6664\u7269\u52FF\u52A1\u609F\u8BEF\u6614\u7199\u6790\u897F\u7852\u77FD\u6670\u563B\u5438\u9521\u727A"],
      ["cf40", "\u87A5\u87A6\u87A7\u87A9\u87AA\u87AE\u87B0\u87B1\u87B2\u87B4\u87B6\u87B7\u87B8\u87B9\u87BB\u87BC\u87BE\u87BF\u87C1", 4, "\u87C7\u87C8\u87C9\u87CC", 4, "\u87D4", 6, "\u87DC\u87DD\u87DE\u87DF\u87E1\u87E2\u87E3\u87E4\u87E6\u87E7\u87E8\u87E9\u87EB\u87EC\u87ED\u87EF", 9],
      ["cf80", "\u87FA\u87FB\u87FC\u87FD\u87FF\u8800\u8801\u8802\u8804", 5, "\u880B", 7, "\u8814\u8817\u8818\u8819\u881A\u881C", 4, "\u8823\u7A00\u606F\u5E0C\u6089\u819D\u5915\u60DC\u7184\u70EF\u6EAA\u6C50\u7280\u6A84\u88AD\u5E2D\u4E60\u5AB3\u559C\u94E3\u6D17\u7CFB\u9699\u620F\u7EC6\u778E\u867E\u5323\u971E\u8F96\u6687\u5CE1\u4FA0\u72ED\u4E0B\u53A6\u590F\u5413\u6380\u9528\u5148\u4ED9\u9C9C\u7EA4\u54B8\u8D24\u8854\u8237\u95F2\u6D8E\u5F26\u5ACC\u663E\u9669\u73B0\u732E\u53BF\u817A\u9985\u7FA1\u5BAA\u9677\u9650\u7EBF\u76F8\u53A2\u9576\u9999\u7BB1\u8944\u6E58\u4E61\u7FD4\u7965\u8BE6\u60F3\u54CD\u4EAB\u9879\u5DF7\u6A61\u50CF\u5411\u8C61\u8427\u785D\u9704\u524A\u54EE\u56A3\u9500\u6D88\u5BB5\u6DC6\u6653"],
      ["d040", "\u8824", 13, "\u8833", 5, "\u883A\u883B\u883D\u883E\u883F\u8841\u8842\u8843\u8846", 5, "\u884E", 5, "\u8855\u8856\u8858\u885A", 6, "\u8866\u8867\u886A\u886D\u886F\u8871\u8873\u8874\u8875\u8876\u8878\u8879\u887A"],
      ["d080", "\u887B\u887C\u8880\u8883\u8886\u8887\u8889\u888A\u888C\u888E\u888F\u8890\u8891\u8893\u8894\u8895\u8897", 4, "\u889D", 4, "\u88A3\u88A5", 5, "\u5C0F\u5B5D\u6821\u8096\u5578\u7B11\u6548\u6954\u4E9B\u6B47\u874E\u978B\u534F\u631F\u643A\u90AA\u659C\u80C1\u8C10\u5199\u68B0\u5378\u87F9\u61C8\u6CC4\u6CFB\u8C22\u5C51\u85AA\u82AF\u950C\u6B23\u8F9B\u65B0\u5FFB\u5FC3\u4FE1\u8845\u661F\u8165\u7329\u60FA\u5174\u5211\u578B\u5F62\u90A2\u884C\u9192\u5E78\u674F\u6027\u59D3\u5144\u51F6\u80F8\u5308\u6C79\u96C4\u718A\u4F11\u4FEE\u7F9E\u673D\u55C5\u9508\u79C0\u8896\u7EE3\u589F\u620C\u9700\u865A\u5618\u987B\u5F90\u8BB8\u84C4\u9157\u53D9\u65ED\u5E8F\u755C\u6064\u7D6E\u5A7F\u7EEA\u7EED\u8F69\u55A7\u5BA3\u60AC\u65CB\u7384"],
      ["d140", "\u88AC\u88AE\u88AF\u88B0\u88B2", 4, "\u88B8\u88B9\u88BA\u88BB\u88BD\u88BE\u88BF\u88C0\u88C3\u88C4\u88C7\u88C8\u88CA\u88CB\u88CC\u88CD\u88CF\u88D0\u88D1\u88D3\u88D6\u88D7\u88DA", 4, "\u88E0\u88E1\u88E6\u88E7\u88E9", 6, "\u88F2\u88F5\u88F6\u88F7\u88FA\u88FB\u88FD\u88FF\u8900\u8901\u8903", 5],
      ["d180", "\u8909\u890B", 4, "\u8911\u8914", 4, "\u891C", 4, "\u8922\u8923\u8924\u8926\u8927\u8928\u8929\u892C\u892D\u892E\u892F\u8931\u8932\u8933\u8935\u8937\u9009\u7663\u7729\u7EDA\u9774\u859B\u5B66\u7A74\u96EA\u8840\u52CB\u718F\u5FAA\u65EC\u8BE2\u5BFB\u9A6F\u5DE1\u6B89\u6C5B\u8BAD\u8BAF\u900A\u8FC5\u538B\u62BC\u9E26\u9E2D\u5440\u4E2B\u82BD\u7259\u869C\u5D16\u8859\u6DAF\u96C5\u54D1\u4E9A\u8BB6\u7109\u54BD\u9609\u70DF\u6DF9\u76D0\u4E25\u7814\u8712\u5CA9\u5EF6\u8A00\u989C\u960E\u708E\u6CBF\u5944\u63A9\u773C\u884D\u6F14\u8273\u5830\u71D5\u538C\u781A\u96C1\u5501\u5F66\u7130\u5BB4\u8C1A\u9A8C\u6B83\u592E\u9E2F\u79E7\u6768\u626C\u4F6F\u75A1\u7F8A\u6D0B\u9633\u6C27\u4EF0\u75D2\u517B\u6837\u6F3E\u9080\u8170\u5996\u7476"],
      ["d240", "\u8938", 8, "\u8942\u8943\u8945", 24, "\u8960", 5, "\u8967", 19, "\u897C"],
      ["d280", "\u897D\u897E\u8980\u8982\u8984\u8985\u8987", 26, "\u6447\u5C27\u9065\u7A91\u8C23\u59DA\u54AC\u8200\u836F\u8981\u8000\u6930\u564E\u8036\u7237\u91CE\u51B6\u4E5F\u9875\u6396\u4E1A\u53F6\u66F3\u814B\u591C\u6DB2\u4E00\u58F9\u533B\u63D6\u94F1\u4F9D\u4F0A\u8863\u9890\u5937\u9057\u79FB\u4EEA\u80F0\u7591\u6C82\u5B9C\u59E8\u5F5D\u6905\u8681\u501A\u5DF2\u4E59\u77E3\u4EE5\u827A\u6291\u6613\u9091\u5C79\u4EBF\u5F79\u81C6\u9038\u8084\u75AB\u4EA6\u88D4\u610F\u6BC5\u5FC6\u4E49\u76CA\u6EA2\u8BE3\u8BAE\u8C0A\u8BD1\u5F02\u7FFC\u7FCC\u7ECE\u8335\u836B\u56E0\u6BB7\u97F3\u9634\u59FB\u541F\u94F6\u6DEB\u5BC5\u996E\u5C39\u5F15\u9690"],
      ["d340", "\u89A2", 30, "\u89C3\u89CD\u89D3\u89D4\u89D5\u89D7\u89D8\u89D9\u89DB\u89DD\u89DF\u89E0\u89E1\u89E2\u89E4\u89E7\u89E8\u89E9\u89EA\u89EC\u89ED\u89EE\u89F0\u89F1\u89F2\u89F4", 6],
      ["d380", "\u89FB", 4, "\u8A01", 5, "\u8A08", 21, "\u5370\u82F1\u6A31\u5A74\u9E70\u5E94\u7F28\u83B9\u8424\u8425\u8367\u8747\u8FCE\u8D62\u76C8\u5F71\u9896\u786C\u6620\u54DF\u62E5\u4F63\u81C3\u75C8\u5EB8\u96CD\u8E0A\u86F9\u548F\u6CF3\u6D8C\u6C38\u607F\u52C7\u7528\u5E7D\u4F18\u60A0\u5FE7\u5C24\u7531\u90AE\u94C0\u72B9\u6CB9\u6E38\u9149\u6709\u53CB\u53F3\u4F51\u91C9\u8BF1\u53C8\u5E7C\u8FC2\u6DE4\u4E8E\u76C2\u6986\u865E\u611A\u8206\u4F59\u4FDE\u903E\u9C7C\u6109\u6E1D\u6E14\u9685\u4E88\u5A31\u96E8\u4E0E\u5C7F\u79B9\u5B87\u8BED\u7FBD\u7389\u57DF\u828B\u90C1\u5401\u9047\u55BB\u5CEA\u5FA1\u6108\u6B32\u72F1\u80B2\u8A89"],
      ["d440", "\u8A1E", 31, "\u8A3F", 8, "\u8A49", 21],
      ["d480", "\u8A5F", 25, "\u8A7A", 6, "\u6D74\u5BD3\u88D5\u9884\u8C6B\u9A6D\u9E33\u6E0A\u51A4\u5143\u57A3\u8881\u539F\u63F4\u8F95\u56ED\u5458\u5706\u733F\u6E90\u7F18\u8FDC\u82D1\u613F\u6028\u9662\u66F0\u7EA6\u8D8A\u8DC3\u94A5\u5CB3\u7CA4\u6708\u60A6\u9605\u8018\u4E91\u90E7\u5300\u9668\u5141\u8FD0\u8574\u915D\u6655\u97F5\u5B55\u531D\u7838\u6742\u683D\u54C9\u707E\u5BB0\u8F7D\u518D\u5728\u54B1\u6512\u6682\u8D5E\u8D43\u810F\u846C\u906D\u7CDF\u51FF\u85FB\u67A3\u65E9\u6FA1\u86A4\u8E81\u566A\u9020\u7682\u7076\u71E5\u8D23\u62E9\u5219\u6CFD\u8D3C\u600E\u589E\u618E\u66FE\u8D60\u624E\u55B3\u6E23\u672D\u8F67"],
      ["d540", "\u8A81", 7, "\u8A8B", 7, "\u8A94", 46],
      ["d580", "\u8AC3", 32, "\u94E1\u95F8\u7728\u6805\u69A8\u548B\u4E4D\u70B8\u8BC8\u6458\u658B\u5B85\u7A84\u503A\u5BE8\u77BB\u6BE1\u8A79\u7C98\u6CBE\u76CF\u65A9\u8F97\u5D2D\u5C55\u8638\u6808\u5360\u6218\u7AD9\u6E5B\u7EFD\u6A1F\u7AE0\u5F70\u6F33\u5F20\u638C\u6DA8\u6756\u4E08\u5E10\u8D26\u4ED7\u80C0\u7634\u969C\u62DB\u662D\u627E\u6CBC\u8D75\u7167\u7F69\u5146\u8087\u53EC\u906E\u6298\u54F2\u86F0\u8F99\u8005\u9517\u8517\u8FD9\u6D59\u73CD\u659F\u771F\u7504\u7827\u81FB\u8D1E\u9488\u4FA6\u6795\u75B9\u8BCA\u9707\u632F\u9547\u9635\u84B8\u6323\u7741\u5F81\u72F0\u4E89\u6014\u6574\u62EF\u6B63\u653F"],
      ["d640", "\u8AE4", 34, "\u8B08", 27],
      ["d680", "\u8B24\u8B25\u8B27", 30, "\u5E27\u75C7\u90D1\u8BC1\u829D\u679D\u652F\u5431\u8718\u77E5\u80A2\u8102\u6C41\u4E4B\u7EC7\u804C\u76F4\u690D\u6B96\u6267\u503C\u4F84\u5740\u6307\u6B62\u8DBE\u53EA\u65E8\u7EB8\u5FD7\u631A\u63B7\u81F3\u81F4\u7F6E\u5E1C\u5CD9\u5236\u667A\u79E9\u7A1A\u8D28\u7099\u75D4\u6EDE\u6CBB\u7A92\u4E2D\u76C5\u5FE0\u949F\u8877\u7EC8\u79CD\u80BF\u91CD\u4EF2\u4F17\u821F\u5468\u5DDE\u6D32\u8BCC\u7CA5\u8F74\u8098\u5E1A\u5492\u76B1\u5B99\u663C\u9AA4\u73E0\u682A\u86DB\u6731\u732A\u8BF8\u8BDB\u9010\u7AF9\u70DB\u716E\u62C4\u77A9\u5631\u4E3B\u8457\u67F1\u52A9\u86C0\u8D2E\u94F8\u7B51"],
      ["d740", "\u8B46", 31, "\u8B67", 4, "\u8B6D", 25],
      ["d780", "\u8B87", 24, "\u8BAC\u8BB1\u8BBB\u8BC7\u8BD0\u8BEA\u8C09\u8C1E\u4F4F\u6CE8\u795D\u9A7B\u6293\u722A\u62FD\u4E13\u7816\u8F6C\u64B0\u8D5A\u7BC6\u6869\u5E84\u88C5\u5986\u649E\u58EE\u72B6\u690E\u9525\u8FFD\u8D58\u5760\u7F00\u8C06\u51C6\u6349\u62D9\u5353\u684C\u7422\u8301\u914C\u5544\u7740\u707C\u6D4A\u5179\u54A8\u8D44\u59FF\u6ECB\u6DC4\u5B5C\u7D2B\u4ED4\u7C7D\u6ED3\u5B50\u81EA\u6E0D\u5B57\u9B03\u68D5\u8E2A\u5B97\u7EFC\u603B\u7EB5\u90B9\u8D70\u594F\u63CD\u79DF\u8DB3\u5352\u65CF\u7956\u8BC5\u963B\u7EC4\u94BB\u7E82\u5634\u9189\u6700\u7F6A\u5C0A\u9075\u6628\u5DE6\u4F50\u67DE\u505A\u4F5C\u5750\u5EA7"],
      ["d840", "\u8C38", 8, "\u8C42\u8C43\u8C44\u8C45\u8C48\u8C4A\u8C4B\u8C4D", 7, "\u8C56\u8C57\u8C58\u8C59\u8C5B", 5, "\u8C63", 6, "\u8C6C", 6, "\u8C74\u8C75\u8C76\u8C77\u8C7B", 6, "\u8C83\u8C84\u8C86\u8C87"],
      ["d880", "\u8C88\u8C8B\u8C8D", 6, "\u8C95\u8C96\u8C97\u8C99", 20, "\u4E8D\u4E0C\u5140\u4E10\u5EFF\u5345\u4E15\u4E98\u4E1E\u9B32\u5B6C\u5669\u4E28\u79BA\u4E3F\u5315\u4E47\u592D\u723B\u536E\u6C10\u56DF\u80E4\u9997\u6BD3\u777E\u9F17\u4E36\u4E9F\u9F10\u4E5C\u4E69\u4E93\u8288\u5B5B\u556C\u560F\u4EC4\u538D\u539D\u53A3\u53A5\u53AE\u9765\u8D5D\u531A\u53F5\u5326\u532E\u533E\u8D5C\u5366\u5363\u5202\u5208\u520E\u522D\u5233\u523F\u5240\u524C\u525E\u5261\u525C\u84AF\u527D\u5282\u5281\u5290\u5293\u5182\u7F54\u4EBB\u4EC3\u4EC9\u4EC2\u4EE8\u4EE1\u4EEB\u4EDE\u4F1B\u4EF3\u4F22\u4F64\u4EF5\u4F25\u4F27\u4F09\u4F2B\u4F5E\u4F67\u6538\u4F5A\u4F5D"],
      ["d940", "\u8CAE", 62],
      ["d980", "\u8CED", 32, "\u4F5F\u4F57\u4F32\u4F3D\u4F76\u4F74\u4F91\u4F89\u4F83\u4F8F\u4F7E\u4F7B\u4FAA\u4F7C\u4FAC\u4F94\u4FE6\u4FE8\u4FEA\u4FC5\u4FDA\u4FE3\u4FDC\u4FD1\u4FDF\u4FF8\u5029\u504C\u4FF3\u502C\u500F\u502E\u502D\u4FFE\u501C\u500C\u5025\u5028\u507E\u5043\u5055\u5048\u504E\u506C\u507B\u50A5\u50A7\u50A9\u50BA\u50D6\u5106\u50ED\u50EC\u50E6\u50EE\u5107\u510B\u4EDD\u6C3D\u4F58\u4F65\u4FCE\u9FA0\u6C46\u7C74\u516E\u5DFD\u9EC9\u9998\u5181\u5914\u52F9\u530D\u8A07\u5310\u51EB\u5919\u5155\u4EA0\u5156\u4EB3\u886E\u88A4\u4EB5\u8114\u88D2\u7980\u5B34\u8803\u7FB8\u51AB\u51B1\u51BD\u51BC"],
      ["da40", "\u8D0E", 14, "\u8D20\u8D51\u8D52\u8D57\u8D5F\u8D65\u8D68\u8D69\u8D6A\u8D6C\u8D6E\u8D6F\u8D71\u8D72\u8D78", 8, "\u8D82\u8D83\u8D86\u8D87\u8D88\u8D89\u8D8C", 4, "\u8D92\u8D93\u8D95", 9, "\u8DA0\u8DA1"],
      ["da80", "\u8DA2\u8DA4", 12, "\u8DB2\u8DB6\u8DB7\u8DB9\u8DBB\u8DBD\u8DC0\u8DC1\u8DC2\u8DC5\u8DC7\u8DC8\u8DC9\u8DCA\u8DCD\u8DD0\u8DD2\u8DD3\u8DD4\u51C7\u5196\u51A2\u51A5\u8BA0\u8BA6\u8BA7\u8BAA\u8BB4\u8BB5\u8BB7\u8BC2\u8BC3\u8BCB\u8BCF\u8BCE\u8BD2\u8BD3\u8BD4\u8BD6\u8BD8\u8BD9\u8BDC\u8BDF\u8BE0\u8BE4\u8BE8\u8BE9\u8BEE\u8BF0\u8BF3\u8BF6\u8BF9\u8BFC\u8BFF\u8C00\u8C02\u8C04\u8C07\u8C0C\u8C0F\u8C11\u8C12\u8C14\u8C15\u8C16\u8C19\u8C1B\u8C18\u8C1D\u8C1F\u8C20\u8C21\u8C25\u8C27\u8C2A\u8C2B\u8C2E\u8C2F\u8C32\u8C33\u8C35\u8C36\u5369\u537A\u961D\u9622\u9621\u9631\u962A\u963D\u963C\u9642\u9649\u9654\u965F\u9667\u966C\u9672\u9674\u9688\u968D\u9697\u96B0\u9097\u909B\u909D\u9099\u90AC\u90A1\u90B4\u90B3\u90B6\u90BA"],
      ["db40", "\u8DD5\u8DD8\u8DD9\u8DDC\u8DE0\u8DE1\u8DE2\u8DE5\u8DE6\u8DE7\u8DE9\u8DED\u8DEE\u8DF0\u8DF1\u8DF2\u8DF4\u8DF6\u8DFC\u8DFE", 6, "\u8E06\u8E07\u8E08\u8E0B\u8E0D\u8E0E\u8E10\u8E11\u8E12\u8E13\u8E15", 7, "\u8E20\u8E21\u8E24", 4, "\u8E2B\u8E2D\u8E30\u8E32\u8E33\u8E34\u8E36\u8E37\u8E38\u8E3B\u8E3C\u8E3E"],
      ["db80", "\u8E3F\u8E43\u8E45\u8E46\u8E4C", 4, "\u8E53", 5, "\u8E5A", 11, "\u8E67\u8E68\u8E6A\u8E6B\u8E6E\u8E71\u90B8\u90B0\u90CF\u90C5\u90BE\u90D0\u90C4\u90C7\u90D3\u90E6\u90E2\u90DC\u90D7\u90DB\u90EB\u90EF\u90FE\u9104\u9122\u911E\u9123\u9131\u912F\u9139\u9143\u9146\u520D\u5942\u52A2\u52AC\u52AD\u52BE\u54FF\u52D0\u52D6\u52F0\u53DF\u71EE\u77CD\u5EF4\u51F5\u51FC\u9B2F\u53B6\u5F01\u755A\u5DEF\u574C\u57A9\u57A1\u587E\u58BC\u58C5\u58D1\u5729\u572C\u572A\u5733\u5739\u572E\u572F\u575C\u573B\u5742\u5769\u5785\u576B\u5786\u577C\u577B\u5768\u576D\u5776\u5773\u57AD\u57A4\u578C\u57B2\u57CF\u57A7\u57B4\u5793\u57A0\u57D5\u57D8\u57DA\u57D9\u57D2\u57B8\u57F4\u57EF\u57F8\u57E4\u57DD"],
      ["dc40", "\u8E73\u8E75\u8E77", 4, "\u8E7D\u8E7E\u8E80\u8E82\u8E83\u8E84\u8E86\u8E88", 6, "\u8E91\u8E92\u8E93\u8E95", 6, "\u8E9D\u8E9F", 11, "\u8EAD\u8EAE\u8EB0\u8EB1\u8EB3", 6, "\u8EBB", 7],
      ["dc80", "\u8EC3", 10, "\u8ECF", 21, "\u580B\u580D\u57FD\u57ED\u5800\u581E\u5819\u5844\u5820\u5865\u586C\u5881\u5889\u589A\u5880\u99A8\u9F19\u61FF\u8279\u827D\u827F\u828F\u828A\u82A8\u8284\u828E\u8291\u8297\u8299\u82AB\u82B8\u82BE\u82B0\u82C8\u82CA\u82E3\u8298\u82B7\u82AE\u82CB\u82CC\u82C1\u82A9\u82B4\u82A1\u82AA\u829F\u82C4\u82CE\u82A4\u82E1\u8309\u82F7\u82E4\u830F\u8307\u82DC\u82F4\u82D2\u82D8\u830C\u82FB\u82D3\u8311\u831A\u8306\u8314\u8315\u82E0\u82D5\u831C\u8351\u835B\u835C\u8308\u8392\u833C\u8334\u8331\u839B\u835E\u832F\u834F\u8347\u8343\u835F\u8340\u8317\u8360\u832D\u833A\u8333\u8366\u8365"],
      ["dd40", "\u8EE5", 62],
      ["dd80", "\u8F24", 32, "\u8368\u831B\u8369\u836C\u836A\u836D\u836E\u83B0\u8378\u83B3\u83B4\u83A0\u83AA\u8393\u839C\u8385\u837C\u83B6\u83A9\u837D\u83B8\u837B\u8398\u839E\u83A8\u83BA\u83BC\u83C1\u8401\u83E5\u83D8\u5807\u8418\u840B\u83DD\u83FD\u83D6\u841C\u8438\u8411\u8406\u83D4\u83DF\u840F\u8403\u83F8\u83F9\u83EA\u83C5\u83C0\u8426\u83F0\u83E1\u845C\u8451\u845A\u8459\u8473\u8487\u8488\u847A\u8489\u8478\u843C\u8446\u8469\u8476\u848C\u848E\u8431\u846D\u84C1\u84CD\u84D0\u84E6\u84BD\u84D3\u84CA\u84BF\u84BA\u84E0\u84A1\u84B9\u84B4\u8497\u84E5\u84E3\u850C\u750D\u8538\u84F0\u8539\u851F\u853A"],
      ["de40", "\u8F45", 32, "\u8F6A\u8F80\u8F8C\u8F92\u8F9D\u8FA0\u8FA1\u8FA2\u8FA4\u8FA5\u8FA6\u8FA7\u8FAA\u8FAC\u8FAD\u8FAE\u8FAF\u8FB2\u8FB3\u8FB4\u8FB5\u8FB7\u8FB8\u8FBA\u8FBB\u8FBC\u8FBF\u8FC0\u8FC3\u8FC6"],
      ["de80", "\u8FC9", 4, "\u8FCF\u8FD2\u8FD6\u8FD7\u8FDA\u8FE0\u8FE1\u8FE3\u8FE7\u8FEC\u8FEF\u8FF1\u8FF2\u8FF4\u8FF5\u8FF6\u8FFA\u8FFB\u8FFC\u8FFE\u8FFF\u9007\u9008\u900C\u900E\u9013\u9015\u9018\u8556\u853B\u84FF\u84FC\u8559\u8548\u8568\u8564\u855E\u857A\u77A2\u8543\u8572\u857B\u85A4\u85A8\u8587\u858F\u8579\u85AE\u859C\u8585\u85B9\u85B7\u85B0\u85D3\u85C1\u85DC\u85FF\u8627\u8605\u8629\u8616\u863C\u5EFE\u5F08\u593C\u5941\u8037\u5955\u595A\u5958\u530F\u5C22\u5C25\u5C2C\u5C34\u624C\u626A\u629F\u62BB\u62CA\u62DA\u62D7\u62EE\u6322\u62F6\u6339\u634B\u6343\u63AD\u63F6\u6371\u637A\u638E\u63B4\u636D\u63AC\u638A\u6369\u63AE\u63BC\u63F2\u63F8\u63E0\u63FF\u63C4\u63DE\u63CE\u6452\u63C6\u63BE\u6445\u6441\u640B\u641B\u6420\u640C\u6426\u6421\u645E\u6484\u646D\u6496"],
      ["df40", "\u9019\u901C\u9023\u9024\u9025\u9027", 5, "\u9030", 4, "\u9037\u9039\u903A\u903D\u903F\u9040\u9043\u9045\u9046\u9048", 4, "\u904E\u9054\u9055\u9056\u9059\u905A\u905C", 5, "\u9064\u9066\u9067\u9069\u906A\u906B\u906C\u906F", 4, "\u9076", 6, "\u907E\u9081"],
      ["df80", "\u9084\u9085\u9086\u9087\u9089\u908A\u908C", 4, "\u9092\u9094\u9096\u9098\u909A\u909C\u909E\u909F\u90A0\u90A4\u90A5\u90A7\u90A8\u90A9\u90AB\u90AD\u90B2\u90B7\u90BC\u90BD\u90BF\u90C0\u647A\u64B7\u64B8\u6499\u64BA\u64C0\u64D0\u64D7\u64E4\u64E2\u6509\u6525\u652E\u5F0B\u5FD2\u7519\u5F11\u535F\u53F1\u53FD\u53E9\u53E8\u53FB\u5412\u5416\u5406\u544B\u5452\u5453\u5454\u5456\u5443\u5421\u5457\u5459\u5423\u5432\u5482\u5494\u5477\u5471\u5464\u549A\u549B\u5484\u5476\u5466\u549D\u54D0\u54AD\u54C2\u54B4\u54D2\u54A7\u54A6\u54D3\u54D4\u5472\u54A3\u54D5\u54BB\u54BF\u54CC\u54D9\u54DA\u54DC\u54A9\u54AA\u54A4\u54DD\u54CF\u54DE\u551B\u54E7\u5520\u54FD\u5514\u54F3\u5522\u5523\u550F\u5511\u5527\u552A\u5567\u558F\u55B5\u5549\u556D\u5541\u5555\u553F\u5550\u553C"],
      ["e040", "\u90C2\u90C3\u90C6\u90C8\u90C9\u90CB\u90CC\u90CD\u90D2\u90D4\u90D5\u90D6\u90D8\u90D9\u90DA\u90DE\u90DF\u90E0\u90E3\u90E4\u90E5\u90E9\u90EA\u90EC\u90EE\u90F0\u90F1\u90F2\u90F3\u90F5\u90F6\u90F7\u90F9\u90FA\u90FB\u90FC\u90FF\u9100\u9101\u9103\u9105", 19, "\u911A\u911B\u911C"],
      ["e080", "\u911D\u911F\u9120\u9121\u9124", 10, "\u9130\u9132", 6, "\u913A", 8, "\u9144\u5537\u5556\u5575\u5576\u5577\u5533\u5530\u555C\u558B\u55D2\u5583\u55B1\u55B9\u5588\u5581\u559F\u557E\u55D6\u5591\u557B\u55DF\u55BD\u55BE\u5594\u5599\u55EA\u55F7\u55C9\u561F\u55D1\u55EB\u55EC\u55D4\u55E6\u55DD\u55C4\u55EF\u55E5\u55F2\u55F3\u55CC\u55CD\u55E8\u55F5\u55E4\u8F94\u561E\u5608\u560C\u5601\u5624\u5623\u55FE\u5600\u5627\u562D\u5658\u5639\u5657\u562C\u564D\u5662\u5659\u565C\u564C\u5654\u5686\u5664\u5671\u566B\u567B\u567C\u5685\u5693\u56AF\u56D4\u56D7\u56DD\u56E1\u56F5\u56EB\u56F9\u56FF\u5704\u570A\u5709\u571C\u5E0F\u5E19\u5E14\u5E11\u5E31\u5E3B\u5E3C"],
      ["e140", "\u9145\u9147\u9148\u9151\u9153\u9154\u9155\u9156\u9158\u9159\u915B\u915C\u915F\u9160\u9166\u9167\u9168\u916B\u916D\u9173\u917A\u917B\u917C\u9180", 4, "\u9186\u9188\u918A\u918E\u918F\u9193", 6, "\u919C", 5, "\u91A4", 5, "\u91AB\u91AC\u91B0\u91B1\u91B2\u91B3\u91B6\u91B7\u91B8\u91B9\u91BB"],
      ["e180", "\u91BC", 10, "\u91C8\u91CB\u91D0\u91D2", 9, "\u91DD", 8, "\u5E37\u5E44\u5E54\u5E5B\u5E5E\u5E61\u5C8C\u5C7A\u5C8D\u5C90\u5C96\u5C88\u5C98\u5C99\u5C91\u5C9A\u5C9C\u5CB5\u5CA2\u5CBD\u5CAC\u5CAB\u5CB1\u5CA3\u5CC1\u5CB7\u5CC4\u5CD2\u5CE4\u5CCB\u5CE5\u5D02\u5D03\u5D27\u5D26\u5D2E\u5D24\u5D1E\u5D06\u5D1B\u5D58\u5D3E\u5D34\u5D3D\u5D6C\u5D5B\u5D6F\u5D5D\u5D6B\u5D4B\u5D4A\u5D69\u5D74\u5D82\u5D99\u5D9D\u8C73\u5DB7\u5DC5\u5F73\u5F77\u5F82\u5F87\u5F89\u5F8C\u5F95\u5F99\u5F9C\u5FA8\u5FAD\u5FB5\u5FBC\u8862\u5F61\u72AD\u72B0\u72B4\u72B7\u72B8\u72C3\u72C1\u72CE\u72CD\u72D2\u72E8\u72EF\u72E9\u72F2\u72F4\u72F7\u7301\u72F3\u7303\u72FA"],
      ["e240", "\u91E6", 62],
      ["e280", "\u9225", 32, "\u72FB\u7317\u7313\u7321\u730A\u731E\u731D\u7315\u7322\u7339\u7325\u732C\u7338\u7331\u7350\u734D\u7357\u7360\u736C\u736F\u737E\u821B\u5925\u98E7\u5924\u5902\u9963\u9967", 5, "\u9974\u9977\u997D\u9980\u9984\u9987\u998A\u998D\u9990\u9991\u9993\u9994\u9995\u5E80\u5E91\u5E8B\u5E96\u5EA5\u5EA0\u5EB9\u5EB5\u5EBE\u5EB3\u8D53\u5ED2\u5ED1\u5EDB\u5EE8\u5EEA\u81BA\u5FC4\u5FC9\u5FD6\u5FCF\u6003\u5FEE\u6004\u5FE1\u5FE4\u5FFE\u6005\u6006\u5FEA\u5FED\u5FF8\u6019\u6035\u6026\u601B\u600F\u600D\u6029\u602B\u600A\u603F\u6021\u6078\u6079\u607B\u607A\u6042"],
      ["e340", "\u9246", 45, "\u9275", 16],
      ["e380", "\u9286", 7, "\u928F", 24, "\u606A\u607D\u6096\u609A\u60AD\u609D\u6083\u6092\u608C\u609B\u60EC\u60BB\u60B1\u60DD\u60D8\u60C6\u60DA\u60B4\u6120\u6126\u6115\u6123\u60F4\u6100\u610E\u612B\u614A\u6175\u61AC\u6194\u61A7\u61B7\u61D4\u61F5\u5FDD\u96B3\u95E9\u95EB\u95F1\u95F3\u95F5\u95F6\u95FC\u95FE\u9603\u9604\u9606\u9608\u960A\u960B\u960C\u960D\u960F\u9612\u9615\u9616\u9617\u9619\u961A\u4E2C\u723F\u6215\u6C35\u6C54\u6C5C\u6C4A\u6CA3\u6C85\u6C90\u6C94\u6C8C\u6C68\u6C69\u6C74\u6C76\u6C86\u6CA9\u6CD0\u6CD4\u6CAD\u6CF7\u6CF8\u6CF1\u6CD7\u6CB2\u6CE0\u6CD6\u6CFA\u6CEB\u6CEE\u6CB1\u6CD3\u6CEF\u6CFE"],
      ["e440", "\u92A8", 5, "\u92AF", 24, "\u92C9", 31],
      ["e480", "\u92E9", 32, "\u6D39\u6D27\u6D0C\u6D43\u6D48\u6D07\u6D04\u6D19\u6D0E\u6D2B\u6D4D\u6D2E\u6D35\u6D1A\u6D4F\u6D52\u6D54\u6D33\u6D91\u6D6F\u6D9E\u6DA0\u6D5E\u6D93\u6D94\u6D5C\u6D60\u6D7C\u6D63\u6E1A\u6DC7\u6DC5\u6DDE\u6E0E\u6DBF\u6DE0\u6E11\u6DE6\u6DDD\u6DD9\u6E16\u6DAB\u6E0C\u6DAE\u6E2B\u6E6E\u6E4E\u6E6B\u6EB2\u6E5F\u6E86\u6E53\u6E54\u6E32\u6E25\u6E44\u6EDF\u6EB1\u6E98\u6EE0\u6F2D\u6EE2\u6EA5\u6EA7\u6EBD\u6EBB\u6EB7\u6ED7\u6EB4\u6ECF\u6E8F\u6EC2\u6E9F\u6F62\u6F46\u6F47\u6F24\u6F15\u6EF9\u6F2F\u6F36\u6F4B\u6F74\u6F2A\u6F09\u6F29\u6F89\u6F8D\u6F8C\u6F78\u6F72\u6F7C\u6F7A\u6FD1"],
      ["e540", "\u930A", 51, "\u933F", 10],
      ["e580", "\u934A", 31, "\u936B\u6FC9\u6FA7\u6FB9\u6FB6\u6FC2\u6FE1\u6FEE\u6FDE\u6FE0\u6FEF\u701A\u7023\u701B\u7039\u7035\u704F\u705E\u5B80\u5B84\u5B95\u5B93\u5BA5\u5BB8\u752F\u9A9E\u6434\u5BE4\u5BEE\u8930\u5BF0\u8E47\u8B07\u8FB6\u8FD3\u8FD5\u8FE5\u8FEE\u8FE4\u8FE9\u8FE6\u8FF3\u8FE8\u9005\u9004\u900B\u9026\u9011\u900D\u9016\u9021\u9035\u9036\u902D\u902F\u9044\u9051\u9052\u9050\u9068\u9058\u9062\u905B\u66B9\u9074\u907D\u9082\u9088\u9083\u908B\u5F50\u5F57\u5F56\u5F58\u5C3B\u54AB\u5C50\u5C59\u5B71\u5C63\u5C66\u7FBC\u5F2A\u5F29\u5F2D\u8274\u5F3C\u9B3B\u5C6E\u5981\u5983\u598D\u59A9\u59AA\u59A3"],
      ["e640", "\u936C", 34, "\u9390", 27],
      ["e680", "\u93AC", 29, "\u93CB\u93CC\u93CD\u5997\u59CA\u59AB\u599E\u59A4\u59D2\u59B2\u59AF\u59D7\u59BE\u5A05\u5A06\u59DD\u5A08\u59E3\u59D8\u59F9\u5A0C\u5A09\u5A32\u5A34\u5A11\u5A23\u5A13\u5A40\u5A67\u5A4A\u5A55\u5A3C\u5A62\u5A75\u80EC\u5AAA\u5A9B\u5A77\u5A7A\u5ABE\u5AEB\u5AB2\u5AD2\u5AD4\u5AB8\u5AE0\u5AE3\u5AF1\u5AD6\u5AE6\u5AD8\u5ADC\u5B09\u5B17\u5B16\u5B32\u5B37\u5B40\u5C15\u5C1C\u5B5A\u5B65\u5B73\u5B51\u5B53\u5B62\u9A75\u9A77\u9A78\u9A7A\u9A7F\u9A7D\u9A80\u9A81\u9A85\u9A88\u9A8A\u9A90\u9A92\u9A93\u9A96\u9A98\u9A9B\u9A9C\u9A9D\u9A9F\u9AA0\u9AA2\u9AA3\u9AA5\u9AA7\u7E9F\u7EA1\u7EA3\u7EA5\u7EA8\u7EA9"],
      ["e740", "\u93CE", 7, "\u93D7", 54],
      ["e780", "\u940E", 32, "\u7EAD\u7EB0\u7EBE\u7EC0\u7EC1\u7EC2\u7EC9\u7ECB\u7ECC\u7ED0\u7ED4\u7ED7\u7EDB\u7EE0\u7EE1\u7EE8\u7EEB\u7EEE\u7EEF\u7EF1\u7EF2\u7F0D\u7EF6\u7EFA\u7EFB\u7EFE\u7F01\u7F02\u7F03\u7F07\u7F08\u7F0B\u7F0C\u7F0F\u7F11\u7F12\u7F17\u7F19\u7F1C\u7F1B\u7F1F\u7F21", 6, "\u7F2A\u7F2B\u7F2C\u7F2D\u7F2F", 4, "\u7F35\u5E7A\u757F\u5DDB\u753E\u9095\u738E\u7391\u73AE\u73A2\u739F\u73CF\u73C2\u73D1\u73B7\u73B3\u73C0\u73C9\u73C8\u73E5\u73D9\u987C\u740A\u73E9\u73E7\u73DE\u73BA\u73F2\u740F\u742A\u745B\u7426\u7425\u7428\u7430\u742E\u742C"],
      ["e840", "\u942F", 14, "\u943F", 43, "\u946C\u946D\u946E\u946F"],
      ["e880", "\u9470", 20, "\u9491\u9496\u9498\u94C7\u94CF\u94D3\u94D4\u94DA\u94E6\u94FB\u951C\u9520\u741B\u741A\u7441\u745C\u7457\u7455\u7459\u7477\u746D\u747E\u749C\u748E\u7480\u7481\u7487\u748B\u749E\u74A8\u74A9\u7490\u74A7\u74D2\u74BA\u97EA\u97EB\u97EC\u674C\u6753\u675E\u6748\u6769\u67A5\u6787\u676A\u6773\u6798\u67A7\u6775\u67A8\u679E\u67AD\u678B\u6777\u677C\u67F0\u6809\u67D8\u680A\u67E9\u67B0\u680C\u67D9\u67B5\u67DA\u67B3\u67DD\u6800\u67C3\u67B8\u67E2\u680E\u67C1\u67FD\u6832\u6833\u6860\u6861\u684E\u6862\u6844\u6864\u6883\u681D\u6855\u6866\u6841\u6867\u6840\u683E\u684A\u6849\u6829\u68B5\u688F\u6874\u6877\u6893\u686B\u68C2\u696E\u68FC\u691F\u6920\u68F9"],
      ["e940", "\u9527\u9533\u953D\u9543\u9548\u954B\u9555\u955A\u9560\u956E\u9574\u9575\u9577", 7, "\u9580", 42],
      ["e980", "\u95AB", 32, "\u6924\u68F0\u690B\u6901\u6957\u68E3\u6910\u6971\u6939\u6960\u6942\u695D\u6984\u696B\u6980\u6998\u6978\u6934\u69CC\u6987\u6988\u69CE\u6989\u6966\u6963\u6979\u699B\u69A7\u69BB\u69AB\u69AD\u69D4\u69B1\u69C1\u69CA\u69DF\u6995\u69E0\u698D\u69FF\u6A2F\u69ED\u6A17\u6A18\u6A65\u69F2\u6A44\u6A3E\u6AA0\u6A50\u6A5B\u6A35\u6A8E\u6A79\u6A3D\u6A28\u6A58\u6A7C\u6A91\u6A90\u6AA9\u6A97\u6AAB\u7337\u7352\u6B81\u6B82\u6B87\u6B84\u6B92\u6B93\u6B8D\u6B9A\u6B9B\u6BA1\u6BAA\u8F6B\u8F6D\u8F71\u8F72\u8F73\u8F75\u8F76\u8F78\u8F77\u8F79\u8F7A\u8F7C\u8F7E\u8F81\u8F82\u8F84\u8F87\u8F8B"],
      ["ea40", "\u95CC", 27, "\u95EC\u95FF\u9607\u9613\u9618\u961B\u961E\u9620\u9623", 6, "\u962B\u962C\u962D\u962F\u9630\u9637\u9638\u9639\u963A\u963E\u9641\u9643\u964A\u964E\u964F\u9651\u9652\u9653\u9656\u9657"],
      ["ea80", "\u9658\u9659\u965A\u965C\u965D\u965E\u9660\u9663\u9665\u9666\u966B\u966D", 4, "\u9673\u9678", 12, "\u9687\u9689\u968A\u8F8D\u8F8E\u8F8F\u8F98\u8F9A\u8ECE\u620B\u6217\u621B\u621F\u6222\u6221\u6225\u6224\u622C\u81E7\u74EF\u74F4\u74FF\u750F\u7511\u7513\u6534\u65EE\u65EF\u65F0\u660A\u6619\u6772\u6603\u6615\u6600\u7085\u66F7\u661D\u6634\u6631\u6636\u6635\u8006\u665F\u6654\u6641\u664F\u6656\u6661\u6657\u6677\u6684\u668C\u66A7\u669D\u66BE\u66DB\u66DC\u66E6\u66E9\u8D32\u8D33\u8D36\u8D3B\u8D3D\u8D40\u8D45\u8D46\u8D48\u8D49\u8D47\u8D4D\u8D55\u8D59\u89C7\u89CA\u89CB\u89CC\u89CE\u89CF\u89D0\u89D1\u726E\u729F\u725D\u7266\u726F\u727E\u727F\u7284\u728B\u728D\u728F\u7292\u6308\u6332\u63B0"],
      ["eb40", "\u968C\u968E\u9691\u9692\u9693\u9695\u9696\u969A\u969B\u969D", 9, "\u96A8", 7, "\u96B1\u96B2\u96B4\u96B5\u96B7\u96B8\u96BA\u96BB\u96BF\u96C2\u96C3\u96C8\u96CA\u96CB\u96D0\u96D1\u96D3\u96D4\u96D6", 9, "\u96E1", 6, "\u96EB"],
      ["eb80", "\u96EC\u96ED\u96EE\u96F0\u96F1\u96F2\u96F4\u96F5\u96F8\u96FA\u96FB\u96FC\u96FD\u96FF\u9702\u9703\u9705\u970A\u970B\u970C\u9710\u9711\u9712\u9714\u9715\u9717", 4, "\u971D\u971F\u9720\u643F\u64D8\u8004\u6BEA\u6BF3\u6BFD\u6BF5\u6BF9\u6C05\u6C07\u6C06\u6C0D\u6C15\u6C18\u6C19\u6C1A\u6C21\u6C29\u6C24\u6C2A\u6C32\u6535\u6555\u656B\u724D\u7252\u7256\u7230\u8662\u5216\u809F\u809C\u8093\u80BC\u670A\u80BD\u80B1\u80AB\u80AD\u80B4\u80B7\u80E7\u80E8\u80E9\u80EA\u80DB\u80C2\u80C4\u80D9\u80CD\u80D7\u6710\u80DD\u80EB\u80F1\u80F4\u80ED\u810D\u810E\u80F2\u80FC\u6715\u8112\u8C5A\u8136\u811E\u812C\u8118\u8132\u8148\u814C\u8153\u8174\u8159\u815A\u8171\u8160\u8169\u817C\u817D\u816D\u8167\u584D\u5AB5\u8188\u8182\u8191\u6ED5\u81A3\u81AA\u81CC\u6726\u81CA\u81BB"],
      ["ec40", "\u9721", 8, "\u972B\u972C\u972E\u972F\u9731\u9733", 4, "\u973A\u973B\u973C\u973D\u973F", 18, "\u9754\u9755\u9757\u9758\u975A\u975C\u975D\u975F\u9763\u9764\u9766\u9767\u9768\u976A", 7],
      ["ec80", "\u9772\u9775\u9777", 4, "\u977D", 7, "\u9786", 4, "\u978C\u978E\u978F\u9790\u9793\u9795\u9796\u9797\u9799", 4, "\u81C1\u81A6\u6B24\u6B37\u6B39\u6B43\u6B46\u6B59\u98D1\u98D2\u98D3\u98D5\u98D9\u98DA\u6BB3\u5F40\u6BC2\u89F3\u6590\u9F51\u6593\u65BC\u65C6\u65C4\u65C3\u65CC\u65CE\u65D2\u65D6\u7080\u709C\u7096\u709D\u70BB\u70C0\u70B7\u70AB\u70B1\u70E8\u70CA\u7110\u7113\u7116\u712F\u7131\u7173\u715C\u7168\u7145\u7172\u714A\u7178\u717A\u7198\u71B3\u71B5\u71A8\u71A0\u71E0\u71D4\u71E7\u71F9\u721D\u7228\u706C\u7118\u7166\u71B9\u623E\u623D\u6243\u6248\u6249\u793B\u7940\u7946\u7949\u795B\u795C\u7953\u795A\u7962\u7957\u7960\u796F\u7967\u797A\u7985\u798A\u799A\u79A7\u79B3\u5FD1\u5FD0"],
      ["ed40", "\u979E\u979F\u97A1\u97A2\u97A4", 6, "\u97AC\u97AE\u97B0\u97B1\u97B3\u97B5", 46],
      ["ed80", "\u97E4\u97E5\u97E8\u97EE", 4, "\u97F4\u97F7", 23, "\u603C\u605D\u605A\u6067\u6041\u6059\u6063\u60AB\u6106\u610D\u615D\u61A9\u619D\u61CB\u61D1\u6206\u8080\u807F\u6C93\u6CF6\u6DFC\u77F6\u77F8\u7800\u7809\u7817\u7818\u7811\u65AB\u782D\u781C\u781D\u7839\u783A\u783B\u781F\u783C\u7825\u782C\u7823\u7829\u784E\u786D\u7856\u7857\u7826\u7850\u7847\u784C\u786A\u789B\u7893\u789A\u7887\u789C\u78A1\u78A3\u78B2\u78B9\u78A5\u78D4\u78D9\u78C9\u78EC\u78F2\u7905\u78F4\u7913\u7924\u791E\u7934\u9F9B\u9EF9\u9EFB\u9EFC\u76F1\u7704\u770D\u76F9\u7707\u7708\u771A\u7722\u7719\u772D\u7726\u7735\u7738\u7750\u7751\u7747\u7743\u775A\u7768"],
      ["ee40", "\u980F", 62],
      ["ee80", "\u984E", 32, "\u7762\u7765\u777F\u778D\u777D\u7780\u778C\u7791\u779F\u77A0\u77B0\u77B5\u77BD\u753A\u7540\u754E\u754B\u7548\u755B\u7572\u7579\u7583\u7F58\u7F61\u7F5F\u8A48\u7F68\u7F74\u7F71\u7F79\u7F81\u7F7E\u76CD\u76E5\u8832\u9485\u9486\u9487\u948B\u948A\u948C\u948D\u948F\u9490\u9494\u9497\u9495\u949A\u949B\u949C\u94A3\u94A4\u94AB\u94AA\u94AD\u94AC\u94AF\u94B0\u94B2\u94B4\u94B6", 4, "\u94BC\u94BD\u94BF\u94C4\u94C8", 6, "\u94D0\u94D1\u94D2\u94D5\u94D6\u94D7\u94D9\u94D8\u94DB\u94DE\u94DF\u94E0\u94E2\u94E4\u94E5\u94E7\u94E8\u94EA"],
      ["ef40", "\u986F", 5, "\u988B\u988E\u9892\u9895\u9899\u98A3\u98A8", 37, "\u98CF\u98D0\u98D4\u98D6\u98D7\u98DB\u98DC\u98DD\u98E0", 4],
      ["ef80", "\u98E5\u98E6\u98E9", 30, "\u94E9\u94EB\u94EE\u94EF\u94F3\u94F4\u94F5\u94F7\u94F9\u94FC\u94FD\u94FF\u9503\u9502\u9506\u9507\u9509\u950A\u950D\u950E\u950F\u9512", 4, "\u9518\u951B\u951D\u951E\u951F\u9522\u952A\u952B\u9529\u952C\u9531\u9532\u9534\u9536\u9537\u9538\u953C\u953E\u953F\u9542\u9535\u9544\u9545\u9546\u9549\u954C\u954E\u954F\u9552\u9553\u9554\u9556\u9557\u9558\u9559\u955B\u955E\u955F\u955D\u9561\u9562\u9564", 8, "\u956F\u9571\u9572\u9573\u953A\u77E7\u77EC\u96C9\u79D5\u79ED\u79E3\u79EB\u7A06\u5D47\u7A03\u7A02\u7A1E\u7A14"],
      ["f040", "\u9908", 4, "\u990E\u990F\u9911", 28, "\u992F", 26],
      ["f080", "\u994A", 9, "\u9956", 12, "\u9964\u9966\u9973\u9978\u9979\u997B\u997E\u9982\u9983\u9989\u7A39\u7A37\u7A51\u9ECF\u99A5\u7A70\u7688\u768E\u7693\u7699\u76A4\u74DE\u74E0\u752C\u9E20\u9E22\u9E28", 4, "\u9E32\u9E31\u9E36\u9E38\u9E37\u9E39\u9E3A\u9E3E\u9E41\u9E42\u9E44\u9E46\u9E47\u9E48\u9E49\u9E4B\u9E4C\u9E4E\u9E51\u9E55\u9E57\u9E5A\u9E5B\u9E5C\u9E5E\u9E63\u9E66", 6, "\u9E71\u9E6D\u9E73\u7592\u7594\u7596\u75A0\u759D\u75AC\u75A3\u75B3\u75B4\u75B8\u75C4\u75B1\u75B0\u75C3\u75C2\u75D6\u75CD\u75E3\u75E8\u75E6\u75E4\u75EB\u75E7\u7603\u75F1\u75FC\u75FF\u7610\u7600\u7605\u760C\u7617\u760A\u7625\u7618\u7615\u7619"],
      ["f140", "\u998C\u998E\u999A", 10, "\u99A6\u99A7\u99A9", 47],
      ["f180", "\u99D9", 32, "\u761B\u763C\u7622\u7620\u7640\u762D\u7630\u763F\u7635\u7643\u763E\u7633\u764D\u765E\u7654\u765C\u7656\u766B\u766F\u7FCA\u7AE6\u7A78\u7A79\u7A80\u7A86\u7A88\u7A95\u7AA6\u7AA0\u7AAC\u7AA8\u7AAD\u7AB3\u8864\u8869\u8872\u887D\u887F\u8882\u88A2\u88C6\u88B7\u88BC\u88C9\u88E2\u88CE\u88E3\u88E5\u88F1\u891A\u88FC\u88E8\u88FE\u88F0\u8921\u8919\u8913\u891B\u890A\u8934\u892B\u8936\u8941\u8966\u897B\u758B\u80E5\u76B2\u76B4\u77DC\u8012\u8014\u8016\u801C\u8020\u8022\u8025\u8026\u8027\u8029\u8028\u8031\u800B\u8035\u8043\u8046\u804D\u8052\u8069\u8071\u8983\u9878\u9880\u9883"],
      ["f240", "\u99FA", 62],
      ["f280", "\u9A39", 32, "\u9889\u988C\u988D\u988F\u9894\u989A\u989B\u989E\u989F\u98A1\u98A2\u98A5\u98A6\u864D\u8654\u866C\u866E\u867F\u867A\u867C\u867B\u86A8\u868D\u868B\u86AC\u869D\u86A7\u86A3\u86AA\u8693\u86A9\u86B6\u86C4\u86B5\u86CE\u86B0\u86BA\u86B1\u86AF\u86C9\u86CF\u86B4\u86E9\u86F1\u86F2\u86ED\u86F3\u86D0\u8713\u86DE\u86F4\u86DF\u86D8\u86D1\u8703\u8707\u86F8\u8708\u870A\u870D\u8709\u8723\u873B\u871E\u8725\u872E\u871A\u873E\u8748\u8734\u8731\u8729\u8737\u873F\u8782\u8722\u877D\u877E\u877B\u8760\u8770\u874C\u876E\u878B\u8753\u8763\u877C\u8764\u8759\u8765\u8793\u87AF\u87A8\u87D2"],
      ["f340", "\u9A5A", 17, "\u9A72\u9A83\u9A89\u9A8D\u9A8E\u9A94\u9A95\u9A99\u9AA6\u9AA9", 6, "\u9AB2\u9AB3\u9AB4\u9AB5\u9AB9\u9ABB\u9ABD\u9ABE\u9ABF\u9AC3\u9AC4\u9AC6", 4, "\u9ACD\u9ACE\u9ACF\u9AD0\u9AD2\u9AD4\u9AD5\u9AD6\u9AD7\u9AD9\u9ADA\u9ADB\u9ADC"],
      ["f380", "\u9ADD\u9ADE\u9AE0\u9AE2\u9AE3\u9AE4\u9AE5\u9AE7\u9AE8\u9AE9\u9AEA\u9AEC\u9AEE\u9AF0", 8, "\u9AFA\u9AFC", 6, "\u9B04\u9B05\u9B06\u87C6\u8788\u8785\u87AD\u8797\u8783\u87AB\u87E5\u87AC\u87B5\u87B3\u87CB\u87D3\u87BD\u87D1\u87C0\u87CA\u87DB\u87EA\u87E0\u87EE\u8816\u8813\u87FE\u880A\u881B\u8821\u8839\u883C\u7F36\u7F42\u7F44\u7F45\u8210\u7AFA\u7AFD\u7B08\u7B03\u7B04\u7B15\u7B0A\u7B2B\u7B0F\u7B47\u7B38\u7B2A\u7B19\u7B2E\u7B31\u7B20\u7B25\u7B24\u7B33\u7B3E\u7B1E\u7B58\u7B5A\u7B45\u7B75\u7B4C\u7B5D\u7B60\u7B6E\u7B7B\u7B62\u7B72\u7B71\u7B90\u7BA6\u7BA7\u7BB8\u7BAC\u7B9D\u7BA8\u7B85\u7BAA\u7B9C\u7BA2\u7BAB\u7BB4\u7BD1\u7BC1\u7BCC\u7BDD\u7BDA\u7BE5\u7BE6\u7BEA\u7C0C\u7BFE\u7BFC\u7C0F\u7C16\u7C0B"],
      ["f440", "\u9B07\u9B09", 5, "\u9B10\u9B11\u9B12\u9B14", 10, "\u9B20\u9B21\u9B22\u9B24", 10, "\u9B30\u9B31\u9B33", 7, "\u9B3D\u9B3E\u9B3F\u9B40\u9B46\u9B4A\u9B4B\u9B4C\u9B4E\u9B50\u9B52\u9B53\u9B55", 5],
      ["f480", "\u9B5B", 32, "\u7C1F\u7C2A\u7C26\u7C38\u7C41\u7C40\u81FE\u8201\u8202\u8204\u81EC\u8844\u8221\u8222\u8223\u822D\u822F\u8228\u822B\u8238\u823B\u8233\u8234\u823E\u8244\u8249\u824B\u824F\u825A\u825F\u8268\u887E\u8885\u8888\u88D8\u88DF\u895E\u7F9D\u7F9F\u7FA7\u7FAF\u7FB0\u7FB2\u7C7C\u6549\u7C91\u7C9D\u7C9C\u7C9E\u7CA2\u7CB2\u7CBC\u7CBD\u7CC1\u7CC7\u7CCC\u7CCD\u7CC8\u7CC5\u7CD7\u7CE8\u826E\u66A8\u7FBF\u7FCE\u7FD5\u7FE5\u7FE1\u7FE6\u7FE9\u7FEE\u7FF3\u7CF8\u7D77\u7DA6\u7DAE\u7E47\u7E9B\u9EB8\u9EB4\u8D73\u8D84\u8D94\u8D91\u8DB1\u8D67\u8D6D\u8C47\u8C49\u914A\u9150\u914E\u914F\u9164"],
      ["f540", "\u9B7C", 62],
      ["f580", "\u9BBB", 32, "\u9162\u9161\u9170\u9169\u916F\u917D\u917E\u9172\u9174\u9179\u918C\u9185\u9190\u918D\u9191\u91A2\u91A3\u91AA\u91AD\u91AE\u91AF\u91B5\u91B4\u91BA\u8C55\u9E7E\u8DB8\u8DEB\u8E05\u8E59\u8E69\u8DB5\u8DBF\u8DBC\u8DBA\u8DC4\u8DD6\u8DD7\u8DDA\u8DDE\u8DCE\u8DCF\u8DDB\u8DC6\u8DEC\u8DF7\u8DF8\u8DE3\u8DF9\u8DFB\u8DE4\u8E09\u8DFD\u8E14\u8E1D\u8E1F\u8E2C\u8E2E\u8E23\u8E2F\u8E3A\u8E40\u8E39\u8E35\u8E3D\u8E31\u8E49\u8E41\u8E42\u8E51\u8E52\u8E4A\u8E70\u8E76\u8E7C\u8E6F\u8E74\u8E85\u8E8F\u8E94\u8E90\u8E9C\u8E9E\u8C78\u8C82\u8C8A\u8C85\u8C98\u8C94\u659B\u89D6\u89DE\u89DA\u89DC"],
      ["f640", "\u9BDC", 62],
      ["f680", "\u9C1B", 32, "\u89E5\u89EB\u89EF\u8A3E\u8B26\u9753\u96E9\u96F3\u96EF\u9706\u9701\u9708\u970F\u970E\u972A\u972D\u9730\u973E\u9F80\u9F83\u9F85", 5, "\u9F8C\u9EFE\u9F0B\u9F0D\u96B9\u96BC\u96BD\u96CE\u96D2\u77BF\u96E0\u928E\u92AE\u92C8\u933E\u936A\u93CA\u938F\u943E\u946B\u9C7F\u9C82\u9C85\u9C86\u9C87\u9C88\u7A23\u9C8B\u9C8E\u9C90\u9C91\u9C92\u9C94\u9C95\u9C9A\u9C9B\u9C9E", 5, "\u9CA5", 4, "\u9CAB\u9CAD\u9CAE\u9CB0", 7, "\u9CBA\u9CBB\u9CBC\u9CBD\u9CC4\u9CC5\u9CC6\u9CC7\u9CCA\u9CCB"],
      ["f740", "\u9C3C", 62],
      ["f780", "\u9C7B\u9C7D\u9C7E\u9C80\u9C83\u9C84\u9C89\u9C8A\u9C8C\u9C8F\u9C93\u9C96\u9C97\u9C98\u9C99\u9C9D\u9CAA\u9CAC\u9CAF\u9CB9\u9CBE", 4, "\u9CC8\u9CC9\u9CD1\u9CD2\u9CDA\u9CDB\u9CE0\u9CE1\u9CCC", 4, "\u9CD3\u9CD4\u9CD5\u9CD7\u9CD8\u9CD9\u9CDC\u9CDD\u9CDF\u9CE2\u977C\u9785\u9791\u9792\u9794\u97AF\u97AB\u97A3\u97B2\u97B4\u9AB1\u9AB0\u9AB7\u9E58\u9AB6\u9ABA\u9ABC\u9AC1\u9AC0\u9AC5\u9AC2\u9ACB\u9ACC\u9AD1\u9B45\u9B43\u9B47\u9B49\u9B48\u9B4D\u9B51\u98E8\u990D\u992E\u9955\u9954\u9ADF\u9AE1\u9AE6\u9AEF\u9AEB\u9AFB\u9AED\u9AF9\u9B08\u9B0F\u9B13\u9B1F\u9B23\u9EBD\u9EBE\u7E3B\u9E82\u9E87\u9E88\u9E8B\u9E92\u93D6\u9E9D\u9E9F\u9EDB\u9EDC\u9EDD\u9EE0\u9EDF\u9EE2\u9EE9\u9EE7\u9EE5\u9EEA\u9EEF\u9F22\u9F2C\u9F2F\u9F39\u9F37\u9F3D\u9F3E\u9F44"],
      ["f840", "\u9CE3", 62],
      ["f880", "\u9D22", 32],
      ["f940", "\u9D43", 62],
      ["f980", "\u9D82", 32],
      ["fa40", "\u9DA3", 62],
      ["fa80", "\u9DE2", 32],
      ["fb40", "\u9E03", 27, "\u9E24\u9E27\u9E2E\u9E30\u9E34\u9E3B\u9E3C\u9E40\u9E4D\u9E50\u9E52\u9E53\u9E54\u9E56\u9E59\u9E5D\u9E5F\u9E60\u9E61\u9E62\u9E65\u9E6E\u9E6F\u9E72\u9E74", 9, "\u9E80"],
      ["fb80", "\u9E81\u9E83\u9E84\u9E85\u9E86\u9E89\u9E8A\u9E8C", 5, "\u9E94", 8, "\u9E9E\u9EA0", 5, "\u9EA7\u9EA8\u9EA9\u9EAA"],
      ["fc40", "\u9EAB", 8, "\u9EB5\u9EB6\u9EB7\u9EB9\u9EBA\u9EBC\u9EBF", 4, "\u9EC5\u9EC6\u9EC7\u9EC8\u9ECA\u9ECB\u9ECC\u9ED0\u9ED2\u9ED3\u9ED5\u9ED6\u9ED7\u9ED9\u9EDA\u9EDE\u9EE1\u9EE3\u9EE4\u9EE6\u9EE8\u9EEB\u9EEC\u9EED\u9EEE\u9EF0", 8, "\u9EFA\u9EFD\u9EFF", 6],
      ["fc80", "\u9F06", 4, "\u9F0C\u9F0F\u9F11\u9F12\u9F14\u9F15\u9F16\u9F18\u9F1A", 5, "\u9F21\u9F23", 8, "\u9F2D\u9F2E\u9F30\u9F31"],
      ["fd40", "\u9F32", 4, "\u9F38\u9F3A\u9F3C\u9F3F", 4, "\u9F45", 10, "\u9F52", 38],
      ["fd80", "\u9F79", 5, "\u9F81\u9F82\u9F8D", 11, "\u9F9C\u9F9D\u9F9E\u9FA1", 4, "\uF92C\uF979\uF995\uF9E7\uF9F1"],
      ["fe40", "\uFA0C\uFA0D\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA18\uFA1F\uFA20\uFA21\uFA23\uFA24\uFA27\uFA28\uFA29"]
    ];
  }
});

// packages/core/node_modules/iconv-lite/encodings/tables/gbk-added.json
var require_gbk_added = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/tables/gbk-added.json"(exports2, module2) {
    module2.exports = [
      ["a140", "\uE4C6", 62],
      ["a180", "\uE505", 32],
      ["a240", "\uE526", 62],
      ["a280", "\uE565", 32],
      ["a2ab", "\uE766", 5],
      ["a2e3", "\u20AC\uE76D"],
      ["a2ef", "\uE76E\uE76F"],
      ["a2fd", "\uE770\uE771"],
      ["a340", "\uE586", 62],
      ["a380", "\uE5C5", 31, "\u3000"],
      ["a440", "\uE5E6", 62],
      ["a480", "\uE625", 32],
      ["a4f4", "\uE772", 10],
      ["a540", "\uE646", 62],
      ["a580", "\uE685", 32],
      ["a5f7", "\uE77D", 7],
      ["a640", "\uE6A6", 62],
      ["a680", "\uE6E5", 32],
      ["a6b9", "\uE785", 7],
      ["a6d9", "\uE78D", 6],
      ["a6ec", "\uE794\uE795"],
      ["a6f3", "\uE796"],
      ["a6f6", "\uE797", 8],
      ["a740", "\uE706", 62],
      ["a780", "\uE745", 32],
      ["a7c2", "\uE7A0", 14],
      ["a7f2", "\uE7AF", 12],
      ["a896", "\uE7BC", 10],
      ["a8bc", "\u1E3F"],
      ["a8bf", "\u01F9"],
      ["a8c1", "\uE7C9\uE7CA\uE7CB\uE7CC"],
      ["a8ea", "\uE7CD", 20],
      ["a958", "\uE7E2"],
      ["a95b", "\uE7E3"],
      ["a95d", "\uE7E4\uE7E5\uE7E6"],
      ["a989", "\u303E\u2FF0", 11],
      ["a997", "\uE7F4", 12],
      ["a9f0", "\uE801", 14],
      ["aaa1", "\uE000", 93],
      ["aba1", "\uE05E", 93],
      ["aca1", "\uE0BC", 93],
      ["ada1", "\uE11A", 93],
      ["aea1", "\uE178", 93],
      ["afa1", "\uE1D6", 93],
      ["d7fa", "\uE810", 4],
      ["f8a1", "\uE234", 93],
      ["f9a1", "\uE292", 93],
      ["faa1", "\uE2F0", 93],
      ["fba1", "\uE34E", 93],
      ["fca1", "\uE3AC", 93],
      ["fda1", "\uE40A", 93],
      ["fe50", "\u2E81\uE816\uE817\uE818\u2E84\u3473\u3447\u2E88\u2E8B\uE81E\u359E\u361A\u360E\u2E8C\u2E97\u396E\u3918\uE826\u39CF\u39DF\u3A73\u39D0\uE82B\uE82C\u3B4E\u3C6E\u3CE0\u2EA7\uE831\uE832\u2EAA\u4056\u415F\u2EAE\u4337\u2EB3\u2EB6\u2EB7\uE83B\u43B1\u43AC\u2EBB\u43DD\u44D6\u4661\u464C\uE843"],
      ["fe80", "\u4723\u4729\u477C\u478D\u2ECA\u4947\u497A\u497D\u4982\u4983\u4985\u4986\u499F\u499B\u49B7\u49B6\uE854\uE855\u4CA3\u4C9F\u4CA0\u4CA1\u4C77\u4CA2\u4D13", 6, "\u4DAE\uE864\uE468", 93],
      ["8135f437", "\uE7C7"]
    ];
  }
});

// packages/core/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json
var require_gb18030_ranges = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json"(exports2, module2) {
    module2.exports = { uChars: [128, 165, 169, 178, 184, 216, 226, 235, 238, 244, 248, 251, 253, 258, 276, 284, 300, 325, 329, 334, 364, 463, 465, 467, 469, 471, 473, 475, 477, 506, 594, 610, 712, 716, 730, 930, 938, 962, 970, 1026, 1104, 1106, 8209, 8215, 8218, 8222, 8231, 8241, 8244, 8246, 8252, 8365, 8452, 8454, 8458, 8471, 8482, 8556, 8570, 8596, 8602, 8713, 8720, 8722, 8726, 8731, 8737, 8740, 8742, 8748, 8751, 8760, 8766, 8777, 8781, 8787, 8802, 8808, 8816, 8854, 8858, 8870, 8896, 8979, 9322, 9372, 9548, 9588, 9616, 9622, 9634, 9652, 9662, 9672, 9676, 9680, 9702, 9735, 9738, 9793, 9795, 11906, 11909, 11913, 11917, 11928, 11944, 11947, 11951, 11956, 11960, 11964, 11979, 12284, 12292, 12312, 12319, 12330, 12351, 12436, 12447, 12535, 12543, 12586, 12842, 12850, 12964, 13200, 13215, 13218, 13253, 13263, 13267, 13270, 13384, 13428, 13727, 13839, 13851, 14617, 14703, 14801, 14816, 14964, 15183, 15471, 15585, 16471, 16736, 17208, 17325, 17330, 17374, 17623, 17997, 18018, 18212, 18218, 18301, 18318, 18760, 18811, 18814, 18820, 18823, 18844, 18848, 18872, 19576, 19620, 19738, 19887, 40870, 59244, 59336, 59367, 59413, 59417, 59423, 59431, 59437, 59443, 59452, 59460, 59478, 59493, 63789, 63866, 63894, 63976, 63986, 64016, 64018, 64021, 64025, 64034, 64037, 64042, 65074, 65093, 65107, 65112, 65127, 65132, 65375, 65510, 65536], gbChars: [0, 36, 38, 45, 50, 81, 89, 95, 96, 100, 103, 104, 105, 109, 126, 133, 148, 172, 175, 179, 208, 306, 307, 308, 309, 310, 311, 312, 313, 341, 428, 443, 544, 545, 558, 741, 742, 749, 750, 805, 819, 820, 7922, 7924, 7925, 7927, 7934, 7943, 7944, 7945, 7950, 8062, 8148, 8149, 8152, 8164, 8174, 8236, 8240, 8262, 8264, 8374, 8380, 8381, 8384, 8388, 8390, 8392, 8393, 8394, 8396, 8401, 8406, 8416, 8419, 8424, 8437, 8439, 8445, 8482, 8485, 8496, 8521, 8603, 8936, 8946, 9046, 9050, 9063, 9066, 9076, 9092, 9100, 9108, 9111, 9113, 9131, 9162, 9164, 9218, 9219, 11329, 11331, 11334, 11336, 11346, 11361, 11363, 11366, 11370, 11372, 11375, 11389, 11682, 11686, 11687, 11692, 11694, 11714, 11716, 11723, 11725, 11730, 11736, 11982, 11989, 12102, 12336, 12348, 12350, 12384, 12393, 12395, 12397, 12510, 12553, 12851, 12962, 12973, 13738, 13823, 13919, 13933, 14080, 14298, 14585, 14698, 15583, 15847, 16318, 16434, 16438, 16481, 16729, 17102, 17122, 17315, 17320, 17402, 17418, 17859, 17909, 17911, 17915, 17916, 17936, 17939, 17961, 18664, 18703, 18814, 18962, 19043, 33469, 33470, 33471, 33484, 33485, 33490, 33497, 33501, 33505, 33513, 33520, 33536, 33550, 37845, 37921, 37948, 38029, 38038, 38064, 38065, 38066, 38069, 38075, 38076, 38078, 39108, 39109, 39113, 39114, 39115, 39116, 39265, 39394, 189e3] };
  }
});

// packages/core/node_modules/iconv-lite/encodings/tables/cp949.json
var require_cp949 = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/tables/cp949.json"(exports2, module2) {
    module2.exports = [
      ["0", "\0", 127],
      ["8141", "\uAC02\uAC03\uAC05\uAC06\uAC0B", 4, "\uAC18\uAC1E\uAC1F\uAC21\uAC22\uAC23\uAC25", 6, "\uAC2E\uAC32\uAC33\uAC34"],
      ["8161", "\uAC35\uAC36\uAC37\uAC3A\uAC3B\uAC3D\uAC3E\uAC3F\uAC41", 9, "\uAC4C\uAC4E", 5, "\uAC55"],
      ["8181", "\uAC56\uAC57\uAC59\uAC5A\uAC5B\uAC5D", 18, "\uAC72\uAC73\uAC75\uAC76\uAC79\uAC7B", 4, "\uAC82\uAC87\uAC88\uAC8D\uAC8E\uAC8F\uAC91\uAC92\uAC93\uAC95", 6, "\uAC9E\uACA2", 5, "\uACAB\uACAD\uACAE\uACB1", 6, "\uACBA\uACBE\uACBF\uACC0\uACC2\uACC3\uACC5\uACC6\uACC7\uACC9\uACCA\uACCB\uACCD", 7, "\uACD6\uACD8", 7, "\uACE2\uACE3\uACE5\uACE6\uACE9\uACEB\uACED\uACEE\uACF2\uACF4\uACF7", 4, "\uACFE\uACFF\uAD01\uAD02\uAD03\uAD05\uAD07", 4, "\uAD0E\uAD10\uAD12\uAD13"],
      ["8241", "\uAD14\uAD15\uAD16\uAD17\uAD19\uAD1A\uAD1B\uAD1D\uAD1E\uAD1F\uAD21", 7, "\uAD2A\uAD2B\uAD2E", 5],
      ["8261", "\uAD36\uAD37\uAD39\uAD3A\uAD3B\uAD3D", 6, "\uAD46\uAD48\uAD4A", 5, "\uAD51\uAD52\uAD53\uAD55\uAD56\uAD57"],
      ["8281", "\uAD59", 7, "\uAD62\uAD64", 7, "\uAD6E\uAD6F\uAD71\uAD72\uAD77\uAD78\uAD79\uAD7A\uAD7E\uAD80\uAD83", 4, "\uAD8A\uAD8B\uAD8D\uAD8E\uAD8F\uAD91", 10, "\uAD9E", 5, "\uADA5", 17, "\uADB8", 7, "\uADC2\uADC3\uADC5\uADC6\uADC7\uADC9", 6, "\uADD2\uADD4", 7, "\uADDD\uADDE\uADDF\uADE1\uADE2\uADE3\uADE5", 18],
      ["8341", "\uADFA\uADFB\uADFD\uADFE\uAE02", 5, "\uAE0A\uAE0C\uAE0E", 5, "\uAE15", 7],
      ["8361", "\uAE1D", 18, "\uAE32\uAE33\uAE35\uAE36\uAE39\uAE3B\uAE3C"],
      ["8381", "\uAE3D\uAE3E\uAE3F\uAE42\uAE44\uAE47\uAE48\uAE49\uAE4B\uAE4F\uAE51\uAE52\uAE53\uAE55\uAE57", 4, "\uAE5E\uAE62\uAE63\uAE64\uAE66\uAE67\uAE6A\uAE6B\uAE6D\uAE6E\uAE6F\uAE71", 6, "\uAE7A\uAE7E", 5, "\uAE86", 5, "\uAE8D", 46, "\uAEBF\uAEC1\uAEC2\uAEC3\uAEC5", 6, "\uAECE\uAED2", 5, "\uAEDA\uAEDB\uAEDD", 8],
      ["8441", "\uAEE6\uAEE7\uAEE9\uAEEA\uAEEC\uAEEE", 5, "\uAEF5\uAEF6\uAEF7\uAEF9\uAEFA\uAEFB\uAEFD", 8],
      ["8461", "\uAF06\uAF09\uAF0A\uAF0B\uAF0C\uAF0E\uAF0F\uAF11", 18],
      ["8481", "\uAF24", 7, "\uAF2E\uAF2F\uAF31\uAF33\uAF35", 6, "\uAF3E\uAF40\uAF44\uAF45\uAF46\uAF47\uAF4A", 5, "\uAF51", 10, "\uAF5E", 5, "\uAF66", 18, "\uAF7A", 5, "\uAF81\uAF82\uAF83\uAF85\uAF86\uAF87\uAF89", 6, "\uAF92\uAF93\uAF94\uAF96", 5, "\uAF9D", 26, "\uAFBA\uAFBB\uAFBD\uAFBE"],
      ["8541", "\uAFBF\uAFC1", 5, "\uAFCA\uAFCC\uAFCF", 4, "\uAFD5", 6, "\uAFDD", 4],
      ["8561", "\uAFE2", 5, "\uAFEA", 5, "\uAFF2\uAFF3\uAFF5\uAFF6\uAFF7\uAFF9", 6, "\uB002\uB003"],
      ["8581", "\uB005", 6, "\uB00D\uB00E\uB00F\uB011\uB012\uB013\uB015", 6, "\uB01E", 9, "\uB029", 26, "\uB046\uB047\uB049\uB04B\uB04D\uB04F\uB050\uB051\uB052\uB056\uB058\uB05A\uB05B\uB05C\uB05E", 29, "\uB07E\uB07F\uB081\uB082\uB083\uB085", 6, "\uB08E\uB090\uB092", 5, "\uB09B\uB09D\uB09E\uB0A3\uB0A4"],
      ["8641", "\uB0A5\uB0A6\uB0A7\uB0AA\uB0B0\uB0B2\uB0B6\uB0B7\uB0B9\uB0BA\uB0BB\uB0BD", 6, "\uB0C6\uB0CA", 5, "\uB0D2"],
      ["8661", "\uB0D3\uB0D5\uB0D6\uB0D7\uB0D9", 6, "\uB0E1\uB0E2\uB0E3\uB0E4\uB0E6", 10],
      ["8681", "\uB0F1", 22, "\uB10A\uB10D\uB10E\uB10F\uB111\uB114\uB115\uB116\uB117\uB11A\uB11E", 4, "\uB126\uB127\uB129\uB12A\uB12B\uB12D", 6, "\uB136\uB13A", 5, "\uB142\uB143\uB145\uB146\uB147\uB149", 6, "\uB152\uB153\uB156\uB157\uB159\uB15A\uB15B\uB15D\uB15E\uB15F\uB161", 22, "\uB17A\uB17B\uB17D\uB17E\uB17F\uB181\uB183", 4, "\uB18A\uB18C\uB18E\uB18F\uB190\uB191\uB195\uB196\uB197\uB199\uB19A\uB19B\uB19D"],
      ["8741", "\uB19E", 9, "\uB1A9", 15],
      ["8761", "\uB1B9", 18, "\uB1CD\uB1CE\uB1CF\uB1D1\uB1D2\uB1D3\uB1D5"],
      ["8781", "\uB1D6", 5, "\uB1DE\uB1E0", 7, "\uB1EA\uB1EB\uB1ED\uB1EE\uB1EF\uB1F1", 7, "\uB1FA\uB1FC\uB1FE", 5, "\uB206\uB207\uB209\uB20A\uB20D", 6, "\uB216\uB218\uB21A", 5, "\uB221", 18, "\uB235", 6, "\uB23D", 26, "\uB259\uB25A\uB25B\uB25D\uB25E\uB25F\uB261", 6, "\uB26A", 4],
      ["8841", "\uB26F", 4, "\uB276", 5, "\uB27D", 6, "\uB286\uB287\uB288\uB28A", 4],
      ["8861", "\uB28F\uB292\uB293\uB295\uB296\uB297\uB29B", 4, "\uB2A2\uB2A4\uB2A7\uB2A8\uB2A9\uB2AB\uB2AD\uB2AE\uB2AF\uB2B1\uB2B2\uB2B3\uB2B5\uB2B6\uB2B7"],
      ["8881", "\uB2B8", 15, "\uB2CA\uB2CB\uB2CD\uB2CE\uB2CF\uB2D1\uB2D3", 4, "\uB2DA\uB2DC\uB2DE\uB2DF\uB2E0\uB2E1\uB2E3\uB2E7\uB2E9\uB2EA\uB2F0\uB2F1\uB2F2\uB2F6\uB2FC\uB2FD\uB2FE\uB302\uB303\uB305\uB306\uB307\uB309", 6, "\uB312\uB316", 5, "\uB31D", 54, "\uB357\uB359\uB35A\uB35D\uB360\uB361\uB362\uB363"],
      ["8941", "\uB366\uB368\uB36A\uB36C\uB36D\uB36F\uB372\uB373\uB375\uB376\uB377\uB379", 6, "\uB382\uB386", 5, "\uB38D"],
      ["8961", "\uB38E\uB38F\uB391\uB392\uB393\uB395", 10, "\uB3A2", 5, "\uB3A9\uB3AA\uB3AB\uB3AD"],
      ["8981", "\uB3AE", 21, "\uB3C6\uB3C7\uB3C9\uB3CA\uB3CD\uB3CF\uB3D1\uB3D2\uB3D3\uB3D6\uB3D8\uB3DA\uB3DC\uB3DE\uB3DF\uB3E1\uB3E2\uB3E3\uB3E5\uB3E6\uB3E7\uB3E9", 18, "\uB3FD", 18, "\uB411", 6, "\uB419\uB41A\uB41B\uB41D\uB41E\uB41F\uB421", 6, "\uB42A\uB42C", 7, "\uB435", 15],
      ["8a41", "\uB445", 10, "\uB452\uB453\uB455\uB456\uB457\uB459", 6, "\uB462\uB464\uB466"],
      ["8a61", "\uB467", 4, "\uB46D", 18, "\uB481\uB482"],
      ["8a81", "\uB483", 4, "\uB489", 19, "\uB49E", 5, "\uB4A5\uB4A6\uB4A7\uB4A9\uB4AA\uB4AB\uB4AD", 7, "\uB4B6\uB4B8\uB4BA", 5, "\uB4C1\uB4C2\uB4C3\uB4C5\uB4C6\uB4C7\uB4C9", 6, "\uB4D1\uB4D2\uB4D3\uB4D4\uB4D6", 5, "\uB4DE\uB4DF\uB4E1\uB4E2\uB4E5\uB4E7", 4, "\uB4EE\uB4F0\uB4F2", 5, "\uB4F9", 26, "\uB516\uB517\uB519\uB51A\uB51D"],
      ["8b41", "\uB51E", 5, "\uB526\uB52B", 4, "\uB532\uB533\uB535\uB536\uB537\uB539", 6, "\uB542\uB546"],
      ["8b61", "\uB547\uB548\uB549\uB54A\uB54E\uB54F\uB551\uB552\uB553\uB555", 6, "\uB55E\uB562", 8],
      ["8b81", "\uB56B", 52, "\uB5A2\uB5A3\uB5A5\uB5A6\uB5A7\uB5A9\uB5AC\uB5AD\uB5AE\uB5AF\uB5B2\uB5B6", 4, "\uB5BE\uB5BF\uB5C1\uB5C2\uB5C3\uB5C5", 6, "\uB5CE\uB5D2", 5, "\uB5D9", 18, "\uB5ED", 18],
      ["8c41", "\uB600", 15, "\uB612\uB613\uB615\uB616\uB617\uB619", 4],
      ["8c61", "\uB61E", 6, "\uB626", 5, "\uB62D", 6, "\uB635", 5],
      ["8c81", "\uB63B", 12, "\uB649", 26, "\uB665\uB666\uB667\uB669", 50, "\uB69E\uB69F\uB6A1\uB6A2\uB6A3\uB6A5", 5, "\uB6AD\uB6AE\uB6AF\uB6B0\uB6B2", 16],
      ["8d41", "\uB6C3", 16, "\uB6D5", 8],
      ["8d61", "\uB6DE", 17, "\uB6F1\uB6F2\uB6F3\uB6F5\uB6F6\uB6F7\uB6F9\uB6FA"],
      ["8d81", "\uB6FB", 4, "\uB702\uB703\uB704\uB706", 33, "\uB72A\uB72B\uB72D\uB72E\uB731", 6, "\uB73A\uB73C", 7, "\uB745\uB746\uB747\uB749\uB74A\uB74B\uB74D", 6, "\uB756", 9, "\uB761\uB762\uB763\uB765\uB766\uB767\uB769", 6, "\uB772\uB774\uB776", 5, "\uB77E\uB77F\uB781\uB782\uB783\uB785", 6, "\uB78E\uB793\uB794\uB795\uB79A\uB79B\uB79D\uB79E"],
      ["8e41", "\uB79F\uB7A1", 6, "\uB7AA\uB7AE", 5, "\uB7B6\uB7B7\uB7B9", 8],
      ["8e61", "\uB7C2", 4, "\uB7C8\uB7CA", 19],
      ["8e81", "\uB7DE", 13, "\uB7EE\uB7EF\uB7F1\uB7F2\uB7F3\uB7F5", 6, "\uB7FE\uB802", 4, "\uB80A\uB80B\uB80D\uB80E\uB80F\uB811", 6, "\uB81A\uB81C\uB81E", 5, "\uB826\uB827\uB829\uB82A\uB82B\uB82D", 6, "\uB836\uB83A", 5, "\uB841\uB842\uB843\uB845", 11, "\uB852\uB854", 7, "\uB85E\uB85F\uB861\uB862\uB863\uB865", 6, "\uB86E\uB870\uB872", 5, "\uB879\uB87A\uB87B\uB87D", 7],
      ["8f41", "\uB885", 7, "\uB88E", 17],
      ["8f61", "\uB8A0", 7, "\uB8A9", 6, "\uB8B1\uB8B2\uB8B3\uB8B5\uB8B6\uB8B7\uB8B9", 4],
      ["8f81", "\uB8BE\uB8BF\uB8C2\uB8C4\uB8C6", 5, "\uB8CD\uB8CE\uB8CF\uB8D1\uB8D2\uB8D3\uB8D5", 7, "\uB8DE\uB8E0\uB8E2", 5, "\uB8EA\uB8EB\uB8ED\uB8EE\uB8EF\uB8F1", 6, "\uB8FA\uB8FC\uB8FE", 5, "\uB905", 18, "\uB919", 6, "\uB921", 26, "\uB93E\uB93F\uB941\uB942\uB943\uB945", 6, "\uB94D\uB94E\uB950\uB952", 5],
      ["9041", "\uB95A\uB95B\uB95D\uB95E\uB95F\uB961", 6, "\uB96A\uB96C\uB96E", 5, "\uB976\uB977\uB979\uB97A\uB97B\uB97D"],
      ["9061", "\uB97E", 5, "\uB986\uB988\uB98B\uB98C\uB98F", 15],
      ["9081", "\uB99F", 12, "\uB9AE\uB9AF\uB9B1\uB9B2\uB9B3\uB9B5", 6, "\uB9BE\uB9C0\uB9C2", 5, "\uB9CA\uB9CB\uB9CD\uB9D3", 4, "\uB9DA\uB9DC\uB9DF\uB9E0\uB9E2\uB9E6\uB9E7\uB9E9\uB9EA\uB9EB\uB9ED", 6, "\uB9F6\uB9FB", 4, "\uBA02", 5, "\uBA09", 11, "\uBA16", 33, "\uBA3A\uBA3B\uBA3D\uBA3E\uBA3F\uBA41\uBA43\uBA44\uBA45\uBA46"],
      ["9141", "\uBA47\uBA4A\uBA4C\uBA4F\uBA50\uBA51\uBA52\uBA56\uBA57\uBA59\uBA5A\uBA5B\uBA5D", 6, "\uBA66\uBA6A", 5],
      ["9161", "\uBA72\uBA73\uBA75\uBA76\uBA77\uBA79", 9, "\uBA86\uBA88\uBA89\uBA8A\uBA8B\uBA8D", 5],
      ["9181", "\uBA93", 20, "\uBAAA\uBAAD\uBAAE\uBAAF\uBAB1\uBAB3", 4, "\uBABA\uBABC\uBABE", 5, "\uBAC5\uBAC6\uBAC7\uBAC9", 14, "\uBADA", 33, "\uBAFD\uBAFE\uBAFF\uBB01\uBB02\uBB03\uBB05", 7, "\uBB0E\uBB10\uBB12", 5, "\uBB19\uBB1A\uBB1B\uBB1D\uBB1E\uBB1F\uBB21", 6],
      ["9241", "\uBB28\uBB2A\uBB2C", 7, "\uBB37\uBB39\uBB3A\uBB3F", 4, "\uBB46\uBB48\uBB4A\uBB4B\uBB4C\uBB4E\uBB51\uBB52"],
      ["9261", "\uBB53\uBB55\uBB56\uBB57\uBB59", 7, "\uBB62\uBB64", 7, "\uBB6D", 4],
      ["9281", "\uBB72", 21, "\uBB89\uBB8A\uBB8B\uBB8D\uBB8E\uBB8F\uBB91", 18, "\uBBA5\uBBA6\uBBA7\uBBA9\uBBAA\uBBAB\uBBAD", 6, "\uBBB5\uBBB6\uBBB8", 7, "\uBBC1\uBBC2\uBBC3\uBBC5\uBBC6\uBBC7\uBBC9", 6, "\uBBD1\uBBD2\uBBD4", 35, "\uBBFA\uBBFB\uBBFD\uBBFE\uBC01"],
      ["9341", "\uBC03", 4, "\uBC0A\uBC0E\uBC10\uBC12\uBC13\uBC19\uBC1A\uBC20\uBC21\uBC22\uBC23\uBC26\uBC28\uBC2A\uBC2B\uBC2C\uBC2E\uBC2F\uBC32\uBC33\uBC35"],
      ["9361", "\uBC36\uBC37\uBC39", 6, "\uBC42\uBC46\uBC47\uBC48\uBC4A\uBC4B\uBC4E\uBC4F\uBC51", 8],
      ["9381", "\uBC5A\uBC5B\uBC5C\uBC5E", 37, "\uBC86\uBC87\uBC89\uBC8A\uBC8D\uBC8F", 4, "\uBC96\uBC98\uBC9B", 4, "\uBCA2\uBCA3\uBCA5\uBCA6\uBCA9", 6, "\uBCB2\uBCB6", 5, "\uBCBE\uBCBF\uBCC1\uBCC2\uBCC3\uBCC5", 7, "\uBCCE\uBCD2\uBCD3\uBCD4\uBCD6\uBCD7\uBCD9\uBCDA\uBCDB\uBCDD", 22, "\uBCF7\uBCF9\uBCFA\uBCFB\uBCFD"],
      ["9441", "\uBCFE", 5, "\uBD06\uBD08\uBD0A", 5, "\uBD11\uBD12\uBD13\uBD15", 8],
      ["9461", "\uBD1E", 5, "\uBD25", 6, "\uBD2D", 12],
      ["9481", "\uBD3A", 5, "\uBD41", 6, "\uBD4A\uBD4B\uBD4D\uBD4E\uBD4F\uBD51", 6, "\uBD5A", 9, "\uBD65\uBD66\uBD67\uBD69", 22, "\uBD82\uBD83\uBD85\uBD86\uBD8B", 4, "\uBD92\uBD94\uBD96\uBD97\uBD98\uBD9B\uBD9D", 6, "\uBDA5", 10, "\uBDB1", 6, "\uBDB9", 24],
      ["9541", "\uBDD2\uBDD3\uBDD6\uBDD7\uBDD9\uBDDA\uBDDB\uBDDD", 11, "\uBDEA", 5, "\uBDF1"],
      ["9561", "\uBDF2\uBDF3\uBDF5\uBDF6\uBDF7\uBDF9", 6, "\uBE01\uBE02\uBE04\uBE06", 5, "\uBE0E\uBE0F\uBE11\uBE12\uBE13"],
      ["9581", "\uBE15", 6, "\uBE1E\uBE20", 35, "\uBE46\uBE47\uBE49\uBE4A\uBE4B\uBE4D\uBE4F", 4, "\uBE56\uBE58\uBE5C\uBE5D\uBE5E\uBE5F\uBE62\uBE63\uBE65\uBE66\uBE67\uBE69\uBE6B", 4, "\uBE72\uBE76", 4, "\uBE7E\uBE7F\uBE81\uBE82\uBE83\uBE85", 6, "\uBE8E\uBE92", 5, "\uBE9A", 13, "\uBEA9", 14],
      ["9641", "\uBEB8", 23, "\uBED2\uBED3"],
      ["9661", "\uBED5\uBED6\uBED9", 6, "\uBEE1\uBEE2\uBEE6", 5, "\uBEED", 8],
      ["9681", "\uBEF6", 10, "\uBF02", 5, "\uBF0A", 13, "\uBF1A\uBF1E", 33, "\uBF42\uBF43\uBF45\uBF46\uBF47\uBF49", 6, "\uBF52\uBF53\uBF54\uBF56", 44],
      ["9741", "\uBF83", 16, "\uBF95", 8],
      ["9761", "\uBF9E", 17, "\uBFB1", 7],
      ["9781", "\uBFB9", 11, "\uBFC6", 5, "\uBFCE\uBFCF\uBFD1\uBFD2\uBFD3\uBFD5", 6, "\uBFDD\uBFDE\uBFE0\uBFE2", 89, "\uC03D\uC03E\uC03F"],
      ["9841", "\uC040", 16, "\uC052", 5, "\uC059\uC05A\uC05B"],
      ["9861", "\uC05D\uC05E\uC05F\uC061", 6, "\uC06A", 15],
      ["9881", "\uC07A", 21, "\uC092\uC093\uC095\uC096\uC097\uC099", 6, "\uC0A2\uC0A4\uC0A6", 5, "\uC0AE\uC0B1\uC0B2\uC0B7", 4, "\uC0BE\uC0C2\uC0C3\uC0C4\uC0C6\uC0C7\uC0CA\uC0CB\uC0CD\uC0CE\uC0CF\uC0D1", 6, "\uC0DA\uC0DE", 5, "\uC0E6\uC0E7\uC0E9\uC0EA\uC0EB\uC0ED", 6, "\uC0F6\uC0F8\uC0FA", 5, "\uC101\uC102\uC103\uC105\uC106\uC107\uC109", 6, "\uC111\uC112\uC113\uC114\uC116", 5, "\uC121\uC122\uC125\uC128\uC129\uC12A\uC12B\uC12E"],
      ["9941", "\uC132\uC133\uC134\uC135\uC137\uC13A\uC13B\uC13D\uC13E\uC13F\uC141", 6, "\uC14A\uC14E", 5, "\uC156\uC157"],
      ["9961", "\uC159\uC15A\uC15B\uC15D", 6, "\uC166\uC16A", 5, "\uC171\uC172\uC173\uC175\uC176\uC177\uC179\uC17A\uC17B"],
      ["9981", "\uC17C", 8, "\uC186", 5, "\uC18F\uC191\uC192\uC193\uC195\uC197", 4, "\uC19E\uC1A0\uC1A2\uC1A3\uC1A4\uC1A6\uC1A7\uC1AA\uC1AB\uC1AD\uC1AE\uC1AF\uC1B1", 11, "\uC1BE", 5, "\uC1C5\uC1C6\uC1C7\uC1C9\uC1CA\uC1CB\uC1CD", 6, "\uC1D5\uC1D6\uC1D9", 6, "\uC1E1\uC1E2\uC1E3\uC1E5\uC1E6\uC1E7\uC1E9", 6, "\uC1F2\uC1F4", 7, "\uC1FE\uC1FF\uC201\uC202\uC203\uC205", 6, "\uC20E\uC210\uC212", 5, "\uC21A\uC21B\uC21D\uC21E\uC221\uC222\uC223"],
      ["9a41", "\uC224\uC225\uC226\uC227\uC22A\uC22C\uC22E\uC230\uC233\uC235", 16],
      ["9a61", "\uC246\uC247\uC249", 6, "\uC252\uC253\uC255\uC256\uC257\uC259", 6, "\uC261\uC262\uC263\uC264\uC266"],
      ["9a81", "\uC267", 4, "\uC26E\uC26F\uC271\uC272\uC273\uC275", 6, "\uC27E\uC280\uC282", 5, "\uC28A", 5, "\uC291", 6, "\uC299\uC29A\uC29C\uC29E", 5, "\uC2A6\uC2A7\uC2A9\uC2AA\uC2AB\uC2AE", 5, "\uC2B6\uC2B8\uC2BA", 33, "\uC2DE\uC2DF\uC2E1\uC2E2\uC2E5", 5, "\uC2EE\uC2F0\uC2F2\uC2F3\uC2F4\uC2F5\uC2F7\uC2FA\uC2FD\uC2FE\uC2FF\uC301", 6, "\uC30A\uC30B\uC30E\uC30F"],
      ["9b41", "\uC310\uC311\uC312\uC316\uC317\uC319\uC31A\uC31B\uC31D", 6, "\uC326\uC327\uC32A", 8],
      ["9b61", "\uC333", 17, "\uC346", 7],
      ["9b81", "\uC34E", 25, "\uC36A\uC36B\uC36D\uC36E\uC36F\uC371\uC373", 4, "\uC37A\uC37B\uC37E", 5, "\uC385\uC386\uC387\uC389\uC38A\uC38B\uC38D", 50, "\uC3C1", 22, "\uC3DA"],
      ["9c41", "\uC3DB\uC3DD\uC3DE\uC3E1\uC3E3", 4, "\uC3EA\uC3EB\uC3EC\uC3EE", 5, "\uC3F6\uC3F7\uC3F9", 5],
      ["9c61", "\uC3FF", 8, "\uC409", 6, "\uC411", 9],
      ["9c81", "\uC41B", 8, "\uC425", 6, "\uC42D\uC42E\uC42F\uC431\uC432\uC433\uC435", 6, "\uC43E", 9, "\uC449", 26, "\uC466\uC467\uC469\uC46A\uC46B\uC46D", 6, "\uC476\uC477\uC478\uC47A", 5, "\uC481", 18, "\uC495", 6, "\uC49D", 12],
      ["9d41", "\uC4AA", 13, "\uC4B9\uC4BA\uC4BB\uC4BD", 8],
      ["9d61", "\uC4C6", 25],
      ["9d81", "\uC4E0", 8, "\uC4EA", 5, "\uC4F2\uC4F3\uC4F5\uC4F6\uC4F7\uC4F9\uC4FB\uC4FC\uC4FD\uC4FE\uC502", 9, "\uC50D\uC50E\uC50F\uC511\uC512\uC513\uC515", 6, "\uC51D", 10, "\uC52A\uC52B\uC52D\uC52E\uC52F\uC531", 6, "\uC53A\uC53C\uC53E", 5, "\uC546\uC547\uC54B\uC54F\uC550\uC551\uC552\uC556\uC55A\uC55B\uC55C\uC55F\uC562\uC563\uC565\uC566\uC567\uC569", 6, "\uC572\uC576", 5, "\uC57E\uC57F\uC581\uC582\uC583\uC585\uC586\uC588\uC589\uC58A\uC58B\uC58E\uC590\uC592\uC593\uC594"],
      ["9e41", "\uC596\uC599\uC59A\uC59B\uC59D\uC59E\uC59F\uC5A1", 7, "\uC5AA", 9, "\uC5B6"],
      ["9e61", "\uC5B7\uC5BA\uC5BF", 4, "\uC5CB\uC5CD\uC5CF\uC5D2\uC5D3\uC5D5\uC5D6\uC5D7\uC5D9", 6, "\uC5E2\uC5E4\uC5E6\uC5E7"],
      ["9e81", "\uC5E8\uC5E9\uC5EA\uC5EB\uC5EF\uC5F1\uC5F2\uC5F3\uC5F5\uC5F8\uC5F9\uC5FA\uC5FB\uC602\uC603\uC604\uC609\uC60A\uC60B\uC60D\uC60E\uC60F\uC611", 6, "\uC61A\uC61D", 6, "\uC626\uC627\uC629\uC62A\uC62B\uC62F\uC631\uC632\uC636\uC638\uC63A\uC63C\uC63D\uC63E\uC63F\uC642\uC643\uC645\uC646\uC647\uC649", 6, "\uC652\uC656", 5, "\uC65E\uC65F\uC661", 10, "\uC66D\uC66E\uC670\uC672", 5, "\uC67A\uC67B\uC67D\uC67E\uC67F\uC681", 6, "\uC68A\uC68C\uC68E", 5, "\uC696\uC697\uC699\uC69A\uC69B\uC69D", 6, "\uC6A6"],
      ["9f41", "\uC6A8\uC6AA", 5, "\uC6B2\uC6B3\uC6B5\uC6B6\uC6B7\uC6BB", 4, "\uC6C2\uC6C4\uC6C6", 5, "\uC6CE"],
      ["9f61", "\uC6CF\uC6D1\uC6D2\uC6D3\uC6D5", 6, "\uC6DE\uC6DF\uC6E2", 5, "\uC6EA\uC6EB\uC6ED\uC6EE\uC6EF\uC6F1\uC6F2"],
      ["9f81", "\uC6F3", 4, "\uC6FA\uC6FB\uC6FC\uC6FE", 5, "\uC706\uC707\uC709\uC70A\uC70B\uC70D", 6, "\uC716\uC718\uC71A", 5, "\uC722\uC723\uC725\uC726\uC727\uC729", 6, "\uC732\uC734\uC736\uC738\uC739\uC73A\uC73B\uC73E\uC73F\uC741\uC742\uC743\uC745", 4, "\uC74B\uC74E\uC750\uC759\uC75A\uC75B\uC75D\uC75E\uC75F\uC761", 6, "\uC769\uC76A\uC76C", 7, "\uC776\uC777\uC779\uC77A\uC77B\uC77F\uC780\uC781\uC782\uC786\uC78B\uC78C\uC78D\uC78F\uC792\uC793\uC795\uC799\uC79B", 4, "\uC7A2\uC7A7", 4, "\uC7AE\uC7AF\uC7B1\uC7B2\uC7B3\uC7B5\uC7B6\uC7B7"],
      ["a041", "\uC7B8\uC7B9\uC7BA\uC7BB\uC7BE\uC7C2", 5, "\uC7CA\uC7CB\uC7CD\uC7CF\uC7D1", 6, "\uC7D9\uC7DA\uC7DB\uC7DC"],
      ["a061", "\uC7DE", 5, "\uC7E5\uC7E6\uC7E7\uC7E9\uC7EA\uC7EB\uC7ED", 13],
      ["a081", "\uC7FB", 4, "\uC802\uC803\uC805\uC806\uC807\uC809\uC80B", 4, "\uC812\uC814\uC817", 4, "\uC81E\uC81F\uC821\uC822\uC823\uC825", 6, "\uC82E\uC830\uC832", 5, "\uC839\uC83A\uC83B\uC83D\uC83E\uC83F\uC841", 6, "\uC84A\uC84B\uC84E", 5, "\uC855", 26, "\uC872\uC873\uC875\uC876\uC877\uC879\uC87B", 4, "\uC882\uC884\uC888\uC889\uC88A\uC88E", 5, "\uC895", 7, "\uC89E\uC8A0\uC8A2\uC8A3\uC8A4"],
      ["a141", "\uC8A5\uC8A6\uC8A7\uC8A9", 18, "\uC8BE\uC8BF\uC8C0\uC8C1"],
      ["a161", "\uC8C2\uC8C3\uC8C5\uC8C6\uC8C7\uC8C9\uC8CA\uC8CB\uC8CD", 6, "\uC8D6\uC8D8\uC8DA", 5, "\uC8E2\uC8E3\uC8E5"],
      ["a181", "\uC8E6", 14, "\uC8F6", 5, "\uC8FE\uC8FF\uC901\uC902\uC903\uC907", 4, "\uC90E\u3000\u3001\u3002\xB7\u2025\u2026\xA8\u3003\xAD\u2015\u2225\uFF3C\u223C\u2018\u2019\u201C\u201D\u3014\u3015\u3008", 9, "\xB1\xD7\xF7\u2260\u2264\u2265\u221E\u2234\xB0\u2032\u2033\u2103\u212B\uFFE0\uFFE1\uFFE5\u2642\u2640\u2220\u22A5\u2312\u2202\u2207\u2261\u2252\xA7\u203B\u2606\u2605\u25CB\u25CF\u25CE\u25C7\u25C6\u25A1\u25A0\u25B3\u25B2\u25BD\u25BC\u2192\u2190\u2191\u2193\u2194\u3013\u226A\u226B\u221A\u223D\u221D\u2235\u222B\u222C\u2208\u220B\u2286\u2287\u2282\u2283\u222A\u2229\u2227\u2228\uFFE2"],
      ["a241", "\uC910\uC912", 5, "\uC919", 18],
      ["a261", "\uC92D", 6, "\uC935", 18],
      ["a281", "\uC948", 7, "\uC952\uC953\uC955\uC956\uC957\uC959", 6, "\uC962\uC964", 7, "\uC96D\uC96E\uC96F\u21D2\u21D4\u2200\u2203\xB4\uFF5E\u02C7\u02D8\u02DD\u02DA\u02D9\xB8\u02DB\xA1\xBF\u02D0\u222E\u2211\u220F\xA4\u2109\u2030\u25C1\u25C0\u25B7\u25B6\u2664\u2660\u2661\u2665\u2667\u2663\u2299\u25C8\u25A3\u25D0\u25D1\u2592\u25A4\u25A5\u25A8\u25A7\u25A6\u25A9\u2668\u260F\u260E\u261C\u261E\xB6\u2020\u2021\u2195\u2197\u2199\u2196\u2198\u266D\u2669\u266A\u266C\u327F\u321C\u2116\u33C7\u2122\u33C2\u33D8\u2121\u20AC\xAE"],
      ["a341", "\uC971\uC972\uC973\uC975", 6, "\uC97D", 10, "\uC98A\uC98B\uC98D\uC98E\uC98F"],
      ["a361", "\uC991", 6, "\uC99A\uC99C\uC99E", 16],
      ["a381", "\uC9AF", 16, "\uC9C2\uC9C3\uC9C5\uC9C6\uC9C9\uC9CB", 4, "\uC9D2\uC9D4\uC9D7\uC9D8\uC9DB\uFF01", 58, "\uFFE6\uFF3D", 32, "\uFFE3"],
      ["a441", "\uC9DE\uC9DF\uC9E1\uC9E3\uC9E5\uC9E6\uC9E8\uC9E9\uC9EA\uC9EB\uC9EE\uC9F2", 5, "\uC9FA\uC9FB\uC9FD\uC9FE\uC9FF\uCA01\uCA02\uCA03\uCA04"],
      ["a461", "\uCA05\uCA06\uCA07\uCA0A\uCA0E", 5, "\uCA15\uCA16\uCA17\uCA19", 12],
      ["a481", "\uCA26\uCA27\uCA28\uCA2A", 28, "\u3131", 93],
      ["a541", "\uCA47", 4, "\uCA4E\uCA4F\uCA51\uCA52\uCA53\uCA55", 6, "\uCA5E\uCA62", 5, "\uCA69\uCA6A"],
      ["a561", "\uCA6B", 17, "\uCA7E", 5, "\uCA85\uCA86"],
      ["a581", "\uCA87", 16, "\uCA99", 14, "\u2170", 9],
      ["a5b0", "\u2160", 9],
      ["a5c1", "\u0391", 16, "\u03A3", 6],
      ["a5e1", "\u03B1", 16, "\u03C3", 6],
      ["a641", "\uCAA8", 19, "\uCABE\uCABF\uCAC1\uCAC2\uCAC3\uCAC5"],
      ["a661", "\uCAC6", 5, "\uCACE\uCAD0\uCAD2\uCAD4\uCAD5\uCAD6\uCAD7\uCADA", 5, "\uCAE1", 6],
      ["a681", "\uCAE8\uCAE9\uCAEA\uCAEB\uCAED", 6, "\uCAF5", 18, "\uCB09\uCB0A\u2500\u2502\u250C\u2510\u2518\u2514\u251C\u252C\u2524\u2534\u253C\u2501\u2503\u250F\u2513\u251B\u2517\u2523\u2533\u252B\u253B\u254B\u2520\u252F\u2528\u2537\u253F\u251D\u2530\u2525\u2538\u2542\u2512\u2511\u251A\u2519\u2516\u2515\u250E\u250D\u251E\u251F\u2521\u2522\u2526\u2527\u2529\u252A\u252D\u252E\u2531\u2532\u2535\u2536\u2539\u253A\u253D\u253E\u2540\u2541\u2543", 7],
      ["a741", "\uCB0B", 4, "\uCB11\uCB12\uCB13\uCB15\uCB16\uCB17\uCB19", 6, "\uCB22", 7],
      ["a761", "\uCB2A", 22, "\uCB42\uCB43\uCB44"],
      ["a781", "\uCB45\uCB46\uCB47\uCB4A\uCB4B\uCB4D\uCB4E\uCB4F\uCB51", 6, "\uCB5A\uCB5B\uCB5C\uCB5E", 5, "\uCB65", 7, "\u3395\u3396\u3397\u2113\u3398\u33C4\u33A3\u33A4\u33A5\u33A6\u3399", 9, "\u33CA\u338D\u338E\u338F\u33CF\u3388\u3389\u33C8\u33A7\u33A8\u33B0", 9, "\u3380", 4, "\u33BA", 5, "\u3390", 4, "\u2126\u33C0\u33C1\u338A\u338B\u338C\u33D6\u33C5\u33AD\u33AE\u33AF\u33DB\u33A9\u33AA\u33AB\u33AC\u33DD\u33D0\u33D3\u33C3\u33C9\u33DC\u33C6"],
      ["a841", "\uCB6D", 10, "\uCB7A", 14],
      ["a861", "\uCB89", 18, "\uCB9D", 6],
      ["a881", "\uCBA4", 19, "\uCBB9", 11, "\xC6\xD0\xAA\u0126"],
      ["a8a6", "\u0132"],
      ["a8a8", "\u013F\u0141\xD8\u0152\xBA\xDE\u0166\u014A"],
      ["a8b1", "\u3260", 27, "\u24D0", 25, "\u2460", 14, "\xBD\u2153\u2154\xBC\xBE\u215B\u215C\u215D\u215E"],
      ["a941", "\uCBC5", 14, "\uCBD5", 10],
      ["a961", "\uCBE0\uCBE1\uCBE2\uCBE3\uCBE5\uCBE6\uCBE8\uCBEA", 18],
      ["a981", "\uCBFD", 14, "\uCC0E\uCC0F\uCC11\uCC12\uCC13\uCC15", 6, "\uCC1E\uCC1F\uCC20\uCC23\uCC24\xE6\u0111\xF0\u0127\u0131\u0133\u0138\u0140\u0142\xF8\u0153\xDF\xFE\u0167\u014B\u0149\u3200", 27, "\u249C", 25, "\u2474", 14, "\xB9\xB2\xB3\u2074\u207F\u2081\u2082\u2083\u2084"],
      ["aa41", "\uCC25\uCC26\uCC2A\uCC2B\uCC2D\uCC2F\uCC31", 6, "\uCC3A\uCC3F", 4, "\uCC46\uCC47\uCC49\uCC4A\uCC4B\uCC4D\uCC4E"],
      ["aa61", "\uCC4F", 4, "\uCC56\uCC5A", 5, "\uCC61\uCC62\uCC63\uCC65\uCC67\uCC69", 6, "\uCC71\uCC72"],
      ["aa81", "\uCC73\uCC74\uCC76", 29, "\u3041", 82],
      ["ab41", "\uCC94\uCC95\uCC96\uCC97\uCC9A\uCC9B\uCC9D\uCC9E\uCC9F\uCCA1", 6, "\uCCAA\uCCAE", 5, "\uCCB6\uCCB7\uCCB9"],
      ["ab61", "\uCCBA\uCCBB\uCCBD", 6, "\uCCC6\uCCC8\uCCCA", 5, "\uCCD1\uCCD2\uCCD3\uCCD5", 5],
      ["ab81", "\uCCDB", 8, "\uCCE5", 6, "\uCCED\uCCEE\uCCEF\uCCF1", 12, "\u30A1", 85],
      ["ac41", "\uCCFE\uCCFF\uCD00\uCD02", 5, "\uCD0A\uCD0B\uCD0D\uCD0E\uCD0F\uCD11", 6, "\uCD1A\uCD1C\uCD1E\uCD1F\uCD20"],
      ["ac61", "\uCD21\uCD22\uCD23\uCD25\uCD26\uCD27\uCD29\uCD2A\uCD2B\uCD2D", 11, "\uCD3A", 4],
      ["ac81", "\uCD3F", 28, "\uCD5D\uCD5E\uCD5F\u0410", 5, "\u0401\u0416", 25],
      ["acd1", "\u0430", 5, "\u0451\u0436", 25],
      ["ad41", "\uCD61\uCD62\uCD63\uCD65", 6, "\uCD6E\uCD70\uCD72", 5, "\uCD79", 7],
      ["ad61", "\uCD81", 6, "\uCD89", 10, "\uCD96\uCD97\uCD99\uCD9A\uCD9B\uCD9D\uCD9E\uCD9F"],
      ["ad81", "\uCDA0\uCDA1\uCDA2\uCDA3\uCDA6\uCDA8\uCDAA", 5, "\uCDB1", 18, "\uCDC5"],
      ["ae41", "\uCDC6", 5, "\uCDCD\uCDCE\uCDCF\uCDD1", 16],
      ["ae61", "\uCDE2", 5, "\uCDE9\uCDEA\uCDEB\uCDED\uCDEE\uCDEF\uCDF1", 6, "\uCDFA\uCDFC\uCDFE", 4],
      ["ae81", "\uCE03\uCE05\uCE06\uCE07\uCE09\uCE0A\uCE0B\uCE0D", 6, "\uCE15\uCE16\uCE17\uCE18\uCE1A", 5, "\uCE22\uCE23\uCE25\uCE26\uCE27\uCE29\uCE2A\uCE2B"],
      ["af41", "\uCE2C\uCE2D\uCE2E\uCE2F\uCE32\uCE34\uCE36", 19],
      ["af61", "\uCE4A", 13, "\uCE5A\uCE5B\uCE5D\uCE5E\uCE62", 5, "\uCE6A\uCE6C"],
      ["af81", "\uCE6E", 5, "\uCE76\uCE77\uCE79\uCE7A\uCE7B\uCE7D", 6, "\uCE86\uCE88\uCE8A", 5, "\uCE92\uCE93\uCE95\uCE96\uCE97\uCE99"],
      ["b041", "\uCE9A", 5, "\uCEA2\uCEA6", 5, "\uCEAE", 12],
      ["b061", "\uCEBB", 5, "\uCEC2", 19],
      ["b081", "\uCED6", 13, "\uCEE6\uCEE7\uCEE9\uCEEA\uCEED", 6, "\uCEF6\uCEFA", 5, "\uAC00\uAC01\uAC04\uAC07\uAC08\uAC09\uAC0A\uAC10", 7, "\uAC19", 4, "\uAC20\uAC24\uAC2C\uAC2D\uAC2F\uAC30\uAC31\uAC38\uAC39\uAC3C\uAC40\uAC4B\uAC4D\uAC54\uAC58\uAC5C\uAC70\uAC71\uAC74\uAC77\uAC78\uAC7A\uAC80\uAC81\uAC83\uAC84\uAC85\uAC86\uAC89\uAC8A\uAC8B\uAC8C\uAC90\uAC94\uAC9C\uAC9D\uAC9F\uACA0\uACA1\uACA8\uACA9\uACAA\uACAC\uACAF\uACB0\uACB8\uACB9\uACBB\uACBC\uACBD\uACC1\uACC4\uACC8\uACCC\uACD5\uACD7\uACE0\uACE1\uACE4\uACE7\uACE8\uACEA\uACEC\uACEF\uACF0\uACF1\uACF3\uACF5\uACF6\uACFC\uACFD\uAD00\uAD04\uAD06"],
      ["b141", "\uCF02\uCF03\uCF05\uCF06\uCF07\uCF09", 6, "\uCF12\uCF14\uCF16", 5, "\uCF1D\uCF1E\uCF1F\uCF21\uCF22\uCF23"],
      ["b161", "\uCF25", 6, "\uCF2E\uCF32", 5, "\uCF39", 11],
      ["b181", "\uCF45", 14, "\uCF56\uCF57\uCF59\uCF5A\uCF5B\uCF5D", 6, "\uCF66\uCF68\uCF6A\uCF6B\uCF6C\uAD0C\uAD0D\uAD0F\uAD11\uAD18\uAD1C\uAD20\uAD29\uAD2C\uAD2D\uAD34\uAD35\uAD38\uAD3C\uAD44\uAD45\uAD47\uAD49\uAD50\uAD54\uAD58\uAD61\uAD63\uAD6C\uAD6D\uAD70\uAD73\uAD74\uAD75\uAD76\uAD7B\uAD7C\uAD7D\uAD7F\uAD81\uAD82\uAD88\uAD89\uAD8C\uAD90\uAD9C\uAD9D\uADA4\uADB7\uADC0\uADC1\uADC4\uADC8\uADD0\uADD1\uADD3\uADDC\uADE0\uADE4\uADF8\uADF9\uADFC\uADFF\uAE00\uAE01\uAE08\uAE09\uAE0B\uAE0D\uAE14\uAE30\uAE31\uAE34\uAE37\uAE38\uAE3A\uAE40\uAE41\uAE43\uAE45\uAE46\uAE4A\uAE4C\uAE4D\uAE4E\uAE50\uAE54\uAE56\uAE5C\uAE5D\uAE5F\uAE60\uAE61\uAE65\uAE68\uAE69\uAE6C\uAE70\uAE78"],
      ["b241", "\uCF6D\uCF6E\uCF6F\uCF72\uCF73\uCF75\uCF76\uCF77\uCF79", 6, "\uCF81\uCF82\uCF83\uCF84\uCF86", 5, "\uCF8D"],
      ["b261", "\uCF8E", 18, "\uCFA2", 5, "\uCFA9"],
      ["b281", "\uCFAA", 5, "\uCFB1", 18, "\uCFC5", 6, "\uAE79\uAE7B\uAE7C\uAE7D\uAE84\uAE85\uAE8C\uAEBC\uAEBD\uAEBE\uAEC0\uAEC4\uAECC\uAECD\uAECF\uAED0\uAED1\uAED8\uAED9\uAEDC\uAEE8\uAEEB\uAEED\uAEF4\uAEF8\uAEFC\uAF07\uAF08\uAF0D\uAF10\uAF2C\uAF2D\uAF30\uAF32\uAF34\uAF3C\uAF3D\uAF3F\uAF41\uAF42\uAF43\uAF48\uAF49\uAF50\uAF5C\uAF5D\uAF64\uAF65\uAF79\uAF80\uAF84\uAF88\uAF90\uAF91\uAF95\uAF9C\uAFB8\uAFB9\uAFBC\uAFC0\uAFC7\uAFC8\uAFC9\uAFCB\uAFCD\uAFCE\uAFD4\uAFDC\uAFE8\uAFE9\uAFF0\uAFF1\uAFF4\uAFF8\uB000\uB001\uB004\uB00C\uB010\uB014\uB01C\uB01D\uB028\uB044\uB045\uB048\uB04A\uB04C\uB04E\uB053\uB054\uB055\uB057\uB059"],
      ["b341", "\uCFCC", 19, "\uCFE2\uCFE3\uCFE5\uCFE6\uCFE7\uCFE9"],
      ["b361", "\uCFEA", 5, "\uCFF2\uCFF4\uCFF6", 5, "\uCFFD\uCFFE\uCFFF\uD001\uD002\uD003\uD005", 5],
      ["b381", "\uD00B", 5, "\uD012", 5, "\uD019", 19, "\uB05D\uB07C\uB07D\uB080\uB084\uB08C\uB08D\uB08F\uB091\uB098\uB099\uB09A\uB09C\uB09F\uB0A0\uB0A1\uB0A2\uB0A8\uB0A9\uB0AB", 4, "\uB0B1\uB0B3\uB0B4\uB0B5\uB0B8\uB0BC\uB0C4\uB0C5\uB0C7\uB0C8\uB0C9\uB0D0\uB0D1\uB0D4\uB0D8\uB0E0\uB0E5\uB108\uB109\uB10B\uB10C\uB110\uB112\uB113\uB118\uB119\uB11B\uB11C\uB11D\uB123\uB124\uB125\uB128\uB12C\uB134\uB135\uB137\uB138\uB139\uB140\uB141\uB144\uB148\uB150\uB151\uB154\uB155\uB158\uB15C\uB160\uB178\uB179\uB17C\uB180\uB182\uB188\uB189\uB18B\uB18D\uB192\uB193\uB194\uB198\uB19C\uB1A8\uB1CC\uB1D0\uB1D4\uB1DC\uB1DD"],
      ["b441", "\uD02E", 5, "\uD036\uD037\uD039\uD03A\uD03B\uD03D", 6, "\uD046\uD048\uD04A", 5],
      ["b461", "\uD051\uD052\uD053\uD055\uD056\uD057\uD059", 6, "\uD061", 10, "\uD06E\uD06F"],
      ["b481", "\uD071\uD072\uD073\uD075", 6, "\uD07E\uD07F\uD080\uD082", 18, "\uB1DF\uB1E8\uB1E9\uB1EC\uB1F0\uB1F9\uB1FB\uB1FD\uB204\uB205\uB208\uB20B\uB20C\uB214\uB215\uB217\uB219\uB220\uB234\uB23C\uB258\uB25C\uB260\uB268\uB269\uB274\uB275\uB27C\uB284\uB285\uB289\uB290\uB291\uB294\uB298\uB299\uB29A\uB2A0\uB2A1\uB2A3\uB2A5\uB2A6\uB2AA\uB2AC\uB2B0\uB2B4\uB2C8\uB2C9\uB2CC\uB2D0\uB2D2\uB2D8\uB2D9\uB2DB\uB2DD\uB2E2\uB2E4\uB2E5\uB2E6\uB2E8\uB2EB", 4, "\uB2F3\uB2F4\uB2F5\uB2F7", 4, "\uB2FF\uB300\uB301\uB304\uB308\uB310\uB311\uB313\uB314\uB315\uB31C\uB354\uB355\uB356\uB358\uB35B\uB35C\uB35E\uB35F\uB364\uB365"],
      ["b541", "\uD095", 14, "\uD0A6\uD0A7\uD0A9\uD0AA\uD0AB\uD0AD", 5],
      ["b561", "\uD0B3\uD0B6\uD0B8\uD0BA", 5, "\uD0C2\uD0C3\uD0C5\uD0C6\uD0C7\uD0CA", 5, "\uD0D2\uD0D6", 4],
      ["b581", "\uD0DB\uD0DE\uD0DF\uD0E1\uD0E2\uD0E3\uD0E5", 6, "\uD0EE\uD0F2", 5, "\uD0F9", 11, "\uB367\uB369\uB36B\uB36E\uB370\uB371\uB374\uB378\uB380\uB381\uB383\uB384\uB385\uB38C\uB390\uB394\uB3A0\uB3A1\uB3A8\uB3AC\uB3C4\uB3C5\uB3C8\uB3CB\uB3CC\uB3CE\uB3D0\uB3D4\uB3D5\uB3D7\uB3D9\uB3DB\uB3DD\uB3E0\uB3E4\uB3E8\uB3FC\uB410\uB418\uB41C\uB420\uB428\uB429\uB42B\uB434\uB450\uB451\uB454\uB458\uB460\uB461\uB463\uB465\uB46C\uB480\uB488\uB49D\uB4A4\uB4A8\uB4AC\uB4B5\uB4B7\uB4B9\uB4C0\uB4C4\uB4C8\uB4D0\uB4D5\uB4DC\uB4DD\uB4E0\uB4E3\uB4E4\uB4E6\uB4EC\uB4ED\uB4EF\uB4F1\uB4F8\uB514\uB515\uB518\uB51B\uB51C\uB524\uB525\uB527\uB528\uB529\uB52A\uB530\uB531\uB534\uB538"],
      ["b641", "\uD105", 7, "\uD10E", 17],
      ["b661", "\uD120", 15, "\uD132\uD133\uD135\uD136\uD137\uD139\uD13B\uD13C\uD13D\uD13E"],
      ["b681", "\uD13F\uD142\uD146", 5, "\uD14E\uD14F\uD151\uD152\uD153\uD155", 6, "\uD15E\uD160\uD162", 5, "\uD169\uD16A\uD16B\uD16D\uB540\uB541\uB543\uB544\uB545\uB54B\uB54C\uB54D\uB550\uB554\uB55C\uB55D\uB55F\uB560\uB561\uB5A0\uB5A1\uB5A4\uB5A8\uB5AA\uB5AB\uB5B0\uB5B1\uB5B3\uB5B4\uB5B5\uB5BB\uB5BC\uB5BD\uB5C0\uB5C4\uB5CC\uB5CD\uB5CF\uB5D0\uB5D1\uB5D8\uB5EC\uB610\uB611\uB614\uB618\uB625\uB62C\uB634\uB648\uB664\uB668\uB69C\uB69D\uB6A0\uB6A4\uB6AB\uB6AC\uB6B1\uB6D4\uB6F0\uB6F4\uB6F8\uB700\uB701\uB705\uB728\uB729\uB72C\uB72F\uB730\uB738\uB739\uB73B\uB744\uB748\uB74C\uB754\uB755\uB760\uB764\uB768\uB770\uB771\uB773\uB775\uB77C\uB77D\uB780\uB784\uB78C\uB78D\uB78F\uB790\uB791\uB792\uB796\uB797"],
      ["b741", "\uD16E", 13, "\uD17D", 6, "\uD185\uD186\uD187\uD189\uD18A"],
      ["b761", "\uD18B", 20, "\uD1A2\uD1A3\uD1A5\uD1A6\uD1A7"],
      ["b781", "\uD1A9", 6, "\uD1B2\uD1B4\uD1B6\uD1B7\uD1B8\uD1B9\uD1BB\uD1BD\uD1BE\uD1BF\uD1C1", 14, "\uB798\uB799\uB79C\uB7A0\uB7A8\uB7A9\uB7AB\uB7AC\uB7AD\uB7B4\uB7B5\uB7B8\uB7C7\uB7C9\uB7EC\uB7ED\uB7F0\uB7F4\uB7FC\uB7FD\uB7FF\uB800\uB801\uB807\uB808\uB809\uB80C\uB810\uB818\uB819\uB81B\uB81D\uB824\uB825\uB828\uB82C\uB834\uB835\uB837\uB838\uB839\uB840\uB844\uB851\uB853\uB85C\uB85D\uB860\uB864\uB86C\uB86D\uB86F\uB871\uB878\uB87C\uB88D\uB8A8\uB8B0\uB8B4\uB8B8\uB8C0\uB8C1\uB8C3\uB8C5\uB8CC\uB8D0\uB8D4\uB8DD\uB8DF\uB8E1\uB8E8\uB8E9\uB8EC\uB8F0\uB8F8\uB8F9\uB8FB\uB8FD\uB904\uB918\uB920\uB93C\uB93D\uB940\uB944\uB94C\uB94F\uB951\uB958\uB959\uB95C\uB960\uB968\uB969"],
      ["b841", "\uD1D0", 7, "\uD1D9", 17],
      ["b861", "\uD1EB", 8, "\uD1F5\uD1F6\uD1F7\uD1F9", 13],
      ["b881", "\uD208\uD20A", 5, "\uD211", 24, "\uB96B\uB96D\uB974\uB975\uB978\uB97C\uB984\uB985\uB987\uB989\uB98A\uB98D\uB98E\uB9AC\uB9AD\uB9B0\uB9B4\uB9BC\uB9BD\uB9BF\uB9C1\uB9C8\uB9C9\uB9CC\uB9CE", 4, "\uB9D8\uB9D9\uB9DB\uB9DD\uB9DE\uB9E1\uB9E3\uB9E4\uB9E5\uB9E8\uB9EC\uB9F4\uB9F5\uB9F7\uB9F8\uB9F9\uB9FA\uBA00\uBA01\uBA08\uBA15\uBA38\uBA39\uBA3C\uBA40\uBA42\uBA48\uBA49\uBA4B\uBA4D\uBA4E\uBA53\uBA54\uBA55\uBA58\uBA5C\uBA64\uBA65\uBA67\uBA68\uBA69\uBA70\uBA71\uBA74\uBA78\uBA83\uBA84\uBA85\uBA87\uBA8C\uBAA8\uBAA9\uBAAB\uBAAC\uBAB0\uBAB2\uBAB8\uBAB9\uBABB\uBABD\uBAC4\uBAC8\uBAD8\uBAD9\uBAFC"],
      ["b941", "\uD22A\uD22B\uD22E\uD22F\uD231\uD232\uD233\uD235", 6, "\uD23E\uD240\uD242", 5, "\uD249\uD24A\uD24B\uD24C"],
      ["b961", "\uD24D", 14, "\uD25D", 6, "\uD265\uD266\uD267\uD268"],
      ["b981", "\uD269", 22, "\uD282\uD283\uD285\uD286\uD287\uD289\uD28A\uD28B\uD28C\uBB00\uBB04\uBB0D\uBB0F\uBB11\uBB18\uBB1C\uBB20\uBB29\uBB2B\uBB34\uBB35\uBB36\uBB38\uBB3B\uBB3C\uBB3D\uBB3E\uBB44\uBB45\uBB47\uBB49\uBB4D\uBB4F\uBB50\uBB54\uBB58\uBB61\uBB63\uBB6C\uBB88\uBB8C\uBB90\uBBA4\uBBA8\uBBAC\uBBB4\uBBB7\uBBC0\uBBC4\uBBC8\uBBD0\uBBD3\uBBF8\uBBF9\uBBFC\uBBFF\uBC00\uBC02\uBC08\uBC09\uBC0B\uBC0C\uBC0D\uBC0F\uBC11\uBC14", 4, "\uBC1B", 4, "\uBC24\uBC25\uBC27\uBC29\uBC2D\uBC30\uBC31\uBC34\uBC38\uBC40\uBC41\uBC43\uBC44\uBC45\uBC49\uBC4C\uBC4D\uBC50\uBC5D\uBC84\uBC85\uBC88\uBC8B\uBC8C\uBC8E\uBC94\uBC95\uBC97"],
      ["ba41", "\uD28D\uD28E\uD28F\uD292\uD293\uD294\uD296", 5, "\uD29D\uD29E\uD29F\uD2A1\uD2A2\uD2A3\uD2A5", 6, "\uD2AD"],
      ["ba61", "\uD2AE\uD2AF\uD2B0\uD2B2", 5, "\uD2BA\uD2BB\uD2BD\uD2BE\uD2C1\uD2C3", 4, "\uD2CA\uD2CC", 5],
      ["ba81", "\uD2D2\uD2D3\uD2D5\uD2D6\uD2D7\uD2D9\uD2DA\uD2DB\uD2DD", 6, "\uD2E6", 9, "\uD2F2\uD2F3\uD2F5\uD2F6\uD2F7\uD2F9\uD2FA\uBC99\uBC9A\uBCA0\uBCA1\uBCA4\uBCA7\uBCA8\uBCB0\uBCB1\uBCB3\uBCB4\uBCB5\uBCBC\uBCBD\uBCC0\uBCC4\uBCCD\uBCCF\uBCD0\uBCD1\uBCD5\uBCD8\uBCDC\uBCF4\uBCF5\uBCF6\uBCF8\uBCFC\uBD04\uBD05\uBD07\uBD09\uBD10\uBD14\uBD24\uBD2C\uBD40\uBD48\uBD49\uBD4C\uBD50\uBD58\uBD59\uBD64\uBD68\uBD80\uBD81\uBD84\uBD87\uBD88\uBD89\uBD8A\uBD90\uBD91\uBD93\uBD95\uBD99\uBD9A\uBD9C\uBDA4\uBDB0\uBDB8\uBDD4\uBDD5\uBDD8\uBDDC\uBDE9\uBDF0\uBDF4\uBDF8\uBE00\uBE03\uBE05\uBE0C\uBE0D\uBE10\uBE14\uBE1C\uBE1D\uBE1F\uBE44\uBE45\uBE48\uBE4C\uBE4E\uBE54\uBE55\uBE57\uBE59\uBE5A\uBE5B\uBE60\uBE61\uBE64"],
      ["bb41", "\uD2FB", 4, "\uD302\uD304\uD306", 5, "\uD30F\uD311\uD312\uD313\uD315\uD317", 4, "\uD31E\uD322\uD323"],
      ["bb61", "\uD324\uD326\uD327\uD32A\uD32B\uD32D\uD32E\uD32F\uD331", 6, "\uD33A\uD33E", 5, "\uD346\uD347\uD348\uD349"],
      ["bb81", "\uD34A", 31, "\uBE68\uBE6A\uBE70\uBE71\uBE73\uBE74\uBE75\uBE7B\uBE7C\uBE7D\uBE80\uBE84\uBE8C\uBE8D\uBE8F\uBE90\uBE91\uBE98\uBE99\uBEA8\uBED0\uBED1\uBED4\uBED7\uBED8\uBEE0\uBEE3\uBEE4\uBEE5\uBEEC\uBF01\uBF08\uBF09\uBF18\uBF19\uBF1B\uBF1C\uBF1D\uBF40\uBF41\uBF44\uBF48\uBF50\uBF51\uBF55\uBF94\uBFB0\uBFC5\uBFCC\uBFCD\uBFD0\uBFD4\uBFDC\uBFDF\uBFE1\uC03C\uC051\uC058\uC05C\uC060\uC068\uC069\uC090\uC091\uC094\uC098\uC0A0\uC0A1\uC0A3\uC0A5\uC0AC\uC0AD\uC0AF\uC0B0\uC0B3\uC0B4\uC0B5\uC0B6\uC0BC\uC0BD\uC0BF\uC0C0\uC0C1\uC0C5\uC0C8\uC0C9\uC0CC\uC0D0\uC0D8\uC0D9\uC0DB\uC0DC\uC0DD\uC0E4"],
      ["bc41", "\uD36A", 17, "\uD37E\uD37F\uD381\uD382\uD383\uD385\uD386\uD387"],
      ["bc61", "\uD388\uD389\uD38A\uD38B\uD38E\uD392", 5, "\uD39A\uD39B\uD39D\uD39E\uD39F\uD3A1", 6, "\uD3AA\uD3AC\uD3AE"],
      ["bc81", "\uD3AF", 4, "\uD3B5\uD3B6\uD3B7\uD3B9\uD3BA\uD3BB\uD3BD", 6, "\uD3C6\uD3C7\uD3CA", 5, "\uD3D1", 5, "\uC0E5\uC0E8\uC0EC\uC0F4\uC0F5\uC0F7\uC0F9\uC100\uC104\uC108\uC110\uC115\uC11C", 4, "\uC123\uC124\uC126\uC127\uC12C\uC12D\uC12F\uC130\uC131\uC136\uC138\uC139\uC13C\uC140\uC148\uC149\uC14B\uC14C\uC14D\uC154\uC155\uC158\uC15C\uC164\uC165\uC167\uC168\uC169\uC170\uC174\uC178\uC185\uC18C\uC18D\uC18E\uC190\uC194\uC196\uC19C\uC19D\uC19F\uC1A1\uC1A5\uC1A8\uC1A9\uC1AC\uC1B0\uC1BD\uC1C4\uC1C8\uC1CC\uC1D4\uC1D7\uC1D8\uC1E0\uC1E4\uC1E8\uC1F0\uC1F1\uC1F3\uC1FC\uC1FD\uC200\uC204\uC20C\uC20D\uC20F\uC211\uC218\uC219\uC21C\uC21F\uC220\uC228\uC229\uC22B\uC22D"],
      ["bd41", "\uD3D7\uD3D9", 7, "\uD3E2\uD3E4", 7, "\uD3EE\uD3EF\uD3F1\uD3F2\uD3F3\uD3F5\uD3F6\uD3F7"],
      ["bd61", "\uD3F8\uD3F9\uD3FA\uD3FB\uD3FE\uD400\uD402", 5, "\uD409", 13],
      ["bd81", "\uD417", 5, "\uD41E", 25, "\uC22F\uC231\uC232\uC234\uC248\uC250\uC251\uC254\uC258\uC260\uC265\uC26C\uC26D\uC270\uC274\uC27C\uC27D\uC27F\uC281\uC288\uC289\uC290\uC298\uC29B\uC29D\uC2A4\uC2A5\uC2A8\uC2AC\uC2AD\uC2B4\uC2B5\uC2B7\uC2B9\uC2DC\uC2DD\uC2E0\uC2E3\uC2E4\uC2EB\uC2EC\uC2ED\uC2EF\uC2F1\uC2F6\uC2F8\uC2F9\uC2FB\uC2FC\uC300\uC308\uC309\uC30C\uC30D\uC313\uC314\uC315\uC318\uC31C\uC324\uC325\uC328\uC329\uC345\uC368\uC369\uC36C\uC370\uC372\uC378\uC379\uC37C\uC37D\uC384\uC388\uC38C\uC3C0\uC3D8\uC3D9\uC3DC\uC3DF\uC3E0\uC3E2\uC3E8\uC3E9\uC3ED\uC3F4\uC3F5\uC3F8\uC408\uC410\uC424\uC42C\uC430"],
      ["be41", "\uD438", 7, "\uD441\uD442\uD443\uD445", 14],
      ["be61", "\uD454", 7, "\uD45D\uD45E\uD45F\uD461\uD462\uD463\uD465", 7, "\uD46E\uD470\uD471\uD472"],
      ["be81", "\uD473", 4, "\uD47A\uD47B\uD47D\uD47E\uD481\uD483", 4, "\uD48A\uD48C\uD48E", 5, "\uD495", 8, "\uC434\uC43C\uC43D\uC448\uC464\uC465\uC468\uC46C\uC474\uC475\uC479\uC480\uC494\uC49C\uC4B8\uC4BC\uC4E9\uC4F0\uC4F1\uC4F4\uC4F8\uC4FA\uC4FF\uC500\uC501\uC50C\uC510\uC514\uC51C\uC528\uC529\uC52C\uC530\uC538\uC539\uC53B\uC53D\uC544\uC545\uC548\uC549\uC54A\uC54C\uC54D\uC54E\uC553\uC554\uC555\uC557\uC558\uC559\uC55D\uC55E\uC560\uC561\uC564\uC568\uC570\uC571\uC573\uC574\uC575\uC57C\uC57D\uC580\uC584\uC587\uC58C\uC58D\uC58F\uC591\uC595\uC597\uC598\uC59C\uC5A0\uC5A9\uC5B4\uC5B5\uC5B8\uC5B9\uC5BB\uC5BC\uC5BD\uC5BE\uC5C4", 6, "\uC5CC\uC5CE"],
      ["bf41", "\uD49E", 10, "\uD4AA", 14],
      ["bf61", "\uD4B9", 18, "\uD4CD\uD4CE\uD4CF\uD4D1\uD4D2\uD4D3\uD4D5"],
      ["bf81", "\uD4D6", 5, "\uD4DD\uD4DE\uD4E0", 7, "\uD4E9\uD4EA\uD4EB\uD4ED\uD4EE\uD4EF\uD4F1", 6, "\uD4F9\uD4FA\uD4FC\uC5D0\uC5D1\uC5D4\uC5D8\uC5E0\uC5E1\uC5E3\uC5E5\uC5EC\uC5ED\uC5EE\uC5F0\uC5F4\uC5F6\uC5F7\uC5FC", 5, "\uC605\uC606\uC607\uC608\uC60C\uC610\uC618\uC619\uC61B\uC61C\uC624\uC625\uC628\uC62C\uC62D\uC62E\uC630\uC633\uC634\uC635\uC637\uC639\uC63B\uC640\uC641\uC644\uC648\uC650\uC651\uC653\uC654\uC655\uC65C\uC65D\uC660\uC66C\uC66F\uC671\uC678\uC679\uC67C\uC680\uC688\uC689\uC68B\uC68D\uC694\uC695\uC698\uC69C\uC6A4\uC6A5\uC6A7\uC6A9\uC6B0\uC6B1\uC6B4\uC6B8\uC6B9\uC6BA\uC6C0\uC6C1\uC6C3\uC6C5\uC6CC\uC6CD\uC6D0\uC6D4\uC6DC\uC6DD\uC6E0\uC6E1\uC6E8"],
      ["c041", "\uD4FE", 5, "\uD505\uD506\uD507\uD509\uD50A\uD50B\uD50D", 6, "\uD516\uD518", 5],
      ["c061", "\uD51E", 25],
      ["c081", "\uD538\uD539\uD53A\uD53B\uD53E\uD53F\uD541\uD542\uD543\uD545", 6, "\uD54E\uD550\uD552", 5, "\uD55A\uD55B\uD55D\uD55E\uD55F\uD561\uD562\uD563\uC6E9\uC6EC\uC6F0\uC6F8\uC6F9\uC6FD\uC704\uC705\uC708\uC70C\uC714\uC715\uC717\uC719\uC720\uC721\uC724\uC728\uC730\uC731\uC733\uC735\uC737\uC73C\uC73D\uC740\uC744\uC74A\uC74C\uC74D\uC74F\uC751", 7, "\uC75C\uC760\uC768\uC76B\uC774\uC775\uC778\uC77C\uC77D\uC77E\uC783\uC784\uC785\uC787\uC788\uC789\uC78A\uC78E\uC790\uC791\uC794\uC796\uC797\uC798\uC79A\uC7A0\uC7A1\uC7A3\uC7A4\uC7A5\uC7A6\uC7AC\uC7AD\uC7B0\uC7B4\uC7BC\uC7BD\uC7BF\uC7C0\uC7C1\uC7C8\uC7C9\uC7CC\uC7CE\uC7D0\uC7D8\uC7DD\uC7E4\uC7E8\uC7EC\uC800\uC801\uC804\uC808\uC80A"],
      ["c141", "\uD564\uD566\uD567\uD56A\uD56C\uD56E", 5, "\uD576\uD577\uD579\uD57A\uD57B\uD57D", 6, "\uD586\uD58A\uD58B"],
      ["c161", "\uD58C\uD58D\uD58E\uD58F\uD591", 19, "\uD5A6\uD5A7"],
      ["c181", "\uD5A8", 31, "\uC810\uC811\uC813\uC815\uC816\uC81C\uC81D\uC820\uC824\uC82C\uC82D\uC82F\uC831\uC838\uC83C\uC840\uC848\uC849\uC84C\uC84D\uC854\uC870\uC871\uC874\uC878\uC87A\uC880\uC881\uC883\uC885\uC886\uC887\uC88B\uC88C\uC88D\uC894\uC89D\uC89F\uC8A1\uC8A8\uC8BC\uC8BD\uC8C4\uC8C8\uC8CC\uC8D4\uC8D5\uC8D7\uC8D9\uC8E0\uC8E1\uC8E4\uC8F5\uC8FC\uC8FD\uC900\uC904\uC905\uC906\uC90C\uC90D\uC90F\uC911\uC918\uC92C\uC934\uC950\uC951\uC954\uC958\uC960\uC961\uC963\uC96C\uC970\uC974\uC97C\uC988\uC989\uC98C\uC990\uC998\uC999\uC99B\uC99D\uC9C0\uC9C1\uC9C4\uC9C7\uC9C8\uC9CA\uC9D0\uC9D1\uC9D3"],
      ["c241", "\uD5CA\uD5CB\uD5CD\uD5CE\uD5CF\uD5D1\uD5D3", 4, "\uD5DA\uD5DC\uD5DE", 5, "\uD5E6\uD5E7\uD5E9\uD5EA\uD5EB\uD5ED\uD5EE"],
      ["c261", "\uD5EF", 4, "\uD5F6\uD5F8\uD5FA", 5, "\uD602\uD603\uD605\uD606\uD607\uD609", 6, "\uD612"],
      ["c281", "\uD616", 5, "\uD61D\uD61E\uD61F\uD621\uD622\uD623\uD625", 7, "\uD62E", 9, "\uD63A\uD63B\uC9D5\uC9D6\uC9D9\uC9DA\uC9DC\uC9DD\uC9E0\uC9E2\uC9E4\uC9E7\uC9EC\uC9ED\uC9EF\uC9F0\uC9F1\uC9F8\uC9F9\uC9FC\uCA00\uCA08\uCA09\uCA0B\uCA0C\uCA0D\uCA14\uCA18\uCA29\uCA4C\uCA4D\uCA50\uCA54\uCA5C\uCA5D\uCA5F\uCA60\uCA61\uCA68\uCA7D\uCA84\uCA98\uCABC\uCABD\uCAC0\uCAC4\uCACC\uCACD\uCACF\uCAD1\uCAD3\uCAD8\uCAD9\uCAE0\uCAEC\uCAF4\uCB08\uCB10\uCB14\uCB18\uCB20\uCB21\uCB41\uCB48\uCB49\uCB4C\uCB50\uCB58\uCB59\uCB5D\uCB64\uCB78\uCB79\uCB9C\uCBB8\uCBD4\uCBE4\uCBE7\uCBE9\uCC0C\uCC0D\uCC10\uCC14\uCC1C\uCC1D\uCC21\uCC22\uCC27\uCC28\uCC29\uCC2C\uCC2E\uCC30\uCC38\uCC39\uCC3B"],
      ["c341", "\uD63D\uD63E\uD63F\uD641\uD642\uD643\uD644\uD646\uD647\uD64A\uD64C\uD64E\uD64F\uD650\uD652\uD653\uD656\uD657\uD659\uD65A\uD65B\uD65D", 4],
      ["c361", "\uD662", 4, "\uD668\uD66A", 5, "\uD672\uD673\uD675", 11],
      ["c381", "\uD681\uD682\uD684\uD686", 5, "\uD68E\uD68F\uD691\uD692\uD693\uD695", 7, "\uD69E\uD6A0\uD6A2", 5, "\uD6A9\uD6AA\uCC3C\uCC3D\uCC3E\uCC44\uCC45\uCC48\uCC4C\uCC54\uCC55\uCC57\uCC58\uCC59\uCC60\uCC64\uCC66\uCC68\uCC70\uCC75\uCC98\uCC99\uCC9C\uCCA0\uCCA8\uCCA9\uCCAB\uCCAC\uCCAD\uCCB4\uCCB5\uCCB8\uCCBC\uCCC4\uCCC5\uCCC7\uCCC9\uCCD0\uCCD4\uCCE4\uCCEC\uCCF0\uCD01\uCD08\uCD09\uCD0C\uCD10\uCD18\uCD19\uCD1B\uCD1D\uCD24\uCD28\uCD2C\uCD39\uCD5C\uCD60\uCD64\uCD6C\uCD6D\uCD6F\uCD71\uCD78\uCD88\uCD94\uCD95\uCD98\uCD9C\uCDA4\uCDA5\uCDA7\uCDA9\uCDB0\uCDC4\uCDCC\uCDD0\uCDE8\uCDEC\uCDF0\uCDF8\uCDF9\uCDFB\uCDFD\uCE04\uCE08\uCE0C\uCE14\uCE19\uCE20\uCE21\uCE24\uCE28\uCE30\uCE31\uCE33\uCE35"],
      ["c441", "\uD6AB\uD6AD\uD6AE\uD6AF\uD6B1", 7, "\uD6BA\uD6BC", 7, "\uD6C6\uD6C7\uD6C9\uD6CA\uD6CB"],
      ["c461", "\uD6CD\uD6CE\uD6CF\uD6D0\uD6D2\uD6D3\uD6D5\uD6D6\uD6D8\uD6DA", 5, "\uD6E1\uD6E2\uD6E3\uD6E5\uD6E6\uD6E7\uD6E9", 4],
      ["c481", "\uD6EE\uD6EF\uD6F1\uD6F2\uD6F3\uD6F4\uD6F6", 5, "\uD6FE\uD6FF\uD701\uD702\uD703\uD705", 11, "\uD712\uD713\uD714\uCE58\uCE59\uCE5C\uCE5F\uCE60\uCE61\uCE68\uCE69\uCE6B\uCE6D\uCE74\uCE75\uCE78\uCE7C\uCE84\uCE85\uCE87\uCE89\uCE90\uCE91\uCE94\uCE98\uCEA0\uCEA1\uCEA3\uCEA4\uCEA5\uCEAC\uCEAD\uCEC1\uCEE4\uCEE5\uCEE8\uCEEB\uCEEC\uCEF4\uCEF5\uCEF7\uCEF8\uCEF9\uCF00\uCF01\uCF04\uCF08\uCF10\uCF11\uCF13\uCF15\uCF1C\uCF20\uCF24\uCF2C\uCF2D\uCF2F\uCF30\uCF31\uCF38\uCF54\uCF55\uCF58\uCF5C\uCF64\uCF65\uCF67\uCF69\uCF70\uCF71\uCF74\uCF78\uCF80\uCF85\uCF8C\uCFA1\uCFA8\uCFB0\uCFC4\uCFE0\uCFE1\uCFE4\uCFE8\uCFF0\uCFF1\uCFF3\uCFF5\uCFFC\uD000\uD004\uD011\uD018\uD02D\uD034\uD035\uD038\uD03C"],
      ["c541", "\uD715\uD716\uD717\uD71A\uD71B\uD71D\uD71E\uD71F\uD721", 6, "\uD72A\uD72C\uD72E", 5, "\uD736\uD737\uD739"],
      ["c561", "\uD73A\uD73B\uD73D", 6, "\uD745\uD746\uD748\uD74A", 5, "\uD752\uD753\uD755\uD75A", 4],
      ["c581", "\uD75F\uD762\uD764\uD766\uD767\uD768\uD76A\uD76B\uD76D\uD76E\uD76F\uD771\uD772\uD773\uD775", 6, "\uD77E\uD77F\uD780\uD782", 5, "\uD78A\uD78B\uD044\uD045\uD047\uD049\uD050\uD054\uD058\uD060\uD06C\uD06D\uD070\uD074\uD07C\uD07D\uD081\uD0A4\uD0A5\uD0A8\uD0AC\uD0B4\uD0B5\uD0B7\uD0B9\uD0C0\uD0C1\uD0C4\uD0C8\uD0C9\uD0D0\uD0D1\uD0D3\uD0D4\uD0D5\uD0DC\uD0DD\uD0E0\uD0E4\uD0EC\uD0ED\uD0EF\uD0F0\uD0F1\uD0F8\uD10D\uD130\uD131\uD134\uD138\uD13A\uD140\uD141\uD143\uD144\uD145\uD14C\uD14D\uD150\uD154\uD15C\uD15D\uD15F\uD161\uD168\uD16C\uD17C\uD184\uD188\uD1A0\uD1A1\uD1A4\uD1A8\uD1B0\uD1B1\uD1B3\uD1B5\uD1BA\uD1BC\uD1C0\uD1D8\uD1F4\uD1F8\uD207\uD209\uD210\uD22C\uD22D\uD230\uD234\uD23C\uD23D\uD23F\uD241\uD248\uD25C"],
      ["c641", "\uD78D\uD78E\uD78F\uD791", 6, "\uD79A\uD79C\uD79E", 5],
      ["c6a1", "\uD264\uD280\uD281\uD284\uD288\uD290\uD291\uD295\uD29C\uD2A0\uD2A4\uD2AC\uD2B1\uD2B8\uD2B9\uD2BC\uD2BF\uD2C0\uD2C2\uD2C8\uD2C9\uD2CB\uD2D4\uD2D8\uD2DC\uD2E4\uD2E5\uD2F0\uD2F1\uD2F4\uD2F8\uD300\uD301\uD303\uD305\uD30C\uD30D\uD30E\uD310\uD314\uD316\uD31C\uD31D\uD31F\uD320\uD321\uD325\uD328\uD329\uD32C\uD330\uD338\uD339\uD33B\uD33C\uD33D\uD344\uD345\uD37C\uD37D\uD380\uD384\uD38C\uD38D\uD38F\uD390\uD391\uD398\uD399\uD39C\uD3A0\uD3A8\uD3A9\uD3AB\uD3AD\uD3B4\uD3B8\uD3BC\uD3C4\uD3C5\uD3C8\uD3C9\uD3D0\uD3D8\uD3E1\uD3E3\uD3EC\uD3ED\uD3F0\uD3F4\uD3FC\uD3FD\uD3FF\uD401"],
      ["c7a1", "\uD408\uD41D\uD440\uD444\uD45C\uD460\uD464\uD46D\uD46F\uD478\uD479\uD47C\uD47F\uD480\uD482\uD488\uD489\uD48B\uD48D\uD494\uD4A9\uD4CC\uD4D0\uD4D4\uD4DC\uD4DF\uD4E8\uD4EC\uD4F0\uD4F8\uD4FB\uD4FD\uD504\uD508\uD50C\uD514\uD515\uD517\uD53C\uD53D\uD540\uD544\uD54C\uD54D\uD54F\uD551\uD558\uD559\uD55C\uD560\uD565\uD568\uD569\uD56B\uD56D\uD574\uD575\uD578\uD57C\uD584\uD585\uD587\uD588\uD589\uD590\uD5A5\uD5C8\uD5C9\uD5CC\uD5D0\uD5D2\uD5D8\uD5D9\uD5DB\uD5DD\uD5E4\uD5E5\uD5E8\uD5EC\uD5F4\uD5F5\uD5F7\uD5F9\uD600\uD601\uD604\uD608\uD610\uD611\uD613\uD614\uD615\uD61C\uD620"],
      ["c8a1", "\uD624\uD62D\uD638\uD639\uD63C\uD640\uD645\uD648\uD649\uD64B\uD64D\uD651\uD654\uD655\uD658\uD65C\uD667\uD669\uD670\uD671\uD674\uD683\uD685\uD68C\uD68D\uD690\uD694\uD69D\uD69F\uD6A1\uD6A8\uD6AC\uD6B0\uD6B9\uD6BB\uD6C4\uD6C5\uD6C8\uD6CC\uD6D1\uD6D4\uD6D7\uD6D9\uD6E0\uD6E4\uD6E8\uD6F0\uD6F5\uD6FC\uD6FD\uD700\uD704\uD711\uD718\uD719\uD71C\uD720\uD728\uD729\uD72B\uD72D\uD734\uD735\uD738\uD73C\uD744\uD747\uD749\uD750\uD751\uD754\uD756\uD757\uD758\uD759\uD760\uD761\uD763\uD765\uD769\uD76C\uD770\uD774\uD77C\uD77D\uD781\uD788\uD789\uD78C\uD790\uD798\uD799\uD79B\uD79D"],
      ["caa1", "\u4F3D\u4F73\u5047\u50F9\u52A0\u53EF\u5475\u54E5\u5609\u5AC1\u5BB6\u6687\u67B6\u67B7\u67EF\u6B4C\u73C2\u75C2\u7A3C\u82DB\u8304\u8857\u8888\u8A36\u8CC8\u8DCF\u8EFB\u8FE6\u99D5\u523B\u5374\u5404\u606A\u6164\u6BBC\u73CF\u811A\u89BA\u89D2\u95A3\u4F83\u520A\u58BE\u5978\u59E6\u5E72\u5E79\u61C7\u63C0\u6746\u67EC\u687F\u6F97\u764E\u770B\u78F5\u7A08\u7AFF\u7C21\u809D\u826E\u8271\u8AEB\u9593\u4E6B\u559D\u66F7\u6E34\u78A3\u7AED\u845B\u8910\u874E\u97A8\u52D8\u574E\u582A\u5D4C\u611F\u61BE\u6221\u6562\u67D1\u6A44\u6E1B\u7518\u75B3\u76E3\u77B0\u7D3A\u90AF\u9451\u9452\u9F95"],
      ["cba1", "\u5323\u5CAC\u7532\u80DB\u9240\u9598\u525B\u5808\u59DC\u5CA1\u5D17\u5EB7\u5F3A\u5F4A\u6177\u6C5F\u757A\u7586\u7CE0\u7D73\u7DB1\u7F8C\u8154\u8221\u8591\u8941\u8B1B\u92FC\u964D\u9C47\u4ECB\u4EF7\u500B\u51F1\u584F\u6137\u613E\u6168\u6539\u69EA\u6F11\u75A5\u7686\u76D6\u7B87\u82A5\u84CB\uF900\u93A7\u958B\u5580\u5BA2\u5751\uF901\u7CB3\u7FB9\u91B5\u5028\u53BB\u5C45\u5DE8\u62D2\u636E\u64DA\u64E7\u6E20\u70AC\u795B\u8DDD\u8E1E\uF902\u907D\u9245\u92F8\u4E7E\u4EF6\u5065\u5DFE\u5EFA\u6106\u6957\u8171\u8654\u8E47\u9375\u9A2B\u4E5E\u5091\u6770\u6840\u5109\u528D\u5292\u6AA2"],
      ["cca1", "\u77BC\u9210\u9ED4\u52AB\u602F\u8FF2\u5048\u61A9\u63ED\u64CA\u683C\u6A84\u6FC0\u8188\u89A1\u9694\u5805\u727D\u72AC\u7504\u7D79\u7E6D\u80A9\u898B\u8B74\u9063\u9D51\u6289\u6C7A\u6F54\u7D50\u7F3A\u8A23\u517C\u614A\u7B9D\u8B19\u9257\u938C\u4EAC\u4FD3\u501E\u50BE\u5106\u52C1\u52CD\u537F\u5770\u5883\u5E9A\u5F91\u6176\u61AC\u64CE\u656C\u666F\u66BB\u66F4\u6897\u6D87\u7085\u70F1\u749F\u74A5\u74CA\u75D9\u786C\u78EC\u7ADF\u7AF6\u7D45\u7D93\u8015\u803F\u811B\u8396\u8B66\u8F15\u9015\u93E1\u9803\u9838\u9A5A\u9BE8\u4FC2\u5553\u583A\u5951\u5B63\u5C46\u60B8\u6212\u6842\u68B0"],
      ["cda1", "\u68E8\u6EAA\u754C\u7678\u78CE\u7A3D\u7CFB\u7E6B\u7E7C\u8A08\u8AA1\u8C3F\u968E\u9DC4\u53E4\u53E9\u544A\u5471\u56FA\u59D1\u5B64\u5C3B\u5EAB\u62F7\u6537\u6545\u6572\u66A0\u67AF\u69C1\u6CBD\u75FC\u7690\u777E\u7A3F\u7F94\u8003\u80A1\u818F\u82E6\u82FD\u83F0\u85C1\u8831\u88B4\u8AA5\uF903\u8F9C\u932E\u96C7\u9867\u9AD8\u9F13\u54ED\u659B\u66F2\u688F\u7A40\u8C37\u9D60\u56F0\u5764\u5D11\u6606\u68B1\u68CD\u6EFE\u7428\u889E\u9BE4\u6C68\uF904\u9AA8\u4F9B\u516C\u5171\u529F\u5B54\u5DE5\u6050\u606D\u62F1\u63A7\u653B\u73D9\u7A7A\u86A3\u8CA2\u978F\u4E32\u5BE1\u6208\u679C\u74DC"],
      ["cea1", "\u79D1\u83D3\u8A87\u8AB2\u8DE8\u904E\u934B\u9846\u5ED3\u69E8\u85FF\u90ED\uF905\u51A0\u5B98\u5BEC\u6163\u68FA\u6B3E\u704C\u742F\u74D8\u7BA1\u7F50\u83C5\u89C0\u8CAB\u95DC\u9928\u522E\u605D\u62EC\u9002\u4F8A\u5149\u5321\u58D9\u5EE3\u66E0\u6D38\u709A\u72C2\u73D6\u7B50\u80F1\u945B\u5366\u639B\u7F6B\u4E56\u5080\u584A\u58DE\u602A\u6127\u62D0\u69D0\u9B41\u5B8F\u7D18\u80B1\u8F5F\u4EA4\u50D1\u54AC\u55AC\u5B0C\u5DA0\u5DE7\u652A\u654E\u6821\u6A4B\u72E1\u768E\u77EF\u7D5E\u7FF9\u81A0\u854E\u86DF\u8F03\u8F4E\u90CA\u9903\u9A55\u9BAB\u4E18\u4E45\u4E5D\u4EC7\u4FF1\u5177\u52FE"],
      ["cfa1", "\u5340\u53E3\u53E5\u548E\u5614\u5775\u57A2\u5BC7\u5D87\u5ED0\u61FC\u62D8\u6551\u67B8\u67E9\u69CB\u6B50\u6BC6\u6BEC\u6C42\u6E9D\u7078\u72D7\u7396\u7403\u77BF\u77E9\u7A76\u7D7F\u8009\u81FC\u8205\u820A\u82DF\u8862\u8B33\u8CFC\u8EC0\u9011\u90B1\u9264\u92B6\u99D2\u9A45\u9CE9\u9DD7\u9F9C\u570B\u5C40\u83CA\u97A0\u97AB\u9EB4\u541B\u7A98\u7FA4\u88D9\u8ECD\u90E1\u5800\u5C48\u6398\u7A9F\u5BAE\u5F13\u7A79\u7AAE\u828E\u8EAC\u5026\u5238\u52F8\u5377\u5708\u62F3\u6372\u6B0A\u6DC3\u7737\u53A5\u7357\u8568\u8E76\u95D5\u673A\u6AC3\u6F70\u8A6D\u8ECC\u994B\uF906\u6677\u6B78\u8CB4"],
      ["d0a1", "\u9B3C\uF907\u53EB\u572D\u594E\u63C6\u69FB\u73EA\u7845\u7ABA\u7AC5\u7CFE\u8475\u898F\u8D73\u9035\u95A8\u52FB\u5747\u7547\u7B60\u83CC\u921E\uF908\u6A58\u514B\u524B\u5287\u621F\u68D8\u6975\u9699\u50C5\u52A4\u52E4\u61C3\u65A4\u6839\u69FF\u747E\u7B4B\u82B9\u83EB\u89B2\u8B39\u8FD1\u9949\uF909\u4ECA\u5997\u64D2\u6611\u6A8E\u7434\u7981\u79BD\u82A9\u887E\u887F\u895F\uF90A\u9326\u4F0B\u53CA\u6025\u6271\u6C72\u7D1A\u7D66\u4E98\u5162\u77DC\u80AF\u4F01\u4F0E\u5176\u5180\u55DC\u5668\u573B\u57FA\u57FC\u5914\u5947\u5993\u5BC4\u5C90\u5D0E\u5DF1\u5E7E\u5FCC\u6280\u65D7\u65E3"],
      ["d1a1", "\u671E\u671F\u675E\u68CB\u68C4\u6A5F\u6B3A\u6C23\u6C7D\u6C82\u6DC7\u7398\u7426\u742A\u7482\u74A3\u7578\u757F\u7881\u78EF\u7941\u7947\u7948\u797A\u7B95\u7D00\u7DBA\u7F88\u8006\u802D\u808C\u8A18\u8B4F\u8C48\u8D77\u9321\u9324\u98E2\u9951\u9A0E\u9A0F\u9A65\u9E92\u7DCA\u4F76\u5409\u62EE\u6854\u91D1\u55AB\u513A\uF90B\uF90C\u5A1C\u61E6\uF90D\u62CF\u62FF\uF90E", 5, "\u90A3\uF914", 4, "\u8AFE\uF919\uF91A\uF91B\uF91C\u6696\uF91D\u7156\uF91E\uF91F\u96E3\uF920\u634F\u637A\u5357\uF921\u678F\u6960\u6E73\uF922\u7537\uF923\uF924\uF925"],
      ["d2a1", "\u7D0D\uF926\uF927\u8872\u56CA\u5A18\uF928", 4, "\u4E43\uF92D\u5167\u5948\u67F0\u8010\uF92E\u5973\u5E74\u649A\u79CA\u5FF5\u606C\u62C8\u637B\u5BE7\u5BD7\u52AA\uF92F\u5974\u5F29\u6012\uF930\uF931\uF932\u7459\uF933", 5, "\u99D1\uF939", 10, "\u6FC3\uF944\uF945\u81BF\u8FB2\u60F1\uF946\uF947\u8166\uF948\uF949\u5C3F\uF94A", 7, "\u5AE9\u8A25\u677B\u7D10\uF952", 5, "\u80FD\uF958\uF959\u5C3C\u6CE5\u533F\u6EBA\u591A\u8336"],
      ["d3a1", "\u4E39\u4EB6\u4F46\u55AE\u5718\u58C7\u5F56\u65B7\u65E6\u6A80\u6BB5\u6E4D\u77ED\u7AEF\u7C1E\u7DDE\u86CB\u8892\u9132\u935B\u64BB\u6FBE\u737A\u75B8\u9054\u5556\u574D\u61BA\u64D4\u66C7\u6DE1\u6E5B\u6F6D\u6FB9\u75F0\u8043\u81BD\u8541\u8983\u8AC7\u8B5A\u931F\u6C93\u7553\u7B54\u8E0F\u905D\u5510\u5802\u5858\u5E62\u6207\u649E\u68E0\u7576\u7CD6\u87B3\u9EE8\u4EE3\u5788\u576E\u5927\u5C0D\u5CB1\u5E36\u5F85\u6234\u64E1\u73B3\u81FA\u888B\u8CB8\u968A\u9EDB\u5B85\u5FB7\u60B3\u5012\u5200\u5230\u5716\u5835\u5857\u5C0E\u5C60\u5CF6\u5D8B\u5EA6\u5F92\u60BC\u6311\u6389\u6417\u6843"],
      ["d4a1", "\u68F9\u6AC2\u6DD8\u6E21\u6ED4\u6FE4\u71FE\u76DC\u7779\u79B1\u7A3B\u8404\u89A9\u8CED\u8DF3\u8E48\u9003\u9014\u9053\u90FD\u934D\u9676\u97DC\u6BD2\u7006\u7258\u72A2\u7368\u7763\u79BF\u7BE4\u7E9B\u8B80\u58A9\u60C7\u6566\u65FD\u66BE\u6C8C\u711E\u71C9\u8C5A\u9813\u4E6D\u7A81\u4EDD\u51AC\u51CD\u52D5\u540C\u61A7\u6771\u6850\u68DF\u6D1E\u6F7C\u75BC\u77B3\u7AE5\u80F4\u8463\u9285\u515C\u6597\u675C\u6793\u75D8\u7AC7\u8373\uF95A\u8C46\u9017\u982D\u5C6F\u81C0\u829A\u9041\u906F\u920D\u5F97\u5D9D\u6A59\u71C8\u767B\u7B49\u85E4\u8B04\u9127\u9A30\u5587\u61F6\uF95B\u7669\u7F85"],
      ["d5a1", "\u863F\u87BA\u88F8\u908F\uF95C\u6D1B\u70D9\u73DE\u7D61\u843D\uF95D\u916A\u99F1\uF95E\u4E82\u5375\u6B04\u6B12\u703E\u721B\u862D\u9E1E\u524C\u8FA3\u5D50\u64E5\u652C\u6B16\u6FEB\u7C43\u7E9C\u85CD\u8964\u89BD\u62C9\u81D8\u881F\u5ECA\u6717\u6D6A\u72FC\u7405\u746F\u8782\u90DE\u4F86\u5D0D\u5FA0\u840A\u51B7\u63A0\u7565\u4EAE\u5006\u5169\u51C9\u6881\u6A11\u7CAE\u7CB1\u7CE7\u826F\u8AD2\u8F1B\u91CF\u4FB6\u5137\u52F5\u5442\u5EEC\u616E\u623E\u65C5\u6ADA\u6FFE\u792A\u85DC\u8823\u95AD\u9A62\u9A6A\u9E97\u9ECE\u529B\u66C6\u6B77\u701D\u792B\u8F62\u9742\u6190\u6200\u6523\u6F23"],
      ["d6a1", "\u7149\u7489\u7DF4\u806F\u84EE\u8F26\u9023\u934A\u51BD\u5217\u52A3\u6D0C\u70C8\u88C2\u5EC9\u6582\u6BAE\u6FC2\u7C3E\u7375\u4EE4\u4F36\u56F9\uF95F\u5CBA\u5DBA\u601C\u73B2\u7B2D\u7F9A\u7FCE\u8046\u901E\u9234\u96F6\u9748\u9818\u9F61\u4F8B\u6FA7\u79AE\u91B4\u96B7\u52DE\uF960\u6488\u64C4\u6AD3\u6F5E\u7018\u7210\u76E7\u8001\u8606\u865C\u8DEF\u8F05\u9732\u9B6F\u9DFA\u9E75\u788C\u797F\u7DA0\u83C9\u9304\u9E7F\u9E93\u8AD6\u58DF\u5F04\u6727\u7027\u74CF\u7C60\u807E\u5121\u7028\u7262\u78CA\u8CC2\u8CDA\u8CF4\u96F7\u4E86\u50DA\u5BEE\u5ED6\u6599\u71CE\u7642\u77AD\u804A\u84FC"],
      ["d7a1", "\u907C\u9B27\u9F8D\u58D8\u5A41\u5C62\u6A13\u6DDA\u6F0F\u763B\u7D2F\u7E37\u851E\u8938\u93E4\u964B\u5289\u65D2\u67F3\u69B4\u6D41\u6E9C\u700F\u7409\u7460\u7559\u7624\u786B\u8B2C\u985E\u516D\u622E\u9678\u4F96\u502B\u5D19\u6DEA\u7DB8\u8F2A\u5F8B\u6144\u6817\uF961\u9686\u52D2\u808B\u51DC\u51CC\u695E\u7A1C\u7DBE\u83F1\u9675\u4FDA\u5229\u5398\u540F\u550E\u5C65\u60A7\u674E\u68A8\u6D6C\u7281\u72F8\u7406\u7483\uF962\u75E2\u7C6C\u7F79\u7FB8\u8389\u88CF\u88E1\u91CC\u91D0\u96E2\u9BC9\u541D\u6F7E\u71D0\u7498\u85FA\u8EAA\u96A3\u9C57\u9E9F\u6797\u6DCB\u7433\u81E8\u9716\u782C"],
      ["d8a1", "\u7ACB\u7B20\u7C92\u6469\u746A\u75F2\u78BC\u78E8\u99AC\u9B54\u9EBB\u5BDE\u5E55\u6F20\u819C\u83AB\u9088\u4E07\u534D\u5A29\u5DD2\u5F4E\u6162\u633D\u6669\u66FC\u6EFF\u6F2B\u7063\u779E\u842C\u8513\u883B\u8F13\u9945\u9C3B\u551C\u62B9\u672B\u6CAB\u8309\u896A\u977A\u4EA1\u5984\u5FD8\u5FD9\u671B\u7DB2\u7F54\u8292\u832B\u83BD\u8F1E\u9099\u57CB\u59B9\u5A92\u5BD0\u6627\u679A\u6885\u6BCF\u7164\u7F75\u8CB7\u8CE3\u9081\u9B45\u8108\u8C8A\u964C\u9A40\u9EA5\u5B5F\u6C13\u731B\u76F2\u76DF\u840C\u51AA\u8993\u514D\u5195\u52C9\u68C9\u6C94\u7704\u7720\u7DBF\u7DEC\u9762\u9EB5\u6EC5"],
      ["d9a1", "\u8511\u51A5\u540D\u547D\u660E\u669D\u6927\u6E9F\u76BF\u7791\u8317\u84C2\u879F\u9169\u9298\u9CF4\u8882\u4FAE\u5192\u52DF\u59C6\u5E3D\u6155\u6478\u6479\u66AE\u67D0\u6A21\u6BCD\u6BDB\u725F\u7261\u7441\u7738\u77DB\u8017\u82BC\u8305\u8B00\u8B28\u8C8C\u6728\u6C90\u7267\u76EE\u7766\u7A46\u9DA9\u6B7F\u6C92\u5922\u6726\u8499\u536F\u5893\u5999\u5EDF\u63CF\u6634\u6773\u6E3A\u732B\u7AD7\u82D7\u9328\u52D9\u5DEB\u61AE\u61CB\u620A\u62C7\u64AB\u65E0\u6959\u6B66\u6BCB\u7121\u73F7\u755D\u7E46\u821E\u8302\u856A\u8AA3\u8CBF\u9727\u9D61\u58A8\u9ED8\u5011\u520E\u543B\u554F\u6587"],
      ["daa1", "\u6C76\u7D0A\u7D0B\u805E\u868A\u9580\u96EF\u52FF\u6C95\u7269\u5473\u5A9A\u5C3E\u5D4B\u5F4C\u5FAE\u672A\u68B6\u6963\u6E3C\u6E44\u7709\u7C73\u7F8E\u8587\u8B0E\u8FF7\u9761\u9EF4\u5CB7\u60B6\u610D\u61AB\u654F\u65FB\u65FC\u6C11\u6CEF\u739F\u73C9\u7DE1\u9594\u5BC6\u871C\u8B10\u525D\u535A\u62CD\u640F\u64B2\u6734\u6A38\u6CCA\u73C0\u749E\u7B94\u7C95\u7E1B\u818A\u8236\u8584\u8FEB\u96F9\u99C1\u4F34\u534A\u53CD\u53DB\u62CC\u642C\u6500\u6591\u69C3\u6CEE\u6F58\u73ED\u7554\u7622\u76E4\u76FC\u78D0\u78FB\u792C\u7D46\u822C\u87E0\u8FD4\u9812\u98EF\u52C3\u62D4\u64A5\u6E24\u6F51"],
      ["dba1", "\u767C\u8DCB\u91B1\u9262\u9AEE\u9B43\u5023\u508D\u574A\u59A8\u5C28\u5E47\u5F77\u623F\u653E\u65B9\u65C1\u6609\u678B\u699C\u6EC2\u78C5\u7D21\u80AA\u8180\u822B\u82B3\u84A1\u868C\u8A2A\u8B17\u90A6\u9632\u9F90\u500D\u4FF3\uF963\u57F9\u5F98\u62DC\u6392\u676F\u6E43\u7119\u76C3\u80CC\u80DA\u88F4\u88F5\u8919\u8CE0\u8F29\u914D\u966A\u4F2F\u4F70\u5E1B\u67CF\u6822\u767D\u767E\u9B44\u5E61\u6A0A\u7169\u71D4\u756A\uF964\u7E41\u8543\u85E9\u98DC\u4F10\u7B4F\u7F70\u95A5\u51E1\u5E06\u68B5\u6C3E\u6C4E\u6CDB\u72AF\u7BC4\u8303\u6CD5\u743A\u50FB\u5288\u58C1\u64D8\u6A97\u74A7\u7656"],
      ["dca1", "\u78A7\u8617\u95E2\u9739\uF965\u535E\u5F01\u8B8A\u8FA8\u8FAF\u908A\u5225\u77A5\u9C49\u9F08\u4E19\u5002\u5175\u5C5B\u5E77\u661E\u663A\u67C4\u68C5\u70B3\u7501\u75C5\u79C9\u7ADD\u8F27\u9920\u9A08\u4FDD\u5821\u5831\u5BF6\u666E\u6B65\u6D11\u6E7A\u6F7D\u73E4\u752B\u83E9\u88DC\u8913\u8B5C\u8F14\u4F0F\u50D5\u5310\u535C\u5B93\u5FA9\u670D\u798F\u8179\u832F\u8514\u8907\u8986\u8F39\u8F3B\u99A5\u9C12\u672C\u4E76\u4FF8\u5949\u5C01\u5CEF\u5CF0\u6367\u68D2\u70FD\u71A2\u742B\u7E2B\u84EC\u8702\u9022\u92D2\u9CF3\u4E0D\u4ED8\u4FEF\u5085\u5256\u526F\u5426\u5490\u57E0\u592B\u5A66"],
      ["dda1", "\u5B5A\u5B75\u5BCC\u5E9C\uF966\u6276\u6577\u65A7\u6D6E\u6EA5\u7236\u7B26\u7C3F\u7F36\u8150\u8151\u819A\u8240\u8299\u83A9\u8A03\u8CA0\u8CE6\u8CFB\u8D74\u8DBA\u90E8\u91DC\u961C\u9644\u99D9\u9CE7\u5317\u5206\u5429\u5674\u58B3\u5954\u596E\u5FFF\u61A4\u626E\u6610\u6C7E\u711A\u76C6\u7C89\u7CDE\u7D1B\u82AC\u8CC1\u96F0\uF967\u4F5B\u5F17\u5F7F\u62C2\u5D29\u670B\u68DA\u787C\u7E43\u9D6C\u4E15\u5099\u5315\u532A\u5351\u5983\u5A62\u5E87\u60B2\u618A\u6249\u6279\u6590\u6787\u69A7\u6BD4\u6BD6\u6BD7\u6BD8\u6CB8\uF968\u7435\u75FA\u7812\u7891\u79D5\u79D8\u7C83\u7DCB\u7FE1\u80A5"],
      ["dea1", "\u813E\u81C2\u83F2\u871A\u88E8\u8AB9\u8B6C\u8CBB\u9119\u975E\u98DB\u9F3B\u56AC\u5B2A\u5F6C\u658C\u6AB3\u6BAF\u6D5C\u6FF1\u7015\u725D\u73AD\u8CA7\u8CD3\u983B\u6191\u6C37\u8058\u9A01\u4E4D\u4E8B\u4E9B\u4ED5\u4F3A\u4F3C\u4F7F\u4FDF\u50FF\u53F2\u53F8\u5506\u55E3\u56DB\u58EB\u5962\u5A11\u5BEB\u5BFA\u5C04\u5DF3\u5E2B\u5F99\u601D\u6368\u659C\u65AF\u67F6\u67FB\u68AD\u6B7B\u6C99\u6CD7\u6E23\u7009\u7345\u7802\u793E\u7940\u7960\u79C1\u7BE9\u7D17\u7D72\u8086\u820D\u838E\u84D1\u86C7\u88DF\u8A50\u8A5E\u8B1D\u8CDC\u8D66\u8FAD\u90AA\u98FC\u99DF\u9E9D\u524A\uF969\u6714\uF96A"],
      ["dfa1", "\u5098\u522A\u5C71\u6563\u6C55\u73CA\u7523\u759D\u7B97\u849C\u9178\u9730\u4E77\u6492\u6BBA\u715E\u85A9\u4E09\uF96B\u6749\u68EE\u6E17\u829F\u8518\u886B\u63F7\u6F81\u9212\u98AF\u4E0A\u50B7\u50CF\u511F\u5546\u55AA\u5617\u5B40\u5C19\u5CE0\u5E38\u5E8A\u5EA0\u5EC2\u60F3\u6851\u6A61\u6E58\u723D\u7240\u72C0\u76F8\u7965\u7BB1\u7FD4\u88F3\u89F4\u8A73\u8C61\u8CDE\u971C\u585E\u74BD\u8CFD\u55C7\uF96C\u7A61\u7D22\u8272\u7272\u751F\u7525\uF96D\u7B19\u5885\u58FB\u5DBC\u5E8F\u5EB6\u5F90\u6055\u6292\u637F\u654D\u6691\u66D9\u66F8\u6816\u68F2\u7280\u745E\u7B6E\u7D6E\u7DD6\u7F72"],
      ["e0a1", "\u80E5\u8212\u85AF\u897F\u8A93\u901D\u92E4\u9ECD\u9F20\u5915\u596D\u5E2D\u60DC\u6614\u6673\u6790\u6C50\u6DC5\u6F5F\u77F3\u78A9\u84C6\u91CB\u932B\u4ED9\u50CA\u5148\u5584\u5B0B\u5BA3\u6247\u657E\u65CB\u6E32\u717D\u7401\u7444\u7487\u74BF\u766C\u79AA\u7DDA\u7E55\u7FA8\u817A\u81B3\u8239\u861A\u87EC\u8A75\u8DE3\u9078\u9291\u9425\u994D\u9BAE\u5368\u5C51\u6954\u6CC4\u6D29\u6E2B\u820C\u859B\u893B\u8A2D\u8AAA\u96EA\u9F67\u5261\u66B9\u6BB2\u7E96\u87FE\u8D0D\u9583\u965D\u651D\u6D89\u71EE\uF96E\u57CE\u59D3\u5BAC\u6027\u60FA\u6210\u661F\u665F\u7329\u73F9\u76DB\u7701\u7B6C"],
      ["e1a1", "\u8056\u8072\u8165\u8AA0\u9192\u4E16\u52E2\u6B72\u6D17\u7A05\u7B39\u7D30\uF96F\u8CB0\u53EC\u562F\u5851\u5BB5\u5C0F\u5C11\u5DE2\u6240\u6383\u6414\u662D\u68B3\u6CBC\u6D88\u6EAF\u701F\u70A4\u71D2\u7526\u758F\u758E\u7619\u7B11\u7BE0\u7C2B\u7D20\u7D39\u852C\u856D\u8607\u8A34\u900D\u9061\u90B5\u92B7\u97F6\u9A37\u4FD7\u5C6C\u675F\u6D91\u7C9F\u7E8C\u8B16\u8D16\u901F\u5B6B\u5DFD\u640D\u84C0\u905C\u98E1\u7387\u5B8B\u609A\u677E\u6DDE\u8A1F\u8AA6\u9001\u980C\u5237\uF970\u7051\u788E\u9396\u8870\u91D7\u4FEE\u53D7\u55FD\u56DA\u5782\u58FD\u5AC2\u5B88\u5CAB\u5CC0\u5E25\u6101"],
      ["e2a1", "\u620D\u624B\u6388\u641C\u6536\u6578\u6A39\u6B8A\u6C34\u6D19\u6F31\u71E7\u72E9\u7378\u7407\u74B2\u7626\u7761\u79C0\u7A57\u7AEA\u7CB9\u7D8F\u7DAC\u7E61\u7F9E\u8129\u8331\u8490\u84DA\u85EA\u8896\u8AB0\u8B90\u8F38\u9042\u9083\u916C\u9296\u92B9\u968B\u96A7\u96A8\u96D6\u9700\u9808\u9996\u9AD3\u9B1A\u53D4\u587E\u5919\u5B70\u5BBF\u6DD1\u6F5A\u719F\u7421\u74B9\u8085\u83FD\u5DE1\u5F87\u5FAA\u6042\u65EC\u6812\u696F\u6A53\u6B89\u6D35\u6DF3\u73E3\u76FE\u77AC\u7B4D\u7D14\u8123\u821C\u8340\u84F4\u8563\u8A62\u8AC4\u9187\u931E\u9806\u99B4\u620C\u8853\u8FF0\u9265\u5D07\u5D27"],
      ["e3a1", "\u5D69\u745F\u819D\u8768\u6FD5\u62FE\u7FD2\u8936\u8972\u4E1E\u4E58\u50E7\u52DD\u5347\u627F\u6607\u7E69\u8805\u965E\u4F8D\u5319\u5636\u59CB\u5AA4\u5C38\u5C4E\u5C4D\u5E02\u5F11\u6043\u65BD\u662F\u6642\u67BE\u67F4\u731C\u77E2\u793A\u7FC5\u8494\u84CD\u8996\u8A66\u8A69\u8AE1\u8C55\u8C7A\u57F4\u5BD4\u5F0F\u606F\u62ED\u690D\u6B96\u6E5C\u7184\u7BD2\u8755\u8B58\u8EFE\u98DF\u98FE\u4F38\u4F81\u4FE1\u547B\u5A20\u5BB8\u613C\u65B0\u6668\u71FC\u7533\u795E\u7D33\u814E\u81E3\u8398\u85AA\u85CE\u8703\u8A0A\u8EAB\u8F9B\uF971\u8FC5\u5931\u5BA4\u5BE6\u6089\u5BE9\u5C0B\u5FC3\u6C81"],
      ["e4a1", "\uF972\u6DF1\u700B\u751A\u82AF\u8AF6\u4EC0\u5341\uF973\u96D9\u6C0F\u4E9E\u4FC4\u5152\u555E\u5A25\u5CE8\u6211\u7259\u82BD\u83AA\u86FE\u8859\u8A1D\u963F\u96C5\u9913\u9D09\u9D5D\u580A\u5CB3\u5DBD\u5E44\u60E1\u6115\u63E1\u6A02\u6E25\u9102\u9354\u984E\u9C10\u9F77\u5B89\u5CB8\u6309\u664F\u6848\u773C\u96C1\u978D\u9854\u9B9F\u65A1\u8B01\u8ECB\u95BC\u5535\u5CA9\u5DD6\u5EB5\u6697\u764C\u83F4\u95C7\u58D3\u62BC\u72CE\u9D28\u4EF0\u592E\u600F\u663B\u6B83\u79E7\u9D26\u5393\u54C0\u57C3\u5D16\u611B\u66D6\u6DAF\u788D\u827E\u9698\u9744\u5384\u627C\u6396\u6DB2\u7E0A\u814B\u984D"],
      ["e5a1", "\u6AFB\u7F4C\u9DAF\u9E1A\u4E5F\u503B\u51B6\u591C\u60F9\u63F6\u6930\u723A\u8036\uF974\u91CE\u5F31\uF975\uF976\u7D04\u82E5\u846F\u84BB\u85E5\u8E8D\uF977\u4F6F\uF978\uF979\u58E4\u5B43\u6059\u63DA\u6518\u656D\u6698\uF97A\u694A\u6A23\u6D0B\u7001\u716C\u75D2\u760D\u79B3\u7A70\uF97B\u7F8A\uF97C\u8944\uF97D\u8B93\u91C0\u967D\uF97E\u990A\u5704\u5FA1\u65BC\u6F01\u7600\u79A6\u8A9E\u99AD\u9B5A\u9F6C\u5104\u61B6\u6291\u6A8D\u81C6\u5043\u5830\u5F66\u7109\u8A00\u8AFA\u5B7C\u8616\u4FFA\u513C\u56B4\u5944\u63A9\u6DF9\u5DAA\u696D\u5186\u4E88\u4F59\uF97F\uF980\uF981\u5982\uF982"],
      ["e6a1", "\uF983\u6B5F\u6C5D\uF984\u74B5\u7916\uF985\u8207\u8245\u8339\u8F3F\u8F5D\uF986\u9918\uF987\uF988\uF989\u4EA6\uF98A\u57DF\u5F79\u6613\uF98B\uF98C\u75AB\u7E79\u8B6F\uF98D\u9006\u9A5B\u56A5\u5827\u59F8\u5A1F\u5BB4\uF98E\u5EF6\uF98F\uF990\u6350\u633B\uF991\u693D\u6C87\u6CBF\u6D8E\u6D93\u6DF5\u6F14\uF992\u70DF\u7136\u7159\uF993\u71C3\u71D5\uF994\u784F\u786F\uF995\u7B75\u7DE3\uF996\u7E2F\uF997\u884D\u8EDF\uF998\uF999\uF99A\u925B\uF99B\u9CF6\uF99C\uF99D\uF99E\u6085\u6D85\uF99F\u71B1\uF9A0\uF9A1\u95B1\u53AD\uF9A2\uF9A3\uF9A4\u67D3\uF9A5\u708E\u7130\u7430\u8276\u82D2"],
      ["e7a1", "\uF9A6\u95BB\u9AE5\u9E7D\u66C4\uF9A7\u71C1\u8449\uF9A8\uF9A9\u584B\uF9AA\uF9AB\u5DB8\u5F71\uF9AC\u6620\u668E\u6979\u69AE\u6C38\u6CF3\u6E36\u6F41\u6FDA\u701B\u702F\u7150\u71DF\u7370\uF9AD\u745B\uF9AE\u74D4\u76C8\u7A4E\u7E93\uF9AF\uF9B0\u82F1\u8A60\u8FCE\uF9B1\u9348\uF9B2\u9719\uF9B3\uF9B4\u4E42\u502A\uF9B5\u5208\u53E1\u66F3\u6C6D\u6FCA\u730A\u777F\u7A62\u82AE\u85DD\u8602\uF9B6\u88D4\u8A63\u8B7D\u8C6B\uF9B7\u92B3\uF9B8\u9713\u9810\u4E94\u4F0D\u4FC9\u50B2\u5348\u543E\u5433\u55DA\u5862\u58BA\u5967\u5A1B\u5BE4\u609F\uF9B9\u61CA\u6556\u65FF\u6664\u68A7\u6C5A\u6FB3"],
      ["e8a1", "\u70CF\u71AC\u7352\u7B7D\u8708\u8AA4\u9C32\u9F07\u5C4B\u6C83\u7344\u7389\u923A\u6EAB\u7465\u761F\u7A69\u7E15\u860A\u5140\u58C5\u64C1\u74EE\u7515\u7670\u7FC1\u9095\u96CD\u9954\u6E26\u74E6\u7AA9\u7AAA\u81E5\u86D9\u8778\u8A1B\u5A49\u5B8C\u5B9B\u68A1\u6900\u6D63\u73A9\u7413\u742C\u7897\u7DE9\u7FEB\u8118\u8155\u839E\u8C4C\u962E\u9811\u66F0\u5F80\u65FA\u6789\u6C6A\u738B\u502D\u5A03\u6B6A\u77EE\u5916\u5D6C\u5DCD\u7325\u754F\uF9BA\uF9BB\u50E5\u51F9\u582F\u592D\u5996\u59DA\u5BE5\uF9BC\uF9BD\u5DA2\u62D7\u6416\u6493\u64FE\uF9BE\u66DC\uF9BF\u6A48\uF9C0\u71FF\u7464\uF9C1"],
      ["e9a1", "\u7A88\u7AAF\u7E47\u7E5E\u8000\u8170\uF9C2\u87EF\u8981\u8B20\u9059\uF9C3\u9080\u9952\u617E\u6B32\u6D74\u7E1F\u8925\u8FB1\u4FD1\u50AD\u5197\u52C7\u57C7\u5889\u5BB9\u5EB8\u6142\u6995\u6D8C\u6E67\u6EB6\u7194\u7462\u7528\u752C\u8073\u8338\u84C9\u8E0A\u9394\u93DE\uF9C4\u4E8E\u4F51\u5076\u512A\u53C8\u53CB\u53F3\u5B87\u5BD3\u5C24\u611A\u6182\u65F4\u725B\u7397\u7440\u76C2\u7950\u7991\u79B9\u7D06\u7FBD\u828B\u85D5\u865E\u8FC2\u9047\u90F5\u91EA\u9685\u96E8\u96E9\u52D6\u5F67\u65ED\u6631\u682F\u715C\u7A36\u90C1\u980A\u4E91\uF9C5\u6A52\u6B9E\u6F90\u7189\u8018\u82B8\u8553"],
      ["eaa1", "\u904B\u9695\u96F2\u97FB\u851A\u9B31\u4E90\u718A\u96C4\u5143\u539F\u54E1\u5713\u5712\u57A3\u5A9B\u5AC4\u5BC3\u6028\u613F\u63F4\u6C85\u6D39\u6E72\u6E90\u7230\u733F\u7457\u82D1\u8881\u8F45\u9060\uF9C6\u9662\u9858\u9D1B\u6708\u8D8A\u925E\u4F4D\u5049\u50DE\u5371\u570D\u59D4\u5A01\u5C09\u6170\u6690\u6E2D\u7232\u744B\u7DEF\u80C3\u840E\u8466\u853F\u875F\u885B\u8918\u8B02\u9055\u97CB\u9B4F\u4E73\u4F91\u5112\u516A\uF9C7\u552F\u55A9\u5B7A\u5BA5\u5E7C\u5E7D\u5EBE\u60A0\u60DF\u6108\u6109\u63C4\u6538\u6709\uF9C8\u67D4\u67DA\uF9C9\u6961\u6962\u6CB9\u6D27\uF9CA\u6E38\uF9CB"],
      ["eba1", "\u6FE1\u7336\u7337\uF9CC\u745C\u7531\uF9CD\u7652\uF9CE\uF9CF\u7DAD\u81FE\u8438\u88D5\u8A98\u8ADB\u8AED\u8E30\u8E42\u904A\u903E\u907A\u9149\u91C9\u936E\uF9D0\uF9D1\u5809\uF9D2\u6BD3\u8089\u80B2\uF9D3\uF9D4\u5141\u596B\u5C39\uF9D5\uF9D6\u6F64\u73A7\u80E4\u8D07\uF9D7\u9217\u958F\uF9D8\uF9D9\uF9DA\uF9DB\u807F\u620E\u701C\u7D68\u878D\uF9DC\u57A0\u6069\u6147\u6BB7\u8ABE\u9280\u96B1\u4E59\u541F\u6DEB\u852D\u9670\u97F3\u98EE\u63D6\u6CE3\u9091\u51DD\u61C9\u81BA\u9DF9\u4F9D\u501A\u5100\u5B9C\u610F\u61FF\u64EC\u6905\u6BC5\u7591\u77E3\u7FA9\u8264\u858F\u87FB\u8863\u8ABC"],
      ["eca1", "\u8B70\u91AB\u4E8C\u4EE5\u4F0A\uF9DD\uF9DE\u5937\u59E8\uF9DF\u5DF2\u5F1B\u5F5B\u6021\uF9E0\uF9E1\uF9E2\uF9E3\u723E\u73E5\uF9E4\u7570\u75CD\uF9E5\u79FB\uF9E6\u800C\u8033\u8084\u82E1\u8351\uF9E7\uF9E8\u8CBD\u8CB3\u9087\uF9E9\uF9EA\u98F4\u990C\uF9EB\uF9EC\u7037\u76CA\u7FCA\u7FCC\u7FFC\u8B1A\u4EBA\u4EC1\u5203\u5370\uF9ED\u54BD\u56E0\u59FB\u5BC5\u5F15\u5FCD\u6E6E\uF9EE\uF9EF\u7D6A\u8335\uF9F0\u8693\u8A8D\uF9F1\u976D\u9777\uF9F2\uF9F3\u4E00\u4F5A\u4F7E\u58F9\u65E5\u6EA2\u9038\u93B0\u99B9\u4EFB\u58EC\u598A\u59D9\u6041\uF9F4\uF9F5\u7A14\uF9F6\u834F\u8CC3\u5165\u5344"],
      ["eda1", "\uF9F7\uF9F8\uF9F9\u4ECD\u5269\u5B55\u82BF\u4ED4\u523A\u54A8\u59C9\u59FF\u5B50\u5B57\u5B5C\u6063\u6148\u6ECB\u7099\u716E\u7386\u74F7\u75B5\u78C1\u7D2B\u8005\u81EA\u8328\u8517\u85C9\u8AEE\u8CC7\u96CC\u4F5C\u52FA\u56BC\u65AB\u6628\u707C\u70B8\u7235\u7DBD\u828D\u914C\u96C0\u9D72\u5B71\u68E7\u6B98\u6F7A\u76DE\u5C91\u66AB\u6F5B\u7BB4\u7C2A\u8836\u96DC\u4E08\u4ED7\u5320\u5834\u58BB\u58EF\u596C\u5C07\u5E33\u5E84\u5F35\u638C\u66B2\u6756\u6A1F\u6AA3\u6B0C\u6F3F\u7246\uF9FA\u7350\u748B\u7AE0\u7CA7\u8178\u81DF\u81E7\u838A\u846C\u8523\u8594\u85CF\u88DD\u8D13\u91AC\u9577"],
      ["eea1", "\u969C\u518D\u54C9\u5728\u5BB0\u624D\u6750\u683D\u6893\u6E3D\u6ED3\u707D\u7E21\u88C1\u8CA1\u8F09\u9F4B\u9F4E\u722D\u7B8F\u8ACD\u931A\u4F47\u4F4E\u5132\u5480\u59D0\u5E95\u62B5\u6775\u696E\u6A17\u6CAE\u6E1A\u72D9\u732A\u75BD\u7BB8\u7D35\u82E7\u83F9\u8457\u85F7\u8A5B\u8CAF\u8E87\u9019\u90B8\u96CE\u9F5F\u52E3\u540A\u5AE1\u5BC2\u6458\u6575\u6EF4\u72C4\uF9FB\u7684\u7A4D\u7B1B\u7C4D\u7E3E\u7FDF\u837B\u8B2B\u8CCA\u8D64\u8DE1\u8E5F\u8FEA\u8FF9\u9069\u93D1\u4F43\u4F7A\u50B3\u5168\u5178\u524D\u526A\u5861\u587C\u5960\u5C08\u5C55\u5EDB\u609B\u6230\u6813\u6BBF\u6C08\u6FB1"],
      ["efa1", "\u714E\u7420\u7530\u7538\u7551\u7672\u7B4C\u7B8B\u7BAD\u7BC6\u7E8F\u8A6E\u8F3E\u8F49\u923F\u9293\u9322\u942B\u96FB\u985A\u986B\u991E\u5207\u622A\u6298\u6D59\u7664\u7ACA\u7BC0\u7D76\u5360\u5CBE\u5E97\u6F38\u70B9\u7C98\u9711\u9B8E\u9EDE\u63A5\u647A\u8776\u4E01\u4E95\u4EAD\u505C\u5075\u5448\u59C3\u5B9A\u5E40\u5EAD\u5EF7\u5F81\u60C5\u633A\u653F\u6574\u65CC\u6676\u6678\u67FE\u6968\u6A89\u6B63\u6C40\u6DC0\u6DE8\u6E1F\u6E5E\u701E\u70A1\u738E\u73FD\u753A\u775B\u7887\u798E\u7A0B\u7A7D\u7CBE\u7D8E\u8247\u8A02\u8AEA\u8C9E\u912D\u914A\u91D8\u9266\u92CC\u9320\u9706\u9756"],
      ["f0a1", "\u975C\u9802\u9F0E\u5236\u5291\u557C\u5824\u5E1D\u5F1F\u608C\u63D0\u68AF\u6FDF\u796D\u7B2C\u81CD\u85BA\u88FD\u8AF8\u8E44\u918D\u9664\u969B\u973D\u984C\u9F4A\u4FCE\u5146\u51CB\u52A9\u5632\u5F14\u5F6B\u63AA\u64CD\u65E9\u6641\u66FA\u66F9\u671D\u689D\u68D7\u69FD\u6F15\u6F6E\u7167\u71E5\u722A\u74AA\u773A\u7956\u795A\u79DF\u7A20\u7A95\u7C97\u7CDF\u7D44\u7E70\u8087\u85FB\u86A4\u8A54\u8ABF\u8D99\u8E81\u9020\u906D\u91E3\u963B\u96D5\u9CE5\u65CF\u7C07\u8DB3\u93C3\u5B58\u5C0A\u5352\u62D9\u731D\u5027\u5B97\u5F9E\u60B0\u616B\u68D5\u6DD9\u742E\u7A2E\u7D42\u7D9C\u7E31\u816B"],
      ["f1a1", "\u8E2A\u8E35\u937E\u9418\u4F50\u5750\u5DE6\u5EA7\u632B\u7F6A\u4E3B\u4F4F\u4F8F\u505A\u59DD\u80C4\u546A\u5468\u55FE\u594F\u5B99\u5DDE\u5EDA\u665D\u6731\u67F1\u682A\u6CE8\u6D32\u6E4A\u6F8D\u70B7\u73E0\u7587\u7C4C\u7D02\u7D2C\u7DA2\u821F\u86DB\u8A3B\u8A85\u8D70\u8E8A\u8F33\u9031\u914E\u9152\u9444\u99D0\u7AF9\u7CA5\u4FCA\u5101\u51C6\u57C8\u5BEF\u5CFB\u6659\u6A3D\u6D5A\u6E96\u6FEC\u710C\u756F\u7AE3\u8822\u9021\u9075\u96CB\u99FF\u8301\u4E2D\u4EF2\u8846\u91CD\u537D\u6ADB\u696B\u6C41\u847A\u589E\u618E\u66FE\u62EF\u70DD\u7511\u75C7\u7E52\u84B8\u8B49\u8D08\u4E4B\u53EA"],
      ["f2a1", "\u54AB\u5730\u5740\u5FD7\u6301\u6307\u646F\u652F\u65E8\u667A\u679D\u67B3\u6B62\u6C60\u6C9A\u6F2C\u77E5\u7825\u7949\u7957\u7D19\u80A2\u8102\u81F3\u829D\u82B7\u8718\u8A8C\uF9FC\u8D04\u8DBE\u9072\u76F4\u7A19\u7A37\u7E54\u8077\u5507\u55D4\u5875\u632F\u6422\u6649\u664B\u686D\u699B\u6B84\u6D25\u6EB1\u73CD\u7468\u74A1\u755B\u75B9\u76E1\u771E\u778B\u79E6\u7E09\u7E1D\u81FB\u852F\u8897\u8A3A\u8CD1\u8EEB\u8FB0\u9032\u93AD\u9663\u9673\u9707\u4F84\u53F1\u59EA\u5AC9\u5E19\u684E\u74C6\u75BE\u79E9\u7A92\u81A3\u86ED\u8CEA\u8DCC\u8FED\u659F\u6715\uF9FD\u57F7\u6F57\u7DDD\u8F2F"],
      ["f3a1", "\u93F6\u96C6\u5FB5\u61F2\u6F84\u4E14\u4F98\u501F\u53C9\u55DF\u5D6F\u5DEE\u6B21\u6B64\u78CB\u7B9A\uF9FE\u8E49\u8ECA\u906E\u6349\u643E\u7740\u7A84\u932F\u947F\u9F6A\u64B0\u6FAF\u71E6\u74A8\u74DA\u7AC4\u7C12\u7E82\u7CB2\u7E98\u8B9A\u8D0A\u947D\u9910\u994C\u5239\u5BDF\u64E6\u672D\u7D2E\u50ED\u53C3\u5879\u6158\u6159\u61FA\u65AC\u7AD9\u8B92\u8B96\u5009\u5021\u5275\u5531\u5A3C\u5EE0\u5F70\u6134\u655E\u660C\u6636\u66A2\u69CD\u6EC4\u6F32\u7316\u7621\u7A93\u8139\u8259\u83D6\u84BC\u50B5\u57F0\u5BC0\u5BE8\u5F69\u63A1\u7826\u7DB5\u83DC\u8521\u91C7\u91F5\u518A\u67F5\u7B56"],
      ["f4a1", "\u8CAC\u51C4\u59BB\u60BD\u8655\u501C\uF9FF\u5254\u5C3A\u617D\u621A\u62D3\u64F2\u65A5\u6ECC\u7620\u810A\u8E60\u965F\u96BB\u4EDF\u5343\u5598\u5929\u5DDD\u64C5\u6CC9\u6DFA\u7394\u7A7F\u821B\u85A6\u8CE4\u8E10\u9077\u91E7\u95E1\u9621\u97C6\u51F8\u54F2\u5586\u5FB9\u64A4\u6F88\u7DB4\u8F1F\u8F4D\u9435\u50C9\u5C16\u6CBE\u6DFB\u751B\u77BB\u7C3D\u7C64\u8A79\u8AC2\u581E\u59BE\u5E16\u6377\u7252\u758A\u776B\u8ADC\u8CBC\u8F12\u5EF3\u6674\u6DF8\u807D\u83C1\u8ACB\u9751\u9BD6\uFA00\u5243\u66FF\u6D95\u6EEF\u7DE0\u8AE6\u902E\u905E\u9AD4\u521D\u527F\u54E8\u6194\u6284\u62DB\u68A2"],
      ["f5a1", "\u6912\u695A\u6A35\u7092\u7126\u785D\u7901\u790E\u79D2\u7A0D\u8096\u8278\u82D5\u8349\u8549\u8C82\u8D85\u9162\u918B\u91AE\u4FC3\u56D1\u71ED\u77D7\u8700\u89F8\u5BF8\u5FD6\u6751\u90A8\u53E2\u585A\u5BF5\u60A4\u6181\u6460\u7E3D\u8070\u8525\u9283\u64AE\u50AC\u5D14\u6700\u589C\u62BD\u63A8\u690E\u6978\u6A1E\u6E6B\u76BA\u79CB\u82BB\u8429\u8ACF\u8DA8\u8FFD\u9112\u914B\u919C\u9310\u9318\u939A\u96DB\u9A36\u9C0D\u4E11\u755C\u795D\u7AFA\u7B51\u7BC9\u7E2E\u84C4\u8E59\u8E74\u8EF8\u9010\u6625\u693F\u7443\u51FA\u672E\u9EDC\u5145\u5FE0\u6C96\u87F2\u885D\u8877\u60B4\u81B5\u8403"],
      ["f6a1", "\u8D05\u53D6\u5439\u5634\u5A36\u5C31\u708A\u7FE0\u805A\u8106\u81ED\u8DA3\u9189\u9A5F\u9DF2\u5074\u4EC4\u53A0\u60FB\u6E2C\u5C64\u4F88\u5024\u55E4\u5CD9\u5E5F\u6065\u6894\u6CBB\u6DC4\u71BE\u75D4\u75F4\u7661\u7A1A\u7A49\u7DC7\u7DFB\u7F6E\u81F4\u86A9\u8F1C\u96C9\u99B3\u9F52\u5247\u52C5\u98ED\u89AA\u4E03\u67D2\u6F06\u4FB5\u5BE2\u6795\u6C88\u6D78\u741B\u7827\u91DD\u937C\u87C4\u79E4\u7A31\u5FEB\u4ED6\u54A4\u553E\u58AE\u59A5\u60F0\u6253\u62D6\u6736\u6955\u8235\u9640\u99B1\u99DD\u502C\u5353\u5544\u577C\uFA01\u6258\uFA02\u64E2\u666B\u67DD\u6FC1\u6FEF\u7422\u7438\u8A17"],
      ["f7a1", "\u9438\u5451\u5606\u5766\u5F48\u619A\u6B4E\u7058\u70AD\u7DBB\u8A95\u596A\u812B\u63A2\u7708\u803D\u8CAA\u5854\u642D\u69BB\u5B95\u5E11\u6E6F\uFA03\u8569\u514C\u53F0\u592A\u6020\u614B\u6B86\u6C70\u6CF0\u7B1E\u80CE\u82D4\u8DC6\u90B0\u98B1\uFA04\u64C7\u6FA4\u6491\u6504\u514E\u5410\u571F\u8A0E\u615F\u6876\uFA05\u75DB\u7B52\u7D71\u901A\u5806\u69CC\u817F\u892A\u9000\u9839\u5078\u5957\u59AC\u6295\u900F\u9B2A\u615D\u7279\u95D6\u5761\u5A46\u5DF4\u628A\u64AD\u64FA\u6777\u6CE2\u6D3E\u722C\u7436\u7834\u7F77\u82AD\u8DDB\u9817\u5224\u5742\u677F\u7248\u74E3\u8CA9\u8FA6\u9211"],
      ["f8a1", "\u962A\u516B\u53ED\u634C\u4F69\u5504\u6096\u6557\u6C9B\u6D7F\u724C\u72FD\u7A17\u8987\u8C9D\u5F6D\u6F8E\u70F9\u81A8\u610E\u4FBF\u504F\u6241\u7247\u7BC7\u7DE8\u7FE9\u904D\u97AD\u9A19\u8CB6\u576A\u5E73\u67B0\u840D\u8A55\u5420\u5B16\u5E63\u5EE2\u5F0A\u6583\u80BA\u853D\u9589\u965B\u4F48\u5305\u530D\u530F\u5486\u54FA\u5703\u5E03\u6016\u629B\u62B1\u6355\uFA06\u6CE1\u6D66\u75B1\u7832\u80DE\u812F\u82DE\u8461\u84B2\u888D\u8912\u900B\u92EA\u98FD\u9B91\u5E45\u66B4\u66DD\u7011\u7206\uFA07\u4FF5\u527D\u5F6A\u6153\u6753\u6A19\u6F02\u74E2\u7968\u8868\u8C79\u98C7\u98C4\u9A43"],
      ["f9a1", "\u54C1\u7A1F\u6953\u8AF7\u8C4A\u98A8\u99AE\u5F7C\u62AB\u75B2\u76AE\u88AB\u907F\u9642\u5339\u5F3C\u5FC5\u6CCC\u73CC\u7562\u758B\u7B46\u82FE\u999D\u4E4F\u903C\u4E0B\u4F55\u53A6\u590F\u5EC8\u6630\u6CB3\u7455\u8377\u8766\u8CC0\u9050\u971E\u9C15\u58D1\u5B78\u8650\u8B14\u9DB4\u5BD2\u6068\u608D\u65F1\u6C57\u6F22\u6FA3\u701A\u7F55\u7FF0\u9591\u9592\u9650\u97D3\u5272\u8F44\u51FD\u542B\u54B8\u5563\u558A\u6ABB\u6DB5\u7DD8\u8266\u929C\u9677\u9E79\u5408\u54C8\u76D2\u86E4\u95A4\u95D4\u965C\u4EA2\u4F09\u59EE\u5AE6\u5DF7\u6052\u6297\u676D\u6841\u6C86\u6E2F\u7F38\u809B\u822A"],
      ["faa1", "\uFA08\uFA09\u9805\u4EA5\u5055\u54B3\u5793\u595A\u5B69\u5BB3\u61C8\u6977\u6D77\u7023\u87F9\u89E3\u8A72\u8AE7\u9082\u99ED\u9AB8\u52BE\u6838\u5016\u5E78\u674F\u8347\u884C\u4EAB\u5411\u56AE\u73E6\u9115\u97FF\u9909\u9957\u9999\u5653\u589F\u865B\u8A31\u61B2\u6AF6\u737B\u8ED2\u6B47\u96AA\u9A57\u5955\u7200\u8D6B\u9769\u4FD4\u5CF4\u5F26\u61F8\u665B\u6CEB\u70AB\u7384\u73B9\u73FE\u7729\u774D\u7D43\u7D62\u7E23\u8237\u8852\uFA0A\u8CE2\u9249\u986F\u5B51\u7A74\u8840\u9801\u5ACC\u4FE0\u5354\u593E\u5CFD\u633E\u6D79\u72F9\u8105\u8107\u83A2\u92CF\u9830\u4EA8\u5144\u5211\u578B"],
      ["fba1", "\u5F62\u6CC2\u6ECE\u7005\u7050\u70AF\u7192\u73E9\u7469\u834A\u87A2\u8861\u9008\u90A2\u93A3\u99A8\u516E\u5F57\u60E0\u6167\u66B3\u8559\u8E4A\u91AF\u978B\u4E4E\u4E92\u547C\u58D5\u58FA\u597D\u5CB5\u5F27\u6236\u6248\u660A\u6667\u6BEB\u6D69\u6DCF\u6E56\u6EF8\u6F94\u6FE0\u6FE9\u705D\u72D0\u7425\u745A\u74E0\u7693\u795C\u7CCA\u7E1E\u80E1\u82A6\u846B\u84BF\u864E\u865F\u8774\u8B77\u8C6A\u93AC\u9800\u9865\u60D1\u6216\u9177\u5A5A\u660F\u6DF7\u6E3E\u743F\u9B42\u5FFD\u60DA\u7B0F\u54C4\u5F18\u6C5E\u6CD3\u6D2A\u70D8\u7D05\u8679\u8A0C\u9D3B\u5316\u548C\u5B05\u6A3A\u706B\u7575"],
      ["fca1", "\u798D\u79BE\u82B1\u83EF\u8A71\u8B41\u8CA8\u9774\uFA0B\u64F4\u652B\u78BA\u78BB\u7A6B\u4E38\u559A\u5950\u5BA6\u5E7B\u60A3\u63DB\u6B61\u6665\u6853\u6E19\u7165\u74B0\u7D08\u9084\u9A69\u9C25\u6D3B\u6ED1\u733E\u8C41\u95CA\u51F0\u5E4C\u5FA8\u604D\u60F6\u6130\u614C\u6643\u6644\u69A5\u6CC1\u6E5F\u6EC9\u6F62\u714C\u749C\u7687\u7BC1\u7C27\u8352\u8757\u9051\u968D\u9EC3\u532F\u56DE\u5EFB\u5F8A\u6062\u6094\u61F7\u6666\u6703\u6A9C\u6DEE\u6FAE\u7070\u736A\u7E6A\u81BE\u8334\u86D4\u8AA8\u8CC4\u5283\u7372\u5B96\u6A6B\u9404\u54EE\u5686\u5B5D\u6548\u6585\u66C9\u689F\u6D8D\u6DC6"],
      ["fda1", "\u723B\u80B4\u9175\u9A4D\u4FAF\u5019\u539A\u540E\u543C\u5589\u55C5\u5E3F\u5F8C\u673D\u7166\u73DD\u9005\u52DB\u52F3\u5864\u58CE\u7104\u718F\u71FB\u85B0\u8A13\u6688\u85A8\u55A7\u6684\u714A\u8431\u5349\u5599\u6BC1\u5F59\u5FBD\u63EE\u6689\u7147\u8AF1\u8F1D\u9EBE\u4F11\u643A\u70CB\u7566\u8667\u6064\u8B4E\u9DF8\u5147\u51F6\u5308\u6D36\u80F8\u9ED1\u6615\u6B23\u7098\u75D5\u5403\u5C79\u7D07\u8A16\u6B20\u6B3D\u6B46\u5438\u6070\u6D3D\u7FD5\u8208\u50D6\u51DE\u559C\u566B\u56CD\u59EC\u5B09\u5E0C\u6199\u6198\u6231\u665E\u66E6\u7199\u71B9\u71BA\u72A7\u79A7\u7A00\u7FB2\u8A70"]
    ];
  }
});

// packages/core/node_modules/iconv-lite/encodings/tables/cp950.json
var require_cp950 = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/tables/cp950.json"(exports2, module2) {
    module2.exports = [
      ["0", "\0", 127],
      ["a140", "\u3000\uFF0C\u3001\u3002\uFF0E\u2027\uFF1B\uFF1A\uFF1F\uFF01\uFE30\u2026\u2025\uFE50\uFE51\uFE52\xB7\uFE54\uFE55\uFE56\uFE57\uFF5C\u2013\uFE31\u2014\uFE33\u2574\uFE34\uFE4F\uFF08\uFF09\uFE35\uFE36\uFF5B\uFF5D\uFE37\uFE38\u3014\u3015\uFE39\uFE3A\u3010\u3011\uFE3B\uFE3C\u300A\u300B\uFE3D\uFE3E\u3008\u3009\uFE3F\uFE40\u300C\u300D\uFE41\uFE42\u300E\u300F\uFE43\uFE44\uFE59\uFE5A"],
      ["a1a1", "\uFE5B\uFE5C\uFE5D\uFE5E\u2018\u2019\u201C\u201D\u301D\u301E\u2035\u2032\uFF03\uFF06\uFF0A\u203B\xA7\u3003\u25CB\u25CF\u25B3\u25B2\u25CE\u2606\u2605\u25C7\u25C6\u25A1\u25A0\u25BD\u25BC\u32A3\u2105\xAF\uFFE3\uFF3F\u02CD\uFE49\uFE4A\uFE4D\uFE4E\uFE4B\uFE4C\uFE5F\uFE60\uFE61\uFF0B\uFF0D\xD7\xF7\xB1\u221A\uFF1C\uFF1E\uFF1D\u2266\u2267\u2260\u221E\u2252\u2261\uFE62", 4, "\uFF5E\u2229\u222A\u22A5\u2220\u221F\u22BF\u33D2\u33D1\u222B\u222E\u2235\u2234\u2640\u2642\u2295\u2299\u2191\u2193\u2190\u2192\u2196\u2197\u2199\u2198\u2225\u2223\uFF0F"],
      ["a240", "\uFF3C\u2215\uFE68\uFF04\uFFE5\u3012\uFFE0\uFFE1\uFF05\uFF20\u2103\u2109\uFE69\uFE6A\uFE6B\u33D5\u339C\u339D\u339E\u33CE\u33A1\u338E\u338F\u33C4\xB0\u5159\u515B\u515E\u515D\u5161\u5163\u55E7\u74E9\u7CCE\u2581", 7, "\u258F\u258E\u258D\u258C\u258B\u258A\u2589\u253C\u2534\u252C\u2524\u251C\u2594\u2500\u2502\u2595\u250C\u2510\u2514\u2518\u256D"],
      ["a2a1", "\u256E\u2570\u256F\u2550\u255E\u256A\u2561\u25E2\u25E3\u25E5\u25E4\u2571\u2572\u2573\uFF10", 9, "\u2160", 9, "\u3021", 8, "\u5341\u5344\u5345\uFF21", 25, "\uFF41", 21],
      ["a340", "\uFF57\uFF58\uFF59\uFF5A\u0391", 16, "\u03A3", 6, "\u03B1", 16, "\u03C3", 6, "\u3105", 10],
      ["a3a1", "\u3110", 25, "\u02D9\u02C9\u02CA\u02C7\u02CB"],
      ["a3e1", "\u20AC"],
      ["a440", "\u4E00\u4E59\u4E01\u4E03\u4E43\u4E5D\u4E86\u4E8C\u4EBA\u513F\u5165\u516B\u51E0\u5200\u5201\u529B\u5315\u5341\u535C\u53C8\u4E09\u4E0B\u4E08\u4E0A\u4E2B\u4E38\u51E1\u4E45\u4E48\u4E5F\u4E5E\u4E8E\u4EA1\u5140\u5203\u52FA\u5343\u53C9\u53E3\u571F\u58EB\u5915\u5927\u5973\u5B50\u5B51\u5B53\u5BF8\u5C0F\u5C22\u5C38\u5C71\u5DDD\u5DE5\u5DF1\u5DF2\u5DF3\u5DFE\u5E72\u5EFE\u5F0B\u5F13\u624D"],
      ["a4a1", "\u4E11\u4E10\u4E0D\u4E2D\u4E30\u4E39\u4E4B\u5C39\u4E88\u4E91\u4E95\u4E92\u4E94\u4EA2\u4EC1\u4EC0\u4EC3\u4EC6\u4EC7\u4ECD\u4ECA\u4ECB\u4EC4\u5143\u5141\u5167\u516D\u516E\u516C\u5197\u51F6\u5206\u5207\u5208\u52FB\u52FE\u52FF\u5316\u5339\u5348\u5347\u5345\u535E\u5384\u53CB\u53CA\u53CD\u58EC\u5929\u592B\u592A\u592D\u5B54\u5C11\u5C24\u5C3A\u5C6F\u5DF4\u5E7B\u5EFF\u5F14\u5F15\u5FC3\u6208\u6236\u624B\u624E\u652F\u6587\u6597\u65A4\u65B9\u65E5\u66F0\u6708\u6728\u6B20\u6B62\u6B79\u6BCB\u6BD4\u6BDB\u6C0F\u6C34\u706B\u722A\u7236\u723B\u7247\u7259\u725B\u72AC\u738B\u4E19"],
      ["a540", "\u4E16\u4E15\u4E14\u4E18\u4E3B\u4E4D\u4E4F\u4E4E\u4EE5\u4ED8\u4ED4\u4ED5\u4ED6\u4ED7\u4EE3\u4EE4\u4ED9\u4EDE\u5145\u5144\u5189\u518A\u51AC\u51F9\u51FA\u51F8\u520A\u52A0\u529F\u5305\u5306\u5317\u531D\u4EDF\u534A\u5349\u5361\u5360\u536F\u536E\u53BB\u53EF\u53E4\u53F3\u53EC\u53EE\u53E9\u53E8\u53FC\u53F8\u53F5\u53EB\u53E6\u53EA\u53F2\u53F1\u53F0\u53E5\u53ED\u53FB\u56DB\u56DA\u5916"],
      ["a5a1", "\u592E\u5931\u5974\u5976\u5B55\u5B83\u5C3C\u5DE8\u5DE7\u5DE6\u5E02\u5E03\u5E73\u5E7C\u5F01\u5F18\u5F17\u5FC5\u620A\u6253\u6254\u6252\u6251\u65A5\u65E6\u672E\u672C\u672A\u672B\u672D\u6B63\u6BCD\u6C11\u6C10\u6C38\u6C41\u6C40\u6C3E\u72AF\u7384\u7389\u74DC\u74E6\u7518\u751F\u7528\u7529\u7530\u7531\u7532\u7533\u758B\u767D\u76AE\u76BF\u76EE\u77DB\u77E2\u77F3\u793A\u79BE\u7A74\u7ACB\u4E1E\u4E1F\u4E52\u4E53\u4E69\u4E99\u4EA4\u4EA6\u4EA5\u4EFF\u4F09\u4F19\u4F0A\u4F15\u4F0D\u4F10\u4F11\u4F0F\u4EF2\u4EF6\u4EFB\u4EF0\u4EF3\u4EFD\u4F01\u4F0B\u5149\u5147\u5146\u5148\u5168"],
      ["a640", "\u5171\u518D\u51B0\u5217\u5211\u5212\u520E\u5216\u52A3\u5308\u5321\u5320\u5370\u5371\u5409\u540F\u540C\u540A\u5410\u5401\u540B\u5404\u5411\u540D\u5408\u5403\u540E\u5406\u5412\u56E0\u56DE\u56DD\u5733\u5730\u5728\u572D\u572C\u572F\u5729\u5919\u591A\u5937\u5938\u5984\u5978\u5983\u597D\u5979\u5982\u5981\u5B57\u5B58\u5B87\u5B88\u5B85\u5B89\u5BFA\u5C16\u5C79\u5DDE\u5E06\u5E76\u5E74"],
      ["a6a1", "\u5F0F\u5F1B\u5FD9\u5FD6\u620E\u620C\u620D\u6210\u6263\u625B\u6258\u6536\u65E9\u65E8\u65EC\u65ED\u66F2\u66F3\u6709\u673D\u6734\u6731\u6735\u6B21\u6B64\u6B7B\u6C16\u6C5D\u6C57\u6C59\u6C5F\u6C60\u6C50\u6C55\u6C61\u6C5B\u6C4D\u6C4E\u7070\u725F\u725D\u767E\u7AF9\u7C73\u7CF8\u7F36\u7F8A\u7FBD\u8001\u8003\u800C\u8012\u8033\u807F\u8089\u808B\u808C\u81E3\u81EA\u81F3\u81FC\u820C\u821B\u821F\u826E\u8272\u827E\u866B\u8840\u884C\u8863\u897F\u9621\u4E32\u4EA8\u4F4D\u4F4F\u4F47\u4F57\u4F5E\u4F34\u4F5B\u4F55\u4F30\u4F50\u4F51\u4F3D\u4F3A\u4F38\u4F43\u4F54\u4F3C\u4F46\u4F63"],
      ["a740", "\u4F5C\u4F60\u4F2F\u4F4E\u4F36\u4F59\u4F5D\u4F48\u4F5A\u514C\u514B\u514D\u5175\u51B6\u51B7\u5225\u5224\u5229\u522A\u5228\u52AB\u52A9\u52AA\u52AC\u5323\u5373\u5375\u541D\u542D\u541E\u543E\u5426\u544E\u5427\u5446\u5443\u5433\u5448\u5442\u541B\u5429\u544A\u5439\u543B\u5438\u542E\u5435\u5436\u5420\u543C\u5440\u5431\u542B\u541F\u542C\u56EA\u56F0\u56E4\u56EB\u574A\u5751\u5740\u574D"],
      ["a7a1", "\u5747\u574E\u573E\u5750\u574F\u573B\u58EF\u593E\u599D\u5992\u59A8\u599E\u59A3\u5999\u5996\u598D\u59A4\u5993\u598A\u59A5\u5B5D\u5B5C\u5B5A\u5B5B\u5B8C\u5B8B\u5B8F\u5C2C\u5C40\u5C41\u5C3F\u5C3E\u5C90\u5C91\u5C94\u5C8C\u5DEB\u5E0C\u5E8F\u5E87\u5E8A\u5EF7\u5F04\u5F1F\u5F64\u5F62\u5F77\u5F79\u5FD8\u5FCC\u5FD7\u5FCD\u5FF1\u5FEB\u5FF8\u5FEA\u6212\u6211\u6284\u6297\u6296\u6280\u6276\u6289\u626D\u628A\u627C\u627E\u6279\u6273\u6292\u626F\u6298\u626E\u6295\u6293\u6291\u6286\u6539\u653B\u6538\u65F1\u66F4\u675F\u674E\u674F\u6750\u6751\u675C\u6756\u675E\u6749\u6746\u6760"],
      ["a840", "\u6753\u6757\u6B65\u6BCF\u6C42\u6C5E\u6C99\u6C81\u6C88\u6C89\u6C85\u6C9B\u6C6A\u6C7A\u6C90\u6C70\u6C8C\u6C68\u6C96\u6C92\u6C7D\u6C83\u6C72\u6C7E\u6C74\u6C86\u6C76\u6C8D\u6C94\u6C98\u6C82\u7076\u707C\u707D\u7078\u7262\u7261\u7260\u72C4\u72C2\u7396\u752C\u752B\u7537\u7538\u7682\u76EF\u77E3\u79C1\u79C0\u79BF\u7A76\u7CFB\u7F55\u8096\u8093\u809D\u8098\u809B\u809A\u80B2\u826F\u8292"],
      ["a8a1", "\u828B\u828D\u898B\u89D2\u8A00\u8C37\u8C46\u8C55\u8C9D\u8D64\u8D70\u8DB3\u8EAB\u8ECA\u8F9B\u8FB0\u8FC2\u8FC6\u8FC5\u8FC4\u5DE1\u9091\u90A2\u90AA\u90A6\u90A3\u9149\u91C6\u91CC\u9632\u962E\u9631\u962A\u962C\u4E26\u4E56\u4E73\u4E8B\u4E9B\u4E9E\u4EAB\u4EAC\u4F6F\u4F9D\u4F8D\u4F73\u4F7F\u4F6C\u4F9B\u4F8B\u4F86\u4F83\u4F70\u4F75\u4F88\u4F69\u4F7B\u4F96\u4F7E\u4F8F\u4F91\u4F7A\u5154\u5152\u5155\u5169\u5177\u5176\u5178\u51BD\u51FD\u523B\u5238\u5237\u523A\u5230\u522E\u5236\u5241\u52BE\u52BB\u5352\u5354\u5353\u5351\u5366\u5377\u5378\u5379\u53D6\u53D4\u53D7\u5473\u5475"],
      ["a940", "\u5496\u5478\u5495\u5480\u547B\u5477\u5484\u5492\u5486\u547C\u5490\u5471\u5476\u548C\u549A\u5462\u5468\u548B\u547D\u548E\u56FA\u5783\u5777\u576A\u5769\u5761\u5766\u5764\u577C\u591C\u5949\u5947\u5948\u5944\u5954\u59BE\u59BB\u59D4\u59B9\u59AE\u59D1\u59C6\u59D0\u59CD\u59CB\u59D3\u59CA\u59AF\u59B3\u59D2\u59C5\u5B5F\u5B64\u5B63\u5B97\u5B9A\u5B98\u5B9C\u5B99\u5B9B\u5C1A\u5C48\u5C45"],
      ["a9a1", "\u5C46\u5CB7\u5CA1\u5CB8\u5CA9\u5CAB\u5CB1\u5CB3\u5E18\u5E1A\u5E16\u5E15\u5E1B\u5E11\u5E78\u5E9A\u5E97\u5E9C\u5E95\u5E96\u5EF6\u5F26\u5F27\u5F29\u5F80\u5F81\u5F7F\u5F7C\u5FDD\u5FE0\u5FFD\u5FF5\u5FFF\u600F\u6014\u602F\u6035\u6016\u602A\u6015\u6021\u6027\u6029\u602B\u601B\u6216\u6215\u623F\u623E\u6240\u627F\u62C9\u62CC\u62C4\u62BF\u62C2\u62B9\u62D2\u62DB\u62AB\u62D3\u62D4\u62CB\u62C8\u62A8\u62BD\u62BC\u62D0\u62D9\u62C7\u62CD\u62B5\u62DA\u62B1\u62D8\u62D6\u62D7\u62C6\u62AC\u62CE\u653E\u65A7\u65BC\u65FA\u6614\u6613\u660C\u6606\u6602\u660E\u6600\u660F\u6615\u660A"],
      ["aa40", "\u6607\u670D\u670B\u676D\u678B\u6795\u6771\u679C\u6773\u6777\u6787\u679D\u6797\u676F\u6770\u677F\u6789\u677E\u6790\u6775\u679A\u6793\u677C\u676A\u6772\u6B23\u6B66\u6B67\u6B7F\u6C13\u6C1B\u6CE3\u6CE8\u6CF3\u6CB1\u6CCC\u6CE5\u6CB3\u6CBD\u6CBE\u6CBC\u6CE2\u6CAB\u6CD5\u6CD3\u6CB8\u6CC4\u6CB9\u6CC1\u6CAE\u6CD7\u6CC5\u6CF1\u6CBF\u6CBB\u6CE1\u6CDB\u6CCA\u6CAC\u6CEF\u6CDC\u6CD6\u6CE0"],
      ["aaa1", "\u7095\u708E\u7092\u708A\u7099\u722C\u722D\u7238\u7248\u7267\u7269\u72C0\u72CE\u72D9\u72D7\u72D0\u73A9\u73A8\u739F\u73AB\u73A5\u753D\u759D\u7599\u759A\u7684\u76C2\u76F2\u76F4\u77E5\u77FD\u793E\u7940\u7941\u79C9\u79C8\u7A7A\u7A79\u7AFA\u7CFE\u7F54\u7F8C\u7F8B\u8005\u80BA\u80A5\u80A2\u80B1\u80A1\u80AB\u80A9\u80B4\u80AA\u80AF\u81E5\u81FE\u820D\u82B3\u829D\u8299\u82AD\u82BD\u829F\u82B9\u82B1\u82AC\u82A5\u82AF\u82B8\u82A3\u82B0\u82BE\u82B7\u864E\u8671\u521D\u8868\u8ECB\u8FCE\u8FD4\u8FD1\u90B5\u90B8\u90B1\u90B6\u91C7\u91D1\u9577\u9580\u961C\u9640\u963F\u963B\u9644"],
      ["ab40", "\u9642\u96B9\u96E8\u9752\u975E\u4E9F\u4EAD\u4EAE\u4FE1\u4FB5\u4FAF\u4FBF\u4FE0\u4FD1\u4FCF\u4FDD\u4FC3\u4FB6\u4FD8\u4FDF\u4FCA\u4FD7\u4FAE\u4FD0\u4FC4\u4FC2\u4FDA\u4FCE\u4FDE\u4FB7\u5157\u5192\u5191\u51A0\u524E\u5243\u524A\u524D\u524C\u524B\u5247\u52C7\u52C9\u52C3\u52C1\u530D\u5357\u537B\u539A\u53DB\u54AC\u54C0\u54A8\u54CE\u54C9\u54B8\u54A6\u54B3\u54C7\u54C2\u54BD\u54AA\u54C1"],
      ["aba1", "\u54C4\u54C8\u54AF\u54AB\u54B1\u54BB\u54A9\u54A7\u54BF\u56FF\u5782\u578B\u57A0\u57A3\u57A2\u57CE\u57AE\u5793\u5955\u5951\u594F\u594E\u5950\u59DC\u59D8\u59FF\u59E3\u59E8\u5A03\u59E5\u59EA\u59DA\u59E6\u5A01\u59FB\u5B69\u5BA3\u5BA6\u5BA4\u5BA2\u5BA5\u5C01\u5C4E\u5C4F\u5C4D\u5C4B\u5CD9\u5CD2\u5DF7\u5E1D\u5E25\u5E1F\u5E7D\u5EA0\u5EA6\u5EFA\u5F08\u5F2D\u5F65\u5F88\u5F85\u5F8A\u5F8B\u5F87\u5F8C\u5F89\u6012\u601D\u6020\u6025\u600E\u6028\u604D\u6070\u6068\u6062\u6046\u6043\u606C\u606B\u606A\u6064\u6241\u62DC\u6316\u6309\u62FC\u62ED\u6301\u62EE\u62FD\u6307\u62F1\u62F7"],
      ["ac40", "\u62EF\u62EC\u62FE\u62F4\u6311\u6302\u653F\u6545\u65AB\u65BD\u65E2\u6625\u662D\u6620\u6627\u662F\u661F\u6628\u6631\u6624\u66F7\u67FF\u67D3\u67F1\u67D4\u67D0\u67EC\u67B6\u67AF\u67F5\u67E9\u67EF\u67C4\u67D1\u67B4\u67DA\u67E5\u67B8\u67CF\u67DE\u67F3\u67B0\u67D9\u67E2\u67DD\u67D2\u6B6A\u6B83\u6B86\u6BB5\u6BD2\u6BD7\u6C1F\u6CC9\u6D0B\u6D32\u6D2A\u6D41\u6D25\u6D0C\u6D31\u6D1E\u6D17"],
      ["aca1", "\u6D3B\u6D3D\u6D3E\u6D36\u6D1B\u6CF5\u6D39\u6D27\u6D38\u6D29\u6D2E\u6D35\u6D0E\u6D2B\u70AB\u70BA\u70B3\u70AC\u70AF\u70AD\u70B8\u70AE\u70A4\u7230\u7272\u726F\u7274\u72E9\u72E0\u72E1\u73B7\u73CA\u73BB\u73B2\u73CD\u73C0\u73B3\u751A\u752D\u754F\u754C\u754E\u754B\u75AB\u75A4\u75A5\u75A2\u75A3\u7678\u7686\u7687\u7688\u76C8\u76C6\u76C3\u76C5\u7701\u76F9\u76F8\u7709\u770B\u76FE\u76FC\u7707\u77DC\u7802\u7814\u780C\u780D\u7946\u7949\u7948\u7947\u79B9\u79BA\u79D1\u79D2\u79CB\u7A7F\u7A81\u7AFF\u7AFD\u7C7D\u7D02\u7D05\u7D00\u7D09\u7D07\u7D04\u7D06\u7F38\u7F8E\u7FBF\u8004"],
      ["ad40", "\u8010\u800D\u8011\u8036\u80D6\u80E5\u80DA\u80C3\u80C4\u80CC\u80E1\u80DB\u80CE\u80DE\u80E4\u80DD\u81F4\u8222\u82E7\u8303\u8305\u82E3\u82DB\u82E6\u8304\u82E5\u8302\u8309\u82D2\u82D7\u82F1\u8301\u82DC\u82D4\u82D1\u82DE\u82D3\u82DF\u82EF\u8306\u8650\u8679\u867B\u867A\u884D\u886B\u8981\u89D4\u8A08\u8A02\u8A03\u8C9E\u8CA0\u8D74\u8D73\u8DB4\u8ECD\u8ECC\u8FF0\u8FE6\u8FE2\u8FEA\u8FE5"],
      ["ada1", "\u8FED\u8FEB\u8FE4\u8FE8\u90CA\u90CE\u90C1\u90C3\u914B\u914A\u91CD\u9582\u9650\u964B\u964C\u964D\u9762\u9769\u97CB\u97ED\u97F3\u9801\u98A8\u98DB\u98DF\u9996\u9999\u4E58\u4EB3\u500C\u500D\u5023\u4FEF\u5026\u5025\u4FF8\u5029\u5016\u5006\u503C\u501F\u501A\u5012\u5011\u4FFA\u5000\u5014\u5028\u4FF1\u5021\u500B\u5019\u5018\u4FF3\u4FEE\u502D\u502A\u4FFE\u502B\u5009\u517C\u51A4\u51A5\u51A2\u51CD\u51CC\u51C6\u51CB\u5256\u525C\u5254\u525B\u525D\u532A\u537F\u539F\u539D\u53DF\u54E8\u5510\u5501\u5537\u54FC\u54E5\u54F2\u5506\u54FA\u5514\u54E9\u54ED\u54E1\u5509\u54EE\u54EA"],
      ["ae40", "\u54E6\u5527\u5507\u54FD\u550F\u5703\u5704\u57C2\u57D4\u57CB\u57C3\u5809\u590F\u5957\u5958\u595A\u5A11\u5A18\u5A1C\u5A1F\u5A1B\u5A13\u59EC\u5A20\u5A23\u5A29\u5A25\u5A0C\u5A09\u5B6B\u5C58\u5BB0\u5BB3\u5BB6\u5BB4\u5BAE\u5BB5\u5BB9\u5BB8\u5C04\u5C51\u5C55\u5C50\u5CED\u5CFD\u5CFB\u5CEA\u5CE8\u5CF0\u5CF6\u5D01\u5CF4\u5DEE\u5E2D\u5E2B\u5EAB\u5EAD\u5EA7\u5F31\u5F92\u5F91\u5F90\u6059"],
      ["aea1", "\u6063\u6065\u6050\u6055\u606D\u6069\u606F\u6084\u609F\u609A\u608D\u6094\u608C\u6085\u6096\u6247\u62F3\u6308\u62FF\u634E\u633E\u632F\u6355\u6342\u6346\u634F\u6349\u633A\u6350\u633D\u632A\u632B\u6328\u634D\u634C\u6548\u6549\u6599\u65C1\u65C5\u6642\u6649\u664F\u6643\u6652\u664C\u6645\u6641\u66F8\u6714\u6715\u6717\u6821\u6838\u6848\u6846\u6853\u6839\u6842\u6854\u6829\u68B3\u6817\u684C\u6851\u683D\u67F4\u6850\u6840\u683C\u6843\u682A\u6845\u6813\u6818\u6841\u6B8A\u6B89\u6BB7\u6C23\u6C27\u6C28\u6C26\u6C24\u6CF0\u6D6A\u6D95\u6D88\u6D87\u6D66\u6D78\u6D77\u6D59\u6D93"],
      ["af40", "\u6D6C\u6D89\u6D6E\u6D5A\u6D74\u6D69\u6D8C\u6D8A\u6D79\u6D85\u6D65\u6D94\u70CA\u70D8\u70E4\u70D9\u70C8\u70CF\u7239\u7279\u72FC\u72F9\u72FD\u72F8\u72F7\u7386\u73ED\u7409\u73EE\u73E0\u73EA\u73DE\u7554\u755D\u755C\u755A\u7559\u75BE\u75C5\u75C7\u75B2\u75B3\u75BD\u75BC\u75B9\u75C2\u75B8\u768B\u76B0\u76CA\u76CD\u76CE\u7729\u771F\u7720\u7728\u77E9\u7830\u7827\u7838\u781D\u7834\u7837"],
      ["afa1", "\u7825\u782D\u7820\u781F\u7832\u7955\u7950\u7960\u795F\u7956\u795E\u795D\u7957\u795A\u79E4\u79E3\u79E7\u79DF\u79E6\u79E9\u79D8\u7A84\u7A88\u7AD9\u7B06\u7B11\u7C89\u7D21\u7D17\u7D0B\u7D0A\u7D20\u7D22\u7D14\u7D10\u7D15\u7D1A\u7D1C\u7D0D\u7D19\u7D1B\u7F3A\u7F5F\u7F94\u7FC5\u7FC1\u8006\u8018\u8015\u8019\u8017\u803D\u803F\u80F1\u8102\u80F0\u8105\u80ED\u80F4\u8106\u80F8\u80F3\u8108\u80FD\u810A\u80FC\u80EF\u81ED\u81EC\u8200\u8210\u822A\u822B\u8228\u822C\u82BB\u832B\u8352\u8354\u834A\u8338\u8350\u8349\u8335\u8334\u834F\u8332\u8339\u8336\u8317\u8340\u8331\u8328\u8343"],
      ["b040", "\u8654\u868A\u86AA\u8693\u86A4\u86A9\u868C\u86A3\u869C\u8870\u8877\u8881\u8882\u887D\u8879\u8A18\u8A10\u8A0E\u8A0C\u8A15\u8A0A\u8A17\u8A13\u8A16\u8A0F\u8A11\u8C48\u8C7A\u8C79\u8CA1\u8CA2\u8D77\u8EAC\u8ED2\u8ED4\u8ECF\u8FB1\u9001\u9006\u8FF7\u9000\u8FFA\u8FF4\u9003\u8FFD\u9005\u8FF8\u9095\u90E1\u90DD\u90E2\u9152\u914D\u914C\u91D8\u91DD\u91D7\u91DC\u91D9\u9583\u9662\u9663\u9661"],
      ["b0a1", "\u965B\u965D\u9664\u9658\u965E\u96BB\u98E2\u99AC\u9AA8\u9AD8\u9B25\u9B32\u9B3C\u4E7E\u507A\u507D\u505C\u5047\u5043\u504C\u505A\u5049\u5065\u5076\u504E\u5055\u5075\u5074\u5077\u504F\u500F\u506F\u506D\u515C\u5195\u51F0\u526A\u526F\u52D2\u52D9\u52D8\u52D5\u5310\u530F\u5319\u533F\u5340\u533E\u53C3\u66FC\u5546\u556A\u5566\u5544\u555E\u5561\u5543\u554A\u5531\u5556\u554F\u5555\u552F\u5564\u5538\u552E\u555C\u552C\u5563\u5533\u5541\u5557\u5708\u570B\u5709\u57DF\u5805\u580A\u5806\u57E0\u57E4\u57FA\u5802\u5835\u57F7\u57F9\u5920\u5962\u5A36\u5A41\u5A49\u5A66\u5A6A\u5A40"],
      ["b140", "\u5A3C\u5A62\u5A5A\u5A46\u5A4A\u5B70\u5BC7\u5BC5\u5BC4\u5BC2\u5BBF\u5BC6\u5C09\u5C08\u5C07\u5C60\u5C5C\u5C5D\u5D07\u5D06\u5D0E\u5D1B\u5D16\u5D22\u5D11\u5D29\u5D14\u5D19\u5D24\u5D27\u5D17\u5DE2\u5E38\u5E36\u5E33\u5E37\u5EB7\u5EB8\u5EB6\u5EB5\u5EBE\u5F35\u5F37\u5F57\u5F6C\u5F69\u5F6B\u5F97\u5F99\u5F9E\u5F98\u5FA1\u5FA0\u5F9C\u607F\u60A3\u6089\u60A0\u60A8\u60CB\u60B4\u60E6\u60BD"],
      ["b1a1", "\u60C5\u60BB\u60B5\u60DC\u60BC\u60D8\u60D5\u60C6\u60DF\u60B8\u60DA\u60C7\u621A\u621B\u6248\u63A0\u63A7\u6372\u6396\u63A2\u63A5\u6377\u6367\u6398\u63AA\u6371\u63A9\u6389\u6383\u639B\u636B\u63A8\u6384\u6388\u6399\u63A1\u63AC\u6392\u638F\u6380\u637B\u6369\u6368\u637A\u655D\u6556\u6551\u6559\u6557\u555F\u654F\u6558\u6555\u6554\u659C\u659B\u65AC\u65CF\u65CB\u65CC\u65CE\u665D\u665A\u6664\u6668\u6666\u665E\u66F9\u52D7\u671B\u6881\u68AF\u68A2\u6893\u68B5\u687F\u6876\u68B1\u68A7\u6897\u68B0\u6883\u68C4\u68AD\u6886\u6885\u6894\u689D\u68A8\u689F\u68A1\u6882\u6B32\u6BBA"],
      ["b240", "\u6BEB\u6BEC\u6C2B\u6D8E\u6DBC\u6DF3\u6DD9\u6DB2\u6DE1\u6DCC\u6DE4\u6DFB\u6DFA\u6E05\u6DC7\u6DCB\u6DAF\u6DD1\u6DAE\u6DDE\u6DF9\u6DB8\u6DF7\u6DF5\u6DC5\u6DD2\u6E1A\u6DB5\u6DDA\u6DEB\u6DD8\u6DEA\u6DF1\u6DEE\u6DE8\u6DC6\u6DC4\u6DAA\u6DEC\u6DBF\u6DE6\u70F9\u7109\u710A\u70FD\u70EF\u723D\u727D\u7281\u731C\u731B\u7316\u7313\u7319\u7387\u7405\u740A\u7403\u7406\u73FE\u740D\u74E0\u74F6"],
      ["b2a1", "\u74F7\u751C\u7522\u7565\u7566\u7562\u7570\u758F\u75D4\u75D5\u75B5\u75CA\u75CD\u768E\u76D4\u76D2\u76DB\u7737\u773E\u773C\u7736\u7738\u773A\u786B\u7843\u784E\u7965\u7968\u796D\u79FB\u7A92\u7A95\u7B20\u7B28\u7B1B\u7B2C\u7B26\u7B19\u7B1E\u7B2E\u7C92\u7C97\u7C95\u7D46\u7D43\u7D71\u7D2E\u7D39\u7D3C\u7D40\u7D30\u7D33\u7D44\u7D2F\u7D42\u7D32\u7D31\u7F3D\u7F9E\u7F9A\u7FCC\u7FCE\u7FD2\u801C\u804A\u8046\u812F\u8116\u8123\u812B\u8129\u8130\u8124\u8202\u8235\u8237\u8236\u8239\u838E\u839E\u8398\u8378\u83A2\u8396\u83BD\u83AB\u8392\u838A\u8393\u8389\u83A0\u8377\u837B\u837C"],
      ["b340", "\u8386\u83A7\u8655\u5F6A\u86C7\u86C0\u86B6\u86C4\u86B5\u86C6\u86CB\u86B1\u86AF\u86C9\u8853\u889E\u8888\u88AB\u8892\u8896\u888D\u888B\u8993\u898F\u8A2A\u8A1D\u8A23\u8A25\u8A31\u8A2D\u8A1F\u8A1B\u8A22\u8C49\u8C5A\u8CA9\u8CAC\u8CAB\u8CA8\u8CAA\u8CA7\u8D67\u8D66\u8DBE\u8DBA\u8EDB\u8EDF\u9019\u900D\u901A\u9017\u9023\u901F\u901D\u9010\u9015\u901E\u9020\u900F\u9022\u9016\u901B\u9014"],
      ["b3a1", "\u90E8\u90ED\u90FD\u9157\u91CE\u91F5\u91E6\u91E3\u91E7\u91ED\u91E9\u9589\u966A\u9675\u9673\u9678\u9670\u9674\u9676\u9677\u966C\u96C0\u96EA\u96E9\u7AE0\u7ADF\u9802\u9803\u9B5A\u9CE5\u9E75\u9E7F\u9EA5\u9EBB\u50A2\u508D\u5085\u5099\u5091\u5080\u5096\u5098\u509A\u6700\u51F1\u5272\u5274\u5275\u5269\u52DE\u52DD\u52DB\u535A\u53A5\u557B\u5580\u55A7\u557C\u558A\u559D\u5598\u5582\u559C\u55AA\u5594\u5587\u558B\u5583\u55B3\u55AE\u559F\u553E\u55B2\u559A\u55BB\u55AC\u55B1\u557E\u5589\u55AB\u5599\u570D\u582F\u582A\u5834\u5824\u5830\u5831\u5821\u581D\u5820\u58F9\u58FA\u5960"],
      ["b440", "\u5A77\u5A9A\u5A7F\u5A92\u5A9B\u5AA7\u5B73\u5B71\u5BD2\u5BCC\u5BD3\u5BD0\u5C0A\u5C0B\u5C31\u5D4C\u5D50\u5D34\u5D47\u5DFD\u5E45\u5E3D\u5E40\u5E43\u5E7E\u5ECA\u5EC1\u5EC2\u5EC4\u5F3C\u5F6D\u5FA9\u5FAA\u5FA8\u60D1\u60E1\u60B2\u60B6\u60E0\u611C\u6123\u60FA\u6115\u60F0\u60FB\u60F4\u6168\u60F1\u610E\u60F6\u6109\u6100\u6112\u621F\u6249\u63A3\u638C\u63CF\u63C0\u63E9\u63C9\u63C6\u63CD"],
      ["b4a1", "\u63D2\u63E3\u63D0\u63E1\u63D6\u63ED\u63EE\u6376\u63F4\u63EA\u63DB\u6452\u63DA\u63F9\u655E\u6566\u6562\u6563\u6591\u6590\u65AF\u666E\u6670\u6674\u6676\u666F\u6691\u667A\u667E\u6677\u66FE\u66FF\u671F\u671D\u68FA\u68D5\u68E0\u68D8\u68D7\u6905\u68DF\u68F5\u68EE\u68E7\u68F9\u68D2\u68F2\u68E3\u68CB\u68CD\u690D\u6912\u690E\u68C9\u68DA\u696E\u68FB\u6B3E\u6B3A\u6B3D\u6B98\u6B96\u6BBC\u6BEF\u6C2E\u6C2F\u6C2C\u6E2F\u6E38\u6E54\u6E21\u6E32\u6E67\u6E4A\u6E20\u6E25\u6E23\u6E1B\u6E5B\u6E58\u6E24\u6E56\u6E6E\u6E2D\u6E26\u6E6F\u6E34\u6E4D\u6E3A\u6E2C\u6E43\u6E1D\u6E3E\u6ECB"],
      ["b540", "\u6E89\u6E19\u6E4E\u6E63\u6E44\u6E72\u6E69\u6E5F\u7119\u711A\u7126\u7130\u7121\u7136\u716E\u711C\u724C\u7284\u7280\u7336\u7325\u7334\u7329\u743A\u742A\u7433\u7422\u7425\u7435\u7436\u7434\u742F\u741B\u7426\u7428\u7525\u7526\u756B\u756A\u75E2\u75DB\u75E3\u75D9\u75D8\u75DE\u75E0\u767B\u767C\u7696\u7693\u76B4\u76DC\u774F\u77ED\u785D\u786C\u786F\u7A0D\u7A08\u7A0B\u7A05\u7A00\u7A98"],
      ["b5a1", "\u7A97\u7A96\u7AE5\u7AE3\u7B49\u7B56\u7B46\u7B50\u7B52\u7B54\u7B4D\u7B4B\u7B4F\u7B51\u7C9F\u7CA5\u7D5E\u7D50\u7D68\u7D55\u7D2B\u7D6E\u7D72\u7D61\u7D66\u7D62\u7D70\u7D73\u5584\u7FD4\u7FD5\u800B\u8052\u8085\u8155\u8154\u814B\u8151\u814E\u8139\u8146\u813E\u814C\u8153\u8174\u8212\u821C\u83E9\u8403\u83F8\u840D\u83E0\u83C5\u840B\u83C1\u83EF\u83F1\u83F4\u8457\u840A\u83F0\u840C\u83CC\u83FD\u83F2\u83CA\u8438\u840E\u8404\u83DC\u8407\u83D4\u83DF\u865B\u86DF\u86D9\u86ED\u86D4\u86DB\u86E4\u86D0\u86DE\u8857\u88C1\u88C2\u88B1\u8983\u8996\u8A3B\u8A60\u8A55\u8A5E\u8A3C\u8A41"],
      ["b640", "\u8A54\u8A5B\u8A50\u8A46\u8A34\u8A3A\u8A36\u8A56\u8C61\u8C82\u8CAF\u8CBC\u8CB3\u8CBD\u8CC1\u8CBB\u8CC0\u8CB4\u8CB7\u8CB6\u8CBF\u8CB8\u8D8A\u8D85\u8D81\u8DCE\u8DDD\u8DCB\u8DDA\u8DD1\u8DCC\u8DDB\u8DC6\u8EFB\u8EF8\u8EFC\u8F9C\u902E\u9035\u9031\u9038\u9032\u9036\u9102\u90F5\u9109\u90FE\u9163\u9165\u91CF\u9214\u9215\u9223\u9209\u921E\u920D\u9210\u9207\u9211\u9594\u958F\u958B\u9591"],
      ["b6a1", "\u9593\u9592\u958E\u968A\u968E\u968B\u967D\u9685\u9686\u968D\u9672\u9684\u96C1\u96C5\u96C4\u96C6\u96C7\u96EF\u96F2\u97CC\u9805\u9806\u9808\u98E7\u98EA\u98EF\u98E9\u98F2\u98ED\u99AE\u99AD\u9EC3\u9ECD\u9ED1\u4E82\u50AD\u50B5\u50B2\u50B3\u50C5\u50BE\u50AC\u50B7\u50BB\u50AF\u50C7\u527F\u5277\u527D\u52DF\u52E6\u52E4\u52E2\u52E3\u532F\u55DF\u55E8\u55D3\u55E6\u55CE\u55DC\u55C7\u55D1\u55E3\u55E4\u55EF\u55DA\u55E1\u55C5\u55C6\u55E5\u55C9\u5712\u5713\u585E\u5851\u5858\u5857\u585A\u5854\u586B\u584C\u586D\u584A\u5862\u5852\u584B\u5967\u5AC1\u5AC9\u5ACC\u5ABE\u5ABD\u5ABC"],
      ["b740", "\u5AB3\u5AC2\u5AB2\u5D69\u5D6F\u5E4C\u5E79\u5EC9\u5EC8\u5F12\u5F59\u5FAC\u5FAE\u611A\u610F\u6148\u611F\u60F3\u611B\u60F9\u6101\u6108\u614E\u614C\u6144\u614D\u613E\u6134\u6127\u610D\u6106\u6137\u6221\u6222\u6413\u643E\u641E\u642A\u642D\u643D\u642C\u640F\u641C\u6414\u640D\u6436\u6416\u6417\u6406\u656C\u659F\u65B0\u6697\u6689\u6687\u6688\u6696\u6684\u6698\u668D\u6703\u6994\u696D"],
      ["b7a1", "\u695A\u6977\u6960\u6954\u6975\u6930\u6982\u694A\u6968\u696B\u695E\u6953\u6979\u6986\u695D\u6963\u695B\u6B47\u6B72\u6BC0\u6BBF\u6BD3\u6BFD\u6EA2\u6EAF\u6ED3\u6EB6\u6EC2\u6E90\u6E9D\u6EC7\u6EC5\u6EA5\u6E98\u6EBC\u6EBA\u6EAB\u6ED1\u6E96\u6E9C\u6EC4\u6ED4\u6EAA\u6EA7\u6EB4\u714E\u7159\u7169\u7164\u7149\u7167\u715C\u716C\u7166\u714C\u7165\u715E\u7146\u7168\u7156\u723A\u7252\u7337\u7345\u733F\u733E\u746F\u745A\u7455\u745F\u745E\u7441\u743F\u7459\u745B\u745C\u7576\u7578\u7600\u75F0\u7601\u75F2\u75F1\u75FA\u75FF\u75F4\u75F3\u76DE\u76DF\u775B\u776B\u7766\u775E\u7763"],
      ["b840", "\u7779\u776A\u776C\u775C\u7765\u7768\u7762\u77EE\u788E\u78B0\u7897\u7898\u788C\u7889\u787C\u7891\u7893\u787F\u797A\u797F\u7981\u842C\u79BD\u7A1C\u7A1A\u7A20\u7A14\u7A1F\u7A1E\u7A9F\u7AA0\u7B77\u7BC0\u7B60\u7B6E\u7B67\u7CB1\u7CB3\u7CB5\u7D93\u7D79\u7D91\u7D81\u7D8F\u7D5B\u7F6E\u7F69\u7F6A\u7F72\u7FA9\u7FA8\u7FA4\u8056\u8058\u8086\u8084\u8171\u8170\u8178\u8165\u816E\u8173\u816B"],
      ["b8a1", "\u8179\u817A\u8166\u8205\u8247\u8482\u8477\u843D\u8431\u8475\u8466\u846B\u8449\u846C\u845B\u843C\u8435\u8461\u8463\u8469\u846D\u8446\u865E\u865C\u865F\u86F9\u8713\u8708\u8707\u8700\u86FE\u86FB\u8702\u8703\u8706\u870A\u8859\u88DF\u88D4\u88D9\u88DC\u88D8\u88DD\u88E1\u88CA\u88D5\u88D2\u899C\u89E3\u8A6B\u8A72\u8A73\u8A66\u8A69\u8A70\u8A87\u8A7C\u8A63\u8AA0\u8A71\u8A85\u8A6D\u8A62\u8A6E\u8A6C\u8A79\u8A7B\u8A3E\u8A68\u8C62\u8C8A\u8C89\u8CCA\u8CC7\u8CC8\u8CC4\u8CB2\u8CC3\u8CC2\u8CC5\u8DE1\u8DDF\u8DE8\u8DEF\u8DF3\u8DFA\u8DEA\u8DE4\u8DE6\u8EB2\u8F03\u8F09\u8EFE\u8F0A"],
      ["b940", "\u8F9F\u8FB2\u904B\u904A\u9053\u9042\u9054\u903C\u9055\u9050\u9047\u904F\u904E\u904D\u9051\u903E\u9041\u9112\u9117\u916C\u916A\u9169\u91C9\u9237\u9257\u9238\u923D\u9240\u923E\u925B\u924B\u9264\u9251\u9234\u9249\u924D\u9245\u9239\u923F\u925A\u9598\u9698\u9694\u9695\u96CD\u96CB\u96C9\u96CA\u96F7\u96FB\u96F9\u96F6\u9756\u9774\u9776\u9810\u9811\u9813\u980A\u9812\u980C\u98FC\u98F4"],
      ["b9a1", "\u98FD\u98FE\u99B3\u99B1\u99B4\u9AE1\u9CE9\u9E82\u9F0E\u9F13\u9F20\u50E7\u50EE\u50E5\u50D6\u50ED\u50DA\u50D5\u50CF\u50D1\u50F1\u50CE\u50E9\u5162\u51F3\u5283\u5282\u5331\u53AD\u55FE\u5600\u561B\u5617\u55FD\u5614\u5606\u5609\u560D\u560E\u55F7\u5616\u561F\u5608\u5610\u55F6\u5718\u5716\u5875\u587E\u5883\u5893\u588A\u5879\u5885\u587D\u58FD\u5925\u5922\u5924\u596A\u5969\u5AE1\u5AE6\u5AE9\u5AD7\u5AD6\u5AD8\u5AE3\u5B75\u5BDE\u5BE7\u5BE1\u5BE5\u5BE6\u5BE8\u5BE2\u5BE4\u5BDF\u5C0D\u5C62\u5D84\u5D87\u5E5B\u5E63\u5E55\u5E57\u5E54\u5ED3\u5ED6\u5F0A\u5F46\u5F70\u5FB9\u6147"],
      ["ba40", "\u613F\u614B\u6177\u6162\u6163\u615F\u615A\u6158\u6175\u622A\u6487\u6458\u6454\u64A4\u6478\u645F\u647A\u6451\u6467\u6434\u646D\u647B\u6572\u65A1\u65D7\u65D6\u66A2\u66A8\u669D\u699C\u69A8\u6995\u69C1\u69AE\u69D3\u69CB\u699B\u69B7\u69BB\u69AB\u69B4\u69D0\u69CD\u69AD\u69CC\u69A6\u69C3\u69A3\u6B49\u6B4C\u6C33\u6F33\u6F14\u6EFE\u6F13\u6EF4\u6F29\u6F3E\u6F20\u6F2C\u6F0F\u6F02\u6F22"],
      ["baa1", "\u6EFF\u6EEF\u6F06\u6F31\u6F38\u6F32\u6F23\u6F15\u6F2B\u6F2F\u6F88\u6F2A\u6EEC\u6F01\u6EF2\u6ECC\u6EF7\u7194\u7199\u717D\u718A\u7184\u7192\u723E\u7292\u7296\u7344\u7350\u7464\u7463\u746A\u7470\u746D\u7504\u7591\u7627\u760D\u760B\u7609\u7613\u76E1\u76E3\u7784\u777D\u777F\u7761\u78C1\u789F\u78A7\u78B3\u78A9\u78A3\u798E\u798F\u798D\u7A2E\u7A31\u7AAA\u7AA9\u7AED\u7AEF\u7BA1\u7B95\u7B8B\u7B75\u7B97\u7B9D\u7B94\u7B8F\u7BB8\u7B87\u7B84\u7CB9\u7CBD\u7CBE\u7DBB\u7DB0\u7D9C\u7DBD\u7DBE\u7DA0\u7DCA\u7DB4\u7DB2\u7DB1\u7DBA\u7DA2\u7DBF\u7DB5\u7DB8\u7DAD\u7DD2\u7DC7\u7DAC"],
      ["bb40", "\u7F70\u7FE0\u7FE1\u7FDF\u805E\u805A\u8087\u8150\u8180\u818F\u8188\u818A\u817F\u8182\u81E7\u81FA\u8207\u8214\u821E\u824B\u84C9\u84BF\u84C6\u84C4\u8499\u849E\u84B2\u849C\u84CB\u84B8\u84C0\u84D3\u8490\u84BC\u84D1\u84CA\u873F\u871C\u873B\u8722\u8725\u8734\u8718\u8755\u8737\u8729\u88F3\u8902\u88F4\u88F9\u88F8\u88FD\u88E8\u891A\u88EF\u8AA6\u8A8C\u8A9E\u8AA3\u8A8D\u8AA1\u8A93\u8AA4"],
      ["bba1", "\u8AAA\u8AA5\u8AA8\u8A98\u8A91\u8A9A\u8AA7\u8C6A\u8C8D\u8C8C\u8CD3\u8CD1\u8CD2\u8D6B\u8D99\u8D95\u8DFC\u8F14\u8F12\u8F15\u8F13\u8FA3\u9060\u9058\u905C\u9063\u9059\u905E\u9062\u905D\u905B\u9119\u9118\u911E\u9175\u9178\u9177\u9174\u9278\u9280\u9285\u9298\u9296\u927B\u9293\u929C\u92A8\u927C\u9291\u95A1\u95A8\u95A9\u95A3\u95A5\u95A4\u9699\u969C\u969B\u96CC\u96D2\u9700\u977C\u9785\u97F6\u9817\u9818\u98AF\u98B1\u9903\u9905\u990C\u9909\u99C1\u9AAF\u9AB0\u9AE6\u9B41\u9B42\u9CF4\u9CF6\u9CF3\u9EBC\u9F3B\u9F4A\u5104\u5100\u50FB\u50F5\u50F9\u5102\u5108\u5109\u5105\u51DC"],
      ["bc40", "\u5287\u5288\u5289\u528D\u528A\u52F0\u53B2\u562E\u563B\u5639\u5632\u563F\u5634\u5629\u5653\u564E\u5657\u5674\u5636\u562F\u5630\u5880\u589F\u589E\u58B3\u589C\u58AE\u58A9\u58A6\u596D\u5B09\u5AFB\u5B0B\u5AF5\u5B0C\u5B08\u5BEE\u5BEC\u5BE9\u5BEB\u5C64\u5C65\u5D9D\u5D94\u5E62\u5E5F\u5E61\u5EE2\u5EDA\u5EDF\u5EDD\u5EE3\u5EE0\u5F48\u5F71\u5FB7\u5FB5\u6176\u6167\u616E\u615D\u6155\u6182"],
      ["bca1", "\u617C\u6170\u616B\u617E\u61A7\u6190\u61AB\u618E\u61AC\u619A\u61A4\u6194\u61AE\u622E\u6469\u646F\u6479\u649E\u64B2\u6488\u6490\u64B0\u64A5\u6493\u6495\u64A9\u6492\u64AE\u64AD\u64AB\u649A\u64AC\u6499\u64A2\u64B3\u6575\u6577\u6578\u66AE\u66AB\u66B4\u66B1\u6A23\u6A1F\u69E8\u6A01\u6A1E\u6A19\u69FD\u6A21\u6A13\u6A0A\u69F3\u6A02\u6A05\u69ED\u6A11\u6B50\u6B4E\u6BA4\u6BC5\u6BC6\u6F3F\u6F7C\u6F84\u6F51\u6F66\u6F54\u6F86\u6F6D\u6F5B\u6F78\u6F6E\u6F8E\u6F7A\u6F70\u6F64\u6F97\u6F58\u6ED5\u6F6F\u6F60\u6F5F\u719F\u71AC\u71B1\u71A8\u7256\u729B\u734E\u7357\u7469\u748B\u7483"],
      ["bd40", "\u747E\u7480\u757F\u7620\u7629\u761F\u7624\u7626\u7621\u7622\u769A\u76BA\u76E4\u778E\u7787\u778C\u7791\u778B\u78CB\u78C5\u78BA\u78CA\u78BE\u78D5\u78BC\u78D0\u7A3F\u7A3C\u7A40\u7A3D\u7A37\u7A3B\u7AAF\u7AAE\u7BAD\u7BB1\u7BC4\u7BB4\u7BC6\u7BC7\u7BC1\u7BA0\u7BCC\u7CCA\u7DE0\u7DF4\u7DEF\u7DFB\u7DD8\u7DEC\u7DDD\u7DE8\u7DE3\u7DDA\u7DDE\u7DE9\u7D9E\u7DD9\u7DF2\u7DF9\u7F75\u7F77\u7FAF"],
      ["bda1", "\u7FE9\u8026\u819B\u819C\u819D\u81A0\u819A\u8198\u8517\u853D\u851A\u84EE\u852C\u852D\u8513\u8511\u8523\u8521\u8514\u84EC\u8525\u84FF\u8506\u8782\u8774\u8776\u8760\u8766\u8778\u8768\u8759\u8757\u874C\u8753\u885B\u885D\u8910\u8907\u8912\u8913\u8915\u890A\u8ABC\u8AD2\u8AC7\u8AC4\u8A95\u8ACB\u8AF8\u8AB2\u8AC9\u8AC2\u8ABF\u8AB0\u8AD6\u8ACD\u8AB6\u8AB9\u8ADB\u8C4C\u8C4E\u8C6C\u8CE0\u8CDE\u8CE6\u8CE4\u8CEC\u8CED\u8CE2\u8CE3\u8CDC\u8CEA\u8CE1\u8D6D\u8D9F\u8DA3\u8E2B\u8E10\u8E1D\u8E22\u8E0F\u8E29\u8E1F\u8E21\u8E1E\u8EBA\u8F1D\u8F1B\u8F1F\u8F29\u8F26\u8F2A\u8F1C\u8F1E"],
      ["be40", "\u8F25\u9069\u906E\u9068\u906D\u9077\u9130\u912D\u9127\u9131\u9187\u9189\u918B\u9183\u92C5\u92BB\u92B7\u92EA\u92AC\u92E4\u92C1\u92B3\u92BC\u92D2\u92C7\u92F0\u92B2\u95AD\u95B1\u9704\u9706\u9707\u9709\u9760\u978D\u978B\u978F\u9821\u982B\u981C\u98B3\u990A\u9913\u9912\u9918\u99DD\u99D0\u99DF\u99DB\u99D1\u99D5\u99D2\u99D9\u9AB7\u9AEE\u9AEF\u9B27\u9B45\u9B44\u9B77\u9B6F\u9D06\u9D09"],
      ["bea1", "\u9D03\u9EA9\u9EBE\u9ECE\u58A8\u9F52\u5112\u5118\u5114\u5110\u5115\u5180\u51AA\u51DD\u5291\u5293\u52F3\u5659\u566B\u5679\u5669\u5664\u5678\u566A\u5668\u5665\u5671\u566F\u566C\u5662\u5676\u58C1\u58BE\u58C7\u58C5\u596E\u5B1D\u5B34\u5B78\u5BF0\u5C0E\u5F4A\u61B2\u6191\u61A9\u618A\u61CD\u61B6\u61BE\u61CA\u61C8\u6230\u64C5\u64C1\u64CB\u64BB\u64BC\u64DA\u64C4\u64C7\u64C2\u64CD\u64BF\u64D2\u64D4\u64BE\u6574\u66C6\u66C9\u66B9\u66C4\u66C7\u66B8\u6A3D\u6A38\u6A3A\u6A59\u6A6B\u6A58\u6A39\u6A44\u6A62\u6A61\u6A4B\u6A47\u6A35\u6A5F\u6A48\u6B59\u6B77\u6C05\u6FC2\u6FB1\u6FA1"],
      ["bf40", "\u6FC3\u6FA4\u6FC1\u6FA7\u6FB3\u6FC0\u6FB9\u6FB6\u6FA6\u6FA0\u6FB4\u71BE\u71C9\u71D0\u71D2\u71C8\u71D5\u71B9\u71CE\u71D9\u71DC\u71C3\u71C4\u7368\u749C\u74A3\u7498\u749F\u749E\u74E2\u750C\u750D\u7634\u7638\u763A\u76E7\u76E5\u77A0\u779E\u779F\u77A5\u78E8\u78DA\u78EC\u78E7\u79A6\u7A4D\u7A4E\u7A46\u7A4C\u7A4B\u7ABA\u7BD9\u7C11\u7BC9\u7BE4\u7BDB\u7BE1\u7BE9\u7BE6\u7CD5\u7CD6\u7E0A"],
      ["bfa1", "\u7E11\u7E08\u7E1B\u7E23\u7E1E\u7E1D\u7E09\u7E10\u7F79\u7FB2\u7FF0\u7FF1\u7FEE\u8028\u81B3\u81A9\u81A8\u81FB\u8208\u8258\u8259\u854A\u8559\u8548\u8568\u8569\u8543\u8549\u856D\u856A\u855E\u8783\u879F\u879E\u87A2\u878D\u8861\u892A\u8932\u8925\u892B\u8921\u89AA\u89A6\u8AE6\u8AFA\u8AEB\u8AF1\u8B00\u8ADC\u8AE7\u8AEE\u8AFE\u8B01\u8B02\u8AF7\u8AED\u8AF3\u8AF6\u8AFC\u8C6B\u8C6D\u8C93\u8CF4\u8E44\u8E31\u8E34\u8E42\u8E39\u8E35\u8F3B\u8F2F\u8F38\u8F33\u8FA8\u8FA6\u9075\u9074\u9078\u9072\u907C\u907A\u9134\u9192\u9320\u9336\u92F8\u9333\u932F\u9322\u92FC\u932B\u9304\u931A"],
      ["c040", "\u9310\u9326\u9321\u9315\u932E\u9319\u95BB\u96A7\u96A8\u96AA\u96D5\u970E\u9711\u9716\u970D\u9713\u970F\u975B\u975C\u9766\u9798\u9830\u9838\u983B\u9837\u982D\u9839\u9824\u9910\u9928\u991E\u991B\u9921\u991A\u99ED\u99E2\u99F1\u9AB8\u9ABC\u9AFB\u9AED\u9B28\u9B91\u9D15\u9D23\u9D26\u9D28\u9D12\u9D1B\u9ED8\u9ED4\u9F8D\u9F9C\u512A\u511F\u5121\u5132\u52F5\u568E\u5680\u5690\u5685\u5687"],
      ["c0a1", "\u568F\u58D5\u58D3\u58D1\u58CE\u5B30\u5B2A\u5B24\u5B7A\u5C37\u5C68\u5DBC\u5DBA\u5DBD\u5DB8\u5E6B\u5F4C\u5FBD\u61C9\u61C2\u61C7\u61E6\u61CB\u6232\u6234\u64CE\u64CA\u64D8\u64E0\u64F0\u64E6\u64EC\u64F1\u64E2\u64ED\u6582\u6583\u66D9\u66D6\u6A80\u6A94\u6A84\u6AA2\u6A9C\u6ADB\u6AA3\u6A7E\u6A97\u6A90\u6AA0\u6B5C\u6BAE\u6BDA\u6C08\u6FD8\u6FF1\u6FDF\u6FE0\u6FDB\u6FE4\u6FEB\u6FEF\u6F80\u6FEC\u6FE1\u6FE9\u6FD5\u6FEE\u6FF0\u71E7\u71DF\u71EE\u71E6\u71E5\u71ED\u71EC\u71F4\u71E0\u7235\u7246\u7370\u7372\u74A9\u74B0\u74A6\u74A8\u7646\u7642\u764C\u76EA\u77B3\u77AA\u77B0\u77AC"],
      ["c140", "\u77A7\u77AD\u77EF\u78F7\u78FA\u78F4\u78EF\u7901\u79A7\u79AA\u7A57\u7ABF\u7C07\u7C0D\u7BFE\u7BF7\u7C0C\u7BE0\u7CE0\u7CDC\u7CDE\u7CE2\u7CDF\u7CD9\u7CDD\u7E2E\u7E3E\u7E46\u7E37\u7E32\u7E43\u7E2B\u7E3D\u7E31\u7E45\u7E41\u7E34\u7E39\u7E48\u7E35\u7E3F\u7E2F\u7F44\u7FF3\u7FFC\u8071\u8072\u8070\u806F\u8073\u81C6\u81C3\u81BA\u81C2\u81C0\u81BF\u81BD\u81C9\u81BE\u81E8\u8209\u8271\u85AA"],
      ["c1a1", "\u8584\u857E\u859C\u8591\u8594\u85AF\u859B\u8587\u85A8\u858A\u8667\u87C0\u87D1\u87B3\u87D2\u87C6\u87AB\u87BB\u87BA\u87C8\u87CB\u893B\u8936\u8944\u8938\u893D\u89AC\u8B0E\u8B17\u8B19\u8B1B\u8B0A\u8B20\u8B1D\u8B04\u8B10\u8C41\u8C3F\u8C73\u8CFA\u8CFD\u8CFC\u8CF8\u8CFB\u8DA8\u8E49\u8E4B\u8E48\u8E4A\u8F44\u8F3E\u8F42\u8F45\u8F3F\u907F\u907D\u9084\u9081\u9082\u9080\u9139\u91A3\u919E\u919C\u934D\u9382\u9328\u9375\u934A\u9365\u934B\u9318\u937E\u936C\u935B\u9370\u935A\u9354\u95CA\u95CB\u95CC\u95C8\u95C6\u96B1\u96B8\u96D6\u971C\u971E\u97A0\u97D3\u9846\u98B6\u9935\u9A01"],
      ["c240", "\u99FF\u9BAE\u9BAB\u9BAA\u9BAD\u9D3B\u9D3F\u9E8B\u9ECF\u9EDE\u9EDC\u9EDD\u9EDB\u9F3E\u9F4B\u53E2\u5695\u56AE\u58D9\u58D8\u5B38\u5F5D\u61E3\u6233\u64F4\u64F2\u64FE\u6506\u64FA\u64FB\u64F7\u65B7\u66DC\u6726\u6AB3\u6AAC\u6AC3\u6ABB\u6AB8\u6AC2\u6AAE\u6AAF\u6B5F\u6B78\u6BAF\u7009\u700B\u6FFE\u7006\u6FFA\u7011\u700F\u71FB\u71FC\u71FE\u71F8\u7377\u7375\u74A7\u74BF\u7515\u7656\u7658"],
      ["c2a1", "\u7652\u77BD\u77BF\u77BB\u77BC\u790E\u79AE\u7A61\u7A62\u7A60\u7AC4\u7AC5\u7C2B\u7C27\u7C2A\u7C1E\u7C23\u7C21\u7CE7\u7E54\u7E55\u7E5E\u7E5A\u7E61\u7E52\u7E59\u7F48\u7FF9\u7FFB\u8077\u8076\u81CD\u81CF\u820A\u85CF\u85A9\u85CD\u85D0\u85C9\u85B0\u85BA\u85B9\u85A6\u87EF\u87EC\u87F2\u87E0\u8986\u89B2\u89F4\u8B28\u8B39\u8B2C\u8B2B\u8C50\u8D05\u8E59\u8E63\u8E66\u8E64\u8E5F\u8E55\u8EC0\u8F49\u8F4D\u9087\u9083\u9088\u91AB\u91AC\u91D0\u9394\u938A\u9396\u93A2\u93B3\u93AE\u93AC\u93B0\u9398\u939A\u9397\u95D4\u95D6\u95D0\u95D5\u96E2\u96DC\u96D9\u96DB\u96DE\u9724\u97A3\u97A6"],
      ["c340", "\u97AD\u97F9\u984D\u984F\u984C\u984E\u9853\u98BA\u993E\u993F\u993D\u992E\u99A5\u9A0E\u9AC1\u9B03\u9B06\u9B4F\u9B4E\u9B4D\u9BCA\u9BC9\u9BFD\u9BC8\u9BC0\u9D51\u9D5D\u9D60\u9EE0\u9F15\u9F2C\u5133\u56A5\u58DE\u58DF\u58E2\u5BF5\u9F90\u5EEC\u61F2\u61F7\u61F6\u61F5\u6500\u650F\u66E0\u66DD\u6AE5\u6ADD\u6ADA\u6AD3\u701B\u701F\u7028\u701A\u701D\u7015\u7018\u7206\u720D\u7258\u72A2\u7378"],
      ["c3a1", "\u737A\u74BD\u74CA\u74E3\u7587\u7586\u765F\u7661\u77C7\u7919\u79B1\u7A6B\u7A69\u7C3E\u7C3F\u7C38\u7C3D\u7C37\u7C40\u7E6B\u7E6D\u7E79\u7E69\u7E6A\u7F85\u7E73\u7FB6\u7FB9\u7FB8\u81D8\u85E9\u85DD\u85EA\u85D5\u85E4\u85E5\u85F7\u87FB\u8805\u880D\u87F9\u87FE\u8960\u895F\u8956\u895E\u8B41\u8B5C\u8B58\u8B49\u8B5A\u8B4E\u8B4F\u8B46\u8B59\u8D08\u8D0A\u8E7C\u8E72\u8E87\u8E76\u8E6C\u8E7A\u8E74\u8F54\u8F4E\u8FAD\u908A\u908B\u91B1\u91AE\u93E1\u93D1\u93DF\u93C3\u93C8\u93DC\u93DD\u93D6\u93E2\u93CD\u93D8\u93E4\u93D7\u93E8\u95DC\u96B4\u96E3\u972A\u9727\u9761\u97DC\u97FB\u985E"],
      ["c440", "\u9858\u985B\u98BC\u9945\u9949\u9A16\u9A19\u9B0D\u9BE8\u9BE7\u9BD6\u9BDB\u9D89\u9D61\u9D72\u9D6A\u9D6C\u9E92\u9E97\u9E93\u9EB4\u52F8\u56A8\u56B7\u56B6\u56B4\u56BC\u58E4\u5B40\u5B43\u5B7D\u5BF6\u5DC9\u61F8\u61FA\u6518\u6514\u6519\u66E6\u6727\u6AEC\u703E\u7030\u7032\u7210\u737B\u74CF\u7662\u7665\u7926\u792A\u792C\u792B\u7AC7\u7AF6\u7C4C\u7C43\u7C4D\u7CEF\u7CF0\u8FAE\u7E7D\u7E7C"],
      ["c4a1", "\u7E82\u7F4C\u8000\u81DA\u8266\u85FB\u85F9\u8611\u85FA\u8606\u860B\u8607\u860A\u8814\u8815\u8964\u89BA\u89F8\u8B70\u8B6C\u8B66\u8B6F\u8B5F\u8B6B\u8D0F\u8D0D\u8E89\u8E81\u8E85\u8E82\u91B4\u91CB\u9418\u9403\u93FD\u95E1\u9730\u98C4\u9952\u9951\u99A8\u9A2B\u9A30\u9A37\u9A35\u9C13\u9C0D\u9E79\u9EB5\u9EE8\u9F2F\u9F5F\u9F63\u9F61\u5137\u5138\u56C1\u56C0\u56C2\u5914\u5C6C\u5DCD\u61FC\u61FE\u651D\u651C\u6595\u66E9\u6AFB\u6B04\u6AFA\u6BB2\u704C\u721B\u72A7\u74D6\u74D4\u7669\u77D3\u7C50\u7E8F\u7E8C\u7FBC\u8617\u862D\u861A\u8823\u8822\u8821\u881F\u896A\u896C\u89BD\u8B74"],
      ["c540", "\u8B77\u8B7D\u8D13\u8E8A\u8E8D\u8E8B\u8F5F\u8FAF\u91BA\u942E\u9433\u9435\u943A\u9438\u9432\u942B\u95E2\u9738\u9739\u9732\u97FF\u9867\u9865\u9957\u9A45\u9A43\u9A40\u9A3E\u9ACF\u9B54\u9B51\u9C2D\u9C25\u9DAF\u9DB4\u9DC2\u9DB8\u9E9D\u9EEF\u9F19\u9F5C\u9F66\u9F67\u513C\u513B\u56C8\u56CA\u56C9\u5B7F\u5DD4\u5DD2\u5F4E\u61FF\u6524\u6B0A\u6B61\u7051\u7058\u7380\u74E4\u758A\u766E\u766C"],
      ["c5a1", "\u79B3\u7C60\u7C5F\u807E\u807D\u81DF\u8972\u896F\u89FC\u8B80\u8D16\u8D17\u8E91\u8E93\u8F61\u9148\u9444\u9451\u9452\u973D\u973E\u97C3\u97C1\u986B\u9955\u9A55\u9A4D\u9AD2\u9B1A\u9C49\u9C31\u9C3E\u9C3B\u9DD3\u9DD7\u9F34\u9F6C\u9F6A\u9F94\u56CC\u5DD6\u6200\u6523\u652B\u652A\u66EC\u6B10\u74DA\u7ACA\u7C64\u7C63\u7C65\u7E93\u7E96\u7E94\u81E2\u8638\u863F\u8831\u8B8A\u9090\u908F\u9463\u9460\u9464\u9768\u986F\u995C\u9A5A\u9A5B\u9A57\u9AD3\u9AD4\u9AD1\u9C54\u9C57\u9C56\u9DE5\u9E9F\u9EF4\u56D1\u58E9\u652C\u705E\u7671\u7672\u77D7\u7F50\u7F88\u8836\u8839\u8862\u8B93\u8B92"],
      ["c640", "\u8B96\u8277\u8D1B\u91C0\u946A\u9742\u9748\u9744\u97C6\u9870\u9A5F\u9B22\u9B58\u9C5F\u9DF9\u9DFA\u9E7C\u9E7D\u9F07\u9F77\u9F72\u5EF3\u6B16\u7063\u7C6C\u7C6E\u883B\u89C0\u8EA1\u91C1\u9472\u9470\u9871\u995E\u9AD6\u9B23\u9ECC\u7064\u77DA\u8B9A\u9477\u97C9\u9A62\u9A65\u7E9C\u8B9C\u8EAA\u91C5\u947D\u947E\u947C\u9C77\u9C78\u9EF7\u8C54\u947F\u9E1A\u7228\u9A6A\u9B31\u9E1B\u9E1E\u7C72"],
      ["c940", "\u4E42\u4E5C\u51F5\u531A\u5382\u4E07\u4E0C\u4E47\u4E8D\u56D7\uFA0C\u5C6E\u5F73\u4E0F\u5187\u4E0E\u4E2E\u4E93\u4EC2\u4EC9\u4EC8\u5198\u52FC\u536C\u53B9\u5720\u5903\u592C\u5C10\u5DFF\u65E1\u6BB3\u6BCC\u6C14\u723F\u4E31\u4E3C\u4EE8\u4EDC\u4EE9\u4EE1\u4EDD\u4EDA\u520C\u531C\u534C\u5722\u5723\u5917\u592F\u5B81\u5B84\u5C12\u5C3B\u5C74\u5C73\u5E04\u5E80\u5E82\u5FC9\u6209\u6250\u6C15"],
      ["c9a1", "\u6C36\u6C43\u6C3F\u6C3B\u72AE\u72B0\u738A\u79B8\u808A\u961E\u4F0E\u4F18\u4F2C\u4EF5\u4F14\u4EF1\u4F00\u4EF7\u4F08\u4F1D\u4F02\u4F05\u4F22\u4F13\u4F04\u4EF4\u4F12\u51B1\u5213\u5209\u5210\u52A6\u5322\u531F\u534D\u538A\u5407\u56E1\u56DF\u572E\u572A\u5734\u593C\u5980\u597C\u5985\u597B\u597E\u5977\u597F\u5B56\u5C15\u5C25\u5C7C\u5C7A\u5C7B\u5C7E\u5DDF\u5E75\u5E84\u5F02\u5F1A\u5F74\u5FD5\u5FD4\u5FCF\u625C\u625E\u6264\u6261\u6266\u6262\u6259\u6260\u625A\u6265\u65EF\u65EE\u673E\u6739\u6738\u673B\u673A\u673F\u673C\u6733\u6C18\u6C46\u6C52\u6C5C\u6C4F\u6C4A\u6C54\u6C4B"],
      ["ca40", "\u6C4C\u7071\u725E\u72B4\u72B5\u738E\u752A\u767F\u7A75\u7F51\u8278\u827C\u8280\u827D\u827F\u864D\u897E\u9099\u9097\u9098\u909B\u9094\u9622\u9624\u9620\u9623\u4F56\u4F3B\u4F62\u4F49\u4F53\u4F64\u4F3E\u4F67\u4F52\u4F5F\u4F41\u4F58\u4F2D\u4F33\u4F3F\u4F61\u518F\u51B9\u521C\u521E\u5221\u52AD\u52AE\u5309\u5363\u5372\u538E\u538F\u5430\u5437\u542A\u5454\u5445\u5419\u541C\u5425\u5418"],
      ["caa1", "\u543D\u544F\u5441\u5428\u5424\u5447\u56EE\u56E7\u56E5\u5741\u5745\u574C\u5749\u574B\u5752\u5906\u5940\u59A6\u5998\u59A0\u5997\u598E\u59A2\u5990\u598F\u59A7\u59A1\u5B8E\u5B92\u5C28\u5C2A\u5C8D\u5C8F\u5C88\u5C8B\u5C89\u5C92\u5C8A\u5C86\u5C93\u5C95\u5DE0\u5E0A\u5E0E\u5E8B\u5E89\u5E8C\u5E88\u5E8D\u5F05\u5F1D\u5F78\u5F76\u5FD2\u5FD1\u5FD0\u5FED\u5FE8\u5FEE\u5FF3\u5FE1\u5FE4\u5FE3\u5FFA\u5FEF\u5FF7\u5FFB\u6000\u5FF4\u623A\u6283\u628C\u628E\u628F\u6294\u6287\u6271\u627B\u627A\u6270\u6281\u6288\u6277\u627D\u6272\u6274\u6537\u65F0\u65F4\u65F3\u65F2\u65F5\u6745\u6747"],
      ["cb40", "\u6759\u6755\u674C\u6748\u675D\u674D\u675A\u674B\u6BD0\u6C19\u6C1A\u6C78\u6C67\u6C6B\u6C84\u6C8B\u6C8F\u6C71\u6C6F\u6C69\u6C9A\u6C6D\u6C87\u6C95\u6C9C\u6C66\u6C73\u6C65\u6C7B\u6C8E\u7074\u707A\u7263\u72BF\u72BD\u72C3\u72C6\u72C1\u72BA\u72C5\u7395\u7397\u7393\u7394\u7392\u753A\u7539\u7594\u7595\u7681\u793D\u8034\u8095\u8099\u8090\u8092\u809C\u8290\u828F\u8285\u828E\u8291\u8293"],
      ["cba1", "\u828A\u8283\u8284\u8C78\u8FC9\u8FBF\u909F\u90A1\u90A5\u909E\u90A7\u90A0\u9630\u9628\u962F\u962D\u4E33\u4F98\u4F7C\u4F85\u4F7D\u4F80\u4F87\u4F76\u4F74\u4F89\u4F84\u4F77\u4F4C\u4F97\u4F6A\u4F9A\u4F79\u4F81\u4F78\u4F90\u4F9C\u4F94\u4F9E\u4F92\u4F82\u4F95\u4F6B\u4F6E\u519E\u51BC\u51BE\u5235\u5232\u5233\u5246\u5231\u52BC\u530A\u530B\u533C\u5392\u5394\u5487\u547F\u5481\u5491\u5482\u5488\u546B\u547A\u547E\u5465\u546C\u5474\u5466\u548D\u546F\u5461\u5460\u5498\u5463\u5467\u5464\u56F7\u56F9\u576F\u5772\u576D\u576B\u5771\u5770\u5776\u5780\u5775\u577B\u5773\u5774\u5762"],
      ["cc40", "\u5768\u577D\u590C\u5945\u59B5\u59BA\u59CF\u59CE\u59B2\u59CC\u59C1\u59B6\u59BC\u59C3\u59D6\u59B1\u59BD\u59C0\u59C8\u59B4\u59C7\u5B62\u5B65\u5B93\u5B95\u5C44\u5C47\u5CAE\u5CA4\u5CA0\u5CB5\u5CAF\u5CA8\u5CAC\u5C9F\u5CA3\u5CAD\u5CA2\u5CAA\u5CA7\u5C9D\u5CA5\u5CB6\u5CB0\u5CA6\u5E17\u5E14\u5E19\u5F28\u5F22\u5F23\u5F24\u5F54\u5F82\u5F7E\u5F7D\u5FDE\u5FE5\u602D\u6026\u6019\u6032\u600B"],
      ["cca1", "\u6034\u600A\u6017\u6033\u601A\u601E\u602C\u6022\u600D\u6010\u602E\u6013\u6011\u600C\u6009\u601C\u6214\u623D\u62AD\u62B4\u62D1\u62BE\u62AA\u62B6\u62CA\u62AE\u62B3\u62AF\u62BB\u62A9\u62B0\u62B8\u653D\u65A8\u65BB\u6609\u65FC\u6604\u6612\u6608\u65FB\u6603\u660B\u660D\u6605\u65FD\u6611\u6610\u66F6\u670A\u6785\u676C\u678E\u6792\u6776\u677B\u6798\u6786\u6784\u6774\u678D\u678C\u677A\u679F\u6791\u6799\u6783\u677D\u6781\u6778\u6779\u6794\u6B25\u6B80\u6B7E\u6BDE\u6C1D\u6C93\u6CEC\u6CEB\u6CEE\u6CD9\u6CB6\u6CD4\u6CAD\u6CE7\u6CB7\u6CD0\u6CC2\u6CBA\u6CC3\u6CC6\u6CED\u6CF2"],
      ["cd40", "\u6CD2\u6CDD\u6CB4\u6C8A\u6C9D\u6C80\u6CDE\u6CC0\u6D30\u6CCD\u6CC7\u6CB0\u6CF9\u6CCF\u6CE9\u6CD1\u7094\u7098\u7085\u7093\u7086\u7084\u7091\u7096\u7082\u709A\u7083\u726A\u72D6\u72CB\u72D8\u72C9\u72DC\u72D2\u72D4\u72DA\u72CC\u72D1\u73A4\u73A1\u73AD\u73A6\u73A2\u73A0\u73AC\u739D\u74DD\u74E8\u753F\u7540\u753E\u758C\u7598\u76AF\u76F3\u76F1\u76F0\u76F5\u77F8\u77FC\u77F9\u77FB\u77FA"],
      ["cda1", "\u77F7\u7942\u793F\u79C5\u7A78\u7A7B\u7AFB\u7C75\u7CFD\u8035\u808F\u80AE\u80A3\u80B8\u80B5\u80AD\u8220\u82A0\u82C0\u82AB\u829A\u8298\u829B\u82B5\u82A7\u82AE\u82BC\u829E\u82BA\u82B4\u82A8\u82A1\u82A9\u82C2\u82A4\u82C3\u82B6\u82A2\u8670\u866F\u866D\u866E\u8C56\u8FD2\u8FCB\u8FD3\u8FCD\u8FD6\u8FD5\u8FD7\u90B2\u90B4\u90AF\u90B3\u90B0\u9639\u963D\u963C\u963A\u9643\u4FCD\u4FC5\u4FD3\u4FB2\u4FC9\u4FCB\u4FC1\u4FD4\u4FDC\u4FD9\u4FBB\u4FB3\u4FDB\u4FC7\u4FD6\u4FBA\u4FC0\u4FB9\u4FEC\u5244\u5249\u52C0\u52C2\u533D\u537C\u5397\u5396\u5399\u5398\u54BA\u54A1\u54AD\u54A5\u54CF"],
      ["ce40", "\u54C3\u830D\u54B7\u54AE\u54D6\u54B6\u54C5\u54C6\u54A0\u5470\u54BC\u54A2\u54BE\u5472\u54DE\u54B0\u57B5\u579E\u579F\u57A4\u578C\u5797\u579D\u579B\u5794\u5798\u578F\u5799\u57A5\u579A\u5795\u58F4\u590D\u5953\u59E1\u59DE\u59EE\u5A00\u59F1\u59DD\u59FA\u59FD\u59FC\u59F6\u59E4\u59F2\u59F7\u59DB\u59E9\u59F3\u59F5\u59E0\u59FE\u59F4\u59ED\u5BA8\u5C4C\u5CD0\u5CD8\u5CCC\u5CD7\u5CCB\u5CDB"],
      ["cea1", "\u5CDE\u5CDA\u5CC9\u5CC7\u5CCA\u5CD6\u5CD3\u5CD4\u5CCF\u5CC8\u5CC6\u5CCE\u5CDF\u5CF8\u5DF9\u5E21\u5E22\u5E23\u5E20\u5E24\u5EB0\u5EA4\u5EA2\u5E9B\u5EA3\u5EA5\u5F07\u5F2E\u5F56\u5F86\u6037\u6039\u6054\u6072\u605E\u6045\u6053\u6047\u6049\u605B\u604C\u6040\u6042\u605F\u6024\u6044\u6058\u6066\u606E\u6242\u6243\u62CF\u630D\u630B\u62F5\u630E\u6303\u62EB\u62F9\u630F\u630C\u62F8\u62F6\u6300\u6313\u6314\u62FA\u6315\u62FB\u62F0\u6541\u6543\u65AA\u65BF\u6636\u6621\u6632\u6635\u661C\u6626\u6622\u6633\u662B\u663A\u661D\u6634\u6639\u662E\u670F\u6710\u67C1\u67F2\u67C8\u67BA"],
      ["cf40", "\u67DC\u67BB\u67F8\u67D8\u67C0\u67B7\u67C5\u67EB\u67E4\u67DF\u67B5\u67CD\u67B3\u67F7\u67F6\u67EE\u67E3\u67C2\u67B9\u67CE\u67E7\u67F0\u67B2\u67FC\u67C6\u67ED\u67CC\u67AE\u67E6\u67DB\u67FA\u67C9\u67CA\u67C3\u67EA\u67CB\u6B28\u6B82\u6B84\u6BB6\u6BD6\u6BD8\u6BE0\u6C20\u6C21\u6D28\u6D34\u6D2D\u6D1F\u6D3C\u6D3F\u6D12\u6D0A\u6CDA\u6D33\u6D04\u6D19\u6D3A\u6D1A\u6D11\u6D00\u6D1D\u6D42"],
      ["cfa1", "\u6D01\u6D18\u6D37\u6D03\u6D0F\u6D40\u6D07\u6D20\u6D2C\u6D08\u6D22\u6D09\u6D10\u70B7\u709F\u70BE\u70B1\u70B0\u70A1\u70B4\u70B5\u70A9\u7241\u7249\u724A\u726C\u7270\u7273\u726E\u72CA\u72E4\u72E8\u72EB\u72DF\u72EA\u72E6\u72E3\u7385\u73CC\u73C2\u73C8\u73C5\u73B9\u73B6\u73B5\u73B4\u73EB\u73BF\u73C7\u73BE\u73C3\u73C6\u73B8\u73CB\u74EC\u74EE\u752E\u7547\u7548\u75A7\u75AA\u7679\u76C4\u7708\u7703\u7704\u7705\u770A\u76F7\u76FB\u76FA\u77E7\u77E8\u7806\u7811\u7812\u7805\u7810\u780F\u780E\u7809\u7803\u7813\u794A\u794C\u794B\u7945\u7944\u79D5\u79CD\u79CF\u79D6\u79CE\u7A80"],
      ["d040", "\u7A7E\u7AD1\u7B00\u7B01\u7C7A\u7C78\u7C79\u7C7F\u7C80\u7C81\u7D03\u7D08\u7D01\u7F58\u7F91\u7F8D\u7FBE\u8007\u800E\u800F\u8014\u8037\u80D8\u80C7\u80E0\u80D1\u80C8\u80C2\u80D0\u80C5\u80E3\u80D9\u80DC\u80CA\u80D5\u80C9\u80CF\u80D7\u80E6\u80CD\u81FF\u8221\u8294\u82D9\u82FE\u82F9\u8307\u82E8\u8300\u82D5\u833A\u82EB\u82D6\u82F4\u82EC\u82E1\u82F2\u82F5\u830C\u82FB\u82F6\u82F0\u82EA"],
      ["d0a1", "\u82E4\u82E0\u82FA\u82F3\u82ED\u8677\u8674\u867C\u8673\u8841\u884E\u8867\u886A\u8869\u89D3\u8A04\u8A07\u8D72\u8FE3\u8FE1\u8FEE\u8FE0\u90F1\u90BD\u90BF\u90D5\u90C5\u90BE\u90C7\u90CB\u90C8\u91D4\u91D3\u9654\u964F\u9651\u9653\u964A\u964E\u501E\u5005\u5007\u5013\u5022\u5030\u501B\u4FF5\u4FF4\u5033\u5037\u502C\u4FF6\u4FF7\u5017\u501C\u5020\u5027\u5035\u502F\u5031\u500E\u515A\u5194\u5193\u51CA\u51C4\u51C5\u51C8\u51CE\u5261\u525A\u5252\u525E\u525F\u5255\u5262\u52CD\u530E\u539E\u5526\u54E2\u5517\u5512\u54E7\u54F3\u54E4\u551A\u54FF\u5504\u5508\u54EB\u5511\u5505\u54F1"],
      ["d140", "\u550A\u54FB\u54F7\u54F8\u54E0\u550E\u5503\u550B\u5701\u5702\u57CC\u5832\u57D5\u57D2\u57BA\u57C6\u57BD\u57BC\u57B8\u57B6\u57BF\u57C7\u57D0\u57B9\u57C1\u590E\u594A\u5A19\u5A16\u5A2D\u5A2E\u5A15\u5A0F\u5A17\u5A0A\u5A1E\u5A33\u5B6C\u5BA7\u5BAD\u5BAC\u5C03\u5C56\u5C54\u5CEC\u5CFF\u5CEE\u5CF1\u5CF7\u5D00\u5CF9\u5E29\u5E28\u5EA8\u5EAE\u5EAA\u5EAC\u5F33\u5F30\u5F67\u605D\u605A\u6067"],
      ["d1a1", "\u6041\u60A2\u6088\u6080\u6092\u6081\u609D\u6083\u6095\u609B\u6097\u6087\u609C\u608E\u6219\u6246\u62F2\u6310\u6356\u632C\u6344\u6345\u6336\u6343\u63E4\u6339\u634B\u634A\u633C\u6329\u6341\u6334\u6358\u6354\u6359\u632D\u6347\u6333\u635A\u6351\u6338\u6357\u6340\u6348\u654A\u6546\u65C6\u65C3\u65C4\u65C2\u664A\u665F\u6647\u6651\u6712\u6713\u681F\u681A\u6849\u6832\u6833\u683B\u684B\u684F\u6816\u6831\u681C\u6835\u682B\u682D\u682F\u684E\u6844\u6834\u681D\u6812\u6814\u6826\u6828\u682E\u684D\u683A\u6825\u6820\u6B2C\u6B2F\u6B2D\u6B31\u6B34\u6B6D\u8082\u6B88\u6BE6\u6BE4"],
      ["d240", "\u6BE8\u6BE3\u6BE2\u6BE7\u6C25\u6D7A\u6D63\u6D64\u6D76\u6D0D\u6D61\u6D92\u6D58\u6D62\u6D6D\u6D6F\u6D91\u6D8D\u6DEF\u6D7F\u6D86\u6D5E\u6D67\u6D60\u6D97\u6D70\u6D7C\u6D5F\u6D82\u6D98\u6D2F\u6D68\u6D8B\u6D7E\u6D80\u6D84\u6D16\u6D83\u6D7B\u6D7D\u6D75\u6D90\u70DC\u70D3\u70D1\u70DD\u70CB\u7F39\u70E2\u70D7\u70D2\u70DE\u70E0\u70D4\u70CD\u70C5\u70C6\u70C7\u70DA\u70CE\u70E1\u7242\u7278"],
      ["d2a1", "\u7277\u7276\u7300\u72FA\u72F4\u72FE\u72F6\u72F3\u72FB\u7301\u73D3\u73D9\u73E5\u73D6\u73BC\u73E7\u73E3\u73E9\u73DC\u73D2\u73DB\u73D4\u73DD\u73DA\u73D7\u73D8\u73E8\u74DE\u74DF\u74F4\u74F5\u7521\u755B\u755F\u75B0\u75C1\u75BB\u75C4\u75C0\u75BF\u75B6\u75BA\u768A\u76C9\u771D\u771B\u7710\u7713\u7712\u7723\u7711\u7715\u7719\u771A\u7722\u7727\u7823\u782C\u7822\u7835\u782F\u7828\u782E\u782B\u7821\u7829\u7833\u782A\u7831\u7954\u795B\u794F\u795C\u7953\u7952\u7951\u79EB\u79EC\u79E0\u79EE\u79ED\u79EA\u79DC\u79DE\u79DD\u7A86\u7A89\u7A85\u7A8B\u7A8C\u7A8A\u7A87\u7AD8\u7B10"],
      ["d340", "\u7B04\u7B13\u7B05\u7B0F\u7B08\u7B0A\u7B0E\u7B09\u7B12\u7C84\u7C91\u7C8A\u7C8C\u7C88\u7C8D\u7C85\u7D1E\u7D1D\u7D11\u7D0E\u7D18\u7D16\u7D13\u7D1F\u7D12\u7D0F\u7D0C\u7F5C\u7F61\u7F5E\u7F60\u7F5D\u7F5B\u7F96\u7F92\u7FC3\u7FC2\u7FC0\u8016\u803E\u8039\u80FA\u80F2\u80F9\u80F5\u8101\u80FB\u8100\u8201\u822F\u8225\u8333\u832D\u8344\u8319\u8351\u8325\u8356\u833F\u8341\u8326\u831C\u8322"],
      ["d3a1", "\u8342\u834E\u831B\u832A\u8308\u833C\u834D\u8316\u8324\u8320\u8337\u832F\u8329\u8347\u8345\u834C\u8353\u831E\u832C\u834B\u8327\u8348\u8653\u8652\u86A2\u86A8\u8696\u868D\u8691\u869E\u8687\u8697\u8686\u868B\u869A\u8685\u86A5\u8699\u86A1\u86A7\u8695\u8698\u868E\u869D\u8690\u8694\u8843\u8844\u886D\u8875\u8876\u8872\u8880\u8871\u887F\u886F\u8883\u887E\u8874\u887C\u8A12\u8C47\u8C57\u8C7B\u8CA4\u8CA3\u8D76\u8D78\u8DB5\u8DB7\u8DB6\u8ED1\u8ED3\u8FFE\u8FF5\u9002\u8FFF\u8FFB\u9004\u8FFC\u8FF6\u90D6\u90E0\u90D9\u90DA\u90E3\u90DF\u90E5\u90D8\u90DB\u90D7\u90DC\u90E4\u9150"],
      ["d440", "\u914E\u914F\u91D5\u91E2\u91DA\u965C\u965F\u96BC\u98E3\u9ADF\u9B2F\u4E7F\u5070\u506A\u5061\u505E\u5060\u5053\u504B\u505D\u5072\u5048\u504D\u5041\u505B\u504A\u5062\u5015\u5045\u505F\u5069\u506B\u5063\u5064\u5046\u5040\u506E\u5073\u5057\u5051\u51D0\u526B\u526D\u526C\u526E\u52D6\u52D3\u532D\u539C\u5575\u5576\u553C\u554D\u5550\u5534\u552A\u5551\u5562\u5536\u5535\u5530\u5552\u5545"],
      ["d4a1", "\u550C\u5532\u5565\u554E\u5539\u5548\u552D\u553B\u5540\u554B\u570A\u5707\u57FB\u5814\u57E2\u57F6\u57DC\u57F4\u5800\u57ED\u57FD\u5808\u57F8\u580B\u57F3\u57CF\u5807\u57EE\u57E3\u57F2\u57E5\u57EC\u57E1\u580E\u57FC\u5810\u57E7\u5801\u580C\u57F1\u57E9\u57F0\u580D\u5804\u595C\u5A60\u5A58\u5A55\u5A67\u5A5E\u5A38\u5A35\u5A6D\u5A50\u5A5F\u5A65\u5A6C\u5A53\u5A64\u5A57\u5A43\u5A5D\u5A52\u5A44\u5A5B\u5A48\u5A8E\u5A3E\u5A4D\u5A39\u5A4C\u5A70\u5A69\u5A47\u5A51\u5A56\u5A42\u5A5C\u5B72\u5B6E\u5BC1\u5BC0\u5C59\u5D1E\u5D0B\u5D1D\u5D1A\u5D20\u5D0C\u5D28\u5D0D\u5D26\u5D25\u5D0F"],
      ["d540", "\u5D30\u5D12\u5D23\u5D1F\u5D2E\u5E3E\u5E34\u5EB1\u5EB4\u5EB9\u5EB2\u5EB3\u5F36\u5F38\u5F9B\u5F96\u5F9F\u608A\u6090\u6086\u60BE\u60B0\u60BA\u60D3\u60D4\u60CF\u60E4\u60D9\u60DD\u60C8\u60B1\u60DB\u60B7\u60CA\u60BF\u60C3\u60CD\u60C0\u6332\u6365\u638A\u6382\u637D\u63BD\u639E\u63AD\u639D\u6397\u63AB\u638E\u636F\u6387\u6390\u636E\u63AF\u6375\u639C\u636D\u63AE\u637C\u63A4\u633B\u639F"],
      ["d5a1", "\u6378\u6385\u6381\u6391\u638D\u6370\u6553\u65CD\u6665\u6661\u665B\u6659\u665C\u6662\u6718\u6879\u6887\u6890\u689C\u686D\u686E\u68AE\u68AB\u6956\u686F\u68A3\u68AC\u68A9\u6875\u6874\u68B2\u688F\u6877\u6892\u687C\u686B\u6872\u68AA\u6880\u6871\u687E\u689B\u6896\u688B\u68A0\u6889\u68A4\u6878\u687B\u6891\u688C\u688A\u687D\u6B36\u6B33\u6B37\u6B38\u6B91\u6B8F\u6B8D\u6B8E\u6B8C\u6C2A\u6DC0\u6DAB\u6DB4\u6DB3\u6E74\u6DAC\u6DE9\u6DE2\u6DB7\u6DF6\u6DD4\u6E00\u6DC8\u6DE0\u6DDF\u6DD6\u6DBE\u6DE5\u6DDC\u6DDD\u6DDB\u6DF4\u6DCA\u6DBD\u6DED\u6DF0\u6DBA\u6DD5\u6DC2\u6DCF\u6DC9"],
      ["d640", "\u6DD0\u6DF2\u6DD3\u6DFD\u6DD7\u6DCD\u6DE3\u6DBB\u70FA\u710D\u70F7\u7117\u70F4\u710C\u70F0\u7104\u70F3\u7110\u70FC\u70FF\u7106\u7113\u7100\u70F8\u70F6\u710B\u7102\u710E\u727E\u727B\u727C\u727F\u731D\u7317\u7307\u7311\u7318\u730A\u7308\u72FF\u730F\u731E\u7388\u73F6\u73F8\u73F5\u7404\u7401\u73FD\u7407\u7400\u73FA\u73FC\u73FF\u740C\u740B\u73F4\u7408\u7564\u7563\u75CE\u75D2\u75CF"],
      ["d6a1", "\u75CB\u75CC\u75D1\u75D0\u768F\u7689\u76D3\u7739\u772F\u772D\u7731\u7732\u7734\u7733\u773D\u7725\u773B\u7735\u7848\u7852\u7849\u784D\u784A\u784C\u7826\u7845\u7850\u7964\u7967\u7969\u796A\u7963\u796B\u7961\u79BB\u79FA\u79F8\u79F6\u79F7\u7A8F\u7A94\u7A90\u7B35\u7B47\u7B34\u7B25\u7B30\u7B22\u7B24\u7B33\u7B18\u7B2A\u7B1D\u7B31\u7B2B\u7B2D\u7B2F\u7B32\u7B38\u7B1A\u7B23\u7C94\u7C98\u7C96\u7CA3\u7D35\u7D3D\u7D38\u7D36\u7D3A\u7D45\u7D2C\u7D29\u7D41\u7D47\u7D3E\u7D3F\u7D4A\u7D3B\u7D28\u7F63\u7F95\u7F9C\u7F9D\u7F9B\u7FCA\u7FCB\u7FCD\u7FD0\u7FD1\u7FC7\u7FCF\u7FC9\u801F"],
      ["d740", "\u801E\u801B\u8047\u8043\u8048\u8118\u8125\u8119\u811B\u812D\u811F\u812C\u811E\u8121\u8115\u8127\u811D\u8122\u8211\u8238\u8233\u823A\u8234\u8232\u8274\u8390\u83A3\u83A8\u838D\u837A\u8373\u83A4\u8374\u838F\u8381\u8395\u8399\u8375\u8394\u83A9\u837D\u8383\u838C\u839D\u839B\u83AA\u838B\u837E\u83A5\u83AF\u8388\u8397\u83B0\u837F\u83A6\u8387\u83AE\u8376\u839A\u8659\u8656\u86BF\u86B7"],
      ["d7a1", "\u86C2\u86C1\u86C5\u86BA\u86B0\u86C8\u86B9\u86B3\u86B8\u86CC\u86B4\u86BB\u86BC\u86C3\u86BD\u86BE\u8852\u8889\u8895\u88A8\u88A2\u88AA\u889A\u8891\u88A1\u889F\u8898\u88A7\u8899\u889B\u8897\u88A4\u88AC\u888C\u8893\u888E\u8982\u89D6\u89D9\u89D5\u8A30\u8A27\u8A2C\u8A1E\u8C39\u8C3B\u8C5C\u8C5D\u8C7D\u8CA5\u8D7D\u8D7B\u8D79\u8DBC\u8DC2\u8DB9\u8DBF\u8DC1\u8ED8\u8EDE\u8EDD\u8EDC\u8ED7\u8EE0\u8EE1\u9024\u900B\u9011\u901C\u900C\u9021\u90EF\u90EA\u90F0\u90F4\u90F2\u90F3\u90D4\u90EB\u90EC\u90E9\u9156\u9158\u915A\u9153\u9155\u91EC\u91F4\u91F1\u91F3\u91F8\u91E4\u91F9\u91EA"],
      ["d840", "\u91EB\u91F7\u91E8\u91EE\u957A\u9586\u9588\u967C\u966D\u966B\u9671\u966F\u96BF\u976A\u9804\u98E5\u9997\u509B\u5095\u5094\u509E\u508B\u50A3\u5083\u508C\u508E\u509D\u5068\u509C\u5092\u5082\u5087\u515F\u51D4\u5312\u5311\u53A4\u53A7\u5591\u55A8\u55A5\u55AD\u5577\u5645\u55A2\u5593\u5588\u558F\u55B5\u5581\u55A3\u5592\u55A4\u557D\u558C\u55A6\u557F\u5595\u55A1\u558E\u570C\u5829\u5837"],
      ["d8a1", "\u5819\u581E\u5827\u5823\u5828\u57F5\u5848\u5825\u581C\u581B\u5833\u583F\u5836\u582E\u5839\u5838\u582D\u582C\u583B\u5961\u5AAF\u5A94\u5A9F\u5A7A\u5AA2\u5A9E\u5A78\u5AA6\u5A7C\u5AA5\u5AAC\u5A95\u5AAE\u5A37\u5A84\u5A8A\u5A97\u5A83\u5A8B\u5AA9\u5A7B\u5A7D\u5A8C\u5A9C\u5A8F\u5A93\u5A9D\u5BEA\u5BCD\u5BCB\u5BD4\u5BD1\u5BCA\u5BCE\u5C0C\u5C30\u5D37\u5D43\u5D6B\u5D41\u5D4B\u5D3F\u5D35\u5D51\u5D4E\u5D55\u5D33\u5D3A\u5D52\u5D3D\u5D31\u5D59\u5D42\u5D39\u5D49\u5D38\u5D3C\u5D32\u5D36\u5D40\u5D45\u5E44\u5E41\u5F58\u5FA6\u5FA5\u5FAB\u60C9\u60B9\u60CC\u60E2\u60CE\u60C4\u6114"],
      ["d940", "\u60F2\u610A\u6116\u6105\u60F5\u6113\u60F8\u60FC\u60FE\u60C1\u6103\u6118\u611D\u6110\u60FF\u6104\u610B\u624A\u6394\u63B1\u63B0\u63CE\u63E5\u63E8\u63EF\u63C3\u649D\u63F3\u63CA\u63E0\u63F6\u63D5\u63F2\u63F5\u6461\u63DF\u63BE\u63DD\u63DC\u63C4\u63D8\u63D3\u63C2\u63C7\u63CC\u63CB\u63C8\u63F0\u63D7\u63D9\u6532\u6567\u656A\u6564\u655C\u6568\u6565\u658C\u659D\u659E\u65AE\u65D0\u65D2"],
      ["d9a1", "\u667C\u666C\u667B\u6680\u6671\u6679\u666A\u6672\u6701\u690C\u68D3\u6904\u68DC\u692A\u68EC\u68EA\u68F1\u690F\u68D6\u68F7\u68EB\u68E4\u68F6\u6913\u6910\u68F3\u68E1\u6907\u68CC\u6908\u6970\u68B4\u6911\u68EF\u68C6\u6914\u68F8\u68D0\u68FD\u68FC\u68E8\u690B\u690A\u6917\u68CE\u68C8\u68DD\u68DE\u68E6\u68F4\u68D1\u6906\u68D4\u68E9\u6915\u6925\u68C7\u6B39\u6B3B\u6B3F\u6B3C\u6B94\u6B97\u6B99\u6B95\u6BBD\u6BF0\u6BF2\u6BF3\u6C30\u6DFC\u6E46\u6E47\u6E1F\u6E49\u6E88\u6E3C\u6E3D\u6E45\u6E62\u6E2B\u6E3F\u6E41\u6E5D\u6E73\u6E1C\u6E33\u6E4B\u6E40\u6E51\u6E3B\u6E03\u6E2E\u6E5E"],
      ["da40", "\u6E68\u6E5C\u6E61\u6E31\u6E28\u6E60\u6E71\u6E6B\u6E39\u6E22\u6E30\u6E53\u6E65\u6E27\u6E78\u6E64\u6E77\u6E55\u6E79\u6E52\u6E66\u6E35\u6E36\u6E5A\u7120\u711E\u712F\u70FB\u712E\u7131\u7123\u7125\u7122\u7132\u711F\u7128\u713A\u711B\u724B\u725A\u7288\u7289\u7286\u7285\u728B\u7312\u730B\u7330\u7322\u7331\u7333\u7327\u7332\u732D\u7326\u7323\u7335\u730C\u742E\u742C\u7430\u742B\u7416"],
      ["daa1", "\u741A\u7421\u742D\u7431\u7424\u7423\u741D\u7429\u7420\u7432\u74FB\u752F\u756F\u756C\u75E7\u75DA\u75E1\u75E6\u75DD\u75DF\u75E4\u75D7\u7695\u7692\u76DA\u7746\u7747\u7744\u774D\u7745\u774A\u774E\u774B\u774C\u77DE\u77EC\u7860\u7864\u7865\u785C\u786D\u7871\u786A\u786E\u7870\u7869\u7868\u785E\u7862\u7974\u7973\u7972\u7970\u7A02\u7A0A\u7A03\u7A0C\u7A04\u7A99\u7AE6\u7AE4\u7B4A\u7B3B\u7B44\u7B48\u7B4C\u7B4E\u7B40\u7B58\u7B45\u7CA2\u7C9E\u7CA8\u7CA1\u7D58\u7D6F\u7D63\u7D53\u7D56\u7D67\u7D6A\u7D4F\u7D6D\u7D5C\u7D6B\u7D52\u7D54\u7D69\u7D51\u7D5F\u7D4E\u7F3E\u7F3F\u7F65"],
      ["db40", "\u7F66\u7FA2\u7FA0\u7FA1\u7FD7\u8051\u804F\u8050\u80FE\u80D4\u8143\u814A\u8152\u814F\u8147\u813D\u814D\u813A\u81E6\u81EE\u81F7\u81F8\u81F9\u8204\u823C\u823D\u823F\u8275\u833B\u83CF\u83F9\u8423\u83C0\u83E8\u8412\u83E7\u83E4\u83FC\u83F6\u8410\u83C6\u83C8\u83EB\u83E3\u83BF\u8401\u83DD\u83E5\u83D8\u83FF\u83E1\u83CB\u83CE\u83D6\u83F5\u83C9\u8409\u840F\u83DE\u8411\u8406\u83C2\u83F3"],
      ["dba1", "\u83D5\u83FA\u83C7\u83D1\u83EA\u8413\u83C3\u83EC\u83EE\u83C4\u83FB\u83D7\u83E2\u841B\u83DB\u83FE\u86D8\u86E2\u86E6\u86D3\u86E3\u86DA\u86EA\u86DD\u86EB\u86DC\u86EC\u86E9\u86D7\u86E8\u86D1\u8848\u8856\u8855\u88BA\u88D7\u88B9\u88B8\u88C0\u88BE\u88B6\u88BC\u88B7\u88BD\u88B2\u8901\u88C9\u8995\u8998\u8997\u89DD\u89DA\u89DB\u8A4E\u8A4D\u8A39\u8A59\u8A40\u8A57\u8A58\u8A44\u8A45\u8A52\u8A48\u8A51\u8A4A\u8A4C\u8A4F\u8C5F\u8C81\u8C80\u8CBA\u8CBE\u8CB0\u8CB9\u8CB5\u8D84\u8D80\u8D89\u8DD8\u8DD3\u8DCD\u8DC7\u8DD6\u8DDC\u8DCF\u8DD5\u8DD9\u8DC8\u8DD7\u8DC5\u8EEF\u8EF7\u8EFA"],
      ["dc40", "\u8EF9\u8EE6\u8EEE\u8EE5\u8EF5\u8EE7\u8EE8\u8EF6\u8EEB\u8EF1\u8EEC\u8EF4\u8EE9\u902D\u9034\u902F\u9106\u912C\u9104\u90FF\u90FC\u9108\u90F9\u90FB\u9101\u9100\u9107\u9105\u9103\u9161\u9164\u915F\u9162\u9160\u9201\u920A\u9225\u9203\u921A\u9226\u920F\u920C\u9200\u9212\u91FF\u91FD\u9206\u9204\u9227\u9202\u921C\u9224\u9219\u9217\u9205\u9216\u957B\u958D\u958C\u9590\u9687\u967E\u9688"],
      ["dca1", "\u9689\u9683\u9680\u96C2\u96C8\u96C3\u96F1\u96F0\u976C\u9770\u976E\u9807\u98A9\u98EB\u9CE6\u9EF9\u4E83\u4E84\u4EB6\u50BD\u50BF\u50C6\u50AE\u50C4\u50CA\u50B4\u50C8\u50C2\u50B0\u50C1\u50BA\u50B1\u50CB\u50C9\u50B6\u50B8\u51D7\u527A\u5278\u527B\u527C\u55C3\u55DB\u55CC\u55D0\u55CB\u55CA\u55DD\u55C0\u55D4\u55C4\u55E9\u55BF\u55D2\u558D\u55CF\u55D5\u55E2\u55D6\u55C8\u55F2\u55CD\u55D9\u55C2\u5714\u5853\u5868\u5864\u584F\u584D\u5849\u586F\u5855\u584E\u585D\u5859\u5865\u585B\u583D\u5863\u5871\u58FC\u5AC7\u5AC4\u5ACB\u5ABA\u5AB8\u5AB1\u5AB5\u5AB0\u5ABF\u5AC8\u5ABB\u5AC6"],
      ["dd40", "\u5AB7\u5AC0\u5ACA\u5AB4\u5AB6\u5ACD\u5AB9\u5A90\u5BD6\u5BD8\u5BD9\u5C1F\u5C33\u5D71\u5D63\u5D4A\u5D65\u5D72\u5D6C\u5D5E\u5D68\u5D67\u5D62\u5DF0\u5E4F\u5E4E\u5E4A\u5E4D\u5E4B\u5EC5\u5ECC\u5EC6\u5ECB\u5EC7\u5F40\u5FAF\u5FAD\u60F7\u6149\u614A\u612B\u6145\u6136\u6132\u612E\u6146\u612F\u614F\u6129\u6140\u6220\u9168\u6223\u6225\u6224\u63C5\u63F1\u63EB\u6410\u6412\u6409\u6420\u6424"],
      ["dda1", "\u6433\u6443\u641F\u6415\u6418\u6439\u6437\u6422\u6423\u640C\u6426\u6430\u6428\u6441\u6435\u642F\u640A\u641A\u6440\u6425\u6427\u640B\u63E7\u641B\u642E\u6421\u640E\u656F\u6592\u65D3\u6686\u668C\u6695\u6690\u668B\u668A\u6699\u6694\u6678\u6720\u6966\u695F\u6938\u694E\u6962\u6971\u693F\u6945\u696A\u6939\u6942\u6957\u6959\u697A\u6948\u6949\u6935\u696C\u6933\u693D\u6965\u68F0\u6978\u6934\u6969\u6940\u696F\u6944\u6976\u6958\u6941\u6974\u694C\u693B\u694B\u6937\u695C\u694F\u6951\u6932\u6952\u692F\u697B\u693C\u6B46\u6B45\u6B43\u6B42\u6B48\u6B41\u6B9B\uFA0D\u6BFB\u6BFC"],
      ["de40", "\u6BF9\u6BF7\u6BF8\u6E9B\u6ED6\u6EC8\u6E8F\u6EC0\u6E9F\u6E93\u6E94\u6EA0\u6EB1\u6EB9\u6EC6\u6ED2\u6EBD\u6EC1\u6E9E\u6EC9\u6EB7\u6EB0\u6ECD\u6EA6\u6ECF\u6EB2\u6EBE\u6EC3\u6EDC\u6ED8\u6E99\u6E92\u6E8E\u6E8D\u6EA4\u6EA1\u6EBF\u6EB3\u6ED0\u6ECA\u6E97\u6EAE\u6EA3\u7147\u7154\u7152\u7163\u7160\u7141\u715D\u7162\u7172\u7178\u716A\u7161\u7142\u7158\u7143\u714B\u7170\u715F\u7150\u7153"],
      ["dea1", "\u7144\u714D\u715A\u724F\u728D\u728C\u7291\u7290\u728E\u733C\u7342\u733B\u733A\u7340\u734A\u7349\u7444\u744A\u744B\u7452\u7451\u7457\u7440\u744F\u7450\u744E\u7442\u7446\u744D\u7454\u74E1\u74FF\u74FE\u74FD\u751D\u7579\u7577\u6983\u75EF\u760F\u7603\u75F7\u75FE\u75FC\u75F9\u75F8\u7610\u75FB\u75F6\u75ED\u75F5\u75FD\u7699\u76B5\u76DD\u7755\u775F\u7760\u7752\u7756\u775A\u7769\u7767\u7754\u7759\u776D\u77E0\u7887\u789A\u7894\u788F\u7884\u7895\u7885\u7886\u78A1\u7883\u7879\u7899\u7880\u7896\u787B\u797C\u7982\u797D\u7979\u7A11\u7A18\u7A19\u7A12\u7A17\u7A15\u7A22\u7A13"],
      ["df40", "\u7A1B\u7A10\u7AA3\u7AA2\u7A9E\u7AEB\u7B66\u7B64\u7B6D\u7B74\u7B69\u7B72\u7B65\u7B73\u7B71\u7B70\u7B61\u7B78\u7B76\u7B63\u7CB2\u7CB4\u7CAF\u7D88\u7D86\u7D80\u7D8D\u7D7F\u7D85\u7D7A\u7D8E\u7D7B\u7D83\u7D7C\u7D8C\u7D94\u7D84\u7D7D\u7D92\u7F6D\u7F6B\u7F67\u7F68\u7F6C\u7FA6\u7FA5\u7FA7\u7FDB\u7FDC\u8021\u8164\u8160\u8177\u815C\u8169\u815B\u8162\u8172\u6721\u815E\u8176\u8167\u816F"],
      ["dfa1", "\u8144\u8161\u821D\u8249\u8244\u8240\u8242\u8245\u84F1\u843F\u8456\u8476\u8479\u848F\u848D\u8465\u8451\u8440\u8486\u8467\u8430\u844D\u847D\u845A\u8459\u8474\u8473\u845D\u8507\u845E\u8437\u843A\u8434\u847A\u8443\u8478\u8432\u8445\u8429\u83D9\u844B\u842F\u8442\u842D\u845F\u8470\u8439\u844E\u844C\u8452\u846F\u84C5\u848E\u843B\u8447\u8436\u8433\u8468\u847E\u8444\u842B\u8460\u8454\u846E\u8450\u870B\u8704\u86F7\u870C\u86FA\u86D6\u86F5\u874D\u86F8\u870E\u8709\u8701\u86F6\u870D\u8705\u88D6\u88CB\u88CD\u88CE\u88DE\u88DB\u88DA\u88CC\u88D0\u8985\u899B\u89DF\u89E5\u89E4"],
      ["e040", "\u89E1\u89E0\u89E2\u89DC\u89E6\u8A76\u8A86\u8A7F\u8A61\u8A3F\u8A77\u8A82\u8A84\u8A75\u8A83\u8A81\u8A74\u8A7A\u8C3C\u8C4B\u8C4A\u8C65\u8C64\u8C66\u8C86\u8C84\u8C85\u8CCC\u8D68\u8D69\u8D91\u8D8C\u8D8E\u8D8F\u8D8D\u8D93\u8D94\u8D90\u8D92\u8DF0\u8DE0\u8DEC\u8DF1\u8DEE\u8DD0\u8DE9\u8DE3\u8DE2\u8DE7\u8DF2\u8DEB\u8DF4\u8F06\u8EFF\u8F01\u8F00\u8F05\u8F07\u8F08\u8F02\u8F0B\u9052\u903F"],
      ["e0a1", "\u9044\u9049\u903D\u9110\u910D\u910F\u9111\u9116\u9114\u910B\u910E\u916E\u916F\u9248\u9252\u9230\u923A\u9266\u9233\u9265\u925E\u9283\u922E\u924A\u9246\u926D\u926C\u924F\u9260\u9267\u926F\u9236\u9261\u9270\u9231\u9254\u9263\u9250\u9272\u924E\u9253\u924C\u9256\u9232\u959F\u959C\u959E\u959B\u9692\u9693\u9691\u9697\u96CE\u96FA\u96FD\u96F8\u96F5\u9773\u9777\u9778\u9772\u980F\u980D\u980E\u98AC\u98F6\u98F9\u99AF\u99B2\u99B0\u99B5\u9AAD\u9AAB\u9B5B\u9CEA\u9CED\u9CE7\u9E80\u9EFD\u50E6\u50D4\u50D7\u50E8\u50F3\u50DB\u50EA\u50DD\u50E4\u50D3\u50EC\u50F0\u50EF\u50E3\u50E0"],
      ["e140", "\u51D8\u5280\u5281\u52E9\u52EB\u5330\u53AC\u5627\u5615\u560C\u5612\u55FC\u560F\u561C\u5601\u5613\u5602\u55FA\u561D\u5604\u55FF\u55F9\u5889\u587C\u5890\u5898\u5886\u5881\u587F\u5874\u588B\u587A\u5887\u5891\u588E\u5876\u5882\u5888\u587B\u5894\u588F\u58FE\u596B\u5ADC\u5AEE\u5AE5\u5AD5\u5AEA\u5ADA\u5AED\u5AEB\u5AF3\u5AE2\u5AE0\u5ADB\u5AEC\u5ADE\u5ADD\u5AD9\u5AE8\u5ADF\u5B77\u5BE0"],
      ["e1a1", "\u5BE3\u5C63\u5D82\u5D80\u5D7D\u5D86\u5D7A\u5D81\u5D77\u5D8A\u5D89\u5D88\u5D7E\u5D7C\u5D8D\u5D79\u5D7F\u5E58\u5E59\u5E53\u5ED8\u5ED1\u5ED7\u5ECE\u5EDC\u5ED5\u5ED9\u5ED2\u5ED4\u5F44\u5F43\u5F6F\u5FB6\u612C\u6128\u6141\u615E\u6171\u6173\u6152\u6153\u6172\u616C\u6180\u6174\u6154\u617A\u615B\u6165\u613B\u616A\u6161\u6156\u6229\u6227\u622B\u642B\u644D\u645B\u645D\u6474\u6476\u6472\u6473\u647D\u6475\u6466\u64A6\u644E\u6482\u645E\u645C\u644B\u6453\u6460\u6450\u647F\u643F\u646C\u646B\u6459\u6465\u6477\u6573\u65A0\u66A1\u66A0\u669F\u6705\u6704\u6722\u69B1\u69B6\u69C9"],
      ["e240", "\u69A0\u69CE\u6996\u69B0\u69AC\u69BC\u6991\u6999\u698E\u69A7\u698D\u69A9\u69BE\u69AF\u69BF\u69C4\u69BD\u69A4\u69D4\u69B9\u69CA\u699A\u69CF\u69B3\u6993\u69AA\u69A1\u699E\u69D9\u6997\u6990\u69C2\u69B5\u69A5\u69C6\u6B4A\u6B4D\u6B4B\u6B9E\u6B9F\u6BA0\u6BC3\u6BC4\u6BFE\u6ECE\u6EF5\u6EF1\u6F03\u6F25\u6EF8\u6F37\u6EFB\u6F2E\u6F09\u6F4E\u6F19\u6F1A\u6F27\u6F18\u6F3B\u6F12\u6EED\u6F0A"],
      ["e2a1", "\u6F36\u6F73\u6EF9\u6EEE\u6F2D\u6F40\u6F30\u6F3C\u6F35\u6EEB\u6F07\u6F0E\u6F43\u6F05\u6EFD\u6EF6\u6F39\u6F1C\u6EFC\u6F3A\u6F1F\u6F0D\u6F1E\u6F08\u6F21\u7187\u7190\u7189\u7180\u7185\u7182\u718F\u717B\u7186\u7181\u7197\u7244\u7253\u7297\u7295\u7293\u7343\u734D\u7351\u734C\u7462\u7473\u7471\u7475\u7472\u7467\u746E\u7500\u7502\u7503\u757D\u7590\u7616\u7608\u760C\u7615\u7611\u760A\u7614\u76B8\u7781\u777C\u7785\u7782\u776E\u7780\u776F\u777E\u7783\u78B2\u78AA\u78B4\u78AD\u78A8\u787E\u78AB\u789E\u78A5\u78A0\u78AC\u78A2\u78A4\u7998\u798A\u798B\u7996\u7995\u7994\u7993"],
      ["e340", "\u7997\u7988\u7992\u7990\u7A2B\u7A4A\u7A30\u7A2F\u7A28\u7A26\u7AA8\u7AAB\u7AAC\u7AEE\u7B88\u7B9C\u7B8A\u7B91\u7B90\u7B96\u7B8D\u7B8C\u7B9B\u7B8E\u7B85\u7B98\u5284\u7B99\u7BA4\u7B82\u7CBB\u7CBF\u7CBC\u7CBA\u7DA7\u7DB7\u7DC2\u7DA3\u7DAA\u7DC1\u7DC0\u7DC5\u7D9D\u7DCE\u7DC4\u7DC6\u7DCB\u7DCC\u7DAF\u7DB9\u7D96\u7DBC\u7D9F\u7DA6\u7DAE\u7DA9\u7DA1\u7DC9\u7F73\u7FE2\u7FE3\u7FE5\u7FDE"],
      ["e3a1", "\u8024\u805D\u805C\u8189\u8186\u8183\u8187\u818D\u818C\u818B\u8215\u8497\u84A4\u84A1\u849F\u84BA\u84CE\u84C2\u84AC\u84AE\u84AB\u84B9\u84B4\u84C1\u84CD\u84AA\u849A\u84B1\u84D0\u849D\u84A7\u84BB\u84A2\u8494\u84C7\u84CC\u849B\u84A9\u84AF\u84A8\u84D6\u8498\u84B6\u84CF\u84A0\u84D7\u84D4\u84D2\u84DB\u84B0\u8491\u8661\u8733\u8723\u8728\u876B\u8740\u872E\u871E\u8721\u8719\u871B\u8743\u872C\u8741\u873E\u8746\u8720\u8732\u872A\u872D\u873C\u8712\u873A\u8731\u8735\u8742\u8726\u8727\u8738\u8724\u871A\u8730\u8711\u88F7\u88E7\u88F1\u88F2\u88FA\u88FE\u88EE\u88FC\u88F6\u88FB"],
      ["e440", "\u88F0\u88EC\u88EB\u899D\u89A1\u899F\u899E\u89E9\u89EB\u89E8\u8AAB\u8A99\u8A8B\u8A92\u8A8F\u8A96\u8C3D\u8C68\u8C69\u8CD5\u8CCF\u8CD7\u8D96\u8E09\u8E02\u8DFF\u8E0D\u8DFD\u8E0A\u8E03\u8E07\u8E06\u8E05\u8DFE\u8E00\u8E04\u8F10\u8F11\u8F0E\u8F0D\u9123\u911C\u9120\u9122\u911F\u911D\u911A\u9124\u9121\u911B\u917A\u9172\u9179\u9173\u92A5\u92A4\u9276\u929B\u927A\u92A0\u9294\u92AA\u928D"],
      ["e4a1", "\u92A6\u929A\u92AB\u9279\u9297\u927F\u92A3\u92EE\u928E\u9282\u9295\u92A2\u927D\u9288\u92A1\u928A\u9286\u928C\u9299\u92A7\u927E\u9287\u92A9\u929D\u928B\u922D\u969E\u96A1\u96FF\u9758\u977D\u977A\u977E\u9783\u9780\u9782\u977B\u9784\u9781\u977F\u97CE\u97CD\u9816\u98AD\u98AE\u9902\u9900\u9907\u999D\u999C\u99C3\u99B9\u99BB\u99BA\u99C2\u99BD\u99C7\u9AB1\u9AE3\u9AE7\u9B3E\u9B3F\u9B60\u9B61\u9B5F\u9CF1\u9CF2\u9CF5\u9EA7\u50FF\u5103\u5130\u50F8\u5106\u5107\u50F6\u50FE\u510B\u510C\u50FD\u510A\u528B\u528C\u52F1\u52EF\u5648\u5642\u564C\u5635\u5641\u564A\u5649\u5646\u5658"],
      ["e540", "\u565A\u5640\u5633\u563D\u562C\u563E\u5638\u562A\u563A\u571A\u58AB\u589D\u58B1\u58A0\u58A3\u58AF\u58AC\u58A5\u58A1\u58FF\u5AFF\u5AF4\u5AFD\u5AF7\u5AF6\u5B03\u5AF8\u5B02\u5AF9\u5B01\u5B07\u5B05\u5B0F\u5C67\u5D99\u5D97\u5D9F\u5D92\u5DA2\u5D93\u5D95\u5DA0\u5D9C\u5DA1\u5D9A\u5D9E\u5E69\u5E5D\u5E60\u5E5C\u7DF3\u5EDB\u5EDE\u5EE1\u5F49\u5FB2\u618B\u6183\u6179\u61B1\u61B0\u61A2\u6189"],
      ["e5a1", "\u619B\u6193\u61AF\u61AD\u619F\u6192\u61AA\u61A1\u618D\u6166\u61B3\u622D\u646E\u6470\u6496\u64A0\u6485\u6497\u649C\u648F\u648B\u648A\u648C\u64A3\u649F\u6468\u64B1\u6498\u6576\u657A\u6579\u657B\u65B2\u65B3\u66B5\u66B0\u66A9\u66B2\u66B7\u66AA\u66AF\u6A00\u6A06\u6A17\u69E5\u69F8\u6A15\u69F1\u69E4\u6A20\u69FF\u69EC\u69E2\u6A1B\u6A1D\u69FE\u6A27\u69F2\u69EE\u6A14\u69F7\u69E7\u6A40\u6A08\u69E6\u69FB\u6A0D\u69FC\u69EB\u6A09\u6A04\u6A18\u6A25\u6A0F\u69F6\u6A26\u6A07\u69F4\u6A16\u6B51\u6BA5\u6BA3\u6BA2\u6BA6\u6C01\u6C00\u6BFF\u6C02\u6F41\u6F26\u6F7E\u6F87\u6FC6\u6F92"],
      ["e640", "\u6F8D\u6F89\u6F8C\u6F62\u6F4F\u6F85\u6F5A\u6F96\u6F76\u6F6C\u6F82\u6F55\u6F72\u6F52\u6F50\u6F57\u6F94\u6F93\u6F5D\u6F00\u6F61\u6F6B\u6F7D\u6F67\u6F90\u6F53\u6F8B\u6F69\u6F7F\u6F95\u6F63\u6F77\u6F6A\u6F7B\u71B2\u71AF\u719B\u71B0\u71A0\u719A\u71A9\u71B5\u719D\u71A5\u719E\u71A4\u71A1\u71AA\u719C\u71A7\u71B3\u7298\u729A\u7358\u7352\u735E\u735F\u7360\u735D\u735B\u7361\u735A\u7359"],
      ["e6a1", "\u7362\u7487\u7489\u748A\u7486\u7481\u747D\u7485\u7488\u747C\u7479\u7508\u7507\u757E\u7625\u761E\u7619\u761D\u761C\u7623\u761A\u7628\u761B\u769C\u769D\u769E\u769B\u778D\u778F\u7789\u7788\u78CD\u78BB\u78CF\u78CC\u78D1\u78CE\u78D4\u78C8\u78C3\u78C4\u78C9\u799A\u79A1\u79A0\u799C\u79A2\u799B\u6B76\u7A39\u7AB2\u7AB4\u7AB3\u7BB7\u7BCB\u7BBE\u7BAC\u7BCE\u7BAF\u7BB9\u7BCA\u7BB5\u7CC5\u7CC8\u7CCC\u7CCB\u7DF7\u7DDB\u7DEA\u7DE7\u7DD7\u7DE1\u7E03\u7DFA\u7DE6\u7DF6\u7DF1\u7DF0\u7DEE\u7DDF\u7F76\u7FAC\u7FB0\u7FAD\u7FED\u7FEB\u7FEA\u7FEC\u7FE6\u7FE8\u8064\u8067\u81A3\u819F"],
      ["e740", "\u819E\u8195\u81A2\u8199\u8197\u8216\u824F\u8253\u8252\u8250\u824E\u8251\u8524\u853B\u850F\u8500\u8529\u850E\u8509\u850D\u851F\u850A\u8527\u851C\u84FB\u852B\u84FA\u8508\u850C\u84F4\u852A\u84F2\u8515\u84F7\u84EB\u84F3\u84FC\u8512\u84EA\u84E9\u8516\u84FE\u8528\u851D\u852E\u8502\u84FD\u851E\u84F6\u8531\u8526\u84E7\u84E8\u84F0\u84EF\u84F9\u8518\u8520\u8530\u850B\u8519\u852F\u8662"],
      ["e7a1", "\u8756\u8763\u8764\u8777\u87E1\u8773\u8758\u8754\u875B\u8752\u8761\u875A\u8751\u875E\u876D\u876A\u8750\u874E\u875F\u875D\u876F\u876C\u877A\u876E\u875C\u8765\u874F\u877B\u8775\u8762\u8767\u8769\u885A\u8905\u890C\u8914\u890B\u8917\u8918\u8919\u8906\u8916\u8911\u890E\u8909\u89A2\u89A4\u89A3\u89ED\u89F0\u89EC\u8ACF\u8AC6\u8AB8\u8AD3\u8AD1\u8AD4\u8AD5\u8ABB\u8AD7\u8ABE\u8AC0\u8AC5\u8AD8\u8AC3\u8ABA\u8ABD\u8AD9\u8C3E\u8C4D\u8C8F\u8CE5\u8CDF\u8CD9\u8CE8\u8CDA\u8CDD\u8CE7\u8DA0\u8D9C\u8DA1\u8D9B\u8E20\u8E23\u8E25\u8E24\u8E2E\u8E15\u8E1B\u8E16\u8E11\u8E19\u8E26\u8E27"],
      ["e840", "\u8E14\u8E12\u8E18\u8E13\u8E1C\u8E17\u8E1A\u8F2C\u8F24\u8F18\u8F1A\u8F20\u8F23\u8F16\u8F17\u9073\u9070\u906F\u9067\u906B\u912F\u912B\u9129\u912A\u9132\u9126\u912E\u9185\u9186\u918A\u9181\u9182\u9184\u9180\u92D0\u92C3\u92C4\u92C0\u92D9\u92B6\u92CF\u92F1\u92DF\u92D8\u92E9\u92D7\u92DD\u92CC\u92EF\u92C2\u92E8\u92CA\u92C8\u92CE\u92E6\u92CD\u92D5\u92C9\u92E0\u92DE\u92E7\u92D1\u92D3"],
      ["e8a1", "\u92B5\u92E1\u92C6\u92B4\u957C\u95AC\u95AB\u95AE\u95B0\u96A4\u96A2\u96D3\u9705\u9708\u9702\u975A\u978A\u978E\u9788\u97D0\u97CF\u981E\u981D\u9826\u9829\u9828\u9820\u981B\u9827\u98B2\u9908\u98FA\u9911\u9914\u9916\u9917\u9915\u99DC\u99CD\u99CF\u99D3\u99D4\u99CE\u99C9\u99D6\u99D8\u99CB\u99D7\u99CC\u9AB3\u9AEC\u9AEB\u9AF3\u9AF2\u9AF1\u9B46\u9B43\u9B67\u9B74\u9B71\u9B66\u9B76\u9B75\u9B70\u9B68\u9B64\u9B6C\u9CFC\u9CFA\u9CFD\u9CFF\u9CF7\u9D07\u9D00\u9CF9\u9CFB\u9D08\u9D05\u9D04\u9E83\u9ED3\u9F0F\u9F10\u511C\u5113\u5117\u511A\u5111\u51DE\u5334\u53E1\u5670\u5660\u566E"],
      ["e940", "\u5673\u5666\u5663\u566D\u5672\u565E\u5677\u571C\u571B\u58C8\u58BD\u58C9\u58BF\u58BA\u58C2\u58BC\u58C6\u5B17\u5B19\u5B1B\u5B21\u5B14\u5B13\u5B10\u5B16\u5B28\u5B1A\u5B20\u5B1E\u5BEF\u5DAC\u5DB1\u5DA9\u5DA7\u5DB5\u5DB0\u5DAE\u5DAA\u5DA8\u5DB2\u5DAD\u5DAF\u5DB4\u5E67\u5E68\u5E66\u5E6F\u5EE9\u5EE7\u5EE6\u5EE8\u5EE5\u5F4B\u5FBC\u619D\u61A8\u6196\u61C5\u61B4\u61C6\u61C1\u61CC\u61BA"],
      ["e9a1", "\u61BF\u61B8\u618C\u64D7\u64D6\u64D0\u64CF\u64C9\u64BD\u6489\u64C3\u64DB\u64F3\u64D9\u6533\u657F\u657C\u65A2\u66C8\u66BE\u66C0\u66CA\u66CB\u66CF\u66BD\u66BB\u66BA\u66CC\u6723\u6A34\u6A66\u6A49\u6A67\u6A32\u6A68\u6A3E\u6A5D\u6A6D\u6A76\u6A5B\u6A51\u6A28\u6A5A\u6A3B\u6A3F\u6A41\u6A6A\u6A64\u6A50\u6A4F\u6A54\u6A6F\u6A69\u6A60\u6A3C\u6A5E\u6A56\u6A55\u6A4D\u6A4E\u6A46\u6B55\u6B54\u6B56\u6BA7\u6BAA\u6BAB\u6BC8\u6BC7\u6C04\u6C03\u6C06\u6FAD\u6FCB\u6FA3\u6FC7\u6FBC\u6FCE\u6FC8\u6F5E\u6FC4\u6FBD\u6F9E\u6FCA\u6FA8\u7004\u6FA5\u6FAE\u6FBA\u6FAC\u6FAA\u6FCF\u6FBF\u6FB8"],
      ["ea40", "\u6FA2\u6FC9\u6FAB\u6FCD\u6FAF\u6FB2\u6FB0\u71C5\u71C2\u71BF\u71B8\u71D6\u71C0\u71C1\u71CB\u71D4\u71CA\u71C7\u71CF\u71BD\u71D8\u71BC\u71C6\u71DA\u71DB\u729D\u729E\u7369\u7366\u7367\u736C\u7365\u736B\u736A\u747F\u749A\u74A0\u7494\u7492\u7495\u74A1\u750B\u7580\u762F\u762D\u7631\u763D\u7633\u763C\u7635\u7632\u7630\u76BB\u76E6\u779A\u779D\u77A1\u779C\u779B\u77A2\u77A3\u7795\u7799"],
      ["eaa1", "\u7797\u78DD\u78E9\u78E5\u78EA\u78DE\u78E3\u78DB\u78E1\u78E2\u78ED\u78DF\u78E0\u79A4\u7A44\u7A48\u7A47\u7AB6\u7AB8\u7AB5\u7AB1\u7AB7\u7BDE\u7BE3\u7BE7\u7BDD\u7BD5\u7BE5\u7BDA\u7BE8\u7BF9\u7BD4\u7BEA\u7BE2\u7BDC\u7BEB\u7BD8\u7BDF\u7CD2\u7CD4\u7CD7\u7CD0\u7CD1\u7E12\u7E21\u7E17\u7E0C\u7E1F\u7E20\u7E13\u7E0E\u7E1C\u7E15\u7E1A\u7E22\u7E0B\u7E0F\u7E16\u7E0D\u7E14\u7E25\u7E24\u7F43\u7F7B\u7F7C\u7F7A\u7FB1\u7FEF\u802A\u8029\u806C\u81B1\u81A6\u81AE\u81B9\u81B5\u81AB\u81B0\u81AC\u81B4\u81B2\u81B7\u81A7\u81F2\u8255\u8256\u8257\u8556\u8545\u856B\u854D\u8553\u8561\u8558"],
      ["eb40", "\u8540\u8546\u8564\u8541\u8562\u8544\u8551\u8547\u8563\u853E\u855B\u8571\u854E\u856E\u8575\u8555\u8567\u8560\u858C\u8566\u855D\u8554\u8565\u856C\u8663\u8665\u8664\u879B\u878F\u8797\u8793\u8792\u8788\u8781\u8796\u8798\u8779\u8787\u87A3\u8785\u8790\u8791\u879D\u8784\u8794\u879C\u879A\u8789\u891E\u8926\u8930\u892D\u892E\u8927\u8931\u8922\u8929\u8923\u892F\u892C\u891F\u89F1\u8AE0"],
      ["eba1", "\u8AE2\u8AF2\u8AF4\u8AF5\u8ADD\u8B14\u8AE4\u8ADF\u8AF0\u8AC8\u8ADE\u8AE1\u8AE8\u8AFF\u8AEF\u8AFB\u8C91\u8C92\u8C90\u8CF5\u8CEE\u8CF1\u8CF0\u8CF3\u8D6C\u8D6E\u8DA5\u8DA7\u8E33\u8E3E\u8E38\u8E40\u8E45\u8E36\u8E3C\u8E3D\u8E41\u8E30\u8E3F\u8EBD\u8F36\u8F2E\u8F35\u8F32\u8F39\u8F37\u8F34\u9076\u9079\u907B\u9086\u90FA\u9133\u9135\u9136\u9193\u9190\u9191\u918D\u918F\u9327\u931E\u9308\u931F\u9306\u930F\u937A\u9338\u933C\u931B\u9323\u9312\u9301\u9346\u932D\u930E\u930D\u92CB\u931D\u92FA\u9325\u9313\u92F9\u92F7\u9334\u9302\u9324\u92FF\u9329\u9339\u9335\u932A\u9314\u930C"],
      ["ec40", "\u930B\u92FE\u9309\u9300\u92FB\u9316\u95BC\u95CD\u95BE\u95B9\u95BA\u95B6\u95BF\u95B5\u95BD\u96A9\u96D4\u970B\u9712\u9710\u9799\u9797\u9794\u97F0\u97F8\u9835\u982F\u9832\u9924\u991F\u9927\u9929\u999E\u99EE\u99EC\u99E5\u99E4\u99F0\u99E3\u99EA\u99E9\u99E7\u9AB9\u9ABF\u9AB4\u9ABB\u9AF6\u9AFA\u9AF9\u9AF7\u9B33\u9B80\u9B85\u9B87\u9B7C\u9B7E\u9B7B\u9B82\u9B93\u9B92\u9B90\u9B7A\u9B95"],
      ["eca1", "\u9B7D\u9B88\u9D25\u9D17\u9D20\u9D1E\u9D14\u9D29\u9D1D\u9D18\u9D22\u9D10\u9D19\u9D1F\u9E88\u9E86\u9E87\u9EAE\u9EAD\u9ED5\u9ED6\u9EFA\u9F12\u9F3D\u5126\u5125\u5122\u5124\u5120\u5129\u52F4\u5693\u568C\u568D\u5686\u5684\u5683\u567E\u5682\u567F\u5681\u58D6\u58D4\u58CF\u58D2\u5B2D\u5B25\u5B32\u5B23\u5B2C\u5B27\u5B26\u5B2F\u5B2E\u5B7B\u5BF1\u5BF2\u5DB7\u5E6C\u5E6A\u5FBE\u5FBB\u61C3\u61B5\u61BC\u61E7\u61E0\u61E5\u61E4\u61E8\u61DE\u64EF\u64E9\u64E3\u64EB\u64E4\u64E8\u6581\u6580\u65B6\u65DA\u66D2\u6A8D\u6A96\u6A81\u6AA5\u6A89\u6A9F\u6A9B\u6AA1\u6A9E\u6A87\u6A93\u6A8E"],
      ["ed40", "\u6A95\u6A83\u6AA8\u6AA4\u6A91\u6A7F\u6AA6\u6A9A\u6A85\u6A8C\u6A92\u6B5B\u6BAD\u6C09\u6FCC\u6FA9\u6FF4\u6FD4\u6FE3\u6FDC\u6FED\u6FE7\u6FE6\u6FDE\u6FF2\u6FDD\u6FE2\u6FE8\u71E1\u71F1\u71E8\u71F2\u71E4\u71F0\u71E2\u7373\u736E\u736F\u7497\u74B2\u74AB\u7490\u74AA\u74AD\u74B1\u74A5\u74AF\u7510\u7511\u7512\u750F\u7584\u7643\u7648\u7649\u7647\u76A4\u76E9\u77B5\u77AB\u77B2\u77B7\u77B6"],
      ["eda1", "\u77B4\u77B1\u77A8\u77F0\u78F3\u78FD\u7902\u78FB\u78FC\u78F2\u7905\u78F9\u78FE\u7904\u79AB\u79A8\u7A5C\u7A5B\u7A56\u7A58\u7A54\u7A5A\u7ABE\u7AC0\u7AC1\u7C05\u7C0F\u7BF2\u7C00\u7BFF\u7BFB\u7C0E\u7BF4\u7C0B\u7BF3\u7C02\u7C09\u7C03\u7C01\u7BF8\u7BFD\u7C06\u7BF0\u7BF1\u7C10\u7C0A\u7CE8\u7E2D\u7E3C\u7E42\u7E33\u9848\u7E38\u7E2A\u7E49\u7E40\u7E47\u7E29\u7E4C\u7E30\u7E3B\u7E36\u7E44\u7E3A\u7F45\u7F7F\u7F7E\u7F7D\u7FF4\u7FF2\u802C\u81BB\u81C4\u81CC\u81CA\u81C5\u81C7\u81BC\u81E9\u825B\u825A\u825C\u8583\u8580\u858F\u85A7\u8595\u85A0\u858B\u85A3\u857B\u85A4\u859A\u859E"],
      ["ee40", "\u8577\u857C\u8589\u85A1\u857A\u8578\u8557\u858E\u8596\u8586\u858D\u8599\u859D\u8581\u85A2\u8582\u8588\u8585\u8579\u8576\u8598\u8590\u859F\u8668\u87BE\u87AA\u87AD\u87C5\u87B0\u87AC\u87B9\u87B5\u87BC\u87AE\u87C9\u87C3\u87C2\u87CC\u87B7\u87AF\u87C4\u87CA\u87B4\u87B6\u87BF\u87B8\u87BD\u87DE\u87B2\u8935\u8933\u893C\u893E\u8941\u8952\u8937\u8942\u89AD\u89AF\u89AE\u89F2\u89F3\u8B1E"],
      ["eea1", "\u8B18\u8B16\u8B11\u8B05\u8B0B\u8B22\u8B0F\u8B12\u8B15\u8B07\u8B0D\u8B08\u8B06\u8B1C\u8B13\u8B1A\u8C4F\u8C70\u8C72\u8C71\u8C6F\u8C95\u8C94\u8CF9\u8D6F\u8E4E\u8E4D\u8E53\u8E50\u8E4C\u8E47\u8F43\u8F40\u9085\u907E\u9138\u919A\u91A2\u919B\u9199\u919F\u91A1\u919D\u91A0\u93A1\u9383\u93AF\u9364\u9356\u9347\u937C\u9358\u935C\u9376\u9349\u9350\u9351\u9360\u936D\u938F\u934C\u936A\u9379\u9357\u9355\u9352\u934F\u9371\u9377\u937B\u9361\u935E\u9363\u9367\u9380\u934E\u9359\u95C7\u95C0\u95C9\u95C3\u95C5\u95B7\u96AE\u96B0\u96AC\u9720\u971F\u9718\u971D\u9719\u979A\u97A1\u979C"],
      ["ef40", "\u979E\u979D\u97D5\u97D4\u97F1\u9841\u9844\u984A\u9849\u9845\u9843\u9925\u992B\u992C\u992A\u9933\u9932\u992F\u992D\u9931\u9930\u9998\u99A3\u99A1\u9A02\u99FA\u99F4\u99F7\u99F9\u99F8\u99F6\u99FB\u99FD\u99FE\u99FC\u9A03\u9ABE\u9AFE\u9AFD\u9B01\u9AFC\u9B48\u9B9A\u9BA8\u9B9E\u9B9B\u9BA6\u9BA1\u9BA5\u9BA4\u9B86\u9BA2\u9BA0\u9BAF\u9D33\u9D41\u9D67\u9D36\u9D2E\u9D2F\u9D31\u9D38\u9D30"],
      ["efa1", "\u9D45\u9D42\u9D43\u9D3E\u9D37\u9D40\u9D3D\u7FF5\u9D2D\u9E8A\u9E89\u9E8D\u9EB0\u9EC8\u9EDA\u9EFB\u9EFF\u9F24\u9F23\u9F22\u9F54\u9FA0\u5131\u512D\u512E\u5698\u569C\u5697\u569A\u569D\u5699\u5970\u5B3C\u5C69\u5C6A\u5DC0\u5E6D\u5E6E\u61D8\u61DF\u61ED\u61EE\u61F1\u61EA\u61F0\u61EB\u61D6\u61E9\u64FF\u6504\u64FD\u64F8\u6501\u6503\u64FC\u6594\u65DB\u66DA\u66DB\u66D8\u6AC5\u6AB9\u6ABD\u6AE1\u6AC6\u6ABA\u6AB6\u6AB7\u6AC7\u6AB4\u6AAD\u6B5E\u6BC9\u6C0B\u7007\u700C\u700D\u7001\u7005\u7014\u700E\u6FFF\u7000\u6FFB\u7026\u6FFC\u6FF7\u700A\u7201\u71FF\u71F9\u7203\u71FD\u7376"],
      ["f040", "\u74B8\u74C0\u74B5\u74C1\u74BE\u74B6\u74BB\u74C2\u7514\u7513\u765C\u7664\u7659\u7650\u7653\u7657\u765A\u76A6\u76BD\u76EC\u77C2\u77BA\u78FF\u790C\u7913\u7914\u7909\u7910\u7912\u7911\u79AD\u79AC\u7A5F\u7C1C\u7C29\u7C19\u7C20\u7C1F\u7C2D\u7C1D\u7C26\u7C28\u7C22\u7C25\u7C30\u7E5C\u7E50\u7E56\u7E63\u7E58\u7E62\u7E5F\u7E51\u7E60\u7E57\u7E53\u7FB5\u7FB3\u7FF7\u7FF8\u8075\u81D1\u81D2"],
      ["f0a1", "\u81D0\u825F\u825E\u85B4\u85C6\u85C0\u85C3\u85C2\u85B3\u85B5\u85BD\u85C7\u85C4\u85BF\u85CB\u85CE\u85C8\u85C5\u85B1\u85B6\u85D2\u8624\u85B8\u85B7\u85BE\u8669\u87E7\u87E6\u87E2\u87DB\u87EB\u87EA\u87E5\u87DF\u87F3\u87E4\u87D4\u87DC\u87D3\u87ED\u87D8\u87E3\u87A4\u87D7\u87D9\u8801\u87F4\u87E8\u87DD\u8953\u894B\u894F\u894C\u8946\u8950\u8951\u8949\u8B2A\u8B27\u8B23\u8B33\u8B30\u8B35\u8B47\u8B2F\u8B3C\u8B3E\u8B31\u8B25\u8B37\u8B26\u8B36\u8B2E\u8B24\u8B3B\u8B3D\u8B3A\u8C42\u8C75\u8C99\u8C98\u8C97\u8CFE\u8D04\u8D02\u8D00\u8E5C\u8E62\u8E60\u8E57\u8E56\u8E5E\u8E65\u8E67"],
      ["f140", "\u8E5B\u8E5A\u8E61\u8E5D\u8E69\u8E54\u8F46\u8F47\u8F48\u8F4B\u9128\u913A\u913B\u913E\u91A8\u91A5\u91A7\u91AF\u91AA\u93B5\u938C\u9392\u93B7\u939B\u939D\u9389\u93A7\u938E\u93AA\u939E\u93A6\u9395\u9388\u9399\u939F\u938D\u93B1\u9391\u93B2\u93A4\u93A8\u93B4\u93A3\u93A5\u95D2\u95D3\u95D1\u96B3\u96D7\u96DA\u5DC2\u96DF\u96D8\u96DD\u9723\u9722\u9725\u97AC\u97AE\u97A8\u97AB\u97A4\u97AA"],
      ["f1a1", "\u97A2\u97A5\u97D7\u97D9\u97D6\u97D8\u97FA\u9850\u9851\u9852\u98B8\u9941\u993C\u993A\u9A0F\u9A0B\u9A09\u9A0D\u9A04\u9A11\u9A0A\u9A05\u9A07\u9A06\u9AC0\u9ADC\u9B08\u9B04\u9B05\u9B29\u9B35\u9B4A\u9B4C\u9B4B\u9BC7\u9BC6\u9BC3\u9BBF\u9BC1\u9BB5\u9BB8\u9BD3\u9BB6\u9BC4\u9BB9\u9BBD\u9D5C\u9D53\u9D4F\u9D4A\u9D5B\u9D4B\u9D59\u9D56\u9D4C\u9D57\u9D52\u9D54\u9D5F\u9D58\u9D5A\u9E8E\u9E8C\u9EDF\u9F01\u9F00\u9F16\u9F25\u9F2B\u9F2A\u9F29\u9F28\u9F4C\u9F55\u5134\u5135\u5296\u52F7\u53B4\u56AB\u56AD\u56A6\u56A7\u56AA\u56AC\u58DA\u58DD\u58DB\u5912\u5B3D\u5B3E\u5B3F\u5DC3\u5E70"],
      ["f240", "\u5FBF\u61FB\u6507\u6510\u650D\u6509\u650C\u650E\u6584\u65DE\u65DD\u66DE\u6AE7\u6AE0\u6ACC\u6AD1\u6AD9\u6ACB\u6ADF\u6ADC\u6AD0\u6AEB\u6ACF\u6ACD\u6ADE\u6B60\u6BB0\u6C0C\u7019\u7027\u7020\u7016\u702B\u7021\u7022\u7023\u7029\u7017\u7024\u701C\u702A\u720C\u720A\u7207\u7202\u7205\u72A5\u72A6\u72A4\u72A3\u72A1\u74CB\u74C5\u74B7\u74C3\u7516\u7660\u77C9\u77CA\u77C4\u77F1\u791D\u791B"],
      ["f2a1", "\u7921\u791C\u7917\u791E\u79B0\u7A67\u7A68\u7C33\u7C3C\u7C39\u7C2C\u7C3B\u7CEC\u7CEA\u7E76\u7E75\u7E78\u7E70\u7E77\u7E6F\u7E7A\u7E72\u7E74\u7E68\u7F4B\u7F4A\u7F83\u7F86\u7FB7\u7FFD\u7FFE\u8078\u81D7\u81D5\u8264\u8261\u8263\u85EB\u85F1\u85ED\u85D9\u85E1\u85E8\u85DA\u85D7\u85EC\u85F2\u85F8\u85D8\u85DF\u85E3\u85DC\u85D1\u85F0\u85E6\u85EF\u85DE\u85E2\u8800\u87FA\u8803\u87F6\u87F7\u8809\u880C\u880B\u8806\u87FC\u8808\u87FF\u880A\u8802\u8962\u895A\u895B\u8957\u8961\u895C\u8958\u895D\u8959\u8988\u89B7\u89B6\u89F6\u8B50\u8B48\u8B4A\u8B40\u8B53\u8B56\u8B54\u8B4B\u8B55"],
      ["f340", "\u8B51\u8B42\u8B52\u8B57\u8C43\u8C77\u8C76\u8C9A\u8D06\u8D07\u8D09\u8DAC\u8DAA\u8DAD\u8DAB\u8E6D\u8E78\u8E73\u8E6A\u8E6F\u8E7B\u8EC2\u8F52\u8F51\u8F4F\u8F50\u8F53\u8FB4\u9140\u913F\u91B0\u91AD\u93DE\u93C7\u93CF\u93C2\u93DA\u93D0\u93F9\u93EC\u93CC\u93D9\u93A9\u93E6\u93CA\u93D4\u93EE\u93E3\u93D5\u93C4\u93CE\u93C0\u93D2\u93E7\u957D\u95DA\u95DB\u96E1\u9729\u972B\u972C\u9728\u9726"],
      ["f3a1", "\u97B3\u97B7\u97B6\u97DD\u97DE\u97DF\u985C\u9859\u985D\u9857\u98BF\u98BD\u98BB\u98BE\u9948\u9947\u9943\u99A6\u99A7\u9A1A\u9A15\u9A25\u9A1D\u9A24\u9A1B\u9A22\u9A20\u9A27\u9A23\u9A1E\u9A1C\u9A14\u9AC2\u9B0B\u9B0A\u9B0E\u9B0C\u9B37\u9BEA\u9BEB\u9BE0\u9BDE\u9BE4\u9BE6\u9BE2\u9BF0\u9BD4\u9BD7\u9BEC\u9BDC\u9BD9\u9BE5\u9BD5\u9BE1\u9BDA\u9D77\u9D81\u9D8A\u9D84\u9D88\u9D71\u9D80\u9D78\u9D86\u9D8B\u9D8C\u9D7D\u9D6B\u9D74\u9D75\u9D70\u9D69\u9D85\u9D73\u9D7B\u9D82\u9D6F\u9D79\u9D7F\u9D87\u9D68\u9E94\u9E91\u9EC0\u9EFC\u9F2D\u9F40\u9F41\u9F4D\u9F56\u9F57\u9F58\u5337\u56B2"],
      ["f440", "\u56B5\u56B3\u58E3\u5B45\u5DC6\u5DC7\u5EEE\u5EEF\u5FC0\u5FC1\u61F9\u6517\u6516\u6515\u6513\u65DF\u66E8\u66E3\u66E4\u6AF3\u6AF0\u6AEA\u6AE8\u6AF9\u6AF1\u6AEE\u6AEF\u703C\u7035\u702F\u7037\u7034\u7031\u7042\u7038\u703F\u703A\u7039\u7040\u703B\u7033\u7041\u7213\u7214\u72A8\u737D\u737C\u74BA\u76AB\u76AA\u76BE\u76ED\u77CC\u77CE\u77CF\u77CD\u77F2\u7925\u7923\u7927\u7928\u7924\u7929"],
      ["f4a1", "\u79B2\u7A6E\u7A6C\u7A6D\u7AF7\u7C49\u7C48\u7C4A\u7C47\u7C45\u7CEE\u7E7B\u7E7E\u7E81\u7E80\u7FBA\u7FFF\u8079\u81DB\u81D9\u820B\u8268\u8269\u8622\u85FF\u8601\u85FE\u861B\u8600\u85F6\u8604\u8609\u8605\u860C\u85FD\u8819\u8810\u8811\u8817\u8813\u8816\u8963\u8966\u89B9\u89F7\u8B60\u8B6A\u8B5D\u8B68\u8B63\u8B65\u8B67\u8B6D\u8DAE\u8E86\u8E88\u8E84\u8F59\u8F56\u8F57\u8F55\u8F58\u8F5A\u908D\u9143\u9141\u91B7\u91B5\u91B2\u91B3\u940B\u9413\u93FB\u9420\u940F\u9414\u93FE\u9415\u9410\u9428\u9419\u940D\u93F5\u9400\u93F7\u9407\u940E\u9416\u9412\u93FA\u9409\u93F8\u940A\u93FF"],
      ["f540", "\u93FC\u940C\u93F6\u9411\u9406\u95DE\u95E0\u95DF\u972E\u972F\u97B9\u97BB\u97FD\u97FE\u9860\u9862\u9863\u985F\u98C1\u98C2\u9950\u994E\u9959\u994C\u994B\u9953\u9A32\u9A34\u9A31\u9A2C\u9A2A\u9A36\u9A29\u9A2E\u9A38\u9A2D\u9AC7\u9ACA\u9AC6\u9B10\u9B12\u9B11\u9C0B\u9C08\u9BF7\u9C05\u9C12\u9BF8\u9C40\u9C07\u9C0E\u9C06\u9C17\u9C14\u9C09\u9D9F\u9D99\u9DA4\u9D9D\u9D92\u9D98\u9D90\u9D9B"],
      ["f5a1", "\u9DA0\u9D94\u9D9C\u9DAA\u9D97\u9DA1\u9D9A\u9DA2\u9DA8\u9D9E\u9DA3\u9DBF\u9DA9\u9D96\u9DA6\u9DA7\u9E99\u9E9B\u9E9A\u9EE5\u9EE4\u9EE7\u9EE6\u9F30\u9F2E\u9F5B\u9F60\u9F5E\u9F5D\u9F59\u9F91\u513A\u5139\u5298\u5297\u56C3\u56BD\u56BE\u5B48\u5B47\u5DCB\u5DCF\u5EF1\u61FD\u651B\u6B02\u6AFC\u6B03\u6AF8\u6B00\u7043\u7044\u704A\u7048\u7049\u7045\u7046\u721D\u721A\u7219\u737E\u7517\u766A\u77D0\u792D\u7931\u792F\u7C54\u7C53\u7CF2\u7E8A\u7E87\u7E88\u7E8B\u7E86\u7E8D\u7F4D\u7FBB\u8030\u81DD\u8618\u862A\u8626\u861F\u8623\u861C\u8619\u8627\u862E\u8621\u8620\u8629\u861E\u8625"],
      ["f640", "\u8829\u881D\u881B\u8820\u8824\u881C\u882B\u884A\u896D\u8969\u896E\u896B\u89FA\u8B79\u8B78\u8B45\u8B7A\u8B7B\u8D10\u8D14\u8DAF\u8E8E\u8E8C\u8F5E\u8F5B\u8F5D\u9146\u9144\u9145\u91B9\u943F\u943B\u9436\u9429\u943D\u943C\u9430\u9439\u942A\u9437\u942C\u9440\u9431\u95E5\u95E4\u95E3\u9735\u973A\u97BF\u97E1\u9864\u98C9\u98C6\u98C0\u9958\u9956\u9A39\u9A3D\u9A46\u9A44\u9A42\u9A41\u9A3A"],
      ["f6a1", "\u9A3F\u9ACD\u9B15\u9B17\u9B18\u9B16\u9B3A\u9B52\u9C2B\u9C1D\u9C1C\u9C2C\u9C23\u9C28\u9C29\u9C24\u9C21\u9DB7\u9DB6\u9DBC\u9DC1\u9DC7\u9DCA\u9DCF\u9DBE\u9DC5\u9DC3\u9DBB\u9DB5\u9DCE\u9DB9\u9DBA\u9DAC\u9DC8\u9DB1\u9DAD\u9DCC\u9DB3\u9DCD\u9DB2\u9E7A\u9E9C\u9EEB\u9EEE\u9EED\u9F1B\u9F18\u9F1A\u9F31\u9F4E\u9F65\u9F64\u9F92\u4EB9\u56C6\u56C5\u56CB\u5971\u5B4B\u5B4C\u5DD5\u5DD1\u5EF2\u6521\u6520\u6526\u6522\u6B0B\u6B08\u6B09\u6C0D\u7055\u7056\u7057\u7052\u721E\u721F\u72A9\u737F\u74D8\u74D5\u74D9\u74D7\u766D\u76AD\u7935\u79B4\u7A70\u7A71\u7C57\u7C5C\u7C59\u7C5B\u7C5A"],
      ["f740", "\u7CF4\u7CF1\u7E91\u7F4F\u7F87\u81DE\u826B\u8634\u8635\u8633\u862C\u8632\u8636\u882C\u8828\u8826\u882A\u8825\u8971\u89BF\u89BE\u89FB\u8B7E\u8B84\u8B82\u8B86\u8B85\u8B7F\u8D15\u8E95\u8E94\u8E9A\u8E92\u8E90\u8E96\u8E97\u8F60\u8F62\u9147\u944C\u9450\u944A\u944B\u944F\u9447\u9445\u9448\u9449\u9446\u973F\u97E3\u986A\u9869\u98CB\u9954\u995B\u9A4E\u9A53\u9A54\u9A4C\u9A4F\u9A48\u9A4A"],
      ["f7a1", "\u9A49\u9A52\u9A50\u9AD0\u9B19\u9B2B\u9B3B\u9B56\u9B55\u9C46\u9C48\u9C3F\u9C44\u9C39\u9C33\u9C41\u9C3C\u9C37\u9C34\u9C32\u9C3D\u9C36\u9DDB\u9DD2\u9DDE\u9DDA\u9DCB\u9DD0\u9DDC\u9DD1\u9DDF\u9DE9\u9DD9\u9DD8\u9DD6\u9DF5\u9DD5\u9DDD\u9EB6\u9EF0\u9F35\u9F33\u9F32\u9F42\u9F6B\u9F95\u9FA2\u513D\u5299\u58E8\u58E7\u5972\u5B4D\u5DD8\u882F\u5F4F\u6201\u6203\u6204\u6529\u6525\u6596\u66EB\u6B11\u6B12\u6B0F\u6BCA\u705B\u705A\u7222\u7382\u7381\u7383\u7670\u77D4\u7C67\u7C66\u7E95\u826C\u863A\u8640\u8639\u863C\u8631\u863B\u863E\u8830\u8832\u882E\u8833\u8976\u8974\u8973\u89FE"],
      ["f840", "\u8B8C\u8B8E\u8B8B\u8B88\u8C45\u8D19\u8E98\u8F64\u8F63\u91BC\u9462\u9455\u945D\u9457\u945E\u97C4\u97C5\u9800\u9A56\u9A59\u9B1E\u9B1F\u9B20\u9C52\u9C58\u9C50\u9C4A\u9C4D\u9C4B\u9C55\u9C59\u9C4C\u9C4E\u9DFB\u9DF7\u9DEF\u9DE3\u9DEB\u9DF8\u9DE4\u9DF6\u9DE1\u9DEE\u9DE6\u9DF2\u9DF0\u9DE2\u9DEC\u9DF4\u9DF3\u9DE8\u9DED\u9EC2\u9ED0\u9EF2\u9EF3\u9F06\u9F1C\u9F38\u9F37\u9F36\u9F43\u9F4F"],
      ["f8a1", "\u9F71\u9F70\u9F6E\u9F6F\u56D3\u56CD\u5B4E\u5C6D\u652D\u66ED\u66EE\u6B13\u705F\u7061\u705D\u7060\u7223\u74DB\u74E5\u77D5\u7938\u79B7\u79B6\u7C6A\u7E97\u7F89\u826D\u8643\u8838\u8837\u8835\u884B\u8B94\u8B95\u8E9E\u8E9F\u8EA0\u8E9D\u91BE\u91BD\u91C2\u946B\u9468\u9469\u96E5\u9746\u9743\u9747\u97C7\u97E5\u9A5E\u9AD5\u9B59\u9C63\u9C67\u9C66\u9C62\u9C5E\u9C60\u9E02\u9DFE\u9E07\u9E03\u9E06\u9E05\u9E00\u9E01\u9E09\u9DFF\u9DFD\u9E04\u9EA0\u9F1E\u9F46\u9F74\u9F75\u9F76\u56D4\u652E\u65B8\u6B18\u6B19\u6B17\u6B1A\u7062\u7226\u72AA\u77D8\u77D9\u7939\u7C69\u7C6B\u7CF6\u7E9A"],
      ["f940", "\u7E98\u7E9B\u7E99\u81E0\u81E1\u8646\u8647\u8648\u8979\u897A\u897C\u897B\u89FF\u8B98\u8B99\u8EA5\u8EA4\u8EA3\u946E\u946D\u946F\u9471\u9473\u9749\u9872\u995F\u9C68\u9C6E\u9C6D\u9E0B\u9E0D\u9E10\u9E0F\u9E12\u9E11\u9EA1\u9EF5\u9F09\u9F47\u9F78\u9F7B\u9F7A\u9F79\u571E\u7066\u7C6F\u883C\u8DB2\u8EA6\u91C3\u9474\u9478\u9476\u9475\u9A60\u9C74\u9C73\u9C71\u9C75\u9E14\u9E13\u9EF6\u9F0A"],
      ["f9a1", "\u9FA4\u7068\u7065\u7CF7\u866A\u883E\u883D\u883F\u8B9E\u8C9C\u8EA9\u8EC9\u974B\u9873\u9874\u98CC\u9961\u99AB\u9A64\u9A66\u9A67\u9B24\u9E15\u9E17\u9F48\u6207\u6B1E\u7227\u864C\u8EA8\u9482\u9480\u9481\u9A69\u9A68\u9B2E\u9E19\u7229\u864B\u8B9F\u9483\u9C79\u9EB7\u7675\u9A6B\u9C7A\u9E1D\u7069\u706A\u9EA4\u9F7E\u9F49\u9F98\u7881\u92B9\u88CF\u58BB\u6052\u7CA7\u5AFA\u2554\u2566\u2557\u2560\u256C\u2563\u255A\u2569\u255D\u2552\u2564\u2555\u255E\u256A\u2561\u2558\u2567\u255B\u2553\u2565\u2556\u255F\u256B\u2562\u2559\u2568\u255C\u2551\u2550\u256D\u256E\u2570\u256F\u2593"]
    ];
  }
});

// packages/core/node_modules/iconv-lite/encodings/tables/big5-added.json
var require_big5_added = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/tables/big5-added.json"(exports2, module2) {
    module2.exports = [
      ["8740", "\u43F0\u4C32\u4603\u45A6\u4578\u{27267}\u4D77\u45B3\u{27CB1}\u4CE2\u{27CC5}\u3B95\u4736\u4744\u4C47\u4C40\u{242BF}\u{23617}\u{27352}\u{26E8B}\u{270D2}\u4C57\u{2A351}\u474F\u45DA\u4C85\u{27C6C}\u4D07\u4AA4\u46A1\u{26B23}\u7225\u{25A54}\u{21A63}\u{23E06}\u{23F61}\u664D\u56FB"],
      ["8767", "\u7D95\u591D\u{28BB9}\u3DF4\u9734\u{27BEF}\u5BDB\u{21D5E}\u5AA4\u3625\u{29EB0}\u5AD1\u5BB7\u5CFC\u676E\u8593\u{29945}\u7461\u749D\u3875\u{21D53}\u{2369E}\u{26021}\u3EEC"],
      ["87a1", "\u{258DE}\u3AF5\u7AFC\u9F97\u{24161}\u{2890D}\u{231EA}\u{20A8A}\u{2325E}\u430A\u8484\u9F96\u942F\u4930\u8613\u5896\u974A\u9218\u79D0\u7A32\u6660\u6A29\u889D\u744C\u7BC5\u6782\u7A2C\u524F\u9046\u34E6\u73C4\u{25DB9}\u74C6\u9FC7\u57B3\u492F\u544C\u4131\u{2368E}\u5818\u7A72\u{27B65}\u8B8F\u46AE\u{26E88}\u4181\u{25D99}\u7BAE\u{224BC}\u9FC8\u{224C1}\u{224C9}\u{224CC}\u9FC9\u8504\u{235BB}\u40B4\u9FCA\u44E1\u{2ADFF}\u62C1\u706E\u9FCB"],
      ["8840", "\u31C0", 4, "\u{2010C}\u31C5\u{200D1}\u{200CD}\u31C6\u31C7\u{200CB}\u{21FE8}\u31C8\u{200CA}\u31C9\u31CA\u31CB\u31CC\u{2010E}\u31CD\u31CE\u0100\xC1\u01CD\xC0\u0112\xC9\u011A\xC8\u014C\xD3\u01D1\xD2\u0FFF\xCA\u0304\u1EBE\u0FFF\xCA\u030C\u1EC0\xCA\u0101\xE1\u01CE\xE0\u0251\u0113\xE9\u011B\xE8\u012B\xED\u01D0\xEC\u014D\xF3\u01D2\xF2\u016B\xFA\u01D4\xF9\u01D6\u01D8\u01DA"],
      ["88a1", "\u01DC\xFC\u0FFF\xEA\u0304\u1EBF\u0FFF\xEA\u030C\u1EC1\xEA\u0261\u23DA\u23DB"],
      ["8940", "\u{2A3A9}\u{21145}"],
      ["8943", "\u650A"],
      ["8946", "\u4E3D\u6EDD\u9D4E\u91DF"],
      ["894c", "\u{27735}\u6491\u4F1A\u4F28\u4FA8\u5156\u5174\u519C\u51E4\u52A1\u52A8\u533B\u534E\u53D1\u53D8\u56E2\u58F0\u5904\u5907\u5932\u5934\u5B66\u5B9E\u5B9F\u5C9A\u5E86\u603B\u6589\u67FE\u6804\u6865\u6D4E\u70BC\u7535\u7EA4\u7EAC\u7EBA\u7EC7\u7ECF\u7EDF\u7F06\u7F37\u827A\u82CF\u836F\u89C6\u8BBE\u8BE2\u8F66\u8F67\u8F6E"],
      ["89a1", "\u7411\u7CFC\u7DCD\u6946\u7AC9\u5227"],
      ["89ab", "\u918C\u78B8\u915E\u80BC"],
      ["89b0", "\u8D0B\u80F6\u{209E7}"],
      ["89b5", "\u809F\u9EC7\u4CCD\u9DC9\u9E0C\u4C3E\u{29DF6}\u{2700E}\u9E0A\u{2A133}\u35C1"],
      ["89c1", "\u6E9A\u823E\u7519"],
      ["89c5", "\u4911\u9A6C\u9A8F\u9F99\u7987\u{2846C}\u{21DCA}\u{205D0}\u{22AE6}\u4E24\u4E81\u4E80\u4E87\u4EBF\u4EEB\u4F37\u344C\u4FBD\u3E48\u5003\u5088\u347D\u3493\u34A5\u5186\u5905\u51DB\u51FC\u5205\u4E89\u5279\u5290\u5327\u35C7\u53A9\u3551\u53B0\u3553\u53C2\u5423\u356D\u3572\u3681\u5493\u54A3\u54B4\u54B9\u54D0\u54EF\u5518\u5523\u5528\u3598\u553F\u35A5\u35BF\u55D7\u35C5"],
      ["8a40", "\u{27D84}\u5525"],
      ["8a43", "\u{20C42}\u{20D15}\u{2512B}\u5590\u{22CC6}\u39EC\u{20341}\u8E46\u{24DB8}\u{294E5}\u4053\u{280BE}\u777A\u{22C38}\u3A34\u47D5\u{2815D}\u{269F2}\u{24DEA}\u64DD\u{20D7C}\u{20FB4}\u{20CD5}\u{210F4}\u648D\u8E7E\u{20E96}\u{20C0B}\u{20F64}\u{22CA9}\u{28256}\u{244D3}"],
      ["8a64", "\u{20D46}\u{29A4D}\u{280E9}\u47F4\u{24EA7}\u{22CC2}\u9AB2\u3A67\u{295F4}\u3FED\u3506\u{252C7}\u{297D4}\u{278C8}\u{22D44}\u9D6E\u9815"],
      ["8a76", "\u43D9\u{260A5}\u64B4\u54E3\u{22D4C}\u{22BCA}\u{21077}\u39FB\u{2106F}"],
      ["8aa1", "\u{266DA}\u{26716}\u{279A0}\u64EA\u{25052}\u{20C43}\u8E68\u{221A1}\u{28B4C}\u{20731}"],
      ["8aac", "\u480B\u{201A9}\u3FFA\u5873\u{22D8D}"],
      ["8ab2", "\u{245C8}\u{204FC}\u{26097}\u{20F4C}\u{20D96}\u5579\u40BB\u43BA"],
      ["8abb", "\u4AB4\u{22A66}\u{2109D}\u81AA\u98F5\u{20D9C}\u6379\u39FE\u{22775}\u8DC0\u56A1\u647C\u3E43"],
      ["8ac9", "\u{2A601}\u{20E09}\u{22ACF}\u{22CC9}"],
      ["8ace", "\u{210C8}\u{239C2}\u3992\u3A06\u{2829B}\u3578\u{25E49}\u{220C7}\u5652\u{20F31}\u{22CB2}\u{29720}\u34BC\u6C3D\u{24E3B}"],
      ["8adf", "\u{27574}\u{22E8B}\u{22208}\u{2A65B}\u{28CCD}\u{20E7A}\u{20C34}\u{2681C}\u7F93\u{210CF}\u{22803}\u{22939}\u35FB\u{251E3}\u{20E8C}\u{20F8D}\u{20EAA}\u3F93\u{20F30}\u{20D47}\u{2114F}\u{20E4C}"],
      ["8af6", "\u{20EAB}\u{20BA9}\u{20D48}\u{210C0}\u{2113D}\u3FF9\u{22696}\u6432\u{20FAD}"],
      ["8b40", "\u{233F4}\u{27639}\u{22BCE}\u{20D7E}\u{20D7F}\u{22C51}\u{22C55}\u3A18\u{20E98}\u{210C7}\u{20F2E}\u{2A632}\u{26B50}\u{28CD2}\u{28D99}\u{28CCA}\u95AA\u54CC\u82C4\u55B9"],
      ["8b55", "\u{29EC3}\u9C26\u9AB6\u{2775E}\u{22DEE}\u7140\u816D\u80EC\u5C1C\u{26572}\u8134\u3797\u535F\u{280BD}\u91B6\u{20EFA}\u{20E0F}\u{20E77}\u{20EFB}\u35DD\u{24DEB}\u3609\u{20CD6}\u56AF\u{227B5}\u{210C9}\u{20E10}\u{20E78}\u{21078}\u{21148}\u{28207}\u{21455}\u{20E79}\u{24E50}\u{22DA4}\u5A54\u{2101D}\u{2101E}\u{210F5}\u{210F6}\u579C\u{20E11}"],
      ["8ba1", "\u{27694}\u{282CD}\u{20FB5}\u{20E7B}\u{2517E}\u3703\u{20FB6}\u{21180}\u{252D8}\u{2A2BD}\u{249DA}\u{2183A}\u{24177}\u{2827C}\u5899\u5268\u361A\u{2573D}\u7BB2\u5B68\u4800\u4B2C\u9F27\u49E7\u9C1F\u9B8D\u{25B74}\u{2313D}\u55FB\u35F2\u5689\u4E28\u5902\u{21BC1}\u{2F878}\u9751\u{20086}\u4E5B\u4EBB\u353E\u5C23\u5F51\u5FC4\u38FA\u624C\u6535\u6B7A\u6C35\u6C3A\u706C\u722B\u4E2C\u72AD\u{248E9}\u7F52\u793B\u7CF9\u7F53\u{2626A}\u34C1"],
      ["8bde", "\u{2634B}\u8002\u8080\u{26612}\u{26951}\u535D\u8864\u89C1\u{278B2}\u8BA0\u8D1D\u9485\u9578\u957F\u95E8\u{28E0F}\u97E6\u9875\u98CE\u98DE\u9963\u{29810}\u9C7C\u9E1F\u9EC4\u6B6F\uF907\u4E37\u{20087}\u961D\u6237\u94A2"],
      ["8c40", "\u503B\u6DFE\u{29C73}\u9FA6\u3DC9\u888F\u{2414E}\u7077\u5CF5\u4B20\u{251CD}\u3559\u{25D30}\u6122\u{28A32}\u8FA7\u91F6\u7191\u6719\u73BA\u{23281}\u{2A107}\u3C8B\u{21980}\u4B10\u78E4\u7402\u51AE\u{2870F}\u4009\u6A63\u{2A2BA}\u4223\u860F\u{20A6F}\u7A2A\u{29947}\u{28AEA}\u9755\u704D\u5324\u{2207E}\u93F4\u76D9\u{289E3}\u9FA7\u77DD\u4EA3\u4FF0\u50BC\u4E2F\u4F17\u9FA8\u5434\u7D8B\u5892\u58D0\u{21DB6}\u5E92\u5E99\u5FC2\u{22712}\u658B"],
      ["8ca1", "\u{233F9}\u6919\u6A43\u{23C63}\u6CFF"],
      ["8ca7", "\u7200\u{24505}\u738C\u3EDB\u{24A13}\u5B15\u74B9\u8B83\u{25CA4}\u{25695}\u7A93\u7BEC\u7CC3\u7E6C\u82F8\u8597\u9FA9\u8890\u9FAA\u8EB9\u9FAB\u8FCF\u855F\u99E0\u9221\u9FAC\u{28DB9}\u{2143F}\u4071\u42A2\u5A1A"],
      ["8cc9", "\u9868\u676B\u4276\u573D"],
      ["8cce", "\u85D6\u{2497B}\u82BF\u{2710D}\u4C81\u{26D74}\u5D7B\u{26B15}\u{26FBE}\u9FAD\u9FAE\u5B96\u9FAF\u66E7\u7E5B\u6E57\u79CA\u3D88\u44C3\u{23256}\u{22796}\u439A\u4536"],
      ["8ce6", "\u5CD5\u{23B1A}\u8AF9\u5C78\u3D12\u{23551}\u5D78\u9FB2\u7157\u4558\u{240EC}\u{21E23}\u4C77\u3978\u344A\u{201A4}\u{26C41}\u8ACC\u4FB4\u{20239}\u59BF\u816C\u9856\u{298FA}\u5F3B"],
      ["8d40", "\u{20B9F}"],
      ["8d42", "\u{221C1}\u{2896D}\u4102\u46BB\u{29079}\u3F07\u9FB3\u{2A1B5}\u40F8\u37D6\u46F7\u{26C46}\u417C\u{286B2}\u{273FF}\u456D\u38D4\u{2549A}\u4561\u451B\u4D89\u4C7B\u4D76\u45EA\u3FC8\u{24B0F}\u3661\u44DE\u44BD\u41ED\u5D3E\u5D48\u5D56\u3DFC\u380F\u5DA4\u5DB9\u3820\u3838\u5E42\u5EBD\u5F25\u5F83\u3908\u3914\u393F\u394D\u60D7\u613D\u5CE5\u3989\u61B7\u61B9\u61CF\u39B8\u622C\u6290\u62E5\u6318\u39F8\u56B1"],
      ["8da1", "\u3A03\u63E2\u63FB\u6407\u645A\u3A4B\u64C0\u5D15\u5621\u9F9F\u3A97\u6586\u3ABD\u65FF\u6653\u3AF2\u6692\u3B22\u6716\u3B42\u67A4\u6800\u3B58\u684A\u6884\u3B72\u3B71\u3B7B\u6909\u6943\u725C\u6964\u699F\u6985\u3BBC\u69D6\u3BDD\u6A65\u6A74\u6A71\u6A82\u3BEC\u6A99\u3BF2\u6AAB\u6AB5\u6AD4\u6AF6\u6B81\u6BC1\u6BEA\u6C75\u6CAA\u3CCB\u6D02\u6D06\u6D26\u6D81\u3CEF\u6DA4\u6DB1\u6E15\u6E18\u6E29\u6E86\u{289C0}\u6EBB\u6EE2\u6EDA\u9F7F\u6EE8\u6EE9\u6F24\u6F34\u3D46\u{23F41}\u6F81\u6FBE\u3D6A\u3D75\u71B7\u5C99\u3D8A\u702C\u3D91\u7050\u7054\u706F\u707F\u7089\u{20325}\u43C1\u35F1\u{20ED8}"],
      ["8e40", "\u{23ED7}\u57BE\u{26ED3}\u713E\u{257E0}\u364E\u69A2\u{28BE9}\u5B74\u7A49\u{258E1}\u{294D9}\u7A65\u7A7D\u{259AC}\u7ABB\u7AB0\u7AC2\u7AC3\u71D1\u{2648D}\u41CA\u7ADA\u7ADD\u7AEA\u41EF\u54B2\u{25C01}\u7B0B\u7B55\u7B29\u{2530E}\u{25CFE}\u7BA2\u7B6F\u839C\u{25BB4}\u{26C7F}\u7BD0\u8421\u7B92\u7BB8\u{25D20}\u3DAD\u{25C65}\u8492\u7BFA\u7C06\u7C35\u{25CC1}\u7C44\u7C83\u{24882}\u7CA6\u667D\u{24578}\u7CC9\u7CC7\u7CE6\u7C74\u7CF3\u7CF5\u7CCE"],
      ["8ea1", "\u7E67\u451D\u{26E44}\u7D5D\u{26ED6}\u748D\u7D89\u7DAB\u7135\u7DB3\u7DD2\u{24057}\u{26029}\u7DE4\u3D13\u7DF5\u{217F9}\u7DE5\u{2836D}\u7E1D\u{26121}\u{2615A}\u7E6E\u7E92\u432B\u946C\u7E27\u7F40\u7F41\u7F47\u7936\u{262D0}\u99E1\u7F97\u{26351}\u7FA3\u{21661}\u{20068}\u455C\u{23766}\u4503\u{2833A}\u7FFA\u{26489}\u8005\u8008\u801D\u8028\u802F\u{2A087}\u{26CC3}\u803B\u803C\u8061\u{22714}\u4989\u{26626}\u{23DE3}\u{266E8}\u6725\u80A7\u{28A48}\u8107\u811A\u58B0\u{226F6}\u6C7F\u{26498}\u{24FB8}\u64E7\u{2148A}\u8218\u{2185E}\u6A53\u{24A65}\u{24A95}\u447A\u8229\u{20B0D}\u{26A52}\u{23D7E}\u4FF9\u{214FD}\u84E2\u8362\u{26B0A}\u{249A7}\u{23530}\u{21773}\u{23DF8}\u82AA\u691B\u{2F994}\u41DB"],
      ["8f40", "\u854B\u82D0\u831A\u{20E16}\u{217B4}\u36C1\u{2317D}\u{2355A}\u827B\u82E2\u8318\u{23E8B}\u{26DA3}\u{26B05}\u{26B97}\u{235CE}\u3DBF\u831D\u55EC\u8385\u450B\u{26DA5}\u83AC\u83C1\u83D3\u347E\u{26ED4}\u6A57\u855A\u3496\u{26E42}\u{22EEF}\u8458\u{25BE4}\u8471\u3DD3\u44E4\u6AA7\u844A\u{23CB5}\u7958\u84A8\u{26B96}\u{26E77}\u{26E43}\u84DE\u840F\u8391\u44A0\u8493\u84E4\u{25C91}\u4240\u{25CC0}\u4543\u8534\u5AF2\u{26E99}\u4527\u8573\u4516\u67BF\u8616"],
      ["8fa1", "\u{28625}\u{2863B}\u85C1\u{27088}\u8602\u{21582}\u{270CD}\u{2F9B2}\u456A\u8628\u3648\u{218A2}\u53F7\u{2739A}\u867E\u8771\u{2A0F8}\u87EE\u{22C27}\u87B1\u87DA\u880F\u5661\u866C\u6856\u460F\u8845\u8846\u{275E0}\u{23DB9}\u{275E4}\u885E\u889C\u465B\u88B4\u88B5\u63C1\u88C5\u7777\u{2770F}\u8987\u898A\u89A6\u89A9\u89A7\u89BC\u{28A25}\u89E7\u{27924}\u{27ABD}\u8A9C\u7793\u91FE\u8A90\u{27A59}\u7AE9\u{27B3A}\u{23F8F}\u4713\u{27B38}\u717C\u8B0C\u8B1F\u{25430}\u{25565}\u8B3F\u8B4C\u8B4D\u8AA9\u{24A7A}\u8B90\u8B9B\u8AAF\u{216DF}\u4615\u884F\u8C9B\u{27D54}\u{27D8F}\u{2F9D4}\u3725\u{27D53}\u8CD6\u{27D98}\u{27DBD}\u8D12\u8D03\u{21910}\u8CDB\u705C\u8D11\u{24CC9}\u3ED0\u8D77"],
      ["9040", "\u8DA9\u{28002}\u{21014}\u{2498A}\u3B7C\u{281BC}\u{2710C}\u7AE7\u8EAD\u8EB6\u8EC3\u92D4\u8F19\u8F2D\u{28365}\u{28412}\u8FA5\u9303\u{2A29F}\u{20A50}\u8FB3\u492A\u{289DE}\u{2853D}\u{23DBB}\u5EF8\u{23262}\u8FF9\u{2A014}\u{286BC}\u{28501}\u{22325}\u3980\u{26ED7}\u9037\u{2853C}\u{27ABE}\u9061\u{2856C}\u{2860B}\u90A8\u{28713}\u90C4\u{286E6}\u90AE\u90FD\u9167\u3AF0\u91A9\u91C4\u7CAC\u{28933}\u{21E89}\u920E\u6C9F\u9241\u9262\u{255B9}\u92B9\u{28AC6}\u{23C9B}\u{28B0C}\u{255DB}"],
      ["90a1", "\u{20D31}\u932C\u936B\u{28AE1}\u{28BEB}\u708F\u5AC3\u{28AE2}\u{28AE5}\u4965\u9244\u{28BEC}\u{28C39}\u{28BFF}\u9373\u945B\u8EBC\u9585\u95A6\u9426\u95A0\u6FF6\u42B9\u{2267A}\u{286D8}\u{2127C}\u{23E2E}\u49DF\u6C1C\u967B\u9696\u416C\u96A3\u{26ED5}\u61DA\u96B6\u78F5\u{28AE0}\u96BD\u53CC\u49A1\u{26CB8}\u{20274}\u{26410}\u{290AF}\u{290E5}\u{24AD1}\u{21915}\u{2330A}\u9731\u8642\u9736\u4A0F\u453D\u4585\u{24AE9}\u7075\u5B41\u971B\u975C\u{291D5}\u9757\u5B4A\u{291EB}\u975F\u9425\u50D0\u{230B7}\u{230BC}\u9789\u979F\u97B1\u97BE\u97C0\u97D2\u97E0\u{2546C}\u97EE\u741C\u{29433}\u97FF\u97F5\u{2941D}\u{2797A}\u4AD1\u9834\u9833\u984B\u9866\u3B0E\u{27175}\u3D51\u{20630}\u{2415C}"],
      ["9140", "\u{25706}\u98CA\u98B7\u98C8\u98C7\u4AFF\u{26D27}\u{216D3}\u55B0\u98E1\u98E6\u98EC\u9378\u9939\u{24A29}\u4B72\u{29857}\u{29905}\u99F5\u9A0C\u9A3B\u9A10\u9A58\u{25725}\u36C4\u{290B1}\u{29BD5}\u9AE0\u9AE2\u{29B05}\u9AF4\u4C0E\u9B14\u9B2D\u{28600}\u5034\u9B34\u{269A8}\u38C3\u{2307D}\u9B50\u9B40\u{29D3E}\u5A45\u{21863}\u9B8E\u{2424B}\u9C02\u9BFF\u9C0C\u{29E68}\u9DD4\u{29FB7}\u{2A192}\u{2A1AB}\u{2A0E1}\u{2A123}\u{2A1DF}\u9D7E\u9D83\u{2A134}\u9E0E\u6888"],
      ["91a1", "\u9DC4\u{2215B}\u{2A193}\u{2A220}\u{2193B}\u{2A233}\u9D39\u{2A0B9}\u{2A2B4}\u9E90\u9E95\u9E9E\u9EA2\u4D34\u9EAA\u9EAF\u{24364}\u9EC1\u3B60\u39E5\u3D1D\u4F32\u37BE\u{28C2B}\u9F02\u9F08\u4B96\u9424\u{26DA2}\u9F17\u9F16\u9F39\u569F\u568A\u9F45\u99B8\u{2908B}\u97F2\u847F\u9F62\u9F69\u7ADC\u9F8E\u7216\u4BBE\u{24975}\u{249BB}\u7177\u{249F8}\u{24348}\u{24A51}\u739E\u{28BDA}\u{218FA}\u799F\u{2897E}\u{28E36}\u9369\u93F3\u{28A44}\u92EC\u9381\u93CB\u{2896C}\u{244B9}\u7217\u3EEB\u7772\u7A43\u70D0\u{24473}\u{243F8}\u717E\u{217EF}\u70A3\u{218BE}\u{23599}\u3EC7\u{21885}\u{2542F}\u{217F8}\u3722\u{216FB}\u{21839}\u36E1\u{21774}\u{218D1}\u{25F4B}\u3723\u{216C0}\u575B\u{24A25}\u{213FE}\u{212A8}"],
      ["9240", "\u{213C6}\u{214B6}\u8503\u{236A6}\u8503\u8455\u{24994}\u{27165}\u{23E31}\u{2555C}\u{23EFB}\u{27052}\u44F4\u{236EE}\u{2999D}\u{26F26}\u67F9\u3733\u3C15\u3DE7\u586C\u{21922}\u6810\u4057\u{2373F}\u{240E1}\u{2408B}\u{2410F}\u{26C21}\u54CB\u569E\u{266B1}\u5692\u{20FDF}\u{20BA8}\u{20E0D}\u93C6\u{28B13}\u939C\u4EF8\u512B\u3819\u{24436}\u4EBC\u{20465}\u{2037F}\u4F4B\u4F8A\u{25651}\u5A68\u{201AB}\u{203CB}\u3999\u{2030A}\u{20414}\u3435\u4F29\u{202C0}\u{28EB3}\u{20275}\u8ADA\u{2020C}\u4E98"],
      ["92a1", "\u50CD\u510D\u4FA2\u4F03\u{24A0E}\u{23E8A}\u4F42\u502E\u506C\u5081\u4FCC\u4FE5\u5058\u50FC\u5159\u515B\u515D\u515E\u6E76\u{23595}\u{23E39}\u{23EBF}\u6D72\u{21884}\u{23E89}\u51A8\u51C3\u{205E0}\u44DD\u{204A3}\u{20492}\u{20491}\u8D7A\u{28A9C}\u{2070E}\u5259\u52A4\u{20873}\u52E1\u936E\u467A\u718C\u{2438C}\u{20C20}\u{249AC}\u{210E4}\u69D1\u{20E1D}\u7479\u3EDE\u7499\u7414\u7456\u7398\u4B8E\u{24ABC}\u{2408D}\u53D0\u3584\u720F\u{240C9}\u55B4\u{20345}\u54CD\u{20BC6}\u571D\u925D\u96F4\u9366\u57DD\u578D\u577F\u363E\u58CB\u5A99\u{28A46}\u{216FA}\u{2176F}\u{21710}\u5A2C\u59B8\u928F\u5A7E\u5ACF\u5A12\u{25946}\u{219F3}\u{21861}\u{24295}\u36F5\u6D05\u7443\u5A21\u{25E83}"],
      ["9340", "\u5A81\u{28BD7}\u{20413}\u93E0\u748C\u{21303}\u7105\u4972\u9408\u{289FB}\u93BD\u37A0\u5C1E\u5C9E\u5E5E\u5E48\u{21996}\u{2197C}\u{23AEE}\u5ECD\u5B4F\u{21903}\u{21904}\u3701\u{218A0}\u36DD\u{216FE}\u36D3\u812A\u{28A47}\u{21DBA}\u{23472}\u{289A8}\u5F0C\u5F0E\u{21927}\u{217AB}\u5A6B\u{2173B}\u5B44\u8614\u{275FD}\u8860\u607E\u{22860}\u{2262B}\u5FDB\u3EB8\u{225AF}\u{225BE}\u{29088}\u{26F73}\u61C0\u{2003E}\u{20046}\u{2261B}\u6199\u6198\u6075\u{22C9B}\u{22D07}\u{246D4}\u{2914D}"],
      ["93a1", "\u6471\u{24665}\u{22B6A}\u3A29\u{22B22}\u{23450}\u{298EA}\u{22E78}\u6337\u{2A45B}\u64B6\u6331\u63D1\u{249E3}\u{22D67}\u62A4\u{22CA1}\u643B\u656B\u6972\u3BF4\u{2308E}\u{232AD}\u{24989}\u{232AB}\u550D\u{232E0}\u{218D9}\u{2943F}\u66CE\u{23289}\u{231B3}\u3AE0\u4190\u{25584}\u{28B22}\u{2558F}\u{216FC}\u{2555B}\u{25425}\u78EE\u{23103}\u{2182A}\u{23234}\u3464\u{2320F}\u{23182}\u{242C9}\u668E\u{26D24}\u666B\u4B93\u6630\u{27870}\u{21DEB}\u6663\u{232D2}\u{232E1}\u661E\u{25872}\u38D1\u{2383A}\u{237BC}\u3B99\u{237A2}\u{233FE}\u74D0\u3B96\u678F\u{2462A}\u68B6\u681E\u3BC4\u6ABE\u3863\u{237D5}\u{24487}\u6A33\u6A52\u6AC9\u6B05\u{21912}\u6511\u6898\u6A4C\u3BD7\u6A7A\u6B57\u{23FC0}\u{23C9A}\u93A0\u92F2\u{28BEA}\u{28ACB}"],
      ["9440", "\u9289\u{2801E}\u{289DC}\u9467\u6DA5\u6F0B\u{249EC}\u6D67\u{23F7F}\u3D8F\u6E04\u{2403C}\u5A3D\u6E0A\u5847\u6D24\u7842\u713B\u{2431A}\u{24276}\u70F1\u7250\u7287\u7294\u{2478F}\u{24725}\u5179\u{24AA4}\u{205EB}\u747A\u{23EF8}\u{2365F}\u{24A4A}\u{24917}\u{25FE1}\u3F06\u3EB1\u{24ADF}\u{28C23}\u{23F35}\u60A7\u3EF3\u74CC\u743C\u9387\u7437\u449F\u{26DEA}\u4551\u7583\u3F63\u{24CD9}\u{24D06}\u3F58\u7555\u7673\u{2A5C6}\u3B19\u7468\u{28ACC}\u{249AB}\u{2498E}\u3AFB"],
      ["94a1", "\u3DCD\u{24A4E}\u3EFF\u{249C5}\u{248F3}\u91FA\u5732\u9342\u{28AE3}\u{21864}\u50DF\u{25221}\u{251E7}\u7778\u{23232}\u770E\u770F\u777B\u{24697}\u{23781}\u3A5E\u{248F0}\u7438\u749B\u3EBF\u{24ABA}\u{24AC7}\u40C8\u{24A96}\u{261AE}\u9307\u{25581}\u781E\u788D\u7888\u78D2\u73D0\u7959\u{27741}\u{256E3}\u410E\u799B\u8496\u79A5\u6A2D\u{23EFA}\u7A3A\u79F4\u416E\u{216E6}\u4132\u9235\u79F1\u{20D4C}\u{2498C}\u{20299}\u{23DBA}\u{2176E}\u3597\u556B\u3570\u36AA\u{201D4}\u{20C0D}\u7AE2\u5A59\u{226F5}\u{25AAF}\u{25A9C}\u5A0D\u{2025B}\u78F0\u5A2A\u{25BC6}\u7AFE\u41F9\u7C5D\u7C6D\u4211\u{25BB3}\u{25EBC}\u{25EA6}\u7CCD\u{249F9}\u{217B0}\u7C8E\u7C7C\u7CAE\u6AB2\u7DDC\u7E07\u7DD3\u7F4E\u{26261}"],
      ["9540", "\u{2615C}\u{27B48}\u7D97\u{25E82}\u426A\u{26B75}\u{20916}\u67D6\u{2004E}\u{235CF}\u57C4\u{26412}\u{263F8}\u{24962}\u7FDD\u7B27\u{2082C}\u{25AE9}\u{25D43}\u7B0C\u{25E0E}\u99E6\u8645\u9A63\u6A1C\u{2343F}\u39E2\u{249F7}\u{265AD}\u9A1F\u{265A0}\u8480\u{27127}\u{26CD1}\u44EA\u8137\u4402\u80C6\u8109\u8142\u{267B4}\u98C3\u{26A42}\u8262\u8265\u{26A51}\u8453\u{26DA7}\u8610\u{2721B}\u5A86\u417F\u{21840}\u5B2B\u{218A1}\u5AE4\u{218D8}\u86A0\u{2F9BC}\u{23D8F}\u882D\u{27422}\u5A02"],
      ["95a1", "\u886E\u4F45\u8887\u88BF\u88E6\u8965\u894D\u{25683}\u8954\u{27785}\u{27784}\u{28BF5}\u{28BD9}\u{28B9C}\u{289F9}\u3EAD\u84A3\u46F5\u46CF\u37F2\u8A3D\u8A1C\u{29448}\u5F4D\u922B\u{24284}\u65D4\u7129\u70C4\u{21845}\u9D6D\u8C9F\u8CE9\u{27DDC}\u599A\u77C3\u59F0\u436E\u36D4\u8E2A\u8EA7\u{24C09}\u8F30\u8F4A\u42F4\u6C58\u6FBB\u{22321}\u489B\u6F79\u6E8B\u{217DA}\u9BE9\u36B5\u{2492F}\u90BB\u9097\u5571\u4906\u91BB\u9404\u{28A4B}\u4062\u{28AFC}\u9427\u{28C1D}\u{28C3B}\u84E5\u8A2B\u9599\u95A7\u9597\u9596\u{28D34}\u7445\u3EC2\u{248FF}\u{24A42}\u{243EA}\u3EE7\u{23225}\u968F\u{28EE7}\u{28E66}\u{28E65}\u3ECC\u{249ED}\u{24A78}\u{23FEE}\u7412\u746B\u3EFC\u9741\u{290B0}"],
      ["9640", "\u6847\u4A1D\u{29093}\u{257DF}\u975D\u9368\u{28989}\u{28C26}\u{28B2F}\u{263BE}\u92BA\u5B11\u8B69\u493C\u73F9\u{2421B}\u979B\u9771\u9938\u{20F26}\u5DC1\u{28BC5}\u{24AB2}\u981F\u{294DA}\u92F6\u{295D7}\u91E5\u44C0\u{28B50}\u{24A67}\u{28B64}\u98DC\u{28A45}\u3F00\u922A\u4925\u8414\u993B\u994D\u{27B06}\u3DFD\u999B\u4B6F\u99AA\u9A5C\u{28B65}\u{258C8}\u6A8F\u9A21\u5AFE\u9A2F\u{298F1}\u4B90\u{29948}\u99BC\u4BBD\u4B97\u937D\u5872\u{21302}\u5822\u{249B8}"],
      ["96a1", "\u{214E8}\u7844\u{2271F}\u{23DB8}\u68C5\u3D7D\u9458\u3927\u6150\u{22781}\u{2296B}\u6107\u9C4F\u9C53\u9C7B\u9C35\u9C10\u9B7F\u9BCF\u{29E2D}\u9B9F\u{2A1F5}\u{2A0FE}\u9D21\u4CAE\u{24104}\u9E18\u4CB0\u9D0C\u{2A1B4}\u{2A0ED}\u{2A0F3}\u{2992F}\u9DA5\u84BD\u{26E12}\u{26FDF}\u{26B82}\u85FC\u4533\u{26DA4}\u{26E84}\u{26DF0}\u8420\u85EE\u{26E00}\u{237D7}\u{26064}\u79E2\u{2359C}\u{23640}\u492D\u{249DE}\u3D62\u93DB\u92BE\u9348\u{202BF}\u78B9\u9277\u944D\u4FE4\u3440\u9064\u{2555D}\u783D\u7854\u78B6\u784B\u{21757}\u{231C9}\u{24941}\u369A\u4F72\u6FDA\u6FD9\u701E\u701E\u5414\u{241B5}\u57BB\u58F3\u578A\u9D16\u57D7\u7134\u34AF\u{241AC}\u71EB\u{26C40}\u{24F97}\u5B28\u{217B5}\u{28A49}"],
      ["9740", "\u610C\u5ACE\u5A0B\u42BC\u{24488}\u372C\u4B7B\u{289FC}\u93BB\u93B8\u{218D6}\u{20F1D}\u8472\u{26CC0}\u{21413}\u{242FA}\u{22C26}\u{243C1}\u5994\u{23DB7}\u{26741}\u7DA8\u{2615B}\u{260A4}\u{249B9}\u{2498B}\u{289FA}\u92E5\u73E2\u3EE9\u74B4\u{28B63}\u{2189F}\u3EE1\u{24AB3}\u6AD8\u73F3\u73FB\u3ED6\u{24A3E}\u{24A94}\u{217D9}\u{24A66}\u{203A7}\u{21424}\u{249E5}\u7448\u{24916}\u70A5\u{24976}\u9284\u73E6\u935F\u{204FE}\u9331\u{28ACE}\u{28A16}\u9386\u{28BE7}\u{255D5}\u4935\u{28A82}\u716B"],
      ["97a1", "\u{24943}\u{20CFF}\u56A4\u{2061A}\u{20BEB}\u{20CB8}\u5502\u79C4\u{217FA}\u7DFE\u{216C2}\u{24A50}\u{21852}\u452E\u9401\u370A\u{28AC0}\u{249AD}\u59B0\u{218BF}\u{21883}\u{27484}\u5AA1\u36E2\u{23D5B}\u36B0\u925F\u5A79\u{28A81}\u{21862}\u9374\u3CCD\u{20AB4}\u4A96\u398A\u50F4\u3D69\u3D4C\u{2139C}\u7175\u42FB\u{28218}\u6E0F\u{290E4}\u44EB\u6D57\u{27E4F}\u7067\u6CAF\u3CD6\u{23FED}\u{23E2D}\u6E02\u6F0C\u3D6F\u{203F5}\u7551\u36BC\u34C8\u4680\u3EDA\u4871\u59C4\u926E\u493E\u8F41\u{28C1C}\u{26BC0}\u5812\u57C8\u36D6\u{21452}\u70FE\u{24362}\u{24A71}\u{22FE3}\u{212B0}\u{223BD}\u68B9\u6967\u{21398}\u{234E5}\u{27BF4}\u{236DF}\u{28A83}\u{237D6}\u{233FA}\u{24C9F}\u6A1A\u{236AD}\u{26CB7}\u843E\u44DF\u44CE"],
      ["9840", "\u{26D26}\u{26D51}\u{26C82}\u{26FDE}\u6F17\u{27109}\u833D\u{2173A}\u83ED\u{26C80}\u{27053}\u{217DB}\u5989\u5A82\u{217B3}\u5A61\u5A71\u{21905}\u{241FC}\u372D\u59EF\u{2173C}\u36C7\u718E\u9390\u669A\u{242A5}\u5A6E\u5A2B\u{24293}\u6A2B\u{23EF9}\u{27736}\u{2445B}\u{242CA}\u711D\u{24259}\u{289E1}\u4FB0\u{26D28}\u5CC2\u{244CE}\u{27E4D}\u{243BD}\u6A0C\u{24256}\u{21304}\u70A6\u7133\u{243E9}\u3DA5\u6CDF\u{2F825}\u{24A4F}\u7E65\u59EB\u5D2F\u3DF3\u5F5C\u{24A5D}\u{217DF}\u7DA4\u8426"],
      ["98a1", "\u5485\u{23AFA}\u{23300}\u{20214}\u577E\u{208D5}\u{20619}\u3FE5\u{21F9E}\u{2A2B6}\u7003\u{2915B}\u5D70\u738F\u7CD3\u{28A59}\u{29420}\u4FC8\u7FE7\u72CD\u7310\u{27AF4}\u7338\u7339\u{256F6}\u7341\u7348\u3EA9\u{27B18}\u906C\u71F5\u{248F2}\u73E1\u81F6\u3ECA\u770C\u3ED1\u6CA2\u56FD\u7419\u741E\u741F\u3EE2\u3EF0\u3EF4\u3EFA\u74D3\u3F0E\u3F53\u7542\u756D\u7572\u758D\u3F7C\u75C8\u75DC\u3FC0\u764D\u3FD7\u7674\u3FDC\u767A\u{24F5C}\u7188\u5623\u8980\u5869\u401D\u7743\u4039\u6761\u4045\u35DB\u7798\u406A\u406F\u5C5E\u77BE\u77CB\u58F2\u7818\u70B9\u781C\u40A8\u7839\u7847\u7851\u7866\u8448\u{25535}\u7933\u6803\u7932\u4103"],
      ["9940", "\u4109\u7991\u7999\u8FBB\u7A06\u8FBC\u4167\u7A91\u41B2\u7ABC\u8279\u41C4\u7ACF\u7ADB\u41CF\u4E21\u7B62\u7B6C\u7B7B\u7C12\u7C1B\u4260\u427A\u7C7B\u7C9C\u428C\u7CB8\u4294\u7CED\u8F93\u70C0\u{20CCF}\u7DCF\u7DD4\u7DD0\u7DFD\u7FAE\u7FB4\u729F\u4397\u8020\u8025\u7B39\u802E\u8031\u8054\u3DCC\u57B4\u70A0\u80B7\u80E9\u43ED\u810C\u732A\u810E\u8112\u7560\u8114\u4401\u3B39\u8156\u8159\u815A"],
      ["99a1", "\u4413\u583A\u817C\u8184\u4425\u8193\u442D\u81A5\u57EF\u81C1\u81E4\u8254\u448F\u82A6\u8276\u82CA\u82D8\u82FF\u44B0\u8357\u9669\u698A\u8405\u70F5\u8464\u60E3\u8488\u4504\u84BE\u84E1\u84F8\u8510\u8538\u8552\u453B\u856F\u8570\u85E0\u4577\u8672\u8692\u86B2\u86EF\u9645\u878B\u4606\u4617\u88AE\u88FF\u8924\u8947\u8991\u{27967}\u8A29\u8A38\u8A94\u8AB4\u8C51\u8CD4\u8CF2\u8D1C\u4798\u585F\u8DC3\u47ED\u4EEE\u8E3A\u55D8\u5754\u8E71\u55F5\u8EB0\u4837\u8ECE\u8EE2\u8EE4\u8EED\u8EF2\u8FB7\u8FC1\u8FCA\u8FCC\u9033\u99C4\u48AD\u98E0\u9213\u491E\u9228\u9258\u926B\u92B1\u92AE\u92BF"],
      ["9a40", "\u92E3\u92EB\u92F3\u92F4\u92FD\u9343\u9384\u93AD\u4945\u4951\u9EBF\u9417\u5301\u941D\u942D\u943E\u496A\u9454\u9479\u952D\u95A2\u49A7\u95F4\u9633\u49E5\u67A0\u4A24\u9740\u4A35\u97B2\u97C2\u5654\u4AE4\u60E8\u98B9\u4B19\u98F1\u5844\u990E\u9919\u51B4\u991C\u9937\u9942\u995D\u9962\u4B70\u99C5\u4B9D\u9A3C\u9B0F\u7A83\u9B69\u9B81\u9BDD\u9BF1\u9BF4\u4C6D\u9C20\u376F\u{21BC2}\u9D49\u9C3A"],
      ["9aa1", "\u9EFE\u5650\u9D93\u9DBD\u9DC0\u9DFC\u94F6\u8FB6\u9E7B\u9EAC\u9EB1\u9EBD\u9EC6\u94DC\u9EE2\u9EF1\u9EF8\u7AC8\u9F44\u{20094}\u{202B7}\u{203A0}\u691A\u94C3\u59AC\u{204D7}\u5840\u94C1\u37B9\u{205D5}\u{20615}\u{20676}\u{216BA}\u5757\u7173\u{20AC2}\u{20ACD}\u{20BBF}\u546A\u{2F83B}\u{20BCB}\u549E\u{20BFB}\u{20C3B}\u{20C53}\u{20C65}\u{20C7C}\u60E7\u{20C8D}\u567A\u{20CB5}\u{20CDD}\u{20CED}\u{20D6F}\u{20DB2}\u{20DC8}\u6955\u9C2F\u87A5\u{20E04}\u{20E0E}\u{20ED7}\u{20F90}\u{20F2D}\u{20E73}\u5C20\u{20FBC}\u5E0B\u{2105C}\u{2104F}\u{21076}\u671E\u{2107B}\u{21088}\u{21096}\u3647\u{210BF}\u{210D3}\u{2112F}\u{2113B}\u5364\u84AD\u{212E3}\u{21375}\u{21336}\u8B81\u{21577}\u{21619}\u{217C3}\u{217C7}\u4E78\u70BB\u{2182D}\u{2196A}"],
      ["9b40", "\u{21A2D}\u{21A45}\u{21C2A}\u{21C70}\u{21CAC}\u{21EC8}\u62C3\u{21ED5}\u{21F15}\u7198\u6855\u{22045}\u69E9\u36C8\u{2227C}\u{223D7}\u{223FA}\u{2272A}\u{22871}\u{2294F}\u82FD\u{22967}\u{22993}\u{22AD5}\u89A5\u{22AE8}\u8FA0\u{22B0E}\u97B8\u{22B3F}\u9847\u9ABD\u{22C4C}"],
      ["9b62", "\u{22C88}\u{22CB7}\u{25BE8}\u{22D08}\u{22D12}\u{22DB7}\u{22D95}\u{22E42}\u{22F74}\u{22FCC}\u{23033}\u{23066}\u{2331F}\u{233DE}\u5FB1\u6648\u66BF\u{27A79}\u{23567}\u{235F3}\u7201\u{249BA}\u77D7\u{2361A}\u{23716}\u7E87\u{20346}\u58B5\u670E"],
      ["9ba1", "\u6918\u{23AA7}\u{27657}\u{25FE2}\u{23E11}\u{23EB9}\u{275FE}\u{2209A}\u48D0\u4AB8\u{24119}\u{28A9A}\u{242EE}\u{2430D}\u{2403B}\u{24334}\u{24396}\u{24A45}\u{205CA}\u51D2\u{20611}\u599F\u{21EA8}\u3BBE\u{23CFF}\u{24404}\u{244D6}\u5788\u{24674}\u399B\u{2472F}\u{285E8}\u{299C9}\u3762\u{221C3}\u8B5E\u{28B4E}\u99D6\u{24812}\u{248FB}\u{24A15}\u7209\u{24AC0}\u{20C78}\u5965\u{24EA5}\u{24F86}\u{20779}\u8EDA\u{2502C}\u528F\u573F\u7171\u{25299}\u{25419}\u{23F4A}\u{24AA7}\u55BC\u{25446}\u{2546E}\u{26B52}\u91D4\u3473\u{2553F}\u{27632}\u{2555E}\u4718\u{25562}\u{25566}\u{257C7}\u{2493F}\u{2585D}\u5066\u34FB\u{233CC}\u60DE\u{25903}\u477C\u{28948}\u{25AAE}\u{25B89}\u{25C06}\u{21D90}\u57A1\u7151\u6FB6\u{26102}\u{27C12}\u9056\u{261B2}\u{24F9A}\u8B62\u{26402}\u{2644A}"],
      ["9c40", "\u5D5B\u{26BF7}\u8F36\u{26484}\u{2191C}\u8AEA\u{249F6}\u{26488}\u{23FEF}\u{26512}\u4BC0\u{265BF}\u{266B5}\u{2271B}\u9465\u{257E1}\u6195\u5A27\u{2F8CD}\u4FBB\u56B9\u{24521}\u{266FC}\u4E6A\u{24934}\u9656\u6D8F\u{26CBD}\u3618\u8977\u{26799}\u{2686E}\u{26411}\u{2685E}\u71DF\u{268C7}\u7B42\u{290C0}\u{20A11}\u{26926}\u9104\u{26939}\u7A45\u9DF0\u{269FA}\u9A26\u{26A2D}\u365F\u{26469}\u{20021}\u7983\u{26A34}\u{26B5B}\u5D2C\u{23519}\u83CF\u{26B9D}\u46D0\u{26CA4}\u753B\u8865\u{26DAE}\u58B6"],
      ["9ca1", "\u371C\u{2258D}\u{2704B}\u{271CD}\u3C54\u{27280}\u{27285}\u9281\u{2217A}\u{2728B}\u9330\u{272E6}\u{249D0}\u6C39\u949F\u{27450}\u{20EF8}\u8827\u88F5\u{22926}\u{28473}\u{217B1}\u6EB8\u{24A2A}\u{21820}\u39A4\u36B9\u5C10\u79E3\u453F\u66B6\u{29CAD}\u{298A4}\u8943\u{277CC}\u{27858}\u56D6\u40DF\u{2160A}\u39A1\u{2372F}\u{280E8}\u{213C5}\u71AD\u8366\u{279DD}\u{291A8}\u5A67\u4CB7\u{270AF}\u{289AB}\u{279FD}\u{27A0A}\u{27B0B}\u{27D66}\u{2417A}\u7B43\u797E\u{28009}\u6FB5\u{2A2DF}\u6A03\u{28318}\u53A2\u{26E07}\u93BF\u6836\u975D\u{2816F}\u{28023}\u{269B5}\u{213ED}\u{2322F}\u{28048}\u5D85\u{28C30}\u{28083}\u5715\u9823\u{28949}\u5DAB\u{24988}\u65BE\u69D5\u53D2\u{24AA5}\u{23F81}\u3C11\u6736\u{28090}\u{280F4}\u{2812E}\u{21FA1}\u{2814F}"],
      ["9d40", "\u{28189}\u{281AF}\u{2821A}\u{28306}\u{2832F}\u{2838A}\u35CA\u{28468}\u{286AA}\u48FA\u63E6\u{28956}\u7808\u9255\u{289B8}\u43F2\u{289E7}\u43DF\u{289E8}\u{28B46}\u{28BD4}\u59F8\u{28C09}\u8F0B\u{28FC5}\u{290EC}\u7B51\u{29110}\u{2913C}\u3DF7\u{2915E}\u{24ACA}\u8FD0\u728F\u568B\u{294E7}\u{295E9}\u{295B0}\u{295B8}\u{29732}\u{298D1}\u{29949}\u{2996A}\u{299C3}\u{29A28}\u{29B0E}\u{29D5A}\u{29D9B}\u7E9F\u{29EF8}\u{29F23}\u4CA4\u9547\u{2A293}\u71A2\u{2A2FF}\u4D91\u9012\u{2A5CB}\u4D9C\u{20C9C}\u8FBE\u55C1"],
      ["9da1", "\u8FBA\u{224B0}\u8FB9\u{24A93}\u4509\u7E7F\u6F56\u6AB1\u4EEA\u34E4\u{28B2C}\u{2789D}\u373A\u8E80\u{217F5}\u{28024}\u{28B6C}\u{28B99}\u{27A3E}\u{266AF}\u3DEB\u{27655}\u{23CB7}\u{25635}\u{25956}\u4E9A\u{25E81}\u{26258}\u56BF\u{20E6D}\u8E0E\u5B6D\u{23E88}\u{24C9E}\u63DE\u62D0\u{217F6}\u{2187B}\u6530\u562D\u{25C4A}\u541A\u{25311}\u3DC6\u{29D98}\u4C7D\u5622\u561E\u7F49\u{25ED8}\u5975\u{23D40}\u8770\u4E1C\u{20FEA}\u{20D49}\u{236BA}\u8117\u9D5E\u8D18\u763B\u9C45\u764E\u77B9\u9345\u5432\u8148\u82F7\u5625\u8132\u8418\u80BD\u55EA\u7962\u5643\u5416\u{20E9D}\u35CE\u5605\u55F1\u66F1\u{282E2}\u362D\u7534\u55F0\u55BA\u5497\u5572\u{20C41}\u{20C96}\u5ED0\u{25148}\u{20E76}\u{22C62}"],
      ["9e40", "\u{20EA2}\u9EAB\u7D5A\u55DE\u{21075}\u629D\u976D\u5494\u8CCD\u71F6\u9176\u63FC\u63B9\u63FE\u5569\u{22B43}\u9C72\u{22EB3}\u519A\u34DF\u{20DA7}\u51A7\u544D\u551E\u5513\u7666\u8E2D\u{2688A}\u75B1\u80B6\u8804\u8786\u88C7\u81B6\u841C\u{210C1}\u44EC\u7304\u{24706}\u5B90\u830B\u{26893}\u567B\u{226F4}\u{27D2F}\u{241A3}\u{27D73}\u{26ED0}\u{272B6}\u9170\u{211D9}\u9208\u{23CFC}\u{2A6A9}\u{20EAC}\u{20EF9}\u7266\u{21CA2}\u474E\u{24FC2}\u{27FF9}\u{20FEB}\u40FA"],
      ["9ea1", "\u9C5D\u651F\u{22DA0}\u48F3\u{247E0}\u{29D7C}\u{20FEC}\u{20E0A}\u6062\u{275A3}\u{20FED}"],
      ["9ead", "\u{26048}\u{21187}\u71A3\u7E8E\u9D50\u4E1A\u4E04\u3577\u5B0D\u6CB2\u5367\u36AC\u39DC\u537D\u36A5\u{24618}\u589A\u{24B6E}\u822D\u544B\u57AA\u{25A95}\u{20979}"],
      ["9ec5", "\u3A52\u{22465}\u7374\u{29EAC}\u4D09\u9BED\u{23CFE}\u{29F30}\u4C5B\u{24FA9}\u{2959E}\u{29FDE}\u845C\u{23DB6}\u{272B2}\u{267B3}\u{23720}\u632E\u7D25\u{23EF7}\u{23E2C}\u3A2A\u9008\u52CC\u3E74\u367A\u45E9\u{2048E}\u7640\u5AF0\u{20EB6}\u787A\u{27F2E}\u58A7\u40BF\u567C\u9B8B\u5D74\u7654\u{2A434}\u9E85\u4CE1\u75F9\u37FB\u6119\u{230DA}\u{243F2}"],
      ["9ef5", "\u565D\u{212A9}\u57A7\u{24963}\u{29E06}\u5234\u{270AE}\u35AD\u6C4A\u9D7C"],
      ["9f40", "\u7C56\u9B39\u57DE\u{2176C}\u5C53\u64D3\u{294D0}\u{26335}\u{27164}\u86AD\u{20D28}\u{26D22}\u{24AE2}\u{20D71}"],
      ["9f4f", "\u51FE\u{21F0F}\u5D8E\u9703\u{21DD1}\u9E81\u904C\u7B1F\u9B02\u5CD1\u7BA3\u6268\u6335\u9AFF\u7BCF\u9B2A\u7C7E\u9B2E\u7C42\u7C86\u9C15\u7BFC\u9B09\u9F17\u9C1B\u{2493E}\u9F5A\u5573\u5BC3\u4FFD\u9E98\u4FF2\u5260\u3E06\u52D1\u5767\u5056\u59B7\u5E12\u97C8\u9DAB\u8F5C\u5469\u97B4\u9940\u97BA\u532C\u6130"],
      ["9fa1", "\u692C\u53DA\u9C0A\u9D02\u4C3B\u9641\u6980\u50A6\u7546\u{2176D}\u99DA\u5273"],
      ["9fae", "\u9159\u9681\u915C"],
      ["9fb2", "\u9151\u{28E97}\u637F\u{26D23}\u6ACA\u5611\u918E\u757A\u6285\u{203FC}\u734F\u7C70\u{25C21}\u{23CFD}"],
      ["9fc1", "\u{24919}\u76D6\u9B9D\u4E2A\u{20CD4}\u83BE\u8842"],
      ["9fc9", "\u5C4A\u69C0\u50ED\u577A\u521F\u5DF5\u4ECE\u6C31\u{201F2}\u4F39\u549C\u54DA\u529A\u8D82\u35FE\u5F0C\u35F3"],
      ["9fdb", "\u6B52\u917C\u9FA5\u9B97\u982E\u98B4\u9ABA\u9EA8\u9E84\u717A\u7B14"],
      ["9fe7", "\u6BFA\u8818\u7F78"],
      ["9feb", "\u5620\u{2A64A}\u8E77\u9F53"],
      ["9ff0", "\u8DD4\u8E4F\u9E1C\u8E01\u6282\u{2837D}\u8E28\u8E75\u7AD3\u{24A77}\u7A3E\u78D8\u6CEA\u8A67\u7607"],
      ["a040", "\u{28A5A}\u9F26\u6CCE\u87D6\u75C3\u{2A2B2}\u7853\u{2F840}\u8D0C\u72E2\u7371\u8B2D\u7302\u74F1\u8CEB\u{24ABB}\u862F\u5FBA\u88A0\u44B7"],
      ["a055", "\u{2183B}\u{26E05}"],
      ["a058", "\u8A7E\u{2251B}"],
      ["a05b", "\u60FD\u7667\u9AD7\u9D44\u936E\u9B8F\u87F5"],
      ["a063", "\u880F\u8CF7\u732C\u9721\u9BB0\u35D6\u72B2\u4C07\u7C51\u994A\u{26159}\u6159\u4C04\u9E96\u617D"],
      ["a073", "\u575F\u616F\u62A6\u6239\u62CE\u3A5C\u61E2\u53AA\u{233F5}\u6364\u6802\u35D2"],
      ["a0a1", "\u5D57\u{28BC2}\u8FDA\u{28E39}"],
      ["a0a6", "\u50D9\u{21D46}\u7906\u5332\u9638\u{20F3B}\u4065"],
      ["a0ae", "\u77FE"],
      ["a0b0", "\u7CC2\u{25F1A}\u7CDA\u7A2D\u8066\u8063\u7D4D\u7505\u74F2\u8994\u821A\u670C\u8062\u{27486}\u805B\u74F0\u8103\u7724\u8989\u{267CC}\u7553\u{26ED1}\u87A9\u87CE\u81C8\u878C\u8A49\u8CAD\u8B43\u772B\u74F8\u84DA\u3635\u69B2\u8DA6"],
      ["a0d4", "\u89A9\u7468\u6DB9\u87C1\u{24011}\u74E7\u3DDB\u7176\u60A4\u619C\u3CD1\u7162\u6077"],
      ["a0e2", "\u7F71\u{28B2D}\u7250\u60E9\u4B7E\u5220\u3C18\u{23CC7}\u{25ED7}\u{27656}\u{25531}\u{21944}\u{212FE}\u{29903}\u{26DDC}\u{270AD}\u5CC1\u{261AD}\u{28A0F}\u{23677}\u{200EE}\u{26846}\u{24F0E}\u4562\u5B1F\u{2634C}\u9F50\u9EA6\u{2626B}"],
      ["a3c0", "\u2400", 31, "\u2421"],
      ["c6a1", "\u2460", 9, "\u2474", 9, "\u2170", 9, "\u4E36\u4E3F\u4E85\u4EA0\u5182\u5196\u51AB\u52F9\u5338\u5369\u53B6\u590A\u5B80\u5DDB\u2F33\u5E7F\u5EF4\u5F50\u5F61\u6534\u65E0\u7592\u7676\u8FB5\u96B6\xA8\u02C6\u30FD\u30FE\u309D\u309E\u3003\u4EDD\u3005\u3006\u3007\u30FC\uFF3B\uFF3D\u273D\u3041", 23],
      ["c740", "\u3059", 58, "\u30A1\u30A2\u30A3\u30A4"],
      ["c7a1", "\u30A5", 81, "\u0410", 5, "\u0401\u0416", 4],
      ["c840", "\u041B", 26, "\u0451\u0436", 25, "\u21E7\u21B8\u21B9\u31CF\u{200CC}\u4E5A\u{2008A}\u5202\u4491"],
      ["c8a1", "\u9FB0\u5188\u9FB1\u{27607}"],
      ["c8cd", "\uFFE2\uFFE4\uFF07\uFF02\u3231\u2116\u2121\u309B\u309C\u2E80\u2E84\u2E86\u2E87\u2E88\u2E8A\u2E8C\u2E8D\u2E95\u2E9C\u2E9D\u2EA5\u2EA7\u2EAA\u2EAC\u2EAE\u2EB6\u2EBC\u2EBE\u2EC6\u2ECA\u2ECC\u2ECD\u2ECF\u2ED6\u2ED7\u2EDE\u2EE3"],
      ["c8f5", "\u0283\u0250\u025B\u0254\u0275\u0153\xF8\u014B\u028A\u026A"],
      ["f9fe", "\uFFED"],
      ["fa40", "\u{20547}\u92DB\u{205DF}\u{23FC5}\u854C\u42B5\u73EF\u51B5\u3649\u{24942}\u{289E4}\u9344\u{219DB}\u82EE\u{23CC8}\u783C\u6744\u62DF\u{24933}\u{289AA}\u{202A0}\u{26BB3}\u{21305}\u4FAB\u{224ED}\u5008\u{26D29}\u{27A84}\u{23600}\u{24AB1}\u{22513}\u5029\u{2037E}\u5FA4\u{20380}\u{20347}\u6EDB\u{2041F}\u507D\u5101\u347A\u510E\u986C\u3743\u8416\u{249A4}\u{20487}\u5160\u{233B4}\u516A\u{20BFF}\u{220FC}\u{202E5}\u{22530}\u{2058E}\u{23233}\u{21983}\u5B82\u877D\u{205B3}\u{23C99}\u51B2\u51B8"],
      ["faa1", "\u9D34\u51C9\u51CF\u51D1\u3CDC\u51D3\u{24AA6}\u51B3\u51E2\u5342\u51ED\u83CD\u693E\u{2372D}\u5F7B\u520B\u5226\u523C\u52B5\u5257\u5294\u52B9\u52C5\u7C15\u8542\u52E0\u860D\u{26B13}\u5305\u{28ADE}\u5549\u6ED9\u{23F80}\u{20954}\u{23FEC}\u5333\u5344\u{20BE2}\u6CCB\u{21726}\u681B\u73D5\u604A\u3EAA\u38CC\u{216E8}\u71DD\u44A2\u536D\u5374\u{286AB}\u537E\u537F\u{21596}\u{21613}\u77E6\u5393\u{28A9B}\u53A0\u53AB\u53AE\u73A7\u{25772}\u3F59\u739C\u53C1\u53C5\u6C49\u4E49\u57FE\u53D9\u3AAB\u{20B8F}\u53E0\u{23FEB}\u{22DA3}\u53F6\u{20C77}\u5413\u7079\u552B\u6657\u6D5B\u546D\u{26B53}\u{20D74}\u555D\u548F\u54A4\u47A6\u{2170D}\u{20EDD}\u3DB4\u{20D4D}"],
      ["fb40", "\u{289BC}\u{22698}\u5547\u4CED\u542F\u7417\u5586\u55A9\u5605\u{218D7}\u{2403A}\u4552\u{24435}\u66B3\u{210B4}\u5637\u66CD\u{2328A}\u66A4\u66AD\u564D\u564F\u78F1\u56F1\u9787\u53FE\u5700\u56EF\u56ED\u{28B66}\u3623\u{2124F}\u5746\u{241A5}\u6C6E\u708B\u5742\u36B1\u{26C7E}\u57E6\u{21416}\u5803\u{21454}\u{24363}\u5826\u{24BF5}\u585C\u58AA\u3561\u58E0\u58DC\u{2123C}\u58FB\u5BFF\u5743\u{2A150}\u{24278}\u93D3\u35A1\u591F\u68A6\u36C3\u6E59"],
      ["fba1", "\u{2163E}\u5A24\u5553\u{21692}\u8505\u59C9\u{20D4E}\u{26C81}\u{26D2A}\u{217DC}\u59D9\u{217FB}\u{217B2}\u{26DA6}\u6D71\u{21828}\u{216D5}\u59F9\u{26E45}\u5AAB\u5A63\u36E6\u{249A9}\u5A77\u3708\u5A96\u7465\u5AD3\u{26FA1}\u{22554}\u3D85\u{21911}\u3732\u{216B8}\u5E83\u52D0\u5B76\u6588\u5B7C\u{27A0E}\u4004\u485D\u{20204}\u5BD5\u6160\u{21A34}\u{259CC}\u{205A5}\u5BF3\u5B9D\u4D10\u5C05\u{21B44}\u5C13\u73CE\u5C14\u{21CA5}\u{26B28}\u5C49\u48DD\u5C85\u5CE9\u5CEF\u5D8B\u{21DF9}\u{21E37}\u5D10\u5D18\u5D46\u{21EA4}\u5CBA\u5DD7\u82FC\u382D\u{24901}\u{22049}\u{22173}\u8287\u3836\u3BC2\u5E2E\u6A8A\u5E75\u5E7A\u{244BC}\u{20CD3}\u53A6\u4EB7\u5ED0\u53A8\u{21771}\u5E09\u5EF4\u{28482}"],
      ["fc40", "\u5EF9\u5EFB\u38A0\u5EFC\u683E\u941B\u5F0D\u{201C1}\u{2F894}\u3ADE\u48AE\u{2133A}\u5F3A\u{26888}\u{223D0}\u5F58\u{22471}\u5F63\u97BD\u{26E6E}\u5F72\u9340\u{28A36}\u5FA7\u5DB6\u3D5F\u{25250}\u{21F6A}\u{270F8}\u{22668}\u91D6\u{2029E}\u{28A29}\u6031\u6685\u{21877}\u3963\u3DC7\u3639\u5790\u{227B4}\u7971\u3E40\u609E\u60A4\u60B3\u{24982}\u{2498F}\u{27A53}\u74A4\u50E1\u5AA0\u6164\u8424\u6142\u{2F8A6}\u{26ED2}\u6181\u51F4\u{20656}\u6187\u5BAA\u{23FB7}"],
      ["fca1", "\u{2285F}\u61D3\u{28B9D}\u{2995D}\u61D0\u3932\u{22980}\u{228C1}\u6023\u615C\u651E\u638B\u{20118}\u62C5\u{21770}\u62D5\u{22E0D}\u636C\u{249DF}\u3A17\u6438\u63F8\u{2138E}\u{217FC}\u6490\u6F8A\u{22E36}\u9814\u{2408C}\u{2571D}\u64E1\u64E5\u947B\u3A66\u643A\u3A57\u654D\u6F16\u{24A28}\u{24A23}\u6585\u656D\u655F\u{2307E}\u65B5\u{24940}\u4B37\u65D1\u40D8\u{21829}\u65E0\u65E3\u5FDF\u{23400}\u6618\u{231F7}\u{231F8}\u6644\u{231A4}\u{231A5}\u664B\u{20E75}\u6667\u{251E6}\u6673\u6674\u{21E3D}\u{23231}\u{285F4}\u{231C8}\u{25313}\u77C5\u{228F7}\u99A4\u6702\u{2439C}\u{24A21}\u3B2B\u69FA\u{237C2}\u675E\u6767\u6762\u{241CD}\u{290ED}\u67D7\u44E9\u6822\u6E50\u923C\u6801\u{233E6}\u{26DA0}\u685D"],
      ["fd40", "\u{2346F}\u69E1\u6A0B\u{28ADF}\u6973\u68C3\u{235CD}\u6901\u6900\u3D32\u3A01\u{2363C}\u3B80\u67AC\u6961\u{28A4A}\u42FC\u6936\u6998\u3BA1\u{203C9}\u8363\u5090\u69F9\u{23659}\u{2212A}\u6A45\u{23703}\u6A9D\u3BF3\u67B1\u6AC8\u{2919C}\u3C0D\u6B1D\u{20923}\u60DE\u6B35\u6B74\u{227CD}\u6EB5\u{23ADB}\u{203B5}\u{21958}\u3740\u5421\u{23B5A}\u6BE1\u{23EFC}\u6BDC\u6C37\u{2248B}\u{248F1}\u{26B51}\u6C5A\u8226\u6C79\u{23DBC}\u44C5\u{23DBD}\u{241A4}\u{2490C}\u{24900}"],
      ["fda1", "\u{23CC9}\u36E5\u3CEB\u{20D32}\u9B83\u{231F9}\u{22491}\u7F8F\u6837\u{26D25}\u{26DA1}\u{26DEB}\u6D96\u6D5C\u6E7C\u6F04\u{2497F}\u{24085}\u{26E72}\u8533\u{26F74}\u51C7\u6C9C\u6E1D\u842E\u{28B21}\u6E2F\u{23E2F}\u7453\u{23F82}\u79CC\u6E4F\u5A91\u{2304B}\u6FF8\u370D\u6F9D\u{23E30}\u6EFA\u{21497}\u{2403D}\u4555\u93F0\u6F44\u6F5C\u3D4E\u6F74\u{29170}\u3D3B\u6F9F\u{24144}\u6FD3\u{24091}\u{24155}\u{24039}\u{23FF0}\u{23FB4}\u{2413F}\u51DF\u{24156}\u{24157}\u{24140}\u{261DD}\u704B\u707E\u70A7\u7081\u70CC\u70D5\u70D6\u70DF\u4104\u3DE8\u71B4\u7196\u{24277}\u712B\u7145\u5A88\u714A\u716E\u5C9C\u{24365}\u714F\u9362\u{242C1}\u712C\u{2445A}\u{24A27}\u{24A22}\u71BA\u{28BE8}\u70BD\u720E"],
      ["fe40", "\u9442\u7215\u5911\u9443\u7224\u9341\u{25605}\u722E\u7240\u{24974}\u68BD\u7255\u7257\u3E55\u{23044}\u680D\u6F3D\u7282\u732A\u732B\u{24823}\u{2882B}\u48ED\u{28804}\u7328\u732E\u73CF\u73AA\u{20C3A}\u{26A2E}\u73C9\u7449\u{241E2}\u{216E7}\u{24A24}\u6623\u36C5\u{249B7}\u{2498D}\u{249FB}\u73F7\u7415\u6903\u{24A26}\u7439\u{205C3}\u3ED7\u745C\u{228AD}\u7460\u{28EB2}\u7447\u73E4\u7476\u83B9\u746C\u3730\u7474\u93F1\u6A2C\u7482\u4953\u{24A8C}"],
      ["fea1", "\u{2415F}\u{24A79}\u{28B8F}\u5B46\u{28C03}\u{2189E}\u74C8\u{21988}\u750E\u74E9\u751E\u{28ED9}\u{21A4B}\u5BD7\u{28EAC}\u9385\u754D\u754A\u7567\u756E\u{24F82}\u3F04\u{24D13}\u758E\u745D\u759E\u75B4\u7602\u762C\u7651\u764F\u766F\u7676\u{263F5}\u7690\u81EF\u37F8\u{26911}\u{2690E}\u76A1\u76A5\u76B7\u76CC\u{26F9F}\u8462\u{2509D}\u{2517D}\u{21E1C}\u771E\u7726\u7740\u64AF\u{25220}\u7758\u{232AC}\u77AF\u{28964}\u{28968}\u{216C1}\u77F4\u7809\u{21376}\u{24A12}\u68CA\u78AF\u78C7\u78D3\u96A5\u792E\u{255E0}\u78D7\u7934\u78B1\u{2760C}\u8FB8\u8884\u{28B2B}\u{26083}\u{2261C}\u7986\u8900\u6902\u7980\u{25857}\u799D\u{27B39}\u793C\u79A9\u6E2A\u{27126}\u3EA8\u79C6\u{2910D}\u79D4"]
    ];
  }
});

// packages/core/node_modules/iconv-lite/encodings/dbcs-data.js
var require_dbcs_data = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/dbcs-data.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = {
      // == Japanese/ShiftJIS ====================================================
      // All japanese encodings are based on JIS X set of standards:
      // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
      // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes.
      //              Has several variations in 1978, 1983, 1990 and 1997.
      // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
      // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
      //              2 planes, first is superset of 0208, second - revised 0212.
      //              Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)
      // Byte encodings are:
      //  * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
      //               encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
      //               Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
      //  * EUC-JP:    Up to 3 bytes per character. Used mostly on *nixes.
      //               0x00-0x7F       - lower part of 0201
      //               0x8E, 0xA1-0xDF - upper part of 0201
      //               (0xA1-0xFE)x2   - 0208 plane (94x94).
      //               0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
      //  * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
      //               Used as-is in ISO2022 family.
      //  * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII,
      //                0201-1976 Roman, 0208-1978, 0208-1983.
      //  * ISO2022-JP-1: Adds esc seq for 0212-1990.
      //  * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
      //  * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
      //  * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
      //
      // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
      //
      // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html
      shiftjis: {
        type: "_dbcs",
        table: /* @__PURE__ */ __name(function() {
          return require_shiftjis();
        }, "table"),
        encodeAdd: { "\xA5": 92, "\u203E": 126 },
        encodeSkipVals: [{ from: 60736, to: 63808 }]
      },
      csshiftjis: "shiftjis",
      mskanji: "shiftjis",
      sjis: "shiftjis",
      windows31j: "shiftjis",
      ms31j: "shiftjis",
      xsjis: "shiftjis",
      windows932: "shiftjis",
      ms932: "shiftjis",
      932: "shiftjis",
      cp932: "shiftjis",
      eucjp: {
        type: "_dbcs",
        table: /* @__PURE__ */ __name(function() {
          return require_eucjp();
        }, "table"),
        encodeAdd: { "\xA5": 92, "\u203E": 126 }
      },
      // TODO: KDDI extension to Shift_JIS
      // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
      // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.
      // == Chinese/GBK ==========================================================
      // http://en.wikipedia.org/wiki/GBK
      // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder
      // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
      gb2312: "cp936",
      gb231280: "cp936",
      gb23121980: "cp936",
      csgb2312: "cp936",
      csiso58gb231280: "cp936",
      euccn: "cp936",
      // Microsoft's CP936 is a subset and approximation of GBK.
      windows936: "cp936",
      ms936: "cp936",
      936: "cp936",
      cp936: {
        type: "_dbcs",
        table: /* @__PURE__ */ __name(function() {
          return require_cp936();
        }, "table")
      },
      // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
      gbk: {
        type: "_dbcs",
        table: /* @__PURE__ */ __name(function() {
          return require_cp936().concat(require_gbk_added());
        }, "table")
      },
      xgbk: "gbk",
      isoir58: "gbk",
      // GB18030 is an algorithmic extension of GBK.
      // Main source: https://www.w3.org/TR/encoding/#gbk-encoder
      // http://icu-project.org/docs/papers/gb18030.html
      // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
      // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
      gb18030: {
        type: "_dbcs",
        table: /* @__PURE__ */ __name(function() {
          return require_cp936().concat(require_gbk_added());
        }, "table"),
        gb18030: /* @__PURE__ */ __name(function() {
          return require_gb18030_ranges();
        }, "gb18030"),
        encodeSkipVals: [128],
        encodeAdd: { "\u20AC": 41699 }
      },
      chinese: "gb18030",
      // == Korean ===============================================================
      // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
      windows949: "cp949",
      ms949: "cp949",
      949: "cp949",
      cp949: {
        type: "_dbcs",
        table: /* @__PURE__ */ __name(function() {
          return require_cp949();
        }, "table")
      },
      cseuckr: "cp949",
      csksc56011987: "cp949",
      euckr: "cp949",
      isoir149: "cp949",
      korean: "cp949",
      ksc56011987: "cp949",
      ksc56011989: "cp949",
      ksc5601: "cp949",
      // == Big5/Taiwan/Hong Kong ================================================
      // There are lots of tables for Big5 and cp950. Please see the following links for history:
      // http://moztw.org/docs/big5/  http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
      // Variations, in roughly number of defined chars:
      //  * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
      //  * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
      //  * Big5-2003 (Taiwan standard) almost superset of cp950.
      //  * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
      //  * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard.
      //    many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
      //    Plus, it has 4 combining sequences.
      //    Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
      //    because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
      //    Implementations are not consistent within browsers; sometimes labeled as just big5.
      //    MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
      //    Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
      //    In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
      //    Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
      //                   http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
      //
      // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
      // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.
      windows950: "cp950",
      ms950: "cp950",
      950: "cp950",
      cp950: {
        type: "_dbcs",
        table: /* @__PURE__ */ __name(function() {
          return require_cp950();
        }, "table")
      },
      // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
      big5: "big5hkscs",
      big5hkscs: {
        type: "_dbcs",
        table: /* @__PURE__ */ __name(function() {
          return require_cp950().concat(require_big5_added());
        }, "table"),
        encodeSkipVals: [
          // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of
          // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU.
          // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter.
          36457,
          36463,
          36478,
          36523,
          36532,
          36557,
          36560,
          36695,
          36713,
          36718,
          36811,
          36862,
          36973,
          36986,
          37060,
          37084,
          37105,
          37311,
          37551,
          37552,
          37553,
          37554,
          37585,
          37959,
          38090,
          38361,
          38652,
          39285,
          39798,
          39800,
          39803,
          39878,
          39902,
          39916,
          39926,
          40002,
          40019,
          40034,
          40040,
          40043,
          40055,
          40124,
          40125,
          40144,
          40279,
          40282,
          40388,
          40431,
          40443,
          40617,
          40687,
          40701,
          40800,
          40907,
          41079,
          41180,
          41183,
          36812,
          37576,
          38468,
          38637,
          // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345
          41636,
          41637,
          41639,
          41638,
          41676,
          41678
        ]
      },
      cnbig5: "big5hkscs",
      csbig5: "big5hkscs",
      xxbig5: "big5hkscs"
    };
  }
});

// packages/core/node_modules/iconv-lite/encodings/index.js
var require_encodings = __commonJS({
  "packages/core/node_modules/iconv-lite/encodings/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var mergeModules = require_merge_exports();
    var modules = [
      require_internal(),
      require_utf32(),
      require_utf16(),
      require_utf7(),
      require_sbcs_codec(),
      require_sbcs_data(),
      require_sbcs_data_generated(),
      require_dbcs_codec(),
      require_dbcs_data()
    ];
    for (i4 = 0; i4 < modules.length; i4++) {
      module2 = modules[i4];
      mergeModules(exports2, module2);
    }
    var module2;
    var i4;
  }
});

// packages/core/node_modules/iconv-lite/lib/streams.js
var require_streams2 = __commonJS({
  "packages/core/node_modules/iconv-lite/lib/streams.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Buffer9 = require_safer().Buffer;
    module2.exports = function(streamModule) {
      var Transform2 = streamModule.Transform;
      function IconvLiteEncoderStream(conv, options2) {
        this.conv = conv;
        options2 = options2 || {};
        options2.decodeStrings = false;
        Transform2.call(this, options2);
      }
      __name(IconvLiteEncoderStream, "IconvLiteEncoderStream");
      IconvLiteEncoderStream.prototype = Object.create(Transform2.prototype, {
        constructor: { value: IconvLiteEncoderStream }
      });
      IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {
        if (typeof chunk !== "string") {
          return done(new Error("Iconv encoding stream needs strings as its input."));
        }
        try {
          var res = this.conv.write(chunk);
          if (res && res.length) this.push(res);
          done();
        } catch (e4) {
          done(e4);
        }
      };
      IconvLiteEncoderStream.prototype._flush = function(done) {
        try {
          var res = this.conv.end();
          if (res && res.length) this.push(res);
          done();
        } catch (e4) {
          done(e4);
        }
      };
      IconvLiteEncoderStream.prototype.collect = function(cb) {
        var chunks = [];
        this.on("error", cb);
        this.on("data", function(chunk) {
          chunks.push(chunk);
        });
        this.on("end", function() {
          cb(null, Buffer9.concat(chunks));
        });
        return this;
      };
      function IconvLiteDecoderStream(conv, options2) {
        this.conv = conv;
        options2 = options2 || {};
        options2.encoding = this.encoding = "utf8";
        Transform2.call(this, options2);
      }
      __name(IconvLiteDecoderStream, "IconvLiteDecoderStream");
      IconvLiteDecoderStream.prototype = Object.create(Transform2.prototype, {
        constructor: { value: IconvLiteDecoderStream }
      });
      IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {
        if (!Buffer9.isBuffer(chunk) && !(chunk instanceof Uint8Array)) {
          return done(new Error("Iconv decoding stream needs buffers as its input."));
        }
        try {
          var res = this.conv.write(chunk);
          if (res && res.length) this.push(res, this.encoding);
          done();
        } catch (e4) {
          done(e4);
        }
      };
      IconvLiteDecoderStream.prototype._flush = function(done) {
        try {
          var res = this.conv.end();
          if (res && res.length) this.push(res, this.encoding);
          done();
        } catch (e4) {
          done(e4);
        }
      };
      IconvLiteDecoderStream.prototype.collect = function(cb) {
        var res = "";
        this.on("error", cb);
        this.on("data", function(chunk) {
          res += chunk;
        });
        this.on("end", function() {
          cb(null, res);
        });
        return this;
      };
      return {
        IconvLiteEncoderStream,
        IconvLiteDecoderStream
      };
    };
  }
});

// packages/core/node_modules/iconv-lite/lib/index.js
var require_lib = __commonJS({
  "packages/core/node_modules/iconv-lite/lib/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var Buffer9 = require_safer().Buffer;
    var bomHandling = require_bom_handling();
    var mergeModules = require_merge_exports();
    var iconv = module2.exports;
    iconv.encodings = null;
    iconv.defaultCharUnicode = "\uFFFD";
    iconv.defaultCharSingleByte = "?";
    iconv.encode = /* @__PURE__ */ __name(function encode6(str2, encoding, options2) {
      str2 = "" + (str2 || "");
      var encoder = iconv.getEncoder(encoding, options2);
      var res = encoder.write(str2);
      var trail = encoder.end();
      return trail && trail.length > 0 ? Buffer9.concat([res, trail]) : res;
    }, "encode");
    iconv.decode = /* @__PURE__ */ __name(function decode2(buf, encoding, options2) {
      if (typeof buf === "string") {
        if (!iconv.skipDecodeWarning) {
          console.error("Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding");
          iconv.skipDecodeWarning = true;
        }
        buf = Buffer9.from("" + (buf || ""), "binary");
      }
      var decoder = iconv.getDecoder(encoding, options2);
      var res = decoder.write(buf);
      var trail = decoder.end();
      return trail ? res + trail : res;
    }, "decode");
    iconv.encodingExists = /* @__PURE__ */ __name(function encodingExists(enc) {
      try {
        iconv.getCodec(enc);
        return true;
      } catch (e4) {
        return false;
      }
    }, "encodingExists");
    iconv.toEncoding = iconv.encode;
    iconv.fromEncoding = iconv.decode;
    iconv._codecDataCache = { __proto__: null };
    iconv.getCodec = /* @__PURE__ */ __name(function getCodec(encoding) {
      if (!iconv.encodings) {
        var raw2 = require_encodings();
        iconv.encodings = { __proto__: null };
        mergeModules(iconv.encodings, raw2);
      }
      var enc = iconv._canonicalizeEncoding(encoding);
      var codecOptions = {};
      while (true) {
        var codec = iconv._codecDataCache[enc];
        if (codec) {
          return codec;
        }
        var codecDef = iconv.encodings[enc];
        switch (typeof codecDef) {
          case "string":
            enc = codecDef;
            break;
          case "object":
            for (var key in codecDef) {
              codecOptions[key] = codecDef[key];
            }
            if (!codecOptions.encodingName) {
              codecOptions.encodingName = enc;
            }
            enc = codecDef.type;
            break;
          case "function":
            if (!codecOptions.encodingName) {
              codecOptions.encodingName = enc;
            }
            codec = new codecDef(codecOptions, iconv);
            iconv._codecDataCache[codecOptions.encodingName] = codec;
            return codec;
          default:
            throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '" + enc + "')");
        }
      }
    }, "getCodec");
    iconv._canonicalizeEncoding = function(encoding) {
      return ("" + encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "");
    };
    iconv.getEncoder = /* @__PURE__ */ __name(function getEncoder(encoding, options2) {
      var codec = iconv.getCodec(encoding);
      var encoder = new codec.encoder(options2, codec);
      if (codec.bomAware && options2 && options2.addBOM) {
        encoder = new bomHandling.PrependBOM(encoder, options2);
      }
      return encoder;
    }, "getEncoder");
    iconv.getDecoder = /* @__PURE__ */ __name(function getDecoder2(encoding, options2) {
      var codec = iconv.getCodec(encoding);
      var decoder = new codec.decoder(options2, codec);
      if (codec.bomAware && !(options2 && options2.stripBOM === false)) {
        decoder = new bomHandling.StripBOM(decoder, options2);
      }
      return decoder;
    }, "getDecoder");
    iconv.enableStreamingAPI = /* @__PURE__ */ __name(function enableStreamingAPI(streamModule2) {
      if (iconv.supportsStreams) {
        return;
      }
      var streams = require_streams2()(streamModule2);
      iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream;
      iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream;
      iconv.encodeStream = /* @__PURE__ */ __name(function encodeStream(encoding, options2) {
        return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options2), options2);
      }, "encodeStream");
      iconv.decodeStream = /* @__PURE__ */ __name(function decodeStream(encoding, options2) {
        return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options2), options2);
      }, "decodeStream");
      iconv.supportsStreams = true;
    }, "enableStreamingAPI");
    var streamModule;
    try {
      streamModule = __require("stream");
    } catch (e4) {
    }
    if (streamModule && streamModule.Transform) {
      iconv.enableStreamingAPI(streamModule);
    } else {
      iconv.encodeStream = iconv.decodeStream = function() {
        throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it.");
      };
    }
    if (false) {
      console.error("iconv-lite warning: js files use non-utf8 encoding. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info.");
    }
  }
});

// packages/core/dist/src/utils/iconvHelper.js
function iconvDecode(buffer, encoding) {
  return iconvLite.decode(buffer, encoding);
}
function iconvEncode(content, encoding) {
  return iconvLite.encode(content, encoding);
}
function iconvEncodingExists(encoding) {
  return iconvLite.encodingExists(encoding);
}
function isUtf8CompatibleEncoding(encoding) {
  const lower3 = encoding.toLowerCase().replace(/[^a-z0-9]/g, "");
  return lower3 === "utf8" || lower3 === "ascii" || lower3 === "usascii";
}
var import_iconv_lite, iconvLite;
var init_iconvHelper = __esm({
  "packages/core/dist/src/utils/iconvHelper.js"() {
    "use strict";
    init_esbuild_shims();
    import_iconv_lite = __toESM(require_lib(), 1);
    iconvLite = import_iconv_lite.default;
    __name(iconvDecode, "iconvDecode");
    __name(iconvEncode, "iconvEncode");
    __name(iconvEncodingExists, "iconvEncodingExists");
    __name(isUtf8CompatibleEncoding, "isUtf8CompatibleEncoding");
  }
});

// packages/core/dist/src/memory/const.js
function setGeminiMdFilename(newFilename) {
  if (Array.isArray(newFilename)) {
    if (newFilename.length > 0) {
      currentGeminiMdFilename = newFilename.map((name4) => name4.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];
}
var QWEN_CONFIG_DIR, DEFAULT_CONTEXT_FILENAME, AGENT_CONTEXT_FILENAME, MEMORY_SECTION_HEADER, currentGeminiMdFilename;
var init_const = __esm({
  "packages/core/dist/src/memory/const.js"() {
    "use strict";
    init_esbuild_shims();
    QWEN_CONFIG_DIR = ".qwen";
    DEFAULT_CONTEXT_FILENAME = "QWEN.md";
    AGENT_CONTEXT_FILENAME = "AGENTS.md";
    MEMORY_SECTION_HEADER = "## Qwen Added Memories";
    currentGeminiMdFilename = [
      DEFAULT_CONTEXT_FILENAME,
      AGENT_CONTEXT_FILENAME
    ];
    __name(setGeminiMdFilename, "setGeminiMdFilename");
    __name(getCurrentGeminiMdFilename, "getCurrentGeminiMdFilename");
    __name(getAllGeminiMdFilenames, "getAllGeminiMdFilenames");
  }
});

// packages/core/dist/src/utils/ignorePatterns.js
import path8 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 = path8.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_const();
    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) {
          for (const filename of getAllGeminiMdFilenames()) {
            patterns.push(`**/${filename}`);
          }
        }
        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();
  }
});

// node_modules/chardet/lib/fs/node.js
var require_node2 = __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_ascii = __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 i4 = 0; i4 < det.rawLen; i4++) {
          const b2 = input[i4];
          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_utf8 = __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 i4 = 0; i4 < det.rawLen; i4++) {
          const b2 = input[i4];
          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 (; ; ) {
            i4++;
            if (i4 >= det.rawLen)
              break;
            if ((input[i4] & 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 i4 = 0; i4 < limit2; i4 += 4) {
          const ch = this.getChar(input, i4);
          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 i4 = ngrams.length - 1; i4 >= 0; i4--) {
          const ngl = ngrams[i4];
          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 i4, j2;
        let escN;
        let hits = 0;
        let misses = 0;
        let shifts = 0;
        let confidence;
        const text = det.inputBytes;
        const textLen = det.inputLen;
        scanInput: for (i4 = 0; i4 < textLen; i4++) {
          if (text[i4] == 27) {
            checkEscapes: for (escN = 0; escN < this.escapeSequences.length; escN++) {
              const seq = this.escapeSequences[escN];
              if (textLen - i4 < seq.length)
                continue checkEscapes;
              for (j2 = 1; j2 < seq.length; j2++)
                if (seq[j2] != text[i4 + j2])
                  continue checkEscapes;
              hits++;
              i4 += seq.length - 1;
              continue scanInput;
            }
            misses++;
          }
          if (text[i4] == 14 || text[i4] == 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_utils3 = __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_lib2 = __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), i4 = 0; i4 < k2.length; i4++) if (k2[i4] !== "default") __createBinding(result, mod2, k2[i4]);
        }
        __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_node2());
    var ascii_1 = __importDefault(require_ascii());
    var utf8_1 = __importDefault(require_utf8());
    var unicode2 = __importStar(require_unicode());
    var mbcs = __importStar(require_mbcs());
    var sbcs = __importStar(require_sbcs());
    var iso2022 = __importStar(require_iso2022());
    var utils_1 = require_utils3();
    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 matches2 = (0, exports2.analyse)(buffer);
      return matches2.length > 0 ? matches2[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 i4 = 0; i4 < 256; i4++)
        byteStats[i4] = 0;
      for (let i4 = buffer.length - 1; i4 >= 0; i4--)
        byteStats[buffer[i4] & 255]++;
      let c1Bytes = false;
      for (let i4 = 128; i4 <= 159; i4 += 1) {
        if (byteStats[i4] !== 0) {
          c1Bytes = true;
          break;
        }
      }
      const context2 = {
        byteStats,
        c1Bytes,
        rawInput: buffer,
        rawLen: buffer.length,
        inputBytes: buffer,
        inputLen: buffer.length
      };
      const matches2 = recognisers.map((rec) => {
        return rec.match(context2);
      }).filter((match2) => {
        return !!match2;
      }).sort((a2, b2) => {
        return b2.confidence - a2.confidence;
      });
      return matches2;
    }, "analyse");
    exports2.analyse = analyse;
    var detectFile = /* @__PURE__ */ __name((filepath, opts = {}) => new Promise((resolve42, reject) => {
      let fd;
      const fs142 = (0, node_1.default)();
      const handler = /* @__PURE__ */ __name((err2, buffer) => {
        if (fd) {
          fs142.closeSync(fd);
        }
        if (err2) {
          reject(err2);
        } else {
          resolve42((0, exports2.detect)(buffer));
        }
      }, "handler");
      if (opts && opts.sampleSize) {
        fd = fs142.openSync(filepath, "r");
        const sample = Buffer.allocUnsafe(opts.sampleSize);
        fs142.read(fd, sample, 0, opts.sampleSize, opts.offset, (err2) => {
          handler(err2, sample);
        });
        return;
      }
      fs142.readFile(filepath, handler);
    }), "detectFile");
    exports2.detectFile = detectFile;
    var detectFileSync = /* @__PURE__ */ __name((filepath, opts = {}) => {
      const fs142 = (0, node_1.default)();
      if (opts && opts.sampleSize) {
        const fd = fs142.openSync(filepath, "r");
        const sample = Buffer.allocUnsafe(opts.sampleSize);
        fs142.readSync(fd, sample, 0, opts.sampleSize, opts.offset);
        fs142.closeSync(fd);
        return (0, exports2.detect)(sample);
      }
      return (0, exports2.detect)(fs142.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 { isUtf8 } from "node:buffer";
import { execSync } from "node:child_process";
import os4 from "node:os";
function resetEncodingCache() {
  cachedSystemEncoding = void 0;
}
function getCachedEncodingForBuffer(buffer) {
  if (isUtf8(buffer)) {
    return "utf-8";
  }
  const detected = detectEncodingFromBuffer(buffer);
  if (detected) {
    return detected;
  }
  if (cachedSystemEncoding === void 0) {
    cachedSystemEncoding = getSystemEncoding();
  }
  if (cachedSystemEncoding) {
    return cachedSystemEncoding;
  }
  return "utf-8";
}
function getSystemEncoding() {
  if (os4.platform() === "win32") {
    try {
      const output = execSync("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 (error40) {
      debugLogger4.warn(`Failed to get Windows code page using 'chcp' command: ${error40 instanceof Error ? error40.message : String(error40)}. Will attempt to detect encoding from command output instead.`);
    }
    return null;
  }
  const env6 = process.env;
  let locale = env6["LC_ALL"] || env6["LC_CTYPE"] || env6["LANG"] || "";
  if (!locale) {
    try {
      locale = execSync("locale charmap", { encoding: "utf8" }).toString().trim();
    } catch (_e2) {
      debugLogger4.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 map3 = {
    437: "cp437",
    850: "cp850",
    852: "cp852",
    866: "cp866",
    874: "windows-874",
    932: "shift_jis",
    936: "gbk",
    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 (map3[cp3]) {
    return map3[cp3];
  }
  debugLogger4.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 (error40) {
    debugLogger4.warn("Failed to detect encoding with chardet:", error40);
  }
  return null;
}
var import_chardet, debugLogger4, cachedSystemEncoding;
var init_systemEncoding = __esm({
  "packages/core/dist/src/utils/systemEncoding.js"() {
    "use strict";
    init_esbuild_shims();
    import_chardet = __toESM(require_lib2(), 1);
    init_debugLogger();
    debugLogger4 = createDebugLogger("ENCODING");
    cachedSystemEncoding = void 0;
    __name(resetEncodingCache, "resetEncodingCache");
    __name(getCachedEncodingForBuffer, "getCachedEncodingForBuffer");
    __name(getSystemEncoding, "getSystemEncoding");
    __name(windowsCodePageToEncoding, "windowsCodePageToEncoding");
    __name(detectEncodingFromBuffer, "detectEncodingFromBuffer");
  }
});

// packages/core/dist/src/utils/pdf.js
import { execFile } from "node:child_process";
function execCommand(command2, args2, options2 = {}) {
  return new Promise((resolve42) => {
    execFile(command2, args2, { encoding: "utf8", ...options2 }, (error40, stdout2, stderr) => {
      if (error40) {
        const errAny = error40;
        const maxBufferExceeded = errAny.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
        const timedOut = !maxBufferExceeded && (errAny.code === "ETIMEDOUT" || errAny.killed === true && (errAny.signal === "SIGTERM" || errAny.signal === void 0 || errAny.signal === null));
        resolve42({
          stdout: String(stdout2 ?? ""),
          stderr: String(stderr ?? ""),
          code: typeof error40.code === "number" ? error40.code : 1,
          maxBufferExceeded,
          timedOut
        });
        return;
      }
      resolve42({
        stdout: String(stdout2 ?? ""),
        stderr: String(stderr ?? ""),
        code: 0,
        maxBufferExceeded: false,
        timedOut: false
      });
    });
  });
}
function parsePDFPageRange(pages) {
  const trimmed2 = pages.trim();
  if (!trimmed2) {
    return null;
  }
  const inRange = /* @__PURE__ */ __name((n3) => Number.isFinite(n3) && n3 >= 1 && n3 <= MAX_PDF_PAGE_NUMBER, "inRange");
  const openEnded = /^(\d+)\s*-$/.exec(trimmed2);
  if (openEnded) {
    const first2 = Number(openEnded[1]);
    if (!inRange(first2))
      return null;
    return { firstPage: first2, lastPage: Infinity };
  }
  const range = /^(\d+)\s*-\s*(\d+)$/.exec(trimmed2);
  if (range) {
    const first2 = Number(range[1]);
    const last2 = Number(range[2]);
    if (!inRange(first2) || !inRange(last2) || last2 < first2)
      return null;
    return { firstPage: first2, lastPage: last2 };
  }
  const single = /^(\d+)$/.exec(trimmed2);
  if (single) {
    const page = Number(single[1]);
    if (!inRange(page))
      return null;
    return { firstPage: page, lastPage: page };
  }
  return null;
}
async function isPdftotextAvailable() {
  if (pdftotextAvailable !== void 0)
    return pdftotextAvailable;
  if (pdftotextAvailablePromise)
    return pdftotextAvailablePromise;
  pdftotextAvailablePromise = (async () => {
    try {
      const { code: code2 } = await execCommand("pdftotext", ["-v"], {
        timeout: 5e3
      });
      return code2 === 0;
    } catch {
      return false;
    }
  })().then((result) => {
    pdftotextAvailable = result;
    return result;
  }).finally(() => {
    pdftotextAvailablePromise = void 0;
  });
  return pdftotextAvailablePromise;
}
async function extractPDFText(filePath, options2) {
  const available = await isPdftotextAvailable();
  if (!available) {
    return {
      success: false,
      error: "pdftotext is not installed. Install poppler-utils to enable PDF text extraction (e.g. `apt-get install poppler-utils` or `brew install poppler`)."
    };
  }
  const args2 = ["-layout"];
  if (options2?.firstPage) {
    args2.push("-f", String(options2.firstPage));
  }
  if (options2?.lastPage && options2.lastPage !== Infinity) {
    args2.push("-l", String(options2.lastPage));
  }
  args2.push("--", filePath, "-");
  try {
    const { stdout: stdout2, stderr, code: code2, maxBufferExceeded, timedOut } = await execCommand("pdftotext", args2, {
      timeout: 3e4,
      // Keep the buffer just above MAX_PDF_TEXT_OUTPUT_CHARS — anything
      // past that is going to be truncated anyway, and capping the child
      // prevents unbounded memory use on pathological text-dense PDFs.
      maxBuffer: MAX_PDF_TEXT_OUTPUT_CHARS * 2
    });
    if (timedOut) {
      return {
        success: false,
        error: `pdftotext timed out after 30s. The PDF may be unusually large or complex; try the 'pages' parameter to narrow the range.`
      };
    }
    if (maxBufferExceeded && stdout2.length >= MAX_PDF_TEXT_OUTPUT_CHARS) {
      return {
        success: true,
        text: stdout2.substring(0, MAX_PDF_TEXT_OUTPUT_CHARS) + `

... [text truncated at ${MAX_PDF_TEXT_OUTPUT_CHARS} characters. Use the 'pages' parameter to read specific page ranges.]`
      };
    }
    if (code2 !== 0 || maxBufferExceeded) {
      if (/password/i.test(stderr)) {
        return {
          success: false,
          error: "PDF is password-protected. Please provide an unprotected version."
        };
      }
      if (/damaged|corrupt|invalid/i.test(stderr)) {
        return {
          success: false,
          error: "PDF file is corrupted or invalid."
        };
      }
      return {
        success: false,
        error: `pdftotext failed: ${stderr || "(no stderr)"}`
      };
    }
    if (!stdout2.trim()) {
      return {
        success: false,
        error: "pdftotext produced no text output. The PDF may contain only images."
      };
    }
    if (stdout2.length > MAX_PDF_TEXT_OUTPUT_CHARS) {
      return {
        success: true,
        text: stdout2.substring(0, MAX_PDF_TEXT_OUTPUT_CHARS) + `

... [text truncated at ${MAX_PDF_TEXT_OUTPUT_CHARS} characters. Use the 'pages' parameter to read specific page ranges.]`
      };
    }
    return { success: true, text: stdout2 };
  } catch (e4) {
    return {
      success: false,
      error: `pdftotext execution failed: ${e4 instanceof Error ? e4.message : String(e4)}`
    };
  }
}
var MAX_PDF_TEXT_OUTPUT_CHARS, MAX_PDF_PAGE_NUMBER, pdftotextAvailable, pdftotextAvailablePromise;
var init_pdf = __esm({
  "packages/core/dist/src/utils/pdf.js"() {
    "use strict";
    init_esbuild_shims();
    MAX_PDF_TEXT_OUTPUT_CHARS = 1e5;
    MAX_PDF_PAGE_NUMBER = 1e6;
    __name(execCommand, "execCommand");
    __name(parsePDFPageRange, "parsePDFPageRange");
    __name(isPdftotextAvailable, "isPdftotextAvailable");
    __name(extractPDFText, "extractPDFText");
  }
});

// packages/core/dist/src/utils/notebook.js
import fs11 from "node:fs";
function stripAnsi(input) {
  return input.replace(ANSI_ESCAPE_RE, "");
}
function sanitizeMimeTypes(keys) {
  return keys.filter((k2) => MIME_TYPE_RE.test(k2));
}
function normalizeSource(source2) {
  return Array.isArray(source2) ? source2.join("") : source2;
}
function processOutputText(text) {
  if (!text)
    return "";
  return Array.isArray(text) ? text.join("") : text;
}
function processOutput(output) {
  switch (output.output_type) {
    case "stream":
      return stripAnsi(processOutputText(output.text));
    case "execute_result":
    case "display_data": {
      const textData = output.data?.["text/plain"];
      if (typeof textData === "string")
        return stripAnsi(textData);
      if (Array.isArray(textData))
        return stripAnsi(textData.join(""));
      const mimeTypes = output.data ? sanitizeMimeTypes(Object.keys(output.data)) : [];
      if (mimeTypes.length > 0) {
        return `[non-text output: ${mimeTypes.join(", ")}]`;
      }
      return "";
    }
    case "error": {
      const parts2 = [];
      if (output.ename)
        parts2.push(output.ename);
      if (output.evalue)
        parts2.push(output.evalue);
      if (output.traceback?.length) {
        parts2.push(output.traceback.join("\n"));
      }
      return stripAnsi(parts2.join(": "));
    }
    default:
      return "";
  }
}
function processCell(cell, index, language) {
  const cellId = cell.id ?? `cell-${index}`;
  const source2 = normalizeSource(cell.source);
  const parts2 = [];
  switch (cell.cell_type) {
    case "code": {
      const execLabel = cell.execution_count != null ? ` [${cell.execution_count}]` : "";
      parts2.push(`--- Code Cell ${cellId}${execLabel} ---`);
      parts2.push(`\`\`\`${language}`);
      parts2.push(source2);
      parts2.push("```");
      if (cell.outputs?.length) {
        const outputTexts = cell.outputs.map(processOutput).filter((t5) => t5.length > 0);
        if (outputTexts.length > 0) {
          let combined = outputTexts.join("\n");
          if (combined.length > LARGE_OUTPUT_THRESHOLD) {
            combined = combined.substring(0, LARGE_OUTPUT_THRESHOLD) + `
... [output truncated, total ${combined.length} chars. Use shell: cat <notebook_path> | jq '.cells[${index}].outputs']`;
          }
          parts2.push("Output:");
          parts2.push(combined);
        }
      }
      break;
    }
    case "markdown":
      parts2.push(`--- Markdown Cell ${cellId} ---`);
      parts2.push(source2);
      break;
    case "raw":
      parts2.push(`--- Raw Cell ${cellId} ---`);
      parts2.push(source2);
      break;
    default:
      parts2.push(`--- Cell ${cellId} ---`);
      parts2.push(source2);
      break;
  }
  return parts2.join("\n");
}
async function readNotebook(filePath) {
  const raw2 = await fs11.promises.readFile(filePath, "utf-8");
  const notebook = JSON.parse(raw2);
  const language = notebook.metadata?.language_info?.name ?? notebook.metadata?.kernelspec?.language ?? "python";
  if (!notebook.cells || notebook.cells.length === 0) {
    return "(empty notebook)";
  }
  const header = `Jupyter Notebook (${language}, ${notebook.cells.length} cells)`;
  const cellTexts = [];
  let totalLength = header.length;
  for (let i4 = 0; i4 < notebook.cells.length; i4++) {
    const cellText = processCell(notebook.cells[i4], i4, language);
    totalLength += cellText.length + 2;
    if (totalLength > MAX_NOTEBOOK_OUTPUT_CHARS) {
      cellTexts.push(`... [${notebook.cells.length - i4} remaining cells truncated, total ${notebook.cells.length} cells. Use shell to inspect: cat <path> | jq '.cells[${i4}:]']`);
      break;
    }
    cellTexts.push(cellText);
  }
  return `${header}

${cellTexts.join("\n\n")}`;
}
var LARGE_OUTPUT_THRESHOLD, MAX_NOTEBOOK_OUTPUT_CHARS, ANSI_ESCAPE_RE, MIME_TYPE_RE;
var init_notebook = __esm({
  "packages/core/dist/src/utils/notebook.js"() {
    "use strict";
    init_esbuild_shims();
    LARGE_OUTPUT_THRESHOLD = 1e4;
    MAX_NOTEBOOK_OUTPUT_CHARS = 1e5;
    ANSI_ESCAPE_RE = /\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P_^X][^\x1B]*\x1B\\|[@-Z\\-_])/g;
    __name(stripAnsi, "stripAnsi");
    MIME_TYPE_RE = /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+(?:\+[A-Za-z0-9!#$&^_.+-]+)?$/;
    __name(sanitizeMimeTypes, "sanitizeMimeTypes");
    __name(normalizeSource, "normalizeSource");
    __name(processOutputText, "processOutputText");
    __name(processOutput, "processOutput");
    __name(processCell, "processCell");
    __name(readNotebook, "readNotebook");
  }
});

// packages/core/dist/src/utils/fileUtils.js
import fs12 from "node:fs";
import fsPromises from "node:fs/promises";
import path9 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 out2 = "";
  for (let i4 = 0; i4 < usable; i4 += 4) {
    const cp3 = littleEndian ? (buf[i4] | buf[i4 + 1] << 8 | buf[i4 + 2] << 16 | buf[i4 + 3] << 24) >>> 0 : (buf[i4 + 3] | buf[i4 + 2] << 8 | buf[i4 + 1] << 16 | buf[i4] << 24) >>> 0;
    if (cp3 <= 1114111 && !(cp3 >= 55296 && cp3 <= 57343)) {
      out2 += String.fromCodePoint(cp3);
    } else {
      out2 += "\uFFFD";
    }
  }
  return out2;
}
function isValidUtf8(buffer) {
  try {
    new TextDecoder("utf-8", { fatal: true }).decode(buffer);
    return true;
  } catch {
    return false;
  }
}
function decodeBOMBuffer(buf, bomInfo) {
  const content = buf.subarray(bomInfo.bomLength);
  switch (bomInfo.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 bomEncodingToName(bomEncoding) {
  switch (bomEncoding) {
    case "utf8":
      return "utf-8";
    case "utf16le":
      return "utf-16le";
    case "utf16be":
      return "utf-16be";
    case "utf32le":
      return "utf-32le";
    case "utf32be":
      return "utf-32be";
    default:
      return "utf-8";
  }
}
async function readFileWithEncodingInfo(filePath) {
  const full = await fs12.promises.readFile(filePath);
  if (full.length === 0)
    return { content: "", encoding: "utf-8", bom: false };
  const bomInfo = detectBOM(full);
  if (bomInfo) {
    return {
      content: decodeBOMBuffer(full, bomInfo),
      encoding: bomEncodingToName(bomInfo.encoding),
      // Mark bom: true for all Unicode BOM variants (UTF-8/16/32) so that
      // the BOM is re-written on save and the file's original format is preserved.
      bom: true
    };
  }
  if (isValidUtf8(full)) {
    return { content: full.toString("utf8"), encoding: "utf-8", bom: false };
  }
  const detected = detectEncodingFromBuffer(full);
  if (detected && !isUtf8CompatibleEncoding(detected)) {
    try {
      if (iconvEncodingExists(detected)) {
        return {
          content: iconvDecode(full, detected),
          encoding: detected,
          bom: false
        };
      }
    } catch (e4) {
      debugLogger5.warn(`Failed to decode file ${filePath} as ${detected}: ${e4 instanceof Error ? e4.message : String(e4)}`);
    }
  }
  return { content: full.toString("utf8"), encoding: "utf-8", bom: false };
}
async function readFileWithEncoding(filePath) {
  const result = await readFileWithEncodingInfo(filePath);
  return result.content;
}
async function countFileLines(filePath) {
  const result = await readFileWithEncodingInfo(filePath);
  return result.content.split("\n").length;
}
async function readFileWithLineAndLimit(params) {
  const { path: filePath, limit: limit2, line } = params;
  const { content, encoding, bom } = await readFileWithEncodingInfo(filePath);
  const lines = content.split("\n");
  const originalLineCount = lines.length;
  const startLine = line || 0;
  const endLine = Math.min(startLine + limit2, originalLineCount);
  const actualStartLine = Math.min(startLine, originalLineCount);
  const selectedLines = lines.slice(actualStartLine, endLine);
  return {
    content: selectedLines.join("\n"),
    bom,
    encoding,
    originalLineCount
  };
}
async function detectFileEncoding(filePath) {
  let fh = null;
  try {
    fh = await fs12.promises.open(filePath, "r");
    const stats = await fh.stat();
    if (stats.size === 0)
      return "utf-8";
    const sampleSize = Math.min(8192, stats.size);
    const buf = Buffer.alloc(sampleSize);
    const { bytesRead } = await fh.read(buf, 0, sampleSize, 0);
    if (bytesRead === 0)
      return "utf-8";
    const sample = buf.subarray(0, bytesRead);
    const bom = detectBOM(sample);
    if (bom) {
      switch (bom.encoding) {
        case "utf8":
          return "utf-8";
        case "utf16le":
          return "utf-16le";
        case "utf16be":
          return "utf-16be";
        case "utf32le":
          return "utf-32le";
        case "utf32be":
          return "utf-32be";
        default:
          return "utf-8";
      }
    }
    if (isValidUtf8(sample))
      return "utf-8";
    const detected = detectEncodingFromBuffer(sample);
    if (detected && !isUtf8CompatibleEncoding(detected)) {
      return detected;
    }
    return "utf-8";
  } catch {
    return "utf-8";
  } finally {
    if (fh) {
      try {
        await fh.close();
      } catch {
      }
    }
  }
}
function getSpecificMimeType(filePath) {
  const lookedUpMime = index_lite_default.getType(filePath);
  return typeof lookedUpMime === "string" ? lookedUpMime : void 0;
}
function isWithinRoot(pathToCheck, rootDirectory) {
  const normalizedPathToCheck = path9.resolve(pathToCheck);
  const normalizedRootDirectory = path9.resolve(rootDirectory);
  const rootWithSeparator = normalizedRootDirectory === path9.sep || normalizedRootDirectory.endsWith(path9.sep) ? normalizedRootDirectory : normalizedRootDirectory + path9.sep;
  return normalizedPathToCheck === normalizedRootDirectory || normalizedPathToCheck.startsWith(rootWithSeparator);
}
async function isBinaryFile(filePath) {
  let fh = null;
  try {
    fh = await fs12.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 i4 = 0; i4 < bytesRead; i4++) {
      if (buf[i4] === 0)
        return true;
      if (buf[i4] < 9 || buf[i4] > 13 && buf[i4] < 32) {
        nonPrintableCount++;
      }
    }
    return nonPrintableCount / bytesRead > 0.3;
  } catch (error40) {
    debugLogger5.warn(`Failed to check if file is binary: ${filePath}`, error40 instanceof Error ? error40.message : String(error40));
    return false;
  } finally {
    if (fh) {
      try {
        await fh.close();
      } catch (closeError) {
        debugLogger5.warn(`Failed to close file handle for: ${filePath}`, closeError instanceof Error ? closeError.message : String(closeError));
      }
    }
  }
}
async function detectFileType(filePath) {
  const ext2 = path9.extname(filePath).toLowerCase();
  if ([".ts", ".mts", ".cts"].includes(ext2)) {
    return "text";
  }
  if (ext2 === ".svg") {
    return "svg";
  }
  if (ext2 === ".ipynb") {
    return "notebook";
  }
  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";
}
function mediaModalityKey(fileType) {
  if (fileType === "image" || fileType === "pdf" || fileType === "audio" || fileType === "video") {
    return fileType;
  }
  return void 0;
}
function unsupportedModalityMessage(modality, displayName) {
  const hint = `This model does not support ${modality} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`;
  return `[Unsupported ${modality} file: "${displayName}". ${hint}]`;
}
async function processSingleFileContent(filePath, config2, offset, limit2, pages) {
  const rootDirectory = config2.getTargetDir();
  try {
    let stats;
    try {
      stats = await fs12.promises.stat(filePath);
    } catch (error40) {
      if (isNodeError(error40) && error40.code === "ENOENT") {
        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
        };
      }
      throw error40;
    }
    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
      };
    }
    if (!stats.isFile()) {
      return {
        llmContent: `Cannot read file: ${path9.basename(filePath)} is not a regular file (e.g. device, socket, or pipe).`,
        returnDisplay: "Not a regular file.",
        error: `Not a regular file: ${filePath}`,
        errorType: ToolErrorType.READ_CONTENT_FAILURE
      };
    }
    const fileType = await detectFileType(filePath);
    const relativePathForDisplay = path9.relative(rootDirectory, filePath).replace(/\\/g, "/");
    const displayName = path9.basename(filePath);
    const modalities = config2.getContentGeneratorConfig?.()?.modalities ?? {};
    const fileSizeInMB = stats.size / (1024 * 1024);
    const willExtractPdfText = fileType === "pdf" && (pages !== void 0 || !modalities.pdf);
    if (willExtractPdfText && fileSizeInMB > PDF_EXTRACTION_MAX_MB) {
      return {
        llmContent: `PDF file is too large for text extraction: ${fileSizeInMB.toFixed(2)}MB exceeds the ${PDF_EXTRACTION_MAX_MB}MB limit. Use the 'pages' parameter to read a narrower range, or split the document.`,
        returnDisplay: `PDF file too large (${fileSizeInMB.toFixed(2)}MB > ${PDF_EXTRACTION_MAX_MB}MB).`,
        error: `PDF exceeds extraction size limit: ${filePath} (${fileSizeInMB.toFixed(2)}MB)`,
        errorType: ToolErrorType.FILE_TOO_LARGE
      };
    }
    if (fileSizeInMB > 9.9 && !willExtractPdfText) {
      return {
        llmContent: "File size exceeds the 10MB limit.",
        returnDisplay: "File size exceeds the 10MB limit.",
        error: `File size exceeds the 10MB limit: ${filePath} (${fileSizeInMB.toFixed(2)}MB)`,
        errorType: ToolErrorType.FILE_TOO_LARGE
      };
    }
    const modality = mediaModalityKey(fileType);
    if (modality && modality !== "pdf") {
      if (!modalities[modality]) {
        const message = unsupportedModalityMessage(modality, displayName);
        debugLogger5.warn(`Model '${config2.getModel()}' does not support ${modality} input. Skipping file: ${relativePathForDisplay}`);
        return {
          llmContent: message,
          returnDisplay: `Skipped ${fileType} file: ${relativePathForDisplay} (model doesn't support ${modality} input)`
        };
      }
    }
    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, _meta } = await config2.getFileSystemService().readTextFile({
          path: filePath,
          limit: limit2 ?? config2.getTruncateToolOutputLines(),
          line: offset
        });
        const originalLineCount = _meta?.originalLineCount ?? await countFileLines(filePath);
        const selectedLines = content.split("\n").map((line) => line.trimEnd());
        const startLine = offset || 0;
        const configCharLimit = config2.getTruncateToolOutputThreshold();
        let llmContent = "";
        let contentLengthTruncated = false;
        let linesIncluded = 0;
        if (Number.isFinite(configCharLimit)) {
          const formattedLines = [];
          let currentLength = 0;
          for (const line of selectedLines) {
            const sep13 = linesIncluded > 0 ? 1 : 0;
            linesIncluded++;
            const projectedLength = currentLength + line.length + sep13;
            if (projectedLength <= configCharLimit) {
              formattedLines.push(line);
              currentLength = projectedLength;
            } else {
              const remaining = Math.max(configCharLimit - currentLength - sep13, 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 = startLine + linesIncluded;
        const contentRangeTruncated = startLine > 0 || actualEndLine < originalLineCount;
        const isTruncated = contentRangeTruncated || contentLengthTruncated;
        let returnDisplay = "";
        if (isTruncated) {
          returnDisplay = `Read lines ${startLine + 1}-${actualEndLine} of ${originalLineCount} from ${relativePathForDisplay}`;
          if (contentLengthTruncated) {
            returnDisplay += " (truncated)";
          }
        }
        return {
          llmContent,
          returnDisplay,
          isTruncated,
          originalLineCount,
          linesShown: [startLine + 1, actualEndLine]
        };
      }
      case "image":
      case "audio":
      case "video": {
        const contentBuffer = await fs12.promises.readFile(filePath);
        const base64Data = contentBuffer.toString("base64");
        const base64SizeInMB = base64Data.length / (1024 * 1024);
        if (base64SizeInMB > 9.9) {
          return {
            llmContent: `File exceeds the 10MB data URI limit after base64 encoding (${base64SizeInMB.toFixed(2)}MB encoded).`,
            returnDisplay: `File exceeds the 10MB data URI limit after base64 encoding.`,
            error: `File exceeds the 10MB data URI limit after base64 encoding: ${filePath} (${base64SizeInMB.toFixed(2)}MB encoded)`,
            errorType: ToolErrorType.FILE_TOO_LARGE
          };
        }
        return {
          llmContent: {
            inlineData: {
              data: base64Data,
              mimeType: index_lite_default.getType(filePath) || "application/octet-stream",
              displayName
            }
          },
          returnDisplay: `Read ${fileType} file: ${relativePathForDisplay}`
        };
      }
      case "pdf": {
        if (!pages && modalities.pdf) {
          const contentBuffer = await fs12.promises.readFile(filePath);
          const base64Data = contentBuffer.toString("base64");
          const base64SizeInMB = base64Data.length / (1024 * 1024);
          if (base64SizeInMB > 9.9) {
            return {
              llmContent: `File exceeds the 10MB data URI limit after base64 encoding (${base64SizeInMB.toFixed(2)}MB encoded).`,
              returnDisplay: `File exceeds the 10MB data URI limit after base64 encoding.`,
              error: `File exceeds the 10MB data URI limit after base64 encoding: ${filePath} (${base64SizeInMB.toFixed(2)}MB encoded)`,
              errorType: ToolErrorType.FILE_TOO_LARGE
            };
          }
          return {
            llmContent: {
              inlineData: {
                data: base64Data,
                mimeType: "application/pdf",
                displayName
              }
            },
            returnDisplay: `Read pdf file: ${relativePathForDisplay}`
          };
        }
        const pageRange = pages ? parsePDFPageRange(pages) : void 0;
        const pdfResult = await extractPDFText(filePath, pageRange ?? void 0);
        if (pdfResult.success) {
          const pagesLabel = pages ? ` (pages ${pages})` : "";
          return {
            llmContent: pdfResult.text,
            returnDisplay: `Read pdf as text${pagesLabel}: ${relativePathForDisplay}`
          };
        }
        return {
          llmContent: `[Cannot extract text from PDF: "${displayName}". ${pdfResult.error}]`,
          returnDisplay: `Failed to read pdf: ${relativePathForDisplay}`,
          error: pdfResult.error,
          errorType: ToolErrorType.READ_CONTENT_FAILURE
        };
      }
      case "notebook": {
        try {
          const content = await readNotebook(filePath);
          return {
            llmContent: content,
            returnDisplay: `Read notebook: ${relativePathForDisplay}`
          };
        } catch (e4) {
          const msg = e4 instanceof Error ? e4.message : String(e4);
          return {
            llmContent: `Error parsing notebook ${relativePathForDisplay}: ${msg}`,
            returnDisplay: `Error reading notebook: ${relativePathForDisplay}`,
            error: `Error parsing notebook ${filePath}: ${msg}`,
            errorType: ToolErrorType.READ_CONTENT_FAILURE
          };
        }
      }
      default: {
        const exhaustiveCheck = fileType;
        return {
          llmContent: `Unhandled file type: ${exhaustiveCheck}`,
          returnDisplay: `Skipped unhandled file type: ${relativePathForDisplay}`,
          error: `Unhandled file type for ${filePath}`
        };
      }
    }
  } catch (error40) {
    const errorMessage = error40 instanceof Error ? error40.message : String(error40);
    const displayPath = path9.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, fs12.constants.F_OK);
    return true;
  } catch (_2) {
    return false;
  }
}
var debugLogger5, DEFAULT_ENCODING, PDF_EXTRACTION_MAX_MB;
var init_fileUtils = __esm({
  "packages/core/dist/src/utils/fileUtils.js"() {
    "use strict";
    init_esbuild_shims();
    init_index_lite();
    init_iconvHelper();
    init_tool_error();
    init_ignorePatterns();
    init_debugLogger();
    init_errors();
    init_systemEncoding();
    init_pdf();
    init_notebook();
    debugLogger5 = createDebugLogger("FILE_UTILS");
    DEFAULT_ENCODING = "utf-8";
    PDF_EXTRACTION_MAX_MB = 100;
    __name(detectBOM, "detectBOM");
    __name(decodeUTF16BE, "decodeUTF16BE");
    __name(decodeUTF32, "decodeUTF32");
    __name(isValidUtf8, "isValidUtf8");
    __name(decodeBOMBuffer, "decodeBOMBuffer");
    __name(bomEncodingToName, "bomEncodingToName");
    __name(readFileWithEncodingInfo, "readFileWithEncodingInfo");
    __name(readFileWithEncoding, "readFileWithEncoding");
    __name(countFileLines, "countFileLines");
    __name(readFileWithLineAndLimit, "readFileWithLineAndLimit");
    __name(detectFileEncoding, "detectFileEncoding");
    __name(getSpecificMimeType, "getSpecificMimeType");
    __name(isWithinRoot, "isWithinRoot");
    __name(isBinaryFile, "isBinaryFile");
    __name(detectFileType, "detectFileType");
    __name(mediaModalityKey, "mediaModalityKey");
    __name(unsupportedModalityMessage, "unsupportedModalityMessage");
    __name(processSingleFileContent, "processSingleFileContent");
    __name(fileExists, "fileExists");
  }
});

// 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 VERSION2;
var init_version = __esm({
  "node_modules/@opentelemetry/api/build/esm/version.js"() {
    init_esbuild_shims();
    VERSION2 = "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(VERSION2);
  }
});

// node_modules/@opentelemetry/api/build/esm/internal/global-utils.js
function registerGlobal(type, instance2, 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: VERSION2
  };
  if (!allowOverride && api[type]) {
    var err2 = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
    diag3.error(err2.stack || err2.message);
    return false;
  }
  if (api.version !== VERSION2) {
    var err2 = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION2);
    diag3.error(err2.stack || err2.message);
    return false;
  }
  api[type] = instance2;
  diag3.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION2 + ".");
  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" + VERSION2 + ".");
  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 = VERSION2.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, args2) {
  var logger6 = getGlobal("diag");
  if (!logger6) {
    return;
  }
  args2.unshift(namespace);
  return logger6[funcName].apply(logger6, __spreadArray([], __read(args2), 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 i4 = m3.call(o3), r5, ar2 = [], e4;
      try {
        while ((n3 === void 0 || n3-- > 0) && !(r5 = i4.next()).done) ar2.push(r5.value);
      } catch (error40) {
        e4 = { error: error40 };
      } finally {
        try {
          if (r5 && !r5.done && (m3 = i4["return"])) m3.call(i4);
        } finally {
          if (e4) throw e4.error;
        }
      }
      return ar2;
    };
    __spreadArray = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i4 = 0, l3 = from.length, ar2; i4 < l3; i4++) {
        if (ar2 || !(i4 in from)) {
          if (!ar2) ar2 = Array.prototype.slice.call(from, 0, i4);
          ar2[i4] = from[i4];
        }
      }
      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 args2 = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args2[_i] = arguments[_i];
        }
        return logProxy("debug", this._namespace, args2);
      };
      DiagComponentLogger2.prototype.error = function() {
        var args2 = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args2[_i] = arguments[_i];
        }
        return logProxy("error", this._namespace, args2);
      };
      DiagComponentLogger2.prototype.info = function() {
        var args2 = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args2[_i] = arguments[_i];
        }
        return logProxy("info", this._namespace, args2);
      };
      DiagComponentLogger2.prototype.warn = function() {
        var args2 = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args2[_i] = arguments[_i];
        }
        return logProxy("warn", this._namespace, args2);
      };
      DiagComponentLogger2.prototype.verbose = function() {
        var args2 = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args2[_i] = arguments[_i];
        }
        return logProxy("verbose", this._namespace, args2);
      };
      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 i4 = m3.call(o3), r5, ar2 = [], e4;
      try {
        while ((n3 === void 0 || n3-- > 0) && !(r5 = i4.next()).done) ar2.push(r5.value);
      } catch (error40) {
        e4 = { error: error40 };
      } finally {
        try {
          if (r5 && !r5.done && (m3 = i4["return"])) m3.call(i4);
        } finally {
          if (e4) throw e4.error;
        }
      }
      return ar2;
    };
    __spreadArray2 = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i4 = 0, l3 = from.length, ar2; i4 < l3; i4++) {
        if (ar2 || !(i4 in from)) {
          if (!ar2) ar2 = Array.prototype.slice.call(from, 0, i4);
          ar2[i4] = from[i4];
        }
      }
      return to.concat(ar2 || Array.prototype.slice.call(from));
    };
    API_NAME = "diag";
    DiagAPI = /** @class */
    function() {
      function DiagAPI2() {
        function _logProxy(funcName) {
          return function() {
            var args2 = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args2[_i] = arguments[_i];
            }
            var logger6 = getGlobal("diag");
            if (!logger6)
              return;
            return logger6[funcName].apply(logger6, __spreadArray2([], __read2(args2), 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 err2 = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
            self2.error((_a7 = err2.stack) !== null && _a7 !== void 0 ? _a7 : err2.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 i4 = m3.call(o3), r5, ar2 = [], e4;
      try {
        while ((n3 === void 0 || n3-- > 0) && !(r5 = i4.next()).done) ar2.push(r5.value);
      } catch (error40) {
        e4 = { error: error40 };
      } finally {
        try {
          if (r5 && !r5.done && (m3 = i4["return"])) m3.call(i4);
        } finally {
          if (e4) throw e4.error;
        }
      }
      return ar2;
    };
    __values2 = function(o3) {
      var s5 = typeof Symbol === "function" && Symbol.iterator, m3 = s5 && o3[s5], i4 = 0;
      if (m3) return m3.call(o3);
      if (o3 && typeof o3.length === "number") return {
        next: /* @__PURE__ */ __name(function() {
          if (o3 && i4 >= o3.length) o3 = void 0;
          return { value: o3 && o3[i4++], 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_utils = __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 args2 = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args2[_i] = arguments[_i];
            }
            if (console) {
              var theFunc = console[funcName];
              if (typeof theFunc !== "function") {
                theFunc = console.log;
              }
              if (typeof theFunc === "function") {
                return theFunc.apply(console, args2);
              }
            }
          };
        }
        __name(_consoleFunc, "_consoleFunc");
        for (var i4 = 0; i4 < consoleMap.length; i4++) {
          this[consoleMap[i4].n] = _consoleFunc(consoleMap[i4].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 i4 = m3.call(o3), r5, ar2 = [], e4;
      try {
        while ((n3 === void 0 || n3-- > 0) && !(r5 = i4.next()).done) ar2.push(r5.value);
      } catch (error40) {
        e4 = { error: error40 };
      } finally {
        try {
          if (r5 && !r5.done && (m3 = i4["return"])) m3.call(i4);
        } finally {
          if (e4) throw e4.error;
        }
      }
      return ar2;
    };
    __spreadArray3 = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i4 = 0, l3 = from.length, ar2; i4 < l3; i4++) {
        if (ar2 || !(i4 in from)) {
          if (!ar2) ar2 = Array.prototype.slice.call(from, 0, i4);
          ar2[i4] = from[i4];
        }
      }
      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 args2 = [];
        for (var _i = 3; _i < arguments.length; _i++) {
          args2[_i - 3] = arguments[_i];
        }
        return fn.call.apply(fn, __spreadArray3([thisArg], __read4(args2), 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 i4 = m3.call(o3), r5, ar2 = [], e4;
      try {
        while ((n3 === void 0 || n3-- > 0) && !(r5 = i4.next()).done) ar2.push(r5.value);
      } catch (error40) {
        e4 = { error: error40 };
      } finally {
        try {
          if (r5 && !r5.done && (m3 = i4["return"])) m3.call(i4);
        } finally {
          if (e4) throw e4.error;
        }
      }
      return ar2;
    };
    __spreadArray4 = function(to, from, pack) {
      if (pack || arguments.length === 2) for (var i4 = 0, l3 = from.length, ar2; i4 < l3; i4++) {
        if (ar2 || !(i4 in from)) {
          if (!ar2) ar2 = Array.prototype.slice.call(from, 0, i4);
          ar2[i4] = from[i4];
        }
      }
      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 args2 = [];
        for (var _i = 3; _i < arguments.length; _i++) {
          args2[_i - 3] = arguments[_i];
        }
        return (_a7 = this._getContextManager()).with.apply(_a7, __spreadArray4([context2, fn, thisArg], __read5(args2), 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(name4, 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(name4, 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(name4, 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, name4, version2, options2) {
        this._provider = _provider;
        this.name = name4;
        this.version = version2;
        this.options = options2;
      }
      __name(ProxyTracer2, "ProxyTracer");
      ProxyTracer2.prototype.startSpan = function(name4, options2, context2) {
        return this._getTracer().startSpan(name4, 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(name4, version2, options2) {
        var _a7;
        return (_a7 = this.getDelegateTracer(name4, version2, options2)) !== null && _a7 !== void 0 ? _a7 : new ProxyTracer(this, name4, 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(name4, version2, options2) {
        var _a7;
        return (_a7 = this._delegate) === null || _a7 === void 0 ? void 0 : _a7.getTracer(name4, 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 i4 = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
          if (i4 !== -1) {
            var key = listMember.slice(0, i4);
            var value = listMember.slice(i4 + 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_utils2 = __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(name4, version2, options2) {
        return this.getMeterProvider().getMeter(name4, 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_utils();
    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_trace = __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 success2 = registerGlobal(API_NAME5, this._proxyTracerProvider, DiagAPI.instance());
        if (success2) {
          this._proxyTracerProvider.setDelegate(provider);
        }
        return success2;
      };
      TraceAPI2.prototype.getTracerProvider = function() {
        return getGlobal(API_NAME5) || this._proxyTracerProvider;
      };
      TraceAPI2.prototype.getTracer = function(name4, version2) {
        return this.getTracerProvider().getTracer(name4, 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_trace();
    trace = TraceAPI.getInstance();
  }
});

// node_modules/@opentelemetry/api/build/esm/index.js
var esm_exports = {};
__export(esm_exports, {
  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_esm = __esm({
  "node_modules/@opentelemetry/api/build/esm/index.js"() {
    init_esbuild_shims();
    init_utils();
    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_utils2();
    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(([name4, { description, valueType, assign }]) => {
    assign(meter.createCounter(name4, { description, valueType }));
  });
  subagentExecutionCounter = meter.createCounter(SUBAGENT_EXECUTION_COUNT, {
    description: "Counts subagent execution events, tagged by status and subagent name.",
    valueType: ValueType.INT
  });
  arenaSessionCounter = meter.createCounter(ARENA_SESSION_COUNT, {
    description: "Counts arena sessions by status and display backend.",
    valueType: ValueType.INT
  });
  arenaSessionDurationHistogram = meter.createHistogram(ARENA_SESSION_DURATION, {
    description: "Duration of arena sessions in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT
  });
  arenaAgentCounter = meter.createCounter(ARENA_AGENT_COUNT, {
    description: "Counts arena agent completions by status and model.",
    valueType: ValueType.INT
  });
  arenaAgentDurationHistogram = meter.createHistogram(ARENA_AGENT_DURATION, {
    description: "Duration of arena agent execution in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT
  });
  arenaAgentTokensCounter = meter.createCounter(ARENA_AGENT_TOKENS, {
    description: "Token usage by arena agents.",
    valueType: ValueType.INT
  });
  arenaResultSelectedCounter = meter.createCounter(ARENA_RESULT_SELECTED, {
    description: "Counts arena result selections by model.",
    valueType: ValueType.INT
  });
  Object.entries(HISTOGRAM_DEFINITIONS).forEach(([name4, { description, unit, valueType, assign }]) => {
    assign(meter.createHistogram(name4, { description, unit, valueType }));
  });
  sessionCounter?.add(1, baseMetricDefinition.getCommonAttributes(config2));
  memoryExtractCounter = meter.createCounter(MEMORY_EXTRACT_COUNT, {
    description: "Counts auto-memory extraction runs, tagged by trigger and status.",
    valueType: ValueType.INT
  });
  memoryExtractDurationHistogram = meter.createHistogram(MEMORY_EXTRACT_DURATION, {
    description: "Duration of auto-memory extraction in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT
  });
  memoryDreamCounter = meter.createCounter(MEMORY_DREAM_COUNT, {
    description: "Counts auto-memory dream (consolidation) runs, tagged by trigger and status.",
    valueType: ValueType.INT
  });
  memoryDreamDurationHistogram = meter.createHistogram(MEMORY_DREAM_DURATION, {
    description: "Duration of auto-memory dream runs in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT
  });
  memoryRecallCounter = meter.createCounter(MEMORY_RECALL_COUNT, {
    description: "Counts auto-memory recall operations, tagged by strategy.",
    valueType: ValueType.INT
  });
  memoryRecallDurationHistogram = meter.createHistogram(MEMORY_RECALL_DURATION, {
    description: "Duration of auto-memory recall operations in milliseconds.",
    unit: "ms",
    valueType: ValueType.INT
  });
  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 recordInvalidChunk(config2) {
  if (!invalidChunkCounter || !isMetricsInitialized)
    return;
  invalidChunkCounter.add(1, baseMetricDefinition.getCommonAttributes(config2));
}
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(([name4, { description, valueType, assign }]) => {
    assign(meter.createCounter(name4, { description, valueType }));
  });
  Object.entries(PERFORMANCE_HISTOGRAM_DEFINITIONS).forEach(([name4, { description, unit, valueType, assign }]) => {
    assign(meter.createHistogram(name4, { description, unit, valueType }));
  });
}
function recordStartupPerformance(config2, durationMs, attributes) {
  if (!startupTimeHistogram || !isPerformanceMonitoringEnabled)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    phase: attributes.phase,
    ...attributes.details
  };
  startupTimeHistogram.record(durationMs, metricAttributes);
}
function recordMemoryUsage(config2, bytes, attributes) {
  if (!memoryUsageGauge || !isPerformanceMonitoringEnabled)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  };
  memoryUsageGauge.record(bytes, metricAttributes);
}
function recordCpuUsage(config2, percentage, attributes) {
  if (!cpuUsageGauge || !isPerformanceMonitoringEnabled)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  };
  cpuUsageGauge.record(percentage, metricAttributes);
}
function recordToolQueueDepth(config2, queueDepth) {
  if (!toolQueueDepthGauge || !isPerformanceMonitoringEnabled)
    return;
  const attributes = {
    ...baseMetricDefinition.getCommonAttributes(config2)
  };
  toolQueueDepthGauge.record(queueDepth, attributes);
}
function recordToolExecutionBreakdown(config2, durationMs, attributes) {
  if (!toolExecutionBreakdownHistogram || !isPerformanceMonitoringEnabled)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  };
  toolExecutionBreakdownHistogram.record(durationMs, metricAttributes);
}
function recordTokenEfficiency(config2, value, attributes) {
  if (!tokenEfficiencyHistogram || !isPerformanceMonitoringEnabled)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  };
  tokenEfficiencyHistogram.record(value, metricAttributes);
}
function recordApiRequestBreakdown(config2, durationMs, attributes) {
  if (!apiRequestBreakdownHistogram || !isPerformanceMonitoringEnabled)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  };
  apiRequestBreakdownHistogram.record(durationMs, metricAttributes);
}
function recordPerformanceScore(config2, score, attributes) {
  if (!performanceScoreGauge || !isPerformanceMonitoringEnabled)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  };
  performanceScoreGauge.record(score, metricAttributes);
}
function recordPerformanceRegression(config2, attributes) {
  if (!regressionDetectionCounter || !isPerformanceMonitoringEnabled)
    return;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  };
  regressionDetectionCounter.add(1, metricAttributes);
  if (attributes.baseline_value !== 0 && regressionPercentageChangeHistogram) {
    const percentageChange = (attributes.current_value - attributes.baseline_value) / attributes.baseline_value * 100;
    regressionPercentageChangeHistogram.record(percentageChange, metricAttributes);
  }
}
function recordBaselineComparison(config2, attributes) {
  if (!baselineComparisonHistogram || !isPerformanceMonitoringEnabled)
    return;
  if (attributes.baseline_value === 0) {
    diag2.warn("Baseline value is zero, skipping comparison.");
    return;
  }
  const percentageChange = (attributes.current_value - attributes.baseline_value) / attributes.baseline_value * 100;
  const metricAttributes = {
    ...baseMetricDefinition.getCommonAttributes(config2),
    ...attributes
  };
  baselineComparisonHistogram.record(percentageChange, metricAttributes);
}
function isPerformanceMonitoringActive() {
  return isPerformanceMonitoringEnabled && isMetricsInitialized;
}
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);
}
function recordArenaSessionStartedMetrics(config2) {
  if (!isMetricsInitialized)
    return;
  arenaSessionCounter?.add(1, {
    ...baseMetricDefinition.getCommonAttributes(config2),
    status: "started"
  });
}
function recordArenaAgentCompletedMetrics(config2, modelId, status, durationMs, inputTokens, outputTokens) {
  if (!isMetricsInitialized)
    return;
  const common = baseMetricDefinition.getCommonAttributes(config2);
  arenaAgentCounter?.add(1, {
    ...common,
    status,
    model_id: modelId
  });
  arenaAgentDurationHistogram?.record(durationMs, {
    ...common,
    model_id: modelId
  });
  if (inputTokens > 0) {
    arenaAgentTokensCounter?.add(inputTokens, {
      ...common,
      model_id: modelId,
      type: "input"
    });
  }
  if (outputTokens > 0) {
    arenaAgentTokensCounter?.add(outputTokens, {
      ...common,
      model_id: modelId,
      type: "output"
    });
  }
}
function recordArenaSessionEndedMetrics(config2, status, displayBackend, durationMs, winnerModelId) {
  if (!isMetricsInitialized)
    return;
  const common = baseMetricDefinition.getCommonAttributes(config2);
  arenaSessionCounter?.add(1, {
    ...common,
    status,
    ...displayBackend ? { display_backend: displayBackend } : {}
  });
  if (durationMs !== void 0 && arenaSessionDurationHistogram) {
    arenaSessionDurationHistogram.record(durationMs, {
      ...common,
      status
    });
  }
  if (winnerModelId) {
    arenaResultSelectedCounter?.add(1, {
      ...common,
      model_id: winnerModelId
    });
  }
}
function recordMemoryExtractMetrics(config2, durationMs, attrs) {
  if (!isMetricsInitialized)
    return;
  const common = baseMetricDefinition.getCommonAttributes(config2);
  memoryExtractCounter?.add(1, {
    ...common,
    trigger: attrs.trigger,
    status: attrs.status
  });
  memoryExtractDurationHistogram?.record(durationMs, {
    ...common,
    trigger: attrs.trigger,
    status: attrs.status
  });
}
function recordMemoryDreamMetrics(config2, durationMs, attrs) {
  if (!isMetricsInitialized)
    return;
  const common = baseMetricDefinition.getCommonAttributes(config2);
  memoryDreamCounter?.add(1, {
    ...common,
    trigger: attrs.trigger,
    status: attrs.status
  });
  memoryDreamDurationHistogram?.record(durationMs, {
    ...common,
    trigger: attrs.trigger,
    status: attrs.status
  });
}
function recordMemoryRecallMetrics(config2, durationMs, attrs) {
  if (!isMetricsInitialized)
    return;
  const common = baseMetricDefinition.getCommonAttributes(config2);
  memoryRecallCounter?.add(1, { ...common, strategy: attrs.strategy });
  memoryRecallDurationHistogram?.record(durationMs, {
    ...common,
    strategy: attrs.strategy
  });
}
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, ARENA_SESSION_COUNT, ARENA_SESSION_DURATION, ARENA_AGENT_COUNT, ARENA_AGENT_DURATION, ARENA_AGENT_TOKENS, ARENA_RESULT_SELECTED, 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, MEMORY_EXTRACT_COUNT, MEMORY_EXTRACT_DURATION, MEMORY_DREAM_COUNT, MEMORY_DREAM_DURATION, MEMORY_RECALL_COUNT, MEMORY_RECALL_DURATION, 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, arenaSessionCounter, arenaSessionDurationHistogram, arenaAgentCounter, arenaAgentDurationHistogram, arenaAgentTokensCounter, arenaResultSelectedCounter, memoryExtractCounter, memoryExtractDurationHistogram, memoryDreamCounter, memoryDreamDurationHistogram, memoryRecallCounter, memoryRecallDurationHistogram, isMetricsInitialized, isPerformanceMonitoringEnabled;
var init_metrics2 = __esm({
  "packages/core/dist/src/telemetry/metrics.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm();
    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`;
    ARENA_SESSION_COUNT = `${SERVICE_NAME}.arena.session.count`;
    ARENA_SESSION_DURATION = `${SERVICE_NAME}.arena.session.duration`;
    ARENA_AGENT_COUNT = `${SERVICE_NAME}.arena.agent.count`;
    ARENA_AGENT_DURATION = `${SERVICE_NAME}.arena.agent.duration`;
    ARENA_AGENT_TOKENS = `${SERVICE_NAME}.arena.agent.tokens`;
    ARENA_RESULT_SELECTED = `${SERVICE_NAME}.arena.result.selected`;
    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`;
    MEMORY_EXTRACT_COUNT = `${SERVICE_NAME}.memory.extract.count`;
    MEMORY_EXTRACT_DURATION = `${SERVICE_NAME}.memory.extract.duration`;
    MEMORY_DREAM_COUNT = `${SERVICE_NAME}.memory.dream.count`;
    MEMORY_DREAM_DURATION = `${SERVICE_NAME}.memory.dream.duration`;
    MEMORY_RECALL_COUNT = `${SERVICE_NAME}.memory.recall.count`;
    MEMORY_RECALL_DURATION = `${SERVICE_NAME}.memory.recall.duration`;
    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(recordInvalidChunk, "recordInvalidChunk");
    __name(recordContentRetry, "recordContentRetry");
    __name(recordContentRetryFailure, "recordContentRetryFailure");
    __name(recordModelSlashCommand, "recordModelSlashCommand");
    __name(initializePerformanceMonitoring, "initializePerformanceMonitoring");
    __name(recordStartupPerformance, "recordStartupPerformance");
    __name(recordMemoryUsage, "recordMemoryUsage");
    __name(recordCpuUsage, "recordCpuUsage");
    __name(recordToolQueueDepth, "recordToolQueueDepth");
    __name(recordToolExecutionBreakdown, "recordToolExecutionBreakdown");
    __name(recordTokenEfficiency, "recordTokenEfficiency");
    __name(recordApiRequestBreakdown, "recordApiRequestBreakdown");
    __name(recordPerformanceScore, "recordPerformanceScore");
    __name(recordPerformanceRegression, "recordPerformanceRegression");
    __name(recordBaselineComparison, "recordBaselineComparison");
    __name(isPerformanceMonitoringActive, "isPerformanceMonitoringActive");
    __name(recordSubagentExecutionMetrics, "recordSubagentExecutionMetrics");
    __name(recordArenaSessionStartedMetrics, "recordArenaSessionStartedMetrics");
    __name(recordArenaAgentCompletedMetrics, "recordArenaAgentCompletedMetrics");
    __name(recordArenaSessionEndedMetrics, "recordArenaSessionEndedMetrics");
    __name(recordMemoryExtractMetrics, "recordMemoryExtractMetrics");
    __name(recordMemoryDreamMetrics, "recordMemoryDreamMetrics");
    __name(recordMemoryRecallMetrics, "recordMemoryRecallMetrics");
  }
});

// packages/core/dist/src/utils/language-detection.js
import * as path10 from "node:path";
function getLanguageFromFilePath(filePath) {
  const extension = path10.extname(filePath).toLowerCase();
  if (extension) {
    return extensionToLanguageMap[extension];
  }
  const filename = path10.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(args2) {
  const filePath = args2["file_path"] || args2["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");
  }
});

// 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, name4, version2, options2) {
        this._provider = _provider;
        this.name = name4;
        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(name4, version2, options2) {
        var _a7;
        return (_a7 = this.getDelegateLogger(name4, version2, options2)) !== null && _a7 !== void 0 ? _a7 : new ProxyLogger_1.ProxyLogger(this, name4, 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(name4, version2, options2) {
        var _a7;
        return (_a7 = this._delegate) === null || _a7 === void 0 ? void 0 : _a7.getLogger(name4, 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_node3 = __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_node3();
    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, instance2, fallback) {
      return (version2) => version2 === requiredVersion ? instance2 : 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(name4, version2, options2) {
        return this.getLoggerProvider().getLogger(name4, 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_utils3 = __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_utils3();
    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_trace2 = __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_utils3();
    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_exports2 = {};
__export(esm_exports2, {
  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_esm2 = __esm({
  "node_modules/@opentelemetry/semantic-conventions/build/esm/index.js"() {
    init_esbuild_shims();
    init_trace2();
    init_resource();
    init_stable_attributes();
    init_stable_metrics();
  }
});

// packages/core/dist/src/utils/internalPromptIds.js
function isInternalPromptId(promptId) {
  return INTERNAL_PROMPT_IDS.has(promptId);
}
var INTERNAL_PROMPT_IDS;
var init_internalPromptIds = __esm({
  "packages/core/dist/src/utils/internalPromptIds.js"() {
    "use strict";
    init_esbuild_shims();
    INTERNAL_PROMPT_IDS = /* @__PURE__ */ new Set([
      "prompt_suggestion",
      "forked_query",
      "speculation"
    ]);
    __name(isInternalPromptId, "isInternalPromptId");
  }
});

// packages/core/dist/src/telemetry/sanitize.js
function sanitizeHookName(hookName) {
  if (!hookName || !hookName.trim()) {
    return "unknown-command";
  }
  const parts2 = hookName.trim().split(/\s+/);
  if (parts2.length === 0) {
    return "unknown-command";
  }
  const command2 = parts2[0];
  if (!command2) {
    return "unknown-command";
  }
  if (command2.includes("/") || command2.includes("\\")) {
    const pathParts = command2.split(/[/\\]/);
    const basename34 = pathParts[pathParts.length - 1];
    return basename34 || "unknown-command";
  }
  return command2;
}
var init_sanitize = __esm({
  "packages/core/dist/src/telemetry/sanitize.js"() {
    "use strict";
    init_esbuild_shims();
    __name(sanitizeHookName, "sanitizeHookName");
  }
});

// packages/core/dist/src/utils/installationManager.js
import * as fs13 from "node:fs";
import { randomUUID } from "node:crypto";
import * as path11 from "node:path";
var debugLogger6, InstallationManager;
var init_installationManager = __esm({
  "packages/core/dist/src/utils/installationManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_storage();
    init_debugLogger();
    debugLogger6 = createDebugLogger("INSTALLATION");
    InstallationManager = class {
      static {
        __name(this, "InstallationManager");
      }
      getInstallationIdPath() {
        return Storage.getInstallationIdPath();
      }
      readInstallationIdFromFile() {
        const installationIdFile = this.getInstallationIdPath();
        if (fs13.existsSync(installationIdFile)) {
          const installationid = fs13.readFileSync(installationIdFile, "utf-8").trim();
          return installationid || null;
        }
        return null;
      }
      writeInstallationIdToFile(installationId) {
        const installationIdFile = this.getInstallationIdPath();
        const dir = path11.dirname(installationIdFile);
        fs13.mkdirSync(dir, { recursive: true });
        fs13.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 (error40) {
          debugLogger6.error("Error accessing installation ID file, generating ephemeral ID:", error40);
          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 i4 = 0;
        while (i4 < size) {
          if (a2[i4] < b2[i4])
            return -1;
          if (a2[i4] > b2[i4])
            return 1;
          i4++;
        }
        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 forEach3(iterable, callback) {
      var iterator2, k2, i4, 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 (i4 = 0, l3 = iterable.length; i4 < l3; i4++) callback(iterable[i4], i4);
        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") {
        iterator2 = iterable;
        i4 = 0;
        while (s5 = iterator2.next(), s5.done !== true) {
          callback(s5.value, i4);
          i4++;
        }
        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 forEach3 = 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), i4, l3, x3, y2, d2, t5;
      for (i4 = 0, l3 = nodes.length; i4 < l3; i4++) {
        x3 = nodes[i4];
        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 (i4 = 0; i4 < heap.size; i4++) {
        if (A4[i4] && heap.comparator(A4[i4].item, heap.min.item) <= 0)
          heap.min = A4[i4];
      }
    }
    __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, i4, l3;
        for (i4 = 0, l3 = nodes.length; i4 < l3; i4++) {
          node = nodes[i4];
          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 proxy2 = {
        size: this.size
      };
      if (this.min && "item" in this.min)
        proxy2.top = this.min.item;
      Object.defineProperty(proxy2, "constructor", {
        value: FibonacciHeap2,
        enumerable: false
      });
      return proxy2;
    };
    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);
      forEach3(iterable, function(value) {
        heap.push(value);
      });
      return heap;
    };
    MaxFibonacciHeap2.from = function(iterable, comparator) {
      var heap = new MaxFibonacciHeap2(comparator);
      forEach3(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, i4, l3;
      for (i4 = 0, l3 = array2.length; i4 < l3; i4++) {
        v2 = getter ? getter(array2[i4]) : array2[i4];
        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, i4, o3, l3;
      for (i4 = 0, l3 = arguments.length; i4 < l3; i4++)
        length += arguments[i4].length;
      var array2 = new arguments[0].constructor(length);
      for (i4 = 0, o3 = 0; i4 < l3; i4++) {
        array2.set(arguments[i4], o3);
        o3 += arguments[i4].length;
      }
      return array2;
    };
    exports2.indices = function(length) {
      var PointerArray = exports2.getPointerArray(length);
      var array2 = new PointerArray(length);
      for (var i4 = 0; i4 < length; i4++)
        array2[i4] = i4;
      return array2;
    };
  }
});

// node_modules/mnemonist/utils/iterables.js
var require_iterables = __commonJS({
  "node_modules/mnemonist/utils/iterables.js"(exports2) {
    init_esbuild_shims();
    var forEach3 = 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 toArray2(target) {
      var l3 = guessLength(target);
      var array2 = typeof l3 === "number" ? new Array(l3) : [];
      var i4 = 0;
      forEach3(target, function(value) {
        array2[i4++] = value;
      });
      return array2;
    }
    __name(toArray2, "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 i4 = 0;
      forEach3(target, function(value) {
        array2[i4] = value;
        indices[i4] = i4++;
      });
      return [array2, indices];
    }
    __name(toArrayWithIndices, "toArrayWithIndices");
    exports2.isArrayLike = isArrayLike2;
    exports2.guessLength = guessLength;
    exports2.toArray = toArray2;
    exports2.toArrayWithIndices = toArrayWithIndices;
  }
});

// node_modules/mnemonist/heap.js
var require_heap = __commonJS({
  "node_modules/mnemonist/heap.js"(exports2, module2) {
    init_esbuild_shims();
    var forEach3 = 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, i4) {
      var item = heap[i4], parentIndex, parent;
      while (i4 > startIndex) {
        parentIndex = i4 - 1 >> 1;
        parent = heap[parentIndex];
        if (compare(item, parent) < 0) {
          heap[i4] = parent;
          i4 = parentIndex;
          continue;
        }
        break;
      }
      heap[i4] = item;
    }
    __name(siftDown, "siftDown");
    function siftUp(compare, heap, i4) {
      var endIndex = heap.length, startIndex = i4, item = heap[i4], childIndex = 2 * i4 + 1, rightIndex;
      while (childIndex < endIndex) {
        rightIndex = childIndex + 1;
        if (rightIndex < endIndex && compare(heap[childIndex], heap[rightIndex]) >= 0) {
          childIndex = rightIndex;
        }
        heap[i4] = heap[childIndex];
        i4 = childIndex;
        childIndex = 2 * i4 + 1;
      }
      heap[i4] = item;
      siftDown(compare, heap, startIndex, i4);
    }
    __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, i4 = l3;
      while (--i4 >= 0)
        siftUp(compare, array2, i4);
    }
    __name(heapify, "heapify");
    function consume(compare, heap) {
      var l3 = heap.length, i4 = 0;
      var array2 = new Array(l3);
      while (i4 < l3)
        array2[i4++] = 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 i4, l3, v2;
      var min = Infinity;
      var result;
      if (n3 === 1) {
        if (iterables.isArrayLike(iterable)) {
          for (i4 = 0, l3 = iterable.length; i4 < l3; i4++) {
            v2 = iterable[i4];
            if (min === Infinity || compare(v2, min) < 0)
              min = v2;
          }
          result = new iterable.constructor(1);
          result[0] = min;
          return result;
        }
        forEach3(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 (i4 = n3, l3 = iterable.length; i4 < l3; i4++)
          if (reverseCompare(iterable[i4], result[0]) > 0)
            replace2(reverseCompare, result, iterable[i4]);
        return result.sort(compare);
      }
      var size = iterables.guessLength(iterable);
      if (size !== null && size < n3)
        n3 = size;
      result = new Array(n3);
      i4 = 0;
      forEach3(iterable, function(value) {
        if (i4 < n3) {
          result[i4] = value;
        } else {
          if (i4 === n3)
            heapify(reverseCompare, result);
          if (reverseCompare(value, result[0]) > 0)
            replace2(reverseCompare, result, value);
        }
        i4++;
      });
      if (result.length > i4)
        result.length = i4;
      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 i4, l3, v2;
      var max = -Infinity;
      var result;
      if (n3 === 1) {
        if (iterables.isArrayLike(iterable)) {
          for (i4 = 0, l3 = iterable.length; i4 < l3; i4++) {
            v2 = iterable[i4];
            if (max === -Infinity || compare(v2, max) > 0)
              max = v2;
          }
          result = new iterable.constructor(1);
          result[0] = max;
          return result;
        }
        forEach3(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 (i4 = n3, l3 = iterable.length; i4 < l3; i4++)
          if (compare(iterable[i4], result[0]) > 0)
            replace2(compare, result, iterable[i4]);
        return result.sort(reverseCompare);
      }
      var size = iterables.guessLength(iterable);
      if (size !== null && size < n3)
        n3 = size;
      result = new Array(n3);
      i4 = 0;
      forEach3(iterable, function(value) {
        if (i4 < n3) {
          result[i4] = value;
        } else {
          if (i4 === n3)
            heapify(compare, result);
          if (compare(value, result[0]) > 0)
            replace2(compare, result, value);
        }
        i4++;
      });
      if (result.length > i4)
        result.length = i4;
      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 proxy2 = this.toArray();
      Object.defineProperty(proxy2, "constructor", {
        value: Heap2,
        enumerable: false
      });
      return proxy2;
    };
    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 = [], i4 = l3, j2 = -1, b2, d2 = 0, bits;
      while (i4--)
        j2 = Math.max(string4[array2[i4] + offset], j2);
      bits = j2 >> 24 && 32 || j2 >> 16 && 24 || j2 >> 8 && 16 || 8;
      for (; d2 < bits; d2 += 4) {
        for (i4 = 16; i4--; )
          buckets[i4] = [];
        for (i4 = l3; i4--; )
          buckets[string4[array2[i4] + offset] >> d2 & 15].push(array2[i4]);
        for (b2 = 0; b2 < 16; b2++) {
          for (j2 = buckets[b2].length; j2--; )
            array2[++i4] = buckets[b2][j2];
        }
      }
    }
    __name(sort, "sort");
    function compare(string4, lookup2, m3, n3) {
      return string4[m3] - string4[n3] || (m3 % 3 === 2 ? string4[m3 + 1] - string4[n3 + 1] || lookup2[m3 + 2] - lookup2[n3 + 2] : lookup2[m3 + 1] - lookup2[n3 + 1]);
    }
    __name(compare, "compare");
    function build(string4, l3) {
      var a2 = [], b2 = [], al = 2 * l3 / 3 | 0, bl = l3 - al, r5 = al + 1 >> 1, i4 = al, j2 = 0, k2, lookup2 = [], result = [];
      if (l3 === 1)
        return [0];
      while (i4--)
        a2[i4] = (i4 * 3 >> 1) + 1;
      for (i4 = 3; i4--; )
        sort(string4, a2, i4);
      j2 = b2[(a2[0] / 3 | 0) + (a2[0] % 3 === 1 ? 0 : r5)] = 1;
      for (i4 = 1; i4 < al; i4++) {
        if (string4[a2[i4]] !== string4[a2[i4 - 1]] || string4[a2[i4] + 1] !== string4[a2[i4 - 1] + 1] || string4[a2[i4] + 2] !== string4[a2[i4 - 1] + 2])
          j2++;
        b2[(a2[i4] / 3 | 0) + (a2[i4] % 3 === 1 ? 0 : r5)] = j2;
      }
      if (j2 < al) {
        b2 = build(b2, al);
        for (i4 = al; i4--; )
          a2[i4] = b2[i4] < r5 ? b2[i4] * 3 + 1 : (b2[i4] - r5) * 3 + 2;
      }
      for (i4 = al; i4--; )
        lookup2[a2[i4]] = i4;
      lookup2[l3] = -1;
      lookup2[l3 + 1] = -2;
      b2 = l3 % 3 === 1 ? [l3 - 1] : [];
      for (i4 = 0; i4 < al; i4++) {
        if (a2[i4] % 3 === 1)
          b2.push(a2[i4] - 1);
      }
      sort(string4, b2, 0);
      for (i4 = 0, j2 = 0, k2 = 0; i4 < al && j2 < bl; )
        result[k2++] = compare(string4, lookup2, a2[i4], b2[j2]) < 0 ? a2[i4++] : b2[j2++];
      while (i4 < al)
        result[k2++] = a2[i4++];
      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, i4;
      if (typeof target !== "string") {
        var uniqueTokens = /* @__PURE__ */ Object.create(null);
        for (i4 = 0; i4 < length; i4++) {
          if (!uniqueTokens[target[i4]])
            uniqueTokens[target[i4]] = true;
        }
        var alphabet2 = /* @__PURE__ */ Object.create(null), sortedUniqueTokens = Object.keys(uniqueTokens).sort();
        for (i4 = 0, l3 = sortedUniqueTokens.length; i4 < l3; i4++)
          alphabet2[sortedUniqueTokens[i4]] = i4 + 1;
        for (i4 = 0; i4 < length; i4++) {
          array2[i4] = alphabet2[target[i4]];
        }
      } else {
        for (i4 = 0; i4 < length; i4++)
          array2[i4] = target.charCodeAt(i4);
      }
      for (i4 = length; i4 < length + paddingOffset; i4++)
        array2[i4] = 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 i4 = 0; i4 < this.length; i4++)
        array2[i4] = this.string.slice(this.array[i4]);
      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 i4 = 0, l3 = this.size; i4 < l3; i4++) {
          this.text.push.apply(this.text, strings[i4]);
          if (i4 < 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, i4, j2, s5, t5;
      for (i4 = 1; i4 < this.length; i4++) {
        s5 = this.array[i4];
        t5 = this.array[i4 - 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 i4 = 0; i4 < this.length; i4++)
        array2[i4] = this.text.slice(this.array[i4]);
      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 args2 = arguments, l3 = args2.length, i4 = 0;
      return new Iterator(function() {
        if (i4 >= l3) return { done: true };
        return { done: false, value: args2[i4++] };
      });
    };
    Iterator.empty = function() {
      var iterator2 = new Iterator(function() {
        return { done: true };
      });
      return iterator2;
    };
    Iterator.fromSequence = function(sequence) {
      var i4 = 0, l3 = sequence.length;
      return new Iterator(function() {
        if (i4 >= l3) return { done: true };
        return { done: false, value: sequence[i4++] };
      });
    };
    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 forEach3 = 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, factory2 = false;
      if (typeof initialCapacityOrOptions === "object") {
        initialCapacity = initialCapacityOrOptions.initialCapacity || 0;
        initialLength = initialCapacityOrOptions.initialLength || 0;
        policy = initialCapacityOrOptions.policy || policy;
        factory2 = initialCapacityOrOptions.factory === true;
      }
      this.factory = factory2 ? 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 i4 = 0, l3 = this.length; i4 < l3; i4++)
            this.array[i4] = oldArray[i4];
        }
      } 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, i4 = 0;
      return new Iterator(function() {
        if (i4 >= l3)
          return {
            done: true
          };
        var value = items[i4];
        i4++;
        return {
          value,
          done: false
        };
      });
    };
    Vector2.prototype.entries = function() {
      var items = this.array, l3 = this.length, i4 = 0;
      return new Iterator(function() {
        if (i4 >= l3)
          return {
            done: true
          };
        var value = items[i4];
        return {
          value: [i4++, value],
          done: false
        };
      });
    };
    if (typeof Symbol !== "undefined")
      Vector2.prototype[Symbol.iterator] = Vector2.prototype.values;
    Vector2.prototype.inspect = function() {
      var proxy2 = this.array.slice(0, this.length);
      proxy2.type = this.array.constructor.name;
      proxy2.items = this.length;
      proxy2.capacity = this.capacity;
      Object.defineProperty(proxy2, "constructor", {
        value: Vector2,
        enumerable: false
      });
      return proxy2;
    };
    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);
      forEach3(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, i4 = this.start, j2 = 0;
      while (j2 < l3) {
        callback.call(scope, this.items[i4], j2, this);
        i4++;
        j2++;
        if (i4 === c4)
          i4 = 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, i4 = this.start, j2 = 0;
      while (j2 < l3) {
        array2[j2] = this.items[i4];
        i4++;
        j2++;
        if (i4 === c4)
          i4 = 0;
      }
      return array2;
    };
    FixedDeque.prototype.values = function() {
      var items = this.items, c4 = this.capacity, l3 = this.size, i4 = this.start, j2 = 0;
      return new Iterator(function() {
        if (j2 >= l3)
          return {
            done: true
          };
        var value = items[i4];
        i4++;
        j2++;
        if (i4 === c4)
          i4 = 0;
        return {
          value,
          done: false
        };
      });
    };
    FixedDeque.prototype.entries = function() {
      var items = this.items, c4 = this.capacity, l3 = this.size, i4 = this.start, j2 = 0;
      return new Iterator(function() {
        if (j2 >= l3)
          return {
            done: true
          };
        var value = items[i4];
        i4++;
        if (i4 === c4)
          i4 = 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 i4, l3;
        for (i4 = 0, l3 = iterable.length; i4 < l3; i4++)
          deque.items[i4] = iterable[i4];
        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 os5 from "node:os";
import fs14 from "node:fs";
import path12 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_dist3(), 1);
    init_debugLogger();
    init_safeJsonStringify();
    init_sanitize();
    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 (error40) {
          this.debugLogger.error("QwenLogger: Failed to enqueue log event.", error40);
        }
      }
      createRumEvent(eventType, type, name4, properties) {
        return {
          timestamp: Date.now(),
          event_type: eventType,
          type,
          name: name4,
          ...properties || {}
        };
      }
      createViewEvent(type, name4, properties) {
        return this.createRumEvent("view", type, name4, properties);
      }
      createActionEvent(type, name4, properties) {
        return this.createRumEvent("action", type, name4, properties);
      }
      createResourceEvent(type, name4, properties) {
        return this.createRumEvent("resource", type, name4, properties);
      }
      createExceptionEvent(type, name4, properties) {
        return this.createRumEvent("exception", type, name4, properties);
      }
      getOsMetadata() {
        return {
          type: os5.platform(),
          version: os5.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 = path12.join(os5.homedir(), ".qwen", "source.json");
          if (fs14.existsSync(sourceJsonPath)) {
            const sourceJsonContent = fs14.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((resolve42, reject) => {
            const body2 = safeJsonStringify(rumPayload);
            const options2 = {
              hostname: USAGE_STATS_HOSTNAME,
              path: USAGE_STATS_PATH,
              method: "POST",
              headers: {
                "Content-Length": Buffer4.byteLength(body2),
                "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 err2 = new Error(`Request failed with status ${res.statusCode}`);
                res.resume();
                return reject(err2);
              }
              res.on("data", (buf) => bufs.push(buf));
              res.on("end", () => resolve42(Buffer4.concat(bufs)));
            });
            req.on("error", reject);
            req.end(body2);
          });
          this.lastFlushTime = Date.now();
          return {};
        } catch (error40) {
          const now = Date.now();
          if (now - this.lastErrorLogTime > ERROR_LOG_INTERVAL_MS) {
            this.debugLogger.error("RUM flush failed.", error40);
            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: {
            approval_mode: event.approval_mode,
            core_tools_enabled: event.core_tools_enabled,
            debug_enabled: event.debug_enabled,
            hooks: event.hooks,
            ide_enabled: event.ide_enabled,
            interactive_shell_enabled: event.interactive_shell_enabled,
            mcp_servers: event.mcp_servers,
            model: event.model,
            sandbox_enabled: event.sandbox_enabled,
            skills: event.skills,
            subagents: event.subagents,
            telemetry_enabled: event.telemetry_enabled,
            truncate_tool_output_lines: event.truncate_tool_output_lines,
            truncate_tool_output_threshold: event.truncate_tool_output_threshold
          }
        });
        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: {
            prompt_id: event.prompt_id,
            prompt_length: event.prompt_length
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logRetryEvent(event) {
        const rumEvent = this.createActionEvent("user", "retry", {
          properties: {
            prompt_id: event.prompt_id
          }
        });
        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,
            subagent_name: event.subagent_name
          }
        });
        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,
            subagent_name: event.subagent_name
          },
          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
          })
        });
        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_message,
          trace_id: event.response_id,
          properties: {
            auth_type: event.auth_type,
            model: event.model,
            prompt_id: event.prompt_id,
            subagent_name: event.subagent_name,
            error_message: event.error_message,
            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();
      }
      // arena events
      logArenaSessionStartedEvent(event) {
        const rumEvent = this.createActionEvent("arena", "arena_session_started", {
          properties: {
            arena_session_id: event.arena_session_id,
            model_ids: JSON.stringify(event.model_ids),
            task_length: event.task_length
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logArenaAgentCompletedEvent(event) {
        const rumEvent = this.createActionEvent("arena", "arena_agent_completed", {
          properties: {
            arena_session_id: event.arena_session_id,
            agent_session_id: event.agent_session_id,
            agent_model_id: event.agent_model_id,
            status: event.status,
            duration_ms: event.duration_ms,
            rounds: event.rounds,
            total_tokens: event.total_tokens,
            input_tokens: event.input_tokens,
            output_tokens: event.output_tokens,
            tool_calls: event.tool_calls,
            successful_tool_calls: event.successful_tool_calls,
            failed_tool_calls: event.failed_tool_calls
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      logArenaSessionEndedEvent(event) {
        const rumEvent = this.createActionEvent("arena", "arena_session_ended", {
          properties: {
            arena_session_id: event.arena_session_id,
            status: event.status,
            duration_ms: event.duration_ms,
            display_backend: event.display_backend,
            agent_count: event.agent_count,
            completed_agents: event.completed_agents,
            failed_agents: event.failed_agents,
            cancelled_agents: event.cancelled_agents,
            winner_model_id: event.winner_model_id
          }
        });
        this.enqueueLogEvent(rumEvent);
        this.flushIfNeeded();
      }
      /**
       * Log a hook call event
       * Records hook execution telemetry for observability
       */
      logHookCallEvent(event) {
        const sanitizedHookName = sanitizeHookName(event.hook_name);
        const properties = {
          hook_event_name: event.hook_event_name,
          hook_type: event.hook_type,
          hook_name: sanitizedHookName,
          duration_ms: event.duration_ms,
          success: event.success ? 1 : 0,
          exit_code: event.exit_code
        };
        if (event.error && this.config?.getTelemetryLogPromptsEnabled()) {
          properties["error"] = event.error;
        }
        const rumEvent = this.createActionEvent("hook", `hook_call#${event.hook_event_name}`, { properties });
        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 i4 = eventsToRequeue.length - 1; i4 >= 0; i4--) {
          this.events.unshift(eventsToRequeue[i4]);
        }
        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(promise2) {
        if (this.hasReachedLimit()) {
          throw new Error("Concurrency Limit reached");
        }
        this._sendingPromises.push(promise2);
        const popPromise = /* @__PURE__ */ __name(() => {
          const index = this._sendingPromises.indexOf(promise2);
          void this._sendingPromises.splice(index, 1);
        }, "popPromise");
        promise2.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_esm(), __toCommonJS(esm_exports));
    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_utils4 = __commonJS({
  "node_modules/@opentelemetry/core/build/src/baggage/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseKeyPairsIntoRecord = exports2.parsePairKeyValue = exports2.getKeyPairs = exports2.serializeKeyPairs = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    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 metadata2;
      if (valueProps.length > 0) {
        metadata2 = (0, api_1.baggageEntryMetadataFromString)(valueProps.join(constants_1.BAGGAGE_PROPERTIES_SEPARATOR));
      }
      return { key, value, metadata: metadata2 };
    }
    __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_esm(), __toCommonJS(esm_exports));
    var suppress_tracing_1 = require_suppress_tracing();
    var constants_1 = require_constants7();
    var utils_1 = require_utils4();
    var W3CBaggagePropagator = class {
      static {
        __name(this, "W3CBaggagePropagator");
      }
      inject(context2, carrier, setter) {
        const baggage = api_1.propagation.getBaggage(context2);
        if (!baggage || (0, suppress_tracing_1.isTracingSuppressed)(context2))
          return;
        const keyPairs = (0, utils_1.getKeyPairs)(baggage).filter((pair) => {
          return pair.length <= constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;
        }).slice(0, constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS);
        const headerValue = (0, utils_1.serializeKeyPairs)(keyPairs);
        if (headerValue.length > 0) {
          setter.set(carrier, constants_1.BAGGAGE_HEADER, headerValue);
        }
      }
      extract(context2, carrier, getter) {
        const headerValue = getter.get(carrier, constants_1.BAGGAGE_HEADER);
        const baggageString = Array.isArray(headerValue) ? headerValue.join(constants_1.BAGGAGE_ITEMS_SEPARATOR) : headerValue;
        if (!baggageString)
          return context2;
        const baggage = {};
        if (baggageString.length === 0) {
          return context2;
        }
        const pairs = baggageString.split(constants_1.BAGGAGE_ITEMS_SEPARATOR);
        pairs.forEach((entry) => {
          const keyPair = (0, utils_1.parsePairKeyValue)(entry);
          if (keyPair) {
            const baggageEntry = { value: keyPair.value };
            if (keyPair.metadata) {
              baggageEntry.metadata = keyPair.metadata;
            }
            baggage[keyPair.key] = baggageEntry;
          }
        });
        if (Object.entries(baggage).length === 0) {
          return context2;
        }
        return api_1.propagation.setBaggage(context2, api_1.propagation.createBaggage(baggage));
      }
      fields() {
        return [constants_1.BAGGAGE_HEADER];
      }
    };
    exports2.W3CBaggagePropagator = W3CBaggagePropagator;
  }
});

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

// node_modules/@opentelemetry/core/build/src/common/attributes.js
var require_attributes = __commonJS({
  "node_modules/@opentelemetry/core/build/src/common/attributes.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isAttributeValue = exports2.isAttributeKey = exports2.sanitizeAttributes = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    function sanitizeAttributes(attributes) {
      const out2 = {};
      if (typeof attributes !== "object" || attributes == null) {
        return out2;
      }
      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)) {
          out2[key] = val.slice();
        } else {
          out2[key] = val;
        }
      }
      return out2;
    }
    __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_esm(), __toCommonJS(esm_exports));
    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_esm(), __toCommonJS(esm_exports));
    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_esm2(), __toCommonJS(esm_exports2));
    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_node4 = __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_node4();
    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 date5 = new Date(time3[0] * 1e3).toISOString();
      return date5.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 out2 = [time1[0] + time22[0], time1[1] + time22[1]];
      if (out2[1] >= SECOND_TO_NANOSECONDS) {
        out2[1] -= SECOND_TO_NANOSECONDS;
        out2[0] += 1;
      }
      return out2;
    }
    __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_esm(), __toCommonJS(esm_exports));
    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 (err2) {
            api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err2.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 (err2) {
            api_1.diag.warn(`Failed to extract with ${propagator.constructor.name}. Err: ${err2.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 i4 = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER2);
          if (i4 !== -1) {
            const key = listMember.slice(0, i4);
            const value = listMember.slice(i4 + 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_esm(), __toCommonJS(esm_exports));
    var suppress_tracing_1 = require_suppress_tracing();
    var TraceState_1 = require_TraceState();
    exports2.TRACE_PARENT_HEADER = "traceparent";
    exports2.TRACE_STATE_HEADER = "tracestate";
    var VERSION7 = "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 = `${VERSION7}-${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_esm(), __toCommonJS(esm_exports));
    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 getPrototypeOf2 = Object.getPrototypeOf;
    var objectProto = Object.prototype;
    var hasOwnProperty3 = objectProto.hasOwnProperty;
    var symToStringTag = Symbol ? Symbol.toStringTag : void 0;
    var nativeObjectToString = objectProto.toString;
    function isPlainObject9(value) {
      if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {
        return false;
      }
      const proto3 = getPrototypeOf2(value);
      if (proto3 === null) {
        return true;
      }
      const Ctor = hasOwnProperty3.call(proto3, "constructor") && proto3.constructor;
      return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString;
    }
    __name(isPlainObject9, "isPlainObject");
    exports2.isPlainObject = isPlainObject9;
    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 = hasOwnProperty3.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 merge5(...args2) {
      let result = args2.shift();
      const objects = /* @__PURE__ */ new WeakMap();
      while (args2.length > 0) {
        result = mergeTwoObjects(result, args2.shift(), 0, objects);
      }
      return result;
    }
    __name(merge5, "merge");
    exports2.merge = merge5;
    function takeValue(value) {
      if (isArray3(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) || isFunction7(two)) {
        result = takeValue(two);
      } else if (isArray3(one)) {
        result = one.slice();
        if (isArray3(two)) {
          for (let i4 = 0, j2 = two.length; i4 < j2; i4++) {
            result.push(takeValue(two[i4]));
          }
        } else if (isObject5(two)) {
          const keys = Object.keys(two);
          for (let i4 = 0, j2 = keys.length; i4 < j2; i4++) {
            const key = keys[i4];
            result[key] = takeValue(two[key]);
          }
        }
      } else if (isObject5(one)) {
        if (isObject5(two)) {
          if (!shouldMerge(one, two)) {
            return two;
          }
          result = Object.assign({}, one);
          const keys = Object.keys(two);
          for (let i4 = 0, j2 = keys.length; i4 < j2; i4++) {
            const key = keys[i4];
            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 (isObject5(obj1) && isObject5(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 i4 = 0, j2 = arr.length; i4 < j2; i4++) {
        const info2 = arr[i4];
        if (info2.key === key && info2.obj === obj) {
          return true;
        }
      }
      return false;
    }
    __name(wasObjectReferenced, "wasObjectReferenced");
    function isArray3(value) {
      return Array.isArray(value);
    }
    __name(isArray3, "isArray");
    function isFunction7(value) {
      return typeof value === "function";
    }
    __name(isFunction7, "isFunction");
    function isObject5(value) {
      return !isPrimitive(value) && !isArray3(value) && !isFunction7(value) && typeof value === "object";
    }
    __name(isObject5, "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(promise2, 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([promise2, 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(url3, urlToMatch) {
      if (typeof urlToMatch === "string") {
        return url3 === urlToMatch;
      } else {
        return !!url3.match(urlToMatch);
      }
    }
    __name(urlMatches, "urlMatches");
    exports2.urlMatches = urlMatches;
    function isUrlIgnored(url3, ignoredUrls) {
      if (!ignoredUrls) {
        return false;
      }
      for (const ignoreUrl of ignoredUrls) {
        if (urlMatches(url3, 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((resolve42, reject) => {
          this._resolve = resolve42;
          this._reject = reject;
        });
      }
      get promise() {
        return this._promise;
      }
      resolve(val) {
        this._resolve(val);
      }
      reject(err2) {
        this._reject(err2);
      }
    };
    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(...args2) {
        if (!this._isCalled) {
          this._isCalled = true;
          try {
            Promise.resolve(this._callback.call(this._that, ...args2)).then((val) => this._deferred.resolve(val), (err2) => this._deferred.reject(err2));
          } catch (err2) {
            this._deferred.reject(err2);
          }
        }
        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_esm(), __toCommonJS(esm_exports));
    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_esm(), __toCommonJS(esm_exports));
    var suppress_tracing_1 = require_suppress_tracing();
    function _export(exporter, arg) {
      return new Promise((resolve42) => {
        api_1.context.with((0, suppress_tracing_1.suppressTracing)(api_1.context.active()), () => {
          exporter.export(arg, (result) => {
            resolve42(result);
          });
        });
      });
    }
    __name(_export, "_export");
    exports2._export = _export;
  }
});

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

// node_modules/@opentelemetry/otlp-exporter-base/build/esm/logging-response-handler.js
function isPartialSuccessResponse(response) {
  return Object.prototype.hasOwnProperty.call(response, "partialSuccess");
}
function createLoggingPartialSuccessResponseHandler() {
  return {
    handleResponse(response) {
      if (response == null || !isPartialSuccessResponse(response) || response.partialSuccess == null || Object.keys(response.partialSuccess).length === 0) {
        return;
      }
      diag2.warn("Received Partial Success response:", JSON.stringify(response.partialSuccess));
    }
  };
}
var init_logging_response_handler = __esm({
  "node_modules/@opentelemetry/otlp-exporter-base/build/esm/logging-response-handler.js"() {
    init_esbuild_shims();
    init_esm();
    __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_esm();
    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, ...args2) => {
      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)(...args2);
        }
      }
    }, "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 = getErrorMessage5;
    exports2.getErrorCode = getErrorCode4;
    function getErrorMessage5(error40) {
      if (error40 instanceof Error) {
        return error40.message;
      } else {
        return String(error40);
      }
    }
    __name(getErrorMessage5, "getErrorMessage");
    function getErrorCode4(error40) {
      if (typeof error40 === "object" && error40 !== null && "code" in error40 && typeof error40.code === "number") {
        return error40.code;
      } else {
        return null;
      }
    }
    __name(getErrorCode4, "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 (error40) {
            const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error40)}. 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((resolve42, reject) => {
              googleCredentials.getRequestMetadata(options2.service_url, (err2, headers) => {
                if (err2) {
                  reject(err2);
                  return;
                }
                if (!headers) {
                  reject(new Error("Headers not set by metadata plugin"));
                  return;
                }
                resolve42(headers);
              });
            });
          }
          getHeaders.then((headers) => {
            const metadata2 = new metadata_1.Metadata();
            for (const key of Object.keys(headers)) {
              metadata2.add(key, headers[key]);
            }
            callback(null, metadata2);
          }, (err2) => {
            callback(err2);
          });
        });
      }
      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((resolve42, reject) => {
          this.metadataGenerator(options2, (err2, metadata2) => {
            if (metadata2 !== void 0) {
              resolve42(metadata2);
            } else {
              reject(err2);
            }
          });
        });
      }
      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 fs142 = __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 = fs142.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(path150) {
      if (path150.startsWith("[")) {
        const hostEnd = path150.indexOf("]");
        if (hostEnd === -1) {
          return null;
        }
        const host = path150.substring(1, hostEnd);
        if (host.indexOf(":") === -1) {
          return null;
        }
        if (path150.length > hostEnd + 1) {
          if (path150[hostEnd + 1] === ":") {
            const portString = path150.substring(hostEnd + 2);
            if (NUMBER_REGEX.test(portString)) {
              return {
                host,
                port: +portString
              };
            } else {
              return null;
            }
          } else {
            return null;
          }
        } else {
          return {
            host
          };
        }
      } else {
        const splitPath = path150.split(":");
        if (splitPath.length === 2) {
          if (NUMBER_REGEX.test(splitPath[1])) {
            return {
              host: splitPath[0],
              port: +splitPath[1]
            };
          } else {
            return null;
          }
        } else {
          return {
            host: path150
          };
        }
      }
    }
    __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((resolve42, 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;
            }
            resolve42({
              socket: tlsSocket,
              secure: true
            });
          });
          tlsSocket.on("error", (error40) => {
            reject(error40);
          });
        });
      }
      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((resolve42) => {
            this.secureContextWatchers.push(resolve42);
          });
        }
      }
      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((resolve42, 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((error40) => {
            reject(error40);
          }, "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;
            }
            resolve42({
              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 os59 = __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 name4 of obj.name) {
        result.name.push(validateName2(name4));
      }
      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 name4 of methodConfig.name) {
          for (const seenName of seenMethodNames) {
            if (name4.service === seenName.service && name4.method === seenName.method) {
              throw new Error(`Invalid service config: duplicate name ${name4.service}/${name4.method}`);
            }
          }
          seenMethodNames.push(name4);
        }
      }
      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 === os59.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(delay5) {
        var _a7, _b2;
        this.trace("runTimer(delay=" + delay5 + ")");
        this.endTime = this.startTime;
        this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay5);
        clearTimeout(this.timerId);
        this.timerId = setTimeout(() => {
          this.trace("timer fired");
          this.running = false;
          this.callback();
        }, delay5);
        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 name4 of methodConfig.name) {
        switch (matchLevel) {
          case "EMPTY":
            if (!name4.service && !name4.method) {
              return true;
            }
            break;
          case "SERVICE":
            if (name4.service === service && !name4.method) {
              return true;
            }
            break;
          case "SERVICE_AND_METHOD":
            if (name4.service === service && name4.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, metadata2) {
          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((error40) => {
            this.handleResolutionFailure(error40);
          }, "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(error40) {
        if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) {
          this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error40), error40.details);
          this.onFailedResolution(error40);
        }
      }
      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 i4 = 0; i4 < keys1.length; i4 += 1) {
        if (keys1[i4] !== keys2[i4]) {
          return false;
        }
        if (options1[keys1[i4]] !== options2[keys2[i4]]) {
          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 i4 = 0; i4 < endpoint1.addresses.length; i4++) {
        if (!subchannelAddressEqual(endpoint1.addresses[i4], endpoint2.addresses[i4])) {
          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 i4 = this.A(t5.u, e4);
          if (i4 < 0) {
            t5 = t5.h;
          } else if (i4 > 0) {
            s5 = t5;
            t5 = t5.i;
          } else return t5;
        }
        return s5;
      }
      K(t5, e4) {
        let s5 = this.C;
        while (t5) {
          const i4 = this.A(t5.u, e4);
          if (i4 <= 0) {
            t5 = t5.h;
          } else {
            s5 = t5;
            t5 = t5.i;
          }
        }
        return s5;
      }
      L(t5, e4) {
        let s5 = this.C;
        while (t5) {
          const i4 = this.A(t5.u, e4);
          if (i4 < 0) {
            s5 = t5;
            t5 = t5.h;
          } else if (i4 > 0) {
            t5 = t5.i;
          } else return t5;
        }
        return s5;
      }
      k(t5, e4) {
        let s5 = this.C;
        while (t5) {
          const i4 = this.A(t5.u, e4);
          if (i4 < 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 i4 = t5.l;
          t5.l = e4.l;
          e4.l = i4;
          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 i4 = 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;
            i4 && i4.push(n3);
            s5 && s5(n3, r5, this);
            r5 += 1;
            n3 = n3.h;
          }
        }
        return i4;
      }
      j(t5) {
        while (true) {
          const e4 = t5.o;
          if (e4.p === 0) return;
          const s5 = e4.o;
          if (e4 === s5.i) {
            const i4 = s5.h;
            if (i4 && i4.p === 1) {
              i4.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 i4 = s5.i;
            if (i4 && i4.p === 1) {
              i4.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 i4;
        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;
          i4 = r5.i;
          this.C.i = i4;
        } 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;
            i4 = r6.h;
            this.C.h = i4;
          } 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) {
                    i4 = new this.N(t5, e4);
                    if (s7.h === void 0) {
                      s7.h = i4;
                      i4.o = s7;
                    } else {
                      r7.i = i4;
                      i4.o = r7;
                    }
                  }
                }
              }
            }
            if (i4 === void 0) {
              i4 = this.v;
              while (true) {
                const s6 = this.A(i4.u, t5);
                if (s6 > 0) {
                  if (i4.i === void 0) {
                    i4.i = new this.N(t5, e4);
                    i4.i.o = i4;
                    i4 = i4.i;
                    break;
                  }
                  i4 = i4.i;
                } else if (s6 < 0) {
                  if (i4.h === void 0) {
                    i4.h = new this.N(t5, e4);
                    i4.h.o = i4;
                    i4 = i4.h;
                    break;
                  }
                  i4 = i4.h;
                } else {
                  i4.l = e4;
                  return this.m;
                }
              }
            }
          }
        }
        if (this.enableIndex) {
          let t6 = i4.o;
          while (t6 !== this.C) {
            t6.M += 1;
            t6 = t6.o;
          }
        }
        this.j(i4);
        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 i4 = s5.B().u;
        if (s5 === this.C.i) {
          if (this.A(i4, 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(i4, 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 i4 = t5.iteratorType === 0;
        if (i4) {
          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, i4) {
        super(t5, e4, i4);
        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, i4) {
            if (s5 !== "1") {
              throw new TypeError("prop must be 1");
            }
            t5.T.l = i4;
            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 i4 = this;
        t5.forEach(function(t6) {
          i4.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, i4) {
          t5([e4.u, e4.l], s5, i4);
        });
      }
      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 error40 = new Error(message);
      const stack = `${error40.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 flags2 = Number(encoding);
        if (!Number.isNaN(flags2)) {
          context2.flags = flags2;
        }
        (_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 flags2 = Number(encoding);
        if (!Number.isNaN(flags2)) {
          context2.flags = flags2;
        }
        (_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(metadata2) {
        this.processingMetadata = true;
        this.listener.onReceiveMetadata(metadata2, (metadata3) => {
          this.processingMetadata = false;
          this.nextListener.onReceiveMetadata(metadata3);
          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(start2) {
        this.start = start2;
        return this;
      }
      withSendMessage(sendMessage2) {
        this.message = sendMessage2;
        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((metadata2, next) => {
        next(metadata2);
      }, "onReceiveMetadata"),
      onReceiveMessage: /* @__PURE__ */ __name((message, next) => {
        next(message);
      }, "onReceiveMessage"),
      onReceiveStatus: /* @__PURE__ */ __name((status, next) => {
        next(status);
      }, "onReceiveStatus")
    };
    var defaultRequester = {
      start: /* @__PURE__ */ __name((metadata2, listener, next) => {
        next(metadata2, 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(metadata2, 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 : (metadata3) => {
          },
          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(metadata2, 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, path150, 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(path150, 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(metadata2, interceptingListener) {
        let readError = null;
        this.call.start(metadata2, {
          onReceiveMetadata: /* @__PURE__ */ __name((metadata3) => {
            var _a7;
            (_a7 = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a7 === void 0 ? void 0 : _a7.call(interceptingListener, metadata3);
          }, "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(metadata2, 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 : (metadata3) => {
          },
          // 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(metadata2, 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 isFunction7(arg) {
      return typeof arg === "function";
    }
    __name(isFunction7, "isFunction");
    function getErrorStackString(error40) {
      var _a7;
      return ((_a7 = error40.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((err2) => {
          if (err2) {
            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 (isFunction7(arg1)) {
          return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 };
        } else if (isFunction7(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 && isFunction7(arg3))) {
            throw new Error("Incorrect arguments passed");
          }
          return { metadata: arg1, options: arg2, callback: arg3 };
        }
      }
      makeUnaryRequest(method, serialize2, deserialize, argument, metadata2, options2, callback) {
        var _a7, _b2;
        const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata2, 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((metadata3) => {
            emitter.emit("metadata", metadata3);
          }, "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, metadata2, options2, callback) {
        var _a7, _b2;
        const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata2, 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((metadata3) => {
            emitter.emit("metadata", metadata3);
          }, "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 metadata2;
        let options2;
        if (arg1 instanceof metadata_1.Metadata) {
          metadata2 = arg1;
          if (arg2) {
            options2 = arg2;
          } else {
            options2 = {};
          }
        } else {
          if (arg1) {
            options2 = arg1;
          } else {
            options2 = {};
          }
          metadata2 = new metadata_1.Metadata();
        }
        return { metadata: metadata2, options: options2 };
      }
      makeServerStreamRequest(method, serialize2, deserialize, argument, metadata2, options2) {
        var _a7, _b2;
        const checkedArguments = this.checkMetadataAndOptions(metadata2, 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 stream5 = 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);
        stream5.call = call;
        let receivedStatus = false;
        let callerStackError = new Error();
        call.start(callProperties.metadata, {
          onReceiveMetadata(metadata3) {
            stream5.emit("metadata", metadata3);
          },
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          onReceiveMessage(message) {
            stream5.push(message);
          },
          onReceiveStatus(status) {
            if (receivedStatus) {
              return;
            }
            receivedStatus = true;
            stream5.push(null);
            if (status.code !== constants_1.Status.OK) {
              const callerStack = getErrorStackString(callerStackError);
              stream5.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack));
            }
            callerStackError = null;
            stream5.emit("status", status);
          }
        });
        call.sendMessage(argument);
        call.halfClose();
        return stream5;
      }
      makeBidiStreamRequest(method, serialize2, deserialize, metadata2, options2) {
        var _a7, _b2;
        const checkedArguments = this.checkMetadataAndOptions(metadata2, 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 stream5 = 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);
        stream5.call = call;
        let receivedStatus = false;
        let callerStackError = new Error();
        call.start(callProperties.metadata, {
          onReceiveMetadata(metadata3) {
            stream5.emit("metadata", metadata3);
          },
          onReceiveMessage(message) {
            stream5.push(message);
          },
          onReceiveStatus(status) {
            if (receivedStatus) {
              return;
            }
            receivedStatus = true;
            stream5.push(null);
            if (status.code !== constants_1.Status.OK) {
              const callerStack = getErrorStackString(callerStackError);
              stream5.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack));
            }
            callerStackError = null;
            stream5.emit("status", status);
          }
        });
        return stream5;
      }
    };
    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((name4) => {
        if (isPrototypePolluted(name4)) {
          return;
        }
        const attrs = methods[name4];
        let methodType;
        if (typeof name4 === "string" && name4.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[name4] = methodFunc;
        Object.assign(ServiceClientImpl.prototype[name4], attrs);
        if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) {
          ServiceClientImpl.prototype[attrs.originalName] = ServiceClientImpl.prototype[name4];
        }
      });
      ServiceClientImpl.service = methods;
      ServiceClientImpl.serviceName = serviceName;
      return ServiceClientImpl;
    }
    __name(makeClientConstructor, "makeClientConstructor");
    function partial2(fn, path150, serialize2, deserialize) {
      return function(...args2) {
        return fn.call(this, path150, serialize2, deserialize, ...args2);
      };
    }
    __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, start2, end) {
      var index = -1, length = array2.length;
      if (start2 < 0) {
        start2 = -start2 > length ? 0 : length + start2;
      }
      end = end > length ? length : end;
      if (end < 0) {
        end += length;
      }
      length = start2 > end ? 0 : end - start2 >>> 0;
      start2 >>>= 0;
      var result = Array(length);
      while (++index < length) {
        result[index] = array2[index + start2];
      }
      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, start2, end) {
      var length = array2.length;
      end = end === void 0 ? length : end;
      return !start2 && end >= length ? array2 : baseSlice(array2, start2, end);
    }
    __name(castSlice, "castSlice");
    function createCaseFirst(methodName) {
      return function(string4) {
        string4 = toString3(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 toString3(value) {
      return value == null ? "" : baseToString(value);
    }
    __name(toString3, "toString");
    var camelCase3 = createCompounder(function(result, word, index) {
      word = word.toLowerCase();
      return result + (index ? capitalize(word) : word);
    });
    function capitalize(string4) {
      return upperFirst(toString3(string4).toLowerCase());
    }
    __name(capitalize, "capitalize");
    function deburr(string4) {
      string4 = toString3(string4);
      return string4 && string4.replace(reLatin, deburrLetter).replace(reComboMark, "");
    }
    __name(deburr, "deburr");
    var upperFirst = createCaseFirst("toUpperCase");
    function words(string4, pattern, guard) {
      string4 = toString3(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(resolve42, reject) {
        params[offset] = /* @__PURE__ */ __name(function callback(err2) {
          if (pending) {
            pending = false;
            if (err2)
              reject(err2);
            else {
              var params2 = new Array(arguments.length - 1), offset2 = 0;
              while (offset2 < params2.length)
                params2[offset2++] = arguments[offset2];
              resolve42.apply(null, params2);
            }
          }
        }, "callback");
        try {
          fn.apply(ctx || null, params);
        } catch (err2) {
          if (pending) {
            pending = false;
            reject(err2);
          }
        }
      }, "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 base643 = exports2;
    base643.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 (i4 = 0; i4 < 64; )
      s64[b64[i4] = i4 < 26 ? i4 + 65 : i4 < 52 ? i4 + 71 : i4 < 62 ? i4 - 4 : i4 - 59 | 43] = i4++;
    var i4;
    base643.encode = /* @__PURE__ */ __name(function encode6(buffer, start2, end) {
      var parts2 = null, chunk = [];
      var i5 = 0, j2 = 0, t5;
      while (start2 < end) {
        var b2 = buffer[start2++];
        switch (j2) {
          case 0:
            chunk[i5++] = b64[b2 >> 2];
            t5 = (b2 & 3) << 4;
            j2 = 1;
            break;
          case 1:
            chunk[i5++] = b64[t5 | b2 >> 4];
            t5 = (b2 & 15) << 2;
            j2 = 2;
            break;
          case 2:
            chunk[i5++] = b64[t5 | b2 >> 6];
            chunk[i5++] = b64[b2 & 63];
            j2 = 0;
            break;
        }
        if (i5 > 8191) {
          (parts2 || (parts2 = [])).push(String.fromCharCode.apply(String, chunk));
          i5 = 0;
        }
      }
      if (j2) {
        chunk[i5++] = b64[t5];
        chunk[i5++] = 61;
        if (j2 === 1)
          chunk[i5++] = 61;
      }
      if (parts2) {
        if (i5)
          parts2.push(String.fromCharCode.apply(String, chunk.slice(0, i5)));
        return parts2.join("");
      }
      return String.fromCharCode.apply(String, chunk.slice(0, i5));
    }, "encode");
    var invalidEncoding = "invalid encoding";
    base643.decode = /* @__PURE__ */ __name(function decode2(string4, buffer, offset) {
      var start2 = offset;
      var j2 = 0, t5;
      for (var i5 = 0; i5 < string4.length; ) {
        var c4 = string4.charCodeAt(i5++);
        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 - start2;
    }, "decode");
    base643.test = /* @__PURE__ */ __name(function test2(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 = EventEmitter16;
    function EventEmitter16() {
      this._listeners = {};
    }
    __name(EventEmitter16, "EventEmitter");
    EventEmitter16.prototype.on = /* @__PURE__ */ __name(function on(evt, fn, ctx) {
      (this._listeners[evt] || (this._listeners[evt] = [])).push({
        fn,
        ctx: ctx || this
      });
      return this;
    }, "on");
    EventEmitter16.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 i4 = 0; i4 < listeners.length; )
            if (listeners[i4].fn === fn)
              listeners.splice(i4, 1);
            else
              ++i4;
        }
      }
      return this;
    }, "off");
    EventEmitter16.prototype.emit = /* @__PURE__ */ __name(function emit(evt) {
      var listeners = this._listeners[evt];
      if (listeners) {
        var args2 = [], i4 = 1;
        for (; i4 < arguments.length; )
          args2.push(arguments[i4++]);
        for (i4 = 0; i4 < listeners.length; )
          listeners[i4].fn.apply(listeners[i4++].ctx, args2);
      }
      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 = factory2(factory2);
    function factory2(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(factory2, "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_utf82 = __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 i4 = 0; i4 < string4.length; ++i4) {
        c4 = string4.charCodeAt(i4);
        if (c4 < 128)
          len += 1;
        else if (c4 < 2048)
          len += 2;
        else if ((c4 & 64512) === 55296 && (string4.charCodeAt(i4 + 1) & 64512) === 56320) {
          ++i4;
          len += 4;
        } else
          len += 3;
      }
      return len;
    }, "utf8_length");
    utf8.read = /* @__PURE__ */ __name(function utf8_read(buffer, start2, end) {
      var len = end - start2;
      if (len < 1)
        return "";
      var parts2 = null, chunk = [], i4 = 0, t5;
      while (start2 < end) {
        t5 = buffer[start2++];
        if (t5 < 128)
          chunk[i4++] = t5;
        else if (t5 > 191 && t5 < 224)
          chunk[i4++] = (t5 & 31) << 6 | buffer[start2++] & 63;
        else if (t5 > 239 && t5 < 365) {
          t5 = ((t5 & 7) << 18 | (buffer[start2++] & 63) << 12 | (buffer[start2++] & 63) << 6 | buffer[start2++] & 63) - 65536;
          chunk[i4++] = 55296 + (t5 >> 10);
          chunk[i4++] = 56320 + (t5 & 1023);
        } else
          chunk[i4++] = (t5 & 15) << 12 | (buffer[start2++] & 63) << 6 | buffer[start2++] & 63;
        if (i4 > 8191) {
          (parts2 || (parts2 = [])).push(String.fromCharCode.apply(String, chunk));
          i4 = 0;
        }
      }
      if (parts2) {
        if (i4)
          parts2.push(String.fromCharCode.apply(String, chunk.slice(0, i4)));
        return parts2.join("");
      }
      return String.fromCharCode.apply(String, chunk.slice(0, i4));
    }, "utf8_read");
    utf8.write = /* @__PURE__ */ __name(function utf8_write(string4, buffer, offset) {
      var start2 = offset, c1, c22;
      for (var i4 = 0; i4 < string4.length; ++i4) {
        c1 = string4.charCodeAt(i4);
        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(i4 + 1)) & 64512) === 56320) {
          c1 = 65536 + ((c1 & 1023) << 10) + (c22 & 1023);
          ++i4;
          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 - start2;
    }, "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 util5 = 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 (util5.isString(value)) {
        if (util5.Long)
          value = util5.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 util5.Long ? new util5.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 util5 = exports2;
    util5.asPromise = require_aspromise();
    util5.base64 = require_base64();
    util5.EventEmitter = require_eventemitter();
    util5.float = require_float();
    util5.inquire = require_inquire();
    util5.utf8 = require_utf82();
    util5.pool = require_pool2();
    util5.LongBits = require_longbits();
    util5.isNode = Boolean(typeof globalThis !== "undefined" && globalThis && globalThis.process && globalThis.process.versions && globalThis.process.versions.node);
    util5.global = util5.isNode && globalThis || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2;
    util5.emptyArray = Object.freeze ? Object.freeze([]) : (
      /* istanbul ignore next */
      []
    );
    util5.emptyObject = Object.freeze ? Object.freeze({}) : (
      /* istanbul ignore next */
      {}
    );
    util5.isInteger = Number.isInteger || /* istanbul ignore next */
    /* @__PURE__ */ __name(function isInteger2(value) {
      return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
    }, "isInteger");
    util5.isString = /* @__PURE__ */ __name(function isString3(value) {
      return typeof value === "string" || value instanceof String;
    }, "isString");
    util5.isObject = /* @__PURE__ */ __name(function isObject5(value) {
      return value && typeof value === "object";
    }, "isObject");
    util5.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`
     */
    util5.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");
    util5.Buffer = function() {
      try {
        var Buffer9 = util5.inquire("buffer").Buffer;
        return Buffer9.prototype.utf8Write ? Buffer9 : (
          /* istanbul ignore next */
          null
        );
      } catch (e4) {
        return null;
      }
    }();
    util5._Buffer_from = null;
    util5._Buffer_allocUnsafe = null;
    util5.newBuffer = /* @__PURE__ */ __name(function newBuffer(sizeOrArray) {
      return typeof sizeOrArray === "number" ? util5.Buffer ? util5._Buffer_allocUnsafe(sizeOrArray) : new util5.Array(sizeOrArray) : util5.Buffer ? util5._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray);
    }, "newBuffer");
    util5.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
    util5.Long = /* istanbul ignore next */
    util5.global.dcodeIO && /* istanbul ignore next */
    util5.global.dcodeIO.Long || /* istanbul ignore next */
    util5.global.Long || util5.inquire("long");
    util5.key2Re = /^true|false|0|1$/;
    util5.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
    util5.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
    util5.longToHash = /* @__PURE__ */ __name(function longToHash(value) {
      return value ? util5.LongBits.from(value).toHash() : util5.LongBits.zeroHash;
    }, "longToHash");
    util5.longFromHash = /* @__PURE__ */ __name(function longFromHash(hash, unsigned) {
      var bits = util5.LongBits.fromHash(hash);
      if (util5.Long)
        return util5.Long.fromBits(bits.lo, bits.hi, unsigned);
      return bits.toNumber(Boolean(unsigned));
    }, "longFromHash");
    function merge5(dst, src, ifNotSet) {
      for (var keys = Object.keys(src), i4 = 0; i4 < keys.length; ++i4)
        if (dst[keys[i4]] === void 0 || !ifNotSet)
          dst[keys[i4]] = src[keys[i4]];
      return dst;
    }
    __name(merge5, "merge");
    util5.merge = merge5;
    util5.lcFirst = /* @__PURE__ */ __name(function lcFirst(str2) {
      return str2.charAt(0).toLowerCase() + str2.substring(1);
    }, "lcFirst");
    function newError(name4) {
      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)
          merge5(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 name4;
          }, "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");
    util5.newError = newError;
    util5.ProtocolError = newError("ProtocolError");
    util5.oneOfGetter = /* @__PURE__ */ __name(function getOneOf(fieldNames) {
      var fieldMap = {};
      for (var i4 = 0; i4 < fieldNames.length; ++i4)
        fieldMap[fieldNames[i4]] = 1;
      return function() {
        for (var keys = Object.keys(this), i5 = keys.length - 1; i5 > -1; --i5)
          if (fieldMap[keys[i5]] === 1 && this[keys[i5]] !== void 0 && this[keys[i5]] !== null)
            return keys[i5];
      };
    }, "getOneOf");
    util5.oneOfSetter = /* @__PURE__ */ __name(function setOneOf(fieldNames) {
      return function(name4) {
        for (var i4 = 0; i4 < fieldNames.length; ++i4)
          if (fieldNames[i4] !== name4)
            delete this[fieldNames[i4]];
      };
    }, "setOneOf");
    util5.toJSONOptions = {
      longs: String,
      enums: String,
      bytes: String,
      json: true
    };
    util5._configure = function() {
      var Buffer9 = util5.Buffer;
      if (!Buffer9) {
        util5._Buffer_from = util5._Buffer_allocUnsafe = null;
        return;
      }
      util5._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");
      util5._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 util5 = require_minimal();
    var BufferWriter;
    var LongBits = util5.LongBits;
    var base643 = util5.base64;
    var utf8 = util5.utf8;
    function Op(fn, len, val) {
      this.fn = fn;
      this.len = len;
      this.next = void 0;
      this.val = val;
    }
    __name(Op, "Op");
    function noop11() {
    }
    __name(noop11, "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(noop11, 0, 0);
      this.tail = this.head;
      this.states = null;
    }
    __name(Writer, "Writer");
    var create4 = /* @__PURE__ */ __name(function create5() {
      return util5.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 = create4();
    Writer.alloc = /* @__PURE__ */ __name(function alloc(size) {
      return new util5.Array(size);
    }, "alloc");
    if (util5.Array !== Array)
      Writer.alloc = util5.pool(Writer.alloc, util5.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(util5.float.writeFloatLE, 4, value);
    }, "write_float");
    Writer.prototype.double = /* @__PURE__ */ __name(function write_double(value) {
      return this._push(util5.float.writeDoubleLE, 8, value);
    }, "write_double");
    var writeBytes = util5.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 i4 = 0; i4 < val.length; ++i4)
        buf[pos2 + i4] = val[i4];
    }, "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 (util5.isString(value)) {
        var buf = Writer.alloc(len = base643.length(value));
        base643.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(noop11, 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(noop11, 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 = create4();
      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 util5 = require_minimal();
    function BufferWriter() {
      Writer.call(this);
    }
    __name(BufferWriter, "BufferWriter");
    BufferWriter._configure = function() {
      BufferWriter.alloc = util5._Buffer_allocUnsafe;
      BufferWriter.writeBytesBuffer = util5.Buffer && util5.Buffer.prototype instanceof Uint8Array && util5.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 i4 = 0; i4 < val.length; )
          buf[pos2++] = val[i4++];
      }, "writeBytesBuffer_copy");
    };
    BufferWriter.prototype.bytes = /* @__PURE__ */ __name(function write_bytes_buffer(value) {
      if (util5.isString(value))
        value = util5._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)
        util5.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 = util5.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 util5 = require_minimal();
    var BufferReader;
    var LongBits = util5.LongBits;
    var utf8 = util5.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 create4 = /* @__PURE__ */ __name(function create5() {
      return util5.Buffer ? /* @__PURE__ */ __name(function create_buffer_setup(buffer) {
        return (Reader.create = /* @__PURE__ */ __name(function create_buffer(buffer2) {
          return util5.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2);
        }, "create_buffer"))(buffer);
      }, "create_buffer_setup") : create_array;
    }, "create");
    Reader.create = create4();
    Reader.prototype._slice = util5.Array.prototype.subarray || /* istanbul ignore next */
    util5.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 i4 = 0;
      if (this.len - this.pos > 4) {
        for (; i4 < 4; ++i4) {
          bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i4 * 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;
        i4 = 0;
      } else {
        for (; i4 < 3; ++i4) {
          if (this.pos >= this.len)
            throw indexOutOfRange(this);
          bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i4 * 7) >>> 0;
          if (this.buf[this.pos++] < 128)
            return bits;
        }
        bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i4 * 7) >>> 0;
        return bits;
      }
      if (this.len - this.pos > 4) {
        for (; i4 < 5; ++i4) {
          bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i4 * 7 + 3) >>> 0;
          if (this.buf[this.pos++] < 128)
            return bits;
        }
      } else {
        for (; i4 < 5; ++i4) {
          if (this.pos >= this.len)
            throw indexOutOfRange(this);
          bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i4 * 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 = util5.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 = util5.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(), start2 = 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(start2, end);
      if (start2 === end) {
        var nativeBuffer = util5.Buffer;
        return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0);
      }
      return this._slice.call(this.buf, start2, 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 = create4();
      BufferReader._configure();
      var fn = util5.Long ? "toLong" : (
        /* istanbul ignore next */
        "toNumber"
      );
      util5.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 util5 = require_minimal();
    function BufferReader(buffer) {
      Reader.call(this, buffer);
    }
    __name(BufferReader, "BufferReader");
    BufferReader._configure = function() {
      if (util5.Buffer)
        BufferReader.prototype._slice = util5.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 util5 = require_minimal();
    (Service.prototype = Object.create(util5.EventEmitter.prototype)).constructor = Service;
    function Service(rpcImpl, requestDelimited, responseDelimited) {
      if (typeof rpcImpl !== "function")
        throw TypeError("rpcImpl must be a function");
      util5.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 util5.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(err2, response) {
            if (err2) {
              self2.emit("error", err2, method);
              return callback(err2);
            }
            if (response === null) {
              self2.end(
                /* endedByRPC */
                true
              );
              return void 0;
            }
            if (!(response instanceof responseCtor)) {
              try {
                response = responseCtor[self2.responseDelimited ? "decodeDelimited" : "decode"](response);
              } catch (err3) {
                self2.emit("error", err3, method);
                return callback(err3);
              }
            }
            self2.emit("data", response, method);
            return callback(null, response);
          }, "rpcCallback")
        );
      } catch (err2) {
        self2.emit("error", err2, method);
        setTimeout(function() {
          callback(err2);
        }, 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 body2 = [];
      function Codegen(formatStringOrScope) {
        if (typeof formatStringOrScope !== "string") {
          var source2 = toString3();
          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");
        body2.push(formatStringOrScope);
        return Codegen;
      }
      __name(Codegen, "Codegen");
      function toString3(functionNameOverride) {
        return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n  " + body2.join("\n  ") + "\n}";
      }
      __name(toString3, "toString");
      Codegen.toString = toString3;
      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 fs142 = 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 && fs142 && fs142.readFile)
        return fs142.readFile(filename, /* @__PURE__ */ __name(function fetchReadFileCallback(err2, contents) {
          return err2 && typeof XMLHttpRequest !== "undefined" ? fetch5.xhr(filename, options2, callback) : err2 ? callback(err2) : 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 i4 = 0; i4 < xhr.responseText.length; ++i4)
              buffer.push(xhr.responseText.charCodeAt(i4) & 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 path150 = exports2;
    var isAbsolute21 = (
      /**
       * Tests if the specified path is absolute.
       * @param {string} path Path to test
       * @returns {boolean} `true` if path is absolute
       */
      path150.isAbsolute = /* @__PURE__ */ __name(function isAbsolute22(path151) {
        return /^(?:\/|\w+:)/.test(path151);
      }, "isAbsolute")
    );
    var normalize13 = (
      /**
       * Normalizes the specified path.
       * @param {string} path Path to normalize
       * @returns {string} Normalized path
       */
      path150.normalize = /* @__PURE__ */ __name(function normalize14(path151) {
        path151 = path151.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
        var parts2 = path151.split("/"), absolute = isAbsolute21(path151), prefix = "";
        if (absolute)
          prefix = parts2.shift() + "/";
        for (var i4 = 0; i4 < parts2.length; ) {
          if (parts2[i4] === "..") {
            if (i4 > 0 && parts2[i4 - 1] !== "..")
              parts2.splice(--i4, 2);
            else if (absolute)
              parts2.splice(i4, 1);
            else
              ++i4;
          } else if (parts2[i4] === ".")
            parts2.splice(i4, 1);
          else
            ++i4;
        }
        return prefix + parts2.join("/");
      }, "normalize")
    );
    path150.resolve = /* @__PURE__ */ __name(function resolve42(originPath, includePath, alreadyNormalized) {
      if (!alreadyNormalized)
        includePath = normalize13(includePath);
      if (isAbsolute21(includePath))
        return includePath;
      if (!alreadyNormalized)
        originPath = normalize13(originPath);
      return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize13(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 util5 = require_util13();
    var OneOf = require_oneof();
    var Type3;
    var Service;
    var Enum;
    Namespace.fromJSON = /* @__PURE__ */ __name(function fromJSON(name4, json3) {
      return new Namespace(name4, json3.options).addJSON(json3.nested);
    }, "fromJSON");
    function arrayToJSON(array2, toJSONOptions) {
      if (!(array2 && array2.length))
        return void 0;
      var obj = {};
      for (var i4 = 0; i4 < array2.length; ++i4)
        obj[array2[i4].name] = array2[i4].toJSON(toJSONOptions);
      return obj;
    }
    __name(arrayToJSON, "arrayToJSON");
    Namespace.arrayToJSON = arrayToJSON;
    Namespace.isReservedId = /* @__PURE__ */ __name(function isReservedId(reserved, id) {
      if (reserved) {
        for (var i4 = 0; i4 < reserved.length; ++i4)
          if (typeof reserved[i4] !== "string" && reserved[i4][0] <= id && reserved[i4][1] > id)
            return true;
      }
      return false;
    }, "isReservedId");
    Namespace.isReservedName = /* @__PURE__ */ __name(function isReservedName(reserved, name4) {
      if (reserved) {
        for (var i4 = 0; i4 < reserved.length; ++i4)
          if (reserved[i4] === name4)
            return true;
      }
      return false;
    }, "isReservedName");
    function Namespace(name4, options2) {
      ReflectionObject.call(this, name4, 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 = util5.toArray(this.nested));
      }, "get")
    });
    Namespace.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      return util5.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), i4 = 0, nested; i4 < names.length; ++i4) {
          nested = nestedJson[names[i4]];
          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[i4], nested)
          );
        }
      }
      return this;
    }, "addJSON");
    Namespace.prototype.get = /* @__PURE__ */ __name(function get4(name4) {
      return this.nested && this.nested[name4] || null;
    }, "get");
    Namespace.prototype.getEnum = /* @__PURE__ */ __name(function getEnum(name4) {
      if (this.nested && this.nested[name4] instanceof Enum)
        return this.nested[name4].values;
      throw Error("no such enum: " + name4);
    }, "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 i4 = 0; i4 < nested.length; ++i4)
              object3.add(nested[i4]);
            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(path150, json3) {
      if (util5.isString(path150))
        path150 = path150.split(".");
      else if (!Array.isArray(path150))
        throw TypeError("illegal path");
      if (path150 && path150.length && path150[0] === "")
        throw Error("path must be relative");
      var ptr = this;
      while (path150.length > 0) {
        var part = path150.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 (json3)
        ptr.addJSON(json3);
      return ptr;
    }, "define");
    Namespace.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      this._resolveFeaturesRecursive(this._edition);
      var nested = this.nestedArray, i4 = 0;
      this.resolve();
      while (i4 < nested.length)
        if (nested[i4] instanceof Namespace)
          nested[i4++].resolveAll();
        else
          nested[i4++].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 lookup2(path150, filterTypes, parentAlreadyChecked) {
      if (typeof filterTypes === "boolean") {
        parentAlreadyChecked = filterTypes;
        filterTypes = void 0;
      } else if (filterTypes && !Array.isArray(filterTypes))
        filterTypes = [filterTypes];
      if (util5.isString(path150) && path150.length) {
        if (path150 === ".")
          return this.root;
        path150 = path150.split(".");
      } else if (!path150.length)
        return this;
      var flatPath = path150.join(".");
      if (path150[0] === "")
        return this.root.lookup(path150.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(path150, 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(path150, flatPath);
        if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) {
          return found;
        }
        current = current.parent;
      }
      return null;
    }, "lookup");
    Namespace.prototype._lookupImpl = /* @__PURE__ */ __name(function lookup2(path150, flatPath) {
      if (Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) {
        return this._lookupCache[flatPath];
      }
      var found = this.get(path150[0]);
      var exact = null;
      if (found) {
        if (path150.length === 1) {
          exact = found;
        } else if (found instanceof Namespace) {
          path150 = path150.slice(1);
          exact = found._lookupImpl(path150, path150.join("."));
        }
      } else {
        for (var i4 = 0; i4 < this.nestedArray.length; ++i4)
          if (this._nestedArray[i4] instanceof Namespace && (found = this._nestedArray[i4]._lookupImpl(path150, flatPath)))
            exact = found;
      }
      this._lookupCache[flatPath] = exact;
      return exact;
    }, "lookup");
    Namespace.prototype.lookupType = /* @__PURE__ */ __name(function lookupType(path150) {
      var found = this.lookup(path150, [Type3]);
      if (!found)
        throw Error("no such type: " + path150);
      return found;
    }, "lookupType");
    Namespace.prototype.lookupEnum = /* @__PURE__ */ __name(function lookupEnum(path150) {
      var found = this.lookup(path150, [Enum]);
      if (!found)
        throw Error("no such Enum '" + path150 + "' in " + this);
      return found;
    }, "lookupEnum");
    Namespace.prototype.lookupTypeOrEnum = /* @__PURE__ */ __name(function lookupTypeOrEnum(path150) {
      var found = this.lookup(path150, [Type3, Enum]);
      if (!found)
        throw Error("no such Type or Enum '" + path150 + "' in " + this);
      return found;
    }, "lookupTypeOrEnum");
    Namespace.prototype.lookupService = /* @__PURE__ */ __name(function lookupService(path150) {
      var found = this.lookup(path150, [Service]);
      if (!found)
        throw Error("no such Service '" + path150 + "' 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 util5 = require_util13();
    function MapField(name4, id, keyType, type, options2, comment) {
      Field.call(this, name4, id, type, void 0, void 0, options2, comment);
      if (!util5.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(name4, json3) {
      return new MapField(name4, json3.id, json3.keyType, json3.type, json3.options, json3.comment);
    }, "fromJSON");
    MapField.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util5.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 resolve42() {
      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 = util5.decorateType(fieldValueType).name;
      else if (fieldValueType && typeof fieldValueType === "object")
        fieldValueType = util5.decorateEnum(fieldValueType).name;
      return /* @__PURE__ */ __name(function mapFieldDecorator(prototype2, fieldName) {
        util5.decorateType(prototype2.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 util5 = require_util13();
    function Method(name4, type, requestType, responseType, requestStream, responseStream, options2, comment, parsedOptions) {
      if (util5.isObject(requestStream)) {
        options2 = requestStream;
        requestStream = responseStream = void 0;
      } else if (util5.isObject(responseStream)) {
        options2 = responseStream;
        responseStream = void 0;
      }
      if (!(type === void 0 || util5.isString(type)))
        throw TypeError("type must be a string");
      if (!util5.isString(requestType))
        throw TypeError("requestType must be a string");
      if (!util5.isString(responseType))
        throw TypeError("responseType must be a string");
      ReflectionObject.call(this, name4, 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(name4, json3) {
      return new Method(name4, json3.type, json3.requestType, json3.responseType, json3.requestStream, json3.responseStream, json3.options, json3.comment, json3.parsedOptions);
    }, "fromJSON");
    Method.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util5.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 resolve42() {
      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 util5 = require_util13();
    var rpc = require_rpc();
    function Service(name4, options2) {
      Namespace.call(this, name4, options2);
      this.methods = {};
      this._methodsArray = null;
    }
    __name(Service, "Service");
    Service.fromJSON = /* @__PURE__ */ __name(function fromJSON(name4, json3) {
      var service = new Service(name4, json3.options);
      if (json3.methods)
        for (var names = Object.keys(json3.methods), i4 = 0; i4 < names.length; ++i4)
          service.add(Method.fromJSON(names[i4], json3.methods[names[i4]]));
      if (json3.nested)
        service.addJSON(json3.nested);
      if (json3.edition)
        service._edition = json3.edition;
      service.comment = json3.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 util5.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 = util5.toArray(this.methods));
      }, "get")
    });
    function clearCache(service) {
      service._methodsArray = null;
      return service;
    }
    __name(clearCache, "clearCache");
    Service.prototype.get = /* @__PURE__ */ __name(function get4(name4) {
      return this.methods[name4] || Namespace.prototype.get.call(this, name4);
    }, "get");
    Service.prototype.resolveAll = /* @__PURE__ */ __name(function resolveAll() {
      if (!this._needsRecursiveResolve) return this;
      Namespace.prototype.resolve.call(this);
      var methods = this.methodsArray;
      for (var i4 = 0; i4 < methods.length; ++i4)
        methods[i4].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 create4(rpcImpl, requestDelimited, responseDelimited) {
      var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);
      for (var i4 = 0, method; i4 < /* initializes */
      this.methodsArray.length; ++i4) {
        var methodName = util5.lcFirst((method = this._methodsArray[i4]).resolve().name).replace(/[^$\w_]/g, "");
        rpcService[methodName] = util5.codegen(["r", "c"], util5.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 util5 = require_minimal();
    function Message(properties) {
      if (properties)
        for (var keys = Object.keys(properties), i4 = 0; i4 < keys.length; ++i4)
          this[keys[i4]] = properties[keys[i4]];
    }
    __name(Message, "Message");
    Message.create = /* @__PURE__ */ __name(function create4(properties) {
      return this.$type.create(properties);
    }, "create");
    Message.encode = /* @__PURE__ */ __name(function encode6(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, util5.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 util5 = require_util13();
    function missing(field) {
      return "missing required '" + field.name + "'";
    }
    __name(missing, "missing");
    function decoder(mtype) {
      var gen = util5.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 i4 = 0;
      for (; i4 < /* initializes */
      mtype.fieldsArray.length; ++i4) {
        var field = mtype._fieldsArray[i4].resolve(), type = field.resolvedType instanceof Enum ? "int32" : field.type, ref = "m" + util5.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())", i4);
          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, i4);
          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, i4);
        else gen("%s=r.%s()", ref, type);
        gen("break")("}");
      }
      gen("default:")("r.skipType(t&7)")("break")("}")("}");
      for (i4 = 0; i4 < mtype._fieldsArray.length; ++i4) {
        var rfield = mtype._fieldsArray[i4];
        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 util5 = 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 = util5.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 i4 = 0; i4 < /* initializes */
      mtype.fieldsArray.length; ++i4) {
        var field = mtype._fieldsArray[i4].resolve(), ref = "m" + util5.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, i4, 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, i4, ref + "[i]")("}");
        } else {
          if (field.partOf) {
            var oneofProp = util5.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, i4, 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 util5 = 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), i4 = 0; i4 < keys.length; ++i4) {
            if (values[keys[i4]] === 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[i4])("case %i:", values[keys[i4]])("m%s=%j", prop, values[keys[i4]])("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 = util5.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 i4 = 0; i4 < fields.length; ++i4) {
        var field = fields[i4].resolve(), prop = util5.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 */
            i4,
            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 */
            i4,
            prop + "[i]"
          )("}")("}");
        } else {
          if (!(field.resolvedType instanceof Enum)) gen("if(d%s!=null){", prop);
          genValuePartial_fromObject(
            gen,
            field,
            /* not sorted */
            i4,
            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(util5.compareFieldsById);
      if (!fields.length)
        return util5.codegen()("return {}");
      var gen = util5.codegen(["m", "o"], mtype.name + "$toObject")("if(!o)")("o={}")("var d={}");
      var repeatedFields = [], mapFields = [], normalFields = [], i4 = 0;
      for (; i4 < fields.length; ++i4)
        if (!fields[i4].partOf)
          (fields[i4].resolve().repeated ? repeatedFields : fields[i4].map ? mapFields : normalFields).push(fields[i4]);
      if (repeatedFields.length) {
        gen("if(o.arrays||o.defaults){");
        for (i4 = 0; i4 < repeatedFields.length; ++i4) gen("d%s=[]", util5.safeProp(repeatedFields[i4].name));
        gen("}");
      }
      if (mapFields.length) {
        gen("if(o.objects||o.defaults){");
        for (i4 = 0; i4 < mapFields.length; ++i4) gen("d%s={}", util5.safeProp(mapFields[i4].name));
        gen("}");
      }
      if (normalFields.length) {
        gen("if(o.defaults){");
        for (i4 = 0; i4 < normalFields.length; ++i4) {
          var field = normalFields[i4], prop = util5.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 (i4 = 0; i4 < fields.length; ++i4) {
        var field = fields[i4], index = mtype._fieldsArray.indexOf(field), prop = util5.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", util5.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 name4 = object3["@type"].substring(object3["@type"].lastIndexOf("/") + 1);
          var type = this.lookup(name4);
          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 name4 = "";
        if (options2 && options2.json && message.type_url && message.value) {
          name4 = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);
          prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1);
          var type = this.lookup(name4);
          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;
          }
          name4 = prefix + messageName;
          object3["@type"] = name4;
          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 util5 = require_util13();
    var encoder = require_encoder();
    var decoder = require_decoder();
    var verifier = require_verifier();
    var converter = require_converter();
    var wrappers = require_wrappers();
    function Type3(name4, options2) {
      Namespace.call(this, name4, 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), i4 = 0; i4 < names.length; ++i4) {
            var field = this.fields[names[i4]], 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 = util5.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 = util5.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 prototype2 = ctor.prototype;
          if (!(prototype2 instanceof Message)) {
            (ctor.prototype = new Message()).constructor = ctor;
            util5.merge(ctor.prototype, prototype2);
          }
          ctor.$type = ctor.prototype.$type = this;
          util5.merge(ctor, Message, true);
          this._ctor = ctor;
          var i4 = 0;
          for (; i4 < /* initializes */
          this.fieldsArray.length; ++i4)
            this._fieldsArray[i4].resolve();
          var ctorProperties = {};
          for (i4 = 0; i4 < /* initializes */
          this.oneofsArray.length; ++i4)
            ctorProperties[this._oneofsArray[i4].resolve().name] = {
              get: util5.oneOfGetter(this._oneofsArray[i4].oneof),
              set: util5.oneOfSetter(this._oneofsArray[i4].oneof)
            };
          if (i4)
            Object.defineProperties(ctor.prototype, ctorProperties);
        }, "set")
      }
    });
    Type3.generateConstructor = /* @__PURE__ */ __name(function generateConstructor(mtype) {
      var gen = util5.codegen(["p"], mtype.name);
      for (var i4 = 0, field; i4 < mtype.fieldsArray.length; ++i4)
        if ((field = mtype._fieldsArray[i4]).map) gen("this%s={}", util5.safeProp(field.name));
        else if (field.repeated) gen("this%s=[]", util5.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(name4, json3) {
      var type = new Type3(name4, json3.options);
      type.extensions = json3.extensions;
      type.reserved = json3.reserved;
      var names = Object.keys(json3.fields), i4 = 0;
      for (; i4 < names.length; ++i4)
        type.add(
          (typeof json3.fields[names[i4]].keyType !== "undefined" ? MapField.fromJSON : Field.fromJSON)(names[i4], json3.fields[names[i4]])
        );
      if (json3.oneofs)
        for (names = Object.keys(json3.oneofs), i4 = 0; i4 < names.length; ++i4)
          type.add(OneOf.fromJSON(names[i4], json3.oneofs[names[i4]]));
      if (json3.nested)
        for (names = Object.keys(json3.nested), i4 = 0; i4 < names.length; ++i4) {
          var nested = json3.nested[names[i4]];
          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[i4], nested)
          );
        }
      if (json3.extensions && json3.extensions.length)
        type.extensions = json3.extensions;
      if (json3.reserved && json3.reserved.length)
        type.reserved = json3.reserved;
      if (json3.group)
        type.group = true;
      if (json3.comment)
        type.comment = json3.comment;
      if (json3.edition)
        type._edition = json3.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 util5.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;
      i4 = 0;
      while (i4 < oneofs.length)
        oneofs[i4++].resolve();
      var fields = this.fieldsArray, i4 = 0;
      while (i4 < fields.length)
        fields[i4++].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(name4) {
      return this.fields[name4] || this.oneofs && this.oneofs[name4] || this.nested && this.nested[name4] || 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(name4) {
      return Namespace.isReservedName(this.reserved, name4);
    }, "isReservedName");
    Type3.prototype.create = /* @__PURE__ */ __name(function create4(properties) {
      return new this.ctor(properties);
    }, "create");
    Type3.prototype.setup = /* @__PURE__ */ __name(function setup() {
      var fullName = this.fullName, types7 = [];
      for (var i4 = 0; i4 < /* initializes */
      this.fieldsArray.length; ++i4)
        types7.push(this._fieldsArray[i4].resolve().resolvedType);
      this.encode = encoder(this)({
        Writer,
        types: types7,
        util: util5
      });
      this.decode = decoder(this)({
        Reader,
        types: types7,
        util: util5
      });
      this.verify = verifier(this)({
        types: types7,
        util: util5
      });
      this.fromObject = converter.fromObject(this)({
        types: types7,
        util: util5
      });
      this.toObject = converter.toObject(this)({
        types: types7,
        util: util5
      });
      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) {
        util5.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 util5 = require_util13();
    var Type3;
    var parse17;
    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(json3, root) {
      if (!root)
        root = new Root2();
      if (json3.options)
        root.setOptions(json3.options);
      return root.addJSON(json3.nested).resolveAll();
    }, "fromJSON");
    Root2.prototype.resolvePath = util5.path.resolve;
    Root2.prototype.fetch = util5.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 util5.asPromise(load, self2, filename, options2);
      }
      var sync2 = callback === SYNC;
      function finish(err2, root) {
        if (!callback) {
          return;
        }
        if (sync2) {
          throw err2;
        }
        if (root) {
          root.resolveAll();
        }
        var cb = callback;
        callback = null;
        cb(err2, root);
      }
      __name(finish, "finish");
      function getBundledFileName(filename2) {
        var idx = filename2.lastIndexOf("google/protobuf/");
        if (idx > -1) {
          var altname = filename2.substring(idx);
          if (altname in common) return altname;
        }
        return null;
      }
      __name(getBundledFileName, "getBundledFileName");
      function process51(filename2, source2) {
        try {
          if (util5.isString(source2) && source2.charAt(0) === "{")
            source2 = JSON.parse(source2);
          if (!util5.isString(source2))
            self2.setOptions(source2.options).addJSON(source2.nested);
          else {
            parse17.filename = filename2;
            var parsed = parse17(source2, self2, options2), resolved2, i5 = 0;
            if (parsed.imports) {
              for (; i5 < parsed.imports.length; ++i5)
                if (resolved2 = getBundledFileName(parsed.imports[i5]) || self2.resolvePath(filename2, parsed.imports[i5]))
                  fetch5(resolved2);
            }
            if (parsed.weakImports) {
              for (i5 = 0; i5 < parsed.weakImports.length; ++i5)
                if (resolved2 = getBundledFileName(parsed.weakImports[i5]) || self2.resolvePath(filename2, parsed.weakImports[i5]))
                  fetch5(resolved2, true);
            }
          }
        } catch (err2) {
          finish(err2);
        }
        if (!sync2 && !queued) {
          finish(null, self2);
        }
      }
      __name(process51, "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) {
            process51(filename2, common[filename2]);
          } else {
            ++queued;
            setTimeout(function() {
              --queued;
              process51(filename2, common[filename2]);
            });
          }
          return;
        }
        if (sync2) {
          var source2;
          try {
            source2 = util5.fs.readFileSync(filename2).toString("utf8");
          } catch (err2) {
            if (!weak)
              finish(err2);
            return;
          }
          process51(filename2, source2);
        } else {
          ++queued;
          self2.fetch(filename2, function(err2, source3) {
            --queued;
            if (!callback) {
              return;
            }
            if (err2) {
              if (!weak)
                finish(err2);
              else if (!queued)
                finish(null, self2);
              return;
            }
            process51(filename2, source3);
          });
        }
      }
      __name(fetch5, "fetch");
      var queued = 0;
      if (util5.isString(filename)) {
        filename = [filename];
      }
      for (var i4 = 0, resolved; i4 < filename.length; ++i4)
        if (resolved = self2.resolvePath("", filename[i4]))
          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 (!util5.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 i4 = 0; i4 < this.deferred.length; )
            if (tryHandleExtension(this, this.deferred[i4]))
              this.deferred.splice(i4, 1);
            else
              ++i4;
        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 i4 = 0; i4 < /* initializes */
        object3.nestedArray.length; ++i4)
          this._handleRemove(object3._nestedArray[i4]);
        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_;
      parse17 = 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 util5 = module2.exports = require_minimal();
    var roots = require_roots();
    var Type3;
    var Enum;
    util5.codegen = require_codegen3();
    util5.fetch = require_fetch2();
    util5.path = require_path();
    util5.fs = util5.inquire("fs");
    util5.toArray = /* @__PURE__ */ __name(function toArray2(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");
    util5.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;
    util5.isReserved = /* @__PURE__ */ __name(function isReserved(name4) {
      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(name4);
    }, "isReserved");
    util5.safeProp = /* @__PURE__ */ __name(function safeProp(prop) {
      if (!/^[$\w_]+$/.test(prop) || util5.isReserved(prop))
        return '["' + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, '\\"') + '"]';
      return "." + prop;
    }, "safeProp");
    util5.ucFirst = /* @__PURE__ */ __name(function ucFirst(str2) {
      return str2.charAt(0).toUpperCase() + str2.substring(1);
    }, "ucFirst");
    var camelCaseRe = /_([a-z])/g;
    util5.camelCase = /* @__PURE__ */ __name(function camelCase3(str2) {
      return str2.substring(0, 1) + str2.substring(1).replace(camelCaseRe, function($0, $1) {
        return $1.toUpperCase();
      });
    }, "camelCase");
    util5.compareFieldsById = /* @__PURE__ */ __name(function compareFieldsById(a2, b2) {
      return a2.id - b2.id;
    }, "compareFieldsById");
    util5.decorateType = /* @__PURE__ */ __name(function decorateType(ctor, typeName) {
      if (ctor.$type) {
        if (typeName && ctor.$type.name !== typeName) {
          util5.decorateRoot.remove(ctor.$type);
          ctor.$type.name = typeName;
          util5.decorateRoot.add(ctor.$type);
        }
        return ctor.$type;
      }
      if (!Type3)
        Type3 = require_type();
      var type = new Type3(typeName || ctor.name);
      util5.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;
    util5.decorateEnum = /* @__PURE__ */ __name(function decorateEnum(object3) {
      if (object3.$type)
        return object3.$type;
      if (!Enum)
        Enum = require_enum3();
      var enm = new Enum("Enum" + decorateEnumIndex++, object3);
      util5.decorateRoot.add(enm);
      Object.defineProperty(object3, "$type", { value: enm, enumerable: false });
      return enm;
    }, "decorateEnum");
    util5.setProperty = /* @__PURE__ */ __name(function setProperty2(dst, path150, value, ifNotSet) {
      function setProp(dst2, path151, value2) {
        var part = path151.shift();
        if (part === "__proto__" || part === "prototype") {
          return dst2;
        }
        if (path151.length > 0) {
          dst2[part] = setProp(dst2[part] || {}, path151, 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 (!path150)
        throw TypeError("path must be specified");
      path150 = path150.split(".");
      return setProp(dst, path150, value);
    }, "setProperty");
    Object.defineProperty(util5, "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 util5 = 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 i4 = 0, o3 = {};
      offset |= 0;
      while (i4 < values.length) o3[s5[i4 + offset]] = values[i4++];
      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    */
      util5.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 util5 = require_util13();
    var Type3;
    var ruleRe = /^required|optional|repeated$/;
    Field.fromJSON = /* @__PURE__ */ __name(function fromJSON(name4, json3) {
      var field = new Field(name4, json3.id, json3.type, json3.rule, json3.extend, json3.options, json3.comment);
      if (json3.edition)
        field._edition = json3.edition;
      field._defaultEdition = "proto3";
      return field;
    }, "fromJSON");
    function Field(name4, id, type, rule, extend3, options2, comment) {
      if (util5.isObject(rule)) {
        comment = extend3;
        options2 = rule;
        rule = extend3 = void 0;
      } else if (util5.isObject(extend3)) {
        comment = options2;
        options2 = extend3;
        extend3 = void 0;
      }
      ReflectionObject.call(this, name4, options2);
      if (!util5.isInteger(id) || id < 0)
        throw TypeError("id must be a non-negative integer");
      if (!util5.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 (extend3 !== void 0 && !util5.isString(extend3))
        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 = extend3 || void 0;
      this.repeated = rule === "repeated";
      this.map = false;
      this.message = null;
      this.partOf = null;
      this.typeDefault = null;
      this.defaultValue = null;
      this.long = util5.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(name4, value, ifNotSet) {
      return ReflectionObject.prototype.setOption.call(this, name4, value, ifNotSet);
    }, "setOption");
    Field.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util5.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 resolve42() {
      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 = util5.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 (util5.base64.test(this.typeDefault))
          util5.base64.decode(this.typeDefault, buf = util5.newBuffer(util5.base64.length(this.typeDefault)), 0);
        else
          util5.utf8.write(this.typeDefault, buf = util5.newBuffer(util5.utf8.length(this.typeDefault)), 0);
        this.typeDefault = buf;
      }
      if (this.map)
        this.defaultValue = util5.emptyObject;
      else if (this.repeated)
        this.defaultValue = util5.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 = util5.decorateType(fieldType).name;
      else if (fieldType && typeof fieldType === "object")
        fieldType = util5.decorateEnum(fieldType).name;
      return /* @__PURE__ */ __name(function fieldDecorator(prototype2, fieldName) {
        util5.decorateType(prototype2.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 util5 = require_util13();
    function OneOf(name4, fieldNames, options2, comment) {
      if (!Array.isArray(fieldNames)) {
        options2 = fieldNames;
        fieldNames = void 0;
      }
      ReflectionObject.call(this, name4, 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(name4, json3) {
      return new OneOf(name4, json3.oneof, json3.options, json3.comment);
    }, "fromJSON");
    OneOf.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util5.toObject([
        "options",
        this.options,
        "oneof",
        this.oneof,
        "comment",
        keepComments ? this.comment : void 0
      ]);
    }, "toJSON");
    function addFieldsToParent(oneof) {
      if (oneof.parent) {
        for (var i4 = 0; i4 < oneof.fieldsArray.length; ++i4)
          if (!oneof.fieldsArray[i4].parent)
            oneof.parent.add(oneof.fieldsArray[i4]);
      }
    }
    __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 i4 = 0; i4 < this.oneof.length; ++i4) {
        var field = parent.get(this.oneof[i4]);
        if (field && !field.partOf) {
          field.partOf = self2;
          self2.fieldsArray.push(field);
        }
      }
      addFieldsToParent(this);
    }, "onAdd");
    OneOf.prototype.onRemove = /* @__PURE__ */ __name(function onRemove(parent) {
      for (var i4 = 0, field; i4 < this.fieldsArray.length; ++i4)
        if ((field = this.fieldsArray[i4]).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(prototype2, oneofName) {
        util5.decorateType(prototype2.constructor).add(new OneOf(oneofName, fieldNames));
        Object.defineProperty(prototype2, oneofName, {
          get: util5.oneOfGetter(fieldNames),
          set: util5.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 util5 = 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(name4, options2) {
      if (!util5.isString(name4))
        throw TypeError("name must be a string");
      if (options2 && !util5.isObject(options2))
        throw TypeError("options must be an object");
      this.options = options2;
      this.parsedOptions = null;
      this.name = name4;
      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 path150 = [this.name], ptr = this.parent;
          while (ptr) {
            path150.unshift(ptr.name);
            ptr = ptr.parent;
          }
          return path150.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 resolve42() {
      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 defaults4 = {};
      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") {
          defaults4 = Object.assign({}, proto2Defaults);
        } else if (edition === "proto3") {
          defaults4 = Object.assign({}, proto3Defaults);
        } else if (edition === "2023") {
          defaults4 = Object.assign({}, editions2023Defaults);
        } else {
          throw new Error("Unknown edition: " + edition);
        }
        this._features = Object.assign(defaults4, 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(name4) {
      if (this.options)
        return this.options[name4];
      return void 0;
    }, "getOption");
    ReflectionObject.prototype.setOption = /* @__PURE__ */ __name(function setOption(name4, value, ifNotSet) {
      if (!this.options)
        this.options = {};
      if (/^features\./.test(name4)) {
        util5.setProperty(this.options, name4, value, ifNotSet);
      } else if (!ifNotSet || this.options[name4] === void 0) {
        if (this.getOption(name4) !== value) this.resolved = false;
        this.options[name4] = value;
      }
      return this;
    }, "setOption");
    ReflectionObject.prototype.setParsedOption = /* @__PURE__ */ __name(function setParsedOption(name4, 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, name4);
        });
        if (opt) {
          var newValue = opt[name4];
          util5.setProperty(newValue, propName, value);
        } else {
          opt = {};
          opt[name4] = util5.setProperty({}, propName, value);
          parsedOptions.push(opt);
        }
      } else {
        var newOpt = {};
        newOpt[name4] = value;
        parsedOptions.push(newOpt);
      }
      return this;
    }, "setParsedOption");
    ReflectionObject.prototype.setOptions = /* @__PURE__ */ __name(function setOptions2(options2, ifNotSet) {
      if (options2)
        for (var keys = Object.keys(options2), i4 = 0; i4 < keys.length; ++i4)
          this.setOption(keys[i4], options2[keys[i4]], ifNotSet);
      return this;
    }, "setOptions");
    ReflectionObject.prototype.toString = /* @__PURE__ */ __name(function toString3() {
      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 util5 = require_util13();
    function Enum(name4, values, options2, comment, comments, valuesOptions) {
      ReflectionObject.call(this, name4, 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), i4 = 0; i4 < keys.length; ++i4)
          if (typeof values[keys[i4]] === "number")
            this.valuesById[this.values[keys[i4]] = values[keys[i4]]] = keys[i4];
      }
    }
    __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(name4, json3) {
      var enm = new Enum(name4, json3.values, json3.options, json3.comment, json3.comments);
      enm.reserved = json3.reserved;
      if (json3.edition)
        enm._edition = json3.edition;
      enm._defaultEdition = "proto3";
      return enm;
    }, "fromJSON");
    Enum.prototype.toJSON = /* @__PURE__ */ __name(function toJSON(toJSONOptions) {
      var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
      return util5.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(name4, id, comment, options2) {
      if (!util5.isString(name4))
        throw TypeError("name must be a string");
      if (!util5.isInteger(id))
        throw TypeError("id must be an integer");
      if (this.values[name4] !== void 0)
        throw Error("duplicate name '" + name4 + "' in " + this);
      if (this.isReservedId(id))
        throw Error("id " + id + " is reserved in " + this);
      if (this.isReservedName(name4))
        throw Error("name '" + name4 + "' 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[name4] = id;
      } else
        this.valuesById[this.values[name4] = id] = name4;
      if (options2) {
        if (this.valuesOptions === void 0)
          this.valuesOptions = {};
        this.valuesOptions[name4] = options2 || null;
      }
      this.comments[name4] = comment || null;
      return this;
    }, "add");
    Enum.prototype.remove = /* @__PURE__ */ __name(function remove2(name4) {
      if (!util5.isString(name4))
        throw TypeError("name must be a string");
      var val = this.values[name4];
      if (val == null)
        throw Error("name '" + name4 + "' does not exist in " + this);
      delete this.valuesById[val];
      delete this.values[name4];
      delete this.comments[name4];
      if (this.valuesOptions)
        delete this.valuesOptions[name4];
      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(name4) {
      return Namespace.isReservedName(this.reserved, name4);
    }, "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 util5 = 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 = util5.codegen(["m", "w"], mtype.name + "$encode")("if(!w)")("w=Writer.create()");
      var i4, ref;
      var fields = (
        /* initializes */
        mtype.fieldsArray.slice().sort(util5.compareFieldsById)
      );
      for (var i4 = 0; i4 < fields.length; ++i4) {
        var field = fields[i4].resolve(), index = mtype._fieldsArray.indexOf(field), type = field.resolvedType instanceof Enum ? "int32" : field.type, wireType = types7.basic[type];
        ref = "m" + util5.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 = tokenize7;
    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");
    tokenize7.unescape = unescape4;
    function tokenize7(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(start2, end, isLeading) {
        var comment = {
          type: source2.charAt(start2++),
          lineEmpty: false,
          leading: isLeading
        };
        var lookback;
        if (alternateCommentMode) {
          lookback = 2;
        } else {
          lookback = 3;
        }
        var commentOffset = start2 - lookback, c4;
        do {
          if (--commentOffset < 0 || (c4 = source2.charAt(commentOffset)) === "\n") {
            comment.lineEmpty = true;
            break;
          }
        } while (c4 === " " || c4 === "	");
        var lines = source2.substring(start2, end).split(setCommentSplitRe);
        for (var i4 = 0; i4 < lines.length; ++i4)
          lines[i4] = lines[i4].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, start2, 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(start2 = offset + 1) === "/";
                while (charAt(++offset) !== "\n") {
                  if (offset === length) {
                    return null;
                  }
                }
                ++offset;
                if (isDoc) {
                  setComment(start2, offset - 1, isLeadingComment);
                  isLeadingComment = true;
                }
                ++line;
                repeat = true;
              } else {
                start2 = 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(start2, offset, isLeadingComment);
                  isLeadingComment = true;
                }
                line++;
                repeat = true;
              }
            } else if ((curr = charAt(offset)) === "*") {
              start2 = offset + 1;
              isDoc = alternateCommentMode || charAt(start2) === "*";
              do {
                if (curr === "\n") {
                  ++line;
                }
                if (++offset === length) {
                  throw illegal("comment");
                }
                prev = curr;
                curr = charAt(offset);
              } while (prev !== "*" || curr !== "/");
              ++offset;
              if (isDoc) {
                setComment(start2, 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(tokenize7, "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 = parse17;
    parse17.filename = null;
    parse17.defaults = { keepCase: false };
    var tokenize7 = 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 util5 = 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 parse17(source2, root, options2) {
      if (!(root instanceof Root2)) {
        options2 = root;
        root = new Root2();
      }
      if (!options2)
        options2 = parse17.defaults;
      var preferTrailingComment = options2.preferTrailingComment || false;
      var tn = tokenize7(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(name4) {
        return name4;
      } : util5.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, name4, insideTryCatch) {
        var filename = parse17.filename;
        if (!insideTryCatch)
          parse17.filename = null;
        return Error("illegal " + (name4 || "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, start2;
        do {
          if (acceptStrings && ((token3 = peek()) === '"' || token3 === "'")) {
            var str2 = readString();
            target.push(str2);
            if (edition >= 2023) {
              throw illegal(str2, "id");
            }
          } else {
            try {
              target.push([start2 = parseId(next()), skip("to", true) ? parseId(next()) : start2]);
            } catch (err2) {
              if (acceptStrings && typeRefRe.test(token3) && edition >= 2023) {
                target.push(token3);
              } else {
                throw err2;
              }
            }
          }
        } while (skip(",", true));
        var dummy = { options: void 0 };
        dummy.setOption = function(name4, value) {
          if (this.options === void 0) this.options = {};
          this.options[name4] = 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 = parse17.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":
              parseField2(type, token4);
              break;
            case "optional":
              if (edition === "proto3") {
                parseField2(type, "proto3_optional");
              } else if (edition !== "proto2") {
                throw illegal(token4);
              } else {
                parseField2(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);
              parseField2(type, "optional");
              break;
          }
        }, "parseType_block"));
        parent.add(type);
        if (parent === ptr) {
          topLevelObjects.push(type);
        }
      }
      __name(parseType, "parseType");
      function parseField2(parent, rule, extend3) {
        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 name4 = next();
        if (!nameRe.test(name4))
          throw illegal(name4, "name");
        name4 = applyCase(name4);
        skip("=");
        var field = new Field(name4, parseId(next()), type, rule, extend3);
        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("_" + name4);
          field.setOption("proto3_optional", true);
          oneof.add(field);
          parent.add(oneof);
        } else {
          parent.add(field);
        }
        if (parent === ptr) {
          topLevelObjects.push(field);
        }
      }
      __name(parseField2, "parseField");
      function parseGroup(parent, rule) {
        if (edition >= 2023) {
          throw illegal("group");
        }
        var name4 = next();
        if (!nameRe.test(name4))
          throw illegal(name4, "name");
        var fieldName = util5.lcFirst(name4);
        if (name4 === fieldName)
          name4 = util5.ucFirst(name4);
        skip("=");
        var id = parseId(next());
        var type = new Type3(name4);
        type.group = true;
        var field = new Field(fieldName, id, name4, rule);
        field.filename = parse17.filename;
        ifBlock(type, /* @__PURE__ */ __name(function parseGroup_block(token3) {
          switch (token3) {
            case "option":
              parseOption(type, token3);
              skip(";");
              break;
            case "required":
            case "repeated":
              parseField2(type, token3);
              break;
            case "optional":
              if (edition === "proto3") {
                parseField2(type, "proto3_optional");
              } else {
                parseField2(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 name4 = next();
        if (!nameRe.test(name4))
          throw illegal(name4, "name");
        skip("=");
        var field = new MapField(applyCase(name4), 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);
            parseField2(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(name4) {
          return this.options[name4];
        };
        dummy.setOption = function(name4, value2) {
          ReflectionObject.prototype.setOption.call(dummy, name4, 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 name4 = propName ? option2.concat(propName) : option2;
        var optionValue = parseOptionValue(parent, name4);
        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, name4) {
        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, name4 + "." + 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, name4 + "." + token2, lastValue);
                }
              }
            } else {
              value = readValue(true);
              setOption(parent, name4 + "." + 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, name4, simpleValue);
        return simpleValue;
      }
      __name(parseOptionValue, "parseOptionValue");
      function setOption(parent, name4, value) {
        if (ptr === parent && /^features\./.test(name4)) {
          topLevelOptions[name4] = value;
          return;
        }
        if (parent.setOption)
          parent.setOption(name4, value);
      }
      __name(setOption, "setOption");
      function setParsedOption(parent, name4, value, propName) {
        if (parent.setParsedOption)
          parent.setParsedOption(name4, 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 name4 = 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(name4, 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":
              parseField2(parent, token4, reference);
              break;
            case "optional":
              if (edition === "proto3") {
                parseField2(parent, "proto3_optional", reference);
              } else {
                parseField2(parent, "optional", reference);
              }
              break;
            default:
              if (edition === "proto2" || !typeRefRe.test(token4))
                throw illegal(token4);
              push2(token4);
              parseField2(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();
      parse17.filename = null;
      return {
        "package": pkg2,
        "imports": imports,
        weakImports,
        root
      };
    }
    __name(parse17, "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(name4, json3) {
      if (!commonRe.test(name4)) {
        name4 = "google/protobuf/" + name4 + ".proto";
        json3 = { nested: { google: { nested: { protobuf: { nested: json3 } } } } };
      }
      common[name4] = json3;
    }
    __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(file2) {
      return common[file2] || 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, i4; 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 (i4 = 0; i4 < fileDescriptor.messageType.length; ++i4)
              filePackage.add(Type3.fromDescriptor(fileDescriptor.messageType[i4], edition));
          if (fileDescriptor.enumType)
            for (i4 = 0; i4 < fileDescriptor.enumType.length; ++i4)
              filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i4], edition));
          if (fileDescriptor.extension)
            for (i4 = 0; i4 < fileDescriptor.extension.length; ++i4)
              filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i4], edition));
          if (fileDescriptor.service)
            for (i4 = 0; i4 < fileDescriptor.service.length; ++i4)
              filePackage.add(Service.fromDescriptor(fileDescriptor.service[i4], edition));
          var opts = fromDescriptorOptions(fileDescriptor.options, exports2.FileOptions);
          if (opts) {
            var ks = Object.keys(opts);
            for (i4 = 0; i4 < ks.length; ++i4)
              filePackage.setOption(ks[i4], opts[ks[i4]]);
          }
        }
      }
      return root.resolveAll();
    }, "fromDescriptor");
    Root2.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor(edition) {
      var set2 = exports2.FileDescriptorSet.create();
      Root_toDescriptorRecursive(this, set2.file, edition);
      return set2;
    }, "toDescriptor");
    function Root_toDescriptorRecursive(ns, files, edition) {
      var file2 = exports2.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" });
      editionToDescriptor(edition, file2);
      if (!(ns instanceof Root2))
        file2["package"] = ns.fullName.substring(1);
      for (var i4 = 0, nested; i4 < ns.nestedArray.length; ++i4)
        if ((nested = ns._nestedArray[i4]) instanceof Type3)
          file2.messageType.push(nested.toDescriptor(edition));
        else if (nested instanceof Enum)
          file2.enumType.push(nested.toDescriptor());
        else if (nested instanceof Field)
          file2.extension.push(nested.toDescriptor(edition));
        else if (nested instanceof Service)
          file2.service.push(nested.toDescriptor());
        else if (nested instanceof /* plain */
        Namespace)
          Root_toDescriptorRecursive(nested, files, edition);
      file2.options = toDescriptorOptions(ns.options, exports2.FileOptions);
      if (file2.messageType.length + file2.enumType.length + file2.extension.length + file2.service.length)
        files.push(file2);
    }
    __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)), i4;
      if (!nested)
        type._edition = edition;
      if (descriptor2.oneofDecl)
        for (i4 = 0; i4 < descriptor2.oneofDecl.length; ++i4)
          type.add(OneOf.fromDescriptor(descriptor2.oneofDecl[i4]));
      if (descriptor2.field)
        for (i4 = 0; i4 < descriptor2.field.length; ++i4) {
          var field = Field.fromDescriptor(descriptor2.field[i4], edition, true);
          type.add(field);
          if (descriptor2.field[i4].hasOwnProperty("oneofIndex"))
            type.oneofsArray[descriptor2.field[i4].oneofIndex].add(field);
        }
      if (descriptor2.extension)
        for (i4 = 0; i4 < descriptor2.extension.length; ++i4)
          type.add(Field.fromDescriptor(descriptor2.extension[i4], edition, true));
      if (descriptor2.nestedType)
        for (i4 = 0; i4 < descriptor2.nestedType.length; ++i4) {
          type.add(Type3.fromDescriptor(descriptor2.nestedType[i4], edition, true));
          if (descriptor2.nestedType[i4].options && descriptor2.nestedType[i4].options.mapEntry)
            type.setOption("map_entry", true);
        }
      if (descriptor2.enumType)
        for (i4 = 0; i4 < descriptor2.enumType.length; ++i4)
          type.add(Enum.fromDescriptor(descriptor2.enumType[i4], edition, true));
      if (descriptor2.extensionRange && descriptor2.extensionRange.length) {
        type.extensions = [];
        for (i4 = 0; i4 < descriptor2.extensionRange.length; ++i4)
          type.extensions.push([descriptor2.extensionRange[i4].start, descriptor2.extensionRange[i4].end]);
      }
      if (descriptor2.reservedRange && descriptor2.reservedRange.length || descriptor2.reservedName && descriptor2.reservedName.length) {
        type.reserved = [];
        if (descriptor2.reservedRange)
          for (i4 = 0; i4 < descriptor2.reservedRange.length; ++i4)
            type.reserved.push([descriptor2.reservedRange[i4].start, descriptor2.reservedRange[i4].end]);
        if (descriptor2.reservedName)
          for (i4 = 0; i4 < descriptor2.reservedName.length; ++i4)
            type.reserved.push(descriptor2.reservedName[i4]);
      }
      return type;
    }, "fromDescriptor");
    Type3.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor(edition) {
      var descriptor2 = exports2.DescriptorProto.create({ name: this.name }), i4;
      for (i4 = 0; i4 < this.fieldsArray.length; ++i4) {
        var fieldDescriptor;
        descriptor2.field.push(fieldDescriptor = this._fieldsArray[i4].toDescriptor(edition));
        if (this._fieldsArray[i4] instanceof MapField) {
          var keyType = toDescriptorType(this._fieldsArray[i4].keyType, this._fieldsArray[i4].resolvedKeyType, false), valueType = toDescriptorType(this._fieldsArray[i4].type, this._fieldsArray[i4].resolvedType, false), valueTypeName = valueType === /* type */
          11 || valueType === /* enum */
          14 ? this._fieldsArray[i4].resolvedType && shortname(this.parent, this._fieldsArray[i4].resolvedType) || this._fieldsArray[i4].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 (i4 = 0; i4 < this.oneofsArray.length; ++i4)
        descriptor2.oneofDecl.push(this._oneofsArray[i4].toDescriptor());
      for (i4 = 0; i4 < this.nestedArray.length; ++i4) {
        if (this._nestedArray[i4] instanceof Field)
          descriptor2.field.push(this._nestedArray[i4].toDescriptor(edition));
        else if (this._nestedArray[i4] instanceof Type3)
          descriptor2.nestedType.push(this._nestedArray[i4].toDescriptor(edition));
        else if (this._nestedArray[i4] instanceof Enum)
          descriptor2.enumType.push(this._nestedArray[i4].toDescriptor());
      }
      if (this.extensions)
        for (i4 = 0; i4 < this.extensions.length; ++i4)
          descriptor2.extensionRange.push(exports2.DescriptorProto.ExtensionRange.create({ start: this.extensions[i4][0], end: this.extensions[i4][1] }));
      if (this.reserved)
        for (i4 = 0; i4 < this.reserved.length; ++i4)
          if (typeof this.reserved[i4] === "string")
            descriptor2.reservedName.push(this.reserved[i4]);
          else
            descriptor2.reservedRange.push(exports2.DescriptorProto.ReservedRange.create({ start: this.reserved[i4][0], end: this.reserved[i4][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 i4 = 0; i4 < descriptor2.value.length; ++i4) {
          var name4 = descriptor2.value[i4].name, value = descriptor2.value[i4].number || 0;
          values[name4 && name4.length ? name4 : "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 i4 = 0, ks = Object.keys(this.values); i4 < ks.length; ++i4)
        values.push(exports2.EnumValueDescriptorProto.create({ name: ks[i4], number: this.values[ks[i4]] }));
      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 i4 = 0; i4 < descriptor2.method.length; ++i4)
          service.add(Method.fromDescriptor(descriptor2.method[i4]));
      return service;
    }, "fromDescriptor");
    Service.prototype.toDescriptor = /* @__PURE__ */ __name(function toDescriptor() {
      var methods = [];
      for (var i4 = 0; i4 < this.methodsArray.length; ++i4)
        methods.push(this._methodsArray[i4].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 i4 = 0, field, key; i4 < type.fieldsArray.length; ++i4) {
        if ((key = (field = type._fieldsArray[i4]).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 i4 = 0; i4 < keys.length; ++i4) {
        var key = keys[i4];
        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("."), i4 = 0, j2 = 0, k2 = toPath3.length - 1;
      if (!(from instanceof Root2) && to instanceof Namespace)
        while (i4 < fromPath.length && j2 < k2 && fromPath[i4] === toPath3[j2]) {
          var other2 = to.lookup(fromPath[i4++], true);
          if (other2 !== null && other2 !== to)
            break;
          ++j2;
        }
      else
        for (; i4 < fromPath.length && j2 < k2 && fromPath[i4] === toPath3[j2]; ++i4, ++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 fs142 = __require("fs");
    var path150 = __require("path");
    var Protobuf = require_protobufjs();
    function addIncludePathResolver(root, includePaths) {
      const originalResolvePath = root.resolvePath;
      root.resolvePath = (origin2, target) => {
        if (path150.isAbsolute(target)) {
          return target;
        }
        for (const directory of includePaths) {
          const fullPath = path150.join(directory, target);
          try {
            fs142.accessSync(fullPath, fs142.constants.R_OK);
            return fullPath;
          } catch (err2) {
            continue;
          }
        }
        process.emitWarning(`${target} not found in any of the include paths ${includePaths}`);
        return originalResolvePath(origin2, 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, factory2) {
      function preferDefault(exports3) {
        return exports3.default || exports3;
      }
      __name(preferDefault, "preferDefault");
      if (typeof define === "function" && define.amd) {
        define([], function() {
          var exports3 = {};
          factory2(exports3);
          return preferDefault(exports3);
        });
      } else if (typeof exports2 === "object") {
        factory2(exports2);
        if (typeof module2 === "object") module2.exports = preferDefault(exports2);
      } else {
        (function() {
          var exports3 = {};
          factory2(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 i4 = 0; i4 < str2.length; i4 += 8) {
            var size = Math.min(8, str2.length - i4), value = parseInt(str2.substring(i4, i4 + 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 toString3(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 _default3 = _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, name4) {
      if (baseName === "") {
        return name4;
      } else {
        return baseName + "." + name4;
      }
    }
    __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((name4) => {
            return getAllHandledReflectionObjects(obj.nested[name4], 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, name4, options2, fileDescriptors) {
      const def2 = {};
      for (const method of service.methodsArray) {
        def2[method.name] = createMethodDefinition(method, name4, 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, name4, options2, fileDescriptors) {
      if (obj instanceof Protobuf.Service) {
        return createServiceDefinition(obj, name4, 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 [name4, obj] of getAllHandledReflectionObjects(root, "")) {
        def2[name4] = createDefinition(obj, name4, 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(json3, options2) {
      options2 = options2 || {};
      const loadedRoot = Protobuf.Root.fromJSON(json3);
      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 (name4, getInfo, channelzEnabled) => {
        const id = getNextId();
        const ref = { id, name: name4, 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(date5) {
      if (!date5) {
        return null;
      }
      const millisSinceEpoch = date5.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 i4;
      for (i4 = channelEntries.lowerBound(startId); !i4.equals(channelEntries.end()) && resultList.length < maxResults; i4 = i4.next()) {
        resultList.push(getChannelMessage(i4.pointer[1]));
      }
      callback(null, {
        channel: resultList,
        end: i4.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 i4;
      for (i4 = serverEntries.lowerBound(startId); !i4.equals(serverEntries.end()) && resultList.length < maxResults; i4 = i4.next()) {
        resultList.push(getServerMessage(i4.pointer[1]));
      }
      callback(null, {
        server: resultList,
        end: i4.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 i4;
      for (i4 = allSockets.lowerBound(startId); !i4.equals(allSockets.end()) && resultList.length < maxResults; i4 = i4.next()) {
        resultList.push(socketRefToMessage(i4.pointer[1].ref));
      }
      callback(null, {
        socket_ref: resultList,
        end: i4.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();
          }
        }, (error40) => {
          this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error40}`);
        });
      }
      /**
       * 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(metadata2, 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(metadata2, 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((addr2) => addr2.host + ":" + addr2.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, {});
          }, (err2) => {
            if (this.pendingLookupPromise === null) {
              return;
            }
            trace2("Resolution error for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + err2.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 (err2) {
                this.latestServiceConfigError = {
                  code: constants_1.Status.UNAVAILABLE,
                  details: `Parsing service config failed with error ${err2.message}`,
                  metadata: new metadata_1.Metadata()
                };
              }
              if (this.latestLookupResult !== null) {
                this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError, null, {});
              }
            }, (err2) => {
            });
          }
        }
      }
      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((addr2) => ({
            host: addr2,
            port: +this.port
          }));
        }
        const addressList = await dns_1.promises.lookup(hostname4, { all: true });
        return addressList.map((addr2) => ({ host: addr2.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 http9 = __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((resolve42, reject) => {
        const request4 = http9.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);
            resolve42(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", (err2) => {
          request4.removeAllListeners();
          (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to proxy " + proxyAddressString + " with error " + err2.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 http23 = __require("http2");
    var os59 = __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 [name4, num] of Object.entries(os59.constants.errno)) {
        if (num === errno) {
          return name4;
        }
      }
      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, flags2) => {
          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 (flags2 & http23.constants.NGHTTP2_FLAG_END_STREAM) {
            this.handleTrailers(headers);
          } else {
            let metadata2;
            try {
              metadata2 = metadata_1.Metadata.fromHttp2Headers(headers);
            } catch (error40) {
              this.endCall({
                code: constants_1.Status.UNKNOWN,
                details: error40.message,
                metadata: new metadata_1.Metadata()
              });
              return;
            }
            this.listener.onReceiveMetadata(metadata2);
          }
        });
        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 http23.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 http23.constants.NGHTTP2_REFUSED_STREAM:
                code2 = constants_1.Status.UNAVAILABLE;
                details = "Stream refused by server";
                break;
              case http23.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 http23.constants.NGHTTP2_ENHANCE_YOUR_CALM:
                code2 = constants_1.Status.RESOURCE_EXHAUSTED;
                details = "Bandwidth exhausted or memory limit exceeded";
                break;
              case http23.constants.NGHTTP2_INADEQUATE_SECURITY:
                code2 = constants_1.Status.PERMISSION_DENIED;
                details = "Protocol not secure enough";
                break;
              case http23.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", (err2) => {
          if (err2.code !== "ERR_HTTP2_STREAM_ERROR") {
            this.trace("Node error event: message=" + err2.message + " code=" + err2.code + " errno=" + getSystemErrorName(err2.errno) + " syscall=" + err2.syscall);
            this.internalError = err2;
          }
          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 metadata2;
        try {
          metadata2 = metadata_1.Metadata.fromHttp2Headers(headers);
        } catch (e4) {
          metadata2 = new metadata_1.Metadata();
        }
        const metadataMap = metadata2.getMap();
        let status;
        if (typeof metadataMap["grpc-status"] === "string") {
          const receivedStatus = Number(metadataMap["grpc-status"]);
          this.trace("received status code " + receivedStatus + " from server");
          metadata2.remove("grpc-status");
          let details = "";
          if (typeof metadataMap["grpc-message"] === "string") {
            try {
              details = decodeURI(metadataMap["grpc-message"]);
            } catch (e4) {
              details = metadataMap["grpc-message"];
            }
            metadata2.remove("grpc-message");
            this.trace('received status details string "' + details + '" from server');
          }
          status = {
            code: receivedStatus,
            details,
            metadata: metadata2
          };
        } else if (this.httpStatusCode) {
          status = mapHttpStatusCode(this.httpStatusCode);
          status.metadata = metadata2;
        } else {
          status = {
            code: constants_1.Status.UNKNOWN,
            details: "No status information received",
            metadata: metadata2
          };
        }
        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 = http23.constants.NGHTTP2_NO_ERROR;
          } else {
            code2 = http23.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((error40) => {
          process.nextTick(() => {
            var _a7;
            let code2 = constants_1.Status.UNAVAILABLE;
            if ((error40 === null || error40 === void 0 ? void 0 : error40.code) === "ERR_STREAM_WRITE_AFTER_END") {
              code2 = constants_1.Status.INTERNAL;
            }
            if (error40) {
              this.cancelWithStatus(code2, `Write error: ${error40.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 (error40) {
          this.endCall({
            code: constants_1.Status.UNAVAILABLE,
            details: `Write failed with error ${error40.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 http23 = __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 } = http23.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 === http23.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", (error40) => {
          this.trace("connection closed with error " + error40.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((err2, duration3, payload) => {
            this.clearKeepaliveTimeout();
            if (err2) {
              this.keepaliveTrace("Ping failed with error " + err2.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(metadata2, host, method, listener, subchannelCallStatsTracker) {
        const headers = metadata2.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((success2) => {
              var _a7;
              if (success2) {
                this.streamTracker.addCallSucceeded();
              } else {
                this.streamTracker.addCallFailed();
              }
              (_a7 = subchannelCallStatsTracker.onStreamEnd) === null || _a7 === void 0 ? void 0 : _a7.call(subchannelCallStatsTracker, success2);
            }, "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((success2) => {
              var _a7;
              (_a7 = subchannelCallStatsTracker.onStreamEnd) === null || _a7 === void 0 ? void 0 : _a7.call(subchannelCallStatsTracker, success2);
            }, "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((resolve42, 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((error40) => {
            var _a7;
            (_a7 = this.session) === null || _a7 === void 0 ? void 0 : _a7.destroy();
            errorMessage = error40.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 = http23.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);
            resolve42(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((resolve42, reject) => {
              const closeCallback = /* @__PURE__ */ __name(() => {
                reject(new Error("Socket closed"));
              }, "closeCallback");
              const errorCallback = /* @__PURE__ */ __name((error40) => {
                reject(error40);
              }, "errorCallback");
              const socket = net2.connect(address, () => {
                socket.removeListener("close", closeCallback);
                socket.removeListener("error", errorCallback);
                resolve42(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(metadata2) {
        let result = metadata2;
        for (let i4 = 0; i4 < this.filters.length; i4++) {
          result = this.filters[i4].sendMetadata(result);
        }
        return result;
      }
      receiveMetadata(metadata2) {
        let result = metadata2;
        for (let i4 = this.filters.length - 1; i4 >= 0; i4--) {
          result = this.filters[i4].receiveMetadata(result);
        }
        return result;
      }
      sendMessage(message) {
        let result = message;
        for (let i4 = 0; i4 < this.filters.length; i4++) {
          result = this.filters[i4].sendMessage(result);
        }
        return result;
      }
      receiveMessage(message) {
        let result = message;
        for (let i4 = this.filters.length - 1; i4 >= 0; i4--) {
          result = this.filters[i4].receiveMessage(result);
        }
        return result;
      }
      receiveTrailers(status) {
        let result = status;
        for (let i4 = this.filters.length - 1; i4 >= 0; i4--) {
          result = this.filters[i4].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((factory2) => factory2.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(metadata2) {
        return metadata2;
      }
      receiveMetadata(metadata2) {
        return metadata2;
      }
      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 zlib5 = __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((resolve42, reject) => {
          zlib5.deflate(message, (err2, output) => {
            if (err2) {
              reject(err2);
            } else {
              resolve42(output);
            }
          });
        });
      }
      decompressMessage(message) {
        return new Promise((resolve42, reject) => {
          let totalLength = 0;
          const messageParts = [];
          const decompresser = zlib5.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", () => {
            resolve42(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((resolve42, reject) => {
          zlib5.gzip(message, (err2, output) => {
            if (err2) {
              reject(err2);
            } else {
              resolve42(output);
            }
          });
        });
      }
      decompressMessage(message) {
        return new Promise((resolve42, reject) => {
          let totalLength = 0;
          const messageParts = [];
          const decompresser = zlib5.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", () => {
            resolve42(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(metadata2) {
        const headers = await metadata2;
        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(metadata2) {
        const receiveEncoding = metadata2.get("grpc-encoding");
        if (receiveEncoding.length > 0) {
          const encoding = receiveEncoding[0];
          if (typeof encoding === "string") {
            this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength);
          }
        }
        metadata2.remove("grpc-encoding");
        const serverSupportedEncodingsHeader = metadata2.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";
          }
        }
        metadata2.remove("grpc-accept-encoding");
        return metadata2;
      }
      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 http23 = __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((metadata2) => {
                    this.trace("Received metadata");
                    this.listener.onReceiveMetadata(metadata2);
                  }, "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 === http23.constants.NGHTTP2_REFUSED_STREAM) {
                      this.outputStatus(status, "REFUSED");
                    } else {
                      this.outputStatus(status, "PROCESSED");
                    }
                  }, "onReceiveStatus")
                });
                this.childStartTime = /* @__PURE__ */ new Date();
              } catch (error40) {
                this.trace("Failed to start call on picked subchannel " + subchannelString + " with error " + error40.message);
                this.outputStatus({
                  code: constants_1.Status.INTERNAL,
                  details: "Failed to start HTTP/2 stream with error " + error40.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();
              }
            }, (error40) => {
              const { code: code3, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error40.code === "number" ? error40.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error40.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(metadata2, listener) {
        this.trace("start called");
        this.listener = listener;
        this.metadata = metadata2;
        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((metadata2) => {
              this.trace("Received metadata");
              this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata2));
            }, "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(metadata2, listener) {
        this.trace("start called");
        this.metadata = metadata2.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 i4 = 0; i4 < this.underlyingCalls.length; i4++) {
          if (i4 === index) {
            continue;
          }
          if (this.underlyingCalls[i4].state === "COMPLETED") {
            continue;
          }
          this.underlyingCalls[i4].state = "COMPLETED";
          this.underlyingCalls[i4].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(metadata2) {
        const mdValue = metadata2.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((metadata2) => {
            this.trace("Received metadata from child [" + child.getCallNumber() + "]");
            this.commitCall(index);
            receivedMetadata = true;
            if (previousAttempts > 0) {
              metadata2.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`);
            }
            if (this.underlyingCalls[index].state === "ACTIVE") {
              this.listener.onReceiveMetadata(metadata2);
            }
          }, "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(metadata2, listener) {
        this.trace("start called");
        this.listener = listener;
        this.initialMetadata = metadata2;
        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((error40) => {
                  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((error40) => {
                  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((error40) => {
                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 error40 = 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 = error40.stack) === null || _f === void 0 ? void 0 : _f.substring(error40.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(metadata2, extraPickInfo) {
        return this.currentPicker.pick({
          metadata: metadata2,
          extraPickInfo
        });
      }
      queueCallForPick(call) {
        this.pickQueue.push(call);
        this.callRefTimerRef();
      }
      getConfig(method, metadata2) {
        if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) {
          this.resolvingLoadBalancer.exitIdle();
        }
        if (this.configSelector) {
          return {
            type: "SUCCESS",
            config: this.configSelector.invoke(method, metadata2, 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(error40, overrideTrailers) {
      var _a7;
      const status = {
        code: constants_1.Status.UNKNOWN,
        details: "message" in error40 ? error40.message : "Unknown Error",
        metadata: (_a7 = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error40.metadata) !== null && _a7 !== void 0 ? _a7 : null
      };
      if ("code" in error40 && typeof error40.code === "number" && Number.isInteger(error40.code)) {
        status.code = error40.code;
        if ("details" in error40 && typeof error40.details === "string") {
          status.details = error40.details;
        }
      }
      return status;
    }
    __name(serverErrorToStatus, "serverErrorToStatus");
    var ServerUnaryCallImpl = class extends events_1.EventEmitter {
      static {
        __name(this, "ServerUnaryCallImpl");
      }
      constructor(path150, call, metadata2, request4) {
        super();
        this.path = path150;
        this.call = call;
        this.metadata = metadata2;
        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(path150, call, metadata2) {
        super({ objectMode: true });
        this.path = path150;
        this.call = call;
        this.metadata = metadata2;
        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(path150, call, metadata2, request4) {
        super({ objectMode: true });
        this.path = path150;
        this.call = call;
        this.metadata = metadata2;
        this.request = request4;
        this.pendingStatus = {
          code: constants_1.Status.OK,
          details: "OK"
        };
        this.cancelled = false;
        this.trailingMetadata = new metadata_1.Metadata();
        this.on("error", (err2) => {
          this.pendingStatus = serverErrorToStatus(err2);
          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(metadata2) {
        if (metadata2) {
          this.trailingMetadata = metadata2;
        }
        return super.end();
      }
    };
    exports2.ServerWritableStreamImpl = ServerWritableStreamImpl;
    var ServerDuplexStreamImpl = class extends stream_1.Duplex {
      static {
        __name(this, "ServerDuplexStreamImpl");
      }
      constructor(path150, call, metadata2) {
        super({ objectMode: true });
        this.path = path150;
        this.call = call;
        this.metadata = metadata2;
        this.pendingStatus = {
          code: constants_1.Status.OK,
          details: "OK"
        };
        this.cancelled = false;
        this.trailingMetadata = new metadata_1.Metadata();
        this.on("error", (err2) => {
          this.pendingStatus = serverErrorToStatus(err2);
          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(metadata2) {
        if (metadata2) {
          this.trailingMetadata = metadata2;
        }
        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 i4 = 0; i4 < keyCertPairs.length; i4++) {
          const pair = keyCertPairs[i4];
          if (pair === null || typeof pair !== "object") {
            throw new TypeError(`keyCertPair[${i4}] must be an object`);
          }
          if (!Buffer.isBuffer(pair.private_key)) {
            throw new TypeError(`keyCertPair[${i4}].private_key must be a Buffer`);
          }
          if (!Buffer.isBuffer(pair.cert_chain)) {
            throw new TypeError(`keyCertPair[${i4}].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 i4 = 0; i4 < this.options.cert.length; i4++) {
            const thisCert = this.options.cert[i4];
            const otherCert = other2.options.cert[i4];
            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 i4 = 0; i4 < this.options.key.length; i4++) {
            const thisKey = this.options.key[i4];
            const otherKey = other2.options.key[i4];
            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 i4 = 0; i4 < this.interceptors.length; i4++) {
          if (this.interceptors[i4] !== other2.interceptors[i4]) {
            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 http23 = __require("http2");
    var error_1 = require_error();
    var zlib5 = __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(metadata2) {
        if (this.cancelled) {
          return;
        }
        this.processingMetadata = true;
        this.listener.onReceiveMetadata(metadata2, (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(start2) {
        this.start = start2;
        return this;
      }
      withSendMetadata(sendMetadata) {
        this.metadata = sendMetadata;
        return this;
      }
      withSendMessage(sendMessage2) {
        this.message = sendMessage2;
        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((metadata2, next) => {
        next(metadata2);
      }, "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((metadata2, next) => {
        next(metadata2);
      }, "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(metadata2) {
        this.processingMetadata = true;
        this.sentMetadata = true;
        this.responder.sendMetadata(metadata2, (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 = {
      [http23.constants.HTTP2_HEADER_STATUS]: http23.constants.HTTP_STATUS_OK,
      [http23.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto"
    };
    var defaultResponseOptions = {
      waitForTrailers: true
    };
    var BaseServerInterceptingCall = class {
      static {
        __name(this, "BaseServerInterceptingCall");
      }
      constructor(stream5, headers, callEventTracker, handler, options2) {
        var _a7;
        this.stream = stream5;
        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", (err2) => {
        });
        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 metadata2 = metadata_1.Metadata.fromHttp2Headers(headers);
        if (logging.isTracerEnabled(TRACER_NAME)) {
          trace2("Request to " + this.handler.path + " received headers " + JSON.stringify(metadata2.toJSON()));
        }
        const timeoutHeader = metadata2.get(GRPC_TIMEOUT_HEADER);
        if (timeoutHeader.length > 0) {
          this.handleTimeoutHeader(timeoutHeader[0]);
        }
        const encodingHeader = metadata2.get(GRPC_ENCODING_HEADER);
        if (encodingHeader.length > 0) {
          this.incomingEncoding = encodingHeader[0];
        }
        metadata2.remove(GRPC_TIMEOUT_HEADER);
        metadata2.remove(GRPC_ENCODING_HEADER);
        metadata2.remove(GRPC_ACCEPT_ENCODING_HEADER);
        metadata2.remove(http23.constants.HTTP2_HEADER_ACCEPT_ENCODING);
        metadata2.remove(http23.constants.HTTP2_HEADER_TE);
        metadata2.remove(http23.constants.HTTP2_HEADER_CONTENT_TYPE);
        this.metadata = metadata2;
      }
      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 = zlib5.createInflate();
          } else {
            decompresser = zlib5.createGunzip();
          }
          return new Promise((resolve42, 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", () => {
              resolve42(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 (err2) {
          this.sendStatus(err2);
          return;
        }
        try {
          queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage);
        } catch (err2) {
          this.sendStatus({
            code: constants_1.Status.INTERNAL,
            details: `Error deserializing request: ${err2.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(metadata2) {
        if (this.checkCancelled()) {
          return;
        }
        if (this.metadataSent) {
          return;
        }
        this.metadataSent = true;
        const custom3 = metadata2 ? metadata2.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, (error40) => {
          var _a7;
          if (error40) {
            this.sendStatus({
              code: constants_1.Status.INTERNAL,
              details: `Error writing message: ${(0, error_1.getErrorMessage)(error40)}`,
              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, stream5, 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(stream5, 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 i4 = 0; i4 < initializers.length; i4++) {
        value = useValue ? initializers[i4].call(thisArg, value) : initializers[i4].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 i4 = decorators.length - 1; i4 >= 0; i4--) {
        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[i4])(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 http23 = __require("http2");
    var util5 = __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 } = http23.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 noop11() {
    }
    __name(noop11, "noop");
    function deprecate6(message) {
      return function(target, context2) {
        return util5.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((name4) => {
            const attrs = service[name4];
            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[name4];
            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, name4);
            }
            const success2 = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType);
            if (success2 === 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((name4) => {
            const attrs = service[name4];
            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 = http23.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 = http23.createServer(this.commonServerOptions);
          }
          http2Server.setTimeout(0, noop11);
          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((resolve42, reject) => {
            const onError2 = /* @__PURE__ */ __name((err2) => {
              this.trace("Failed to bind " + (0, subchannel_address_1.subchannelAddressToString)(address) + " with error " + err2.message);
              resolve42({
                port: "port" in address ? address.port : 1,
                error: err2.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));
              resolve42({
                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((resolve42, 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;
                }
                resolve42(addressList);
              }, "onSuccessfulResolution"),
              onError: /* @__PURE__ */ __name((error40) => {
                reject(new Error(error40.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((error40, port2) => {
            process.nextTick(() => callback(error40, 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), (error40) => callback(error40, 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);
            }, (error40) => {
              callback(error40, 0);
            });
          } else {
            this.boundPorts.set(boundPortObject.mapKey, boundPortObject);
            completionPromise.then((portNum) => {
              boundPortObject.completionPromise = null;
              boundPortObject.portNumber = portNum;
              callback(null, portNum);
            }, (error40) => {
              callback(error40, 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(http23.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(http23.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(http23.constants.NGHTTP2_CANCEL);
          });
          this.sessions.clear();
          (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
          this.shutdown = true;
        }
        register(name4, handler, serialize2, deserialize, type) {
          if (this.handlers.has(name4)) {
            return false;
          }
          this.handlers.set(name4, {
            func: handler,
            serialize: serialize2,
            deserialize,
            type,
            path: name4
          });
          return true;
        }
        unregister(name4) {
          return this.handlers.delete(name4);
        }
        /**
         * @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((error40) => {
            (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
            callback(error40);
          }, "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(stream5, headers) {
          const contentType = headers[http23.constants.HTTP2_HEADER_CONTENT_TYPE];
          if (typeof contentType !== "string" || !contentType.startsWith("application/grpc")) {
            stream5.respond({
              [http23.constants.HTTP2_HEADER_STATUS]: http23.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE
            }, { endStream: true });
            return false;
          }
          return true;
        }
        _retrieveHandler(path150) {
          serverCallTrace("Received call to method " + path150 + " at address " + this.serverAddressString);
          const handler = this.handlers.get(path150);
          if (handler === void 0) {
            serverCallTrace("No handler registered for method " + path150 + ". Sending UNIMPLEMENTED status.");
            return null;
          }
          return handler;
        }
        _respondWithError(err2, stream5, channelzSessionInfo = null) {
          var _b2, _c2;
          const trailersToSend = Object.assign({ "grpc-status": (_b2 = err2.code) !== null && _b2 !== void 0 ? _b2 : constants_1.Status.INTERNAL, "grpc-message": err2.details, [http23.constants.HTTP2_HEADER_STATUS]: http23.constants.HTTP_STATUS_OK, [http23.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto" }, (_c2 = err2.metadata) === null || _c2 === void 0 ? void 0 : _c2.toHttp2Headers());
          stream5.respond(trailersToSend, { endStream: true });
          this.callTracker.addCallFailed();
          channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
        }
        _channelzHandler(extraInterceptors, stream5, headers) {
          this.onStreamOpened(stream5);
          const channelzSessionInfo = this.sessions.get(stream5.session);
          this.callTracker.addCallStarted();
          channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted();
          if (!this._verifyContentType(stream5, headers)) {
            this.callTracker.addCallFailed();
            channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed();
            return;
          }
          const path150 = headers[HTTP2_HEADER_PATH];
          const handler = this._retrieveHandler(path150);
          if (!handler) {
            this._respondWithError(getUnimplementedStatusResponse(path150), stream5, 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((success2) => {
              if (channelzSessionInfo) {
                if (success2) {
                  channelzSessionInfo.streamTracker.addCallSucceeded();
                } else {
                  channelzSessionInfo.streamTracker.addCallFailed();
                }
              }
            }, "onStreamEnd")
          };
          const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream5, 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, stream5, headers) {
          this.onStreamOpened(stream5);
          if (this._verifyContentType(stream5, headers) !== true) {
            return;
          }
          const path150 = headers[HTTP2_HEADER_PATH];
          const handler = this._retrieveHandler(path150);
          if (!handler) {
            this._respondWithError(getUnimplementedStatusResponse(path150), stream5, null);
            return;
          }
          const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream5, 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(http23.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((err2, duration3, payload) => {
                  clearKeepaliveTimeout();
                  if (err2) {
                    this.keepaliveTrace("Ping failed with error: " + err2.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(http23.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((err2, duration3, payload) => {
                  clearKeepaliveTimeout();
                  if (err2) {
                    this.keepaliveTrace("Ping failed with error: " + err2.message);
                    this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to error of a ping frame " + err2.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(stream5) {
          const session = stream5.session;
          const idleTimeoutObj = this.sessionIdleTimeouts.get(session);
          if (idleTimeoutObj) {
            idleTimeoutObj.activeStreams += 1;
            stream5.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 stream5;
      function respond(err2, value, trailer, flags2) {
        if (err2) {
          call.sendStatus((0, server_call_1.serverErrorToStatus)(err2, 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(metadata2) {
          requestMetadata = metadata2;
          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;
          }
          stream5 = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage);
          try {
            handler.func(stream5, respond);
          } catch (err2) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err2.message}`,
              metadata: null
            });
          }
        },
        onCancel() {
          if (stream5) {
            stream5.cancelled = true;
            stream5.emit("cancelled", "cancelled");
          }
        }
      });
    }
    __name(handleUnary, "handleUnary");
    function handleClientStreaming(call, handler) {
      let stream5;
      function respond(err2, value, trailer, flags2) {
        if (err2) {
          call.sendStatus((0, server_call_1.serverErrorToStatus)(err2, 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(metadata2) {
          stream5 = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata2);
          try {
            handler.func(stream5, respond);
          } catch (err2) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err2.message}`,
              metadata: null
            });
          }
        },
        onReceiveMessage(message) {
          stream5.push(message);
        },
        onReceiveHalfClose() {
          stream5.push(null);
        },
        onCancel() {
          if (stream5) {
            stream5.cancelled = true;
            stream5.emit("cancelled", "cancelled");
            stream5.destroy();
          }
        }
      });
    }
    __name(handleClientStreaming, "handleClientStreaming");
    function handleServerStreaming(call, handler) {
      let stream5;
      let requestMetadata;
      let requestMessage = null;
      call.start({
        onReceiveMetadata(metadata2) {
          requestMetadata = metadata2;
          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;
          }
          stream5 = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage);
          try {
            handler.func(stream5);
          } catch (err2) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err2.message}`,
              metadata: null
            });
          }
        },
        onCancel() {
          if (stream5) {
            stream5.cancelled = true;
            stream5.emit("cancelled", "cancelled");
            stream5.destroy();
          }
        }
      });
    }
    __name(handleServerStreaming, "handleServerStreaming");
    function handleBidiStreaming(call, handler) {
      let stream5;
      call.start({
        onReceiveMetadata(metadata2) {
          stream5 = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata2);
          try {
            handler.func(stream5);
          } catch (err2) {
            call.sendStatus({
              code: constants_1.Status.UNKNOWN,
              details: `Server method handler threw error ${err2.message}`,
              metadata: null
            });
          }
        },
        onReceiveMessage(message) {
          stream5.push(message);
        },
        onReceiveHalfClose() {
          stream5.push(null);
        },
        onCancel() {
          if (stream5) {
            stream5.cancelled = true;
            stream5.emit("cancelled", "cancelled");
            stream5.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(metadata2) {
        this.metadata = metadata2;
        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 i4 = result.length - 1; i4 > 1; i4--) {
        const j2 = Math.floor(Math.random() * (i4 + 1));
        const temp = result[i4];
        result[i4] = 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 i4 = 0; i4 < Math.max(firstList.length, secondList.length); i4++) {
        if (i4 < firstList.length) {
          result.push(firstList[i4]);
        }
        if (i4 < secondList.length) {
          result.push(secondList[i4]);
        }
      }
      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 fs142 = __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)(fs142.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 path150;
        if (target.authority === "") {
          path150 = "/" + target.path;
        } else {
          path150 = target.path;
        }
        this.endpoints = [{ addresses: [{ path: path150 }] }];
      }
      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 path150 of pathList) {
          const hostPort = (0, uri_parser_1.splitHostPort)(path150);
          if (hostPort === null) {
            this.error = {
              code: constants_1.Status.UNAVAILABLE,
              details: `Failed to parse ${target.scheme} address ${path150}`,
              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 ${path150}`,
              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(path150, name4) {
      const serviceDefinition = {
        export: {
          path: path150,
          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, name4);
    }
    __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 (error40) {
            return Promise.resolve({
              status: "failure",
              error: error40
            });
          }
          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 (error40) {
            return Promise.resolve({
              status: "failure",
              error: error40
            });
          }
        }
        return new Promise((resolve42) => {
          const deadline = Date.now() + timeoutMillis;
          if (this._metadata == null) {
            return resolve42({
              error: new Error("metadata was null"),
              status: "failure"
            });
          }
          this._client.export(buffer, this._metadata, { deadline }, (err2, response) => {
            if (err2) {
              resolve42({
                status: "failure",
                error: err2
              });
            } else {
              resolve42({
                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_esm(), __toCommonJS(esm_exports));
    function validateAndNormalizeUrl(url3) {
      url3 = url3.trim();
      const hasProtocol = url3.match(/^([\w]{1,8}):\/\//);
      if (!hasProtocol) {
        url3 = `https://${url3}`;
      }
      const target = new url_1.URL(url3);
      if (target.protocol === "unix:") {
        return url3;
      }
      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(metadata2, additionalMetadata) {
      for (const [key, value] of Object.entries(additionalMetadata.getMap())) {
        if (metadata2.get(key).length < 1) {
          metadata2.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 metadata2 = defaultConfiguration.metadata();
          overrideMetadataEntriesIfNotPresent(
            metadata2,
            // 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(metadata2, fallbackConfiguration.metadata?.() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)());
          return metadata2;
        }, "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 metadata2 = (0, grpc_exporter_transport_1.createEmptyMetadata)();
          metadata2.set("User-Agent", `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`);
          return metadata2;
        }, "metadata"),
        url: "http://localhost:4317",
        credentials: /* @__PURE__ */ __name((url3) => {
          if (url3.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 delay5 = new Date(retryAfter).getTime() - Date.now();
  if (delay5 >= 0) {
    return delay5;
  }
  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 error40 = new OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString());
        onDone({
          status: "failure",
          error: error40
        });
      }
    });
  });
  req.setTimeout(timeoutMillis, () => {
    req.destroy();
    onDone({
      status: "failure",
      error: new Error("Request Timeout")
    });
  });
  req.on("error", (error40) => {
    onDone({
      status: "failure",
      error: error40
    });
  });
  compressAndSend(req, params.compression, data, (error40) => {
    onDone({
      status: "failure",
      error: error40
    });
  });
}
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((resolve42) => {
          send(this._parameters, agent, data, (result) => {
            resolve42(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((resolve42, reject) => {
          setTimeout(() => {
            this._transport.send(data, timeoutMillis).then(resolve42, 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_esm();
    __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_esm();
    __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(url3) {
  if (url3 == null) {
    return void 0;
  }
  try {
    new URL(url3);
    return url3;
  } catch {
    throw new Error(`Configuration: Could not parse user-provided export URL: '${url3}'`);
  }
}
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(url3) {
  try {
    const parsedUrl = new URL(url3);
    return parsedUrl.toString();
  } catch {
    diag2.warn(`Configuration: Could not parse environment-provided export URL: '${url3}', falling back to undefined`);
    return void 0;
  }
}
function appendResourcePathToUrl(url3, path150) {
  try {
    new URL(url3);
  } catch {
    diag2.warn(`Configuration: Could not parse environment-provided export URL: '${url3}', falling back to undefined`);
    return void 0;
  }
  if (!url3.endsWith("/")) {
    url3 = url3 + "/";
  }
  url3 += path150;
  try {
    new URL(url3);
  } catch {
    diag2.warn(`Configuration: Provided URL appended with '${path150}' is not a valid URL, using 'undefined' instead of '${url3}'`);
    return void 0;
  }
  return url3;
}
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_esm();
    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_esm();
    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 fs142 = __require("fs");
    var path150 = __require("path");
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    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 metadata2 = (0, grpc_exporter_transport_1.createEmptyMetadata)();
      for (const [key, value] of Object.entries(mergeHeaders3)) {
        metadata2.set(key, value);
      }
      return metadata2;
    }
    __name(getMetadataFromEnv, "getMetadataFromEnv");
    function getMetadataProviderFromEnv(signalIdentifier) {
      const metadata2 = getMetadataFromEnv(signalIdentifier);
      if (metadata2 == null) {
        return void 0;
      }
      return () => metadata2;
    }
    __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 fs142.readFileSync(path150.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_esm(), __toCommonJS(esm_exports));
    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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new AnyValue(properties);
              }, "create");
              AnyValue.encode = /* @__PURE__ */ __name(function encode6(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, error40) {
                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 === error40)
                    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 error40 = $root.opentelemetry.proto.common.v1.ArrayValue.verify(message.arrayValue);
                    if (error40)
                      return "arrayValue." + error40;
                  }
                }
                if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) {
                  if (properties.value === 1)
                    return "value: multiple values";
                  properties.value = 1;
                  {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValueList.verify(message.kvlistValue);
                    if (error40)
                      return "kvlistValue." + error40;
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(ArrayValue, "ArrayValue");
              ArrayValue.prototype.values = $util.emptyArray;
              ArrayValue.create = /* @__PURE__ */ __name(function create4(properties) {
                return new ArrayValue(properties);
              }, "create");
              ArrayValue.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.values != null && message.values.length)
                  for (var i4 = 0; i4 < message.values.length; ++i4)
                    $root.opentelemetry.proto.common.v1.AnyValue.encode(message.values[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.values.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.values[i4]);
                    if (error40)
                      return "values." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.values.length; ++i4) {
                    if (typeof object3.values[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: object expected");
                    message.values[i4] = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object3.values[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(KeyValueList, "KeyValueList");
              KeyValueList.prototype.values = $util.emptyArray;
              KeyValueList.create = /* @__PURE__ */ __name(function create4(properties) {
                return new KeyValueList(properties);
              }, "create");
              KeyValueList.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.values != null && message.values.length)
                  for (var i4 = 0; i4 < message.values.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.values[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.values.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.values[i4]);
                    if (error40)
                      return "values." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.values.length; ++i4) {
                    if (typeof object3.values[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: object expected");
                    message.values[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.values[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(KeyValue, "KeyValue");
              KeyValue.prototype.key = null;
              KeyValue.prototype.value = null;
              KeyValue.create = /* @__PURE__ */ __name(function create4(properties) {
                return new KeyValue(properties);
              }, "create");
              KeyValue.encode = /* @__PURE__ */ __name(function encode6(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, error40) {
                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 === error40)
                    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 error40 = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.value);
                  if (error40)
                    return "value." + error40;
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new InstrumentationScope(properties);
              }, "create");
              InstrumentationScope.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.attributes.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.attributes.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i4]);
                    if (error40)
                      return "attributes." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.attributes.length; ++i4) {
                    if (typeof object3.attributes[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: object expected");
                    message.attributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new EntityRef(properties);
              }, "create");
              EntityRef.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.idKeys.length; ++i4)
                    writer.uint32(
                      /* id 3, wireType 2 =*/
                      26
                    ).string(message.idKeys[i4]);
                if (message.descriptionKeys != null && message.descriptionKeys.length)
                  for (var i4 = 0; i4 < message.descriptionKeys.length; ++i4)
                    writer.uint32(
                      /* id 4, wireType 2 =*/
                      34
                    ).string(message.descriptionKeys[i4]);
                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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.idKeys.length; ++i4)
                    if (!$util.isString(message.idKeys[i4]))
                      return "idKeys: string[] expected";
                }
                if (message.descriptionKeys != null && message.hasOwnProperty("descriptionKeys")) {
                  if (!Array.isArray(message.descriptionKeys))
                    return "descriptionKeys: array expected";
                  for (var i4 = 0; i4 < message.descriptionKeys.length; ++i4)
                    if (!$util.isString(message.descriptionKeys[i4]))
                      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 i4 = 0; i4 < object3.idKeys.length; ++i4)
                    message.idKeys[i4] = String(object3.idKeys[i4]);
                }
                if (object3.descriptionKeys) {
                  if (!Array.isArray(object3.descriptionKeys))
                    throw TypeError(".opentelemetry.proto.common.v1.EntityRef.descriptionKeys: array expected");
                  message.descriptionKeys = [];
                  for (var i4 = 0; i4 < object3.descriptionKeys.length; ++i4)
                    message.descriptionKeys[i4] = String(object3.descriptionKeys[i4]);
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(Resource, "Resource");
              Resource.prototype.attributes = $util.emptyArray;
              Resource.prototype.droppedAttributesCount = null;
              Resource.prototype.entityRefs = $util.emptyArray;
              Resource.create = /* @__PURE__ */ __name(function create4(properties) {
                return new Resource(properties);
              }, "create");
              Resource.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.attributes != null && message.attributes.length)
                  for (var i4 = 0; i4 < message.attributes.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i4], 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 i4 = 0; i4 < message.entityRefs.length; ++i4)
                    $root.opentelemetry.proto.common.v1.EntityRef.encode(message.entityRefs[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.attributes.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i4]);
                    if (error40)
                      return "attributes." + error40;
                  }
                }
                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 i4 = 0; i4 < message.entityRefs.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.EntityRef.verify(message.entityRefs[i4]);
                    if (error40)
                      return "entityRefs." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.attributes.length; ++i4) {
                    if (typeof object3.attributes[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: object expected");
                    message.attributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i4]);
                  }
                }
                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 i4 = 0; i4 < object3.entityRefs.length; ++i4) {
                    if (typeof object3.entityRefs[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: object expected");
                    message.entityRefs[i4] = $root.opentelemetry.proto.common.v1.EntityRef.fromObject(object3.entityRefs[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(TracesData, "TracesData");
              TracesData.prototype.resourceSpans = $util.emptyArray;
              TracesData.create = /* @__PURE__ */ __name(function create4(properties) {
                return new TracesData(properties);
              }, "create");
              TracesData.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resourceSpans != null && message.resourceSpans.length)
                  for (var i4 = 0; i4 < message.resourceSpans.length; ++i4)
                    $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.resourceSpans.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i4]);
                    if (error40)
                      return "resourceSpans." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.resourceSpans.length; ++i4) {
                    if (typeof object3.resourceSpans[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: object expected");
                    message.resourceSpans[i4] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object3.resourceSpans[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(ResourceSpans, "ResourceSpans");
              ResourceSpans.prototype.resource = null;
              ResourceSpans.prototype.scopeSpans = $util.emptyArray;
              ResourceSpans.prototype.schemaUrl = null;
              ResourceSpans.create = /* @__PURE__ */ __name(function create4(properties) {
                return new ResourceSpans(properties);
              }, "create");
              ResourceSpans.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.scopeSpans.length; ++i4)
                    $root.opentelemetry.proto.trace.v1.ScopeSpans.encode(message.scopeSpans[i4], 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, error40) {
                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 === error40)
                    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 error40 = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error40)
                    return "resource." + error40;
                }
                if (message.scopeSpans != null && message.hasOwnProperty("scopeSpans")) {
                  if (!Array.isArray(message.scopeSpans))
                    return "scopeSpans: array expected";
                  for (var i4 = 0; i4 < message.scopeSpans.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.trace.v1.ScopeSpans.verify(message.scopeSpans[i4]);
                    if (error40)
                      return "scopeSpans." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.scopeSpans.length; ++i4) {
                    if (typeof object3.scopeSpans[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: object expected");
                    message.scopeSpans[i4] = $root.opentelemetry.proto.trace.v1.ScopeSpans.fromObject(object3.scopeSpans[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(ScopeSpans, "ScopeSpans");
              ScopeSpans.prototype.scope = null;
              ScopeSpans.prototype.spans = $util.emptyArray;
              ScopeSpans.prototype.schemaUrl = null;
              ScopeSpans.create = /* @__PURE__ */ __name(function create4(properties) {
                return new ScopeSpans(properties);
              }, "create");
              ScopeSpans.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.spans.length; ++i4)
                    $root.opentelemetry.proto.trace.v1.Span.encode(message.spans[i4], 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, error40) {
                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 === error40)
                    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 error40 = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error40)
                    return "scope." + error40;
                }
                if (message.spans != null && message.hasOwnProperty("spans")) {
                  if (!Array.isArray(message.spans))
                    return "spans: array expected";
                  for (var i4 = 0; i4 < message.spans.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.trace.v1.Span.verify(message.spans[i4]);
                    if (error40)
                      return "spans." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.spans.length; ++i4) {
                    if (typeof object3.spans[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: object expected");
                    message.spans[i4] = $root.opentelemetry.proto.trace.v1.Span.fromObject(object3.spans[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new Span(properties);
              }, "create");
              Span.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.attributes.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i4], 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 i4 = 0; i4 < message.events.length; ++i4)
                    $root.opentelemetry.proto.trace.v1.Span.Event.encode(message.events[i4], 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 i4 = 0; i4 < message.links.length; ++i4)
                    $root.opentelemetry.proto.trace.v1.Span.Link.encode(message.links[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.attributes.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i4]);
                    if (error40)
                      return "attributes." + error40;
                  }
                }
                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 i4 = 0; i4 < message.events.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.trace.v1.Span.Event.verify(message.events[i4]);
                    if (error40)
                      return "events." + error40;
                  }
                }
                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 i4 = 0; i4 < message.links.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.trace.v1.Span.Link.verify(message.links[i4]);
                    if (error40)
                      return "links." + error40;
                  }
                }
                if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount")) {
                  if (!$util.isInteger(message.droppedLinksCount))
                    return "droppedLinksCount: integer expected";
                }
                if (message.status != null && message.hasOwnProperty("status")) {
                  var error40 = $root.opentelemetry.proto.trace.v1.Status.verify(message.status);
                  if (error40)
                    return "status." + error40;
                }
                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 i4 = 0; i4 < object3.attributes.length; ++i4) {
                    if (typeof object3.attributes[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: object expected");
                    message.attributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i4]);
                  }
                }
                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 i4 = 0; i4 < object3.events.length; ++i4) {
                    if (typeof object3.events[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.events: object expected");
                    message.events[i4] = $root.opentelemetry.proto.trace.v1.Span.Event.fromObject(object3.events[i4]);
                  }
                }
                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 i4 = 0; i4 < object3.links.length; ++i4) {
                    if (typeof object3.links[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.trace.v1.Span.links: object expected");
                    message.links[i4] = $root.opentelemetry.proto.trace.v1.Span.Link.fromObject(object3.links[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __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 create4(properties) {
                  return new Event2(properties);
                }, "create");
                Event2.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.attributes.length; ++i4)
                      $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i4], 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, error40) {
                  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 === error40)
                      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 i4 = 0; i4 < message.attributes.length; ++i4) {
                      var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i4]);
                      if (error40)
                        return "attributes." + error40;
                    }
                  }
                  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 i4 = 0; i4 < object3.attributes.length; ++i4) {
                      if (typeof object3.attributes[i4] !== "object")
                        throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: object expected");
                      message.attributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i4]);
                    }
                  }
                  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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __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 create4(properties) {
                  return new Link2(properties);
                }, "create");
                Link2.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.attributes.length; ++i4)
                      $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i4], 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, error40) {
                  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 === error40)
                      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 i4 = 0; i4 < message.attributes.length; ++i4) {
                      var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i4]);
                      if (error40)
                        return "attributes." + error40;
                    }
                  }
                  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 i4 = 0; i4 < object3.attributes.length; ++i4) {
                      if (typeof object3.attributes[i4] !== "object")
                        throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: object expected");
                      message.attributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i4]);
                    }
                  }
                  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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(Status, "Status");
              Status.prototype.message = null;
              Status.prototype.code = null;
              Status.create = /* @__PURE__ */ __name(function create4(properties) {
                return new Status(properties);
              }, "create");
              Status.encode = /* @__PURE__ */ __name(function encode6(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, error40) {
                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 === error40)
                    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 create4(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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(ExportTraceServiceRequest, "ExportTraceServiceRequest");
                ExportTraceServiceRequest.prototype.resourceSpans = $util.emptyArray;
                ExportTraceServiceRequest.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new ExportTraceServiceRequest(properties);
                }, "create");
                ExportTraceServiceRequest.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.resourceSpans != null && message.resourceSpans.length)
                    for (var i4 = 0; i4 < message.resourceSpans.length; ++i4)
                      $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i4], 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, error40) {
                  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 === error40)
                      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 i4 = 0; i4 < message.resourceSpans.length; ++i4) {
                      var error40 = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i4]);
                      if (error40)
                        return "resourceSpans." + error40;
                    }
                  }
                  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 i4 = 0; i4 < object3.resourceSpans.length; ++i4) {
                      if (typeof object3.resourceSpans[i4] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: object expected");
                      message.resourceSpans[i4] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object3.resourceSpans[i4]);
                    }
                  }
                  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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(ExportTraceServiceResponse, "ExportTraceServiceResponse");
                ExportTraceServiceResponse.prototype.partialSuccess = null;
                ExportTraceServiceResponse.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new ExportTraceServiceResponse(properties);
                }, "create");
                ExportTraceServiceResponse.encode = /* @__PURE__ */ __name(function encode6(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, error40) {
                  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 === error40)
                      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 error40 = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify(message.partialSuccess);
                    if (error40)
                      return "partialSuccess." + error40;
                  }
                  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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(ExportTracePartialSuccess, "ExportTracePartialSuccess");
                ExportTracePartialSuccess.prototype.rejectedSpans = null;
                ExportTracePartialSuccess.prototype.errorMessage = null;
                ExportTracePartialSuccess.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new ExportTracePartialSuccess(properties);
                }, "create");
                ExportTracePartialSuccess.encode = /* @__PURE__ */ __name(function encode6(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, error40) {
                  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 === error40)
                      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 create4(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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(ExportMetricsServiceRequest, "ExportMetricsServiceRequest");
                ExportMetricsServiceRequest.prototype.resourceMetrics = $util.emptyArray;
                ExportMetricsServiceRequest.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new ExportMetricsServiceRequest(properties);
                }, "create");
                ExportMetricsServiceRequest.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.resourceMetrics != null && message.resourceMetrics.length)
                    for (var i4 = 0; i4 < message.resourceMetrics.length; ++i4)
                      $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i4], 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, error40) {
                  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 === error40)
                      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 i4 = 0; i4 < message.resourceMetrics.length; ++i4) {
                      var error40 = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i4]);
                      if (error40)
                        return "resourceMetrics." + error40;
                    }
                  }
                  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 i4 = 0; i4 < object3.resourceMetrics.length; ++i4) {
                      if (typeof object3.resourceMetrics[i4] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: object expected");
                      message.resourceMetrics[i4] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object3.resourceMetrics[i4]);
                    }
                  }
                  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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(ExportMetricsServiceResponse, "ExportMetricsServiceResponse");
                ExportMetricsServiceResponse.prototype.partialSuccess = null;
                ExportMetricsServiceResponse.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new ExportMetricsServiceResponse(properties);
                }, "create");
                ExportMetricsServiceResponse.encode = /* @__PURE__ */ __name(function encode6(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, error40) {
                  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 === error40)
                      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 error40 = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify(message.partialSuccess);
                    if (error40)
                      return "partialSuccess." + error40;
                  }
                  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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(ExportMetricsPartialSuccess, "ExportMetricsPartialSuccess");
                ExportMetricsPartialSuccess.prototype.rejectedDataPoints = null;
                ExportMetricsPartialSuccess.prototype.errorMessage = null;
                ExportMetricsPartialSuccess.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new ExportMetricsPartialSuccess(properties);
                }, "create");
                ExportMetricsPartialSuccess.encode = /* @__PURE__ */ __name(function encode6(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, error40) {
                  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 === error40)
                      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 create4(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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(ExportLogsServiceRequest, "ExportLogsServiceRequest");
                ExportLogsServiceRequest.prototype.resourceLogs = $util.emptyArray;
                ExportLogsServiceRequest.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new ExportLogsServiceRequest(properties);
                }, "create");
                ExportLogsServiceRequest.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                  if (!writer)
                    writer = $Writer.create();
                  if (message.resourceLogs != null && message.resourceLogs.length)
                    for (var i4 = 0; i4 < message.resourceLogs.length; ++i4)
                      $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i4], 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, error40) {
                  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 === error40)
                      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 i4 = 0; i4 < message.resourceLogs.length; ++i4) {
                      var error40 = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i4]);
                      if (error40)
                        return "resourceLogs." + error40;
                    }
                  }
                  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 i4 = 0; i4 < object3.resourceLogs.length; ++i4) {
                      if (typeof object3.resourceLogs[i4] !== "object")
                        throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: object expected");
                      message.resourceLogs[i4] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object3.resourceLogs[i4]);
                    }
                  }
                  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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(ExportLogsServiceResponse, "ExportLogsServiceResponse");
                ExportLogsServiceResponse.prototype.partialSuccess = null;
                ExportLogsServiceResponse.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new ExportLogsServiceResponse(properties);
                }, "create");
                ExportLogsServiceResponse.encode = /* @__PURE__ */ __name(function encode6(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, error40) {
                  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 === error40)
                      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 error40 = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify(message.partialSuccess);
                    if (error40)
                      return "partialSuccess." + error40;
                  }
                  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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(ExportLogsPartialSuccess, "ExportLogsPartialSuccess");
                ExportLogsPartialSuccess.prototype.rejectedLogRecords = null;
                ExportLogsPartialSuccess.prototype.errorMessage = null;
                ExportLogsPartialSuccess.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new ExportLogsPartialSuccess(properties);
                }, "create");
                ExportLogsPartialSuccess.encode = /* @__PURE__ */ __name(function encode6(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, error40) {
                  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 === error40)
                      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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(MetricsData, "MetricsData");
              MetricsData.prototype.resourceMetrics = $util.emptyArray;
              MetricsData.create = /* @__PURE__ */ __name(function create4(properties) {
                return new MetricsData(properties);
              }, "create");
              MetricsData.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resourceMetrics != null && message.resourceMetrics.length)
                  for (var i4 = 0; i4 < message.resourceMetrics.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.resourceMetrics.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i4]);
                    if (error40)
                      return "resourceMetrics." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.resourceMetrics.length; ++i4) {
                    if (typeof object3.resourceMetrics[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: object expected");
                    message.resourceMetrics[i4] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object3.resourceMetrics[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(ResourceMetrics, "ResourceMetrics");
              ResourceMetrics.prototype.resource = null;
              ResourceMetrics.prototype.scopeMetrics = $util.emptyArray;
              ResourceMetrics.prototype.schemaUrl = null;
              ResourceMetrics.create = /* @__PURE__ */ __name(function create4(properties) {
                return new ResourceMetrics(properties);
              }, "create");
              ResourceMetrics.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.scopeMetrics.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.ScopeMetrics.encode(message.scopeMetrics[i4], 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, error40) {
                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 === error40)
                    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 error40 = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error40)
                    return "resource." + error40;
                }
                if (message.scopeMetrics != null && message.hasOwnProperty("scopeMetrics")) {
                  if (!Array.isArray(message.scopeMetrics))
                    return "scopeMetrics: array expected";
                  for (var i4 = 0; i4 < message.scopeMetrics.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.verify(message.scopeMetrics[i4]);
                    if (error40)
                      return "scopeMetrics." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.scopeMetrics.length; ++i4) {
                    if (typeof object3.scopeMetrics[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: object expected");
                    message.scopeMetrics[i4] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.fromObject(object3.scopeMetrics[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(ScopeMetrics, "ScopeMetrics");
              ScopeMetrics.prototype.scope = null;
              ScopeMetrics.prototype.metrics = $util.emptyArray;
              ScopeMetrics.prototype.schemaUrl = null;
              ScopeMetrics.create = /* @__PURE__ */ __name(function create4(properties) {
                return new ScopeMetrics(properties);
              }, "create");
              ScopeMetrics.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.metrics.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.Metric.encode(message.metrics[i4], 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, error40) {
                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 === error40)
                    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 error40 = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error40)
                    return "scope." + error40;
                }
                if (message.metrics != null && message.hasOwnProperty("metrics")) {
                  if (!Array.isArray(message.metrics))
                    return "metrics: array expected";
                  for (var i4 = 0; i4 < message.metrics.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.Metric.verify(message.metrics[i4]);
                    if (error40)
                      return "metrics." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.metrics.length; ++i4) {
                    if (typeof object3.metrics[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: object expected");
                    message.metrics[i4] = $root.opentelemetry.proto.metrics.v1.Metric.fromObject(object3.metrics[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new Metric(properties);
              }, "create");
              Metric.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.metadata.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.metadata[i4], 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, error40) {
                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 === error40)
                    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 error40 = $root.opentelemetry.proto.metrics.v1.Gauge.verify(message.gauge);
                    if (error40)
                      return "gauge." + error40;
                  }
                }
                if (message.sum != null && message.hasOwnProperty("sum")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error40 = $root.opentelemetry.proto.metrics.v1.Sum.verify(message.sum);
                    if (error40)
                      return "sum." + error40;
                  }
                }
                if (message.histogram != null && message.hasOwnProperty("histogram")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error40 = $root.opentelemetry.proto.metrics.v1.Histogram.verify(message.histogram);
                    if (error40)
                      return "histogram." + error40;
                  }
                }
                if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error40 = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.verify(message.exponentialHistogram);
                    if (error40)
                      return "exponentialHistogram." + error40;
                  }
                }
                if (message.summary != null && message.hasOwnProperty("summary")) {
                  if (properties.data === 1)
                    return "data: multiple values";
                  properties.data = 1;
                  {
                    var error40 = $root.opentelemetry.proto.metrics.v1.Summary.verify(message.summary);
                    if (error40)
                      return "summary." + error40;
                  }
                }
                if (message.metadata != null && message.hasOwnProperty("metadata")) {
                  if (!Array.isArray(message.metadata))
                    return "metadata: array expected";
                  for (var i4 = 0; i4 < message.metadata.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.metadata[i4]);
                    if (error40)
                      return "metadata." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.metadata.length; ++i4) {
                    if (typeof object3.metadata[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: object expected");
                    message.metadata[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.metadata[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(Gauge, "Gauge");
              Gauge.prototype.dataPoints = $util.emptyArray;
              Gauge.create = /* @__PURE__ */ __name(function create4(properties) {
                return new Gauge(properties);
              }, "create");
              Gauge.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i4 = 0; i4 < message.dataPoints.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.dataPoints.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i4]);
                    if (error40)
                      return "dataPoints." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.dataPoints.length; ++i4) {
                    if (typeof object3.dataPoints[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: object expected");
                    message.dataPoints[i4] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object3.dataPoints[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(Sum, "Sum");
              Sum.prototype.dataPoints = $util.emptyArray;
              Sum.prototype.aggregationTemporality = null;
              Sum.prototype.isMonotonic = null;
              Sum.create = /* @__PURE__ */ __name(function create4(properties) {
                return new Sum(properties);
              }, "create");
              Sum.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i4 = 0; i4 < message.dataPoints.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.dataPoints.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i4]);
                    if (error40)
                      return "dataPoints." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.dataPoints.length; ++i4) {
                    if (typeof object3.dataPoints[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: object expected");
                    message.dataPoints[i4] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object3.dataPoints[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(Histogram, "Histogram");
              Histogram.prototype.dataPoints = $util.emptyArray;
              Histogram.prototype.aggregationTemporality = null;
              Histogram.create = /* @__PURE__ */ __name(function create4(properties) {
                return new Histogram(properties);
              }, "create");
              Histogram.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i4 = 0; i4 < message.dataPoints.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.encode(message.dataPoints[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.dataPoints.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.verify(message.dataPoints[i4]);
                    if (error40)
                      return "dataPoints." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.dataPoints.length; ++i4) {
                    if (typeof object3.dataPoints[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: object expected");
                    message.dataPoints[i4] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.fromObject(object3.dataPoints[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(ExponentialHistogram, "ExponentialHistogram");
              ExponentialHistogram.prototype.dataPoints = $util.emptyArray;
              ExponentialHistogram.prototype.aggregationTemporality = null;
              ExponentialHistogram.create = /* @__PURE__ */ __name(function create4(properties) {
                return new ExponentialHistogram(properties);
              }, "create");
              ExponentialHistogram.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i4 = 0; i4 < message.dataPoints.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.encode(message.dataPoints[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.dataPoints.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify(message.dataPoints[i4]);
                    if (error40)
                      return "dataPoints." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.dataPoints.length; ++i4) {
                    if (typeof object3.dataPoints[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: object expected");
                    message.dataPoints[i4] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.fromObject(object3.dataPoints[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(Summary, "Summary");
              Summary.prototype.dataPoints = $util.emptyArray;
              Summary.create = /* @__PURE__ */ __name(function create4(properties) {
                return new Summary(properties);
              }, "create");
              Summary.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.dataPoints != null && message.dataPoints.length)
                  for (var i4 = 0; i4 < message.dataPoints.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.encode(message.dataPoints[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.dataPoints.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.verify(message.dataPoints[i4]);
                    if (error40)
                      return "dataPoints." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.dataPoints.length; ++i4) {
                    if (typeof object3.dataPoints[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: object expected");
                    message.dataPoints[i4] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.fromObject(object3.dataPoints[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new NumberDataPoint(properties);
              }, "create");
              NumberDataPoint.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.exemplars.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i4], 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 i4 = 0; i4 < message.attributes.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.attributes.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i4]);
                    if (error40)
                      return "attributes." + error40;
                  }
                }
                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 i4 = 0; i4 < message.exemplars.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i4]);
                    if (error40)
                      return "exemplars." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.attributes.length; ++i4) {
                    if (typeof object3.attributes[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: object expected");
                    message.attributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i4]);
                  }
                }
                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 i4 = 0; i4 < object3.exemplars.length; ++i4) {
                    if (typeof object3.exemplars[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: object expected");
                    message.exemplars[i4] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object3.exemplars[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new HistogramDataPoint(properties);
              }, "create");
              HistogramDataPoint.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.bucketCounts.length; ++i4)
                    writer.fixed64(message.bucketCounts[i4]);
                  writer.ldelim();
                }
                if (message.explicitBounds != null && message.explicitBounds.length) {
                  writer.uint32(
                    /* id 7, wireType 2 =*/
                    58
                  ).fork();
                  for (var i4 = 0; i4 < message.explicitBounds.length; ++i4)
                    writer.double(message.explicitBounds[i4]);
                  writer.ldelim();
                }
                if (message.exemplars != null && message.exemplars.length)
                  for (var i4 = 0; i4 < message.exemplars.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i4], writer.uint32(
                      /* id 8, wireType 2 =*/
                      66
                    ).fork()).ldelim();
                if (message.attributes != null && message.attributes.length)
                  for (var i4 = 0; i4 < message.attributes.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.attributes.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i4]);
                    if (error40)
                      return "attributes." + error40;
                  }
                }
                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 i4 = 0; i4 < message.bucketCounts.length; ++i4)
                    if (!$util.isInteger(message.bucketCounts[i4]) && !(message.bucketCounts[i4] && $util.isInteger(message.bucketCounts[i4].low) && $util.isInteger(message.bucketCounts[i4].high)))
                      return "bucketCounts: integer|Long[] expected";
                }
                if (message.explicitBounds != null && message.hasOwnProperty("explicitBounds")) {
                  if (!Array.isArray(message.explicitBounds))
                    return "explicitBounds: array expected";
                  for (var i4 = 0; i4 < message.explicitBounds.length; ++i4)
                    if (typeof message.explicitBounds[i4] !== "number")
                      return "explicitBounds: number[] expected";
                }
                if (message.exemplars != null && message.hasOwnProperty("exemplars")) {
                  if (!Array.isArray(message.exemplars))
                    return "exemplars: array expected";
                  for (var i4 = 0; i4 < message.exemplars.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i4]);
                    if (error40)
                      return "exemplars." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.attributes.length; ++i4) {
                    if (typeof object3.attributes[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: object expected");
                    message.attributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i4]);
                  }
                }
                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 i4 = 0; i4 < object3.bucketCounts.length; ++i4)
                    if ($util.Long)
                      (message.bucketCounts[i4] = $util.Long.fromValue(object3.bucketCounts[i4])).unsigned = false;
                    else if (typeof object3.bucketCounts[i4] === "string")
                      message.bucketCounts[i4] = parseInt(object3.bucketCounts[i4], 10);
                    else if (typeof object3.bucketCounts[i4] === "number")
                      message.bucketCounts[i4] = object3.bucketCounts[i4];
                    else if (typeof object3.bucketCounts[i4] === "object")
                      message.bucketCounts[i4] = new $util.LongBits(object3.bucketCounts[i4].low >>> 0, object3.bucketCounts[i4].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 i4 = 0; i4 < object3.explicitBounds.length; ++i4)
                    message.explicitBounds[i4] = Number(object3.explicitBounds[i4]);
                }
                if (object3.exemplars) {
                  if (!Array.isArray(object3.exemplars))
                    throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: array expected");
                  message.exemplars = [];
                  for (var i4 = 0; i4 < object3.exemplars.length; ++i4) {
                    if (typeof object3.exemplars[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: object expected");
                    message.exemplars[i4] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object3.exemplars[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new ExponentialHistogramDataPoint(properties);
              }, "create");
              ExponentialHistogramDataPoint.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.attributes != null && message.attributes.length)
                  for (var i4 = 0; i4 < message.attributes.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i4], 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 i4 = 0; i4 < message.exemplars.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.attributes.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i4]);
                    if (error40)
                      return "attributes." + error40;
                  }
                }
                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 error40 = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.positive);
                  if (error40)
                    return "positive." + error40;
                }
                if (message.negative != null && message.hasOwnProperty("negative")) {
                  var error40 = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.negative);
                  if (error40)
                    return "negative." + error40;
                }
                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 i4 = 0; i4 < message.exemplars.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i4]);
                    if (error40)
                      return "exemplars." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.attributes.length; ++i4) {
                    if (typeof object3.attributes[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: object expected");
                    message.attributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i4]);
                  }
                }
                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 i4 = 0; i4 < object3.exemplars.length; ++i4) {
                    if (typeof object3.exemplars[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: object expected");
                    message.exemplars[i4] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object3.exemplars[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(Buckets, "Buckets");
                Buckets.prototype.offset = null;
                Buckets.prototype.bucketCounts = $util.emptyArray;
                Buckets.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new Buckets(properties);
                }, "create");
                Buckets.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.bucketCounts.length; ++i4)
                      writer.uint64(message.bucketCounts[i4]);
                    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, error40) {
                  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 === error40)
                      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 i4 = 0; i4 < message.bucketCounts.length; ++i4)
                      if (!$util.isInteger(message.bucketCounts[i4]) && !(message.bucketCounts[i4] && $util.isInteger(message.bucketCounts[i4].low) && $util.isInteger(message.bucketCounts[i4].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 i4 = 0; i4 < object3.bucketCounts.length; ++i4)
                      if ($util.Long)
                        (message.bucketCounts[i4] = $util.Long.fromValue(object3.bucketCounts[i4])).unsigned = true;
                      else if (typeof object3.bucketCounts[i4] === "string")
                        message.bucketCounts[i4] = parseInt(object3.bucketCounts[i4], 10);
                      else if (typeof object3.bucketCounts[i4] === "number")
                        message.bucketCounts[i4] = object3.bucketCounts[i4];
                      else if (typeof object3.bucketCounts[i4] === "object")
                        message.bucketCounts[i4] = new $util.LongBits(object3.bucketCounts[i4].low >>> 0, object3.bucketCounts[i4].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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new SummaryDataPoint(properties);
              }, "create");
              SummaryDataPoint.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.quantileValues.length; ++i4)
                    $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.encode(message.quantileValues[i4], writer.uint32(
                      /* id 6, wireType 2 =*/
                      50
                    ).fork()).ldelim();
                if (message.attributes != null && message.attributes.length)
                  for (var i4 = 0; i4 < message.attributes.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.attributes.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i4]);
                    if (error40)
                      return "attributes." + error40;
                  }
                }
                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 i4 = 0; i4 < message.quantileValues.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify(message.quantileValues[i4]);
                    if (error40)
                      return "quantileValues." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.attributes.length; ++i4) {
                    if (typeof object3.attributes[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: object expected");
                    message.attributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i4]);
                  }
                }
                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 i4 = 0; i4 < object3.quantileValues.length; ++i4) {
                    if (typeof object3.quantileValues[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: object expected");
                    message.quantileValues[i4] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.fromObject(object3.quantileValues[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                      if (properties[keys[i4]] != null)
                        this[keys[i4]] = properties[keys[i4]];
                  }
                }
                __name(ValueAtQuantile, "ValueAtQuantile");
                ValueAtQuantile.prototype.quantile = null;
                ValueAtQuantile.prototype.value = null;
                ValueAtQuantile.create = /* @__PURE__ */ __name(function create4(properties) {
                  return new ValueAtQuantile(properties);
                }, "create");
                ValueAtQuantile.encode = /* @__PURE__ */ __name(function encode6(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, error40) {
                  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 === error40)
                      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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new Exemplar(properties);
              }, "create");
              Exemplar.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.filteredAttributes.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.filteredAttributes[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.filteredAttributes.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.filteredAttributes[i4]);
                    if (error40)
                      return "filteredAttributes." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.filteredAttributes.length; ++i4) {
                    if (typeof object3.filteredAttributes[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: object expected");
                    message.filteredAttributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.filteredAttributes[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(LogsData, "LogsData");
              LogsData.prototype.resourceLogs = $util.emptyArray;
              LogsData.create = /* @__PURE__ */ __name(function create4(properties) {
                return new LogsData(properties);
              }, "create");
              LogsData.encode = /* @__PURE__ */ __name(function encode6(message, writer) {
                if (!writer)
                  writer = $Writer.create();
                if (message.resourceLogs != null && message.resourceLogs.length)
                  for (var i4 = 0; i4 < message.resourceLogs.length; ++i4)
                    $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i4], 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, error40) {
                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 === error40)
                    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 i4 = 0; i4 < message.resourceLogs.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i4]);
                    if (error40)
                      return "resourceLogs." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.resourceLogs.length; ++i4) {
                    if (typeof object3.resourceLogs[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: object expected");
                    message.resourceLogs[i4] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object3.resourceLogs[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(ResourceLogs, "ResourceLogs");
              ResourceLogs.prototype.resource = null;
              ResourceLogs.prototype.scopeLogs = $util.emptyArray;
              ResourceLogs.prototype.schemaUrl = null;
              ResourceLogs.create = /* @__PURE__ */ __name(function create4(properties) {
                return new ResourceLogs(properties);
              }, "create");
              ResourceLogs.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.scopeLogs.length; ++i4)
                    $root.opentelemetry.proto.logs.v1.ScopeLogs.encode(message.scopeLogs[i4], 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, error40) {
                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 === error40)
                    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 error40 = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource);
                  if (error40)
                    return "resource." + error40;
                }
                if (message.scopeLogs != null && message.hasOwnProperty("scopeLogs")) {
                  if (!Array.isArray(message.scopeLogs))
                    return "scopeLogs: array expected";
                  for (var i4 = 0; i4 < message.scopeLogs.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.logs.v1.ScopeLogs.verify(message.scopeLogs[i4]);
                    if (error40)
                      return "scopeLogs." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.scopeLogs.length; ++i4) {
                    if (typeof object3.scopeLogs[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: object expected");
                    message.scopeLogs[i4] = $root.opentelemetry.proto.logs.v1.ScopeLogs.fromObject(object3.scopeLogs[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __name(ScopeLogs, "ScopeLogs");
              ScopeLogs.prototype.scope = null;
              ScopeLogs.prototype.logRecords = $util.emptyArray;
              ScopeLogs.prototype.schemaUrl = null;
              ScopeLogs.create = /* @__PURE__ */ __name(function create4(properties) {
                return new ScopeLogs(properties);
              }, "create");
              ScopeLogs.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.logRecords.length; ++i4)
                    $root.opentelemetry.proto.logs.v1.LogRecord.encode(message.logRecords[i4], 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, error40) {
                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 === error40)
                    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 error40 = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope);
                  if (error40)
                    return "scope." + error40;
                }
                if (message.logRecords != null && message.hasOwnProperty("logRecords")) {
                  if (!Array.isArray(message.logRecords))
                    return "logRecords: array expected";
                  for (var i4 = 0; i4 < message.logRecords.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.logs.v1.LogRecord.verify(message.logRecords[i4]);
                    if (error40)
                      return "logRecords." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.logRecords.length; ++i4) {
                    if (typeof object3.logRecords[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: object expected");
                    message.logRecords[i4] = $root.opentelemetry.proto.logs.v1.LogRecord.fromObject(object3.logRecords[i4]);
                  }
                }
                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), i4 = 0; i4 < keys.length; ++i4)
                    if (properties[keys[i4]] != null)
                      this[keys[i4]] = properties[keys[i4]];
                }
              }
              __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 create4(properties) {
                return new LogRecord(properties);
              }, "create");
              LogRecord.encode = /* @__PURE__ */ __name(function encode6(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 i4 = 0; i4 < message.attributes.length; ++i4)
                    $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i4], 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, error40) {
                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 === error40)
                    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 error40 = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.body);
                  if (error40)
                    return "body." + error40;
                }
                if (message.attributes != null && message.hasOwnProperty("attributes")) {
                  if (!Array.isArray(message.attributes))
                    return "attributes: array expected";
                  for (var i4 = 0; i4 < message.attributes.length; ++i4) {
                    var error40 = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i4]);
                    if (error40)
                      return "attributes." + error40;
                  }
                }
                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 i4 = 0; i4 < object3.attributes.length; ++i4) {
                    if (typeof object3.attributes[i4] !== "object")
                      throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: object expected");
                    message.attributes[i4] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object3.attributes[i4]);
                  }
                }
                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 i4 = 0; i4 < hexStr.length; i4 += 2) {
        const hi = intValue(hexStr.charCodeAt(i4));
        const lo = intValue(hexStr.charCodeAt(i4 + 1));
        buf[offset++] = hi << 4 | lo;
      }
      return buf;
    }
    __name(hexToBinary, "hexToBinary");
    exports2.hexToBinary = hexToBinary;
  }
});

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

// node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js
var require_internal2 = __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_internal3 = __commonJS({
  "node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.toLogAttributes = exports2.createExportLogsServiceRequest = void 0;
    var utils_1 = require_utils5();
    var internal_1 = require_internal2();
    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: name4, version: version2 = "", schemaUrl = "" } } = record2;
        let ismMap = resourceMap.get(resource);
        if (!ismMap) {
          ismMap = /* @__PURE__ */ new Map();
          resourceMap.set(resource, ismMap);
        }
        const ismKey = `${name4}@${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_internal3();
    var logsResponseType = root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse;
    var logsRequestType = root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest;
    exports2.ProtobufLogsSerializer = {
      serializeRequest: /* @__PURE__ */ __name((arg) => {
        const request4 = (0, internal_1.createExportLogsServiceRequest)(arg);
        return logsRequestType.encode(request4).finish();
      }, "serializeRequest"),
      deserializeResponse: /* @__PURE__ */ __name((arg) => {
        return logsResponseType.decode(arg);
      }, "deserializeResponse")
    };
  }
});

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

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

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

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

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

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

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

// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js
var require_Buckets = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Buckets = void 0;
    var Buckets = class _Buckets {
      static {
        __name(this, "Buckets");
      }
      backing;
      indexBase;
      indexStart;
      indexEnd;
      /**
       * The term index refers to the number of the exponential histogram bucket
       * used to determine its boundaries. The lower boundary of a bucket is
       * determined by base ** index and the upper boundary of a bucket is
       * determined by base ** (index + 1). index values are signed to account
       * for values less than or equal to 1.
       *
       * indexBase is the index of the 0th position in the
       * backing array, i.e., backing[0] is the count
       * in the bucket with index `indexBase`.
       *
       * indexStart is the smallest index value represented
       * in the backing array.
       *
       * indexEnd is the largest index value represented in
       * the backing array.
       */
      constructor(backing = new BucketsBacking(), indexBase = 0, indexStart = 0, indexEnd = 0) {
        this.backing = backing;
        this.indexBase = indexBase;
        this.indexStart = indexStart;
        this.indexEnd = indexEnd;
      }
      /**
       * Offset is the bucket index of the smallest entry in the counts array
       * @returns {number}
       */
      get offset() {
        return this.indexStart;
      }
      /**
       * Buckets is a view into the backing array.
       * @returns {number}
       */
      get length() {
        if (this.backing.length === 0) {
          return 0;
        }
        if (this.indexEnd === this.indexStart && this.at(0) === 0) {
          return 0;
        }
        return this.indexEnd - this.indexStart + 1;
      }
      /**
       * An array of counts, where count[i] carries the count
       * of the bucket at index (offset+i).  count[i] is the count of
       * values greater than base^(offset+i) and less than or equal to
       * base^(offset+i+1).
       * @returns {number} The logical counts based on the backing array
       */
      counts() {
        return Array.from({ length: this.length }, (_2, i4) => this.at(i4));
      }
      /**
       * 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 i4 = 0; i4 < this.length; i4++) {
          if (this.at(i4) !== 0) {
            this.indexStart += i4;
            break;
          } else if (i4 === this.length - 1) {
            this.indexStart = this.indexEnd = this.indexBase = 0;
            return;
          }
        }
        for (let i4 = this.length - 1; i4 >= 0; i4--) {
          if (this.at(i4) !== 0) {
            this.indexEnd -= this.length - i4 - 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 i4 = mod2; i4 < each && inpos < size; i4++) {
            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 i4 = 0; i4 < num; i4++) {
          const tmp = this._counts[from + i4];
          this._counts[from + i4] = this._counts[limit2 - i4 - 1];
          this._counts[limit2 - i4 - 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 util5 = 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 util5.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 util5 = require_util15();
    var types_1 = require_types5();
    var LogarithmMapping = class {
      static {
        __name(this, "LogarithmMapping");
      }
      _scale;
      _scaleFactor;
      _inverseFactor;
      constructor(scale) {
        this._scale = scale;
        this._scaleFactor = util5.ldexp(Math.LOG2E, scale);
        this._inverseFactor = util5.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, i4) => {
      if (i4 > 10) {
        return new LogarithmMapping_1.LogarithmMapping(i4 - 10);
      }
      return new ExponentMapping_1.ExponentMapping(i4 - 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_esm(), __toCommonJS(esm_exports));
    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 i4 = 0; i4 < theirs.length; i4++) {
          this._incrementIndexBy(ours, theirOffset + i4 >> theirChange, theirs.at(i4));
        }
      }
      /**
       * _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 i4 = 0; i4 < theirs.length; i4++) {
          const ourIndex = theirOffset + i4 >> theirChange;
          let bucketIndex = ourIndex - ours.indexBase;
          if (bucketIndex < 0) {
            bucketIndex += ours.backing.length;
          }
          ours.decrementBucket(bucketIndex, theirs.at(i4));
        }
        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_esm(), __toCommonJS(esm_exports));
    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_esm(), __toCommonJS(esm_exports));
    var utils_1 = require_utils6();
    var AggregationSelector_1 = require_AggregationSelector();
    var MetricReader = class {
      static {
        __name(this, "MetricReader");
      }
      // Tracks the shutdown state.
      // TODO: use BindOncePromise here once a new version of @opentelemetry/core is available.
      _shutdown = false;
      // Additional MetricProducers which will be combined with the SDK's output
      _metricProducers;
      // MetricProducer used by this instance which produces metrics from the SDK
      _sdkMetricProducer;
      _aggregationTemporalitySelector;
      _aggregationSelector;
      _cardinalitySelector;
      constructor(options2) {
        this._aggregationSelector = options2?.aggregationSelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_SELECTOR;
        this._aggregationTemporalitySelector = options2?.aggregationTemporalitySelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;
        this._metricProducers = options2?.metricProducers ?? [];
        this._cardinalitySelector = options2?.cardinalitySelector;
      }
      setMetricProducer(metricProducer) {
        if (this._sdkMetricProducer) {
          throw new Error("MetricReader can not be bound to a MeterProvider again.");
        }
        this._sdkMetricProducer = metricProducer;
        this.onInitialized();
      }
      selectAggregation(instrumentType) {
        return this._aggregationSelector(instrumentType);
      }
      selectAggregationTemporality(instrumentType) {
        return this._aggregationTemporalitySelector(instrumentType);
      }
      selectCardinalityLimit(instrumentType) {
        return this._cardinalitySelector ? this._cardinalitySelector(instrumentType) : 2e3;
      }
      /**
       * Handle once the SDK has initialized this {@link MetricReader}
       * Overriding this method is optional.
       */
      onInitialized() {
      }
      async collect(options2) {
        if (this._sdkMetricProducer === void 0) {
          throw new Error("MetricReader is not bound to a MetricProducer");
        }
        if (this._shutdown) {
          throw new Error("MetricReader is shutdown");
        }
        const [sdkCollectionResults, ...additionalCollectionResults] = await Promise.all([
          this._sdkMetricProducer.collect({
            timeoutMillis: options2?.timeoutMillis
          }),
          ...this._metricProducers.map((producer) => producer.collect({
            timeoutMillis: options2?.timeoutMillis
          }))
        ]);
        const errors = sdkCollectionResults.errors.concat((0, utils_1.FlatMap)(additionalCollectionResults, (result) => result.errors));
        const resource = sdkCollectionResults.resourceMetrics.resource;
        const scopeMetrics = sdkCollectionResults.resourceMetrics.scopeMetrics.concat((0, utils_1.FlatMap)(additionalCollectionResults, (result) => result.resourceMetrics.scopeMetrics));
        return {
          resourceMetrics: {
            resource,
            scopeMetrics
          },
          errors
        };
      }
      async shutdown(options2) {
        if (this._shutdown) {
          api.diag.error("Cannot call shutdown twice.");
          return;
        }
        if (options2?.timeoutMillis == null) {
          await this.onShutdown();
        } else {
          await (0, utils_1.callWithTimeout)(this.onShutdown(), options2.timeoutMillis);
        }
        this._shutdown = true;
      }
      async forceFlush(options2) {
        if (this._shutdown) {
          api.diag.warn("Cannot forceFlush on already shutdown MetricReader.");
          return;
        }
        if (options2?.timeoutMillis == null) {
          await this.onForceFlush();
          return;
        }
        await (0, utils_1.callWithTimeout)(this.onForceFlush(), options2.timeoutMillis);
      }
    };
    exports2.MetricReader = MetricReader;
  }
});

// node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js
var require_PeriodicExportingMetricReader = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PeriodicExportingMetricReader = void 0;
    var api = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src8();
    var MetricReader_1 = require_MetricReader();
    var utils_1 = require_utils6();
    var PeriodicExportingMetricReader2 = class extends MetricReader_1.MetricReader {
      static {
        __name(this, "PeriodicExportingMetricReader");
      }
      _interval;
      _exporter;
      _exportInterval;
      _exportTimeout;
      constructor(options2) {
        super({
          aggregationSelector: options2.exporter.selectAggregation?.bind(options2.exporter),
          aggregationTemporalitySelector: options2.exporter.selectAggregationTemporality?.bind(options2.exporter),
          metricProducers: options2.metricProducers
        });
        if (options2.exportIntervalMillis !== void 0 && options2.exportIntervalMillis <= 0) {
          throw Error("exportIntervalMillis must be greater than 0");
        }
        if (options2.exportTimeoutMillis !== void 0 && options2.exportTimeoutMillis <= 0) {
          throw Error("exportTimeoutMillis must be greater than 0");
        }
        if (options2.exportTimeoutMillis !== void 0 && options2.exportIntervalMillis !== void 0 && options2.exportIntervalMillis < options2.exportTimeoutMillis) {
          throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");
        }
        this._exportInterval = options2.exportIntervalMillis ?? 6e4;
        this._exportTimeout = options2.exportTimeoutMillis ?? 3e4;
        this._exporter = options2.exporter;
      }
      async _runOnce() {
        try {
          await (0, utils_1.callWithTimeout)(this._doRun(), this._exportTimeout);
        } catch (err2) {
          if (err2 instanceof utils_1.TimeoutError) {
            api.diag.error("Export took longer than %s milliseconds and timed out.", this._exportTimeout);
            return;
          }
          (0, core_1.globalErrorHandler)(err2);
        }
      }
      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_node5 = __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_node5();
    Object.defineProperty(exports2, "defaultServiceName", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_1.defaultServiceName;
    }, "get") });
  }
});

// node_modules/@opentelemetry/resources/build/src/utils.js
var require_utils7 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.identity = exports2.isPromiseLike = void 0;
    var isPromiseLike = /* @__PURE__ */ __name((val) => {
      return val !== null && typeof val === "object" && typeof val.then === "function";
    }, "isPromiseLike");
    exports2.isPromiseLike = isPromiseLike;
    function identity(_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_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src8();
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var platform_1 = require_platform3();
    var utils_1 = require_utils7();
    var ResourceImpl = class _ResourceImpl {
      static {
        __name(this, "ResourceImpl");
      }
      _rawAttributes;
      _asyncAttributesPending = false;
      _memoizedAttributes;
      static FromAttributeList(attributes) {
        const res = new _ResourceImpl({});
        res._rawAttributes = guardedRawAttributes(attributes);
        res._asyncAttributesPending = attributes.filter(([_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 i4 = 0; i4 < this._rawAttributes.length; i4++) {
          const [k2, v2] = this._rawAttributes[i4];
          this._rawAttributes[i4] = [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((err2) => {
              api_1.diag.debug("promise rejection for resource attribute: %s - %s", k2, err2);
              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_esm(), __toCommonJS(esm_exports));
    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_esm(), __toCommonJS(esm_exports));
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    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(name4) {
        return name4.length <= this._MAX_LENGTH && this._isBaggageOctetString(name4);
      }
      // https://www.w3.org/TR/baggage/#definition
      _isBaggageOctetString(str2) {
        for (let i4 = 0; i4 < str2.length; i4++) {
          const ch = str2.charCodeAt(i4);
          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 util5 = __require("util");
    exports2.execAsync = util5.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_esm(), __toCommonJS(esm_exports));
    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 parts2 = idLine.split('" = "');
        if (parts2.length === 2) {
          return parts2[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_esm(), __toCommonJS(esm_exports));
    async function getMachineId() {
      const paths = ["/etc/machine-id", "/var/lib/dbus/machine-id"];
      for (const path150 of paths) {
        try {
          const result = await fs_1.promises.readFile(path150, { 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_esm(), __toCommonJS(esm_exports));
    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 process51 = __require("process");
    var execAsync_1 = require_execAsync();
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    async function getMachineId() {
      const args2 = "QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid";
      let command2 = "%windir%\\System32\\REG.exe";
      if (process51.arch === "ia32" && "PROCESSOR_ARCHITEW6432" in process51.env) {
        command2 = "%windir%\\sysnative\\cmd.exe /c " + command2;
      }
      try {
        const result = await (0, execAsync_1.execAsync)(`${command2} ${args2}`);
        const parts2 = result.stdout.split("REG_SZ");
        if (parts2.length === 2) {
          return parts2[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_esm(), __toCommonJS(esm_exports));
    async function getMachineId() {
      api_1.diag.debug("could not read machine-id: unsupported platform");
      return void 0;
    }
    __name(getMachineId, "getMachineId");
    exports2.getMachineId = getMachineId;
  }
});

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

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js
var require_utils8 = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.normalizeType = exports2.normalizeArch = void 0;
    var 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_utils8();
    var HostDetector = class {
      static {
        __name(this, "HostDetector");
      }
      detect(_config) {
        const attributes = {
          [semconv_1.ATTR_HOST_NAME]: (0, os_1.hostname)(),
          [semconv_1.ATTR_HOST_ARCH]: (0, utils_1.normalizeArch)((0, os_1.arch)()),
          [semconv_1.ATTR_HOST_ID]: (0, getMachineId_1.getMachineId)()
        };
        return { attributes };
      }
    };
    exports2.hostDetector = new HostDetector();
  }
});

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

// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js
var require_ProcessDetector = __commonJS({
  "node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.processDetector = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var semconv_1 = require_semconv2();
    var os59 = __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 = os59.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_node6 = __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_node6();
    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_esm(), __toCommonJS(esm_exports));
    var utils_1 = require_utils6();
    function createInstrumentDescriptor(name4, type, options2) {
      if (!isValidName(name4)) {
        api_1.diag.warn(`Invalid metric name: "${name4}". The metric name should be a ASCII string with a length no greater than 255 characters.`);
      }
      return {
        name: name4,
        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(name4) {
      return name4.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_esm(), __toCommonJS(esm_exports));
    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(it3) {
      return it3 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(name4, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name4, MetricData_1.InstrumentType.GAUGE, options2);
        const storage = this._meterSharedState.registerMetricStorage(descriptor2);
        return new Instruments_1.GaugeInstrument(storage, descriptor2);
      }
      /**
       * Create a {@link Histogram} instrument.
       */
      createHistogram(name4, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name4, MetricData_1.InstrumentType.HISTOGRAM, options2);
        const storage = this._meterSharedState.registerMetricStorage(descriptor2);
        return new Instruments_1.HistogramInstrument(storage, descriptor2);
      }
      /**
       * Create a {@link Counter} instrument.
       */
      createCounter(name4, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name4, MetricData_1.InstrumentType.COUNTER, options2);
        const storage = this._meterSharedState.registerMetricStorage(descriptor2);
        return new Instruments_1.CounterInstrument(storage, descriptor2);
      }
      /**
       * Create a {@link UpDownCounter} instrument.
       */
      createUpDownCounter(name4, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name4, 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(name4, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name4, 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(name4, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name4, 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(name4, options2) {
        const descriptor2 = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name4, MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, options2);
        const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor2);
        return new Instruments_1.ObservableUpDownCounterInstrument(descriptor2, storages, this._meterSharedState.observableRegistry);
      }
      /**
       * @see {@link Meter.addBatchObservableCallback}
       */
      addBatchObservableCallback(callback, observables) {
        this._meterSharedState.observableRegistry.addBatchCallback(callback, observables);
      }
      /**
       * @see {@link Meter.removeBatchObservableCallback}
       */
      removeBatchObservableCallback(callback, observables) {
        this._meterSharedState.observableRegistry.removeBatchCallback(callback, observables);
      }
    };
    exports2.Meter = Meter;
  }
});

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

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

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

// node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js
var require_TemporalMetricProcessor = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TemporalMetricProcessor = void 0;
    var AggregationTemporality_1 = require_AggregationTemporality();
    var HashMap_1 = require_HashMap();
    var TemporalMetricProcessor = class _TemporalMetricProcessor {
      static {
        __name(this, "TemporalMetricProcessor");
      }
      _aggregator;
      _unreportedAccumulations = /* @__PURE__ */ new Map();
      _reportHistory = /* @__PURE__ */ new Map();
      constructor(_aggregator, collectorHandles) {
        this._aggregator = _aggregator;
        collectorHandles.forEach((handle2) => {
          this._unreportedAccumulations.set(handle2, []);
        });
      }
      /**
       * 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 it3 of unreportedList) {
          result = _TemporalMetricProcessor.merge(result, it3, this._aggregator);
        }
        return result;
      }
      static merge(last2, current, aggregator) {
        const result = last2;
        const iterator2 = current.entries();
        let next = iterator2.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 = iterator2.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(map3) {
      return Array.from(map3.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_esm(), __toCommonJS(esm_exports));
    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((it3) => {
          it3.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_esm(), __toCommonJS(esm_exports));
    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 map3 = this._buffer.get(metric);
        if (map3 == null) {
          map3 = new HashMap_1.AttributeHashMap();
          this._buffer.set(metric, map3);
        }
        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;
          }
        }
        map3.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_esm(), __toCommonJS(esm_exports));
    var Instruments_1 = require_Instruments();
    var ObservableResult_1 = require_ObservableResult();
    var utils_1 = require_utils6();
    var ObservableRegistry = class {
      static {
        __name(this, "ObservableRegistry");
      }
      _callbacks = [];
      _batchCallbacks = [];
      addCallback(callback, instrument) {
        const idx = this._findCallback(callback, instrument);
        if (idx >= 0) {
          return;
        }
        this._callbacks.push({ callback, instrument });
      }
      removeCallback(callback, instrument) {
        const idx = this._findCallback(callback, instrument);
        if (idx < 0) {
          return;
        }
        this._callbacks.splice(idx, 1);
      }
      addBatchCallback(callback, instruments) {
        const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument));
        if (observableInstruments.size === 0) {
          api_1.diag.error("BatchObservableCallback is not associated with valid instruments", instruments);
          return;
        }
        const idx = this._findBatchCallback(callback, observableInstruments);
        if (idx >= 0) {
          return;
        }
        this._batchCallbacks.push({ callback, instruments: observableInstruments });
      }
      removeBatchCallback(callback, instruments) {
        const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument));
        const idx = this._findBatchCallback(callback, observableInstruments);
        if (idx < 0) {
          return;
        }
        this._batchCallbacks.splice(idx, 1);
      }
      /**
       * @returns a promise of rejected reasons for invoking callbacks.
       */
      async observe(collectionTime, timeoutMillis) {
        const callbackFutures = this._observeCallbacks(collectionTime, timeoutMillis);
        const batchCallbackFutures = this._observeBatchCallbacks(collectionTime, timeoutMillis);
        const results = await (0, utils_1.PromiseAllSettled)([
          ...callbackFutures,
          ...batchCallbackFutures
        ]);
        const rejections = results.filter(utils_1.isPromiseAllSettledRejectionResult).map((it3) => it3.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_utils6();
    var AsyncMetricStorage_1 = require_AsyncMetricStorage();
    var MetricStorageRegistry_1 = require_MetricStorageRegistry();
    var MultiWritableMetricStorage_1 = require_MultiWritableMetricStorage();
    var ObservableRegistry_1 = require_ObservableRegistry();
    var SyncMetricStorage_1 = require_SyncMetricStorage();
    var AttributesProcessor_1 = require_AttributesProcessor();
    var MeterSharedState = class {
      static {
        __name(this, "MeterSharedState");
      }
      _meterProviderSharedState;
      _instrumentationScope;
      metricStorageRegistry = new MetricStorageRegistry_1.MetricStorageRegistry();
      observableRegistry = new ObservableRegistry_1.ObservableRegistry();
      meter;
      constructor(_meterProviderSharedState, _instrumentationScope) {
        this._meterProviderSharedState = _meterProviderSharedState;
        this._instrumentationScope = _instrumentationScope;
        this.meter = new Meter_1.Meter(this);
      }
      registerMetricStorage(descriptor2) {
        const storages = this._registerMetricStorage(descriptor2, SyncMetricStorage_1.SyncMetricStorage);
        if (storages.length === 1) {
          return storages[0];
        }
        return new MultiWritableMetricStorage_1.MultiMetricStorage(storages);
      }
      registerAsyncMetricStorage(descriptor2) {
        const storages = this._registerMetricStorage(descriptor2, AsyncMetricStorage_1.AsyncMetricStorage);
        return storages;
      }
      /**
       * @param collector opaque handle of {@link MetricCollector} which initiated the collection.
       * @param collectionTime the HrTime at which the collection was initiated.
       * @param options options for collection.
       * @returns the list of metric data collected.
       */
      async collect(collector, collectionTime, options2) {
        const errors = await this.observableRegistry.observe(collectionTime, options2?.timeoutMillis);
        const storages = this.metricStorageRegistry.getStorages(collector);
        if (storages.length === 0) {
          return null;
        }
        const metricDataList = storages.map((metricStorage) => {
          return metricStorage.collect(collector, collectionTime);
        }).filter(utils_1.isNotNullish);
        if (metricDataList.length === 0) {
          return { errors };
        }
        return {
          scopeMetrics: {
            scope: this._instrumentationScope,
            metrics: metricDataList
          },
          errors
        };
      }
      _registerMetricStorage(descriptor2, MetricStorageType) {
        const views = this._meterProviderSharedState.viewRegistry.findViews(descriptor2, this._instrumentationScope);
        let storages = views.map((view) => {
          const viewDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptorWithView)(view, descriptor2);
          const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleStorage(viewDescriptor);
          if (compatibleStorage != null) {
            return compatibleStorage;
          }
          const aggregator = view.aggregation.createAggregator(viewDescriptor);
          const viewStorage = new MetricStorageType(viewDescriptor, aggregator, view.attributesProcessor, this._meterProviderSharedState.metricCollectors, view.aggregationCardinalityLimit);
          this.metricStorageRegistry.register(viewStorage);
          return viewStorage;
        });
        if (storages.length === 0) {
          const perCollectorAggregations = this._meterProviderSharedState.selectAggregations(descriptor2.type);
          const collectorStorages = perCollectorAggregations.map(([collector, aggregation]) => {
            const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(collector, descriptor2);
            if (compatibleStorage != null) {
              return compatibleStorage;
            }
            const aggregator = aggregation.createAggregator(descriptor2);
            const cardinalityLimit = collector.selectCardinalityLimit(descriptor2.type);
            const storage = new MetricStorageType(descriptor2, aggregator, (0, AttributesProcessor_1.createNoopAttributesProcessor)(), [collector], cardinalityLimit);
            this.metricStorageRegistry.registerForCollector(collector, storage);
            return storage;
          });
          storages = storages.concat(collectorStorages);
        }
        return storages;
      }
    };
    exports2.MeterSharedState = MeterSharedState;
  }
});

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

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

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

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

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

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

// node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js
var require_MeterProvider = __commonJS({
  "node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MeterProvider = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    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(name4, 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: name4,
          version: version2,
          schemaUrl: options2.schemaUrl
        }).meter;
      }
      /**
       * Shut down the MeterProvider and all registered
       * MetricReaders.
       *
       * Returns a promise which is resolved when all flushes are complete.
       */
      async shutdown(options2) {
        if (this._shutdown) {
          api_1.diag.warn("shutdown may only be called once per MeterProvider");
          return;
        }
        this._shutdown = true;
        await Promise.all(this._sharedState.metricCollectors.map((collector) => {
          return collector.shutdown(options2);
        }));
      }
      /**
       * Notifies all registered MetricReaders to flush any buffered data.
       *
       * Returns a promise which is resolved when all flushes are complete.
       */
      async forceFlush(options2) {
        if (this._shutdown) {
          api_1.diag.warn("invalid attempt to force flush after MeterProvider shutdown");
          return;
        }
        await Promise.all(this._sharedState.metricCollectors.map((collector) => {
          return collector.forceFlush(options2);
        }));
      }
    };
    exports2.MeterProvider = MeterProvider;
  }
});

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

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

// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js
var require_internal4 = __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_esm(), __toCommonJS(esm_exports));
    var sdk_metrics_1 = require_src14();
    var internal_types_1 = require_internal_types();
    var utils_1 = require_utils5();
    var internal_1 = require_internal2();
    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 out2 = {
        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:
          out2.sum = {
            aggregationTemporality,
            isMonotonic: metricData.isMonotonic,
            dataPoints: toSingularDataPoints(metricData, encoder)
          };
          break;
        case sdk_metrics_1.DataPointType.GAUGE:
          out2.gauge = {
            dataPoints: toSingularDataPoints(metricData, encoder)
          };
          break;
        case sdk_metrics_1.DataPointType.HISTOGRAM:
          out2.histogram = {
            aggregationTemporality,
            dataPoints: toHistogramDataPoints(metricData, encoder)
          };
          break;
        case sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM:
          out2.exponentialHistogram = {
            aggregationTemporality,
            dataPoints: toExponentialHistogramDataPoints(metricData, encoder)
          };
          break;
      }
      return out2;
    }
    __name(toMetric, "toMetric");
    exports2.toMetric = toMetric;
    function toSingularDataPoint(dataPoint, valueType, encoder) {
      const out2 = {
        attributes: (0, internal_1.toAttributes)(dataPoint.attributes),
        startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime),
        timeUnixNano: encoder.encodeHrTime(dataPoint.endTime)
      };
      switch (valueType) {
        case api_1.ValueType.INT:
          out2.asInt = dataPoint.value;
          break;
        case api_1.ValueType.DOUBLE:
          out2.asDouble = dataPoint.value;
          break;
      }
      return out2;
    }
    __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_internal4();
    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_internal5 = __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_internal2();
    var utils_1 = require_utils5();
    function sdkSpanToOtlpSpan(span, encoder) {
      const ctx = span.spanContext();
      const status = span.status;
      const parentSpanId = span.parentSpanContext?.spanId ? encoder.encodeSpanContext(span.parentSpanContext?.spanId) : void 0;
      return {
        traceId: encoder.encodeSpanContext(ctx.traceId),
        spanId: encoder.encodeSpanContext(ctx.spanId),
        parentSpanId,
        traceState: ctx.traceState?.serialize(),
        name: span.name,
        // Span kind is offset by 1 because the API does not define a value for unset
        kind: span.kind == null ? 0 : span.kind + 1,
        startTimeUnixNano: encoder.encodeHrTime(span.startTime),
        endTimeUnixNano: encoder.encodeHrTime(span.endTime),
        attributes: (0, internal_1.toAttributes)(span.attributes),
        droppedAttributesCount: span.droppedAttributesCount,
        events: span.events.map((event) => toOtlpSpanEvent(event, encoder)),
        droppedEventsCount: span.droppedEventsCount,
        status: {
          // API and proto enums share the same values
          code: status.code,
          message: status.message
        },
        links: span.links.map((link3) => toOtlpLink(link3, encoder)),
        droppedLinksCount: span.droppedLinksCount
      };
    }
    __name(sdkSpanToOtlpSpan, "sdkSpanToOtlpSpan");
    exports2.sdkSpanToOtlpSpan = sdkSpanToOtlpSpan;
    function toOtlpLink(link3, encoder) {
      return {
        attributes: link3.attributes ? (0, internal_1.toAttributes)(link3.attributes) : [],
        spanId: encoder.encodeSpanContext(link3.context.spanId),
        traceId: encoder.encodeSpanContext(link3.context.traceId),
        traceState: link3.context.traceState?.serialize(),
        droppedAttributesCount: link3.droppedAttributesCount || 0
      };
    }
    __name(toOtlpLink, "toOtlpLink");
    exports2.toOtlpLink = toOtlpLink;
    function toOtlpSpanEvent(timedEvent, encoder) {
      return {
        attributes: timedEvent.attributes ? (0, internal_1.toAttributes)(timedEvent.attributes) : [],
        name: timedEvent.name,
        timeUnixNano: encoder.encodeHrTime(timedEvent.time),
        droppedAttributesCount: timedEvent.droppedAttributesCount || 0
      };
    }
    __name(toOtlpSpanEvent, "toOtlpSpanEvent");
    exports2.toOtlpSpanEvent = toOtlpSpanEvent;
    function createExportTraceServiceRequest(spans, options2) {
      const encoder = (0, utils_1.getOtlpEncoder)(options2);
      return {
        resourceSpans: spanRecordsToResourceSpans(spans, encoder)
      };
    }
    __name(createExportTraceServiceRequest, "createExportTraceServiceRequest");
    exports2.createExportTraceServiceRequest = createExportTraceServiceRequest;
    function createResourceMap(readableSpans) {
      const resourceMap = /* @__PURE__ */ new Map();
      for (const 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 out2 = [];
      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
        };
        out2.push(transformedSpans);
        entry = entryIterator.next();
      }
      return out2;
    }
    __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_internal5();
    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_internal3();
    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_internal4();
    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_internal5();
    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_esm(), __toCommonJS(esm_exports));
    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_node7 = __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_node7();
    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_node8 = __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_node8();
    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_node9 = __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_node9();
    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_esm(), __toCommonJS(esm_exports));
    var api = (init_esm(), __toCommonJS(esm_exports));
    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(body2) {
        if (this._isLogRecordReadonly()) {
          return;
        }
        this._body = body2;
      }
      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: body2, 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 = body2;
        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(body2) {
        this.body = body2;
        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_esm(), __toCommonJS(esm_exports));
    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_esm(), __toCommonJS(esm_exports));
    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(name4, version2, options2) {
        if (this._shutdownOnce.isCalled) {
          api_1.diag.warn("A shutdown LoggerProvider cannot provide a Logger");
          return api_logs_1.NOOP_LOGGER;
        }
        if (!name4) {
          api_1.diag.warn("Logger requested without instrumentation scope name.");
        }
        const loggerName = name4 || 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_esm(), __toCommonJS(esm_exports));
    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((resolve42, reject) => {
          const promises9 = [];
          const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize);
          for (let i4 = 0; i4 < batchCount; i4++) {
            promises9.push(this._flushOneBatch());
          }
          Promise.all(promises9).then(() => {
            resolve42();
          }).catch(reject);
        });
      }
      _flushOneBatch() {
        this._clearTimer();
        if (this._finishedLogRecords.length === 0) {
          return Promise.resolve();
        }
        return new Promise((resolve42, reject) => {
          (0, core_2.callWithTimeout)(this._export(this._finishedLogRecords.splice(0, this._maxExportBatchSize)), this._exportTimeoutMillis).then(() => resolve42()).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_node10 = __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_node10();
    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(...args2) {
          return manager.with(context2, () => target.apply(this, args2));
        }, "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 map3 = this._getPatchMap(ee2);
        if (map3 !== 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 map3 = contextManager._getPatchMap(ee2);
          if (map3 !== void 0) {
            if (arguments.length === 0) {
              contextManager._createPatchMap(ee2);
            } else if (map3[event] !== void 0) {
              delete map3[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 map3 = contextManager._getPatchMap(ee2);
          if (map3 === void 0) {
            map3 = contextManager._createPatchMap(ee2);
          }
          let listeners = map3[event];
          if (listeners === void 0) {
            listeners = /* @__PURE__ */ new WeakMap();
            map3[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 map3 = /* @__PURE__ */ Object.create(null);
        ee2[this._kOtListeners] = map3;
        return map3;
      }
      _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_esm(), __toCommonJS(esm_exports));
    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, ...args2) {
        this._enterContext(context2);
        try {
          return fn.call(thisArg, ...args2);
        } 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_esm(), __toCommonJS(esm_exports));
    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, ...args2) {
        const cb = thisArg == null ? fn : fn.bind(thisArg);
        return this._asyncLocalStorage.run(context2, cb, ...args2);
      }
      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_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src8();
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    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(name4, 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: name4,
          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(name4) {
        if (this._isSpanEnded())
          return this;
        this.name = name4;
        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 error40 = 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}}`, error40);
        }
        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_esm(), __toCommonJS(esm_exports));
    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_esm(), __toCommonJS(esm_exports));
    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 i4 = 0; i4 < traceId.length / 8; i4++) {
          const pos2 = i4 * 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_esm(), __toCommonJS(esm_exports));
    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 mergeConfig3(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(mergeConfig3, "mergeConfig");
    exports2.mergeConfig = mergeConfig3;
    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_esm(), __toCommonJS(esm_exports));
    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((resolve42, reject) => {
          const promises9 = [];
          const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
          for (let i4 = 0, j2 = count; i4 < j2; i4++) {
            promises9.push(this._flushOneBatch());
          }
          Promise.all(promises9).then(() => {
            resolve42();
          }).catch(reject);
        });
      }
      _flushOneBatch() {
        this._clearTimer();
        if (this._finishedSpans.length === 0) {
          return Promise.resolve();
        }
        return new Promise((resolve42, 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) {
                resolve42();
              } else {
                reject(result.error ?? new Error("BatchSpanProcessor: span export failed"));
              }
            }), "doExport");
            let pendingResources = null;
            for (let i4 = 0, len = spans.length; i4 < len; i4++) {
              const span = spans[i4];
              if (span.resource.asyncAttributesPending && span.resource.waitForAsyncAttributes) {
                pendingResources ??= [];
                pendingResources.push(span.resource.waitForAsyncAttributes());
              }
            }
            if (pendingResources === null) {
              doExport();
            } else {
              Promise.all(pendingResources).then(doExport, (err2) => {
                (0, core_1.globalErrorHandler)(err2);
                reject(err2);
              });
            }
          });
        });
      }
      _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 generateId2() {
        for (let i4 = 0; i4 < bytes / 4; i4++) {
          SHARED_BUFFER.writeUInt32BE(Math.random() * 2 ** 32 >>> 0, i4 * 4);
        }
        for (let i4 = 0; i4 < bytes; i4++) {
          if (SHARED_BUFFER[i4] > 0) {
            break;
          } else if (i4 === 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_node11 = __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_node11();
    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_esm(), __toCommonJS(esm_exports));
    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(name4, 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, name4, 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: name4,
          kind: spanKind,
          links,
          parentSpanContext: validParentSpanContext,
          attributes: initAttributes,
          startTime: options2.startTime,
          spanProcessor: this._spanProcessor,
          spanLimits: this._spanLimits
        });
        return span;
      }
      startActiveSpan(name4, 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(name4, 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 promises9 = [];
        for (const spanProcessor of this._spanProcessors) {
          promises9.push(spanProcessor.forceFlush());
        }
        return new Promise((resolve42) => {
          Promise.all(promises9).then(() => {
            resolve42();
          }).catch((error40) => {
            (0, core_1.globalErrorHandler)(error40 || new Error("MultiSpanProcessor: forceFlush failed"));
            resolve42();
          });
        });
      }
      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 promises9 = [];
        for (const spanProcessor of this._spanProcessors) {
          promises9.push(spanProcessor.shutdown());
        }
        return new Promise((resolve42, reject) => {
          Promise.all(promises9).then(() => {
            resolve42();
          }, 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(name4, version2, options2) {
        const key = `${name4}@${version2 || ""}:${options2?.schemaUrl || ""}`;
        if (!this._tracers.has(key)) {
          this._tracers.set(key, new Tracer_1.Tracer({ name: name4, version: version2, schemaUrl: options2?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor));
        }
        return this._tracers.get(key);
      }
      forceFlush() {
        const timeout2 = this._config.forceFlushTimeoutMillis;
        const promises9 = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => {
          return new Promise((resolve42) => {
            let state;
            const timeoutInterval = setTimeout(() => {
              resolve42(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;
                resolve42(state);
              }
            }).catch((error40) => {
              clearTimeout(timeoutInterval);
              state = ForceFlushState.error;
              resolve42(error40);
            });
          });
        });
        return new Promise((resolve42, reject) => {
          Promise.all(promises9).then((results) => {
            const errors = results.filter((result) => result !== ForceFlushState.resolved);
            if (errors.length > 0) {
              reject(errors);
            } else {
              resolve42();
            }
          }).catch((error40) => reject([error40]));
        });
      }
      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_esm(), __toCommonJS(esm_exports));
    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((err2) => (0, core_1.globalErrorHandler)(err2));
        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_esm(), __toCommonJS(esm_exports));
    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 i4 = 0, j2 = instrumentations.length; i4 < j2; i4++) {
        const instrumentation = instrumentations[i4];
        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_esm(), __toCommonJS(esm_exports));
    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_esm(), __toCommonJS(esm_exports));
    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 i4 = 0; i4 < Math.max(v1.length, v2.length); i4++) {
        const res = _compareVersionStrings(v1[i4] || "0", v2[i4] || "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, name4, value) {
      const enumerable = !!obj[name4] && Object.prototype.propertyIsEnumerable.call(obj, name4);
      Object.defineProperty(obj, name4, {
        configurable: true,
        enumerable,
        writable: true,
        value
      });
    }
    __name(defineProperty2, "defineProperty");
    var wrap2 = /* @__PURE__ */ __name((nodule, name4, wrapper) => {
      if (!nodule || !nodule[name4]) {
        logger6("no original function " + String(name4) + " to wrap");
        return;
      }
      if (!wrapper) {
        logger6("no wrapper function");
        logger6(new Error().stack);
        return;
      }
      const original = nodule[name4];
      if (typeof original !== "function" || typeof wrapper !== "function") {
        logger6("original object and wrapper must be functions");
        return;
      }
      const wrapped = wrapper(original, name4);
      defineProperty2(wrapped, "__original", original);
      defineProperty2(wrapped, "__unwrap", () => {
        if (nodule[name4] === wrapped) {
          defineProperty2(nodule, name4, original);
        }
      });
      defineProperty2(wrapped, "__wrapped", true);
      defineProperty2(nodule, name4, 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((name4) => {
          (0, exports2.wrap)(nodule, name4, wrapper);
        });
      });
    }, "massWrap");
    exports2.massWrap = massWrap;
    var unwrap = /* @__PURE__ */ __name((nodule, name4) => {
      if (!nodule || !nodule[name4]) {
        logger6("no function to unwrap.");
        logger6(new Error().stack);
        return;
      }
      const wrapped = nodule[name4];
      if (!wrapped.__unwrap) {
        logger6("no original to unwrap to -- has " + String(name4) + " 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((name4) => {
          (0, exports2.unwrap)(nodule, name4);
        });
      });
    }, "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_esm(), __toCommonJS(esm_exports));
    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, info2) {
        if (!hookHandler) {
          return;
        }
        try {
          hookHandler(span, info2);
        } 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 sep13 = __require("path").sep;
    module2.exports = function(file2) {
      var segments = file2.split(sep13);
      var index = segments.lastIndexOf("node_modules");
      if (index === -1) return;
      if (!segments[index + 1]) return;
      var scoped = segments[index + 1][0] === "@";
      var name4 = scoped ? segments[index + 1] + "/" + segments[index + 2] : segments[index + 1];
      var offset = scoped ? 3 : 2;
      var basedir = "";
      var lastBaseDirSegmentIndex = index + offset - 1;
      for (var i4 = 0; i4 <= lastBaseDirSegmentIndex; i4++) {
        if (i4 === lastBaseDirSegmentIndex) {
          basedir += segments[i4];
        } else {
          basedir += segments[i4] + sep13;
        }
      }
      var path150 = "";
      var lastSegmentIndex = segments.length - 1;
      for (var i22 = index + offset; i22 <= lastSegmentIndex; i22++) {
        if (i22 === lastSegmentIndex) {
          path150 += segments[i22];
        } else {
          path150 += segments[i22] + sep13;
        }
      }
      return {
        name: name4,
        basedir,
        path: path150
      };
    };
  }
});

// node_modules/resolve/lib/homedir.js
var require_homedir = __commonJS({
  "node_modules/resolve/lib/homedir.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var os59 = __require("os");
    module2.exports = os59.homedir || /* @__PURE__ */ __name(function homedir34() {
      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 path150 = __require("path");
    var parse17 = path150.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 = parse17(absoluteStart);
      while (parsed.dir !== paths[paths.length - 1]) {
        paths.push(parsed.dir);
        parsed = parse17(parsed.dir);
      }
      return paths.reduce(function(dirs, aPath) {
        return dirs.concat(modules.map(function(moduleDir) {
          return path150.resolve(prefix, aPath, moduleDir);
        }));
      }, []);
    }, "getNodeModulesDirs");
    module2.exports = /* @__PURE__ */ __name(function nodeModulesPaths(start2, opts, request4) {
      var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ["node_modules"];
      if (opts && typeof opts.paths === "function") {
        return opts.paths(
          request4,
          start2,
          function() {
            return getNodeModulesDirs(start2, modules);
          },
          opts
        );
      }
      var dirs = getNodeModulesDirs(start2, 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 i4 = 0; i4 < a2.length; i4 += 1) {
        arr[i4] = a2[i4];
      }
      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 i4 = offset || 0, j2 = 0; i4 < arrLike.length; i4 += 1, j2 += 1) {
        arr[j2] = arrLike[i4];
      }
      return arr;
    }, "slicy");
    var joiny = /* @__PURE__ */ __name(function(arr, joiner) {
      var str2 = "";
      for (var i4 = 0; i4 < arr.length; i4 += 1) {
        str2 += arr[i4];
        if (i4 + 1 < arr.length) {
          str2 += joiner;
        }
      }
      return str2;
    }, "joiny");
    module2.exports = /* @__PURE__ */ __name(function bind2(that) {
      var target = this;
      if (typeof target !== "function" || toStr.apply(target) !== funcType) {
        throw new TypeError(ERROR_MESSAGE + target);
      }
      var args2 = slicy(arguments, 1);
      var bound;
      var binder = /* @__PURE__ */ __name(function() {
        if (this instanceof bound) {
          var result = target.apply(
            this,
            concatty(args2, arguments)
          );
          if (Object(result) === result) {
            return result;
          }
          return this;
        }
        return target.apply(
          that,
          concatty(args2, arguments)
        );
      }, "binder");
      var boundLength = max(0, target.length - args2.length);
      var boundArgs = [];
      for (var i4 = 0; i4 < boundLength; i4++) {
        boundArgs[i4] = "$" + i4;
      }
      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 bind2 = require_function_bind();
    module2.exports = bind2.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 parts2 = specifier.split(" ");
      var op = parts2.length > 1 ? parts2[0] : "=";
      var versionParts = (parts2.length > 1 ? parts2[1] : parts2[0]).split(".");
      for (var i4 = 0; i4 < 3; ++i4) {
        var cur = parseInt(nodeParts[i4] || 0, 10);
        var ver = parseInt(versionParts[i4] || 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 i4 = 0; i4 < specifiers.length; ++i4) {
        if (!specifierIncluded(current, specifiers[i4])) {
          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 i4 = 0; i4 < specifierValue.length; ++i4) {
          if (matchesRange(current, specifierValue[i4])) {
            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 fs142 = __require("fs");
    var getHomedir = require_homedir();
    var path150 = __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" && fs142.realpath && typeof fs142.realpath.native === "function" ? fs142.realpath.native : fs142.realpath;
    var homedir34 = getHomedir();
    var defaultPaths = /* @__PURE__ */ __name(function() {
      return [
        path150.join(homedir34, ".node_modules"),
        path150.join(homedir34, ".node_libraries")
      ];
    }, "defaultPaths");
    var defaultIsFile = /* @__PURE__ */ __name(function isFile4(file2, cb) {
      fs142.stat(file2, function(err2, stat14) {
        if (!err2) {
          return cb(null, stat14.isFile() || stat14.isFIFO());
        }
        if (err2.code === "ENOENT" || err2.code === "ENOTDIR") return cb(null, false);
        return cb(err2);
      });
    }, "isFile");
    var defaultIsDir = /* @__PURE__ */ __name(function isDirectory(dir, cb) {
      fs142.stat(dir, function(err2, stat14) {
        if (!err2) {
          return cb(null, stat14.isDirectory());
        }
        if (err2.code === "ENOENT" || err2.code === "ENOTDIR") return cb(null, false);
        return cb(err2);
      });
    }, "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(readFile25, pkgfile, cb) {
      readFile25(pkgfile, function(readFileErr, body2) {
        if (readFileErr) cb(readFileErr);
        else {
          try {
            var pkg2 = JSON.parse(body2);
            cb(null, pkg2);
          } catch (jsonErr) {
            cb(null);
          }
        }
      });
    }, "defaultReadPackage");
    var getPackageCandidates = /* @__PURE__ */ __name(function getPackageCandidates2(x3, start2, opts) {
      var dirs = nodeModulesPaths(start2, opts, x3);
      for (var i4 = 0; i4 < dirs.length; i4++) {
        dirs[i4] = path150.join(dirs[i4], x3);
      }
      return dirs;
    }, "getPackageCandidates");
    module2.exports = /* @__PURE__ */ __name(function resolve42(x3, options2, callback) {
      var cb = callback;
      var opts = options2;
      if (typeof options2 === "function") {
        cb = opts;
        opts = {};
      }
      if (typeof x3 !== "string") {
        var err2 = new TypeError("Path must be a string.");
        return process.nextTick(function() {
          cb(err2);
        });
      }
      opts = normalizeOptions(x3, opts);
      var isFile4 = opts.isFile || defaultIsFile;
      var isDirectory = opts.isDirectory || defaultIsDir;
      var readFile25 = opts.readFile || fs142.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 || path150.dirname(caller());
      var parent = opts.filename || basedir;
      opts.paths = opts.paths || defaultPaths();
      var absoluteStart = path150.resolve(basedir);
      maybeRealpath(
        realpath3,
        absoluteStart,
        opts,
        function(err3, realStart) {
          if (err3) cb(err3);
          else init2(realStart);
        }
      );
      var res;
      function init2(basedir2) {
        if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x3)) {
          res = path150.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(err3, n3, pkg2) {
          if (err3) cb(err3);
          else if (n3) {
            return maybeRealpath(realpath3, n3, opts, function(err4, realN) {
              if (err4) {
                cb(err4);
              } else {
                cb(null, realN, pkg2);
              }
            });
          } else {
            var moduleError = new Error("Cannot find module '" + x3 + "' from '" + parent + "'");
            moduleError.code = "MODULE_NOT_FOUND";
            cb(moduleError);
          }
        });
      }
      __name(init2, "init");
      function onfile(err3, m3, pkg2) {
        if (err3) cb(err3);
        else if (m3) cb(null, m3, pkg2);
        else loadAsDirectory(res, function(err4, d2, pkg3) {
          if (err4) cb(err4);
          else if (d2) {
            maybeRealpath(realpath3, d2, opts, function(err5, realD) {
              if (err5) {
                cb(err5);
              } 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 file2 = x5 + exts2[0];
          var pkg2 = loadPackage;
          if (pkg2) onpkg(null, pkg2);
          else loadpkg(path150.dirname(file2), onpkg);
          function onpkg(err3, pkg_, dir) {
            pkg2 = pkg_;
            if (err3) return cb2(err3);
            if (dir && pkg2 && opts.pathFilter) {
              var rfile = path150.relative(dir, file2);
              var rel = rfile.slice(0, rfile.length - exts2[0].length);
              var r5 = opts.pathFilter(pkg2, x5, rel);
              if (r5) return load(
                [""].concat(extensions.slice()),
                path150.resolve(dir, r5),
                pkg2
              );
            }
            isFile4(file2, onex);
          }
          __name(onpkg, "onpkg");
          function onex(err3, ex) {
            if (err3) return cb2(err3);
            if (ex) return cb2(null, file2, 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(path150.dirname(dir), cb2);
          var pkgfile = path150.join(pkgdir, "package.json");
          isFile4(pkgfile, function(err3, ex) {
            if (!ex) return loadpkg(path150.dirname(dir), cb2);
            readPackage2(readFile25, pkgfile, function(err4, pkgParam) {
              if (err4) cb2(err4);
              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 = path150.join(pkgdir, "package.json");
          isFile4(pkgfile, function(err3, ex) {
            if (err3) return cb2(err3);
            if (!ex) return loadAsFile(path150.join(x4, "index"), fpkg, cb2);
            readPackage2(readFile25, pkgfile, function(err4, pkgParam) {
              if (err4) return cb2(err4);
              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(path150.resolve(x4, pkg2.main), pkg2, function(err5, m3, pkg3) {
                  if (err5) return cb2(err5);
                  if (m3) return cb2(null, m3, pkg3);
                  if (!pkg3) return loadAsFile(path150.join(x4, "index"), pkg3, cb2);
                  var dir = path150.resolve(x4, pkg3.main);
                  loadAsDirectory(dir, pkg3, function(err6, n3, pkg4) {
                    if (err6) return cb2(err6);
                    if (n3) return cb2(null, n3, pkg4);
                    loadAsFile(path150.join(x4, "index"), pkg4, cb2);
                  });
                });
                return;
              }
              loadAsFile(path150.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(path150.dirname(dir), isdir);
        function isdir(err3, isdir2) {
          if (err3) return cb2(err3);
          if (!isdir2) return processDirs(cb2, dirs.slice(1));
          loadAsFile(dir, opts.package, onfile2);
        }
        __name(isdir, "isdir");
        function onfile2(err3, m3, pkg2) {
          if (err3) return cb2(err3);
          if (m3) return cb2(null, m3, pkg2);
          loadAsDirectory(dir, opts.package, ondir);
        }
        __name(onfile2, "onfile");
        function ondir(err3, n3, pkg2) {
          if (err3) return cb2(err3);
          if (n3) return cb2(null, n3, pkg2);
          processDirs(cb2, dirs.slice(1));
        }
        __name(ondir, "ondir");
      }
      __name(processDirs, "processDirs");
      function loadNodeModules(x4, start2, cb2) {
        var thunk = /* @__PURE__ */ __name(function() {
          return getPackageCandidates(x4, start2, opts);
        }, "thunk");
        processDirs(
          cb2,
          packageIterator ? packageIterator(x4, start2, 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 fs142 = __require("fs");
    var path150 = __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" && fs142.realpathSync && typeof fs142.realpathSync.native === "function" ? fs142.realpathSync.native : fs142.realpathSync;
    var homedir34 = getHomedir();
    var defaultPaths = /* @__PURE__ */ __name(function() {
      return [
        path150.join(homedir34, ".node_modules"),
        path150.join(homedir34, ".node_libraries")
      ];
    }, "defaultPaths");
    var defaultIsFile = /* @__PURE__ */ __name(function isFile4(file2) {
      try {
        var stat14 = fs142.statSync(file2, { throwIfNoEntry: false });
      } catch (e4) {
        if (e4 && (e4.code === "ENOENT" || e4.code === "ENOTDIR")) return false;
        throw e4;
      }
      return !!stat14 && (stat14.isFile() || stat14.isFIFO());
    }, "isFile");
    var defaultIsDir = /* @__PURE__ */ __name(function isDirectory(dir) {
      try {
        var stat14 = fs142.statSync(dir, { throwIfNoEntry: false });
      } catch (e4) {
        if (e4 && (e4.code === "ENOENT" || e4.code === "ENOTDIR")) return false;
        throw e4;
      }
      return !!stat14 && stat14.isDirectory();
    }, "isDirectory");
    var defaultRealpathSync = /* @__PURE__ */ __name(function realpathSync12(x3) {
      try {
        return realpathFS(x3);
      } catch (realpathErr) {
        if (realpathErr.code !== "ENOENT") {
          throw realpathErr;
        }
      }
      return x3;
    }, "realpathSync");
    var maybeRealpathSync = /* @__PURE__ */ __name(function maybeRealpathSync2(realpathSync12, x3, opts) {
      if (opts && opts.preserveSymlinks === false) {
        return realpathSync12(x3);
      }
      return x3;
    }, "maybeRealpathSync");
    var defaultReadPackageSync = /* @__PURE__ */ __name(function defaultReadPackageSync2(readFileSync36, pkgfile) {
      var body2 = readFileSync36(pkgfile);
      try {
        var pkg2 = JSON.parse(body2);
        return pkg2;
      } catch (jsonErr) {
      }
    }, "defaultReadPackageSync");
    var getPackageCandidates = /* @__PURE__ */ __name(function getPackageCandidates2(x3, start2, opts) {
      var dirs = nodeModulesPaths(start2, opts, x3);
      for (var i4 = 0; i4 < dirs.length; i4++) {
        dirs[i4] = path150.join(dirs[i4], 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 isFile4 = opts.isFile || defaultIsFile;
      var readFileSync36 = opts.readFileSync || fs142.readFileSync;
      var isDirectory = opts.isDirectory || defaultIsDir;
      var realpathSync12 = 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 || path150.dirname(caller());
      var parent = opts.filename || basedir;
      opts.paths = opts.paths || defaultPaths();
      var absoluteStart = maybeRealpathSync(realpathSync12, path150.resolve(basedir), opts);
      if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x3)) {
        var res = path150.resolve(absoluteStart, x3);
        if (x3 === "." || x3 === ".." || x3.slice(-1) === "/") res += "/";
        var m3 = loadAsFileSync(res) || loadAsDirectorySync(res);
        if (m3) return maybeRealpathSync(realpathSync12, m3, opts);
      } else if (includeCoreModules && isCore(x3)) {
        return x3;
      } else {
        var n3 = loadNodeModulesSync(x3, absoluteStart);
        if (n3) return maybeRealpathSync(realpathSync12, n3, opts);
      }
      var err2 = new Error("Cannot find module '" + x3 + "' from '" + parent + "'");
      err2.code = "MODULE_NOT_FOUND";
      throw err2;
      function loadAsFileSync(x4) {
        var pkg2 = loadpkg(path150.dirname(x4));
        if (pkg2 && pkg2.dir && pkg2.pkg && opts.pathFilter) {
          var rfile = path150.relative(pkg2.dir, x4);
          var r5 = opts.pathFilter(pkg2.pkg, x4, rfile);
          if (r5) {
            x4 = path150.resolve(pkg2.dir, r5);
          }
        }
        if (isFile4(x4)) {
          return x4;
        }
        for (var i4 = 0; i4 < extensions.length; i4++) {
          var file2 = x4 + extensions[i4];
          if (isFile4(file2)) {
            return file2;
          }
        }
      }
      __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 = path150.join(maybeRealpathSync(realpathSync12, dir, opts), "package.json");
        if (!isFile4(pkgfile)) {
          return loadpkg(path150.dirname(dir));
        }
        var pkg2 = readPackageSync2(readFileSync36, pkgfile);
        if (pkg2 && opts.packageFilter) {
          pkg2 = opts.packageFilter(
            pkg2,
            /*pkgfile,*/
            dir
          );
        }
        return { pkg: pkg2, dir };
      }
      __name(loadpkg, "loadpkg");
      function loadAsDirectorySync(x4) {
        var pkgfile = path150.join(maybeRealpathSync(realpathSync12, x4, opts), "/package.json");
        if (isFile4(pkgfile)) {
          try {
            var pkg2 = readPackageSync2(readFileSync36, 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(path150.resolve(x4, pkg2.main));
              if (m4) return m4;
              var n4 = loadAsDirectorySync(path150.resolve(x4, pkg2.main));
              if (n4) return n4;
            } catch (e4) {
            }
          }
        }
        return loadAsFileSync(path150.join(x4, "/index"));
      }
      __name(loadAsDirectorySync, "loadAsDirectorySync");
      function loadNodeModulesSync(x4, start2) {
        var thunk = /* @__PURE__ */ __name(function() {
          return getPackageCandidates(x4, start2, opts);
        }, "thunk");
        var dirs = packageIterator ? packageIterator(x4, start2, thunk, opts) : thunk();
        for (var i4 = 0; i4 < dirs.length; i4++) {
          var dir = dirs[i4];
          if (isDirectory(path150.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 path150 = __require("path");
    var Module2 = __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 (Module2.isBuiltin) {
      isCore = Module2.isBuiltin;
    } else if (Module2.builtinModules) {
      isCore = /* @__PURE__ */ __name((moduleName2) => {
        if (moduleName2.startsWith("node:")) {
          return true;
        }
        if (builtinModules === void 0) {
          builtinModules = new Set(Module2.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 resolve42(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 resolve43 = require_resolve3();
          _resolve = /* @__PURE__ */ __name(function(moduleName3, basedir2) {
            return resolve43.sync(moduleName3, { basedir: basedir2 });
          }, "_resolve");
        }
      }
      return _resolve(moduleName2, basedir);
    }
    __name(resolve42, "resolve");
    var normalize13 = /([/\\]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 Module2._resolveFilename !== "function") {
        console.error("Error: Expected Module._resolveFilename to be a function (was: %s) - aborting!", typeof Module2._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 = Module2.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 = Module2.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(args2, coreOnly) {
        const id = args2[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, args2);
        } else {
          try {
            filename = Module2._resolveFilename(id, this);
          } catch (resolveErr) {
            debug3('Module._resolveFilename("%s") threw %j, calling original Module.require', id, resolveErr.message);
            return self2._origRequire.apply(this, args2);
          }
        }
        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, args2) : self2._origRequire.apply(this, args2);
        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 = path150.parse(filename);
          moduleName2 = parsedPath.name;
          basedir = parsedPath.dir;
        } else {
          const stat14 = moduleDetailsFromPath(filename);
          if (stat14 === void 0) {
            debug3("could not parse filename: %s", filename);
            return exports3;
          }
          moduleName2 = stat14.name;
          basedir = stat14.basedir;
          const fullModuleName = resolveModuleName(stat14);
          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 = resolve42(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 + path150.sep + path150.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 === Module2.prototype.require) {
        Module2.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(stat14) {
      const normalizedPath = path150.sep !== "/" ? stat14.path.split(path150.sep).join("/") : stat14.path;
      return path150.posix.join(stat14.name, normalizedPath).replace(normalize13, "");
    }
    __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 path150 = __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, name4, basedir) => {
            const normalizedModuleName = normalizePathSeparators(name4);
            const matches2 = 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 matches2) {
              exports3 = onRequire(exports3, name4, 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 path150.sep !== ModuleNameTrie_1.ModuleNameSeparator ? moduleNameOrPath.split(path150.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 proxyHandler2 = {
      set(target, name4, value) {
        return setters.get(target)[name4](value);
      },
      get(target, name4) {
        if (name4 === Symbol.toStringTag) {
          return "Module";
        }
        const getter = getters.get(target)[name4];
        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(name4, namespace, set2, get4, specifier) {
      specifiers.set(name4, specifier);
      setters.set(namespace, set2);
      getters.set(namespace, get4);
      const proxy2 = new Proxy(namespace, proxyHandler2);
      importHooks.forEach((hook) => hook(name4, proxy2));
      toHook.push([name4, proxy2]);
    }
    __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 path150 = __require("path");
    var parse17 = require_module_details_from_path();
    var { fileURLToPath: fileURLToPath19 } = __require("url");
    var { MessageChannel: MessageChannel2 } = __require("worker_threads");
    var {
      importHooks,
      specifiers,
      toHook,
      getExperimentalPatchInternals
    } = require_register();
    function addHook(hook) {
      importHooks.push(hook);
      toHook.forEach(([name4, namespace]) => hook(name4, 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, name4, baseDir) {
      const newDefault = hookFn(namespace, name4, 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 promise2 = new Promise((resolve42) => {
          resolveFn = resolve42;
        }).then(() => {
          clearInterval(timer);
        });
        if (pendingAckCount === 0) {
          resolveFn();
        }
        return promise2;
      }
      __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 = (name4, namespace) => {
        const filename = name4;
        const isBuiltin = name4.startsWith("node:");
        let baseDir;
        if (isBuiltin) {
          name4 = name4.replace(/^node:/, "");
        } else {
          if (name4.startsWith("file://")) {
            try {
              name4 = fileURLToPath19(name4);
            } catch (e4) {
            }
          }
          const details = parse17(name4);
          if (details) {
            name4 = details.name;
            baseDir = details.basedir;
          }
        }
        if (modules) {
          for (const moduleName2 of modules) {
            if (moduleName2 === name4) {
              if (baseDir) {
                if (internals) {
                  name4 = name4 + path150.sep + path150.relative(baseDir, fileURLToPath19(filename));
                } else {
                  if (!getExperimentalPatchInternals() && !baseDir.endsWith(specifiers.get(filename))) continue;
                }
              }
              callHookFn(hookFn, namespace, name4, baseDir);
            }
          }
        } else {
          callHookFn(hookFn, namespace, name4, baseDir);
        }
      };
      addHook(this._iitmHook);
    }
    __name(Hook, "Hook");
    Hook.prototype.unhook = function() {
      removeHook(this._iitmHook);
    };
    module2.exports = Hook;
    module2.exports.Hook = Hook;
    module2.exports.addHook = addHook;
    module2.exports.removeHook = removeHook;
    module2.exports.createAddHookMessageChannel = createAddHookMessageChannel;
  }
});

// node_modules/@opentelemetry/instrumentation/build/src/utils.js
var require_utils9 = __commonJS({
  "node_modules/@opentelemetry/instrumentation/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isWrapped = exports2.safeExecuteInTheMiddleAsync = exports2.safeExecuteInTheMiddle = void 0;
    function safeExecuteInTheMiddle(execute, onFinish, preventThrowingError) {
      let error40;
      let result;
      try {
        result = execute();
      } catch (e4) {
        error40 = e4;
      } finally {
        onFinish(error40, result);
        if (error40 && !preventThrowingError) {
          throw error40;
        }
        return result;
      }
    }
    __name(safeExecuteInTheMiddle, "safeExecuteInTheMiddle");
    exports2.safeExecuteInTheMiddle = safeExecuteInTheMiddle;
    async function safeExecuteInTheMiddleAsync(execute, onFinish, preventThrowingError) {
      let error40;
      let result;
      try {
        result = await execute();
      } catch (e4) {
        error40 = e4;
      } finally {
        onFinish(error40, result);
        if (error40 && !preventThrowingError) {
          throw error40;
        }
        return result;
      }
    }
    __name(safeExecuteInTheMiddleAsync, "safeExecuteInTheMiddleAsync");
    exports2.safeExecuteInTheMiddleAsync = safeExecuteInTheMiddleAsync;
    function isWrapped(func2) {
      return typeof func2 === "function" && typeof func2.__original === "function" && typeof func2.__unwrap === "function" && func2.__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 path150 = __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_esm(), __toCommonJS(esm_exports));
    var require_in_the_middle_1 = require_require_in_the_middle();
    var fs_1 = __require("fs");
    var utils_1 = require_utils9();
    var InstrumentationBase = class extends instrumentation_1.InstrumentationAbstract {
      static {
        __name(this, "InstrumentationBase");
      }
      _modules;
      _hooks = [];
      _requireInTheMiddleSingleton = RequireInTheMiddleSingleton_1.RequireInTheMiddleSingleton.getInstance();
      _enabled = false;
      constructor(instrumentationName, instrumentationVersion, 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((moduleExports2, name4, wrapper) => {
        if ((0, utils_1.isWrapped)(moduleExports2[name4])) {
          this._unwrap(moduleExports2, name4);
        }
        if (!util_1.types.isProxy(moduleExports2)) {
          return (0, shimmer_1.wrap)(moduleExports2, name4, wrapper);
        } else {
          const wrapped = (0, shimmer_1.wrap)(Object.assign({}, moduleExports2), name4, wrapper);
          Object.defineProperty(moduleExports2, name4, {
            value: wrapped
          });
          return wrapped;
        }
      }, "_wrap");
      _unwrap = /* @__PURE__ */ __name((moduleExports2, name4) => {
        if (!util_1.types.isProxy(moduleExports2)) {
          return (0, shimmer_1.unwrap)(moduleExports2, name4);
        } else {
          return Object.defineProperty(moduleExports2, name4, {
            value: moduleExports2[name4]
          });
        }
      }, "_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((moduleExports2) => {
          names.forEach((name4) => {
            this._wrap(moduleExports2, name4, 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((moduleExports2) => {
          names.forEach((name4) => {
            this._unwrap(moduleExports2, name4);
          });
        });
      }, "_massUnwrap");
      _warnOnPreloadedModules() {
        this._modules.forEach((module3) => {
          const { name: name4 } = module3;
          try {
            const resolvedModule = __require.resolve(name4);
            if (__require.cache[resolvedModule]) {
              this._diag.warn(`Module ${name4} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${name4}`);
            }
          } catch {
          }
        });
      }
      _extractPackageVersion(baseDir) {
        try {
          const json3 = (0, fs_1.readFileSync)(path150.join(baseDir, "package.json"), {
            encoding: "utf8"
          });
          const version2 = JSON.parse(json3).version;
          return typeof version2 === "string" ? version2 : void 0;
        } catch {
          api_1.diag.warn("Failed extracting version", baseDir);
        }
        return void 0;
      }
      _onRequire(module3, exports3, name4, 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 === name4) {
          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 = path150.normalize(name4);
        const supportedFileInstrumentations = files.filter((f5) => f5.name === normalizedName).filter((f5) => isSupported(f5.supportedVersions, version2, module3.includePrerelease));
        return supportedFileInstrumentations.reduce((patchedExports, file2) => {
          file2.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: file2.name,
              baseDir
            });
            return file2.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 file2 of module3.files) {
              if (file2.moduleExports) {
                this._diag.debug("Applying instrumentation patch for nodejs module file on instrumentation enabled", {
                  module: module3.name,
                  version: module3.moduleVersion,
                  fileName: file2.name
                });
                file2.patch(file2.moduleExports, module3.moduleVersion);
              }
            }
          }
          return;
        }
        this._warnOnPreloadedModules();
        for (const module3 of this._modules) {
          const hookFn = /* @__PURE__ */ __name((exports3, name4, baseDir) => {
            if (!baseDir && path150.isAbsolute(name4)) {
              const parsedPath = path150.parse(name4);
              name4 = parsedPath.name;
              baseDir = parsedPath.dir;
            }
            return this._onRequire(module3, exports3, name4, baseDir);
          }, "hookFn");
          const onRequire = /* @__PURE__ */ __name((exports3, name4, baseDir) => {
            return this._onRequire(module3, exports3, name4, baseDir);
          }, "onRequire");
          const hook = path150.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 file2 of module3.files) {
            if (file2.moduleExports) {
              this._diag.debug("Removing instrumentation patch for nodejs module file on instrumentation disabled", {
                module: module3.name,
                version: module3.moduleVersion,
                fileName: file2.name
              });
              file2.unpatch(file2.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_node12 = __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_node12();
    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(name4, supportedVersions, patch, unpatch, files) {
        this.name = name4;
        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(name4, supportedVersions, patch, unpatch) {
        this.supportedVersions = supportedVersions;
        this.patch = patch;
        this.unpatch = unpatch;
        this.name = (0, index_1.normalize)(name4);
      }
    };
    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_utils9();
    Object.defineProperty(exports2, "isWrapped", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.isWrapped;
    }, "get") });
    Object.defineProperty(exports2, "safeExecuteInTheMiddle", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.safeExecuteInTheMiddle;
    }, "get") });
    Object.defineProperty(exports2, "safeExecuteInTheMiddleAsync", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return utils_1.safeExecuteInTheMiddleAsync;
    }, "get") });
    var semconvStability_1 = require_semconvStability();
    Object.defineProperty(exports2, "SemconvStability", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return semconvStability_1.SemconvStability;
    }, "get") });
    Object.defineProperty(exports2, "semconvStabilityFromStr", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return semconvStability_1.semconvStabilityFromStr;
    }, "get") });
  }
});

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

// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js
var require_OTLPLogExporter3 = __commonJS({
  "node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.OTLPLogExporter = void 0;
    var otlp_exporter_base_1 = (init_esm3(), __toCommonJS(esm_exports3));
    var otlp_transformer_1 = require_src15();
    var node_http_1 = (init_index_node_http(), __toCommonJS(index_node_http_exports));
    var version_1 = require_version6();
    var OTLPLogExporter2 = class extends otlp_exporter_base_1.OTLPExporterBase {
      static {
        __name(this, "OTLPLogExporter");
      }
      constructor(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_node13 = __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_node13();
    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_node14 = __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_node14();
    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_esm(), __toCommonJS(esm_exports));
    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(name4) {
      return name4.replace(invalidCharacterRegex, "_").replace(multipleUnderscoreRegex, "_");
    }
    __name(sanitizePrometheusMetricName, "sanitizePrometheusMetricName");
    function enforcePrometheusNamingConvention(name4, data) {
      if (!name4.endsWith("_total") && data.dataPointType === sdk_metrics_1.DataPointType.SUM && data.isMonotonic) {
        name4 = name4 + "_total";
      }
      return name4;
    }
    __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 name4 = sanitizePrometheusMetricName(escapeString(metricData.descriptor.name));
        if (this._prefix) {
          name4 = `${this._prefix}${name4}`;
        }
        const dataPointType = metricData.dataPointType;
        name4 = enforcePrometheusNamingConvention(name4, metricData);
        const help = `# HELP ${name4} ${escapeString(metricData.descriptor.description || "description missing")}`;
        const unit = metricData.descriptor.unit ? `
# UNIT ${name4} ${escapeString(metricData.descriptor.unit)}` : "";
        const type = `# TYPE ${name4} ${toPrometheusType(metricData)}`;
        let results = "";
        switch (dataPointType) {
          case sdk_metrics_1.DataPointType.SUM:
          case sdk_metrics_1.DataPointType.GAUGE: {
            results = metricData.dataPoints.map((it3) => this._serializeSingularDataPoint(name4, metricData, it3)).join("");
            break;
          }
          case sdk_metrics_1.DataPointType.HISTOGRAM: {
            results = metricData.dataPoints.map((it3) => this._serializeHistogramDataPoint(name4, metricData, it3)).join("");
            break;
          }
          default: {
            api_1.diag.error(`Unrecognizable DataPointType: ${dataPointType} for metric "${name4}"`);
          }
        }
        return `${help}${unit}
${type}
${results}`.trim();
      }
      _serializeSingularDataPoint(name4, data, dataPoint) {
        let results = "";
        name4 = enforcePrometheusNamingConvention(name4, data);
        const { value, attributes } = dataPoint;
        const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime);
        results += stringify4(name4, attributes, value, this._appendTimestamp ? timestamp : void 0, this._additionalAttributes);
        return results;
      }
      _serializeHistogramDataPoint(name4, data, dataPoint) {
        let results = "";
        name4 = enforcePrometheusNamingConvention(name4, 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(name4 + "_" + 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(name4 + "_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 name4 = "target_info";
        const help = `# HELP ${name4} Target metadata`;
        const type = `# TYPE ${name4} gauge`;
        const results = stringify4(name4, 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_esm(), __toCommonJS(esm_exports));
    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, (err2) => {
            api_1.diag.error(err2);
            callback(err2);
          });
        } 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((resolve42) => {
            this._server.close((err2) => {
              if (!err2) {
                api_1.diag.debug("Prometheus exporter was stopped");
              } else {
                if (err2.code !== "ERR_SERVER_NOT_RUNNING") {
                  (0, core_1.globalErrorHandler)(err2);
                }
              }
              resolve42();
            });
          });
        }
      }
      /**
       * Starts the Prometheus export server
       */
      startServer() {
        this._startServerPromise ??= new Promise((resolve42, 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}`);
            resolve42();
          });
        });
        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));
        }, (err2) => {
          response.end(`# failed to export metrics: ${err2}`);
        });
      }, "_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_node15 = __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_node15();
    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_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src8();
    var http9 = __require("http");
    var https9 = __require("https");
    function prepareSend(urlStr, headers) {
      const url3 = 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 } = url3.protocol === "http:" ? http9 : https9;
        const req = request4(url3, 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", (error40) => {
          return done({
            code: core_1.ExportResultCode.FAILED,
            error: error40
          });
        });
        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_node16 = __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_node16();
    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_esm(), __toCommonJS(esm_exports));
    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((name4) => tags[name4] = String(resource.attributes[name4]));
      return tags;
    }
    __name(_toZipkinTags, "_toZipkinTags");
    exports2._toZipkinTags = _toZipkinTags;
    function _toZipkinAnnotations(events) {
      return events.map((event) => ({
        timestamp: Math.round((0, core_1.hrTimeToMicroseconds)(event.time)),
        value: event.name
      }));
    }
    __name(_toZipkinAnnotations, "_toZipkinAnnotations");
    exports2._toZipkinAnnotations = _toZipkinAnnotations;
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/utils.js
var require_utils10 = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.prepareGetHeaders = void 0;
    function prepareGetHeaders(getExportRequestHeaders) {
      return function() {
        return getExportRequestHeaders();
      };
    }
    __name(prepareGetHeaders, "prepareGetHeaders");
    exports2.prepareGetHeaders = prepareGetHeaders;
  }
});

// node_modules/@opentelemetry/exporter-zipkin/build/src/zipkin.js
var require_zipkin = __commonJS({
  "node_modules/@opentelemetry/exporter-zipkin/build/src/zipkin.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ZipkinExporter = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src8();
    var index_1 = require_platform14();
    var transform_1 = require_transform();
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var utils_1 = require_utils10();
    var ZipkinExporter = class {
      static {
        __name(this, "ZipkinExporter");
      }
      DEFAULT_SERVICE_NAME = "OpenTelemetry Service";
      _statusCodeTagName;
      _statusDescriptionTagName;
      _urlStr;
      _send;
      _getHeaders;
      _serviceName;
      _isShutdown;
      _sendingPromises = [];
      constructor(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 promise2 = new Promise((resolve42) => {
          this._sendSpans(spans, serviceName, (result) => {
            resolve42();
            resultCallback(result);
          });
        });
        this._sendingPromises.push(promise2);
        const popPromise = /* @__PURE__ */ __name(() => {
          const index = this._sendingPromises.indexOf(promise2);
          this._sendingPromises.splice(index, 1);
        }, "popPromise");
        promise2.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((resolve42, reject) => {
          Promise.all(this._sendingPromises).then(() => {
            resolve42();
          }, 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_esm(), __toCommonJS(esm_exports));
    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_esm(), __toCommonJS(esm_exports));
    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_esm(), __toCommonJS(esm_exports));
    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_esm(), __toCommonJS(esm_exports));
    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, , flags2] = headers;
      const traceId = _traceId.padStart(32, "0");
      const spanId = _spanId.padStart(16, "0");
      const traceFlags = VALID_HEX_RE.test(flags2) ? parseInt(flags2, 16) & 1 : 1;
      return { traceId, spanId, isRemote: true, traceFlags };
    }
    __name(deserializeSpanContext, "deserializeSpanContext");
  }
});

// node_modules/@opentelemetry/propagator-jaeger/build/src/index.js
var require_src33 = __commonJS({
  "node_modules/@opentelemetry/propagator-jaeger/build/src/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.UBER_TRACE_ID_HEADER = exports2.UBER_BAGGAGE_HEADER_PREFIX = exports2.JaegerPropagator = void 0;
    var JaegerPropagator_1 = require_JaegerPropagator();
    Object.defineProperty(exports2, "JaegerPropagator", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return JaegerPropagator_1.JaegerPropagator;
    }, "get") });
    Object.defineProperty(exports2, "UBER_BAGGAGE_HEADER_PREFIX", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return JaegerPropagator_1.UBER_BAGGAGE_HEADER_PREFIX;
    }, "get") });
    Object.defineProperty(exports2, "UBER_TRACE_ID_HEADER", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return JaegerPropagator_1.UBER_TRACE_ID_HEADER;
    }, "get") });
  }
});

// node_modules/@opentelemetry/sdk-node/build/src/utils.js
var require_utils11 = __commonJS({
  "node_modules/@opentelemetry/sdk-node/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getPropagatorFromEnv = exports2.getSpanProcessorsFromEnv = exports2.getOtlpProtocolFromEnv = exports2.filterBlanksAndNulls = exports2.getResourceDetectorsFromEnv = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    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 name4 of traceExportersList) {
        const exporter = exportersMap.get(name4)?.();
        if (exporter) {
          exporters.push(exporter);
        } else {
          api_1.diag.warn(`Unrecognized OTEL_TRACES_EXPORTER value: ${name4}.`);
        }
      }
      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((name4) => {
        const propagator = propagatorsFactory.get(name4)?.();
        if (!propagator) {
          api_1.diag.warn(`Propagator "${name4}" 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_esm(), __toCommonJS(esm_exports));
    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_esm2(), __toCommonJS(esm_exports2));
    var core_1 = require_src8();
    var utils_1 = require_utils11();
    function getValueInMillis(envName, defaultValue) {
      return parseInt(process.env[envName] || "") || defaultValue;
    }
    __name(getValueInMillis, "getValueInMillis");
    function configureMetricProviderFromEnv() {
      const metricReaders = [];
      const enabledExporters = (0, core_1.getStringListFromEnv)("OTEL_METRICS_EXPORTER");
      if (!enabledExporters) {
        return metricReaders;
      }
      if (enabledExporters.length === 0) {
        api_1.diag.debug("OTEL_METRICS_EXPORTER is empty. Using default otlp exporter.");
      }
      if (enabledExporters.includes("none")) {
        api_1.diag.info(`OTEL_METRICS_EXPORTER contains "none". Metric provider will not be initialized.`);
        return metricReaders;
      }
      enabledExporters.forEach((exporter) => {
        if (exporter === "otlp") {
          const protocol = process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?.trim() || process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim();
          const exportIntervalMillis = getValueInMillis("OTEL_METRIC_EXPORT_INTERVAL", 6e4);
          const exportTimeoutMillis = getValueInMillis("OTEL_METRIC_EXPORT_TIMEOUT", 3e4);
          switch (protocol) {
            case "grpc":
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_grpc_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
              break;
            case "http/json":
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_http_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
              break;
            case "http/protobuf":
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_proto_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
              break;
            default:
              api_1.diag.warn(`Unsupported OTLP metrics protocol: "${protocol}". Using http/protobuf.`);
              metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
                exporter: new exporter_metrics_otlp_proto_1.OTLPMetricExporter(),
                exportIntervalMillis,
                exportTimeoutMillis
              }));
          }
        } else if (exporter === "console") {
          metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({
            exporter: new sdk_metrics_1.ConsoleMetricExporter()
          }));
        } else if (exporter === "prometheus") {
          metricReaders.push(new exporter_prometheus_1.PrometheusExporter());
        } else {
          api_1.diag.warn(`Unsupported OTEL_METRICS_EXPORTER value: "${exporter}". Supported values are: otlp, console, prometheus, none.`);
        }
      });
      return metricReaders;
    }
    __name(configureMetricProviderFromEnv, "configureMetricProviderFromEnv");
    var NodeSDK2 = class {
      static {
        __name(this, "NodeSDK");
      }
      _tracerProviderConfig;
      _loggerProviderConfig;
      _meterProviderConfig;
      _instrumentations;
      _resource;
      _resourceDetectors;
      _autoDetectResources;
      _tracerProvider;
      _loggerProvider;
      _meterProvider;
      _serviceName;
      _configuration;
      _disabled;
      /**
       * Create a new NodeJS SDK instance
       */
      constructor(configuration = {}) {
        if ((0, core_1.getBooleanFromEnv)("OTEL_SDK_DISABLED")) {
          this._disabled = true;
        }
        const logLevel = (0, core_1.getStringFromEnv)("OTEL_LOG_LEVEL");
        if (logLevel != null) {
          api_1.diag.setLogger(new api_1.DiagConsoleLogger(), {
            logLevel: (0, core_1.diagLogLevelFromString)(logLevel)
          });
        }
        this._configuration = configuration;
        this._resource = configuration.resource ?? (0, resources_1.defaultResource)();
        this._autoDetectResources = configuration.autoDetectResources ?? true;
        if (!this._autoDetectResources) {
          this._resourceDetectors = [];
        } else if (configuration.resourceDetectors != null) {
          this._resourceDetectors = configuration.resourceDetectors;
        } else if ((0, core_1.getStringFromEnv)("OTEL_NODE_RESOURCE_DETECTORS")) {
          this._resourceDetectors = (0, utils_1.getResourceDetectorsFromEnv)();
        } else {
          this._resourceDetectors = [resources_1.envDetector, resources_1.processDetector, resources_1.hostDetector];
        }
        this._serviceName = configuration.serviceName;
        if (configuration.traceExporter || configuration.spanProcessor || configuration.spanProcessors) {
          const tracerProviderConfig = {};
          if (configuration.sampler) {
            tracerProviderConfig.sampler = configuration.sampler;
          }
          if (configuration.spanLimits) {
            tracerProviderConfig.spanLimits = configuration.spanLimits;
          }
          if (configuration.idGenerator) {
            tracerProviderConfig.idGenerator = configuration.idGenerator;
          }
          if (configuration.spanProcessor) {
            api_1.diag.warn("The 'spanProcessor' option is deprecated. Please use 'spanProcessors' instead.");
          }
          const spanProcessor = configuration.spanProcessor ?? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
          new sdk_trace_base_1.BatchSpanProcessor(configuration.traceExporter);
          const spanProcessors = configuration.spanProcessors ?? [spanProcessor];
          this._tracerProviderConfig = {
            tracerConfig: tracerProviderConfig,
            spanProcessors,
            contextManager: configuration.contextManager,
            textMapPropagator: configuration.textMapPropagator
          };
        }
        if (configuration.logRecordProcessors) {
          this._loggerProviderConfig = {
            logRecordProcessors: configuration.logRecordProcessors
          };
        } else if (configuration.logRecordProcessor) {
          this._loggerProviderConfig = {
            logRecordProcessors: [configuration.logRecordProcessor]
          };
          api_1.diag.warn("The 'logRecordProcessor' option is deprecated. Please use 'logRecordProcessors' instead.");
        } else {
          this.configureLoggerProviderFromEnv();
        }
        if (configuration.metricReader || configuration.views) {
          const meterProviderConfig = {};
          if (configuration.metricReader) {
            meterProviderConfig.reader = configuration.metricReader;
          }
          if (configuration.views) {
            meterProviderConfig.views = configuration.views;
          }
          this._meterProviderConfig = meterProviderConfig;
        }
        this._instrumentations = configuration.instrumentations?.flat() ?? [];
      }
      /**
       * Call this method to construct SDK components and register them with the OpenTelemetry API.
       */
      start() {
        if (this._disabled) {
          return;
        }
        (0, instrumentation_1.registerInstrumentations)({
          instrumentations: this._instrumentations
        });
        if (this._autoDetectResources) {
          const internalConfig = {
            detectors: this._resourceDetectors
          };
          this._resource = this._resource.merge((0, resources_1.detectResources)(internalConfig));
        }
        this._resource = this._serviceName === void 0 ? this._resource : this._resource.merge((0, resources_1.resourceFromAttributes)({
          [semantic_conventions_1.ATTR_SERVICE_NAME]: this._serviceName
        }));
        const spanProcessors = this._tracerProviderConfig ? this._tracerProviderConfig.spanProcessors : (0, utils_1.getSpanProcessorsFromEnv)();
        this._tracerProvider = new sdk_trace_node_1.NodeTracerProvider({
          ...this._configuration,
          resource: this._resource,
          spanProcessors
        });
        if (spanProcessors.length > 0) {
          this._tracerProvider.register({
            contextManager: this._tracerProviderConfig?.contextManager ?? // _tracerProviderConfig may be undefined if trace-specific settings are not provided - fall back to raw config
            this._configuration?.contextManager,
            propagator: this._tracerProviderConfig?.textMapPropagator ?? (0, utils_1.getPropagatorFromEnv)()
          });
        }
        if (this._loggerProviderConfig) {
          const loggerProvider = new sdk_logs_1.LoggerProvider({
            resource: this._resource,
            processors: this._loggerProviderConfig.logRecordProcessors
          });
          this._loggerProvider = loggerProvider;
          api_logs_1.logs.setGlobalLoggerProvider(loggerProvider);
        }
        const metricReadersFromEnv = configureMetricProviderFromEnv();
        if (this._meterProviderConfig || metricReadersFromEnv.length > 0) {
          const readers = [];
          if (this._meterProviderConfig?.reader) {
            readers.push(this._meterProviderConfig.reader);
          }
          if (readers.length === 0) {
            metricReadersFromEnv.forEach((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 promises9 = [];
        if (this._tracerProvider) {
          promises9.push(this._tracerProvider.shutdown());
        }
        if (this._loggerProvider) {
          promises9.push(this._loggerProvider.shutdown());
        }
        if (this._meterProvider) {
          promises9.push(this._meterProvider.shutdown());
        }
        return Promise.all(promises9).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_esm(), __toCommonJS(esm_exports));
    exports2.contextBase = (init_esm(), __toCommonJS(esm_exports));
    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 util5 = __require("util");
    function ParseError2(message, input) {
      Error.captureStackTrace(this, ParseError2);
      this.name = this.constructor.name;
      this.message = message;
      this.input = input;
    }
    __name(ParseError2, "ParseError");
    util5.inherits(ParseError2, Error);
    module2.exports = ParseError2;
  }
});

// node_modules/forwarded-parse/lib/ascii.js
var require_ascii2 = __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 util5 = __require("util");
    var ParseError2 = require_error2();
    var ascii = require_ascii2();
    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 util5.format(
        "Unexpected character '%s' at index %d",
        header.charAt(position),
        position
      );
    }
    __name(unexpectedCharacterMessage, "unexpectedCharacterMessage");
    function parse17(header) {
      var mustUnescape = false;
      var isEscaping = false;
      var inQuotes = false;
      var forwarded = {};
      var output = [];
      var start2 = -1;
      var end = -1;
      var parameter;
      var code2;
      for (var i4 = 0; i4 < header.length; i4++) {
        code2 = header.charCodeAt(i4);
        if (parameter === void 0) {
          if (i4 !== 0 && start2 === -1 && (code2 === 32 || code2 === 9)) {
            continue;
          }
          if (isTokenChar(code2)) {
            if (start2 === -1) start2 = i4;
          } else if (code2 === 61 && start2 !== -1) {
            parameter = header.slice(start2, i4).toLowerCase();
            start2 = -1;
          } else {
            throw new ParseError2(unexpectedCharacterMessage(header, i4), header);
          }
        } else {
          if (isEscaping && (code2 === 9 || isPrint(code2) || isExtended(code2))) {
            isEscaping = false;
          } else if (isTokenChar(code2)) {
            if (end !== -1) {
              throw new ParseError2(unexpectedCharacterMessage(header, i4), header);
            }
            if (start2 === -1) start2 = i4;
          } else if (isDelimiter2(code2) || isExtended(code2)) {
            if (inQuotes) {
              if (code2 === 34) {
                inQuotes = false;
                end = i4;
              } else if (code2 === 92) {
                if (start2 === -1) start2 = i4;
                isEscaping = mustUnescape = true;
              } else if (start2 === -1) {
                start2 = i4;
              }
            } else if (code2 === 34 && header.charCodeAt(i4 - 1) === 61) {
              inQuotes = true;
            } else if ((code2 === 44 || code2 === 59) && (start2 !== -1 || end !== -1)) {
              if (start2 !== -1) {
                if (end === -1) end = i4;
                forwarded[parameter] = mustUnescape ? decode2(header.slice(start2, end)) : header.slice(start2, end);
              } else {
                forwarded[parameter] = "";
              }
              if (code2 === 44) {
                output.push(forwarded);
                forwarded = {};
              }
              parameter = void 0;
              start2 = end = -1;
            } else {
              throw new ParseError2(unexpectedCharacterMessage(header, i4), header);
            }
          } else if (code2 === 32 || code2 === 9) {
            if (end !== -1) continue;
            if (inQuotes) {
              if (start2 === -1) start2 = i4;
            } else if (start2 !== -1) {
              end = i4;
            } else {
              throw new ParseError2(unexpectedCharacterMessage(header, i4), header);
            }
          } else {
            throw new ParseError2(unexpectedCharacterMessage(header, i4), header);
          }
        }
      }
      if (parameter === void 0 || inQuotes || start2 === -1 && end === -1 || code2 === 32 || code2 === 9) {
        throw new ParseError2("Unexpected end of input", header);
      }
      if (start2 !== -1) {
        if (end === -1) end = i4;
        forwarded[parameter] = mustUnescape ? decode2(header.slice(start2, end)) : header.slice(start2, end);
      } else {
        forwarded[parameter] = "";
      }
      output.push(forwarded);
      return output;
    }
    __name(parse17, "parse");
    module2.exports = parse17;
  }
});

// node_modules/@opentelemetry/instrumentation-http/build/src/utils.js
var require_utils12 = __commonJS({
  "node_modules/@opentelemetry/instrumentation-http/build/src/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.headerCapture = exports2.getIncomingStableRequestMetricAttributesOnResponse = exports2.getIncomingRequestMetricAttributesOnResponse = exports2.getIncomingRequestAttributesOnResponse = exports2.getIncomingRequestMetricAttributes = exports2.getIncomingRequestAttributes = exports2.getRemoteClientAddress = exports2.getOutgoingStableRequestMetricAttributesOnResponse = exports2.getOutgoingRequestMetricAttributesOnResponse = exports2.getOutgoingRequestAttributesOnResponse = exports2.setAttributesFromHttpKind = exports2.getOutgoingRequestMetricAttributes = exports2.getOutgoingRequestAttributes = exports2.extractHostnameAndPort = exports2.isValidOptionsType = exports2.getRequestInfo = exports2.isCompressed = exports2.setResponseContentLengthAttribute = exports2.setRequestContentLengthAttribute = exports2.setSpanWithError = exports2.satisfiesPattern = exports2.parseResponseStatus = exports2.getAbsoluteUrl = void 0;
    var api_1 = (init_esm(), __toCommonJS(esm_exports));
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var semconv_1 = require_semconv3();
    var core_1 = require_src8();
    var instrumentation_1 = require_src26();
    var url3 = __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 path150 = 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}${path150}`;
    }, "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, error40, semconvStability) => {
      const message = error40.message;
      if (semconvStability & instrumentation_1.SemconvStability.OLD) {
        span.setAttribute(AttributeNames_1.AttributeNames.HTTP_ERROR_NAME, error40.name);
        span.setAttribute(AttributeNames_1.AttributeNames.HTTP_ERROR_MESSAGE, message);
      }
      if (semconvStability & instrumentation_1.SemconvStability.STABLE) {
        span.setAttribute(semantic_conventions_1.ATTR_ERROR_TYPE, error40.name);
      }
      span.setStatus({ code: api_1.SpanStatusCode.ERROR, message });
      span.recordException(error40);
    }, "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: origin2, host } = new URL(stringUrl);
      const options2 = {
        protocol,
        hostname: hostname4 && hostname4[0] === "[" ? hostname4.slice(1, -1) : hostname4,
        hash,
        search,
        pathname,
        path: `${pathname || ""}${search || ""}`,
        href,
        origin: origin2,
        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 origin2;
      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 || "/";
        }
        origin2 = `${optionsParsed.protocol || "http:"}//${optionsParsed.host}`;
        if (extraOptions !== void 0) {
          Object.assign(optionsParsed, extraOptions);
        }
      } else if (options2 instanceof url3.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;
        origin2 = 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);
        origin2 = `${optionsParsed.protocol || "http:"}//${hostname4}`;
        pathname = options2.pathname;
        if (!pathname && optionsParsed.path) {
          try {
            const parsedUrl = new URL(optionsParsed.path, origin2);
            pathname = parsedUrl.pathname || "/";
          } catch {
            pathname = "/";
          }
        }
      }
      const method = optionsParsed.method ? optionsParsed.method.toUpperCase() : "GET";
      return { origin: origin2, 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 matches2 = requestOptions.host?.match(/^([^:/ ]+)(:\d{1,5})?/) || null;
      const hostname4 = requestOptions.hostname || (matches2 === null ? "localhost" : matches2[1]);
      let port = requestOptions.port;
      if (!port) {
        if (matches2 && matches2[2]) {
          port = matches2[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 name4 of internal_types_1.SYNTHETIC_TEST_NAMES) {
        if (userAgentString.includes(name4)) {
          return semconv_1.USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST;
        }
      }
      for (const name4 of internal_types_1.SYNTHETIC_BOT_NAMES) {
        if (userAgentString.includes(name4)) {
          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 parts2 = hostHeader.split(":");
      if (parts2.length === 1) {
        if (proto3 === "http") {
          return { host: parts2[0], port: "80" };
        }
        if (proto3 === "https") {
          return { host: parts2[0], port: "443" };
        }
        return { host: parts2[0] };
      }
      if (parts2.length === 2) {
        return {
          host: parts2[0],
          port: parts2[1]
        };
      }
      if (parts2[0].startsWith("[")) {
        if (parts2[parts2.length - 1].endsWith("]")) {
          if (proto3 === "http") {
            return { host: hostHeader, port: "80" };
          }
          if (proto3 === "https") {
            return { host: hostHeader, port: "443" };
          }
        } else if (parts2[parts2.length - 2].endsWith("]")) {
          return {
            host: parts2.slice(0, -1).join(":"),
            port: parts2[parts2.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 i4 = 0, len = headers.length; i4 < len; i4++) {
        const capturedHeader = headers[i4].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_esm(), __toCommonJS(esm_exports));
    var core_1 = require_src8();
    var url3 = __require("url");
    var version_1 = require_version9();
    var instrumentation_1 = require_src26();
    var events_1 = __require("events");
    var semantic_conventions_1 = (init_esm2(), __toCommonJS(esm_exports2));
    var utils_1 = require_utils12();
    var HttpInstrumentation2 = class extends instrumentation_1.InstrumentationBase {
      static {
        __name(this, "HttpInstrumentation");
      }
      /** keep track on spans not ended */
      _spanNotEnded = /* @__PURE__ */ new WeakSet();
      _headerCapture;
      _semconvStability = instrumentation_1.SemconvStability.OLD;
      constructor(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", ["*"], (moduleExports2) => {
          const isESM = moduleExports2[Symbol.toStringTag] === "Module";
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            const patchedRequest = this._wrap(moduleExports2, "request", this._getPatchOutgoingRequestFunction("http"));
            const patchedGet = this._wrap(moduleExports2, "get", this._getPatchOutgoingGetFunction(patchedRequest));
            if (isESM) {
              moduleExports2.default.request = patchedRequest;
              moduleExports2.default.get = patchedGet;
            }
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._wrap(moduleExports2.Server.prototype, "emit", this._getPatchIncomingRequestFunction("http"));
          }
          return moduleExports2;
        }, (moduleExports2) => {
          if (moduleExports2 === void 0)
            return;
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            this._unwrap(moduleExports2, "request");
            this._unwrap(moduleExports2, "get");
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._unwrap(moduleExports2.Server.prototype, "emit");
          }
        });
      }
      _getHttpsInstrumentation() {
        return new instrumentation_1.InstrumentationNodeModuleDefinition("https", ["*"], (moduleExports2) => {
          const isESM = moduleExports2[Symbol.toStringTag] === "Module";
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            const patchedRequest = this._wrap(moduleExports2, "request", this._getPatchHttpsOutgoingRequestFunction("https"));
            const patchedGet = this._wrap(moduleExports2, "get", this._getPatchHttpsOutgoingGetFunction(patchedRequest));
            if (isESM) {
              moduleExports2.default.request = patchedRequest;
              moduleExports2.default.get = patchedGet;
            }
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._wrap(moduleExports2.Server.prototype, "emit", this._getPatchIncomingRequestFunction("https"));
          }
          return moduleExports2;
        }, (moduleExports2) => {
          if (moduleExports2 === void 0)
            return;
          if (!this.getConfig().disableOutgoingRequestInstrumentation) {
            this._unwrap(moduleExports2, "request");
            this._unwrap(moduleExports2, "get");
          }
          if (!this.getConfig().disableIncomingRequestInstrumentation) {
            this._unwrap(moduleExports2.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, ...args2) {
            const req = clientRequest(options2, ...args2);
            req.end();
            return req;
          }, "outgoingGetRequest");
        };
      }
      /** Patches HTTPS outgoing requests */
      _getPatchHttpsOutgoingRequestFunction(component) {
        return (original) => {
          const instrumentation = this;
          return /* @__PURE__ */ __name(function httpsOutgoingRequest(options2, ...args2) {
            if (component === "https" && typeof options2 === "object" && options2?.constructor?.name !== "URL") {
              options2 = Object.assign({}, options2);
              instrumentation._setDefaultOptions(options2);
            }
            return instrumentation._getPatchOutgoingRequestFunction(component)(original)(options2, ...args2);
          }, "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, ...args2) {
            return instrumentation._getPatchOutgoingGetFunction(clientRequest)(original)(options2, ...args2);
          }, "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, (error40) => {
            this._diag.debug("outgoingRequest on error()", error40);
            if (responseFinished) {
              return;
            }
            responseFinished = true;
            (0, utils_1.setSpanWithError)(span, error40, this._semconvStability);
            span.setStatus({
              code: api_1.SpanStatusCode.ERROR,
              message: error40.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, (error40) => {
          this._diag.debug("outgoingRequest on request error()", error40);
          if (responseFinished) {
            return;
          }
          responseFinished = true;
          (0, utils_1.setSpanWithError)(span, error40, 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, ...args2) {
          if (event !== "request") {
            return original.apply(this, [event, ...args2]);
          }
          const request4 = args2[0];
          const response = args2[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, ...args2]);
            });
          }
          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, (err2) => {
              hasError = true;
              instrumentation._onServerResponseError(span, oldMetricAttributes, stableMetricAttributes, startTime, err2);
            });
            return (0, instrumentation_1.safeExecuteInTheMiddle)(() => original.apply(this, [event, ...args2]), (error40) => {
              if (error40) {
                (0, utils_1.setSpanWithError)(span, error40, instrumentation._semconvStability);
                instrumentation._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes);
                throw error40;
              }
            });
          });
        }, "incomingRequest");
      }
      _outgoingRequestFunction(component, original) {
        const instrumentation = this;
        return /* @__PURE__ */ __name(function outgoingRequest(options2, ...args2) {
          if (!(0, utils_1.isValidOptionsType)(options2)) {
            return original.apply(this, [options2, ...args2]);
          }
          const extraOptions = typeof args2[0] === "object" && (typeof options2 === "string" || options2 instanceof url3.URL) ? args2.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, ...args2]);
          }
          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 = args2[args2.length - 1];
            if (typeof cb === "function") {
              args2[args2.length - 1] = api_1.context.bind(parentContext, cb);
            }
            const request4 = (0, instrumentation_1.safeExecuteInTheMiddle)(() => {
              if (invalidUrl) {
                return original.apply(this, [options2, ...args2]);
              } else {
                return original.apply(this, [optionsParsed, ...args2]);
              }
            }, (error40) => {
              if (error40) {
                (0, utils_1.setSpanWithError)(span, error40, instrumentation._semconvStability);
                instrumentation._closeHttpSpan(span, api_1.SpanKind.CLIENT, startTime, oldMetricAttributes, stableMetricAttributes);
                throw error40;
              }
            });
            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, error40) {
        (0, utils_1.setSpanWithError)(span, error40, this._semconvStability);
        this._closeHttpSpan(span, api_1.SpanKind.SERVER, startTime, oldMetricAttributes, stableMetricAttributes);
      }
      _startHttpSpan(name4, 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(name4, 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 fs15 from "node:fs";
var import_core3, import_sdk_metrics, FileExporter, FileSpanExporter, FileLogExporter, FileMetricExporter;
var init_file_exporters = __esm({
  "packages/core/dist/src/telemetry/file-exporters.js"() {
    "use strict";
    init_esbuild_shims();
    import_core3 = __toESM(require_src8(), 1);
    import_sdk_metrics = __toESM(require_src14(), 1);
    init_safeJsonStringify();
    FileExporter = class {
      static {
        __name(this, "FileExporter");
      }
      writeStream;
      constructor(filePath) {
        this.writeStream = fs15.createWriteStream(filePath, { flags: "a" });
      }
      serialize(data) {
        return safeJsonStringify(data, 2) + "\n";
      }
      shutdown() {
        return new Promise((resolve42) => {
          this.writeStream.end(resolve42);
        });
      }
    };
    FileSpanExporter = class extends FileExporter {
      static {
        __name(this, "FileSpanExporter");
      }
      export(spans, resultCallback) {
        const data = spans.map((span) => this.serialize(span)).join("");
        this.writeStream.write(data, (err2) => {
          resultCallback({
            code: err2 ? import_core3.ExportResultCode.FAILED : import_core3.ExportResultCode.SUCCESS,
            error: err2 || 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, (err2) => {
          resultCallback({
            code: err2 ? import_core3.ExportResultCode.FAILED : import_core3.ExportResultCode.SUCCESS,
            error: err2 || void 0
          });
        });
      }
    };
    FileMetricExporter = class extends FileExporter {
      static {
        __name(this, "FileMetricExporter");
      }
      export(metrics2, resultCallback) {
        const data = this.serialize(metrics2);
        this.writeStream.write(data, (err2) => {
          resultCallback({
            code: err2 ? import_core3.ExportResultCode.FAILED : import_core3.ExportResultCode.SUCCESS,
            error: err2 || 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 url3 = new URL(trimmedEndpoint);
    if (protocol === "grpc") {
      return url3.origin;
    }
    return url3.href;
  } catch (error40) {
    diag2.error("Invalid OTLP endpoint URL provided:", trimmedEndpoint, error40);
    return void 0;
  }
}
function initializeTelemetry(config2) {
  if (telemetryInitialized || !config2.getTelemetryEnabled()) {
    return;
  }
  const debugLogger174 = 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();
    debugLogger174.debug("OpenTelemetry SDK started successfully.");
    telemetryInitialized = true;
    initializeMetrics(config2);
  } catch (error40) {
    debugLogger174.error("Error starting OpenTelemetry SDK:", error40);
  }
  process.on("SIGTERM", () => {
    shutdownTelemetry();
  });
  process.on("SIGINT", () => {
    shutdownTelemetry();
  });
  process.on("exit", () => {
    shutdownTelemetry();
  });
}
async function shutdownTelemetry() {
  if (!telemetryInitialized || !sdk) {
    return;
  }
  const debugLogger174 = createDebugLogger("OTEL");
  try {
    await sdk.shutdown();
    debugLogger174.debug("OpenTelemetry SDK shut down successfully.");
  } catch (error40) {
    debugLogger174.error("Error shutting down SDK:", error40);
  } 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_esm();
    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_esm2();
    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/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,
    sandbox_enabled: event.sandbox_enabled,
    core_tools_enabled: event.core_tools_enabled,
    approval_mode: event.approval_mode,
    file_filtering_respect_git_ignore: event.file_filtering_respect_git_ignore,
    debug_mode: event.debug_enabled,
    truncate_tool_output_threshold: event.truncate_tool_output_threshold,
    truncate_tool_output_lines: event.truncate_tool_output_lines,
    mcp_servers: event.mcp_servers,
    mcp_servers_count: event.mcp_servers_count,
    mcp_tools: event.mcp_tools,
    mcp_tools_count: event.mcp_tools_count,
    hooks: event.hooks,
    ide_enabled: event.ide_enabled,
    interactive_shell_enabled: event.interactive_shell_enabled,
    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 logUserRetry(config2, event) {
  QwenLogger.getInstance(config2)?.logRetryEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    "event.name": EVENT_USER_RETRY,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    prompt_id: event.prompt_id
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `User retry.`,
    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);
  if (!isInternalPromptId(event.prompt_id)) {
    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 logFlashFallback(config2, event) {
  QwenLogger.getInstance(config2)?.logFlashFallbackEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...event,
    "event.name": EVENT_FLASH_FALLBACK,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Switching to flash as Fallback.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logRipgrepFallback(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);
  if (!isInternalPromptId(event.prompt_id)) {
    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_message,
    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_message}. 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);
  if (!isInternalPromptId(event.prompt_id)) {
    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"
  });
}
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 logHookCall(config2, event) {
  QwenLogger.getInstance(config2)?.logHookCallEvent(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);
}
function logArenaSessionStarted(config2, event) {
  QwenLogger.getInstance(config2)?.logArenaSessionStartedEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...event,
    model_ids: JSON.stringify(event.model_ids),
    "event.name": EVENT_ARENA_SESSION_STARTED,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Arena session started. Agents: ${event.model_ids.length}.`,
    attributes
  };
  logger6.emit(logRecord);
  recordArenaSessionStartedMetrics(config2);
}
function logArenaAgentCompleted(config2, event) {
  QwenLogger.getInstance(config2)?.logArenaAgentCompletedEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...event,
    "event.name": EVENT_ARENA_AGENT_COMPLETED,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Arena agent ${event.agent_model_id} ${event.status}. Duration: ${event.duration_ms}ms. Tokens: ${event.total_tokens}.`,
    attributes
  };
  logger6.emit(logRecord);
  recordArenaAgentCompletedMetrics(config2, event.agent_model_id, event.status, event.duration_ms, event.input_tokens, event.output_tokens);
}
function logArenaSessionEnded(config2, event) {
  QwenLogger.getInstance(config2)?.logArenaSessionEndedEvent(event);
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    ...event,
    "event.name": EVENT_ARENA_SESSION_ENDED,
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Arena session ended: ${event.status}.${event.winner_model_id ? ` Winner: ${event.winner_model_id}.` : ""}`,
    attributes
  };
  logger6.emit(logRecord);
  recordArenaSessionEndedMetrics(config2, event.status, event.display_backend, event.duration_ms, event.winner_model_id);
}
function logPromptSuggestion(config2, event) {
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    "event.name": EVENT_PROMPT_SUGGESTION,
    "event.timestamp": event["event.timestamp"],
    outcome: event.outcome
  };
  if (event.prompt_id) {
    attributes["prompt_id"] = event.prompt_id;
  }
  if (event.accept_method) {
    attributes["accept_method"] = event.accept_method;
  }
  if (event.time_to_accept_ms !== void 0) {
    attributes["time_to_accept_ms"] = event.time_to_accept_ms;
  }
  if (event.time_to_ignore_ms !== void 0) {
    attributes["time_to_ignore_ms"] = event.time_to_ignore_ms;
  }
  if (event.time_to_first_keystroke_ms !== void 0) {
    attributes["time_to_first_keystroke_ms"] = event.time_to_first_keystroke_ms;
  }
  if (event.suggestion_length !== void 0) {
    attributes["suggestion_length"] = event.suggestion_length;
  }
  if (event.similarity !== void 0) {
    attributes["similarity"] = event.similarity;
  }
  if (event.was_focused_when_shown !== void 0) {
    attributes["was_focused_when_shown"] = event.was_focused_when_shown;
  }
  if (event.reason) {
    attributes["reason"] = event.reason;
  }
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Prompt suggestion: ${event.outcome}.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logSpeculation(config2, event) {
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    "event.name": EVENT_SPECULATION,
    "event.timestamp": event["event.timestamp"],
    outcome: event.outcome,
    turns_used: event.turns_used,
    files_written: event.files_written,
    tool_use_count: event.tool_use_count,
    duration_ms: event.duration_ms,
    had_pipelined_suggestion: event.had_pipelined_suggestion
  };
  if (event.boundary_type) {
    attributes["boundary_type"] = event.boundary_type;
  }
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  const logRecord = {
    body: `Speculation: ${event.outcome}.`,
    attributes
  };
  logger6.emit(logRecord);
}
function logMemoryExtract(config2, event) {
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    "event.name": EVENT_MEMORY_EXTRACT,
    "event.timestamp": event["event.timestamp"],
    trigger: event.trigger,
    status: event.status,
    patches_count: event.patches_count,
    touched_topics: event.touched_topics,
    duration_ms: event.duration_ms
  };
  if (event.skipped_reason) {
    attributes["skipped_reason"] = event.skipped_reason;
  }
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  logger6.emit({
    body: `Memory extract: ${event.status}. Patches: ${event.patches_count}. Topics: ${event.touched_topics || "none"}.`,
    attributes
  });
  recordMemoryExtractMetrics(config2, event.duration_ms, {
    trigger: event.trigger,
    status: event.status,
    patches_count: event.patches_count
  });
}
function logMemoryDream(config2, event) {
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    "event.name": EVENT_MEMORY_DREAM,
    "event.timestamp": event["event.timestamp"],
    trigger: event.trigger,
    status: event.status,
    deduped_entries: event.deduped_entries,
    touched_topics_count: event.touched_topics_count,
    touched_topics: event.touched_topics,
    duration_ms: event.duration_ms
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  logger6.emit({
    body: `Memory dream: ${event.status}. Deduped: ${event.deduped_entries}. Topics: ${event.touched_topics || "none"}.`,
    attributes
  });
  recordMemoryDreamMetrics(config2, event.duration_ms, {
    trigger: event.trigger,
    status: event.status,
    deduped_entries: event.deduped_entries
  });
}
function logMemoryRecall(config2, event) {
  if (!isTelemetrySdkInitialized())
    return;
  const attributes = {
    ...getCommonAttributes(config2),
    "event.name": EVENT_MEMORY_RECALL,
    "event.timestamp": event["event.timestamp"],
    query_length: event.query_length,
    docs_scanned: event.docs_scanned,
    docs_selected: event.docs_selected,
    strategy: event.strategy,
    duration_ms: event.duration_ms
  };
  const logger6 = import_api_logs.logs.getLogger(SERVICE_NAME);
  logger6.emit({
    body: `Memory recall: strategy=${event.strategy}. Selected ${event.docs_selected}/${event.docs_scanned} docs.`,
    attributes
  });
  recordMemoryRecallMetrics(config2, event.duration_ms, {
    strategy: event.strategy,
    docs_selected: event.docs_selected
  });
}
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_esm2();
    init_internalPromptIds();
    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(logUserRetry, "logUserRetry");
    __name(logToolCall, "logToolCall");
    __name(logToolOutputTruncated, "logToolOutputTruncated");
    __name(logFileOperation, "logFileOperation");
    __name(logApiRequest, "logApiRequest");
    __name(logFlashFallback, "logFlashFallback");
    __name(logRipgrepFallback, "logRipgrepFallback");
    __name(logApiError, "logApiError");
    __name(logApiCancel, "logApiCancel");
    __name(logApiResponse, "logApiResponse");
    __name(logLoopDetected, "logLoopDetected");
    __name(logLoopDetectionDisabled, "logLoopDetectionDisabled");
    __name(logNextSpeakerCheck, "logNextSpeakerCheck");
    __name(logSlashCommand, "logSlashCommand");
    __name(logIdeConnection, "logIdeConnection");
    __name(logConversationFinishedEvent, "logConversationFinishedEvent");
    __name(logChatCompression, "logChatCompression");
    __name(logKittySequenceOverflow, "logKittySequenceOverflow");
    __name(logContentRetry, "logContentRetry");
    __name(logContentRetryFailure, "logContentRetryFailure");
    __name(logSubagentExecution, "logSubagentExecution");
    __name(logModelSlashCommand, "logModelSlashCommand");
    __name(logHookCall, "logHookCall");
    __name(logExtensionInstallEvent, "logExtensionInstallEvent");
    __name(logExtensionUninstall, "logExtensionUninstall");
    __name(logExtensionUpdateEvent, "logExtensionUpdateEvent");
    __name(logExtensionEnable, "logExtensionEnable");
    __name(logExtensionDisable, "logExtensionDisable");
    __name(logAuth, "logAuth");
    __name(logSkillLaunch, "logSkillLaunch");
    __name(logUserFeedback, "logUserFeedback");
    __name(logArenaSessionStarted, "logArenaSessionStarted");
    __name(logArenaAgentCompleted, "logArenaAgentCompleted");
    __name(logArenaSessionEnded, "logArenaSessionEnded");
    __name(logPromptSuggestion, "logPromptSuggestion");
    __name(logSpeculation, "logSpeculation");
    __name(logMemoryExtract, "logMemoryExtract");
    __name(logMemoryDream, "logMemoryDream");
    __name(logMemoryRecall, "logMemoryRecall");
  }
});

// packages/core/dist/src/memory/paths.js
import * as fs16 from "node:fs";
import * as os6 from "node:os";
import * as path13 from "node:path";
function findGitRoot(startPath) {
  let current = path13.resolve(startPath);
  while (true) {
    const gitPath = path13.join(current, ".git");
    if (fs16.existsSync(gitPath)) {
      return current;
    }
    const parent = path13.dirname(current);
    if (parent === current) {
      return null;
    }
    current = parent;
  }
}
function findCanonicalGitRoot(startPath) {
  const gitRoot = findGitRoot(startPath);
  if (!gitRoot) {
    return null;
  }
  try {
    const gitContent = fs16.readFileSync(path13.join(gitRoot, ".git"), "utf-8").trim();
    if (!gitContent.startsWith("gitdir:")) {
      return gitRoot;
    }
    const worktreeGitDir = path13.resolve(gitRoot, gitContent.slice("gitdir:".length).trim());
    const commonDir = path13.resolve(worktreeGitDir, fs16.readFileSync(path13.join(worktreeGitDir, "commondir"), "utf-8").trim());
    if (path13.resolve(path13.dirname(worktreeGitDir)) !== path13.join(commonDir, "worktrees")) {
      return gitRoot;
    }
    const backlink = fs16.realpathSync(fs16.readFileSync(path13.join(worktreeGitDir, "gitdir"), "utf-8").trim());
    if (backlink !== path13.join(fs16.realpathSync(gitRoot), ".git")) {
      return gitRoot;
    }
    if (path13.basename(commonDir) !== ".git") {
      return commonDir.normalize("NFC");
    }
    return path13.dirname(commonDir).normalize("NFC");
  } catch {
    return gitRoot;
  }
}
function getMemoryBaseDir() {
  if (process.env["QWEN_CODE_MEMORY_BASE_DIR"]) {
    return process.env["QWEN_CODE_MEMORY_BASE_DIR"];
  }
  return path13.join(os6.homedir(), QWEN_DIR);
}
function getAutoMemoryRoot(projectRoot) {
  const cached2 = _autoMemoryRootCache.get(projectRoot);
  if (cached2 !== void 0)
    return cached2;
  let result;
  if (process.env["QWEN_CODE_MEMORY_LOCAL"] === "1") {
    result = path13.join(projectRoot, QWEN_DIR, AUTO_MEMORY_DIRNAME);
  } else {
    const canonicalRoot = findCanonicalGitRoot(projectRoot) ?? path13.resolve(projectRoot);
    result = path13.join(getMemoryBaseDir(), "projects", sanitizeCwd(canonicalRoot), AUTO_MEMORY_DIRNAME);
  }
  _autoMemoryRootCache.set(projectRoot, result);
  return result;
}
function clearAutoMemoryRootCache() {
  _autoMemoryRootCache.clear();
}
function getAutoMemoryProjectStateDir(projectRoot) {
  return path13.dirname(getAutoMemoryRoot(projectRoot));
}
function isAutoMemPath(absolutePath, projectRoot) {
  const normalizedPath = path13.normalize(absolutePath);
  const memRoot = path13.normalize(getAutoMemoryRoot(projectRoot));
  const rel = path13.relative(memRoot, normalizedPath);
  return rel === "" || !rel.startsWith("..") && !path13.isAbsolute(rel);
}
function getAutoMemoryIndexPath(projectRoot) {
  return path13.join(getAutoMemoryRoot(projectRoot), AUTO_MEMORY_INDEX_FILENAME);
}
function getAutoMemoryMetadataPath(projectRoot) {
  return path13.join(getAutoMemoryProjectStateDir(projectRoot), AUTO_MEMORY_METADATA_FILENAME);
}
function getAutoMemoryExtractCursorPath(projectRoot) {
  return path13.join(getAutoMemoryProjectStateDir(projectRoot), AUTO_MEMORY_EXTRACT_CURSOR_FILENAME);
}
function getAutoMemoryConsolidationLockPath(projectRoot) {
  return path13.join(getAutoMemoryProjectStateDir(projectRoot), AUTO_MEMORY_CONSOLIDATION_LOCK_FILENAME);
}
function getAutoMemoryTopicFilename(type) {
  return `${type}.md`;
}
function getAutoMemoryTopicPath(projectRoot, type) {
  return path13.join(getAutoMemoryRoot(projectRoot), getAutoMemoryTopicFilename(type));
}
function getAutoMemoryFilePath(projectRoot, relativePath) {
  return path13.join(getAutoMemoryRoot(projectRoot), relativePath);
}
var AUTO_MEMORY_DIRNAME, AUTO_MEMORY_INDEX_FILENAME, AUTO_MEMORY_METADATA_FILENAME, AUTO_MEMORY_EXTRACT_CURSOR_FILENAME, AUTO_MEMORY_CONSOLIDATION_LOCK_FILENAME, _autoMemoryRootCache;
var init_paths2 = __esm({
  "packages/core/dist/src/memory/paths.js"() {
    "use strict";
    init_esbuild_shims();
    init_paths();
    AUTO_MEMORY_DIRNAME = "memory";
    AUTO_MEMORY_INDEX_FILENAME = "MEMORY.md";
    AUTO_MEMORY_METADATA_FILENAME = "meta.json";
    AUTO_MEMORY_EXTRACT_CURSOR_FILENAME = "extract-cursor.json";
    AUTO_MEMORY_CONSOLIDATION_LOCK_FILENAME = "consolidation.lock";
    __name(findGitRoot, "findGitRoot");
    __name(findCanonicalGitRoot, "findCanonicalGitRoot");
    __name(getMemoryBaseDir, "getMemoryBaseDir");
    _autoMemoryRootCache = /* @__PURE__ */ new Map();
    __name(getAutoMemoryRoot, "getAutoMemoryRoot");
    __name(clearAutoMemoryRootCache, "clearAutoMemoryRootCache");
    __name(getAutoMemoryProjectStateDir, "getAutoMemoryProjectStateDir");
    __name(isAutoMemPath, "isAutoMemPath");
    __name(getAutoMemoryIndexPath, "getAutoMemoryIndexPath");
    __name(getAutoMemoryMetadataPath, "getAutoMemoryMetadataPath");
    __name(getAutoMemoryExtractCursorPath, "getAutoMemoryExtractCursorPath");
    __name(getAutoMemoryConsolidationLockPath, "getAutoMemoryConsolidationLockPath");
    __name(getAutoMemoryTopicFilename, "getAutoMemoryTopicFilename");
    __name(getAutoMemoryTopicPath, "getAutoMemoryTopicPath");
    __name(getAutoMemoryFilePath, "getAutoMemoryFilePath");
  }
});

// packages/core/dist/src/memory/memoryAge.js
function memoryAgeDays(mtimeMs) {
  return Math.max(0, Math.floor((Date.now() - mtimeMs) / 864e5));
}
function memoryAge(mtimeMs) {
  const d2 = memoryAgeDays(mtimeMs);
  if (d2 === 0)
    return "today";
  if (d2 === 1)
    return "yesterday";
  return `${d2} days ago`;
}
function memoryFreshnessText(mtimeMs) {
  const d2 = memoryAgeDays(mtimeMs);
  if (d2 <= 1)
    return "";
  return `This memory is ${d2} days old. Memories are point-in-time observations, not live state \u2014 claims about code behavior or file:line citations may be outdated. Verify against current code before asserting as fact.`;
}
function memoryFreshnessNote(mtimeMs) {
  const text = memoryFreshnessText(mtimeMs);
  if (!text)
    return "";
  return `<system-reminder>${text}</system-reminder>
`;
}
var init_memoryAge = __esm({
  "packages/core/dist/src/memory/memoryAge.js"() {
    "use strict";
    init_esbuild_shims();
    __name(memoryAgeDays, "memoryAgeDays");
    __name(memoryAge, "memoryAge");
    __name(memoryFreshnessText, "memoryFreshnessText");
    __name(memoryFreshnessNote, "memoryFreshnessNote");
  }
});

// packages/core/dist/src/tools/read-file.js
var read_file_exports = {};
__export(read_file_exports, {
  ReadFileTool: () => ReadFileTool
});
import os7 from "node:os";
import path14 from "node:path";
import fs17 from "node:fs/promises";
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_pdf();
    init_metrics2();
    init_telemetry_utils();
    init_loggers();
    init_types4();
    init_paths();
    init_storage();
    init_paths2();
    init_memoryAge();
    ReadFileToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "ReadFileToolInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      getDescription() {
        const relativePath = makeRelative(this.params.file_path, this.config.getTargetDir());
        const shortPath = shortenPath(relativePath);
        if (this.params.pages) {
          return `${shortPath} (pages ${this.params.pages})`;
        }
        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.file_path, line: this.params.offset }];
      }
      /**
       * Returns 'ask' for paths outside the workspace/temp/userSkills directories,
       * so that external file reads require user confirmation.
       */
      async getDefaultPermission() {
        const filePath = path14.resolve(this.params.file_path);
        const workspaceContext = this.config.getWorkspaceContext();
        const allowedRoots = [
          this.config.storage.getProjectTempDir(),
          // Background subagent transcripts live under <projectDir>/subagents/ and
          // are advertised to the model as polling targets via read_file.
          path14.join(this.config.storage.getProjectDir(), "subagents"),
          Storage.getGlobalTempDir(),
          os7.tmpdir(),
          ...this.config.storage.getUserSkillsDirs(),
          Storage.getUserExtensionsDir()
        ];
        if (workspaceContext.isPathWithinWorkspace(filePath) || isSubpaths(allowedRoots, filePath) || // isAutoMemPath uses the narrower managed auto-memory root for this
        // project — not the broad getMemoryBaseDir() — to avoid exposing
        // sensitive ~/.qwen files such as settings.json or OAuth credentials.
        isAutoMemPath(filePath, this.config.getTargetDir())) {
          return "allow";
        }
        return "ask";
      }
      async execute() {
        const result = await processSingleFileContent(this.params.file_path, this.config, this.params.offset, this.params.limit, this.params.pages);
        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 [start2, end] = result.linesShown;
          const total = result.originalLineCount;
          llmContent = `Showing lines ${start2}-${end} of ${total} total lines.

---

${result.llmContent}`;
        } else {
          llmContent = result.llmContent || "";
        }
        const projectRoot = this.config.getTargetDir();
        if (typeof llmContent === "string" && isAutoMemPath(path14.resolve(this.params.file_path), projectRoot)) {
          try {
            const stat14 = await fs17.stat(path14.resolve(this.params.file_path));
            const note = memoryFreshnessNote(stat14.mtimeMs);
            if (note) {
              llmContent = note + llmContent;
            }
          } catch {
          }
        }
        const lines = typeof result.llmContent === "string" ? result.llmContent.split("\n").length : void 0;
        const mimetype = getSpecificMimeType(this.params.file_path);
        const programming_language = getProgrammingLanguage({
          file_path: this.params.file_path
        });
        logFileOperation(this.config, new FileOperationEvent(ReadFileTool.Name, FileOperation.READ, lines, mimetype, path14.extname(this.params.file_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), PDF files, and Jupyter notebooks (.ipynb). For text files, it can read specific line ranges. For PDF files, use the 'pages' parameter to extract specific page ranges as text (e.g. '1-5'). Max 20 pages per request. This tool can read Jupyter notebooks (.ipynb) and returns structured cell content with outputs.`, Kind.Read, {
          properties: {
            file_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"
            },
            pages: {
              description: "Optional: For PDF files, the page range to extract as text (e.g., '1-5', '3', '10-20'). Pages are 1-indexed. Max 20 pages per request. Open-ended ranges like '3-' are not supported. When provided, PDF content is extracted as text regardless of model capabilities.",
              type: "string"
            }
          },
          required: ["file_path"],
          type: "object"
        });
        this.config = config2;
      }
      validateToolParamValues(params) {
        const filePath = params.file_path;
        if (params.file_path.trim() === "") {
          return "The 'file_path' parameter must be non-empty.";
        }
        if (!path14.isAbsolute(filePath)) {
          return `File path must be absolute, but was relative: ${filePath}. You must provide an absolute path.`;
        }
        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";
        }
        if (params.pages) {
          const parsed = parsePDFPageRange(params.pages);
          if (!parsed) {
            return `Invalid pages parameter: '${params.pages}'. Use formats like '5' or '1-10'.`;
          }
          if (parsed.lastPage === Infinity) {
            return `Open-ended page ranges (e.g. '3-') are not supported; specify an explicit end page within the 20-page limit (e.g. '3-22').`;
          }
          const maxPages = 20;
          if (parsed.lastPage - parsed.firstPage + 1 > maxPages) {
            return `Pages range exceeds maximum of ${maxPages} pages per request.`;
          }
        }
        const fileService = this.config.getFileService();
        if (fileService.shouldQwenIgnoreFile(params.file_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/utils/truncation.js
import * as fs18 from "node:fs/promises";
import * as path15 from "node:path";
import * as crypto4 from "node:crypto";
async function truncateAndSaveToFile(content, fileName, projectTempDir, threshold, truncateLines) {
  const lines = content.split("\n");
  if (content.length <= threshold && lines.length <= truncateLines) {
    return { content };
  }
  const effectiveLines = Math.min(truncateLines, lines.length);
  const headCount = Math.max(Math.floor(effectiveLines / 5), 1);
  const tailCount = effectiveLines - headCount;
  const separator = "\n\n---\n... [CONTENT TRUNCATED] ...\n---\n\n";
  const ellipsis = "...";
  const headBudget = Math.floor(threshold / 5);
  const beginning = [];
  let headChars = 0;
  for (let i4 = 0; i4 < Math.min(headCount, lines.length); i4++) {
    const remaining = headBudget - headChars;
    if (remaining <= 0)
      break;
    if (lines[i4].length + 1 > remaining) {
      const sliceLen = Math.max(remaining - ellipsis.length, 0);
      beginning.push(lines[i4].slice(0, sliceLen) + ellipsis);
      headChars = headBudget;
      break;
    }
    beginning.push(lines[i4]);
    headChars += lines[i4].length + 1;
  }
  const tailBudget = Math.max(threshold - headChars - separator.length, 0);
  const end = [];
  let tailChars = 0;
  const tailStart = Math.max(lines.length - tailCount, beginning.length);
  for (let i4 = lines.length - 1; i4 >= tailStart; i4--) {
    const remaining = tailBudget - tailChars;
    if (remaining <= 0)
      break;
    if (lines[i4].length + 1 > remaining) {
      const sliceLen = Math.max(remaining - ellipsis.length, 0);
      end.unshift(ellipsis + lines[i4].slice(-sliceLen));
      tailChars = tailBudget;
      break;
    }
    end.unshift(lines[i4]);
    tailChars += lines[i4].length + 1;
  }
  const truncatedContent = beginning.join("\n") + separator + end.join("\n");
  const safeFileName = `${path15.basename(fileName)}.output`;
  const outputFile = path15.join(projectTempDir, safeFileName);
  try {
    await fs18.writeFile(outputFile, content);
    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.

Truncated part of the output:
${truncatedContent}`,
      outputFile
    };
  } catch (_error) {
    return {
      content: truncatedContent + `
[Note: Could not save full output to file]`
    };
  }
}
async function truncateToolOutput(config2, toolName, content) {
  const threshold = config2.getTruncateToolOutputThreshold();
  const lines = config2.getTruncateToolOutputLines();
  if (threshold <= 0 || lines <= 0) {
    return { content };
  }
  const originalLength = content.length;
  const fileName = `${toolName}_${crypto4.randomBytes(6).toString("hex")}`;
  const result = await truncateAndSaveToFile(content, fileName, config2.storage.getProjectTempDir(), threshold, lines);
  if (result.outputFile) {
    logToolOutputTruncated(config2, new ToolOutputTruncatedEvent("", {
      toolName,
      originalContentLength: originalLength,
      truncatedContentLength: result.content.length,
      threshold,
      lines
    }));
  }
  return result;
}
var init_truncation = __esm({
  "packages/core/dist/src/utils/truncation.js"() {
    "use strict";
    init_esbuild_shims();
    init_read_file();
    init_loggers();
    init_types4();
    __name(truncateAndSaveToFile, "truncateAndSaveToFile");
    __name(truncateToolOutput, "truncateToolOutput");
  }
});

// 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 getDisplayFromParts(parts2) {
  if (parts2.length === 0) {
    return "";
  }
  const displayParts = [];
  for (const part of parts2) {
    if (part.text !== void 0) {
      displayParts.push(part.text);
    } else if (part.inlineData) {
      displayParts.push(`[${part.inlineData.mimeType}]`);
    }
  }
  return displayParts.join("\n");
}
function generateValidName(name4) {
  let validToolname = name4.replace(/[^a-zA-Z0-9_.-]/g, "_");
  if (validToolname.length > 63) {
    validToolname = validToolname.slice(0, 28) + "___" + validToolname.slice(-32);
  }
  return validToolname;
}
var debugLogger7, 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();
    init_truncation();
    init_debugLogger();
    debugLogger7 = createDebugLogger("MCP_TOOL");
    DiscoveredMCPToolInvocation = class _DiscoveredMCPToolInvocation extends BaseToolInvocation {
      static {
        __name(this, "DiscoveredMCPToolInvocation");
      }
      mcpTool;
      serverName;
      serverToolName;
      displayName;
      trust;
      cliConfig;
      mcpClient;
      mcpTimeout;
      annotations;
      retryCount;
      static MAX_RECONNECT_RETRIES = 3;
      constructor(mcpTool, serverName, serverToolName, displayName, trust, params = {}, cliConfig, mcpClient, mcpTimeout, annotations, retryCount = 0) {
        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;
        this.retryCount = retryCount;
      }
      /**
       * MCP tool default permission based on trust and annotations:
       * - trust: true in a trusted folder → 'allow' (server explicitly trusted by user config)
       * - readOnlyHint → 'allow'
       * - All other MCP tools → 'ask'
       */
      async getDefaultPermission() {
        if (this.trust === true && this.cliConfig?.isTrustedFolder()) {
          return "allow";
        }
        if (this.annotations?.readOnlyHint === true) {
          return "allow";
        }
        return "ask";
      }
      /**
       * Constructs confirmation dialog details for an MCP tool call.
       */
      async getConfirmationDetails(_abortSignal) {
        const permissionRule = `mcp__${this.serverName}__${this.serverToolName}`;
        const confirmationDetails = {
          type: "mcp",
          title: "Confirm MCP Tool Execution",
          serverName: this.serverName,
          toolName: this.serverToolName,
          toolDisplayName: this.displayName,
          permissionRules: [permissionRule],
          onConfirm: /* @__PURE__ */ __name(async (_outcome, _payload) => {
          }, "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 error40 = response?.error;
          const isError = error40?.isError;
          if (error40 && (isError === true || isError === "true")) {
            return true;
          }
        }
        return false;
      }
      async attemptReconnect() {
        if (!this.cliConfig) {
          return null;
        }
        try {
          debugLogger7.info(`Attempting to reconnect MCP server '${this.serverName}'...`);
          const toolRegistry = this.cliConfig.getToolRegistry();
          await toolRegistry.discoverToolsForServer(this.serverName);
          const newTool = await toolRegistry.ensureTool(`mcp__${this.serverName}__${this.serverToolName}`);
          if (newTool instanceof DiscoveredMCPTool) {
            debugLogger7.info(`Successfully reconnected to MCP server '${this.serverName}'`);
            return newTool;
          }
          return null;
        } catch (error40) {
          debugLogger7.error(`Failed to reconnect MCP server '${this.serverName}': ${error40}`);
          return null;
        }
      }
      async handleReconnectOnError(error40, signal, updateOutput2) {
        debugLogger7.error(`MCP server error '${this.serverName}': ${error40}`);
        if (this.retryCount < _DiscoveredMCPToolInvocation.MAX_RECONNECT_RETRIES) {
          debugLogger7.info(`Reconnection attempt ${this.retryCount + 1}/${_DiscoveredMCPToolInvocation.MAX_RECONNECT_RETRIES} for MCP server '${this.serverName}'`);
          const newTool = await this.attemptReconnect();
          if (newTool) {
            const newInvocation = new _DiscoveredMCPToolInvocation(newTool["mcpTool"], this.serverName, this.serverToolName, this.displayName, this.trust, this.params, this.cliConfig, newTool["mcpClient"], this.mcpTimeout, this.annotations, this.retryCount + 1);
            return newInvocation.execute(signal, updateOutput2);
          }
        } else if (this.retryCount >= _DiscoveredMCPToolInvocation.MAX_RECONNECT_RETRIES) {
          debugLogger7.error(`Max reconnection attempts (${_DiscoveredMCPToolInvocation.MAX_RECONNECT_RETRIES}) reached for MCP server '${this.serverName}'`);
        }
        throw error40;
      }
      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) {
        try {
          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);
          const truncatedParts = await this.truncateTextParts(transformedParts);
          return {
            llmContent: truncatedParts,
            returnDisplay: getDisplayFromParts(truncatedParts)
          };
        } catch (error40) {
          return this.handleReconnectOnError(error40, signal, updateOutput2);
        }
      }
      /**
       * 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
          }
        ];
        try {
          const rawResponseParts = await new Promise((resolve42, reject) => {
            if (signal.aborted) {
              const error40 = new Error("Tool call aborted");
              error40.name = "AbortError";
              reject(error40);
              return;
            }
            const onAbort = /* @__PURE__ */ __name(() => {
              cleanup();
              const error40 = new Error("Tool call aborted");
              error40.name = "AbortError";
              reject(error40);
            }, "onAbort");
            const cleanup = /* @__PURE__ */ __name(() => {
              signal.removeEventListener("abort", onAbort);
            }, "cleanup");
            signal.addEventListener("abort", onAbort, { once: true });
            this.mcpTool.callTool(functionCalls).then((res) => {
              cleanup();
              resolve42(res);
            }).catch((err2) => {
              cleanup();
              reject(err2);
            });
          });
          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);
          const truncatedParts = await this.truncateTextParts(transformedParts);
          return {
            llmContent: truncatedParts,
            returnDisplay: getDisplayFromParts(truncatedParts)
          };
        } catch (error40) {
          return this.handleReconnectOnError(error40, signal);
        }
      }
      /**
       * Truncates text parts in the transformed result if they exceed the
       * configured threshold. Non-text parts (images, audio, etc.) are preserved.
       */
      async truncateTextParts(parts2) {
        if (!this.cliConfig) {
          return parts2;
        }
        const result = [];
        for (const part of parts2) {
          if (part.text && !part.inlineData) {
            const truncated = await truncateToolOutput(this.cliConfig, `mcp__${this.serverName}__${this.serverToolName}`, part.text);
            result.push({ text: truncated.content });
          } else {
            result.push(part);
          }
        }
        return result;
      }
      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(getDisplayFromParts, "getDisplayFromParts");
    __name(generateValidName, "generateValidName");
  }
});

// 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 } : {}
  };
}
function makeArenaSessionStartedEvent({ arena_session_id, model_ids, task_length }) {
  return {
    "event.name": "arena_session_started",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    arena_session_id,
    model_ids,
    task_length
  };
}
function makeArenaAgentCompletedEvent({ arena_session_id, agent_session_id, agent_model_id, status, duration_ms, rounds, total_tokens, input_tokens, output_tokens, tool_calls, successful_tool_calls, failed_tool_calls }) {
  return {
    "event.name": "arena_agent_completed",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    arena_session_id,
    agent_session_id,
    agent_model_id,
    status,
    duration_ms,
    rounds,
    total_tokens,
    input_tokens,
    output_tokens,
    tool_calls,
    successful_tool_calls,
    failed_tool_calls
  };
}
function makeArenaSessionEndedEvent({ arena_session_id, status, duration_ms, display_backend, agent_count, completed_agents, failed_agents, cancelled_agents, winner_model_id }) {
  return {
    "event.name": "arena_session_ended",
    "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
    arena_session_id,
    status,
    duration_ms,
    display_backend,
    agent_count,
    completed_agents,
    failed_agents,
    cancelled_agents,
    winner_model_id
  };
}
var StartSessionEvent, EndSessionEvent, UserPromptEvent, UserRetryEvent, ToolCallEvent, ApiRequestEvent, ApiErrorEvent, ApiCancelEvent, ApiResponseEvent, FlashFallbackEvent, RipgrepFallbackEvent, LoopType, LoopDetectedEvent, LoopDetectionDisabledEvent, NextSpeakerCheckEvent, SlashCommandStatus, IdeConnectionType, IdeConnectionEvent, ConversationFinishedEvent, KittySequenceOverflowEvent, FileOperationEvent, ContentRetryEvent, ContentRetryFailureEvent, ExtensionInstallEvent, ToolOutputTruncatedEvent, ExtensionUninstallEvent, ExtensionUpdateEvent, ExtensionEnableEvent, ModelSlashCommandEvent, SubagentExecutionEvent, AuthEvent, HookCallEvent, SkillLaunchEvent, UserFeedbackRating, UserFeedbackEvent, ExtensionDisableEvent, PromptSuggestionEvent, SpeculationEvent, MemoryExtractEvent, MemoryDreamEvent, MemoryRecallEvent;
var init_types4 = __esm({
  "packages/core/dist/src/telemetry/types.js"() {
    "use strict";
    init_esbuild_shims();
    init_mcp_tool();
    init_tool_call_decision();
    init_tool_names();
    StartSessionEvent = class {
      static {
        __name(this, "StartSessionEvent");
      }
      "event.name";
      "event.timestamp";
      session_id;
      model;
      sandbox_enabled;
      core_tools_enabled;
      approval_mode;
      debug_enabled;
      truncate_tool_output_threshold;
      truncate_tool_output_lines;
      mcp_servers;
      telemetry_enabled;
      file_filtering_respect_git_ignore;
      mcp_servers_count;
      mcp_tools_count;
      mcp_tools;
      output_format;
      hooks;
      ide_enabled;
      interactive_shell_enabled;
      skills;
      subagents;
      constructor(config2) {
        const mcpServers = config2.getMcpServers();
        const toolRegistry = config2.getToolRegistry();
        this["event.name"] = "cli_config";
        this.session_id = config2.getSessionId();
        this.model = config2.getModel();
        this.sandbox_enabled = typeof config2.getSandbox() === "string" || !!config2.getSandbox();
        this.core_tools_enabled = (config2.getPermissionManager?.()?.getAllowRawStrings() ?? config2.getCoreTools() ?? []).join(",");
        this.approval_mode = config2.getApprovalMode();
        this.debug_enabled = config2.getDebugMode();
        this.truncate_tool_output_threshold = config2.getTruncateToolOutputThreshold();
        this.truncate_tool_output_lines = config2.getTruncateToolOutputLines();
        this.mcp_servers = mcpServers ? Object.keys(mcpServers).join(",") : "";
        this.telemetry_enabled = config2.getTelemetryEnabled();
        this.file_filtering_respect_git_ignore = config2.getFileFilteringRespectGitIgnore();
        this.mcp_servers_count = mcpServers ? Object.keys(mcpServers).length : 0;
        this.output_format = config2.getOutputFormat();
        this.ide_enabled = config2.getIdeMode();
        this.interactive_shell_enabled = config2.getShouldUseNodePtyShell();
        const hookSystem = config2.getHookSystem();
        if (hookSystem) {
          const allHooks = hookSystem.getAllHooks();
          const uniqueEventNames = [...new Set(allHooks.map((h3) => h3.eventName))];
          if (uniqueEventNames.length > 0) {
            this.hooks = uniqueEventNames.join(",");
          }
        }
        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 agentTool = toolRegistry.getTool(ToolNames.AGENT);
          const subagentNames = agentTool?.getAvailableSubagentNames?.();
          if (subagentNames && subagentNames.length > 0) {
            this.subagents = subagentNames.join(",");
          }
        }
      }
    };
    EndSessionEvent = class {
      static {
        __name(this, "EndSessionEvent");
      }
      "event.name";
      "event.timestamp";
      session_id;
      constructor(config2) {
        this["event.name"] = "end_session";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.session_id = config2?.getSessionId();
      }
    };
    UserPromptEvent = class {
      static {
        __name(this, "UserPromptEvent");
      }
      "event.name";
      "event.timestamp";
      prompt_length;
      prompt_id;
      auth_type;
      prompt;
      constructor(prompt_length, prompt_Id, auth_type, prompt) {
        this["event.name"] = "user_prompt";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.prompt_length = prompt_length;
        this.prompt_id = prompt_Id;
        this.auth_type = auth_type;
        this.prompt = prompt;
      }
    };
    UserRetryEvent = class {
      static {
        __name(this, "UserRetryEvent");
      }
      "event.name";
      "event.timestamp";
      prompt_id;
      constructor(prompt_id) {
        this["event.name"] = "user_retry";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.prompt_id = prompt_id;
      }
    };
    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;
      /**
       * Name of the subagent that issued this request, or undefined when the
       * request originates from the main conversation.
       */
      subagent_name;
      constructor(model, prompt_id, request_text, subagent_name) {
        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;
        this.subagent_name = subagent_name;
      }
    };
    ApiErrorEvent = class {
      static {
        __name(this, "ApiErrorEvent");
      }
      "event.name";
      "event.timestamp";
      // ISO 8601
      response_id;
      model;
      duration_ms;
      prompt_id;
      auth_type;
      // Human-readable error message (e.g. "Request failed with status 429")
      error_message;
      // Error class or category (e.g. "RateLimitError", "invalid_request_error")
      error_type;
      // HTTP status code from the API response (e.g. 429, 500)
      status_code;
      /**
       * Name of the subagent that issued this request, or undefined when the
       * request originates from the main conversation.
       */
      subagent_name;
      constructor(opts) {
        this["event.name"] = "api_error";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.response_id = opts.responseId;
        this.model = opts.model;
        this.duration_ms = opts.durationMs;
        this.prompt_id = opts.promptId;
        this.auth_type = opts.authType;
        this.error_message = opts.errorMessage;
        this.error_type = opts.errorType;
        this.status_code = opts.statusCode;
        this.subagent_name = opts.subagentName;
      }
    };
    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;
      total_token_count;
      response_text;
      prompt_id;
      auth_type;
      /**
       * Name of the subagent that issued this request, or undefined when the
       * request originates from the main conversation.
       */
      subagent_name;
      constructor(response_id, model, duration_ms, prompt_id, auth_type, usage_data, response_text, subagent_name) {
        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.total_token_count = usage_data?.totalTokenCount ?? 0;
        this.response_text = response_text;
        this.prompt_id = prompt_id;
        this.auth_type = auth_type;
        this.subagent_name = subagent_name;
      }
    };
    FlashFallbackEvent = class {
      static {
        __name(this, "FlashFallbackEvent");
      }
      "event.name";
      "event.timestamp";
      auth_type;
      constructor(auth_type) {
        this["event.name"] = "flash_fallback";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.auth_type = auth_type;
      }
    };
    RipgrepFallbackEvent = class {
      static {
        __name(this, "RipgrepFallbackEvent");
      }
      "event.name";
      "event.timestamp";
      use_ripgrep;
      use_builtin_ripgrep;
      error;
      constructor(use_ripgrep, use_builtin_ripgrep, error40) {
        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 = error40;
      }
    };
    (function(LoopType2) {
      LoopType2["CONSECUTIVE_IDENTICAL_TOOL_CALLS"] = "consecutive_identical_tool_calls";
      LoopType2["CHANTING_IDENTICAL_SENTENCES"] = "chanting_identical_sentences";
      LoopType2["REPETITIVE_THOUGHTS"] = "repetitive_thoughts";
      LoopType2["READ_FILE_LOOP"] = "read_file_loop";
      LoopType2["ACTION_STAGNATION"] = "action_stagnation";
    })(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;
      }
    };
    HookCallEvent = class {
      static {
        __name(this, "HookCallEvent");
      }
      "event.name";
      "event.timestamp";
      hook_event_name;
      hook_type;
      hook_name;
      hook_input;
      hook_output;
      exit_code;
      stdout;
      stderr;
      duration_ms;
      success;
      error;
      constructor(hookEventName, hookType, hookName, hookInput, durationMs, success2, hookOutput, exitCode, stdout2, stderr, error40) {
        this["event.name"] = "hook_call";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.hook_event_name = hookEventName;
        this.hook_type = hookType;
        this.hook_name = hookName;
        this.hook_input = hookInput;
        this.hook_output = hookOutput;
        this.exit_code = exitCode;
        this.stdout = stdout2;
        this.stderr = stderr;
        this.duration_ms = durationMs;
        this.success = success2;
        this.error = error40;
      }
    };
    SkillLaunchEvent = class {
      static {
        __name(this, "SkillLaunchEvent");
      }
      "event.name";
      "event.timestamp";
      skill_name;
      success;
      constructor(skill_name, success2) {
        this["event.name"] = "skill_launch";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.skill_name = skill_name;
        this.success = success2;
      }
    };
    (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;
      }
    };
    __name(makeArenaSessionStartedEvent, "makeArenaSessionStartedEvent");
    __name(makeArenaAgentCompletedEvent, "makeArenaAgentCompletedEvent");
    __name(makeArenaSessionEndedEvent, "makeArenaSessionEndedEvent");
    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;
      }
    };
    PromptSuggestionEvent = class {
      static {
        __name(this, "PromptSuggestionEvent");
      }
      "event.name";
      "event.timestamp";
      outcome;
      prompt_id;
      accept_method;
      time_to_accept_ms;
      time_to_ignore_ms;
      time_to_first_keystroke_ms;
      suggestion_length;
      similarity;
      was_focused_when_shown;
      reason;
      constructor(params) {
        this["event.name"] = "qwen-code.prompt_suggestion";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.outcome = params.outcome;
        this.prompt_id = params.prompt_id ?? "user_intent";
        this.accept_method = params.accept_method;
        this.time_to_accept_ms = params.time_to_accept_ms;
        this.time_to_ignore_ms = params.time_to_ignore_ms;
        this.time_to_first_keystroke_ms = params.time_to_first_keystroke_ms;
        this.suggestion_length = params.suggestion_length;
        this.similarity = params.similarity;
        this.was_focused_when_shown = params.was_focused_when_shown;
        this.reason = params.reason;
      }
    };
    SpeculationEvent = class {
      static {
        __name(this, "SpeculationEvent");
      }
      "event.name";
      "event.timestamp";
      outcome;
      turns_used;
      files_written;
      tool_use_count;
      duration_ms;
      boundary_type;
      had_pipelined_suggestion;
      constructor(params) {
        this["event.name"] = "qwen-code.speculation";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.outcome = params.outcome;
        this.turns_used = params.turns_used;
        this.files_written = params.files_written;
        this.tool_use_count = params.tool_use_count;
        this.duration_ms = params.duration_ms;
        this.boundary_type = params.boundary_type;
        this.had_pipelined_suggestion = params.had_pipelined_suggestion;
      }
    };
    MemoryExtractEvent = class {
      static {
        __name(this, "MemoryExtractEvent");
      }
      "event.name";
      "event.timestamp";
      /** 'auto' = triggered by session turn; 'manual' = user-initiated */
      trigger;
      status;
      skipped_reason;
      patches_count;
      touched_topics;
      duration_ms;
      constructor(params) {
        this["event.name"] = "qwen-code.memory.extract";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.trigger = params.trigger;
        this.status = params.status;
        this.skipped_reason = params.skipped_reason;
        this.patches_count = params.patches_count;
        this.touched_topics = params.touched_topics.join(",");
        this.duration_ms = params.duration_ms;
      }
    };
    MemoryDreamEvent = class {
      static {
        __name(this, "MemoryDreamEvent");
      }
      "event.name";
      "event.timestamp";
      /** 'auto' = scheduler-triggered; 'manual' = user ran /dream */
      trigger;
      status;
      deduped_entries;
      touched_topics_count;
      touched_topics;
      duration_ms;
      constructor(params) {
        this["event.name"] = "qwen-code.memory.dream";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.trigger = params.trigger;
        this.status = params.status;
        this.deduped_entries = params.deduped_entries;
        this.touched_topics_count = params.touched_topics.length;
        this.touched_topics = params.touched_topics.join(",");
        this.duration_ms = params.duration_ms;
      }
    };
    MemoryRecallEvent = class {
      static {
        __name(this, "MemoryRecallEvent");
      }
      "event.name";
      "event.timestamp";
      query_length;
      docs_scanned;
      docs_selected;
      strategy;
      duration_ms;
      constructor(params) {
        this["event.name"] = "qwen-code.memory.recall";
        this["event.timestamp"] = (/* @__PURE__ */ new Date()).toISOString();
        this.query_length = params.query_length;
        this.docs_scanned = params.docs_scanned;
        this.docs_selected = params.docs_selected;
        this.strategy = params.strategy;
        this.duration_ms = params.duration_ms;
      }
    };
  }
});

// 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, start2, count) {
  return text.substring(0, start2) + text.substring(start2 + 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 i4 = 0;
  let output = "";
  parseMarkdownCodeBlock(["```", "[```", "{```"]);
  const processed = parseValue2();
  if (!processed) {
    throwUnexpectedEnd();
  }
  parseMarkdownCodeBlock(["```", "```]", "```}"]);
  const processedComma = parseCharacter(",");
  if (processedComma) {
    parseWhitespaceAndSkipComments();
  }
  if (isStartOfValue(text[i4]) && endsWithCommaOrNewline(output)) {
    if (!processedComma) {
      output = insertBeforeLastWhitespace(output, ",");
    }
    parseNewlineDelimitedJSON();
  } else if (processedComma) {
    output = stripLastOccurrence(output, ",");
  }
  while (text[i4] === "}" || text[i4] === "]") {
    i4++;
    parseWhitespaceAndSkipComments();
  }
  if (i4 >= 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 start2 = i4;
    let changed = parseWhitespace(skipNewline);
    do {
      changed = parseComment();
      if (changed) {
        changed = parseWhitespace(skipNewline);
      }
    } while (changed);
    return i4 > start2;
  }
  __name(parseWhitespaceAndSkipComments, "parseWhitespaceAndSkipComments");
  function parseWhitespace(skipNewline) {
    const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline;
    let whitespace = "";
    while (true) {
      if (_isWhiteSpace(text, i4)) {
        whitespace += text[i4];
        i4++;
      } else if (isSpecialWhitespace(text, i4)) {
        whitespace += " ";
        i4++;
      } else {
        break;
      }
    }
    if (whitespace.length > 0) {
      output += whitespace;
      return true;
    }
    return false;
  }
  __name(parseWhitespace, "parseWhitespace");
  function parseComment() {
    if (text[i4] === "/" && text[i4 + 1] === "*") {
      while (i4 < text.length && !atEndOfBlockComment(text, i4)) {
        i4++;
      }
      i4 += 2;
      return true;
    }
    if (text[i4] === "/" && text[i4 + 1] === "/") {
      while (i4 < text.length && text[i4] !== "\n") {
        i4++;
      }
      return true;
    }
    return false;
  }
  __name(parseComment, "parseComment");
  function parseMarkdownCodeBlock(blocks) {
    if (skipMarkdownCodeBlock(blocks)) {
      if (isFunctionNameCharStart(text[i4])) {
        while (i4 < text.length && isFunctionNameChar(text[i4])) {
          i4++;
        }
      }
      parseWhitespaceAndSkipComments();
      return true;
    }
    return false;
  }
  __name(parseMarkdownCodeBlock, "parseMarkdownCodeBlock");
  function skipMarkdownCodeBlock(blocks) {
    parseWhitespace(true);
    for (const block2 of blocks) {
      const end = i4 + block2.length;
      if (text.slice(i4, end) === block2) {
        i4 = end;
        return true;
      }
    }
    return false;
  }
  __name(skipMarkdownCodeBlock, "skipMarkdownCodeBlock");
  function parseCharacter(char) {
    if (text[i4] === char) {
      output += text[i4];
      i4++;
      return true;
    }
    return false;
  }
  __name(parseCharacter, "parseCharacter");
  function skipCharacter(char) {
    if (text[i4] === char) {
      i4++;
      return true;
    }
    return false;
  }
  __name(skipCharacter, "skipCharacter");
  function skipEscapeCharacter() {
    return skipCharacter("\\");
  }
  __name(skipEscapeCharacter, "skipEscapeCharacter");
  function skipEllipsis() {
    parseWhitespaceAndSkipComments();
    if (text[i4] === "." && text[i4 + 1] === "." && text[i4 + 2] === ".") {
      i4 += 3;
      parseWhitespaceAndSkipComments();
      skipCharacter(",");
      return true;
    }
    return false;
  }
  __name(skipEllipsis, "skipEllipsis");
  function parseObject() {
    if (text[i4] === "{") {
      output += "{";
      i4++;
      parseWhitespaceAndSkipComments();
      if (skipCharacter(",")) {
        parseWhitespaceAndSkipComments();
      }
      let initial = true;
      while (i4 < text.length && text[i4] !== "}") {
        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[i4] === "}" || text[i4] === "{" || text[i4] === "]" || text[i4] === "[" || text[i4] === void 0) {
            output = stripLastOccurrence(output, ",");
          } else {
            throwObjectKeyExpected();
          }
          break;
        }
        parseWhitespaceAndSkipComments();
        const processedColon = parseCharacter(":");
        const truncatedText = i4 >= text.length;
        if (!processedColon) {
          if (isStartOfValue(text[i4]) || truncatedText) {
            output = insertBeforeLastWhitespace(output, ":");
          } else {
            throwColonExpected();
          }
        }
        const processedValue = parseValue2();
        if (!processedValue) {
          if (processedColon || truncatedText) {
            output += "null";
          } else {
            throwColonExpected();
          }
        }
      }
      if (text[i4] === "}") {
        output += "}";
        i4++;
      } else {
        output = insertBeforeLastWhitespace(output, "}");
      }
      return true;
    }
    return false;
  }
  __name(parseObject, "parseObject");
  function parseArray() {
    if (text[i4] === "[") {
      output += "[";
      i4++;
      parseWhitespaceAndSkipComments();
      if (skipCharacter(",")) {
        parseWhitespaceAndSkipComments();
      }
      let initial = true;
      while (i4 < text.length && text[i4] !== "]") {
        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[i4] === "]") {
        output += "]";
        i4++;
      } 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[i4] === "\\";
    if (skipEscapeChars) {
      i4++;
      skipEscapeChars = true;
    }
    if (isQuote(text[i4])) {
      const isEndQuote = isDoubleQuote(text[i4]) ? isDoubleQuote : isSingleQuote(text[i4]) ? isSingleQuote : isSingleQuoteLike(text[i4]) ? isSingleQuoteLike : isDoubleQuoteLike;
      const iBefore = i4;
      const oBefore = output.length;
      let str2 = '"';
      i4++;
      while (true) {
        if (i4 >= text.length) {
          const iPrev = prevNonWhitespaceIndex(i4 - 1);
          if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {
            i4 = iBefore;
            output = output.substring(0, oBefore);
            return parseString(true);
          }
          str2 = insertBeforeLastWhitespace(str2, '"');
          output += str2;
          return true;
        }
        if (i4 === stopAtIndex) {
          str2 = insertBeforeLastWhitespace(str2, '"');
          output += str2;
          return true;
        }
        if (isEndQuote(text[i4])) {
          const iQuote = i4;
          const oQuote = str2.length;
          str2 += '"';
          i4++;
          output += str2;
          parseWhitespaceAndSkipComments(false);
          if (stopAtDelimiter || i4 >= text.length || isDelimiter(text[i4]) || isQuote(text[i4]) || isDigit2(text[i4])) {
            parseConcatenatedString();
            return true;
          }
          const iPrevChar = prevNonWhitespaceIndex(iQuote - 1);
          const prevChar = text.charAt(iPrevChar);
          if (prevChar === ",") {
            i4 = iBefore;
            output = output.substring(0, oBefore);
            return parseString(false, iPrevChar);
          }
          if (isDelimiter(prevChar)) {
            i4 = iBefore;
            output = output.substring(0, oBefore);
            return parseString(true);
          }
          output = output.substring(0, oBefore);
          i4 = iQuote + 1;
          str2 = `${str2.substring(0, oQuote)}\\${str2.substring(oQuote)}`;
        } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i4])) {
          if (text[i4 - 1] === ":" && regexUrlStart.test(text.substring(iBefore + 1, i4 + 2))) {
            while (i4 < text.length && regexUrlChar.test(text[i4])) {
              str2 += text[i4];
              i4++;
            }
          }
          str2 = insertBeforeLastWhitespace(str2, '"');
          output += str2;
          parseConcatenatedString();
          return true;
        } else if (text[i4] === "\\") {
          const char = text.charAt(i4 + 1);
          const escapeChar = escapeCharacters[char];
          if (escapeChar !== void 0) {
            str2 += text.slice(i4, i4 + 2);
            i4 += 2;
          } else if (char === "u") {
            let j2 = 2;
            while (j2 < 6 && isHex(text[i4 + j2])) {
              j2++;
            }
            if (j2 === 6) {
              str2 += text.slice(i4, i4 + 6);
              i4 += 6;
            } else if (i4 + j2 >= text.length) {
              i4 = text.length;
            } else {
              throwInvalidUnicodeCharacter();
            }
          } else {
            str2 += char;
            i4 += 2;
          }
        } else {
          const char = text.charAt(i4);
          if (char === '"' && text[i4 - 1] !== "\\") {
            str2 += `\\${char}`;
            i4++;
          } else if (isControlCharacter(char)) {
            str2 += controlCharacters[char];
            i4++;
          } else {
            if (!isValidStringCharacter(char)) {
              throwInvalidCharacter(char);
            }
            str2 += char;
            i4++;
          }
        }
        if (skipEscapeChars) {
          skipEscapeCharacter();
        }
      }
    }
    return false;
  }
  __name(parseString, "parseString");
  function parseConcatenatedString() {
    let processed2 = false;
    parseWhitespaceAndSkipComments();
    while (text[i4] === "+") {
      processed2 = true;
      i4++;
      parseWhitespaceAndSkipComments();
      output = stripLastOccurrence(output, '"', true);
      const start2 = output.length;
      const parsedStr = parseString();
      if (parsedStr) {
        output = removeAtIndex(output, start2, 1);
      } else {
        output = insertBeforeLastWhitespace(output, '"');
      }
    }
    return processed2;
  }
  __name(parseConcatenatedString, "parseConcatenatedString");
  function parseNumber() {
    const start2 = i4;
    if (text[i4] === "-") {
      i4++;
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start2);
        return true;
      }
      if (!isDigit2(text[i4])) {
        i4 = start2;
        return false;
      }
    }
    while (isDigit2(text[i4])) {
      i4++;
    }
    if (text[i4] === ".") {
      i4++;
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start2);
        return true;
      }
      if (!isDigit2(text[i4])) {
        i4 = start2;
        return false;
      }
      while (isDigit2(text[i4])) {
        i4++;
      }
    }
    if (text[i4] === "e" || text[i4] === "E") {
      i4++;
      if (text[i4] === "-" || text[i4] === "+") {
        i4++;
      }
      if (atEndOfNumber()) {
        repairNumberEndingWithNumericSymbol(start2);
        return true;
      }
      if (!isDigit2(text[i4])) {
        i4 = start2;
        return false;
      }
      while (isDigit2(text[i4])) {
        i4++;
      }
    }
    if (!atEndOfNumber()) {
      i4 = start2;
      return false;
    }
    if (i4 > start2) {
      const num = text.slice(start2, i4);
      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(name4, value) {
    if (text.slice(i4, i4 + name4.length) === name4) {
      output += value;
      i4 += name4.length;
      return true;
    }
    return false;
  }
  __name(parseKeyword, "parseKeyword");
  function parseUnquotedString(isKey) {
    const start2 = i4;
    if (isFunctionNameCharStart(text[i4])) {
      while (i4 < text.length && isFunctionNameChar(text[i4])) {
        i4++;
      }
      let j2 = i4;
      while (isWhitespace(text, j2)) {
        j2++;
      }
      if (text[j2] === "(") {
        i4 = j2 + 1;
        parseValue2();
        if (text[i4] === ")") {
          i4++;
          if (text[i4] === ";") {
            i4++;
          }
        }
        return true;
      }
    }
    while (i4 < text.length && !isUnquotedStringDelimiter(text[i4]) && !isQuote(text[i4]) && (!isKey || text[i4] !== ":")) {
      i4++;
    }
    if (text[i4 - 1] === ":" && regexUrlStart.test(text.substring(start2, i4 + 2))) {
      while (i4 < text.length && regexUrlChar.test(text[i4])) {
        i4++;
      }
    }
    if (i4 > start2) {
      while (isWhitespace(text, i4 - 1) && i4 > 0) {
        i4--;
      }
      const symbol2 = text.slice(start2, i4);
      output += symbol2 === "undefined" ? "null" : JSON.stringify(symbol2);
      if (text[i4] === '"') {
        i4++;
      }
      return true;
    }
  }
  __name(parseUnquotedString, "parseUnquotedString");
  function parseRegex() {
    if (text[i4] === "/") {
      const start2 = i4;
      i4++;
      while (i4 < text.length && (text[i4] !== "/" || text[i4 - 1] === "\\")) {
        i4++;
      }
      i4++;
      output += `"${text.substring(start2, i4)}"`;
      return true;
    }
  }
  __name(parseRegex, "parseRegex");
  function prevNonWhitespaceIndex(start2) {
    let prev = start2;
    while (prev > 0 && isWhitespace(text, prev)) {
      prev--;
    }
    return prev;
  }
  __name(prevNonWhitespaceIndex, "prevNonWhitespaceIndex");
  function atEndOfNumber() {
    return i4 >= text.length || isDelimiter(text[i4]) || isWhitespace(text, i4);
  }
  __name(atEndOfNumber, "atEndOfNumber");
  function repairNumberEndingWithNumericSymbol(start2) {
    output += `${text.slice(start2, i4)}0`;
  }
  __name(repairNumberEndingWithNumericSymbol, "repairNumberEndingWithNumericSymbol");
  function throwInvalidCharacter(char) {
    throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i4);
  }
  __name(throwInvalidCharacter, "throwInvalidCharacter");
  function throwUnexpectedCharacter() {
    throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i4])}`, i4);
  }
  __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", i4);
  }
  __name(throwObjectKeyExpected, "throwObjectKeyExpected");
  function throwColonExpected() {
    throw new JSONRepairError("Colon expected", i4);
  }
  __name(throwColonExpected, "throwColonExpected");
  function throwInvalidUnicodeCharacter() {
    const chars = text.slice(i4, i4 + 6);
    throw new JSONRepairError(`Invalid unicode character "${chars}"`, i4);
  }
  __name(throwInvalidUnicodeCharacter, "throwInvalidUnicodeCharacter");
}
function atEndOfBlockComment(text, i4) {
  return text[i4] === "*" && text[i4 + 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 (error40) {
    try {
      const repairedJson = jsonrepair(jsonString);
      return JSON.parse(repairedJson);
    } catch (repairError) {
      debugLogger8.error("Failed to parse JSON even with jsonrepair:", {
        originalError: error40,
        repairError,
        jsonString
      });
      return fallbackValue;
    }
  }
}
var debugLogger8;
var init_safeJsonParse = __esm({
  "packages/core/dist/src/utils/safeJsonParse.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm4();
    init_debugLogger();
    debugLogger8 = createDebugLogger("JSON_PARSE");
    __name(safeJsonParse, "safeJsonParse");
  }
});

// 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
function 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);
}
async function convertGeminiToolsToOpenAI(geminiTools, schemaCompliance = "auto") {
  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 func2 of actualTool.functionDeclarations) {
        if (func2.name && func2.description) {
          let parameters;
          if (func2.parametersJsonSchema) {
            const paramsCopy = {
              ...func2.parametersJsonSchema
            };
            parameters = paramsCopy;
          } else if (func2.parameters) {
            parameters = convertGeminiToolParametersToOpenAI(func2.parameters);
          }
          if (parameters) {
            parameters = convertSchema(parameters, schemaCompliance);
          }
          openAITools.push({
            type: "function",
            function: {
              name: func2.name,
              description: func2.description,
              parameters
            }
          });
        }
      }
    }
  }
  return openAITools;
}
function convertGeminiRequestToOpenAI(request4, requestContext, options2 = { cleanOrphanToolCalls: true }) {
  let messages = [];
  addSystemInstructionMessage(request4, messages);
  processContents(request4.contents, messages, requestContext);
  if (options2.cleanOrphanToolCalls) {
    messages = cleanOrphanedToolCalls(messages);
  }
  messages = mergeConsecutiveAssistantMessages(messages);
  return messages;
}
function convertGeminiResponseToOpenAI(response, requestContext) {
  const candidate = response.candidates?.[0];
  const parts2 = candidate?.content?.parts || [];
  const thoughtParts = [];
  const contentParts = [];
  const toolCalls = [];
  let toolCallIndex = 0;
  for (const part of parts2) {
    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 = 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 || requestContext.model,
    choices: [
      {
        index: 0,
        message,
        finish_reason: finishReason,
        logprobs: null
      }
    ],
    usage: usage2
  };
}
function addSystemInstructionMessage(request4, messages) {
  if (!request4.config?.systemInstruction)
    return;
  const systemText = extractTextFromContentUnion(request4.config.systemInstruction);
  if (systemText) {
    messages.push({
      role: "system",
      content: systemText
    });
  }
}
function processContents(contents, messages, requestContext) {
  if (Array.isArray(contents)) {
    for (const content of contents) {
      processContent(content, messages, requestContext);
    }
  } else if (contents) {
    processContent(contents, messages, requestContext);
  }
}
function processContent(content, messages, requestContext) {
  if (typeof content === "string") {
    messages.push({ role: "user", content });
    return;
  }
  if (!isContentObject(content))
    return;
  const parts2 = content.parts || [];
  const role = content.role === "model" ? "assistant" : "user";
  const contentParts = [];
  const reasoningParts = [];
  const toolCalls = [];
  let toolCallIndex = 0;
  const accumulatedSplitMedia = [];
  for (const part of parts2) {
    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 = createMediaContentPart(part, requestContext);
    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 = createToolMessage(part.functionResponse, requestContext);
      if (toolMessage) {
        if (requestContext.splitToolMedia && Array.isArray(toolMessage.content)) {
          const mediaParts = [];
          const textParts = [];
          for (const cp3 of toolMessage.content) {
            if (cp3 && (cp3.type === "image_url" || cp3.type === "input_audio" || cp3.type === "video_url" || cp3.type === "file")) {
              mediaParts.push(cp3);
            } else if (cp3 && cp3.type === "text") {
              textParts.push(cp3);
            }
          }
          if (mediaParts.length > 0) {
            const textOnly = textParts.map((p2) => p2.text).join("\n");
            toolMessage.content = textOnly || "[media attached in following user message]";
            accumulatedSplitMedia.push(...mediaParts);
          }
        }
        messages.push(toolMessage);
      }
    }
  }
  if (accumulatedSplitMedia.length > 0) {
    messages.push({
      role: "user",
      content: [
        {
          type: "text",
          text: "(attached media from previous tool call)"
        },
        ...accumulatedSplitMedia
      ]
    });
  }
  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",
      // When there is reasoning content but no text, use "" instead of null.
      // Some OpenAI-compatible providers (e.g. Ollama) reject content: null
      // when reasoning_content is present, returning HTTP 400.
      // For tool-call-only messages we keep null to stay spec-compliant.
      content: assistantTextContent || (reasoningParts.length > 0 ? "" : 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
    });
  }
}
function 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 error40 = responseObject["error"];
    if (typeof error40 === "string") {
      return error40;
    }
  }
  try {
    const serialized = JSON.stringify(response);
    return serialized ?? String(response);
  } catch {
    return String(response);
  }
}
function createToolMessage(response, requestContext) {
  const textContent2 = extractFunctionResponseContent(response.response);
  const contentParts = [];
  if (textContent2) {
    contentParts.push({ type: "text", text: textContent2 });
  }
  for (const part of response.parts || []) {
    const mediaPart = createMediaContentPart(part, requestContext);
    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
  };
}
function createMediaContentPart(part, requestContext) {
  const { modalities } = requestContext;
  if (part.inlineData?.mimeType && part.inlineData?.data) {
    const mimeType = part.inlineData.mimeType;
    const mediaType = getMediaType(mimeType);
    const displayName = part.inlineData.displayName || mimeType;
    if (mediaType === "image") {
      if (!modalities.image) {
        return unsupportedModalityPlaceholder("image", displayName, requestContext);
      }
      const dataUrl = `data:${mimeType};base64,${part.inlineData.data}`;
      return {
        type: "image_url",
        image_url: { url: dataUrl }
      };
    }
    if (mimeType === "application/pdf") {
      if (!modalities.pdf) {
        return unsupportedModalityPlaceholder("pdf", displayName, requestContext);
      }
      const filename = part.inlineData.displayName || "document.pdf";
      return {
        type: "file",
        file: {
          filename,
          file_data: `data:${mimeType};base64,${part.inlineData.data}`
        }
      };
    }
    if (mediaType === "audio") {
      if (!modalities.audio) {
        return unsupportedModalityPlaceholder("audio", displayName, requestContext);
      }
      const format4 = getAudioFormat(mimeType);
      if (format4) {
        return {
          type: "input_audio",
          input_audio: {
            data: `data:${mimeType};base64,${part.inlineData.data}`,
            format: format4
          }
        };
      }
    }
    if (mediaType === "video") {
      if (!modalities.video) {
        return unsupportedModalityPlaceholder("video", displayName, requestContext);
      }
      return {
        type: "video_url",
        video_url: {
          url: `data:${mimeType};base64,${part.inlineData.data}`
        }
      };
    }
    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 = getMediaType(mimeType);
    if (mediaType === "image") {
      if (!modalities.image) {
        return unsupportedModalityPlaceholder("image", filename, requestContext);
      }
      return {
        type: "image_url",
        image_url: { url: fileUri }
      };
    }
    if (mimeType === "application/pdf") {
      if (!modalities.pdf) {
        return unsupportedModalityPlaceholder("pdf", filename, requestContext);
      }
      return {
        type: "file",
        file: {
          filename,
          file_data: fileUri
        }
      };
    }
    if (mediaType === "video") {
      if (!modalities.video) {
        return unsupportedModalityPlaceholder("video", filename, requestContext);
      }
      return {
        type: "video_url",
        video_url: {
          url: fileUri
        }
      };
    }
    const displayNameStr = part.fileData.displayName ? ` (${part.fileData.displayName})` : "";
    return {
      type: "text",
      text: `Unsupported file media type: ${mimeType}${displayNameStr}.`
    };
  }
  return null;
}
function unsupportedModalityPlaceholder(modality, displayName, requestContext) {
  debugLogger9.warn(`Model '${requestContext.model}' does not support ${modality} input. Replacing with text placeholder: ${displayName}`);
  let hint;
  if (modality === "pdf") {
    hint = "This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:\n/extensions install https://github.com/anthropics/skills:document-skills";
  } else {
    hint = `This model does not support ${modality} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`;
  }
  return {
    type: "text",
    text: `[Unsupported ${modality} file: "${displayName}". ${hint}]`
  };
}
function getMediaType(mimeType) {
  if (mimeType.startsWith("image/"))
    return "image";
  if (mimeType.startsWith("audio/"))
    return "audio";
  if (mimeType.startsWith("video/"))
    return "video";
  return "file";
}
function getAudioFormat(mimeType) {
  if (mimeType.includes("wav"))
    return "wav";
  if (mimeType.includes("mp3") || mimeType.includes("mpeg"))
    return "mp3";
  return null;
}
function isContentObject(content) {
  return typeof content === "object" && content !== null && "role" in content && "parts" in content && Array.isArray(content["parts"]);
}
function extractTextFromContentUnion(contentUnion) {
  if (typeof contentUnion === "string") {
    return contentUnion;
  }
  if (Array.isArray(contentUnion)) {
    return contentUnion.map((item) => 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 "";
}
function convertOpenAIResponseToGemini(openaiResponse, requestContext) {
  const choice2 = openaiResponse.choices?.[0];
  const response = new GenerateContentResponse();
  if (choice2) {
    const parts2 = [];
    const reasoningText = choice2.message.reasoning_content ?? choice2.message.reasoning;
    if (reasoningText) {
      parts2.push({ text: reasoningText, thought: true });
    }
    if (choice2.message.content) {
      parts2.push({ text: choice2.message.content });
    }
    if (choice2.message.tool_calls) {
      for (const toolCall of choice2.message.tool_calls) {
        if (toolCall.function) {
          let args2 = {};
          if (toolCall.function.arguments) {
            args2 = safeJsonParse(toolCall.function.arguments, {});
          }
          parts2.push({
            functionCall: {
              id: toolCall.id,
              name: toolCall.function.name,
              args: args2
            }
          });
        }
      }
    }
    response.candidates = [
      {
        content: {
          parts: parts2,
          role: "model"
        },
        finishReason: mapOpenAIFinishReasonToGemini(choice2.finish_reason || "stop"),
        index: 0,
        safetyRatings: []
      }
    ];
  } else {
    response.candidates = [];
  }
  response.responseId = openaiResponse.id;
  response.createTime = openaiResponse.created ? openaiResponse.created.toString() : (/* @__PURE__ */ new Date()).getTime().toString();
  response.modelVersion = requestContext.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;
}
function convertOpenAIChunkToGemini(chunk, requestContext) {
  const choice2 = chunk.choices?.[0];
  const response = new GenerateContentResponse();
  const toolCallParser = requestContext.toolCallParser;
  if (!toolCallParser) {
    throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");
  }
  if (choice2) {
    const parts2 = [];
    const reasoningText = choice2.delta?.reasoning_content ?? choice2.delta?.reasoning;
    if (reasoningText) {
      parts2.push({ text: reasoningText, thought: true });
    }
    if (choice2.delta?.content) {
      if (typeof choice2.delta.content === "string") {
        parts2.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) {
          toolCallParser.addChunk(index, toolCall.function.arguments, toolCall.id, toolCall.function.name);
        } else {
          toolCallParser.addChunk(
            index,
            "",
            // Empty chunk for metadata-only updates
            toolCall.id,
            toolCall.function?.name
          );
        }
      }
    }
    let toolCallsTruncated = false;
    if (choice2.finish_reason) {
      toolCallsTruncated = toolCallParser.hasIncompleteToolCalls();
      const completedToolCalls = toolCallParser.getCompletedToolCalls();
      for (const toolCall of completedToolCalls) {
        if (toolCall.name) {
          parts2.push({
            functionCall: {
              id: toolCall.id || `call_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
              name: toolCall.name,
              args: toolCall.args
            }
          });
        }
      }
    }
    const effectiveFinishReason = toolCallsTruncated && choice2.finish_reason !== "length" ? "length" : choice2.finish_reason;
    const candidate = {
      content: {
        parts: parts2,
        role: "model"
      },
      index: 0,
      safetyRatings: []
    };
    if (effectiveFinishReason) {
      candidate.finishReason = mapOpenAIFinishReasonToGemini(effectiveFinishReason);
    }
    response.candidates = [candidate];
  } else {
    response.candidates = [];
  }
  response.responseId = chunk.id;
  response.createTime = chunk.created ? chunk.created.toString() : (/* @__PURE__ */ new Date()).getTime().toString();
  response.modelVersion = requestContext.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;
}
function 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;
}
function 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";
  }
}
function 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;
}
function 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;
}
var debugLogger9, OpenAIContentConverter;
var init_converter = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/converter.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_safeJsonParse();
    init_debugLogger();
    init_schemaConverter();
    debugLogger9 = createDebugLogger("CONVERTER");
    __name(convertGeminiToolParametersToOpenAI, "convertGeminiToolParametersToOpenAI");
    __name(convertGeminiToolsToOpenAI, "convertGeminiToolsToOpenAI");
    __name(convertGeminiRequestToOpenAI, "convertGeminiRequestToOpenAI");
    __name(convertGeminiResponseToOpenAI, "convertGeminiResponseToOpenAI");
    __name(addSystemInstructionMessage, "addSystemInstructionMessage");
    __name(processContents, "processContents");
    __name(processContent, "processContent");
    __name(extractFunctionResponseContent, "extractFunctionResponseContent");
    __name(createToolMessage, "createToolMessage");
    __name(createMediaContentPart, "createMediaContentPart");
    __name(unsupportedModalityPlaceholder, "unsupportedModalityPlaceholder");
    __name(getMediaType, "getMediaType");
    __name(getAudioFormat, "getAudioFormat");
    __name(isContentObject, "isContentObject");
    __name(extractTextFromContentUnion, "extractTextFromContentUnion");
    __name(convertOpenAIResponseToGemini, "convertOpenAIResponseToGemini");
    __name(convertOpenAIChunkToGemini, "convertOpenAIChunkToGemini");
    __name(mapOpenAIFinishReasonToGemini, "mapOpenAIFinishReasonToGemini");
    __name(mapGeminiFinishReasonToOpenAI, "mapGeminiFinishReasonToOpenAI");
    __name(cleanOrphanedToolCalls, "cleanOrphanedToolCalls");
    __name(mergeConsecutiveAssistantMessages, "mergeConsecutiveAssistantMessages");
    OpenAIContentConverter = {
      convertGeminiToolParametersToOpenAI,
      convertGeminiToolsToOpenAI,
      convertGeminiRequestToOpenAI,
      convertGeminiResponseToOpenAI,
      convertOpenAIResponseToGemini,
      convertOpenAIChunkToGemini
    };
  }
});

// node_modules/uuid/dist/esm-node/rng.js
import crypto5 from "crypto";
function rng() {
  if (poolPtr > rnds8Pool.length - 16) {
    crypto5.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 i4 = 0; i4 < 256; ++i4) {
      byteToHex.push((i4 + 256).toString(16).slice(1));
    }
    __name(unsafeStringify, "unsafeStringify");
  }
});

// node_modules/uuid/dist/esm-node/native.js
import crypto6 from "crypto";
var native_default;
var init_native = __esm({
  "node_modules/uuid/dist/esm-node/native.js"() {
    init_esbuild_shims();
    native_default = {
      randomUUID: crypto6.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 i4 = 0; i4 < 16; ++i4) {
      buf[offset + i4] = rnds[i4];
    }
    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 path16 from "node:path";
import { promises as fs19 } from "node:fs";
import * as os8 from "os";
var debugLogger10, OpenAILogger, openaiLogger;
var init_openaiLogger = __esm({
  "packages/core/dist/src/utils/openaiLogger.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm_node();
    init_debugLogger();
    debugLogger10 = 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)
       * @param cwd Optional working directory for resolving relative paths. Defaults to process.cwd().
       *            In ACP mode, process.cwd() may be '/' (filesystem root), so callers should
       *            pass the project working directory from Config.getWorkingDir().
       */
      constructor(customLogDir, cwd6) {
        const baseCwd = cwd6 || process.cwd();
        if (customLogDir) {
          let resolvedPath = customLogDir;
          if (customLogDir === "~" || customLogDir.startsWith("~/")) {
            resolvedPath = path16.join(os8.homedir(), customLogDir.slice(1));
          } else if (!path16.isAbsolute(customLogDir)) {
            resolvedPath = path16.resolve(baseCwd, customLogDir);
          }
          this.logDir = path16.normalize(resolvedPath);
        } else {
          this.logDir = path16.join(baseCwd, "logs", "openai");
        }
      }
      /**
       * Initialize the logger by creating the log directory if it doesn't exist
       */
      async initialize() {
        if (this.initialized)
          return;
        try {
          await fs19.mkdir(this.logDir, { recursive: true });
          this.initialized = true;
        } catch (error40) {
          debugLogger10.error("Failed to initialize OpenAI logger:", error40);
          throw new Error(`Failed to initialize OpenAI logger: ${error40}`);
        }
      }
      /**
       * 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, error40) {
        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 = path16.join(this.logDir, filename);
        const logData = {
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          request: request4,
          response: response || null,
          error: error40 ? {
            message: error40.message,
            stack: error40.stack
          } : null,
          system: {
            hostname: os8.hostname(),
            platform: os8.platform(),
            release: os8.release(),
            nodeVersion: process.version
          }
        };
        try {
          await fs19.writeFile(filePath, JSON.stringify(logData, null, 2), "utf-8");
          return filePath;
        } catch (writeError) {
          debugLogger10.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 fs19.readdir(this.logDir);
          const logFiles = files.filter((file2) => file2.startsWith("openai-") && file2.endsWith(".json")).map((file2) => path16.join(this.logDir, file2)).sort().reverse();
          return limit2 ? logFiles.slice(0, limit2) : logFiles;
        } catch (error40) {
          if (error40.code === "ENOENT") {
            return [];
          }
          debugLogger10.error("Failed to read OpenAI log directory:", error40);
          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 fs19.readFile(filePath, "utf-8");
          return JSON.parse(content);
        } catch (error40) {
          debugLogger10.error(`Failed to read log file ${filePath}:`, error40);
          throw new Error(`Failed to read log file: ${error40}`);
        }
      }
    };
    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_types4();
    init_loggers();
    init_internalPromptIds();
    init_subagentNameContext();
    init_converter();
    init_openaiLogger();
    init_errors();
    LoggingContentGenerator = class {
      static {
        __name(this, "LoggingContentGenerator");
      }
      wrapped;
      config;
      openaiLogger;
      schemaCompliance;
      modalities;
      constructor(wrapped, config2, generatorConfig) {
        this.wrapped = wrapped;
        this.config = config2;
        this.modalities = generatorConfig.modalities;
        if (generatorConfig.enableOpenAILogging) {
          this.openaiLogger = new OpenAILogger(generatorConfig.openAILoggingDir, config2.getWorkingDir());
          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, subagentNameContext.getStore()));
      }
      _logApiResponse(responseId, durationMs, model, prompt_id, usageMetadata, responseText) {
        logApiResponse(this.config, new ApiResponseEvent(responseId, model, durationMs, prompt_id, this.config.getAuthType(), usageMetadata, responseText, subagentNameContext.getStore()));
      }
      _logApiError(responseId, durationMs, error40, model, prompt_id) {
        const errorMessage = getErrorMessage(error40);
        const errorType = getErrorType(error40);
        const errorResponseId = error40?.requestID || error40?.request_id || responseId;
        const errorStatus = getErrorStatus(error40);
        logApiError(this.config, new ApiErrorEvent({
          responseId: errorResponseId,
          model,
          durationMs,
          promptId: prompt_id,
          authType: this.config.getAuthType(),
          errorMessage,
          errorType,
          statusCode: errorStatus,
          subagentName: subagentNameContext.getStore()
        }));
      }
      async generateContent(req, userPromptId) {
        const startTime = Date.now();
        const isInternal = isInternalPromptId(userPromptId);
        if (!isInternal) {
          this.logApiRequest(this.toContents(req.contents), req.model, userPromptId);
        }
        const openaiRequest = isInternal ? void 0 : 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);
          if (!isInternal) {
            await this.logOpenAIInteraction(openaiRequest, response);
          }
          return response;
        } catch (error40) {
          const durationMs = Date.now() - startTime;
          this._logApiError("", durationMs, error40, req.model, userPromptId);
          if (!isInternal) {
            await this.logOpenAIInteraction(openaiRequest, void 0, error40);
          }
          throw error40;
        }
      }
      async generateContentStream(req, userPromptId) {
        const startTime = Date.now();
        const isInternal = isInternalPromptId(userPromptId);
        if (!isInternal) {
          this.logApiRequest(this.toContents(req.contents), req.model, userPromptId);
        }
        const openaiRequest = isInternal ? void 0 : await this.buildOpenAIRequestForLogging(req);
        let stream5;
        try {
          stream5 = await this.wrapped.generateContentStream(req, userPromptId);
        } catch (error40) {
          const durationMs = Date.now() - startTime;
          this._logApiError("", durationMs, error40, req.model, userPromptId);
          if (!isInternal) {
            await this.logOpenAIInteraction(openaiRequest, void 0, error40);
          }
          throw error40;
        }
        return this.loggingStreamWrapper(stream5, startTime, userPromptId, req.model, openaiRequest);
      }
      async *loggingStreamWrapper(stream5, startTime, userPromptId, model, openaiRequest) {
        const isInternal = isInternalPromptId(userPromptId);
        const responses = [];
        let firstResponseId = "";
        let firstModelVersion = "";
        let lastUsageMetadata;
        try {
          for await (const response of stream5) {
            if (!firstResponseId && response.responseId) {
              firstResponseId = response.responseId;
            }
            if (!firstModelVersion && response.modelVersion) {
              firstModelVersion = response.modelVersion;
            }
            if (!isInternal) {
              responses.push(response);
            }
            if (response.usageMetadata) {
              lastUsageMetadata = response.usageMetadata;
            }
            yield response;
          }
          const durationMs = Date.now() - startTime;
          this._logApiResponse(firstResponseId, durationMs, firstModelVersion || model, userPromptId, lastUsageMetadata);
          if (!isInternal) {
            const consolidatedResponse = this.consolidateGeminiResponsesForLogging(responses);
            await this.logOpenAIInteraction(openaiRequest, consolidatedResponse);
          }
        } catch (error40) {
          const durationMs = Date.now() - startTime;
          this._logApiError(firstResponseId, durationMs, error40, firstModelVersion || model, userPromptId);
          if (!isInternal) {
            await this.logOpenAIInteraction(openaiRequest, void 0, error40);
          }
          throw error40;
        }
      }
      async buildOpenAIRequestForLogging(request4) {
        if (!this.openaiLogger) {
          return void 0;
        }
        const requestContext = this.createLoggingRequestContext(request4.model);
        const messages = OpenAIContentConverter.convertGeminiRequestToOpenAI(request4, requestContext, {
          cleanOrphanToolCalls: false
        });
        const openaiRequest = {
          model: request4.model,
          messages
        };
        if (request4.config?.tools) {
          openaiRequest.tools = await OpenAIContentConverter.convertGeminiToolsToOpenAI(request4.config.tools, this.schemaCompliance ?? "auto");
        }
        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;
      }
      createLoggingRequestContext(model) {
        return {
          model,
          modalities: this.modalities ?? {},
          startTime: 0
        };
      }
      async logOpenAIInteraction(openaiRequest, response, error40) {
        if (!this.openaiLogger || !openaiRequest) {
          return;
        }
        const openaiResponse = response ? this.convertGeminiResponseToOpenAIForLogging(response, openaiRequest) : void 0;
        await this.openaiLogger.logInteraction(openaiRequest, openaiResponse, error40 instanceof Error ? error40 : error40 ? new Error(String(error40)) : void 0);
      }
      convertGeminiResponseToOpenAIForLogging(response, openaiRequest) {
        return OpenAIContentConverter.convertGeminiResponseToOpenAI(response, this.createLoggingRequestContext(openaiRequest.model));
      }
      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 parts2 = candidate?.content?.parts ?? [];
          for (const part of parts2) {
            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(parts2) {
        return parts2.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 normalize3(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 findTokenLimit(model, type = "input") {
  const norm = normalize3(model);
  const patterns = type === "output" ? OUTPUT_PATTERNS : PATTERNS;
  for (const [regex3, limit2] of patterns) {
    if (regex3.test(norm)) {
      return limit2;
    }
  }
  return void 0;
}
function hasExplicitOutputLimit(model) {
  const norm = normalize3(model);
  return OUTPUT_PATTERNS.some(([regex3]) => regex3.test(norm));
}
function knownTokenLimit(model, type = "input") {
  return findTokenLimit(model, type);
}
function tokenLimit(model, type = "input") {
  return knownTokenLimit(model, type) ?? (type === "output" ? DEFAULT_OUTPUT_TOKEN_LIMIT : DEFAULT_TOKEN_LIMIT);
}
var DEFAULT_TOKEN_LIMIT, DEFAULT_OUTPUT_TOKEN_LIMIT, CAPPED_DEFAULT_MAX_TOKENS, ESCALATED_MAX_TOKENS, 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 = 32e3;
    CAPPED_DEFAULT_MAX_TOKENS = 8e3;
    ESCALATED_MAX_TOKENS = 64e3;
    LIMITS = {
      "32k": 32768,
      "64k": 65536,
      "128k": 131072,
      "192k": 196608,
      // MiniMax-M2.5 context window
      "200k": 2e5,
      // vendor-declared decimal, used by OpenAI, Anthropic, etc.
      "256k": 262144,
      "272k": 272e3,
      // vendor-declared decimal, GPT-5.x input (400K total - 128K output)
      "384k": 384e3,
      // vendor-declared decimal, DeepSeek V4 max output
      "400k": 4e5,
      // vendor-declared decimal, used by OpenAI GPT-5.x
      "512k": 524288,
      "1m": 1e6,
      // Output token limits (typically much smaller than input limits)
      "4k": 4096,
      "8k": 8192,
      "16k": 16384
    };
    __name(normalize3, "normalize");
    PATTERNS = [
      // -------------------
      // Google Gemini
      // -------------------
      [/^gemini-3/, LIMITS["1m"]],
      // Gemini 3.x (Pro, Flash, 3.1, etc.): 1M
      [/^gemini-/, LIMITS["1m"]],
      // Gemini fallback (1.5, 2.x): 1M
      // -------------------
      // OpenAI
      // -------------------
      [/^gpt-5/, LIMITS["272k"]],
      // GPT-5.x: 272K input (400K total - 128K output)
      [/^gpt-/, LIMITS["128k"]],
      // GPT fallback (4o, 4.1, etc.): 128K
      [/^o\d/, LIMITS["200k"]],
      // o-series (o3, o4-mini, etc.): 200K
      // -------------------
      // Anthropic Claude
      // -------------------
      [/^claude-/, LIMITS["200k"]],
      // All Claude models: 200K
      // -------------------
      // Alibaba / Qwen
      // -------------------
      // Commercial API models (1,000,000 context)
      [/^qwen3-coder-plus/, LIMITS["1m"]],
      [/^qwen3-coder-flash/, LIMITS["1m"]],
      [/^qwen3\.\d/, LIMITS["1m"]],
      [/^qwen-plus-latest$/, LIMITS["1m"]],
      [/^qwen-flash-latest$/, LIMITS["1m"]],
      [/^coder-model$/, LIMITS["1m"]],
      // Commercial API models (256K context)
      [/^qwen3-max/, LIMITS["256k"]],
      // Open-source Qwen3 variants: 256K native
      [/^qwen3-coder-/, LIMITS["256k"]],
      // Qwen fallback (VL, turbo, plus, 2.5, etc.): 128K
      [/^qwen/, LIMITS["256k"]],
      // -------------------
      // DeepSeek
      // -------------------
      [/^deepseek-v4/, LIMITS["1m"]],
      // DeepSeek V4 (flash, pro): 1M
      [/^deepseek/, LIMITS["128k"]],
      // -------------------
      // Zhipu GLM
      // -------------------
      [/^glm-5/, 202752],
      // GLM-5: exact vendor limit
      [/^glm-/, 202752],
      // GLM fallback: 128K
      // -------------------
      // MiniMax
      // -------------------
      [/^minimax-m2\.5/i, LIMITS["192k"]],
      // MiniMax-M2.5: 196,608
      [/^minimax-/i, LIMITS["200k"]],
      // MiniMax fallback: 200K
      // -------------------
      // Moonshot / Kimi
      // -------------------
      [/^kimi-/, LIMITS["256k"]],
      // Kimi fallback: 256K
      // -------------------
      // ByteDance Seed-OSS (512K)
      // -------------------
      [/^seed-oss/, LIMITS["512k"]]
    ];
    OUTPUT_PATTERNS = [
      // Google Gemini
      [/^gemini-3/, LIMITS["64k"]],
      // Gemini 3.x: 64K
      [/^gemini-/, LIMITS["8k"]],
      // Gemini fallback: 8K
      // OpenAI
      [/^gpt-5/, LIMITS["128k"]],
      // GPT-5.x: 128K
      [/^gpt-/, LIMITS["16k"]],
      // GPT fallback: 16K
      [/^o\d/, LIMITS["128k"]],
      // o-series: 128K
      // Anthropic Claude
      [/^claude-opus-4-6/, LIMITS["128k"]],
      // Opus 4.6: 128K
      [/^claude-sonnet-4-6/, LIMITS["64k"]],
      // Sonnet 4.6: 64K
      [/^claude-/, LIMITS["64k"]],
      // Claude fallback: 64K
      // Alibaba / Qwen
      [/^qwen3\.\d/, LIMITS["64k"]],
      [/^coder-model$/, LIMITS["64k"]],
      [/^qwen/, LIMITS["32k"]],
      // Qwen fallback (VL, turbo, plus, etc.): 8K
      // DeepSeek
      [/^deepseek-v4/, LIMITS["384k"]],
      // DeepSeek V4 (flash, pro): 384K
      [/^deepseek-reasoner/, LIMITS["64k"]],
      [/^deepseek-r1/, LIMITS["64k"]],
      [/^deepseek-chat/, LIMITS["8k"]],
      // Zhipu GLM
      [/^glm-5/, LIMITS["16k"]],
      [/^glm-4\.7/, LIMITS["16k"]],
      // MiniMax
      [/^minimax-m2\.5/i, LIMITS["64k"]],
      // Kimi
      [/^kimi-k2\.5/, LIMITS["32k"]]
    ];
    __name(findTokenLimit, "findTokenLimit");
    __name(hasExplicitOutputLimit, "hasExplicitOutputLimit");
    __name(knownTokenLimit, "knownTokenLimit");
    __name(tokenLimit, "tokenLimit");
  }
});

// packages/core/dist/src/core/modalityDefaults.js
function defaultModalities(model) {
  const norm = normalize3(model);
  for (const [regex3, modalities] of MODALITY_PATTERNS) {
    if (regex3.test(norm)) {
      return { ...modalities };
    }
  }
  return {};
}
var FULL_MULTIMODAL, MODALITY_PATTERNS;
var init_modalityDefaults = __esm({
  "packages/core/dist/src/core/modalityDefaults.js"() {
    "use strict";
    init_esbuild_shims();
    init_tokenLimits();
    FULL_MULTIMODAL = {
      image: true,
      pdf: true,
      audio: true,
      video: true
    };
    MODALITY_PATTERNS = [
      // -------------------
      // Google Gemini — full multimodal
      // -------------------
      [/^gemini-3/, FULL_MULTIMODAL],
      [/^gemini-/, FULL_MULTIMODAL],
      // -------------------
      // OpenAI — image by default for all gpt/o-series models
      // -------------------
      [/^gpt-5/, { image: true }],
      [/^gpt-/, { image: true }],
      [/^o\d/, { image: true }],
      // -------------------
      // Anthropic Claude — image + pdf
      // -------------------
      [/^claude-/, { image: true, pdf: true }],
      // -------------------
      // Alibaba / Qwen
      // -------------------
      // Qwen3.5-Plus, Qwen3.6-Plus: image + video support
      [/^qwen3\.5-plus/, { image: true, video: true }],
      [/^qwen3\.6-plus/, { image: true, video: true }],
      [/^coder-model$/, { image: true, video: true }],
      // Qwen VL (vision-language) models: image + video
      [/^qwen-vl-/, { image: true, video: true }],
      [/^qwen3-vl-/, { image: true, video: true }],
      // Qwen coder / text models: text-only
      [/^qwen3-coder-/, {}],
      [/^qwen/, {}],
      // -------------------
      // DeepSeek — text-only
      // -------------------
      [/^deepseek/, {}],
      // -------------------
      // Zhipu GLM
      // -------------------
      [/^glm-4\.5v/, { image: true }],
      [/^glm-5(?:-|$)/, {}],
      [/^glm-/, {}],
      // -------------------
      // MiniMax — text-only
      // -------------------
      [/^minimax-/, {}],
      // -------------------
      // Moonshot / Kimi
      // -------------------
      [/^kimi-k2\.5/, { image: true, video: true }],
      [/^kimi-/, {}]
    ];
    __name(defaultModalities, "defaultModalities");
  }
});

// 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_types5 = __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",
      "retryErrorCodes",
      "enableCacheControl",
      "schemaCompliance",
      "reasoning",
      "contextWindowSize",
      "customHeaders",
      "extra_body",
      "modalities",
      "splitToolMedia"
    ];
    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.6 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 debugLogger11, ModelRegistry;
var init_modelRegistry = __esm({
  "packages/core/dist/src/models/modelRegistry.js"() {
    "use strict";
    init_esbuild_shims();
    init_contentGenerator();
    init_modalityDefaults();
    init_tokenLimits();
    init_constants2();
    init_types5();
    init_models();
    init_constants3();
    init_debugLogger();
    init_constants3();
    debugLogger11 = 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) {
              debugLogger11.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)) {
            debugLogger11.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 ?? tokenLimit(model.id),
          modalities: model.generationConfig.modalities ?? defaultModalities(model.id),
          baseUrl: model.baseUrl,
          envKey: model.envKey
        }));
      }
      /**
       * 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) {
              debugLogger11.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_modalityDefaults();
    init_modelRegistry();
    init_types5();
    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 out2 = {};
        for (const key of Object.keys(value)) {
          out2[key] = _ModelsConfig.deepClone(value[key]);
        }
        return out2;
      }
      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);
      }
      /**
       * Get a fully resolved provider model config for the given authType/modelId.
       * Returns undefined for raw runtime models that are not present in the registry.
       */
      getResolvedModel(authType, modelId) {
        return this.modelRegistry.getModel(authType, modelId);
      }
      /**
       * Set model programmatically (e.g., VLM auto-switch, fallback).
       * Supports both registry models and raw model IDs.
       */
      async setModel(newModel, metadata2) {
        if (this.currentAuthType === AuthType2.QWEN_OAUTH && newModel === DEFAULT_QWEN_MODEL) {
          this.strictModelProviderSelection = false;
          this._generationConfig.model = newModel;
          this.generationConfigSources["model"] = {
            kind: "programmatic",
            detail: metadata2?.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: metadata2?.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 (error40) {
          this.rollbackToStateSnapshot(rollbackSnapshot);
          throw error40;
        }
      }
      /**
       * 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"
          };
        }
        if (gc.modalities === void 0) {
          this._generationConfig.modalities = defaultModalities(model.id);
          this.generationConfigSources["modalities"] = {
            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) {
            const hasBeenApplied = this.generationConfigSources["baseUrl"]?.kind === "modelProviders";
            const isProviderChanged = hasBeenApplied && (this._generationConfig.apiKeyEnvKey !== resolved.envKey || this._generationConfig.baseUrl !== resolved.baseUrl);
            const isUnchanged = previousAuthType === authType && this._generationConfig.model === modelId && !isProviderChanged;
            const savedApiKey = isUnchanged ? this._generationConfig.apiKey : void 0;
            const savedApiKeySource = isUnchanged ? this.generationConfigSources["apiKey"] ? { ...this.generationConfigSources["apiKey"] } : void 0 : void 0;
            this.applyResolvedModelDefaults(resolved);
            if (isUnchanged && !this._generationConfig.apiKey && savedApiKey) {
              this._generationConfig.apiKey = savedApiKey;
              if (savedApiKeySource) {
                this.generationConfigSources["apiKey"] = savedApiKeySource;
              }
            }
            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 (error40) {
          this.rollbackToStateSnapshot(rollbackSnapshot);
          throw error40;
        }
      }
      /**
       * 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 __classPrivateFieldGet2(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(__classPrivateFieldGet2, "__classPrivateFieldGet");
  }
});

// node_modules/openai/internal/utils/uuid.mjs
var uuid4;
var init_uuid = __esm({
  "node_modules/openai/internal/utils/uuid.mjs"() {
    init_esbuild_shims();
    uuid4 = /* @__PURE__ */ __name(function() {
      const { crypto: crypto18 } = globalThis;
      if (crypto18?.randomUUID) {
        uuid4 = crypto18.randomUUID.bind(crypto18);
        return crypto18.randomUUID();
      }
      const u8 = new Uint8Array(1);
      const randomByte = crypto18 ? () => crypto18.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
      return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c4) => (+c4 ^ randomByte() & 15 >> +c4 / 4).toString(16));
    }, "uuid4");
  }
});

// node_modules/openai/internal/errors.mjs
function isAbortError2(err2) {
  return typeof err2 === "object" && err2 !== null && // Spec-compliant fetch implementations
  ("name" in err2 && err2.name === "AbortError" || // Expo fetch
  "message" in err2 && String(err2.message).includes("FetchRequestCanceledException"));
}
var castToError;
var init_errors2 = __esm({
  "node_modules/openai/internal/errors.mjs"() {
    init_esbuild_shims();
    __name(isAbortError2, "isAbortError");
    castToError = /* @__PURE__ */ __name((err2) => {
      if (err2 instanceof Error)
        return err2;
      if (typeof err2 === "object" && err2 !== null) {
        try {
          if (Object.prototype.toString.call(err2) === "[object Error]") {
            const error40 = new Error(err2.message, err2.cause ? { cause: err2.cause } : {});
            if (err2.stack)
              error40.stack = err2.stack;
            if (err2.cause && !error40.cause)
              error40.cause = err2.cause;
            if (err2.name)
              error40.name = err2.name;
            return error40;
          }
        } catch {
        }
        try {
          return new Error(JSON.stringify(err2));
        } catch {
        }
      }
      return new Error(err2);
    }, "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, error40, message, headers) {
        super(`${_APIError.makeMessage(status, error40, message)}`);
        this.status = status;
        this.headers = headers;
        this.requestID = headers?.get("x-request-id");
        this.error = error40;
        const data = error40;
        this.code = data?.["code"];
        this.param = data?.["param"];
        this.type = data?.["type"];
      }
      static makeMessage(status, error40, message) {
        const msg = error40?.message ? typeof error40.message === "string" ? error40.message : JSON.stringify(error40.message) : error40 ? JSON.stringify(error40) : 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 error40 = errorResponse?.["error"];
        if (status === 400) {
          return new BadRequestError2(status, error40, message, headers);
        }
        if (status === 401) {
          return new AuthenticationError(status, error40, message, headers);
        }
        if (status === 403) {
          return new PermissionDeniedError(status, error40, message, headers);
        }
        if (status === 404) {
          return new NotFoundError(status, error40, message, headers);
        }
        if (status === 409) {
          return new ConflictError(status, error40, message, headers);
        }
        if (status === 422) {
          return new UnprocessableEntityError(status, error40, message, headers);
        }
        if (status === 429) {
          return new RateLimitError(status, error40, message, headers);
        }
        if (status >= 500) {
          return new InternalServerError(status, error40, message, headers);
        }
        return new _APIError(status, error40, 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((url3) => {
      return startsWithSchemeRegexp.test(url3);
    }, "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((name4, n3) => {
      if (typeof n3 !== "number" || !Number.isInteger(n3)) {
        throw new OpenAIError(`${name4} must be an integer`);
      }
      if (n3 < 0) {
        throw new OpenAIError(`${name4} must be a positive integer`);
      }
      return n3;
    }, "validatePositiveInteger");
    safeJSON = /* @__PURE__ */ __name((text) => {
      try {
        return JSON.parse(text);
      } catch (err2) {
        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((resolve42) => setTimeout(resolve42, ms)), "sleep");
  }
});

// node_modules/openai/version.mjs
var VERSION3;
var init_version2 = __esm({
  "node_modules/openai/version.mjs"() {
    init_esbuild_shims();
    VERSION3 = "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": VERSION3,
          "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": VERSION3,
          "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": VERSION3,
          "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": 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(getBrowserInfo, "getBrowserInfo");
    normalizeArch = /* @__PURE__ */ __name((arch3) => {
      if (arch3 === "x32")
        return "x32";
      if (arch3 === "x86_64" || arch3 === "x64")
        return "x64";
      if (arch3 === "arm")
        return "arm";
      if (arch3 === "aarch64" || arch3 === "arm64")
        return "arm64";
      if (arch3)
        return `other:${arch3}`;
      return "unknown";
    }, "normalizeArch");
    normalizePlatform = /* @__PURE__ */ __name((platform15) => {
      platform15 = platform15.toLowerCase();
      if (platform15.includes("ios"))
        return "iOS";
      if (platform15 === "android")
        return "Android";
      if (platform15 === "darwin")
        return "MacOS";
      if (platform15 === "win32")
        return "Windows";
      if (platform15 === "freebsd")
        return "FreeBSD";
      if (platform15 === "openbsd")
        return "OpenBSD";
      if (platform15 === "linux")
        return "Linux";
      if (platform15)
        return `Other:${platform15}`;
      return "Unknown";
    }, "normalizePlatform");
    getPlatformHeaders = /* @__PURE__ */ __name(() => {
      return _platformHeaders ?? (_platformHeaders = getPlatformProperties());
    }, "getPlatformHeaders");
  }
});

// node_modules/openai/internal/shims.mjs
function getDefaultFetch() {
  if (typeof fetch !== "undefined") {
    return fetch;
  }
  throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
}
function makeReadableStream(...args2) {
  const ReadableStream6 = globalThis.ReadableStream;
  if (typeof ReadableStream6 === "undefined") {
    throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
  }
  return new ReadableStream6(...args2);
}
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(stream5) {
  if (stream5[Symbol.asyncIterator])
    return stream5;
  const reader = stream5.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(stream5) {
  if (stream5 === null || typeof stream5 !== "object")
    return;
  if (stream5[Symbol.asyncIterator]) {
    await stream5[Symbol.asyncIterator]().return?.();
    return;
  }
  const reader = stream5.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: body2 }) => {
      return {
        bodyHeaders: {
          "content-type": "application/json"
        },
        body: JSON.stringify(body2)
      };
    }, "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 i4 = 0; i4 < val.length; i4 += 1) {
      mapped.push(fn(val[i4]));
    }
    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 i4 = 0; i4 < 256; ++i4) {
        array2.push("%" + ((i4 < 16 ? "0" : "") + i4.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 out2 = "";
      for (let j2 = 0; j2 < string4.length; j2 += limit) {
        const segment = string4.length >= limit ? string4.slice(j2, j2 + limit) : string4;
        const arr = [];
        for (let i4 = 0; i4 < segment.length; ++i4) {
          let c4 = segment.charCodeAt(i4);
          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(i4);
            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;
          }
          i4 += 1;
          c4 = 65536 + ((c4 & 1023) << 10 | segment.charCodeAt(i4) & 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];
        }
        out2 += arr.join("");
      }
      return out2;
    }, "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, filter5, 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 filter5 === "function") {
    obj = filter5(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(filter5)) {
    obj_keys = filter5;
  } 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,
      filter5,
      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 filter5 = defaults.filter;
  if (typeof opts.filter === "function" || isArray(opts.filter)) {
    filter5 = 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: filter5,
    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 filter5;
  if (typeof options2.filter === "function") {
    filter5 = options2.filter;
    obj = filter5("", obj);
  } else if (isArray(options2.filter)) {
    filter5 = options2.filter;
    obj_keys = filter5;
  }
  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 i4 = 0; i4 < obj_keys.length; ++i4) {
    const key = obj_keys[i4];
    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(date5) {
        return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date5);
      },
      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 i4 = startIndex ?? 0; i4 < buffer.length; i4++) {
    if (buffer[i4] === newline2) {
      return { preceding: i4, index: i4 + 1, carriage: false };
    }
    if (buffer[i4] === carriage) {
      return { preceding: i4, index: i4 + 1, carriage: true };
    }
  }
  return null;
}
function findDoubleNewlineIndex(buffer) {
  const newline2 = 10;
  const carriage = 13;
  for (let i4 = 0; i4 < buffer.length - 1; i4++) {
    if (buffer[i4] === newline2 && buffer[i4 + 1] === newline2) {
      return i4 + 2;
    }
    if (buffer[i4] === carriage && buffer[i4 + 1] === carriage) {
      return i4 + 2;
    }
    if (buffer[i4] === carriage && buffer[i4 + 1] === newline2 && i4 + 3 < buffer.length && buffer[i4 + 2] === carriage && buffer[i4 + 3] === newline2) {
      return i4 + 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([__classPrivateFieldGet2(this, _LineDecoder_buffer, "f"), binaryChunk]), "f");
        const lines = [];
        let patternIndex;
        while ((patternIndex = findNewlineIndex(__classPrivateFieldGet2(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
          if (patternIndex.carriage && __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f") == null) {
            __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
            continue;
          }
          if (__classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
            lines.push(decodeUTF8(__classPrivateFieldGet2(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
            __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet2(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f")), "f");
            __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
            continue;
          }
          const endIndex = __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
          const line = decodeUTF8(__classPrivateFieldGet2(this, _LineDecoder_buffer, "f").subarray(0, endIndex));
          lines.push(line);
          __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet2(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f");
          __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
        }
        return lines;
      }
      flush() {
        if (!__classPrivateFieldGet2(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(([name4, value]) => [
          name4,
          name4.toLowerCase() === "authorization" || name4.toLowerCase() === "cookie" || name4.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(iterator2) {
  let data = new Uint8Array();
  for await (const chunk of iterator2) {
    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(iterator2, controller, client) {
        this.iterator = iterator2;
        _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* iterator2() {
          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(iterator2, "iterator");
        return new _Stream(iterator2, 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* iterator2() {
          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(iterator2, "iterator");
        return new _Stream(iterator2, 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 iterator2 = this.iterator();
        const teeIterator = /* @__PURE__ */ __name((queue) => {
          return {
            next: /* @__PURE__ */ __name(() => {
              if (queue.length === 0) {
                const result = iterator2.next();
                left3.push(result);
                right3.push(result);
              }
              return queue.shift();
            }, "next")
          };
        }, "teeIterator");
        return [
          new _Stream(() => teeIterator(left3), this.controller, __classPrivateFieldGet2(this, _Stream_client, "f")),
          new _Stream(() => teeIterator(right3), this.controller, __classPrivateFieldGet2(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 (err2) {
              ctrl.error(err2);
            }
          },
          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 body2 = 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 json3 = await response.json();
      return addRequestID(json3, response);
    }
    const text = await response.text();
    return text;
  })();
  loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
    retryOfRequestLogID,
    url: response.url,
    status: response.status,
    body: body2,
    durationMs: Date.now() - startTime
  }));
  return body2;
}
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((resolve42) => {
          resolve42(null);
        });
        this.responsePromise = responsePromise;
        this.parseResponse = parseResponse2;
        _APIPromise_client.set(this, void 0);
        __classPrivateFieldSet(this, _APIPromise_client, client, "f");
      }
      _thenUnwrap(transform2) {
        return new _APIPromise(__classPrivateFieldGet2(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(__classPrivateFieldGet2(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, body2, options2) {
        _AbstractPage_client.set(this, void 0);
        __classPrivateFieldSet(this, _AbstractPage_client, client, "f");
        this.options = options2;
        this.response = response;
        this.body = body2;
      }
      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 __classPrivateFieldGet2(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, body2, options2) {
        super(client, response, body2, options2);
        this.data = body2.data || [];
        this.object = body2.object;
      }
      getPaginatedItems() {
        return this.data ?? [];
      }
      nextPageRequestOptions() {
        return null;
      }
    };
    CursorPage = class extends AbstractPage {
      static {
        __name(this, "CursorPage");
      }
      constructor(client, response, body2, options2) {
        super(client, response, body2, options2);
        this.data = body2.data || [];
        this.has_more = body2.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 promise2 = (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, promise2);
  return promise2;
}
var checkFileSupport, isAsyncIterable, multipartFormRequestOptions, supportsFormDataMap, createForm, isNamedBlob, addFormValue;
var init_uploads = __esm({
  "node_modules/openai/internal/uploads.mjs"() {
    init_esbuild_shims();
    init_shims();
    checkFileSupport = /* @__PURE__ */ __name(() => {
      if (typeof File === "undefined") {
        const { process: process51 } = globalThis;
        const isOldNode = typeof process51?.versions?.node === "string" && parseInt(process51.versions.node.split(".")) < 20;
        throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
      }
    }, "checkFileSupport");
    __name(makeFile, "makeFile");
    __name(getName, "getName");
    isAsyncIterable = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterable");
    multipartFormRequestOptions = /* @__PURE__ */ __name(async (opts, fetch5) => {
      return { ...opts, body: await createForm(opts.body, fetch5) };
    }, "multipartFormRequestOptions");
    supportsFormDataMap = /* @__PURE__ */ new WeakMap();
    __name(supportsFormData, "supportsFormData");
    createForm = /* @__PURE__ */ __name(async (body2, 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(body2 || {}).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(([name4, prop]) => addFormValue(form, `${key}[${name4}]`, 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, name4, 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();
    name4 || (name4 = new URL(value.url).pathname.split(/[\\/]/).pop());
    return makeFile(await getBytes(blob), name4, options2);
  }
  const parts2 = await getBytes(value);
  name4 || (name4 = getName(value));
  if (!options2?.type) {
    const type = parts2.find((part) => typeof part === "object" && "type" in part && part.type);
    if (typeof type === "string") {
      options2 = { ...options2, type };
    }
  }
  return makeFile(parts2, name4, options2);
}
async function getBytes(value) {
  let parts2 = [];
  if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
  value instanceof ArrayBuffer) {
    parts2.push(value);
  } else if (isBlobLike(value)) {
    parts2.push(value instanceof Blob ? value : await value.arrayBuffer());
  } else if (isAsyncIterable(value)) {
    for await (const chunk of value) {
      parts2.push(...await getBytes(chunk));
    }
  } else {
    const constructor = value?.constructor?.name;
    throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`);
  }
  return parts2;
}
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, path17;
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 path150(statics, ...params) {
      if (statics.length === 1)
        return statics[0];
      let postPath = false;
      const invalidSegments = [];
      const path151 = 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 = path151.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")}
${path151}
${underline}`);
      }
      return path151;
    }, "path"), "createPathTagFunction");
    path17 = /* @__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(path17`/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((resolve42, reject) => {
          __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve42, "f");
          __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f");
        }), "f");
        __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve42, reject) => {
          __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve42, "f");
          __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f");
        }), "f");
        __classPrivateFieldGet2(this, _EventStream_connectedPromise, "f").catch(() => {
        });
        __classPrivateFieldGet2(this, _EventStream_endPromise, "f").catch(() => {
        });
      }
      _run(executor) {
        setTimeout(() => {
          executor().then(() => {
            this._emitFinal();
            this._emit("end");
          }, __classPrivateFieldGet2(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
        }, 0);
      }
      _connected() {
        if (this.ended)
          return;
        __classPrivateFieldGet2(this, _EventStream_resolveConnectedPromise, "f").call(this);
        this._emit("connect");
      }
      get ended() {
        return __classPrivateFieldGet2(this, _EventStream_ended, "f");
      }
      get errored() {
        return __classPrivateFieldGet2(this, _EventStream_errored, "f");
      }
      get aborted() {
        return __classPrivateFieldGet2(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 = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet2(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 = __classPrivateFieldGet2(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 = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet2(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((resolve42, reject) => {
          __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
          if (event !== "error")
            this.once("error", reject);
          this.once(event, resolve42);
        });
      }
      async done() {
        __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
        await __classPrivateFieldGet2(this, _EventStream_endPromise, "f");
      }
      _emit(event, ...args2) {
        if (__classPrivateFieldGet2(this, _EventStream_ended, "f")) {
          return;
        }
        if (event === "end") {
          __classPrivateFieldSet(this, _EventStream_ended, true, "f");
          __classPrivateFieldGet2(this, _EventStream_resolveEndPromise, "f").call(this);
        }
        const listeners = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event];
        if (listeners) {
          __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] = listeners.filter((l3) => !l3.once);
          listeners.forEach(({ listener }) => listener(...args2));
        }
        if (event === "abort") {
          const error40 = args2[0];
          if (!__classPrivateFieldGet2(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error40);
          }
          __classPrivateFieldGet2(this, _EventStream_rejectConnectedPromise, "f").call(this, error40);
          __classPrivateFieldGet2(this, _EventStream_rejectEndPromise, "f").call(this, error40);
          this._emit("end");
          return;
        }
        if (event === "error") {
          const error40 = args2[0];
          if (!__classPrivateFieldGet2(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error40);
          }
          __classPrivateFieldGet2(this, _EventStream_rejectConnectedPromise, "f").call(this, error40);
          __classPrivateFieldGet2(this, _EventStream_rejectEndPromise, "f").call(this, error40);
          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(error40) {
      __classPrivateFieldSet(this, _EventStream_errored, true, "f");
      if (error40 instanceof Error && error40.name === "AbortError") {
        error40 = new APIUserAbortError();
      }
      if (error40 instanceof APIUserAbortError) {
        __classPrivateFieldSet(this, _EventStream_aborted, true, "f");
        return this._emit("abort", error40);
      }
      if (error40 instanceof OpenAIError) {
        return this._emit("error", error40);
      }
      if (error40 instanceof Error) {
        const openAIError = new OpenAIError(error40.message);
        openAIError.cause = error40;
        return this._emit("error", openAIError);
      }
      return this._emit("error", new OpenAIError(String(error40)));
    }, "_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 __classPrivateFieldGet2(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 __classPrivateFieldGet2(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 __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
      }
      async finalFunctionToolCallResult() {
        await this.done();
        return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
      }
      async totalUsage() {
        await this.done();
        return __classPrivateFieldGet2(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 = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
        if (finalMessage)
          this._emit("finalMessage", finalMessage);
        const finalContent = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
        if (finalContent)
          this._emit("finalContent", finalContent);
        const finalFunctionCall = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
        if (finalFunctionCall)
          this._emit("finalFunctionToolCall", finalFunctionCall);
        const finalFunctionCallResult = __classPrivateFieldGet2(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", __classPrivateFieldGet2(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());
        }
        __classPrivateFieldGet2(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: stream5, ...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 i4 = 0; i4 < maxChatCompletions; ++i4) {
          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: name4, arguments: args2 } = tool_call.function;
            const fn = functionsByName[name4];
            if (!fn) {
              const content2 = `Invalid tool_call: ${JSON.stringify(name4)}. Available options are: ${Object.keys(functionsByName).map((name5) => JSON.stringify(name5)).join(", ")}. Please try again`;
              this._addMessage({ role, tool_call_id, content: content2 });
              continue;
            } else if (singleFunctionToCall && singleFunctionToCall !== name4) {
              const content2 = `Invalid tool_call: ${JSON.stringify(name4)}. ${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(args2) : args2;
            } catch (error40) {
              const content2 = error40 instanceof Error ? error40.message : String(error40);
              this._addMessage({ role, tool_call_id, content: content2 });
              continue;
            }
            const rawContent = await fn.function(parsed, this);
            const content = __classPrivateFieldGet2(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 __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
    }, "_AbstractChatCompletionRunner_getFinalContent"), _AbstractChatCompletionRunner_getFinalMessage = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_getFinalMessage2() {
      let i4 = this.messages.length;
      while (i4-- > 0) {
        const message = this.messages[i4];
        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 i4 = this.messages.length - 1; i4 >= 0; i4--) {
        const message = this.messages[i4];
        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 i4 = this.messages.length - 1; i4 >= 0; i4--) {
        const message = this.messages[i4];
        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 start2 = 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(start2, ++index - Number(escape7)));
          } catch (e4) {
            throwMalformedError(String(e4));
          }
        } else if (Allow.STR & allow) {
          try {
            return JSON.parse(jsonString.substring(start2, index - Number(escape7)) + '"');
          } catch (e4) {
            return JSON.parse(jsonString.substring(start2, 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 start2 = 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(start2, index));
        } catch (e4) {
          if (jsonString.substring(start2, index) === "-" && Allow.NUM & allow)
            markPartialJSON("Not sure what '-' is");
          try {
            return JSON.parse(jsonString.substring(start2, 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: args2, name: name4 } = function_call;
        if (args2 == null) {
          throw new OpenAIError(`missing function_call.arguments for choice ${index}`);
        }
        if (!name4) {
          throw new OpenAIError(`missing function_call.name for choice ${index}`);
        }
        return {
          ...choiceRest,
          message: {
            content,
            function_call: { arguments: args2, name: name4 },
            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, i4) => {
              const { function: fn, type, id: id2, ...toolRest } = tool_call;
              const { arguments: args2, name: name4, ...fnRest } = fn || {};
              if (id2 == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i4}].id
${str(snapshot)}`);
              }
              if (type == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i4}].type
${str(snapshot)}`);
              }
              if (name4 == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i4}].function.name
${str(snapshot)}`);
              }
              if (args2 == null) {
                throw new OpenAIError(`missing choices[${index}].tool_calls[${i4}].function.arguments
${str(snapshot)}`);
              }
              return { ...toolRest, id: id2, type, function: { ...fnRest, name: name4, arguments: args2 } };
            })
          }
        };
      }
      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 __classPrivateFieldGet2(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(stream5) {
        const runner = new _ChatCompletionStream(null);
        runner._run(() => runner._fromReadableStream(stream5));
        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());
        }
        __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
        const stream5 = await client.chat.completions.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal });
        this._connected();
        for await (const chunk of stream5) {
          __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addChatCompletion(__classPrivateFieldGet2(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());
        }
        __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
        this._connected();
        const stream5 = Stream3.fromReadableStream(readableStream, this.controller);
        let chatId;
        for await (const chunk of stream5) {
          if (chatId && chatId !== chunk.id) {
            this._addChatCompletion(__classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
          }
          __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
          chatId = chunk.id;
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addChatCompletion(__classPrivateFieldGet2(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 = __classPrivateFieldGet2(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
        };
        __classPrivateFieldGet2(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 = __classPrivateFieldGet2(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 = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
          if (choiceSnapshot.finish_reason) {
            __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
            if (state.current_tool_call_index != null) {
              __classPrivateFieldGet2(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) {
              __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
              if (state.current_tool_call_index != null) {
                __classPrivateFieldGet2(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 = __classPrivateFieldGet2(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 = __classPrivateFieldGet2(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 = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
        if (choiceSnapshot.message.content && !state.content_done) {
          state.content_done = true;
          const responseFormat = __classPrivateFieldGet2(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 = __classPrivateFieldGet2(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, __classPrivateFieldGet2(this, _ChatCompletionStream_params, "f"));
      }, "_ChatCompletionStream_endRequest"), _ChatCompletionStream_getAutoParseableResponseFormat = /* @__PURE__ */ __name(function _ChatCompletionStream_getAutoParseableResponseFormat2() {
        const responseFormat = __classPrivateFieldGet2(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 = __classPrivateFieldGet2(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 (__classPrivateFieldGet2(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet2(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 && __classPrivateFieldGet2(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(__classPrivateFieldGet2(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", (err2) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err2);
          }
          readQueue.length = 0;
        });
        this.on("error", (err2) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err2);
          }
          readQueue.length = 0;
        });
        return {
          next: /* @__PURE__ */ __name(async () => {
            if (!pushQueue.length) {
              if (done) {
                return { value: void 0, done: true };
              }
              return new Promise((resolve42, reject) => readQueue.push({ resolve: resolve42, 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 stream5 = new Stream3(this[Symbol.asyncIterator].bind(this), this.controller);
        return stream5.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(stream5) {
        const runner = new _ChatCompletionStreamingRunner(null);
        runner._run(() => runner._fromReadableStream(stream5));
        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(body2, options2) {
        return this._client.post("/chat/completions", { body: body2, ...options2, stream: body2.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(path17`/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, body2, options2) {
        return this._client.post(path17`/chat/completions/${completionID}`, { body: body2, ...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(path17`/chat/completions/${completionID}`, options2);
      }
      parse(body2, options2) {
        validateInputTools(body2.tools);
        return this._client.chat.completions.create(body2, {
          ...options2,
          headers: {
            ...options2?.headers,
            "X-Stainless-Helper-Method": "chat.completions.parse"
          }
        })._thenUnwrap((completion3) => parseChatCompletion(completion3, body2));
      }
      runTools(body2, options2) {
        if (body2.stream) {
          return ChatCompletionStreamingRunner.runTools(this._client, body2, options2);
        }
        return ChatCompletionRunner.runTools(this._client, body2, options2);
      }
      /**
       * Creates a chat completion stream
       */
      stream(body2, options2) {
        return ChatCompletionStream.createChatCompletion(this._client, body2, 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 name4 of nulls) {
      yield [name4, 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 name4 = row[0];
    if (typeof name4 !== "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 [name4, null];
      }
      yield [name4, 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 [name4, value] of iterateHeaders(headers)) {
          const lowerName = name4.toLowerCase();
          if (!seenHeaders.has(lowerName)) {
            targetHeaders.delete(name4);
            seenHeaders.add(lowerName);
          }
          if (value === null) {
            targetHeaders.delete(name4);
            nullHeaders.add(lowerName);
          } else {
            targetHeaders.append(name4, 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(body2, options2) {
        return this._client.post("/audio/speech", {
          body: body2,
          ...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(body2, options2) {
        return this._client.post("/audio/transcriptions", multipartFormRequestOptions({
          body: body2,
          ...options2,
          stream: body2.stream ?? false,
          __metadata: { model: body2.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(body2, options2) {
        return this._client.post("/audio/translations", multipartFormRequestOptions({ body: body2, ...options2, __metadata: { model: body2.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(body2, options2) {
        return this._client.post("/batches", { body: body2, ...options2 });
      }
      /**
       * Retrieves a batch.
       */
      retrieve(batchID, options2) {
        return this._client.get(path17`/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(path17`/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(body2, options2) {
        return this._client.post("/assistants", {
          body: body2,
          ...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(path17`/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, body2, options2) {
        return this._client.post(path17`/assistants/${assistantID}`, {
          body: body2,
          ...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(path17`/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(body2, options2) {
        return this._client.post("/realtime/sessions", {
          body: body2,
          ...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(body2, options2) {
        return this._client.post("/realtime/transcription_sessions", {
          body: body2,
          ...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, body2, options2) {
        return this._client.post(path17`/threads/${threadID}/messages`, {
          body: body2,
          ...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(path17`/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, ...body2 } = params;
        return this._client.post(path17`/threads/${thread_id}/messages/${messageID}`, {
          body: body2,
          ...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(path17`/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(path17`/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(path17`/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(path17`/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 i4 = 0; i4 < len; i4++) {
          bytes[i4] = binaryStr.charCodeAt(i4);
        }
        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((env6) => {
      if (typeof globalThis.process !== "undefined") {
        return globalThis.process.env?.[env6]?.trim() ?? void 0;
      }
      if (typeof globalThis.Deno !== "undefined") {
        return globalThis.Deno.env?.get?.(env6)?.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", (err2) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err2);
          }
          readQueue.length = 0;
        });
        this.on("error", (err2) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err2);
          }
          readQueue.length = 0;
        });
        return {
          next: /* @__PURE__ */ __name(async () => {
            if (!pushQueue.length) {
              if (done) {
                return { value: void 0, done: true };
              }
              return new Promise((resolve42, reject) => readQueue.push({ resolve: resolve42, 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(stream5) {
        const runner = new _a();
        runner._run(() => runner._fromReadableStream(stream5));
        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 stream5 = Stream3.fromReadableStream(readableStream, this.controller);
        for await (const event of stream5) {
          __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
      }
      toReadableStream() {
        const stream5 = new Stream3(this[Symbol.asyncIterator].bind(this), this.controller);
        return stream5.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(run2, runId, params, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        const body2 = { ...params, stream: true };
        const stream5 = await run2.submitToolOutputs(runId, body2, {
          ...options2,
          signal: this.controller.signal
        });
        this._connected();
        for await (const event of stream5) {
          __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addRun(__classPrivateFieldGet2(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 __classPrivateFieldGet2(this, _AssistantStream_currentEvent, "f");
      }
      currentRun() {
        return __classPrivateFieldGet2(this, _AssistantStream_currentRunSnapshot, "f");
      }
      currentMessageSnapshot() {
        return __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f");
      }
      currentRunStepSnapshot() {
        return __classPrivateFieldGet2(this, _AssistantStream_currentRunStepSnapshot, "f");
      }
      async finalRunSteps() {
        await this.done();
        return Object.values(__classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f"));
      }
      async finalMessages() {
        await this.done();
        return Object.values(__classPrivateFieldGet2(this, _AssistantStream_messageSnapshots, "f"));
      }
      async finalRun() {
        await this.done();
        if (!__classPrivateFieldGet2(this, _AssistantStream_finalRun, "f"))
          throw Error("Final run was not received.");
        return __classPrivateFieldGet2(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 body2 = { ...params, stream: true };
        const stream5 = await thread.createAndRun(body2, { ...options2, signal: this.controller.signal });
        this._connected();
        for await (const event of stream5) {
          __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
      }
      async _createAssistantStream(run2, threadId, params, options2) {
        const signal = options2?.signal;
        if (signal) {
          if (signal.aborted)
            this.controller.abort();
          signal.addEventListener("abort", () => this.controller.abort());
        }
        const body2 = { ...params, stream: true };
        const stream5 = await run2.create(threadId, body2, { ...options2, signal: this.controller.signal });
        this._connected();
        for await (const event of stream5) {
          __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return this._addRun(__classPrivateFieldGet2(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(run2) {
        return run2;
      }
      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");
      __classPrivateFieldGet2(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":
          __classPrivateFieldGet2(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":
          __classPrivateFieldGet2(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":
          __classPrivateFieldGet2(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 (!__classPrivateFieldGet2(this, _AssistantStream_finalRun, "f"))
        throw Error("Final run has not been received");
      return __classPrivateFieldGet2(this, _AssistantStream_finalRun, "f");
    }, "_AssistantStream_endRequest"), _AssistantStream_handleMessage = /* @__PURE__ */ __name(function _AssistantStream_handleMessage2(event) {
      const [accumulatedMessage, newContent] = __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f"));
      __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
      __classPrivateFieldGet2(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 != __classPrivateFieldGet2(this, _AssistantStream_currentContentIndex, "f")) {
                if (__classPrivateFieldGet2(this, _AssistantStream_currentContent, "f")) {
                  switch (__classPrivateFieldGet2(this, _AssistantStream_currentContent, "f").type) {
                    case "text":
                      this._emit("textDone", __classPrivateFieldGet2(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f"));
                      break;
                    case "image_file":
                      this._emit("imageFileDone", __classPrivateFieldGet2(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet2(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 (__classPrivateFieldGet2(this, _AssistantStream_currentContentIndex, "f") !== void 0) {
            const currentContent = event.data.content[__classPrivateFieldGet2(this, _AssistantStream_currentContentIndex, "f")];
            if (currentContent) {
              switch (currentContent.type) {
                case "image_file":
                  this._emit("imageFileDone", currentContent.image_file, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f"));
                  break;
                case "text":
                  this._emit("textDone", currentContent.text, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f"));
                  break;
              }
            }
          }
          if (__classPrivateFieldGet2(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 = __classPrivateFieldGet2(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 == __classPrivateFieldGet2(this, _AssistantStream_currentToolCallIndex, "f")) {
                this._emit("toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);
              } else {
                if (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")) {
                  this._emit("toolCallDone", __classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f"));
                }
                __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
                __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
                if (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f"))
                  this._emit("toolCallCreated", __classPrivateFieldGet2(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 (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")) {
              this._emit("toolCallDone", __classPrivateFieldGet2(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) {
      __classPrivateFieldGet2(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":
          __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
          return event.data;
        case "thread.run.step.delta":
          let snapshot = __classPrivateFieldGet2(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);
            __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
          }
          return __classPrivateFieldGet2(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":
          __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
          break;
      }
      if (__classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id])
        return __classPrivateFieldGet2(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] = __classPrivateFieldGet2(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 (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")) {
            this._emit("toolCallDone", __classPrivateFieldGet2(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, ...body2 } = params;
        return this._client.post(path17`/threads/${threadID}/runs`, {
          query: { include },
          body: body2,
          ...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(path17`/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, ...body2 } = params;
        return this._client.post(path17`/threads/${thread_id}/runs/${runID}`, {
          body: body2,
          ...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(path17`/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(path17`/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, body2, options2) {
        const run2 = await this.create(threadId, body2, options2);
        return await this.poll(run2.id, { thread_id: threadId }, options2);
      }
      /**
       * Create a Run stream
       *
       * @deprecated use `stream` instead
       */
      createAndStream(threadId, body2, options2) {
        return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body2, 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: run2, response } = await this.retrieve(runId, params, {
            ...options2,
            headers: { ...options2?.headers, ...headers }
          }).withResponse();
          switch (run2.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 run2;
          }
        }
      }
      /**
       * Create a Run stream
       */
      stream(threadId, body2, options2) {
        return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body2, options2);
      }
      submitToolOutputs(runID, params, options2) {
        const { thread_id, ...body2 } = params;
        return this._client.post(path17`/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, {
          body: body2,
          ...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 run2 = await this.submitToolOutputs(runId, params, options2);
        return await this.poll(run2.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(body2 = {}, options2) {
        return this._client.post("/threads", {
          body: body2,
          ...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(path17`/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, body2, options2) {
        return this._client.post(path17`/threads/${threadID}`, {
          body: body2,
          ...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(path17`/threads/${threadID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      createAndRun(body2, options2) {
        return this._client.post("/threads/runs", {
          body: body2,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
          stream: body2.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(body2, options2) {
        const run2 = await this.createAndRun(body2, options2);
        return await this.runs.poll(run2.id, { thread_id: run2.thread_id }, options2);
      }
      /**
       * Create a thread and stream the run back
       */
      createAndRunStream(body2, options2) {
        return AssistantStream.createThreadAssistantStream(body2, 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(body2, options2) {
        return this._client.post("/completions", { body: body2, ...options2, stream: body2.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(path17`/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, body2, options2) {
        return this._client.post(path17`/containers/${containerID}/files`, multipartFormRequestOptions({ body: body2, ...options2 }, this._client));
      }
      /**
       * Retrieve Container File
       */
      retrieve(fileID, params, options2) {
        const { container_id } = params;
        return this._client.get(path17`/containers/${container_id}/files/${fileID}`, options2);
      }
      /**
       * List Container files
       */
      list(containerID, query = {}, options2) {
        return this._client.getAPIList(path17`/containers/${containerID}/files`, CursorPage, {
          query,
          ...options2
        });
      }
      /**
       * Delete Container File
       */
      delete(fileID, params, options2) {
        const { container_id } = params;
        return this._client.delete(path17`/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(body2, options2) {
        return this._client.post("/containers", { body: body2, ...options2 });
      }
      /**
       * Retrieve Container
       */
      retrieve(containerID, options2) {
        return this._client.get(path17`/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(path17`/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(body2, options2) {
        const hasUserProvidedEncodingFormat = !!body2.encoding_format;
        let encoding_format = hasUserProvidedEncodingFormat ? body2.encoding_format : "base64";
        if (hasUserProvidedEncodingFormat) {
          loggerFor(this._client).debug("embeddings/user defined encoding_format:", body2.encoding_format);
        }
        const response = this._client.post("/embeddings", {
          body: {
            ...body2,
            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(path17`/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(path17`/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, body2, options2) {
        return this._client.post(path17`/evals/${evalID}/runs`, { body: body2, ...options2 });
      }
      /**
       * Get an evaluation run by ID.
       */
      retrieve(runID, params, options2) {
        const { eval_id } = params;
        return this._client.get(path17`/evals/${eval_id}/runs/${runID}`, options2);
      }
      /**
       * Get a list of runs for an evaluation.
       */
      list(evalID, query = {}, options2) {
        return this._client.getAPIList(path17`/evals/${evalID}/runs`, CursorPage, {
          query,
          ...options2
        });
      }
      /**
       * Delete an eval run.
       */
      delete(runID, params, options2) {
        const { eval_id } = params;
        return this._client.delete(path17`/evals/${eval_id}/runs/${runID}`, options2);
      }
      /**
       * Cancel an ongoing evaluation run.
       */
      cancel(runID, params, options2) {
        const { eval_id } = params;
        return this._client.post(path17`/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(body2, options2) {
        return this._client.post("/evals", { body: body2, ...options2 });
      }
      /**
       * Get an evaluation by ID.
       */
      retrieve(evalID, options2) {
        return this._client.get(path17`/evals/${evalID}`, options2);
      }
      /**
       * Update certain properties of an evaluation.
       */
      update(evalID, body2, options2) {
        return this._client.post(path17`/evals/${evalID}`, { body: body2, ...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(path17`/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(body2, options2) {
        return this._client.post("/files", multipartFormRequestOptions({ body: body2, ...options2 }, this._client));
      }
      /**
       * Returns information about a specific file.
       */
      retrieve(fileID, options2) {
        return this._client.get(path17`/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(path17`/files/${fileID}`, options2);
      }
      /**
       * Returns the contents of the specified file.
       */
      content(fileID, options2) {
        return this._client.get(path17`/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 start2 = Date.now();
        let file2 = await this.retrieve(id);
        while (!file2.status || !TERMINAL_STATES.has(file2.status)) {
          await sleep2(pollInterval);
          file2 = await this.retrieve(id);
          if (Date.now() - start2 > maxWait) {
            throw new APIConnectionTimeoutError({
              message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`
            });
          }
        }
        return file2;
      }
    };
  }
});

// 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(body2, options2) {
        return this._client.post("/fine_tuning/alpha/graders/run", { body: body2, ...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(body2, options2) {
        return this._client.post("/fine_tuning/alpha/graders/validate", { body: body2, ...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, body2, options2) {
        return this._client.getAPIList(path17`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, Page, { body: body2, 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(path17`/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(path17`/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(path17`/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(body2, options2) {
        return this._client.post("/fine_tuning/jobs", { body: body2, ...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(path17`/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(path17`/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(path17`/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(path17`/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(path17`/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(body2, options2) {
        return this._client.post("/images/variations", multipartFormRequestOptions({ body: body2, ...options2 }, this._client));
      }
      edit(body2, options2) {
        return this._client.post("/images/edits", multipartFormRequestOptions({ body: body2, ...options2, stream: body2.stream ?? false }, this._client));
      }
      generate(body2, options2) {
        return this._client.post("/images/generations", { body: body2, ...options2, stream: body2.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(path17`/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(path17`/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(body2, options2) {
        return this._client.post("/moderations", { body: body2, ...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, name4) {
  return input_tools.find((tool) => tool.type === "function" && tool.name === name4);
}
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());
        }
        __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
        let stream5;
        let starting_after = null;
        if ("response_id" in params) {
          stream5 = await client.responses.retrieve(params.response_id, { stream: true }, { ...options2, signal: this.controller.signal, stream: true });
          starting_after = params.starting_after ?? null;
        } else {
          stream5 = await client.responses.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal });
        }
        this._connected();
        for await (const event of stream5) {
          __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after);
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError();
        }
        return __classPrivateFieldGet2(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((name4, event2) => {
          if (starting_after == null || event2.sequence_number > starting_after) {
            this._emit(name4, event2);
          }
        }, "maybeEmit");
        const response = __classPrivateFieldGet2(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 = __classPrivateFieldGet2(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, __classPrivateFieldGet2(this, _ResponseStream_params, "f"));
        __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f");
        return parsedResponse;
      }, "_ResponseStream_endRequest"), _ResponseStream_accumulateResponse = /* @__PURE__ */ __name(function _ResponseStream_accumulateResponse2(event) {
        let snapshot = __classPrivateFieldGet2(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", (err2) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err2);
          }
          readQueue.length = 0;
        });
        this.on("error", (err2) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err2);
          }
          readQueue.length = 0;
        });
        return {
          next: /* @__PURE__ */ __name(async () => {
            if (!pushQueue.length) {
              if (done) {
                return { value: void 0, done: true };
              }
              return new Promise((resolve42, reject) => readQueue.push({ resolve: resolve42, 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 = __classPrivateFieldGet2(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(path17`/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(body2, options2) {
        return this._client.post("/responses", { body: body2, ...options2, stream: body2.stream ?? false })._thenUnwrap((rsp) => {
          if ("object" in rsp && rsp.object === "response") {
            addOutputText(rsp);
          }
          return rsp;
        });
      }
      retrieve(responseID, query = {}, options2) {
        return this._client.get(path17`/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(path17`/responses/${responseID}`, {
          ...options2,
          headers: buildHeaders([{ Accept: "*/*" }, options2?.headers])
        });
      }
      parse(body2, options2) {
        return this._client.responses.create(body2, options2)._thenUnwrap((response) => parseResponse(response, body2));
      }
      /**
       * Creates a model response stream
       */
      stream(body2, options2) {
        return ResponseStream.createResponse(this._client, body2, 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(path17`/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, body2, options2) {
        return this._client.post(path17`/uploads/${uploadID}/parts`, multipartFormRequestOptions({ body: body2, ...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(body2, options2) {
        return this._client.post("/uploads", { body: body2, ...options2 });
      }
      /**
       * Cancels the Upload. No Parts may be added after an Upload is cancelled.
       */
      cancel(uploadID, options2) {
        return this._client.post(path17`/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, body2, options2) {
        return this._client.post(path17`/uploads/${uploadID}/complete`, { body: body2, ...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 (promises9) => {
      const results = await Promise.allSettled(promises9);
      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, body2, options2) {
        return this._client.post(path17`/vector_stores/${vectorStoreID}/file_batches`, {
          body: body2,
          ...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(path17`/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(path17`/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, body2, options2) {
        const batch = await this.create(vectorStoreId, body2);
        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(path17`/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(iterator2) {
          for (let item of iterator2) {
            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, body2, options2) {
        return this._client.post(path17`/vector_stores/${vectorStoreID}/files`, {
          body: body2,
          ...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(path17`/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, ...body2 } = params;
        return this._client.post(path17`/vector_stores/${vector_store_id}/files/${fileID}`, {
          body: body2,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Returns a list of vector store files.
       */
      list(vectorStoreID, query = {}, options2) {
        return this._client.getAPIList(path17`/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(path17`/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, body2, options2) {
        const file2 = await this.create(vectorStoreId, body2, options2);
        return await this.poll(vectorStoreId, file2.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 file2 = fileResponse.data;
          switch (file2.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 file2;
          }
        }
      }
      /**
       * 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, file2, options2) {
        const fileInfo = await this._client.files.create({ file: file2, 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, file2, options2) {
        const fileInfo = await this.upload(vectorStoreId, file2, 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(path17`/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(body2, options2) {
        return this._client.post("/vector_stores", {
          body: body2,
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Retrieves a vector store.
       */
      retrieve(vectorStoreID, options2) {
        return this._client.get(path17`/vector_stores/${vectorStoreID}`, {
          ...options2,
          headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers])
        });
      }
      /**
       * Modifies a vector store.
       */
      update(vectorStoreID, body2, options2) {
        return this._client.post(path17`/vector_stores/${vectorStoreID}`, {
          body: body2,
          ...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(path17`/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, body2, options2) {
        return this._client.getAPIList(path17`/vector_stores/${vectorStoreID}/search`, Page, {
          body: body2,
          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");
        }
        __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret);
        const headersObj = buildHeaders([headers]).values;
        const signatureHeader = __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature");
        const timestamp = __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp");
        const webhookId = __classPrivateFieldGet2(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, name4) {
      if (!headers) {
        throw new Error(`Headers are required`);
      }
      const value = headers.get(name4);
      if (value === null || value === void 0) {
        throw new Error(`Missing required header: ${name4}`);
      }
      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 ${VERSION3}`;
      }
      defaultIdempotencyKey() {
        return `stainless-node-retry-${uuid4()}`;
      }
      makeStatusError(status, error40, message, headers) {
        return APIError.generate(status, error40, message, headers);
      }
      buildURL(path150, query, defaultBaseURL) {
        const baseURL = !__classPrivateFieldGet2(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
        const url3 = isAbsoluteURL(path150) ? new URL(path150) : new URL(baseURL + (baseURL.endsWith("/") && path150.startsWith("/") ? path150.slice(1) : path150));
        const defaultQuery = this.defaultQuery();
        if (!isEmptyObj(defaultQuery)) {
          query = { ...defaultQuery, ...query };
        }
        if (typeof query === "object" && query && !Array.isArray(query)) {
          url3.search = this.stringifyQuery(query);
        }
        return url3.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: url3, options: options2 }) {
      }
      get(path150, opts) {
        return this.methodRequest("get", path150, opts);
      }
      post(path150, opts) {
        return this.methodRequest("post", path150, opts);
      }
      patch(path150, opts) {
        return this.methodRequest("patch", path150, opts);
      }
      put(path150, opts) {
        return this.methodRequest("put", path150, opts);
      }
      delete(path150, opts) {
        return this.methodRequest("delete", path150, opts);
      }
      methodRequest(method, path150, opts) {
        return this.request(Promise.resolve(opts).then((opts2) => {
          return { method, path: path150, ...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: url3, timeout: timeout2 } = await this.buildRequest(options2, {
          retryCount: maxRetries - retriesRemaining
        });
        await this.prepareRequest(req, { url: url3, 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: url3,
          options: options2,
          headers: req.headers
        }));
        if (options2.signal?.aborted) {
          throw new APIUserAbortError();
        }
        const controller = new AbortController();
        const response = await this.fetchWithTimeout(url3, 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: url3,
              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: url3,
            durationMs: headersTime - startTime,
            message: response.message
          }));
          if (isTimeout) {
            throw new APIConnectionTimeoutError();
          }
          throw new APIConnectionError({ cause: response });
        }
        const specialHeaders = [...response.headers.entries()].filter(([name4]) => name4 === "x-request-id").map(([name4, value]) => ", " + name4 + ": " + JSON.stringify(value)).join("");
        const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url3} ${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((err3) => castToError(err3).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 err2 = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
          throw err2;
        }
        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(path150, Page3, opts) {
        return this.requestAPIList(Page3, { method: "get", path: path150, ...opts });
      }
      requestAPIList(Page3, options2) {
        const request4 = this.makeRequest(options2, null, void 0);
        return new PagePromise(this, request4, Page3);
      }
      async fetchWithTimeout(url3, init2, ms, controller) {
        const { signal, method, ...options2 } = init2 || {};
        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, url3, 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: path150, query, defaultBaseURL } = options2;
        const url3 = this.buildURL(path150, query, defaultBaseURL);
        if ("timeout" in options2)
          validatePositiveInteger("timeout", options2.timeout);
        options2.timeout = options2.timeout ?? this.timeout;
        const { bodyHeaders, body: body2 } = 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 && body2 instanceof globalThis.ReadableStream && { duplex: "half" },
          ...body2 && { body: body2 },
          ...this.fetchOptions ?? {},
          ...options2.fetchOptions ?? {}
        };
        return { req, url: url3, 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: body2, headers: rawHeaders } }) {
        if (!body2) {
          return { bodyHeaders: void 0, body: void 0 };
        }
        const headers = buildHeaders([rawHeaders]);
        if (
          // Pass raw type verbatim
          ArrayBuffer.isView(body2) || body2 instanceof ArrayBuffer || body2 instanceof DataView || typeof body2 === "string" && // Preserve legacy string encoding behavior for now
          headers.values.has("content-type") || // `Blob` is superset of `File`
          body2 instanceof Blob || // `FormData` -> `multipart/form-data`
          body2 instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
          body2 instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
          globalThis.ReadableStream && body2 instanceof globalThis.ReadableStream
        ) {
          return { bodyHeaders: void 0, body: body2 };
        } else if (typeof body2 === "object" && (Symbol.asyncIterator in body2 || Symbol.iterator in body2 && "next" in body2 && typeof body2.next === "function")) {
          return { bodyHeaders: void 0, body: ReadableStreamFrom(body2) };
        } else {
          return __classPrivateFieldGet2(this, _OpenAI_encoder, "f").call(this, { body: body2, 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, init2) => {
          const bunFetchOptions = {
            ...init2,
            // @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 getOrCreateSharedDispatcher(proxyUrl) {
  const cached2 = dispatcherCache.get(proxyUrl);
  if (cached2) {
    return cached2;
  }
  const dispatcher = proxyUrl ? new import_undici.ProxyAgent({
    uri: proxyUrl,
    headersTimeout: 0,
    bodyTimeout: 0,
    keepAliveTimeout: 6e4
  }) : new import_undici.Agent({
    headersTimeout: 0,
    bodyTimeout: 0,
    keepAliveTimeout: 6e4
  });
  dispatcherCache.set(proxyUrl, dispatcher);
  return dispatcher;
}
function buildFetchOptionsWithDispatcher(sdkType, proxyUrl) {
  try {
    const dispatcher = getOrCreateSharedDispatcher(proxyUrl);
    return { fetchOptions: { dispatcher } };
  } catch {
    return sdkType === "openai" ? void 0 : {};
  }
}
var import_undici, dispatcherCache;
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");
    dispatcherCache = /* @__PURE__ */ new Map();
    __name(getOrCreateSharedDispatcher, "getOrCreateSharedDispatcher");
    __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();
    init_tokenLimits();
    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;
        const requestWithTokenLimits = this.applyOutputTokenLimit(request4);
        return {
          ...requestWithTokenLimits,
          ...extraBody ? extraBody : {}
        };
      }
      getDefaultGenerationConfig() {
        return {};
      }
      /**
       * Apply output token limit to a request's max_tokens parameter.
       *
       * Purpose:
       * Some APIs (e.g., OpenAI-compatible) default to a very small max_tokens value,
       * which can cause responses to be truncated mid-output. This function ensures
       * a reasonable default is set while respecting user configuration.
       *
       * Logic:
       * 1. If user explicitly configured max_tokens:
       *    - For known models (in OUTPUT_PATTERNS): use the user's value, but cap at
       *      model's max output limit to avoid API errors
       *      (input + max_output > contextWindowSize would cause 400 errors on some APIs)
       *    - For unknown models (deployment aliases, self-hosted): respect user's
       *      configured value entirely (backend may support larger limits)
       * 2. If user didn't configure max_tokens:
       *    - Check QWEN_CODE_MAX_OUTPUT_TOKENS env var first
       *    - Otherwise use min(modelLimit, CAPPED_DEFAULT_MAX_TOKENS=8K)
       *    - Requests hitting the 8K cap get one clean retry at 64K (geminiChat.ts)
       * 3. If model has no specific limit (tokenLimit returns default):
       *    - Still apply CAPPED_DEFAULT_MAX_TOKENS as safeguard
       *
       * Examples:
       * - User sets 4K, known model limit 64K → uses 4K (respects user preference)
       * - User sets 100K, known model limit 64K → uses 64K (capped to avoid API error)
       * - User sets 100K, unknown model → uses 100K (respects user, backend may support it)
       * - User not set, model limit 64K → uses 8K (capped default for slot optimization)
       * - User not set, model limit 4K → uses 4K (model limit is lower)
       * - User not set, env QWEN_CODE_MAX_OUTPUT_TOKENS=16000 -> uses 16K
       *
       * @param request - The chat completion request parameters
       * @returns The request with max_tokens adjusted according to the logic
       */
      applyOutputTokenLimit(request4) {
        if (this.contentGeneratorConfig.samplingParams !== void 0) {
          return request4;
        }
        const userMaxTokens = request4.max_tokens;
        const modelLimit = tokenLimit(request4.model, "output");
        const isKnownModel = hasExplicitOutputLimit(request4.model);
        let effectiveMaxTokens;
        if (userMaxTokens !== void 0 && userMaxTokens !== null) {
          if (isKnownModel) {
            effectiveMaxTokens = Math.min(userMaxTokens, modelLimit);
          } else {
            effectiveMaxTokens = userMaxTokens;
          }
        } else {
          const envVal = process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"];
          const envMaxTokens = envVal ? parseInt(envVal, 10) : NaN;
          if (!isNaN(envMaxTokens) && envMaxTokens > 0) {
            effectiveMaxTokens = isKnownModel ? Math.min(envMaxTokens, modelLimit) : envMaxTokens;
          } else {
            effectiveMaxTokens = Math.min(modelLimit, CAPPED_DEFAULT_MAX_TOKENS);
          }
        }
        return {
          ...request4,
          max_tokens: effectiveMaxTokens
        };
      }
    };
  }
});

// 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_default();
    DashScopeOpenAICompatibleProvider = class _DashScopeOpenAICompatibleProvider extends DefaultOpenAICompatibleProvider {
      static {
        __name(this, "DashScopeOpenAICompatibleProvider");
      }
      constructor(contentGeneratorConfig, cliConfig) {
        super(contentGeneratorConfig, cliConfig);
      }
      static isDashScopeProvider(contentGeneratorConfig) {
        const { authType, baseUrl } = contentGeneratorConfig;
        if (authType === AuthType2.QWEN_OAUTH)
          return true;
        if (!baseUrl)
          return true;
        return /([\w-]+\.)?dashscope(-intl)?\.aliyuncs\.com/i.test(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 {};
      }
      /**
       * 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;
      }
      /**
       * 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
function flattenContentParts(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 (typeof part === "string") {
      return part;
    }
    if (part.type === "text") {
      return part.text ?? "";
    }
    return `[Unsupported content type: ${part.type}]`;
  }).join("\n\n");
  return {
    ...message,
    content: text
  };
}
function ensureReasoningContentOnToolCalls(message) {
  if (message.role !== "assistant") {
    return message;
  }
  const extended = message;
  if (typeof extended.reasoning_content === "string" && extended.reasoning_content.length > 0) {
    return message;
  }
  return {
    ...extended,
    reasoning_content: ""
  };
}
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 ?? "";
        if (baseUrl.toLowerCase().includes("api.deepseek.com")) {
          return true;
        }
        const model = contentGeneratorConfig.model ?? "";
        return model.toLowerCase().includes("deepseek");
      }
      /**
       * DeepSeek's API requires message content to be a plain string, not an
       * array of content parts. Flatten any text-part arrays into joined strings
       * and reject non-text parts that DeepSeek cannot handle.
       */
      buildRequest(request4, userPromptId) {
        const baseRequest = super.buildRequest(request4, userPromptId);
        if (!baseRequest.messages?.length) {
          return baseRequest;
        }
        const messages = baseRequest.messages.map((message) => {
          const flattened = flattenContentParts(message);
          return ensureReasoningContentOnToolCalls(flattened);
        });
        return {
          ...baseRequest,
          messages
        };
      }
      getDefaultGenerationConfig() {
        return {
          temperature: 0
        };
      }
    };
    __name(flattenContentParts, "flattenContentParts");
    __name(ensureReasoningContentOnToolCalls, "ensureReasoningContentOnToolCalls");
  }
});

// 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/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, name4) {
        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 (name4)
          meta.name = name4;
        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 args2 = {};
            try {
              args2 = JSON.parse(buffer);
            } catch {
              const inString = this.inStrings.get(index);
              if (inString) {
                try {
                  args2 = JSON.parse(buffer + '"');
                } catch {
                  args2 = safeJsonParse(buffer, {});
                }
              } else {
                args2 = safeJsonParse(buffer, {});
              }
            }
            completed.push({
              id: meta.id,
              name: meta.name,
              args: args2,
              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
        };
      }
      /**
       * Checks whether any buffered tool call has incomplete JSON at stream end.
       *
       * A tool call is considered incomplete when its JSON parsing state indicates
       * the buffer was truncated mid-stream:
       * - depth > 0: unclosed braces/brackets remain
       * - inString === true: still inside a string literal
       *
       * This is critical for detecting output truncation that the LLM provider
       * may not report correctly via finish_reason (e.g. reporting "stop" or
       * "tool_calls" instead of "length" when output was actually cut off).
       *
       * @returns true if at least one tool call buffer has incomplete JSON
       */
      hasIncompleteToolCalls() {
        for (const [index] of this.buffers.entries()) {
          const meta = this.toolCallMeta.get(index);
          if (!meta?.name)
            continue;
          const depth = this.depths.get(index) || 0;
          const inString = this.inStrings.get(index) || false;
          if (depth > 0 || inString) {
            return true;
          }
        }
        return false;
      }
    };
  }
});

// packages/core/dist/src/core/openaiContentGenerator/pipeline.js
import { setMaxListeners } from "node:events";
function raiseAbortListenerCap(signal) {
  if (signal)
    setMaxListeners(0, signal);
}
var StreamContentError, ContentGenerationPipeline;
var init_pipeline = __esm({
  "packages/core/dist/src/core/openaiContentGenerator/pipeline.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_converter();
    init_streamingToolCallParser();
    __name(raiseAbortListenerCap, "raiseAbortListenerCap");
    StreamContentError = class extends Error {
      static {
        __name(this, "StreamContentError");
      }
      constructor(message) {
        super(message);
        this.name = "StreamContentError";
      }
    };
    ContentGenerationPipeline = class {
      static {
        __name(this, "ContentGenerationPipeline");
      }
      config;
      client;
      contentGeneratorConfig;
      constructor(config2) {
        this.config = config2;
        this.contentGeneratorConfig = config2.contentGeneratorConfig;
        this.client = this.config.provider.buildClient();
      }
      async execute(request4, userPromptId) {
        raiseAbortListenerCap(request4.config?.abortSignal);
        return this.executeWithErrorHandling(request4, userPromptId, false, async (openaiRequest, context2) => {
          const openaiResponse = await this.client.chat.completions.create(openaiRequest, {
            signal: request4.config?.abortSignal
          });
          const geminiResponse = OpenAIContentConverter.convertOpenAIResponseToGemini(openaiResponse, context2);
          return geminiResponse;
        });
      }
      async executeStream(request4, userPromptId) {
        raiseAbortListenerCap(request4.config?.abortSignal);
        return this.executeWithErrorHandling(request4, userPromptId, true, async (openaiRequest, context2) => {
          const stream5 = await this.client.chat.completions.create(openaiRequest, {
            signal: request4.config?.abortSignal
          });
          return this.processStreamWithLogging(stream5, 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(stream5, context2, request4) {
        const collectedGeminiResponses = [];
        let pendingFinishResponse = null;
        let finishYielded = false;
        try {
          for await (const chunk of stream5) {
            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 = OpenAIContentConverter.convertOpenAIChunkToGemini(chunk, context2);
            if (response.candidates?.[0]?.content?.parts?.length === 0 && !response.candidates?.[0]?.finishReason && !response.usageMetadata) {
              continue;
            }
            if (finishYielded) {
              if (response.usageMetadata) {
                const pending = pendingFinishResponse;
                if (pending) {
                  pending.usageMetadata = response.usageMetadata;
                }
              }
              collectedGeminiResponses.push(response);
              continue;
            }
            const shouldYield = this.handleChunkMerging(response, collectedGeminiResponses, (mergedResponse) => {
              pendingFinishResponse = mergedResponse;
            });
            if (shouldYield) {
              if (pendingFinishResponse) {
                yield pendingFinishResponse;
                finishYielded = true;
              } else {
                yield response;
              }
            }
          }
          if (pendingFinishResponse && !finishYielded) {
            yield pendingFinishResponse;
          }
        } catch (error40) {
          if (error40 instanceof StreamContentError) {
            throw error40;
          }
          await this.handleError(error40, 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) {
          if (hasPendingFinish) {
            const lastResponse = collectedGeminiResponses[collectedGeminiResponses.length - 1];
            if (response.usageMetadata) {
              lastResponse.usageMetadata = response.usageMetadata;
            }
            setPendingFinish(lastResponse);
          } else {
            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, context2, isStreaming) {
        const messages = OpenAIContentConverter.convertGeminiRequestToOpenAI(request4, context2);
        const baseRequest = {
          model: context2.model,
          messages,
          ...this.buildGenerateContentConfig(request4)
        };
        if (isStreaming) {
          baseRequest.stream = true;
          baseRequest.stream_options = { include_usage: true };
        }
        if (request4.config?.tools && request4.config.tools.length > 0) {
          baseRequest.tools = await OpenAIContentConverter.convertGeminiToolsToOpenAI(request4.config.tools, this.contentGeneratorConfig.schemaCompliance ?? "auto");
        }
        const providerRequest = this.config.provider.buildRequest(baseRequest, userPromptId);
        if (request4.config?.thinkingConfig?.includeThoughts === false) {
          const typed = providerRequest;
          if ("enable_thinking" in typed) {
            typed["enable_thinking"] = false;
          }
          if ("reasoning" in typed) {
            delete typed["reasoning"];
          }
        }
        return providerRequest;
      }
      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");
        if (configSamplingParams !== void 0) {
          return { ...configSamplingParams };
        }
        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, executor) {
        const context2 = this.createRequestContext(request4, isStreaming);
        try {
          const openaiRequest = await this.buildRequest(request4, userPromptId, context2, isStreaming);
          const result = await executor(openaiRequest, context2);
          return result;
        } catch (error40) {
          return await this.handleError(error40, context2, request4);
        }
      }
      /**
       * Shared error handling logic for both executeWithErrorHandling and processStreamWithLogging
       * This centralizes the common error processing steps to avoid duplication
       */
      async handleError(error40, context2, request4) {
        this.config.errorHandler.handle(error40, context2, request4);
      }
      /**
       * Create request context with common properties
       */
      createRequestContext(request4, isStreaming) {
        const effectiveModel = request4.model || this.contentGeneratorConfig.model;
        const toolCallParser = isStreaming ? new StreamingToolCallParser() : void 0;
        return {
          model: effectiveModel,
          modalities: this.contentGeneratorConfig.modalities ?? {},
          startTime: Date.now(),
          splitToolMedia: this.contentGeneratorConfig.splitToolMedia ?? false,
          ...toolCallParser ? { toolCallParser } : {}
        };
      }
    };
  }
});

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

${this.getTimeoutTroubleshootingTips()}`);
        }
        throw error40;
      }
      shouldSuppressErrorLogging(error40, request4) {
        return this.shouldSuppressLogging(error40, request4);
      }
      isTimeoutError(error40) {
        if (!error40)
          return false;
        const errorMessage = error40 instanceof Error ? error40.message.toLowerCase() : String(error40).toLowerCase();
        const errorCode = error40?.code;
        const errorType = error40?.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(error40, context2, isTimeoutError) {
        const durationSeconds = Math.round((Date.now() - context2.startTime) / 1e3);
        if (isTimeoutError) {
          return `Request timeout after ${durationSeconds}s. Try reducing input length or increasing timeout in config.`;
        }
        return error40 instanceof Error ? error40.message : String(error40);
      }
      getTimeoutTroubleshootingTips() {
        const tips = [
          "- Reduce input length or complexity",
          "- Increase timeout in config: contentGenerator.timeout",
          "- Check network connectivity"
        ];
        return `Troubleshooting tips:
${tips.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 i4 = 0; i4 < text.length; i4++) {
          const charCode = text.charCodeAt(i4);
          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 debugLogger13, ImageTokenizer;
var init_imageTokenizer = __esm({
  "packages/core/dist/src/utils/request-tokenizer/imageTokenizer.js"() {
    "use strict";
    init_esbuild_shims();
    init_supportedImageFormats();
    init_debugLogger();
    debugLogger13 = 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)) {
            debugLogger13.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 (error40) {
          debugLogger13.warn("Failed to extract image metadata:", error40);
          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(metadata2) {
        return this.calculateTokensWithScaling(metadata2.width, metadata2.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 metadata2 = await this.extractImageMetadata(data, mimeType);
            results.push(this.calculateTokens(metadata2));
          } catch (error40) {
            debugLogger13.warn("Error calculating tokens for image:", error40);
            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 i4 = 0; i4 < numEntries; i4++) {
          const entryOffset = ifdOffset + 2 + i4 * 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;
        }
        debugLogger13.warn("Could not extract HEIC dimensions, using default");
        return { width: 512, height: 512 };
      }
    };
  }
});

// packages/core/dist/src/utils/request-tokenizer/requestTokenizer.js
var debugLogger14, 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();
    debugLogger14 = 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 (error40) {
          debugLogger14.error("Error calculating tokens:", error40);
          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 (error40) {
          debugLogger14.warn("Error calculating text tokens:", error40);
          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 (error40) {
          debugLogger14.warn("Error calculating image tokens:", error40);
          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 (error40) {
            debugLogger14.warn("Error calculating audio tokens:", error40);
            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 (error40) {
          debugLogger14.warn("Error calculating other content tokens:", error40);
          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 (error40) {
          debugLogger14.warn("Error in fallback token calculation:", error40);
          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 (error40) {
          debugLogger14.warn("Failed to serialize unknown part type:", error40);
        }
      }
    };
  }
});

// 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 debugLogger15, 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();
    debugLogger15 = createDebugLogger("OPENAI");
    OpenAIContentGenerator = class {
      static {
        __name(this, "OpenAIContentGenerator");
      }
      pipeline;
      constructor(contentGeneratorConfig, cliConfig, provider) {
        const pipelineConfig = {
          cliConfig,
          provider,
          contentGeneratorConfig,
          errorHandler: new EnhancedErrorHandler((error40, request4) => this.shouldSuppressErrorLogging(error40, 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(error40, request4) {
        if (isAbortError(error40) && 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 (error40) {
          debugLogger15.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:", error40);
          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 (error40) {
          debugLogger15.error("OpenAI API Embedding Error:", error40);
          throw new Error(`OpenAI API error: ${error40 instanceof Error ? error40.message : String(error40)}`);
        }
      }
      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 fs20 from "node:fs";
function hasDockerEnv() {
  try {
    fs20.statSync("/.dockerenv");
    return true;
  } catch {
    return false;
  }
}
function hasDockerCGroup() {
  try {
    return fs20.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 fs21 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 {
        fs21.statSync("/run/.containerenv");
        return true;
      } catch {
        return false;
      }
    }, "hasContainerEnv");
    __name(isInsideContainer, "isInsideContainer");
  }
});

// node_modules/is-wsl/index.js
import process3 from "node:process";
import os9 from "node:os";
import fs22 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 (os9.release().toLowerCase().includes("microsoft")) {
        if (isInsideContainer()) {
          return false;
        }
        return true;
      }
      try {
        return fs22.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 fs23, { 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 fs23.access(configFilePath2, fsConstants.F_OK);
          isConfigFileExists = true;
        } catch {
        }
        if (!isConfigFileExists) {
          return defaultMountPoint;
        }
        const configContent = await fs23.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 as execFile2 } from "node:child_process";
async function defaultBrowserId() {
  if (process5.platform !== "darwin") {
    throw new Error("macOS only");
  }
  const { stdout: stdout2 } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
  const match2 = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout2);
  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(execFile2);
    __name(defaultBrowserId, "defaultBrowserId");
  }
});

// node_modules/run-applescript/index.js
import process6 from "node:process";
import { promisify as promisify3 } from "node:util";
import { execFile as execFile3, 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: stdout2 } = await execFileAsync2("osascript", ["-e", script, outputArguments]);
  return stdout2.trim();
}
var execFileAsync2;
var init_run_applescript = __esm({
  "node_modules/run-applescript/index.js"() {
    init_esbuild_shims();
    execFileAsync2 = promisify3(execFile3);
    __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 execFile4 } from "node:child_process";
async function defaultBrowser(_execFileAsync = execFileAsync3) {
  const { stdout: stdout2 } = 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(stdout2);
  if (!match2) {
    throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout2)}`);
  }
  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(execFile4);
    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 execFile5 } from "node:child_process";
async function defaultBrowser2() {
  if (process7.platform === "darwin") {
    const id = await defaultBrowserId();
    const name4 = await bundleName(id);
    return { name: name4, id };
  }
  if (process7.platform === "linux") {
    const { stdout: stdout2 } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
    const id = stdout2.trim();
    const name4 = titleize(id.replace(/.desktop$/, "").replace("-", " "));
    return { name: name4, 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(execFile5);
    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 path18 from "node:path";
import { fileURLToPath as fileURLToPath2 } from "node:url";
import { promisify as promisify6 } from "node:util";
import childProcess from "node:child_process";
import fs24, { 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: stdout2 } = await execFile6(
    powershellPath,
    [
      "-NoProfile",
      "-NonInteractive",
      "-ExecutionPolicy",
      "Bypass",
      "-EncodedCommand",
      encodedCommand
    ],
    { encoding: "utf8" }
  );
  const progId = stdout2.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(binary2) {
  if (typeof binary2 === "string" || Array.isArray(binary2)) {
    return binary2;
  }
  const { [arch]: archBinary } = binary2;
  if (!archBinary) {
    throw new Error(`${arch} is not supported`);
  }
  return archBinary;
}
function detectPlatformBinary({ [platform3]: platformBinary }, { wsl }) {
  if (wsl && is_wsl_default) {
    return detectArchBinary(wsl);
  }
  if (!platformBinary) {
    throw new Error(`${platform3} is not supported`);
  }
  return detectArchBinary(platformBinary);
}
var execFile6, __dirname2, localXdgOpenPath, platform3, 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();
    execFile6 = promisify6(childProcess.execFile);
    __dirname2 = path18.dirname(fileURLToPath2(import.meta.url));
    localXdgOpenPath = path18.join(__dirname2, "xdg-open");
    ({ platform: platform3, arch } = process8);
    __name(getWindowsDefaultBrowserFromWsl, "getWindowsDefaultBrowserFromWsl");
    pTryEach = /* @__PURE__ */ __name(async (array2, mapper) => {
      let latestError;
      for (const item of array2) {
        try {
          return await mapper(item);
        } catch (error40) {
          latestError = error40;
        }
      }
      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 flags2 = {
          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(flags2[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 (platform3 === "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 (platform3 === "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 fs24.access(localXdgOpenPath, fsConstants2.X_OK);
            exeLocalXdgOpen = true;
          } catch {
          }
          const useSystemXdgOpen = process8.versions.electron ?? (platform3 === "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 (platform3 === "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((resolve42, reject) => {
          subprocess.once("error", reject);
          subprocess.once("close", (exitCode) => {
            if (!options2.allowNonzeroExitCode && exitCode > 0) {
              reject(new Error(`Exited with code ${exitCode}`));
              return;
            }
            resolve42(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(url3) {
  try {
    const hostname4 = new URL2(url3).hostname;
    return PRIVATE_IP_RANGES.some((range) => range.test(hostname4));
  } catch (_e2) {
    return false;
  }
}
async function fetchWithTimeout(url3, timeout2, headers) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeout2);
  try {
    const response = await fetch(url3, {
      signal: controller.signal,
      headers
    });
    return response;
  } catch (error40) {
    if (isNodeError(error40) && error40.code === "ABORT_ERR") {
      throw new FetchError2(`Request timed out after ${timeout2}ms`, "ETIMEDOUT");
    }
    throw new FetchError2(getErrorMessage(error40));
  } finally {
    clearTimeout(timeoutId);
  }
}
function getErrorCode(error40) {
  if (!error40 || typeof error40 !== "object") {
    return void 0;
  }
  if ("code" in error40 && typeof error40["code"] === "string") {
    return error40["code"];
  }
  return void 0;
}
function formatUnknownErrorMessage(error40) {
  if (typeof error40 === "string") {
    return error40;
  }
  if (typeof error40 === "number" || typeof error40 === "boolean" || typeof error40 === "bigint") {
    return String(error40);
  }
  if (error40 instanceof Error) {
    return error40.message;
  }
  if (!error40 || typeof error40 !== "object") {
    return void 0;
  }
  const message = error40["message"];
  if (typeof message === "string") {
    return message;
  }
  return void 0;
}
function formatErrorCause(error40) {
  if (!(error40 instanceof Error)) {
    return void 0;
  }
  const cause = error40.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(error40, options2 = {}) {
  const errorMessage = getErrorMessage(error40);
  const code2 = error40 instanceof Error ? getErrorCode(error40.cause) ?? getErrorCode(error40) : getErrorCode(error40);
  const cause = formatErrorCause(error40);
  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 path19 from "node:path";
import { promises as fs25, unlinkSync } from "node:fs";
import * as os10 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 debugLogger16, 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();
    debugLogger16 = 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 (error40) {
          if (error40 instanceof TokenManagerError) {
            throw error40;
          }
          throw new TokenManagerError(TokenError.REFRESH_FAILED, `Failed to get valid credentials: ${error40 instanceof Error ? error40.message : String(error40)}`, error40);
        }
      }
      /**
       * 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(promise2, timeoutMs, operationType = "Operation") {
        let timeoutId;
        return Promise.race([
          promise2.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(fs25.stat(filePath), 3e3, "File operation");
          const fileModTime = stats.mtimeMs;
          if (fileModTime > this.memoryCache.fileModTime) {
            await this.reloadCredentialsFromFile(qwenClient);
            this.memoryCache.fileModTime = fileModTime;
          }
        } catch (error40) {
          if (error40 instanceof Error && "code" in error40 && error40.code !== "ENOENT") {
            this.updateCacheState(null, 0, checkTime);
            throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to access credentials file: ${error40.message}`, error40);
          }
          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 fs25.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 (error40) {
          if (error40 instanceof Error && "code" in error40 && error40.code !== "ENOENT") {
            this.updateCacheState(null, 0);
            throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to access credentials file during refresh: ${error40.message}`, error40);
          }
          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 fs25.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 (error40) {
          if (error40 instanceof Error && error40.message.includes("Invalid credentials")) {
            debugLogger16.warn(`Failed to validate credentials file: ${error40.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();
        let lockAcquired = false;
        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);
          lockAcquired = true;
          const lockAcquisitionTime = Date.now() - startTime;
          if (lockAcquisitionTime > 5e3) {
            debugLogger16.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) {
            debugLogger16.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 (error40) {
          if (error40 instanceof CredentialsClearRequiredError) {
            debugLogger16.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, error40.message, error40);
          }
          if (error40 instanceof TokenManagerError) {
            throw error40;
          }
          if (error40 instanceof Error && (error40.message.includes("fetch") || error40.message.includes("network") || error40.message.includes("timeout"))) {
            throw new TokenManagerError(TokenError.NETWORK_ERROR, `Network error during token refresh: ${error40.message}`, error40);
          }
          throw new TokenManagerError(TokenError.REFRESH_FAILED, `Unexpected error during token refresh: ${error40 instanceof Error ? error40.message : String(error40)}`, error40);
        } finally {
          if (lockAcquired) {
            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 = path19.dirname(filePath);
        const tempPath = `${filePath}.tmp.${randomUUID2()}`;
        try {
          await this.withTimeout(fs25.mkdir(dirPath, { recursive: true, mode: 448 }), 5e3, "File operation");
        } catch (error40) {
          throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to create credentials directory: ${error40 instanceof Error ? error40.message : String(error40)}`, error40);
        }
        const credString = JSON.stringify(credentials, null, 2);
        try {
          await this.withTimeout(fs25.writeFile(tempPath, credString, { mode: 384 }), 5e3, "File operation");
          await this.withTimeout(fs25.rename(tempPath, filePath), 5e3, "File operation");
          const stats = await this.withTimeout(fs25.stat(filePath), 5e3, "File operation");
          this.memoryCache.fileModTime = stats.mtimeMs;
        } catch (error40) {
          try {
            await this.withTimeout(fs25.unlink(tempPath), 1e3, "File operation");
          } catch (_cleanupError) {
          }
          throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to write credentials file: ${error40 instanceof Error ? error40.message : String(error40)}`, error40);
        }
      }
      /**
       * 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 path19.join(os10.homedir(), QWEN_DIR3, QWEN_CREDENTIAL_FILENAME);
      }
      /**
       * Get the full path to the lock file
       *
       * @returns The absolute path to the lock file
       */
      getLockFilePath() {
        return path19.join(os10.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 fs25.writeFile(lockPath, lockId, { flag: "wx" });
            return;
          } catch (error40) {
            if (error40.code === "EEXIST") {
              try {
                const stats = await fs25.stat(lockPath);
                const lockAge = Date.now() - stats.mtimeMs;
                if (lockAge > LOCK_TIMEOUT_MS) {
                  const tempPath = `${lockPath}.stale.${randomUUID2()}`;
                  try {
                    await fs25.rename(lockPath, tempPath);
                    await fs25.unlink(tempPath);
                    debugLogger16.warn(`Removed stale lock file: ${lockPath} (age: ${lockAge}ms)`);
                    continue;
                  } catch (renameError) {
                    debugLogger16.warn(`Failed to remove stale lock file ${lockPath}: ${renameError instanceof Error ? renameError.message : String(renameError)}`);
                  }
                }
              } catch (statError) {
                debugLogger16.warn(`Failed to stat lock file ${lockPath}: ${statError instanceof Error ? statError.message : String(statError)}`);
              }
              await new Promise((resolve42) => setTimeout(resolve42, currentInterval));
              currentInterval = Math.min(currentInterval * 1.5, maxInterval);
            } else {
              throw new TokenManagerError(TokenError.FILE_ACCESS_ERROR, `Failed to create lock file: ${error40 instanceof Error ? error40.message : String(error40)}`, error40);
            }
          }
        }
        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 fs25.unlink(lockPath);
        } catch (error40) {
          if (error40.code !== "ENOENT") {
            debugLogger16.warn(`Failed to release lock file ${lockPath}: ${error40 instanceof Error ? error40.message : String(error40)}`);
          }
        }
      }
      /**
       * 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 crypto7 from "crypto";
import path20 from "node:path";
import { promises as fs26 } from "node:fs";
import * as os11 from "os";
import { EventEmitter as EventEmitter2 } from "events";
import { randomUUID as randomUUID3 } from "node:crypto";
function generateCodeVerifier() {
  return crypto7.randomBytes(32).toString("base64url");
}
function generateCodeChallenge(codeVerifier) {
  const hash = crypto7.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 (error40) {
    if (error40 instanceof TokenManagerError) {
      switch (error40.type) {
        case TokenError.NO_REFRESH_TOKEN:
          debugLogger17.debug("No refresh token available, proceeding with device flow");
          break;
        case TokenError.REFRESH_FAILED:
          debugLogger17.debug("Token refresh failed, proceeding with device flow");
          break;
        case TokenError.NETWORK_ERROR:
          debugLogger17.warn("Network error during token refresh, trying device flow");
          break;
        default:
          debugLogger17.warn("Token manager error:", error40.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 url3 = verificationUriComplete;
  const minWidth = 70;
  const maxWidth = 80;
  const boxWidth = Math.min(Math.max(title.length + 4, minWidth), maxWidth);
  const contentWidth = boxWidth - 4;
  const wrapText3 = /* @__PURE__ */ __name((text, width) => {
    if (text.startsWith("http://") || text.startsWith("https://")) {
      const lines2 = [];
      for (let i4 = 0; i4 < text.length; i4 += width) {
        lines2.push(text.substring(i4, i4 + 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 = wrapText3("Please visit the following URL in your browser to authorize:", contentWidth);
  const urlLines = wrapText3(url3, 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.";
    debugLogger17.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 (url3) => {
    let childProcess3;
    try {
      childProcess3 = await open_default(url3);
      if (childProcess3 && typeof childProcess3.on === "function") {
        childProcess3.on("error", (err2) => {
          debugLogger17.warn(`Browser launch process error: ${err2.message}`);
          debugLogger17.info(`Please open this URL manually: ${url3}`);
        });
      } else {
        debugLogger17.debug("open() did not return a valid child process object.");
      }
    } catch (err2) {
      const errorMessage = err2 instanceof Error ? err2.message : String(err2);
      debugLogger17.warn(`Failed to open browser automatically: ${errorMessage}`);
      debugLogger17.info(`Please open this URL manually: ${url3}`);
    }
  }, "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...");
    debugLogger17.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 {
        debugLogger17.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.");
          debugLogger17.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);
            debugLogger17.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((resolve42) => {
            const checkInterval = 100;
            let elapsedTime = 0;
            const intervalId = setInterval(() => {
              elapsedTime += checkInterval;
              if (isCancelled) {
                clearInterval(intervalId);
                resolve42();
                return;
              }
              if (elapsedTime >= pollInterval) {
                clearInterval(intervalId);
                resolve42();
                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 (error40) {
        const errorMessage = error40 instanceof Error ? error40.message : String(error40);
        const statusCode = error40 instanceof Error ? error40.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((resolve42) => setTimeout(resolve42, pollInterval));
      }
    }
    const timeoutMessage = "Authorization timeout, please restart the process.";
    emitAuthProgress("timeout", timeoutMessage);
    return { success: false, reason: "timeout", message: timeoutMessage };
  } catch (error40) {
    const fullErrorMessage = formatFetchErrorForUser(error40, {
      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 fs26.mkdir(path20.dirname(filePath), { recursive: true });
    const credString = JSON.stringify(credentials, null, 2);
    await fs26.writeFile(filePath, credString);
  } catch (error40) {
    const errorMessage = error40 instanceof Error ? error40.message : String(error40);
    const errorCode = error40 instanceof Error && "code" in error40 ? error40.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 \`${path20.dirname(filePath)}\` and writing to \`${filePath}\`. ${errorMessage}. Please check permissions.`);
  }
}
async function clearQwenCredentials() {
  try {
    const filePath = getQwenCachedCredentialPath();
    await fs26.unlink(filePath);
    debugLogger17.debug("Cached Qwen credentials cleared successfully.");
  } catch (error40) {
    if (error40 instanceof Error && "code" in error40 && error40.code === "ENOENT") {
      return;
    }
    debugLogger17.warn("Warning: Failed to clear cached Qwen credentials:", error40);
  } finally {
    try {
      SharedTokenManager.getInstance().clearCache();
    } catch {
    }
  }
}
function getQwenCachedCredentialPath() {
  return path20.join(os11.homedir(), QWEN_DIR4, QWEN_CREDENTIAL_FILENAME2);
}
var debugLogger17, 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();
    debugLogger17 = 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 (error40) {
          debugLogger17.warn("Failed to get access token from shared manager:", error40);
          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();
        debugLogger17.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 error41 = new Error(`Device token poll failed: ${response.status} ${response.statusText}. Response: ${responseText}`);
            error41.status = response.status;
            throw error41;
          }
          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 error40 = new Error(`Device token poll failed: ${errorData.error || "Unknown error"} - ${errorData.error_description}`);
          error40.status = response.status;
          throw error40;
        }
        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 || response.status === 401) {
            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}`);
        }
        let responseText;
        try {
          responseText = await response.text();
        } catch {
          responseText = "";
        }
        let responseData;
        try {
          responseData = JSON.parse(responseText);
        } catch {
          throw new Error(`Qwen OAuth refresh returned invalid JSON: ${responseText || "(empty response body)"}`);
        }
        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(error40, _request) {
        return this.isAuthError(error40);
      }
      /**
       * 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 (error40) {
          if (this.isAuthError(error40)) {
            throw error40;
          }
          this.debugLogger.warn("Failed to get token from shared manager:", error40);
          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 (error40) {
          if (this.isAuthError(error40)) {
            await this.sharedManager.getValidCredentials(this.qwenClient, true);
            return await attemptOperation();
          }
          throw error40;
        }
      }
      /**
       * 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(error40) {
        if (!error40)
          return false;
        const errorMessage = error40 instanceof Error ? error40.message.toLowerCase() : String(error40).toLowerCase();
        const errorWithCode = error40;
        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 VERSION4;
var init_version3 = __esm({
  "node_modules/@anthropic-ai/sdk/version.mjs"() {
    init_esbuild_shims();
    VERSION4 = "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_lib3 = __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 i4 = 0; (c4 = x3.codePointAt(i4)) !== void 0; ++i4) {
        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 i4 = 0; i4 < n3; ++i4) {
        const c4 = S4.charCodeAt(i4);
        if (c4 < 55296 || c4 > 57343) {
          U2.push(String.fromCodePoint(c4));
        } else if (56320 <= c4 && c4 <= 57343) {
          U2.push(String.fromCodePoint(65533));
        } else {
          if (i4 === n3 - 1) {
            U2.push(String.fromCodePoint(65533));
          } else {
            const d2 = S4.charCodeAt(i4 + 1);
            if (56320 <= d2 && d2 <= 57343) {
              const a2 = c4 & 1023;
              const b2 = d2 & 1023;
              U2.push(String.fromCodePoint((2 << 15) + (2 << 9) * a2 + b2));
              ++i4;
            } 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_utils13 = __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 i4 = 0; i4 < keys.length; ++i4) {
        Object.defineProperty(target, keys[i4], Object.getOwnPropertyDescriptor(source2, keys[i4]));
      }
    }, "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/punycode/punycode.js
var require_punycode = __commonJS({
  "node_modules/punycode/punycode.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var maxInt = 2147483647;
    var base = 36;
    var tMin = 1;
    var tMax = 26;
    var skew = 38;
    var damp = 700;
    var initialBias = 72;
    var initialN = 128;
    var delimiter2 = "-";
    var regexPunycode = /^xn--/;
    var regexNonASCII = /[^\0-\x7F]/;
    var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
    var errors = {
      "overflow": "Overflow: input needs wider integers to process",
      "not-basic": "Illegal input >= 0x80 (not a basic code point)",
      "invalid-input": "Invalid input"
    };
    var baseMinusTMin = base - tMin;
    var floor = Math.floor;
    var stringFromCharCode = String.fromCharCode;
    function error40(type) {
      throw new RangeError(errors[type]);
    }
    __name(error40, "error");
    function map3(array2, callback) {
      const result = [];
      let length = array2.length;
      while (length--) {
        result[length] = callback(array2[length]);
      }
      return result;
    }
    __name(map3, "map");
    function mapDomain(domain2, callback) {
      const parts2 = domain2.split("@");
      let result = "";
      if (parts2.length > 1) {
        result = parts2[0] + "@";
        domain2 = parts2[1];
      }
      domain2 = domain2.replace(regexSeparators, ".");
      const labels = domain2.split(".");
      const encoded = map3(labels, callback).join(".");
      return result + encoded;
    }
    __name(mapDomain, "mapDomain");
    function ucs2decode(string4) {
      const output = [];
      let counter = 0;
      const length = string4.length;
      while (counter < length) {
        const value = string4.charCodeAt(counter++);
        if (value >= 55296 && value <= 56319 && counter < length) {
          const extra = string4.charCodeAt(counter++);
          if ((extra & 64512) == 56320) {
            output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
          } else {
            output.push(value);
            counter--;
          }
        } else {
          output.push(value);
        }
      }
      return output;
    }
    __name(ucs2decode, "ucs2decode");
    var ucs2encode = /* @__PURE__ */ __name((codePoints) => String.fromCodePoint(...codePoints), "ucs2encode");
    var basicToDigit = /* @__PURE__ */ __name(function(codePoint) {
      if (codePoint >= 48 && codePoint < 58) {
        return 26 + (codePoint - 48);
      }
      if (codePoint >= 65 && codePoint < 91) {
        return codePoint - 65;
      }
      if (codePoint >= 97 && codePoint < 123) {
        return codePoint - 97;
      }
      return base;
    }, "basicToDigit");
    var digitToBasic = /* @__PURE__ */ __name(function(digit, flag) {
      return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
    }, "digitToBasic");
    var adapt = /* @__PURE__ */ __name(function(delta, numPoints, firstTime) {
      let k2 = 0;
      delta = firstTime ? floor(delta / damp) : delta >> 1;
      delta += floor(delta / numPoints);
      for (; delta > baseMinusTMin * tMax >> 1; k2 += base) {
        delta = floor(delta / baseMinusTMin);
      }
      return floor(k2 + (baseMinusTMin + 1) * delta / (delta + skew));
    }, "adapt");
    var decode2 = /* @__PURE__ */ __name(function(input) {
      const output = [];
      const inputLength = input.length;
      let i4 = 0;
      let n3 = initialN;
      let bias = initialBias;
      let basic = input.lastIndexOf(delimiter2);
      if (basic < 0) {
        basic = 0;
      }
      for (let j2 = 0; j2 < basic; ++j2) {
        if (input.charCodeAt(j2) >= 128) {
          error40("not-basic");
        }
        output.push(input.charCodeAt(j2));
      }
      for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; ) {
        const oldi = i4;
        for (let w2 = 1, k2 = base; ; k2 += base) {
          if (index >= inputLength) {
            error40("invalid-input");
          }
          const digit = basicToDigit(input.charCodeAt(index++));
          if (digit >= base) {
            error40("invalid-input");
          }
          if (digit > floor((maxInt - i4) / w2)) {
            error40("overflow");
          }
          i4 += digit * w2;
          const t5 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
          if (digit < t5) {
            break;
          }
          const baseMinusT = base - t5;
          if (w2 > floor(maxInt / baseMinusT)) {
            error40("overflow");
          }
          w2 *= baseMinusT;
        }
        const out2 = output.length + 1;
        bias = adapt(i4 - oldi, out2, oldi == 0);
        if (floor(i4 / out2) > maxInt - n3) {
          error40("overflow");
        }
        n3 += floor(i4 / out2);
        i4 %= out2;
        output.splice(i4++, 0, n3);
      }
      return String.fromCodePoint(...output);
    }, "decode");
    var encode6 = /* @__PURE__ */ __name(function(input) {
      const output = [];
      input = ucs2decode(input);
      const inputLength = input.length;
      let n3 = initialN;
      let delta = 0;
      let bias = initialBias;
      for (const currentValue of input) {
        if (currentValue < 128) {
          output.push(stringFromCharCode(currentValue));
        }
      }
      const basicLength = output.length;
      let handledCPCount = basicLength;
      if (basicLength) {
        output.push(delimiter2);
      }
      while (handledCPCount < inputLength) {
        let m3 = maxInt;
        for (const currentValue of input) {
          if (currentValue >= n3 && currentValue < m3) {
            m3 = currentValue;
          }
        }
        const handledCPCountPlusOne = handledCPCount + 1;
        if (m3 - n3 > floor((maxInt - delta) / handledCPCountPlusOne)) {
          error40("overflow");
        }
        delta += (m3 - n3) * handledCPCountPlusOne;
        n3 = m3;
        for (const currentValue of input) {
          if (currentValue < n3 && ++delta > maxInt) {
            error40("overflow");
          }
          if (currentValue === n3) {
            let q2 = delta;
            for (let k2 = base; ; k2 += base) {
              const t5 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
              if (q2 < t5) {
                break;
              }
              const qMinusT = q2 - t5;
              const baseMinusT = base - t5;
              output.push(
                stringFromCharCode(digitToBasic(t5 + qMinusT % baseMinusT, 0))
              );
              q2 = floor(qMinusT / baseMinusT);
            }
            output.push(stringFromCharCode(digitToBasic(q2, 0)));
            bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
            delta = 0;
            ++handledCPCount;
          }
        }
        ++delta;
        ++n3;
      }
      return output.join("");
    }, "encode");
    var toUnicode = /* @__PURE__ */ __name(function(input) {
      return mapDomain(input, function(string4) {
        return regexPunycode.test(string4) ? decode2(string4.slice(4).toLowerCase()) : string4;
      });
    }, "toUnicode");
    var toASCII = /* @__PURE__ */ __name(function(input) {
      return mapDomain(input, function(string4) {
        return regexNonASCII.test(string4) ? "xn--" + encode6(string4) : string4;
      });
    }, "toASCII");
    var punycode = {
      /**
       * A string representing the current Punycode.js version number.
       * @memberOf punycode
       * @type String
       */
      "version": "2.3.1",
      /**
       * An object of methods to convert from JavaScript's internal character
       * representation (UCS-2) to Unicode code points, and back.
       * @see <https://mathiasbynens.be/notes/javascript-encoding>
       * @memberOf punycode
       * @type Object
       */
      "ucs2": {
        "decode": ucs2decode,
        "encode": ucs2encode
      },
      "decode": decode2,
      "encode": encode6,
      "toASCII": toASCII,
      "toUnicode": toUnicode
    };
    module2.exports = punycode;
  }
});

// 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 normalize13(str2) {
      return str2.split("\0").map(function(s5) {
        return s5.normalize("NFC");
      }).join("\0");
    }
    __name(normalize13, "normalize");
    function findStatus(val) {
      var start2 = 0;
      var end = mappingTable.length - 1;
      while (start2 <= end) {
        var mid = Math.floor((start2 + 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 {
          start2 = 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 i4 = 0; i4 < len; ++i4) {
        var codePoint = domain_name.codePointAt(i4);
        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 error40 = false;
      if (normalize13(label) !== label || label[3] === "-" && label[4] === "-" || label[0] === "-" || label[label.length - 1] === "-" || label.indexOf(".") !== -1 || label.search(combiningMarksRegex) === 0) {
        error40 = true;
      }
      var len = countSymbols(label);
      for (var i4 = 0; i4 < len; ++i4) {
        var status = findStatus(label.codePointAt(i4));
        if (processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid" || processing === PROCESSING_OPTIONS.NONTRANSITIONAL && status[1] !== "valid" && status[1] !== "deviation") {
          error40 = true;
          break;
        }
      }
      return {
        label,
        error: error40
      };
    }
    __name(validateLabel, "validateLabel");
    function processing(domain_name, useSTD3, processing_option) {
      var result = mapChars(domain_name, useSTD3, processing_option);
      result.string = normalize13(result.string);
      var labels = result.string.split(".");
      for (var i4 = 0; i4 < labels.length; ++i4) {
        try {
          var validation2 = validateLabel(labels[i4]);
          labels[i4] = 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 i4 = 0; i4 < labels.length; ++i4) {
          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(url3) {
      return isSpecialScheme(url3.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 i4 = 0; i4 < buf.length; ++i4) {
        str2 += percentEncode(buf[i4]);
      }
      return str2;
    }
    __name(utf8PercentEncode, "utf8PercentEncode");
    function utf8PercentDecode(str2) {
      const input = new Buffer(str2);
      const output = [];
      for (let i4 = 0; i4 < input.length; ++i4) {
        if (input[i4] !== 37) {
          output.push(input[i4]);
        } else if (input[i4] === 37 && isASCIIHex(input[i4 + 1]) && isASCIIHex(input[i4 + 2])) {
          output.push(parseInt(input.slice(i4 + 1, i4 + 3).toString(), 16));
          i4 += 2;
        } else {
          output.push(input[i4]);
        }
      }
      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 parts2 = input.split(".");
      if (parts2[parts2.length - 1] === "") {
        if (parts2.length > 1) {
          parts2.pop();
        }
      }
      if (parts2.length > 4) {
        return input;
      }
      const numbers = [];
      for (const part of parts2) {
        if (part === "") {
          return input;
        }
        const n3 = parseIPv4Number(part);
        if (n3 === failure) {
          return input;
        }
        numbers.push(n3);
      }
      for (let i4 = 0; i4 < numbers.length - 1; ++i4) {
        if (numbers[i4] > 255) {
          return failure;
        }
      }
      if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) {
        return failure;
      }
      let ipv43 = numbers.pop();
      let counter = 0;
      for (const n3 of numbers) {
        ipv43 += n3 * Math.pow(256, 3 - counter);
        ++counter;
      }
      return ipv43;
    }
    __name(parseIPv4, "parseIPv4");
    function serializeIPv4(address) {
      let output = "";
      let n3 = address;
      for (let i4 = 1; i4 <= 4; ++i4) {
        output = String(n3 % 256) + output;
        if (i4 !== 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 domain2 = utf8PercentDecode(input);
      const asciiDomain = tr46.toASCII(domain2, 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 i4 = 0; i4 < decoded.length; ++i4) {
        output += percentEncodeChar(decoded[i4], isC0ControlPercentEncode);
      }
      return output;
    }
    __name(parseOpaqueHost, "parseOpaqueHost");
    function findLongestZeroSequence(arr) {
      let maxIdx = null;
      let maxLen = 1;
      let currStart = null;
      let currLen = 0;
      for (let i4 = 0; i4 < arr.length; ++i4) {
        if (arr[i4] !== 0) {
          if (currLen > maxLen) {
            maxIdx = currStart;
            maxLen = currLen;
          }
          currStart = null;
          currLen = 0;
        } else {
          if (currStart === null) {
            currStart = i4;
          }
          ++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(url3) {
      return url3.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, "");
    }
    __name(trimControlChars, "trimControlChars");
    function trimTabAndNewline(url3) {
      return url3.replace(/\u0009|\u000A|\u000D/g, "");
    }
    __name(trimTabAndNewline, "trimTabAndNewline");
    function shortenPath2(url3) {
      const path150 = url3.path;
      if (path150.length === 0) {
        return;
      }
      if (url3.scheme === "file" && path150.length === 1 && isNormalizedWindowsDriveLetter(path150[0])) {
        return;
      }
      path150.pop();
    }
    __name(shortenPath2, "shortenPath");
    function includesCredentials(url3) {
      return url3.username !== "" || url3.password !== "";
    }
    __name(includesCredentials, "includesCredentials");
    function cannotHaveAUsernamePasswordPort(url3) {
      return url3.host === null || url3.host === "" || url3.cannotBeABaseURL || url3.scheme === "file";
    }
    __name(cannotHaveAUsernamePasswordPort, "cannotHaveAUsernamePasswordPort");
    function isNormalizedWindowsDriveLetter(string4) {
      return /^[A-Za-z]:$/.test(string4);
    }
    __name(isNormalizedWindowsDriveLetter, "isNormalizedWindowsDriveLetter");
    function URLStateMachine(input, base, encodingOverride, url3, stateOverride) {
      this.pointer = 0;
      this.input = input;
      this.base = base || null;
      this.encodingOverride = encodingOverride || "utf-8";
      this.stateOverride = stateOverride;
      this.url = url3;
      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 i4 = 0; i4 < buffer.length; ++i4) {
          if (buffer[i4] < 33 || buffer[i4] > 126 || buffer[i4] === 34 || buffer[i4] === 35 || buffer[i4] === 60 || buffer[i4] === 62) {
            this.url.query += percentEncode(buffer[i4]);
          } else {
            this.url.query += String.fromCodePoint(buffer[i4]);
          }
        }
        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(url3, excludeFragment) {
      let output = url3.scheme + ":";
      if (url3.host !== null) {
        output += "//";
        if (url3.username !== "" || url3.password !== "") {
          output += url3.username;
          if (url3.password !== "") {
            output += ":" + url3.password;
          }
          output += "@";
        }
        output += serializeHost(url3.host);
        if (url3.port !== null) {
          output += ":" + url3.port;
        }
      } else if (url3.host === null && url3.scheme === "file") {
        output += "//";
      }
      if (url3.cannotBeABaseURL) {
        output += url3.path[0];
      } else {
        for (const string4 of url3.path) {
          output += "/" + string4;
        }
      }
      if (url3.query !== null) {
        output += "?" + url3.query;
      }
      if (!excludeFragment && url3.fragment !== null) {
        output += "#" + url3.fragment;
      }
      return output;
    }
    __name(serializeURL, "serializeURL");
    function serializeOrigin(tuple2) {
      let result = tuple2.scheme + "://";
      result += serializeHost(tuple2.host);
      if (tuple2.port !== null) {
        result += ":" + tuple2.port;
      }
      return result;
    }
    __name(serializeOrigin, "serializeOrigin");
    module2.exports.serializeURL = serializeURL;
    module2.exports.serializeURLOrigin = function(url3) {
      switch (url3.scheme) {
        case "blob":
          try {
            return module2.exports.serializeURLOrigin(module2.exports.parseURL(url3.path[0]));
          } catch (e4) {
            return "null";
          }
        case "ftp":
        case "gopher":
        case "http":
        case "https":
        case "ws":
        case "wss":
          return serializeOrigin({
            scheme: url3.scheme,
            host: url3.host,
            port: url3.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(url3, username) {
      url3.username = "";
      const decoded = punycode.ucs2.decode(username);
      for (let i4 = 0; i4 < decoded.length; ++i4) {
        url3.username += percentEncodeChar(decoded[i4], isUserinfoPercentEncode);
      }
    };
    module2.exports.setThePassword = function(url3, password) {
      url3.password = "";
      const decoded = punycode.ucs2.decode(password);
      for (let i4 = 0; i4 < decoded.length; ++i4) {
        url3.password += percentEncodeChar(decoded[i4], 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 url3 = 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(url3, { 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 url3 = this._url;
        if (url3.host === null) {
          return "";
        }
        if (url3.port === null) {
          return usm.serializeHost(url3.host);
        }
        return usm.serializeHost(url3.host) + ":" + usm.serializeInteger(url3.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 url3 = this._url;
        if (v2 === "") {
          url3.query = null;
          return;
        }
        const input = v2[0] === "?" ? v2.substring(1) : v2;
        url3.query = "";
        usm.basicURLParse(input, { url: url3, 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_lib3();
    var utils = require_utils13();
    var Impl = require_URL_impl();
    var impl = utils.implSymbol;
    function URL5(url3) {
      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 args2 = [];
      for (let i4 = 0; i4 < arguments.length && i4 < 2; ++i4) {
        args2[i4] = arguments[i4];
      }
      args2[0] = conversions["USVString"](args2[0]);
      if (args2[1] !== void 0) {
        args2[1] = conversions["USVString"](args2[1]);
      }
      module2.exports.setup(this, args2);
    }
    __name(URL5, "URL");
    URL5.prototype.toJSON = /* @__PURE__ */ __name(function toJSON() {
      if (!this || !module2.exports.is(this)) {
        throw new TypeError("Illegal invocation");
      }
      const args2 = [];
      for (let i4 = 0; i4 < arguments.length && i4 < 0; ++i4) {
        args2[i4] = arguments[i4];
      }
      return this[impl].toJSON.apply(this[impl], args2);
    }, "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_lib4 = __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 http9 = _interopDefault(__require("http"));
    var Url = _interopDefault(__require("url"));
    var whatwgUrl = _interopDefault(require_public_api());
    var https9 = _interopDefault(__require("https"));
    var zlib5 = _interopDefault(__require("zlib"));
    var Readable8 = Stream9.Readable;
    var BUFFER4 = 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 i4 = 0; i4 < length; i4++) {
            const element = a2[i4];
            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[BUFFER4];
            } else {
              buffer = Buffer.from(typeof element === "string" ? element : String(element));
            }
            size += buffer.length;
            buffers.push(buffer);
          }
        }
        this[BUFFER4] = 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[BUFFER4].length;
      }
      get type() {
        return this[TYPE2];
      }
      text() {
        return Promise.resolve(this[BUFFER4].toString());
      }
      arrayBuffer() {
        const buf = this[BUFFER4];
        const ab2 = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
        return Promise.resolve(ab2);
      }
      stream() {
        const readable = new Readable8();
        readable._read = function() {
        };
        readable.push(this[BUFFER4]);
        readable.push(null);
        return readable;
      }
      toString() {
        return "[object Blob]";
      }
      slice() {
        const size = this.size;
        const start2 = arguments[0];
        const end = arguments[1];
        let relativeStart, relativeEnd;
        if (start2 === void 0) {
          relativeStart = 0;
        } else if (start2 < 0) {
          relativeStart = Math.max(size + start2, 0);
        } else {
          relativeStart = Math.min(start2, 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[BUFFER4];
        const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
        const blob = new _Blob2([], { type: arguments[2] });
        blob[BUFFER4] = 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(body2) {
      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 (body2 == null) {
        body2 = null;
      } else if (isURLSearchParams2(body2)) {
        body2 = Buffer.from(body2.toString());
      } else if (isBlob5(body2)) ;
      else if (Buffer.isBuffer(body2)) ;
      else if (Object.prototype.toString.call(body2) === "[object ArrayBuffer]") {
        body2 = Buffer.from(body2);
      } else if (ArrayBuffer.isView(body2)) {
        body2 = Buffer.from(body2.buffer, body2.byteOffset, body2.byteLength);
      } else if (body2 instanceof Stream9) ;
      else {
        body2 = Buffer.from(String(body2));
      }
      this[INTERNALS7] = {
        body: body2,
        disturbed: false,
        error: null
      };
      this.size = size;
      this.timeout = timeout2;
      if (body2 instanceof Stream9) {
        body2.on("error", function(err2) {
          const error40 = err2.name === "AbortError" ? err2 : new FetchError4(`Invalid response body while trying to fetch ${_this.url}: ${err2.message}`, "system", err2);
          _this[INTERNALS7].error = error40;
        });
      }
    }
    __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()
            }),
            {
              [BUFFER4]: 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 (err2) {
            return Body3.Promise.reject(new FetchError4(`invalid json response body at ${_this2.url} reason: ${err2.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 name4 of Object.getOwnPropertyNames(Body3.prototype)) {
        if (!(name4 in proto3)) {
          const desc2 = Object.getOwnPropertyDescriptor(Body3.prototype, name4);
          Object.defineProperty(proto3, name4, 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 body2 = this.body;
      if (body2 === null) {
        return Body3.Promise.resolve(Buffer.alloc(0));
      }
      if (isBlob5(body2)) {
        body2 = body2.stream();
      }
      if (Buffer.isBuffer(body2)) {
        return Body3.Promise.resolve(body2);
      }
      if (!(body2 instanceof Stream9)) {
        return Body3.Promise.resolve(Buffer.alloc(0));
      }
      let accum = [];
      let accumBytes = 0;
      let abort2 = false;
      return new Body3.Promise(function(resolve42, reject) {
        let resTimeout;
        if (_this4.timeout) {
          resTimeout = setTimeout(function() {
            abort2 = true;
            reject(new FetchError4(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, "body-timeout"));
          }, _this4.timeout);
        }
        body2.on("error", function(err2) {
          if (err2.name === "AbortError") {
            abort2 = true;
            reject(err2);
          } else {
            reject(new FetchError4(`Invalid response body while trying to fetch ${_this4.url}: ${err2.message}`, "system", err2));
          }
        });
        body2.on("data", function(chunk) {
          if (abort2 || chunk === null) {
            return;
          }
          if (_this4.size && accumBytes + chunk.length > _this4.size) {
            abort2 = true;
            reject(new FetchError4(`content size at ${_this4.url} over limit: ${_this4.size}`, "max-size"));
            return;
          }
          accumBytes += chunk.length;
          accum.push(chunk);
        });
        body2.on("end", function() {
          if (abort2) {
            return;
          }
          clearTimeout(resTimeout);
          try {
            resolve42(Buffer.concat(accum, accumBytes));
          } catch (err2) {
            reject(new FetchError4(`Could not create Buffer from response body for ${_this4.url}: ${err2.message}`, "system", err2));
          }
        });
      });
    }
    __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 isURLSearchParams2(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(isURLSearchParams2, "isURLSearchParams");
    function isBlob5(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(isBlob5, "isBlob");
    function clone4(instance2) {
      let p1, p2;
      let body2 = instance2.body;
      if (instance2.bodyUsed) {
        throw new Error("cannot clone body after it is used");
      }
      if (body2 instanceof Stream9 && typeof body2.getBoundary !== "function") {
        p1 = new PassThrough8();
        p2 = new PassThrough8();
        body2.pipe(p1);
        body2.pipe(p2);
        instance2[INTERNALS7].body = p1;
        body2 = p2;
      }
      return body2;
    }
    __name(clone4, "clone");
    function extractContentType3(body2) {
      if (body2 === null) {
        return null;
      } else if (typeof body2 === "string") {
        return "text/plain;charset=UTF-8";
      } else if (isURLSearchParams2(body2)) {
        return "application/x-www-form-urlencoded;charset=UTF-8";
      } else if (isBlob5(body2)) {
        return body2.type || null;
      } else if (Buffer.isBuffer(body2)) {
        return null;
      } else if (Object.prototype.toString.call(body2) === "[object ArrayBuffer]") {
        return null;
      } else if (ArrayBuffer.isView(body2)) {
        return null;
      } else if (typeof body2.getBoundary === "function") {
        return `multipart/form-data;boundary=${body2.getBoundary()}`;
      } else if (body2 instanceof Stream9) {
        return null;
      } else {
        return "text/plain;charset=UTF-8";
      }
    }
    __name(extractContentType3, "extractContentType");
    function getTotalBytes3(instance2) {
      const body2 = instance2.body;
      if (body2 === null) {
        return 0;
      } else if (isBlob5(body2)) {
        return body2.size;
      } else if (Buffer.isBuffer(body2)) {
        return body2.length;
      } else if (body2 && typeof body2.getLengthSync === "function") {
        if (body2._lengthRetrievers && body2._lengthRetrievers.length == 0 || // 1.x
        body2.hasKnownLength && body2.hasKnownLength()) {
          return body2.getLengthSync();
        }
        return null;
      } else {
        return null;
      }
    }
    __name(getTotalBytes3, "getTotalBytes");
    function writeToStream3(dest, instance2) {
      const body2 = instance2.body;
      if (body2 === null) {
        dest.end();
      } else if (isBlob5(body2)) {
        body2.stream().pipe(dest);
      } else if (Buffer.isBuffer(body2)) {
        dest.write(body2);
        dest.end();
      } else {
        body2.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(name4) {
      name4 = `${name4}`;
      if (invalidTokenRegex.test(name4) || name4 === "") {
        throw new TypeError(`${name4} 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(map3, name4) {
      name4 = name4.toLowerCase();
      for (const key in map3) {
        if (key.toLowerCase() === name4) {
          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 init2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : void 0;
        this[MAP] = /* @__PURE__ */ Object.create(null);
        if (init2 instanceof _Headers) {
          const rawHeaders = init2.raw();
          const headerNames = Object.keys(rawHeaders);
          for (const headerName of headerNames) {
            for (const value of rawHeaders[headerName]) {
              this.append(headerName, value);
            }
          }
          return;
        }
        if (init2 == null) ;
        else if (typeof init2 === "object") {
          const method = init2[Symbol.iterator];
          if (method != null) {
            if (typeof method !== "function") {
              throw new TypeError("Header pairs must be iterable");
            }
            const pairs = [];
            for (const pair of init2) {
              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(init2)) {
              const value = init2[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(name4) {
        name4 = `${name4}`;
        validateName2(name4);
        const key = find(this[MAP], name4);
        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 i4 = 0;
        while (i4 < pairs.length) {
          var _pairs$i = pairs[i4];
          const name4 = _pairs$i[0], value = _pairs$i[1];
          callback.call(thisArg, value, name4, this);
          pairs = getHeaders(this);
          i4++;
        }
      }
      /**
       * Overwrite header values given name
       *
       * @param   String  name   Header name
       * @param   String  value  Header value
       * @return  Void
       */
      set(name4, value) {
        name4 = `${name4}`;
        value = `${value}`;
        validateName2(name4);
        validateValue2(value);
        const key = find(this[MAP], name4);
        this[MAP][key !== void 0 ? key : name4] = [value];
      }
      /**
       * Append a value onto existing header
       *
       * @param   String  name   Header name
       * @param   String  value  Header value
       * @return  Void
       */
      append(name4, value) {
        name4 = `${name4}`;
        value = `${value}`;
        validateName2(name4);
        validateValue2(value);
        const key = find(this[MAP], name4);
        if (key !== void 0) {
          this[MAP][key].push(value);
        } else {
          this[MAP][name4] = [value];
        }
      }
      /**
       * Check for header name existence
       *
       * @param   String   name  Header name
       * @return  Boolean
       */
      has(name4) {
        name4 = `${name4}`;
        validateName2(name4);
        return find(this[MAP], name4) !== void 0;
      }
      /**
       * Delete all header values given name
       *
       * @param   String  name  Header name
       * @return  Void
       */
      delete(name4) {
        name4 = `${name4}`;
        validateName2(name4);
        const key = find(this[MAP], name4);
        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 INTERNAL2 = Symbol("internal");
    function createHeadersIterator(target, kind2) {
      const iterator2 = Object.create(HeadersIteratorPrototype);
      iterator2[INTERNAL2] = {
        target,
        kind: kind2,
        index: 0
      };
      return iterator2;
    }
    __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[INTERNAL2];
        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[INTERNAL2].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 name4 of Object.keys(obj)) {
        if (invalidTokenRegex.test(name4)) {
          continue;
        }
        if (Array.isArray(obj[name4])) {
          for (const val of obj[name4]) {
            if (invalidHeaderCharRegex.test(val)) {
              continue;
            }
            if (headers[MAP][name4] === void 0) {
              headers[MAP][name4] = [val];
            } else {
              headers[MAP][name4].push(val);
            }
          }
        } else if (!invalidHeaderCharRegex.test(obj[name4])) {
          headers[MAP][name4] = [obj[name4]];
        }
      }
      return headers;
    }
    __name(createHeadersLenient, "createHeadersLenient");
    var INTERNALS$1 = Symbol("Response internals");
    var STATUS_CODES = http9.STATUS_CODES;
    var Response6 = class _Response {
      static {
        __name(this, "Response");
      }
      constructor() {
        let body2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : null;
        let opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        Body3.call(this, body2, opts);
        const status = opts.status || 200;
        const headers = new Headers6(opts.headers);
        if (body2 != null && !headers.has("Content-Type")) {
          const contentType = extractContentType3(body2);
          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 isRequest4(input) {
      return typeof input === "object" && typeof input[INTERNALS$2] === "object";
    }
    __name(isRequest4, "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 init2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        let parsedURL;
        if (!isRequest4(input)) {
          if (input && input.href) {
            parsedURL = parseURL(input.href);
          } else {
            parsedURL = parseURL(`${input}`);
          }
          input = {};
        } else {
          parsedURL = parseURL(input.url);
        }
        let method = init2.method || input.method || "GET";
        method = method.toUpperCase();
        if ((init2.body != null || isRequest4(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body");
        }
        let inputBody = init2.body != null ? init2.body : isRequest4(input) && input.body !== null ? clone4(input) : null;
        Body3.call(this, inputBody, {
          timeout: init2.timeout || input.timeout || 0,
          size: init2.size || input.size || 0
        });
        const headers = new Headers6(init2.headers || input.headers || {});
        if (inputBody != null && !headers.has("Content-Type")) {
          const contentType = extractContentType3(inputBody);
          if (contentType) {
            headers.append("Content-Type", contentType);
          }
        }
        let signal = isRequest4(input) ? input.signal : null;
        if ("signal" in init2) signal = init2.signal;
        if (signal != null && !isAbortSignal3(signal)) {
          throw new TypeError("Expected signal to be an instanceof AbortSignal");
        }
        this[INTERNALS$2] = {
          method,
          redirect: init2.redirect || input.redirect || "follow",
          headers,
          parsedURL,
          signal
        };
        this.follow = init2.follow !== void 0 ? init2.follow : input.follow !== void 0 ? input.follow : 20;
        this.compress = init2.compress !== void 0 ? init2.compress : input.compress !== void 0 ? input.compress : true;
        this.counter = init2.counter || input.counter || 0;
        this.agent = init2.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(url3, 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(resolve42, reject) {
        const request4 = new Request6(url3, opts);
        const options2 = getNodeRequestOptions3(request4);
        const send = (options2.protocol === "https:" ? https9 : http9).request;
        const signal = request4.signal;
        let response = null;
        const abort2 = /* @__PURE__ */ __name(function abort3() {
          let error40 = new AbortError4("The user aborted a request.");
          reject(error40);
          if (request4.body && request4.body instanceof Stream9.Readable) {
            destroyStream(request4.body, error40);
          }
          if (!response || !response.body) return;
          response.body.emit("error", error40);
        }, "abort");
        if (signal && signal.aborted) {
          abort2();
          return;
        }
        const abortAndFinalize = /* @__PURE__ */ __name(function abortAndFinalize2() {
          abort2();
          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(err2) {
          reject(new FetchError4(`request to ${request4.url} failed, reason: ${err2.message}`, "system", err2));
          if (response && response.body) {
            destroyStream(response.body, err2);
          }
          finalize();
        });
        fixResponseChunkedTransferBadEnding3(req, function(err2) {
          if (signal && signal.aborted) {
            return;
          }
          if (response && response.body) {
            destroyStream(response.body, err2);
          }
        });
        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 err2 = new Error("Premature close");
                err2.code = "ERR_STREAM_PREMATURE_CLOSE";
                response.body.emit("error", err2);
              }
            });
          });
        }
        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 (err2) {
              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 (err2) {
                    reject(err2);
                  }
                }
                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 name4 of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                    requestOpts.headers.delete(name4);
                  }
                }
                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");
                }
                resolve42(fetch5(new Request6(locationURL, requestOpts)));
                finalize();
                return;
            }
          }
          res.once("end", function() {
            if (signal) signal.removeEventListener("abort", abortAndFinalize);
          });
          let body2 = 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(body2, response_options);
            resolve42(response);
            return;
          }
          const zlibOptions2 = {
            flush: zlib5.Z_SYNC_FLUSH,
            finishFlush: zlib5.Z_SYNC_FLUSH
          };
          if (codings == "gzip" || codings == "x-gzip") {
            body2 = body2.pipe(zlib5.createGunzip(zlibOptions2));
            response = new Response6(body2, response_options);
            resolve42(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) {
                body2 = body2.pipe(zlib5.createInflate());
              } else {
                body2 = body2.pipe(zlib5.createInflateRaw());
              }
              response = new Response6(body2, response_options);
              resolve42(response);
            });
            raw2.on("end", function() {
              if (!response) {
                response = new Response6(body2, response_options);
                resolve42(response);
              }
            });
            return;
          }
          if (codings == "br" && typeof zlib5.createBrotliDecompress === "function") {
            body2 = body2.pipe(zlib5.createBrotliDecompress());
            response = new Response6(body2, response_options);
            resolve42(response);
            return;
          }
          response = new Response6(body2, response_options);
          resolve42(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 err2 = new Error("Premature close");
              err2.code = "ERR_STREAM_PREMATURE_CLOSE";
              errorCallback(err2);
            }
          });
        }
      });
    }
    __name(fixResponseChunkedTransferBadEnding3, "fixResponseChunkedTransferBadEnding");
    function destroyStream(stream5, err2) {
      if (stream5.destroy) {
        stream5.destroy(err2);
      } else {
        stream5.emit("error", err2);
        stream5.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 i3.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[C2](), 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, i4 = a2 - a2 % r5;
  let l3 = n3, s5 = false;
  i4 > o3 && (l3 = i4 - 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, i4;
  n3 = void 0 !== t5.start ? () => t5.start(o3) : () => {
  }, a2 = void 0 !== t5.pull ? () => t5.pull(o3) : () => c(void 0), i4 = 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, i5) {
    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 = i5, 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, i4, 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 WritableStream2);
}
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 i4 = 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 C3 = 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(i4.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(() => i4.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 ? i4.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(() => i4.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(C3, 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(), i4.releaseLock(), void 0 !== a2 && a2.removeEventListener("abort", k2), e5 ? W2(t6) : P2(void 0), null;
    }
    __name(F4, "F");
    w2 || (b(i4.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, i4 = 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 !== i4 || (o3.error(t7), n3.error(t7), h3 && p2 || a2(void 0)), null));
    }
    __name(y2, "y");
    function g2() {
      l3 && (i4.releaseLock(), i4 = e5.getReader(), y2(i4), l3 = false), b(i4.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(i4.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 || (i4.releaseLock(), i4 = e5.getReader({ mode: "byob" }), y2(i4), l3 = true);
      const u2 = r6 ? n3 : o3, c4 = r6 ? o3 : n3;
      b(i4.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(i4.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 = i4.cancel(e7);
        a2(o4);
      }
      return m3;
    }
    __name(R2, "R");
    function T2(e6) {
      if (p2 = true, r5 = e6, h3) {
        const e7 = [t6, r5], o4 = i4.cancel(e7);
        a2(o4);
      }
      return m3;
    }
    __name(T2, "T");
    const q2 = new ReadableStream3({ type: "bytes", start(e6) {
      o3 = e6;
    }, pull: S4, cancel: R2 }), C3 = new ReadableStream3({ type: "bytes", start(e6) {
      n3 = e6;
    }, pull: v2, cancel: T2 });
    return y2(i4), [q2, C3];
  }(e4) : function(e5, t6) {
    const r5 = e5.getReader();
    let o3, n3, a2, i4, 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 || i4.close(), f5 && h3 || l3(void 0), null;
        const t7 = e6.value, r6 = t7, o4 = t7;
        return f5 || a2.enqueue(r6), h3 || i4.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) {
      i4 = e6;
    }, pull: m3, cancel: g2 });
    return _(r5.closed, (e6) => (a2.error(e6), i4.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, i4, l3;
  a2 = void 0 !== t5.start ? () => t5.start(n3) : () => {
  }, i4 = 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, i5) {
    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 = i5, 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, i4, 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, i3, l, s2, y, S2, v, R, T, q, C2, z, L, ReadableStreamDefaultReader, te, re2, ae, ReadableStreamBYOBRequest, ReadableByteStreamController, ReadableStreamBYOBReader, Ue, WritableStream2, 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;
    i3 = 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]]");
    C2 = 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, i4 = 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, i4, n3, a2);
          else {
            e5._pendingPullIntos.length > 0 && Ce(e5);
            G(r5, new Uint8Array(i4, n3, a2), false);
          }
          else Le(r5) ? (me(e5, i4, n3, a2), Te(e5)) : me(e5, i4, 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);
      }
      [C2]() {
        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, i4 = t7.buffer, l3 = { buffer: i4, bufferByteLength: i4.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;
    WritableStream2 = 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, i4 = 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 === i4 ? void 0 : Ve(i4, 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, i4, l3, s5;
          a3 = void 0 !== t6.start ? () => t6.start(n4) : () => {
          };
          i4 = 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, i5, 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 = i5, 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, i4, 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(WritableStream2.prototype, { abort: { enumerable: true }, close: { enumerable: true }, getWriter: { enumerable: true }, locked: { enumerable: true } }), n(WritableStream2.prototype.abort, "abort"), n(WritableStream2.prototype.close, "close"), n(WritableStream2.prototype.getWriter, "getWriter"), "symbol" == typeof e2.toStringTag && Object.defineProperty(WritableStream2.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 i4 = 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), i4;
        }(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);
      }
      [C2]() {
      }
    };
    __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, i4 = 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 === i4 ? void 0 : Yt(i4, 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, i5 = 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: i5 };
        }(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 i4 = $e(n3, 0), l3 = Me(n3), s5 = $e(o3, 1), f5 = Me(o3);
        let b2;
        !function(e5, t6, r6, o4, n4, a3) {
          function i5() {
            return t6;
          }
          __name(i5, "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, i6) {
            return new WritableStream2({ 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: i6 });
          }(e5, i5, 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, i5, 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, i4, 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(parts2, clone4 = false) {
  for (const part of parts2) {
    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, start2 = 0, end) {
  end !== null && end !== void 0 ? end : end = blobSize;
  let relativeStart = start2 < 0 ? Math.max(blobSize + start2, 0) : Math.min(start2, 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 __classPrivateFieldGet3, __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();
    __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);
    };
    __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, __classPrivateFieldGet3(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f");
          __classPrivateFieldGet3(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 __classPrivateFieldGet3(this, _Blob_type, "f");
      }
      get size() {
        return __classPrivateFieldGet3(this, _Blob_size, "f");
      }
      slice(start2, end, contentType) {
        return new _Blob2(sliceBlob(__classPrivateFieldGet3(this, _Blob_parts, "f"), this.size, start2, end), {
          type: contentType
        });
      }
      async text() {
        const decoder = new TextDecoder();
        let result = "";
        for await (const chunk of consumeBlobParts(__classPrivateFieldGet3(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(__classPrivateFieldGet3(this, _Blob_parts, "f"))) {
          view.set(chunk, offset);
          offset += chunk.length;
        }
        return view.buffer;
      }
      stream() {
        const iterator2 = consumeBlobParts(__classPrivateFieldGet3(this, _Blob_parts, "f"), true);
        return new ReadableStream3({
          async pull(controller) {
            const { value, done } = await iterator2.next();
            if (done) {
              return queueMicrotask(() => controller.close());
            }
            controller.enqueue(value);
          },
          async cancel() {
            await iterator2.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, __classPrivateFieldGet4, _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;
    };
    __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);
    };
    File5 = class extends Blob5 {
      static {
        __name(this, "File");
      }
      constructor(fileBits, name4, 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(name4), "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 __classPrivateFieldGet4(this, _File_name, "f");
      }
      get lastModified() {
        return __classPrivateFieldGet4(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 __classPrivateFieldGet5, _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();
    __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);
    };
    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: name4, value, fileName }) => this.append(name4, 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(name4, value, fileName) {
        __classPrivateFieldGet5(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
          name: name4,
          fileName,
          append: true,
          rawValue: value,
          argsLength: arguments.length
        });
      }
      set(name4, value, fileName) {
        __classPrivateFieldGet5(this, _FormData_instances, "m", _FormData_setEntry).call(this, {
          name: name4,
          fileName,
          append: false,
          rawValue: value,
          argsLength: arguments.length
        });
      }
      get(name4) {
        const field = __classPrivateFieldGet5(this, _FormData_entries, "f").get(String(name4));
        if (!field) {
          return null;
        }
        return field[0];
      }
      getAll(name4) {
        const field = __classPrivateFieldGet5(this, _FormData_entries, "f").get(String(name4));
        if (!field) {
          return [];
        }
        return field.slice();
      }
      has(name4) {
        return __classPrivateFieldGet5(this, _FormData_entries, "f").has(String(name4));
      }
      delete(name4) {
        __classPrivateFieldGet5(this, _FormData_entries, "f").delete(String(name4));
      }
      *keys() {
        for (const key of __classPrivateFieldGet5(this, _FormData_entries, "f").keys()) {
          yield key;
        }
      }
      *entries() {
        for (const name4 of this.keys()) {
          const values = this.getAll(name4);
          for (const value of values) {
            yield [name4, value];
          }
        }
      }
      *values() {
        for (const [, value] of this) {
          yield value;
        }
      }
      [(_FormData_setEntry = /* @__PURE__ */ __name(function _FormData_setEntry2({ name: name4, rawValue, append: append3, fileName, argsLength }) {
        const methodName = append3 ? "append" : "set";
        if (argsLength < 2) {
          throw new TypeError(`Failed to execute '${methodName}' on 'FormData': 2 arguments required, but only ${argsLength} present.`);
        }
        name4 = String(name4);
        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 = __classPrivateFieldGet5(this, _FormData_entries, "f").get(name4);
        if (!values) {
          return void __classPrivateFieldGet5(this, _FormData_entries, "f").set(name4, [value]);
        }
        if (!append3) {
          return void __classPrivateFieldGet5(this, _FormData_entries, "f").set(name4, [value]);
        }
        values.push(value);
      }, "_FormData_setEntry"), Symbol.iterator)]() {
        return this.entries();
      }
      forEach(callback, thisArg) {
        for (const [name4, value] of this) {
          callback.call(thisArg, value, name4, 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 util5 = __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 err2 = new Error(util5.format("humanize-ms(%j) result undefined", t5));
        console.warn(err2.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(...args2) {
        super.reuseSocket(...args2);
        const socket = args2[0];
        const req = args2[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((err2, socket) => {
          if (called) return;
          called = true;
          if (err2) {
            this.createSocketErrorCount++;
            return oncreate(err2);
          }
          this[INIT_SOCKET](socket, options2);
          oncreate(err2, 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 name4 = agent.getName(options2);
        if (socket.writable && agent.requests[name4] && agent.requests[name4].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 name4 = agent.getName(options2);
        if (agent.freeSockets[name4] && agent.freeSockets[name4].indexOf(socket) !== -1) {
          socket.destroy();
          agent.removeSocket(socket, options2);
          debug3("%s is free, destroy quietly", socket[SOCKET_NAME]);
        } else {
          if (reqTimeoutListenerCount === 0) {
            const error40 = new Error("Socket timeout");
            error40.code = "ERR_SOCKET_TIMEOUT";
            error40.timeout = timeout2;
            socket.destroy(error40);
            agent.removeSocket(socket, options2);
            debug3("%s destroy with timeout error", socket[SOCKET_NAME]);
          }
        }
      }
      __name(onTimeout, "onTimeout");
      socket.on("timeout", onTimeout);
      function onError2(err2) {
        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],
          err2,
          listenerCount
        );
        agent.errorSocketCount++;
        if (listenerCount === 1) {
          debug3("%s emit uncaught error event", socket[SOCKET_NAME]);
          socket.removeListener("error", onError2);
          socket.emit("error", err2);
        }
      }
      __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 i4 = 0; i4 < keys.length; ++i4) {
        const key = keys[i4];
        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 i4 = 0; i4 < keys.length; ++i4) {
        const key = keys[i4];
        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 isObject5(x3) {
      return x3 !== null && typeof x3 === "object";
    }
    __name(isObject5, "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" && !isObject5(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 i4 = 0; i4 < eventNames.length; ++i4) {
        defineEventAttribute(CustomEventTarget.prototype, eventNames[i4]);
      }
      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 i4 = 0; i4 < arguments.length; ++i4) {
          types7[i4] = arguments[i4];
        }
        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" && !isObject5(listener)) {
          throw new TypeError("'listener' should be a function or an object.");
        }
        const listeners = getListeners(this);
        const optionsIsObj = isObject5(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 = isObject5(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 (err2) {
              if (typeof console !== "undefined" && typeof console.error === "function") {
                console.error(err2);
              }
            }
          } 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, i4, str2) => {
      if (match2 === "\r" && str2[i4 + 1] !== "\n" || match2 === "\n" && str2[i4 - 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((name4) => String(name4).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, __classPrivateFieldGet6, _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;
    };
    __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);
    };
    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, __classPrivateFieldGet6(this, _FormDataEncoder_encoder, "f").encode(__classPrivateFieldGet6(this, _FormDataEncoder_CRLF, "f")), "f");
        __classPrivateFieldSet4(this, _FormDataEncoder_CRLF_BYTES_LENGTH, __classPrivateFieldGet6(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, __classPrivateFieldGet6(this, _FormDataEncoder_encoder, "f").encode(`${__classPrivateFieldGet6(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet6(this, _FormDataEncoder_DASHES, "f")}${__classPrivateFieldGet6(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 [name4, raw2] of __classPrivateFieldGet6(this, _FormDataEncoder_form, "f")) {
          const value = isFileLike2(raw2) ? raw2 : __classPrivateFieldGet6(this, _FormDataEncoder_encoder, "f").encode(normalizeValue_default(raw2));
          length += __classPrivateFieldGet6(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name4, value).byteLength;
          length += isFileLike2(value) ? value.size : value.byteLength;
          length += __classPrivateFieldGet6(this, _FormDataEncoder_CRLF_BYTES_LENGTH, "f");
        }
        return length + __classPrivateFieldGet6(this, _FormDataEncoder_footer, "f").byteLength;
      }
      *values() {
        for (const [name4, raw2] of __classPrivateFieldGet6(this, _FormDataEncoder_form, "f").entries()) {
          const value = isFileLike2(raw2) ? raw2 : __classPrivateFieldGet6(this, _FormDataEncoder_encoder, "f").encode(normalizeValue_default(raw2));
          yield __classPrivateFieldGet6(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name4, value);
          yield value;
          yield __classPrivateFieldGet6(this, _FormDataEncoder_CRLF_BYTES, "f");
        }
        yield __classPrivateFieldGet6(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(name4, value) {
        let header = "";
        header += `${__classPrivateFieldGet6(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet6(this, _FormDataEncoder_CRLF, "f")}`;
        header += `Content-Disposition: form-data; name="${escapeName_default(name4)}"`;
        if (isFileLike2(value)) {
          header += `; filename="${escapeName_default(value.name)}"${__classPrivateFieldGet6(this, _FormDataEncoder_CRLF, "f")}`;
          header += `Content-Type: ${value.type || "application/octet-stream"}`;
        }
        if (__classPrivateFieldGet6(this, _FormDataEncoder_options, "f").enableAdditionalHeaders === true) {
          header += `${__classPrivateFieldGet6(this, _FormDataEncoder_CRLF, "f")}Content-Length: ${isFileLike2(value) ? value.size : value.byteLength}`;
        }
        return __classPrivateFieldGet6(this, _FormDataEncoder_encoder, "f").encode(`${header}${__classPrivateFieldGet6(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(body2) {
        this.body = body2;
      }
      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 fs27 } from "fs";
import { basename as basename6 } from "path";
function createFileFromPath(path150, { mtimeMs, size }, filenameOrOptions, options2 = {}) {
  let filename;
  if (isPlainObject_default2(filenameOrOptions)) {
    [options2, filename] = [filenameOrOptions, void 0];
  } else {
    filename = filenameOrOptions;
  }
  const file2 = new FileFromPath({ path: path150, size, lastModified: mtimeMs });
  if (!filename) {
    filename = file2.name;
  }
  return new File5([file2], filename, {
    ...options2,
    lastModified: file2.lastModified
  });
}
function fileFromPathSync(path150, filenameOrOptions, options2 = {}) {
  const stats = statSync2(path150);
  return createFileFromPath(path150, stats, filenameOrOptions, options2);
}
async function fileFromPath2(path150, filenameOrOptions, options2) {
  const stats = await fs27.stat(path150);
  return createFileFromPath(path150, stats, filenameOrOptions, options2);
}
var import_node_domexception2, __classPrivateFieldSet5, __classPrivateFieldGet7, _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;
    };
    __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);
    };
    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 = basename6(__classPrivateFieldGet7(this, _FileFromPath_path, "f"));
        this.size = input.size;
        this.lastModified = input.lastModified;
      }
      slice(start2, end) {
        return new _FileFromPath({
          path: __classPrivateFieldGet7(this, _FileFromPath_path, "f"),
          lastModified: this.lastModified,
          size: end - start2,
          start: start2
        });
      }
      async *stream() {
        const { mtimeMs } = await fs27.stat(__classPrivateFieldGet7(this, _FileFromPath_path, "f"));
        if (mtimeMs > this.lastModified) {
          throw new import_node_domexception2.default(MESSAGE, "NotReadableError");
        }
        if (this.size) {
          yield* createReadStream2(__classPrivateFieldGet7(this, _FileFromPath_path, "f"), {
            start: __classPrivateFieldGet7(this, _FileFromPath_start, "f"),
            end: __classPrivateFieldGet7(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(path150, ...args2) {
  const { fileFromPath: _fileFromPath } = await Promise.resolve().then(() => (init_fileFromPath(), fileFromPath_exports));
  if (!fileFromPathWarned) {
    console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path150)}) instead`);
    fileFromPathWarned = true;
  }
  return await _fileFromPath(path150, ...args2);
}
async function getMultipartRequestOptions2(form, opts) {
  const encoder = new FormDataEncoder(form);
  const readable = Readable3.from(encoder);
  const body2 = new MultipartBody(readable);
  const headers = {
    ...opts.headers,
    ...encoder.headers,
    "Content-Length": encoder.contentLength
  };
  return { ...opts, body: body2, 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((url3) => url3.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_lib4(), 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, error40, message, headers) {
        super(`${_APIError.makeMessage(status, error40, message)}`);
        this.status = status;
        this.headers = headers;
        this.request_id = headers?.["request-id"];
        this.error = error40;
      }
      static makeMessage(status, error40, message) {
        const msg = error40?.message ? typeof error40.message === "string" ? error40.message : JSON.stringify(error40.message) : error40 ? JSON.stringify(error40) : 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 error40 = errorResponse;
        if (status === 400) {
          return new BadRequestError3(status, error40, message, headers);
        }
        if (status === 401) {
          return new AuthenticationError2(status, error40, message, headers);
        }
        if (status === 403) {
          return new PermissionDeniedError2(status, error40, message, headers);
        }
        if (status === 404) {
          return new NotFoundError2(status, error40, message, headers);
        }
        if (status === 409) {
          return new ConflictError2(status, error40, message, headers);
        }
        if (status === 422) {
          return new UnprocessableEntityError2(status, error40, message, headers);
        }
        if (status === 429) {
          return new RateLimitError2(status, error40, message, headers);
        }
        if (status >= 500) {
          return new InternalServerError2(status, error40, message, headers);
        }
        return new _APIError(status, error40, 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(stream5) {
  if (stream5[Symbol.asyncIterator])
    return stream5;
  const reader = stream5.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(iterator2) {
  let data = new Uint8Array();
  for await (const chunk of iterator2) {
    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 i4 = 0; i4 < buffer.length - 2; i4++) {
    if (buffer[i4] === newline2 && buffer[i4 + 1] === newline2) {
      return i4 + 2;
    }
    if (buffer[i4] === carriage && buffer[i4 + 1] === carriage) {
      return i4 + 2;
    }
    if (buffer[i4] === carriage && buffer[i4 + 1] === newline2 && i4 + 3 < buffer.length && buffer[i4 + 2] === carriage && buffer[i4 + 3] === newline2) {
      return i4 + 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(iterator2, controller) {
        this.iterator = iterator2;
        this.controller = controller;
      }
      static fromSSEResponse(response, controller) {
        let consumed = false;
        async function* iterator2() {
          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(iterator2, "iterator");
        return new _Stream(iterator2, 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* iterator2() {
          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(iterator2, "iterator");
        return new _Stream(iterator2, 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 iterator2 = this.iterator();
        const teeIterator = /* @__PURE__ */ __name((queue) => {
          return {
            next: /* @__PURE__ */ __name(() => {
              if (queue.length === 0) {
                const result = iterator2.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 (err2) {
              ctrl.error(err2);
            }
          },
          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, name4, options2) {
  value = await value;
  if (isFileLike3(value)) {
    return value;
  }
  if (isResponseLike2(value)) {
    const blob = await value.blob();
    name4 || (name4 = new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file");
    const data = isBlobLike2(blob) ? [await blob.arrayBuffer()] : [blob];
    return new File4(data, name4, options2);
  }
  const bits = await getBytes2(value);
  name4 || (name4 = getName2(value) ?? "unknown_file");
  if (!options2?.type) {
    const type = bits[0]?.type;
    if (typeof type === "string") {
      options2 = { ...options2, type };
    }
  }
  return new File4(bits, name4, options2);
}
async function getBytes2(value) {
  let parts2 = [];
  if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
  value instanceof ArrayBuffer) {
    parts2.push(value);
  } else if (isBlobLike2(value)) {
    parts2.push(await value.arrayBuffer());
  } else if (isAsyncIterableIterator(value)) {
    for await (const chunk of value) {
      parts2.push(chunk);
    }
  } else {
    throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError2(value)}`);
  }
  return parts2;
}
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((body2) => body2 && typeof body2 === "object" && body2.body && body2[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 json3 = await response.json();
    debug("response", response.status, response.url, response.headers, json3);
    return _addRequestID(json3, 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, ...args2) {
  if (typeof process !== "undefined" && process?.env?.["DEBUG"] === "true") {
    console.log(`Anthropic:DEBUG:${action}`, ...args2);
  }
}
var __classPrivateFieldSet6, __classPrivateFieldGet8, _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;
    };
    __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);
    };
    __name(defaultParseResponse2, "defaultParseResponse");
    __name(_addRequestID, "_addRequestID");
    APIPromise2 = class _APIPromise extends Promise {
      static {
        __name(this, "APIPromise");
      }
      constructor(responsePromise, parseResponse2 = defaultParseResponse2) {
        super((resolve42) => {
          resolve42(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(path150, opts) {
        return this.methodRequest("get", path150, opts);
      }
      post(path150, opts) {
        return this.methodRequest("post", path150, opts);
      }
      patch(path150, opts) {
        return this.methodRequest("patch", path150, opts);
      }
      put(path150, opts) {
        return this.methodRequest("put", path150, opts);
      }
      delete(path150, opts) {
        return this.methodRequest("delete", path150, opts);
      }
      methodRequest(method, path150, opts) {
        return this.request(Promise.resolve(opts).then(async (opts2) => {
          const body2 = 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: path150, ...opts2, body: body2 };
        }));
      }
      getAPIList(path150, Page3, opts) {
        return this.requestAPIList(Page3, { method: "get", path: path150, ...opts });
      }
      calculateContentLength(body2) {
        if (typeof body2 === "string") {
          if (typeof Buffer !== "undefined") {
            return Buffer.byteLength(body2, "utf8").toString();
          }
          if (typeof TextEncoder !== "undefined") {
            const encoder = new TextEncoder();
            const encoded = encoder.encode(body2);
            return encoded.length.toString();
          }
        } else if (ArrayBuffer.isView(body2)) {
          return body2.byteLength.toString();
        }
        return null;
      }
      buildRequest(options2, { retryCount = 0 } = {}) {
        const { method, path: path150, query, headers = {} } = options2;
        const body2 = 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(body2);
        const url3 = this.buildURL(path150, query);
        if ("timeout" in options2)
          validatePositiveInteger2("timeout", options2.timeout);
        const timeout2 = options2.timeout ?? this.timeout;
        const httpAgent = options2.httpAgent ?? this.httpAgent ?? getDefaultAgent(url3);
        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,
          ...body2 && { body: body2 },
          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: url3, 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: url3, options: options2 }) {
      }
      parseHeaders(headers) {
        return !headers ? {} : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) : { ...headers };
      }
      makeStatusError(status, error40, message, headers) {
        return APIError2.generate(status, error40, 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: url3, timeout: timeout2 } = this.buildRequest(options2, { retryCount: maxRetries - retriesRemaining });
        await this.prepareRequest(req, { url: url3, options: options2 });
        debug("request", url3, options2, req.headers);
        if (options2.signal?.aborted) {
          throw new APIUserAbortError2();
        }
        const controller = new AbortController();
        const response = await this.fetchWithTimeout(url3, 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, url3, 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, url3, responseHeaders, errMessage);
          const err2 = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);
          throw err2;
        }
        return { response, options: options2, controller };
      }
      requestAPIList(Page3, options2) {
        const request4 = this.makeRequest(options2, null);
        return new PagePromise2(this, request4, Page3);
      }
      buildURL(path150, query) {
        const url3 = isAbsoluteURL2(path150) ? new URL(path150) : new URL(this.baseURL + (this.baseURL.endsWith("/") && path150.startsWith("/") ? path150.slice(1) : path150));
        const defaultQuery = this.defaultQuery();
        if (!isEmptyObj2(defaultQuery)) {
          query = { ...defaultQuery, ...query };
        }
        if (typeof query === "object" && query && !Array.isArray(query)) {
          url3.search = this.stringifyQuery(query);
        }
        return url3.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(url3, init2, ms, controller) {
        const { signal, ...options2 } = init2 || {};
        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, url3, 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 ${VERSION4}`;
      }
    };
    AbstractPage2 = class {
      static {
        __name(this, "AbstractPage");
      }
      constructor(client, response, body2, options2) {
        _AbstractPage_client2.set(this, void 0);
        __classPrivateFieldSet6(this, _AbstractPage_client2, client, "f");
        this.options = options2;
        this.response = response;
        this.body = body2;
      }
      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 __classPrivateFieldGet8(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, name4) {
          const key = name4.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": VERSION4,
          "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": VERSION4,
          "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": VERSION4,
          "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": VERSION4,
          "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": VERSION4,
        "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((platform15) => {
      platform15 = platform15.toLowerCase();
      if (platform15.includes("ios"))
        return "iOS";
      if (platform15 === "android")
        return "Android";
      if (platform15 === "darwin")
        return "MacOS";
      if (platform15 === "win32")
        return "Windows";
      if (platform15 === "freebsd")
        return "FreeBSD";
      if (platform15 === "openbsd")
        return "OpenBSD";
      if (platform15 === "linux")
        return "Linux";
      if (platform15)
        return `Other:${platform15}`;
      return "Unknown";
    }, "normalizePlatform");
    getPlatformHeaders2 = /* @__PURE__ */ __name(() => {
      return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2());
    }, "getPlatformHeaders");
    safeJSON2 = /* @__PURE__ */ __name((text) => {
      try {
        return JSON.parse(text);
      } catch (err2) {
        return void 0;
      }
    }, "safeJSON");
    startsWithSchemeRegexp2 = /^[a-z][a-z0-9+.-]*:/i;
    isAbsoluteURL2 = /* @__PURE__ */ __name((url3) => {
      return startsWithSchemeRegexp2.test(url3);
    }, "isAbsoluteURL");
    sleep3 = /* @__PURE__ */ __name((ms) => new Promise((resolve42) => setTimeout(resolve42, ms)), "sleep");
    validatePositiveInteger2 = /* @__PURE__ */ __name((name4, n3) => {
      if (typeof n3 !== "number" || !Number.isInteger(n3)) {
        throw new AnthropicError(`${name4} must be an integer`);
      }
      if (n3 < 0) {
        throw new AnthropicError(`${name4} must be a positive integer`);
      }
      return n3;
    }, "validatePositiveInteger");
    castToError2 = /* @__PURE__ */ __name((err2) => {
      if (err2 instanceof Error)
        return err2;
      if (typeof err2 === "object" && err2 !== null) {
        try {
          return new Error(JSON.stringify(err2));
        } catch {
        }
      }
      return new Error(String(err2));
    }, "castToError");
    readEnv2 = /* @__PURE__ */ __name((env6) => {
      if (typeof process !== "undefined") {
        return process.env?.[env6]?.trim() ?? void 0;
      }
      if (typeof Deno !== "undefined") {
        return Deno.env?.get?.(env6)?.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, body2, options2) {
        super(client, response, body2, options2);
        this.data = body2.data || [];
        this.has_more = body2.has_more || false;
        this.first_id = body2.first_id || null;
        this.last_id = body2.last_id || null;
      }
      getPaginatedItems() {
        return this.data ?? [];
      }
      // @deprecated Please use `nextPageInfo()` instead
      nextPageParams() {
        const info2 = this.nextPageInfo();
        if (!info2)
          return null;
        if ("params" in info2)
          return info2.params;
        const params = Object.fromEntries(info2.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(iterator2, controller) {
        this.iterator = iterator2;
        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, ...body2 } = params;
        return this._client.post("/v1/messages/batches?beta=true", {
          body: body2,
          ...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, __classPrivateFieldGet9, _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;
    };
    __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_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, (error40) => {
          __classPrivateFieldSet7(this, _BetaMessageStream_errored, true, "f");
          if (error40 instanceof Error && error40.name === "AbortError") {
            error40 = new APIUserAbortError2();
          }
          if (error40 instanceof APIUserAbortError2) {
            __classPrivateFieldSet7(this, _BetaMessageStream_aborted, true, "f");
            return this._emit("abort", error40);
          }
          if (error40 instanceof AnthropicError) {
            return this._emit("error", error40);
          }
          if (error40 instanceof Error) {
            const anthropicError = new AnthropicError(error40.message);
            anthropicError.cause = error40;
            return this._emit("error", anthropicError);
          }
          return this._emit("error", new AnthropicError(String(error40)));
        });
        __classPrivateFieldSet7(this, _BetaMessageStream_connectedPromise, new Promise((resolve42, reject) => {
          __classPrivateFieldSet7(this, _BetaMessageStream_resolveConnectedPromise, resolve42, "f");
          __classPrivateFieldSet7(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
        }), "f");
        __classPrivateFieldSet7(this, _BetaMessageStream_endPromise, new Promise((resolve42, reject) => {
          __classPrivateFieldSet7(this, _BetaMessageStream_resolveEndPromise, resolve42, "f");
          __classPrivateFieldSet7(this, _BetaMessageStream_rejectEndPromise, reject, "f");
        }), "f");
        __classPrivateFieldGet9(this, _BetaMessageStream_connectedPromise, "f").catch(() => {
        });
        __classPrivateFieldGet9(this, _BetaMessageStream_endPromise, "f").catch(() => {
        });
      }
      get response() {
        return __classPrivateFieldGet9(this, _BetaMessageStream_response, "f");
      }
      get request_id() {
        return __classPrivateFieldGet9(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 __classPrivateFieldGet9(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(stream5) {
        const runner = new _BetaMessageStream();
        runner._run(() => runner._fromReadableStream(stream5));
        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");
        }, __classPrivateFieldGet9(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());
        }
        __classPrivateFieldGet9(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
        const { response, data: stream5 } = await messages.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal }).withResponse();
        this._connected(response);
        for await (const event of stream5) {
          __classPrivateFieldGet9(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError2();
        }
        __classPrivateFieldGet9(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");
        __classPrivateFieldGet9(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response);
        this._emit("connect");
      }
      get ended() {
        return __classPrivateFieldGet9(this, _BetaMessageStream_ended, "f");
      }
      get errored() {
        return __classPrivateFieldGet9(this, _BetaMessageStream_errored, "f");
      }
      get aborted() {
        return __classPrivateFieldGet9(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 = __classPrivateFieldGet9(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet9(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 = __classPrivateFieldGet9(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 = __classPrivateFieldGet9(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet9(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((resolve42, reject) => {
          __classPrivateFieldSet7(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
          if (event !== "error")
            this.once("error", reject);
          this.once(event, resolve42);
        });
      }
      async done() {
        __classPrivateFieldSet7(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
        await __classPrivateFieldGet9(this, _BetaMessageStream_endPromise, "f");
      }
      get currentMessage() {
        return __classPrivateFieldGet9(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 __classPrivateFieldGet9(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 __classPrivateFieldGet9(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this);
      }
      _emit(event, ...args2) {
        if (__classPrivateFieldGet9(this, _BetaMessageStream_ended, "f"))
          return;
        if (event === "end") {
          __classPrivateFieldSet7(this, _BetaMessageStream_ended, true, "f");
          __classPrivateFieldGet9(this, _BetaMessageStream_resolveEndPromise, "f").call(this);
        }
        const listeners = __classPrivateFieldGet9(this, _BetaMessageStream_listeners, "f")[event];
        if (listeners) {
          __classPrivateFieldGet9(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l3) => !l3.once);
          listeners.forEach(({ listener }) => listener(...args2));
        }
        if (event === "abort") {
          const error40 = args2[0];
          if (!__classPrivateFieldGet9(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error40);
          }
          __classPrivateFieldGet9(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error40);
          __classPrivateFieldGet9(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error40);
          this._emit("end");
          return;
        }
        if (event === "error") {
          const error40 = args2[0];
          if (!__classPrivateFieldGet9(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error40);
          }
          __classPrivateFieldGet9(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error40);
          __classPrivateFieldGet9(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error40);
          this._emit("end");
        }
      }
      _emitFinal() {
        const finalMessage = this.receivedMessages.at(-1);
        if (finalMessage) {
          this._emit("finalMessage", __classPrivateFieldGet9(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());
        }
        __classPrivateFieldGet9(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
        this._connected(null);
        const stream5 = Stream4.fromReadableStream(readableStream, this.controller);
        for await (const event of stream5) {
          __classPrivateFieldGet9(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError2();
        }
        __classPrivateFieldGet9(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 = __classPrivateFieldGet9(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 = __classPrivateFieldGet9(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 = __classPrivateFieldGet9(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", (err2) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err2);
          }
          readQueue.length = 0;
        });
        this.on("error", (err2) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err2);
          }
          readQueue.length = 0;
        });
        return {
          next: /* @__PURE__ */ __name(async () => {
            if (!pushQueue.length) {
              if (done) {
                return { value: void 0, done: true };
              }
              return new Promise((resolve42, reject) => readQueue.push({ resolve: resolve42, 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 stream5 = new Stream4(this[Symbol.asyncIterator].bind(this), this.controller);
        return stream5.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, ...body2 } = params;
        if (body2.model in DEPRECATED_MODELS) {
          console.warn(`The model '${body2.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body2.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: body2,
          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(body2, options2) {
        return BetaMessageStream.createMessage(this, body2, 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, ...body2 } = params;
        return this._client.post("/v1/messages/count_tokens?beta=true", {
          body: body2,
          ...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(body2, options2) {
        return this._client.post("/v1/complete", {
          body: body2,
          timeout: this._client._options.timeout ?? 6e5,
          ...options2,
          stream: body2.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(body2, options2) {
        return this._client.post("/v1/messages/batches", { body: body2, ...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, __classPrivateFieldGet10, _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;
    };
    __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);
    };
    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, (error40) => {
          __classPrivateFieldSet8(this, _MessageStream_errored, true, "f");
          if (error40 instanceof Error && error40.name === "AbortError") {
            error40 = new APIUserAbortError2();
          }
          if (error40 instanceof APIUserAbortError2) {
            __classPrivateFieldSet8(this, _MessageStream_aborted, true, "f");
            return this._emit("abort", error40);
          }
          if (error40 instanceof AnthropicError) {
            return this._emit("error", error40);
          }
          if (error40 instanceof Error) {
            const anthropicError = new AnthropicError(error40.message);
            anthropicError.cause = error40;
            return this._emit("error", anthropicError);
          }
          return this._emit("error", new AnthropicError(String(error40)));
        });
        __classPrivateFieldSet8(this, _MessageStream_connectedPromise, new Promise((resolve42, reject) => {
          __classPrivateFieldSet8(this, _MessageStream_resolveConnectedPromise, resolve42, "f");
          __classPrivateFieldSet8(this, _MessageStream_rejectConnectedPromise, reject, "f");
        }), "f");
        __classPrivateFieldSet8(this, _MessageStream_endPromise, new Promise((resolve42, reject) => {
          __classPrivateFieldSet8(this, _MessageStream_resolveEndPromise, resolve42, "f");
          __classPrivateFieldSet8(this, _MessageStream_rejectEndPromise, reject, "f");
        }), "f");
        __classPrivateFieldGet10(this, _MessageStream_connectedPromise, "f").catch(() => {
        });
        __classPrivateFieldGet10(this, _MessageStream_endPromise, "f").catch(() => {
        });
      }
      get response() {
        return __classPrivateFieldGet10(this, _MessageStream_response, "f");
      }
      get request_id() {
        return __classPrivateFieldGet10(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 __classPrivateFieldGet10(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(stream5) {
        const runner = new _MessageStream();
        runner._run(() => runner._fromReadableStream(stream5));
        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");
        }, __classPrivateFieldGet10(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());
        }
        __classPrivateFieldGet10(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
        const { response, data: stream5 } = await messages.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal }).withResponse();
        this._connected(response);
        for await (const event of stream5) {
          __classPrivateFieldGet10(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError2();
        }
        __classPrivateFieldGet10(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");
        __classPrivateFieldGet10(this, _MessageStream_resolveConnectedPromise, "f").call(this, response);
        this._emit("connect");
      }
      get ended() {
        return __classPrivateFieldGet10(this, _MessageStream_ended, "f");
      }
      get errored() {
        return __classPrivateFieldGet10(this, _MessageStream_errored, "f");
      }
      get aborted() {
        return __classPrivateFieldGet10(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 = __classPrivateFieldGet10(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet10(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 = __classPrivateFieldGet10(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 = __classPrivateFieldGet10(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet10(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((resolve42, reject) => {
          __classPrivateFieldSet8(this, _MessageStream_catchingPromiseCreated, true, "f");
          if (event !== "error")
            this.once("error", reject);
          this.once(event, resolve42);
        });
      }
      async done() {
        __classPrivateFieldSet8(this, _MessageStream_catchingPromiseCreated, true, "f");
        await __classPrivateFieldGet10(this, _MessageStream_endPromise, "f");
      }
      get currentMessage() {
        return __classPrivateFieldGet10(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 __classPrivateFieldGet10(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 __classPrivateFieldGet10(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
      }
      _emit(event, ...args2) {
        if (__classPrivateFieldGet10(this, _MessageStream_ended, "f"))
          return;
        if (event === "end") {
          __classPrivateFieldSet8(this, _MessageStream_ended, true, "f");
          __classPrivateFieldGet10(this, _MessageStream_resolveEndPromise, "f").call(this);
        }
        const listeners = __classPrivateFieldGet10(this, _MessageStream_listeners, "f")[event];
        if (listeners) {
          __classPrivateFieldGet10(this, _MessageStream_listeners, "f")[event] = listeners.filter((l3) => !l3.once);
          listeners.forEach(({ listener }) => listener(...args2));
        }
        if (event === "abort") {
          const error40 = args2[0];
          if (!__classPrivateFieldGet10(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error40);
          }
          __classPrivateFieldGet10(this, _MessageStream_rejectConnectedPromise, "f").call(this, error40);
          __classPrivateFieldGet10(this, _MessageStream_rejectEndPromise, "f").call(this, error40);
          this._emit("end");
          return;
        }
        if (event === "error") {
          const error40 = args2[0];
          if (!__classPrivateFieldGet10(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
            Promise.reject(error40);
          }
          __classPrivateFieldGet10(this, _MessageStream_rejectConnectedPromise, "f").call(this, error40);
          __classPrivateFieldGet10(this, _MessageStream_rejectEndPromise, "f").call(this, error40);
          this._emit("end");
        }
      }
      _emitFinal() {
        const finalMessage = this.receivedMessages.at(-1);
        if (finalMessage) {
          this._emit("finalMessage", __classPrivateFieldGet10(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());
        }
        __classPrivateFieldGet10(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
        this._connected(null);
        const stream5 = Stream4.fromReadableStream(readableStream, this.controller);
        for await (const event of stream5) {
          __classPrivateFieldGet10(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
        }
        if (stream5.controller.signal?.aborted) {
          throw new APIUserAbortError2();
        }
        __classPrivateFieldGet10(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 = __classPrivateFieldGet10(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 = __classPrivateFieldGet10(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 = __classPrivateFieldGet10(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", (err2) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err2);
          }
          readQueue.length = 0;
        });
        this.on("error", (err2) => {
          done = true;
          for (const reader of readQueue) {
            reader.reject(err2);
          }
          readQueue.length = 0;
        });
        return {
          next: /* @__PURE__ */ __name(async () => {
            if (!pushQueue.length) {
              if (done) {
                return { value: void 0, done: true };
              }
              return new Promise((resolve42, reject) => readQueue.push({ resolve: resolve42, 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 stream5 = new Stream4(this[Symbol.asyncIterator].bind(this), this.controller);
        return stream5.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(body2, options2) {
        if (body2.model in DEPRECATED_MODELS2) {
          console.warn(`The model '${body2.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS2[body2.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: body2,
          timeout: this._client._options.timeout ?? 6e5,
          ...options2,
          stream: body2.stream ?? false
        });
      }
      /**
       * Create a Message stream
       */
      stream(body2, options2) {
        return MessageStream.createMessage(this, body2, 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(body2, options2) {
        return this._client.post("/v1/messages/count_tokens", { body: body2, ...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 func2 of actualTool.functionDeclarations) {
            if (!func2.name || !func2.description)
              continue;
            let inputSchema;
            if (func2.parametersJsonSchema) {
              inputSchema = {
                ...func2.parametersJsonSchema
              };
            } else if (func2.parameters) {
              inputSchema = func2.parameters;
            }
            if (!inputSchema) {
              inputSchema = { type: "object", properties: {} };
            }
            inputSchema = convertSchema(inputSchema, this.schemaCompliance);
            if (typeof inputSchema["type"] !== "string") {
              inputSchema["type"] = "object";
            }
            tools.push({
              name: func2.name,
              description: func2.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 parts2 = [];
        for (const block2 of response.content || []) {
          const blockType = String(block2["type"] || "");
          if (blockType === "text") {
            const text = typeof block2.text === "string" ? block2.text : "";
            if (text) {
              parts2.push({ text });
            }
          } else if (blockType === "tool_use") {
            const toolUse = block2;
            parts2.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
              };
              parts2.push(thoughtPart);
            }
          } else if (blockType === "redacted_thinking") {
            parts2.push({ text: "", thought: true });
          }
        }
        const candidate = {
          content: {
            parts: parts2,
            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 parts2 = content.parts || [];
        const role = content.role === "model" ? "assistant" : "user";
        const contentBlocks = [];
        let toolCallIndex = 0;
        for (const part of parts2) {
          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 error40 = responseObject["error"];
          if (typeof error40 === "string") {
            return error40;
          }
        }
        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 i4 = messages.length - 1; i4 >= 0; i4--) {
          const msg = messages[i4];
          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 debugLogger18, 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();
    init_tokenLimits();
    debugLogger18 = 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 stream5 = await this.client.messages.create(streamingRequest, {
          signal: request4.config?.abortSignal
        });
        return this.processStream(stream5);
      }
      async countTokens(request4) {
        try {
          const estimator = new RequestTokenizer();
          const result = await estimator.calculateTokens(request4);
          return {
            totalTokens: result.totalTokens
          };
        } catch (error40) {
          debugLogger18.warn("Failed to calculate tokens with tokenizer, falling back to simple method:", error40);
          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 userMaxTokens = getParam("max_tokens", "maxOutputTokens");
        const modelId = this.contentGeneratorConfig.model;
        const modelLimit = tokenLimit(modelId, "output");
        const isKnownModel = hasExplicitOutputLimit(modelId);
        let maxTokens;
        if (userMaxTokens !== void 0 && userMaxTokens !== null) {
          maxTokens = isKnownModel ? Math.min(userMaxTokens, modelLimit) : userMaxTokens;
        } else {
          const envVal = process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"];
          const envMaxTokens = envVal ? parseInt(envVal, 10) : NaN;
          if (!isNaN(envMaxTokens) && envMaxTokens > 0) {
            maxTokens = isKnownModel ? Math.min(envMaxTokens, modelLimit) : envMaxTokens;
          } else {
            maxTokens = Math.min(modelLimit, CAPPED_DEFAULT_MAX_TOKENS);
          }
        }
        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(stream5) {
        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 stream5) {
          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 args2 = safeJsonParse(blockState.inputJson || "{}", {});
                const chunk = this.buildGeminiChunk({
                  functionCall: {
                    id: blockState.id,
                    name: blockState.name,
                    args: args2
                  }
                }, 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.15.6";
  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 = config2.baseUrl ? {
    headers,
    baseUrl: config2.baseUrl
  } : { 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, path150, source2) {
  sources[path150] = source2;
}
function getSeedSource(seed, path150) {
  return seed?.[path150];
}
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((path150) => getSeedSource(seedSources, path150) ?? { 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 };
}
function createContentGeneratorConfig(config2, authType, generationConfig) {
  return resolveContentGeneratorConfigWithSources(config2, authType, generationConfig).config;
}
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 (error40) {
      throw new Error(`${error40 instanceof Error ? error40.message : String(error40)}`);
    }
  } 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(createContentGeneratorConfig, "createContentGeneratorConfig");
    __name(createContentGenerator, "createContentGenerator");
  }
});

// packages/core/dist/src/utils/quotaErrorDetection.js
function isApiError(error40) {
  return typeof error40 === "object" && error40 !== null && "error" in error40 && typeof error40.error === "object" && "message" in error40.error;
}
function isStructuredError(error40) {
  return typeof error40 === "object" && error40 !== null && "message" in error40 && typeof error40.message === "string";
}
function isProQuotaExceededError(error40) {
  const checkMessage = /* @__PURE__ */ __name((message) => message.includes("Quota exceeded for quota metric 'Gemini") && message.includes("Pro Requests'"), "checkMessage");
  if (typeof error40 === "string") {
    return checkMessage(error40);
  }
  if (isStructuredError(error40)) {
    return checkMessage(error40.message);
  }
  if (isApiError(error40)) {
    return checkMessage(error40.error.message);
  }
  if (error40 && typeof error40 === "object" && "response" in error40) {
    const gaxiosError = error40;
    if (gaxiosError.response && gaxiosError.response.data) {
      if (typeof gaxiosError.response.data === "string") {
        return checkMessage(gaxiosError.response.data);
      }
      if (typeof gaxiosError.response.data === "object" && gaxiosError.response.data !== null && "error" in gaxiosError.response.data) {
        const errorData = gaxiosError.response.data;
        return checkMessage(errorData.error?.message || "");
      }
    }
  }
  return false;
}
function isGenericQuotaExceededError(error40) {
  if (typeof error40 === "string") {
    return error40.includes("Quota exceeded for quota metric");
  }
  if (isStructuredError(error40)) {
    return error40.message.includes("Quota exceeded for quota metric");
  }
  if (isApiError(error40)) {
    return error40.error.message.includes("Quota exceeded for quota metric");
  }
  return false;
}
function isQwenQuotaExceededError(error40) {
  if (typeof error40 !== "object" || error40 === null) {
    return false;
  }
  const { status, code: code2, message } = error40;
  return status === 429 && code2 === "insufficient_quota" && typeof message === "string" && message.toLowerCase().includes("free allocated quota exceeded");
}
var init_quotaErrorDetection = __esm({
  "packages/core/dist/src/utils/quotaErrorDetection.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isApiError, "isApiError");
    __name(isStructuredError, "isStructuredError");
    __name(isProQuotaExceededError, "isProQuotaExceededError");
    __name(isGenericQuotaExceededError, "isGenericQuotaExceededError");
    __name(isQwenQuotaExceededError, "isQwenQuotaExceededError");
  }
});

// packages/core/dist/src/utils/retry.js
function defaultShouldRetry(error40) {
  const status = getErrorStatus(error40);
  return status === 429 || status !== void 0 && status >= 500 && status < 600;
}
function isTransientCapacityError(error40) {
  const status = getErrorStatus(error40);
  return status === 429 || status === 529;
}
function isUnattendedMode() {
  const val = process.env["QWEN_CODE_UNATTENDED_RETRY"];
  return val === "true" || val === "1";
}
function delay(ms) {
  return new Promise((resolve42) => setTimeout(resolve42, ms));
}
async function sleepWithHeartbeat(totalMs, ctx) {
  let remaining = totalMs;
  while (remaining > 0) {
    if (ctx.signal?.aborted) {
      throw new Error("Retry aborted by signal");
    }
    const chunk = Math.max(1, Math.min(remaining, ctx.heartbeatInterval));
    await delay(chunk);
    remaining -= chunk;
    if (remaining > 0 && ctx.heartbeatFn) {
      ctx.heartbeatFn({
        attempt: ctx.attempt,
        remainingMs: remaining,
        error: ctx.error
      });
    }
  }
}
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, persistentMode, persistentMaxBackoffMs, persistentCapMs, heartbeatIntervalMs, heartbeatFn, signal } = {
    ...DEFAULT_RETRY_OPTIONS,
    ...cleanOptions
  };
  const persistent = persistentMode ?? false;
  const maxBackoff = persistentMaxBackoffMs ?? PERSISTENT_MAX_BACKOFF_MS;
  const capMs = persistentCapMs ?? PERSISTENT_CAP_MS;
  const heartbeatInterval = heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS;
  let attempt = 0;
  let persistentAttempt = 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 (error40) {
      const errorStatus = getErrorStatus(error40);
      if (authType === AuthType2.QWEN_OAUTH && isQwenQuotaExceededError(error40)) {
        throw new Error(`Qwen OAuth free tier has been discontinued as of 2026-04-15.

To continue using Qwen Code, try one of these alternatives:
  - OpenRouter:    https://openrouter.ai/docs/quickstart
  - Fireworks AI:  https://docs.fireworks.ai/api-reference/introduction
  - ModelStudio:   https://help.aliyun.com/zh/model-studio/coding-plan

After setting up your API key, run /auth to configure your provider.`);
      }
      const isTransient = isTransientCapacityError(error40);
      const callerAllowsRetry = shouldRetryOnError(error40);
      const shouldPersist = persistent && isTransient && callerAllowsRetry;
      if (!shouldPersist) {
        if (attempt >= maxAttempts || !callerAllowsRetry) {
          throw error40;
        }
      }
      let delayMs;
      if (shouldPersist) {
        persistentAttempt++;
        const retryAfterMs = errorStatus === 429 ? getRetryAfterDelayMs(error40) : 0;
        if (retryAfterMs > 0) {
          delayMs = Math.min(retryAfterMs, capMs);
        } else {
          delayMs = Math.min(initialDelayMs * Math.pow(2, persistentAttempt - 1), maxBackoff);
          delayMs = Math.min(delayMs, capMs);
          delayMs += delayMs * 0.25 * (Math.random() * 2 - 1);
          delayMs = Math.min(Math.max(0, delayMs), maxBackoff, capMs);
        }
        const reportedAttempt = persistentAttempt;
        debugLogger19.warn(`[Persistent] Attempt ${reportedAttempt} failed with status ${errorStatus ?? "unknown"}. Retrying in ${Math.ceil(delayMs / 1e3)}s...`, error40);
        await sleepWithHeartbeat(delayMs, {
          attempt: reportedAttempt,
          error: error40,
          heartbeatInterval,
          heartbeatFn,
          signal
        });
        if (attempt >= maxAttempts) {
          attempt = maxAttempts - 1;
        }
      } else {
        const retryAfterMs = errorStatus === 429 ? getRetryAfterDelayMs(error40) : 0;
        if (retryAfterMs > 0) {
          debugLogger19.warn(`Attempt ${attempt} failed with status ${errorStatus ?? "unknown"}. Retrying after explicit delay of ${retryAfterMs}ms...`, error40);
          await delay(retryAfterMs);
          currentDelay = initialDelayMs;
        } else {
          logRetryAttempt(attempt, error40, 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 getRetryAfterDelayMs(error40) {
  if (typeof error40 === "object" && error40 !== null) {
    if ("response" in error40 && typeof error40.response === "object" && error40.response !== null) {
      const response = error40.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, error40, errorStatus) {
  const message = errorStatus ? `Attempt ${attempt} failed with status ${errorStatus}. Retrying with backoff...` : `Attempt ${attempt} failed. Retrying with backoff...`;
  if (errorStatus === 429) {
    debugLogger19.warn(message, error40);
  } else if (errorStatus && errorStatus >= 500 && errorStatus < 600) {
    debugLogger19.error(message, error40);
  } else {
    debugLogger19.warn(message, error40);
  }
}
var debugLogger19, PERSISTENT_MAX_BACKOFF_MS, PERSISTENT_CAP_MS, HEARTBEAT_INTERVAL_MS, 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();
    init_errors();
    debugLogger19 = createDebugLogger("RETRY");
    PERSISTENT_MAX_BACKOFF_MS = 5 * 60 * 1e3;
    PERSISTENT_CAP_MS = 6 * 60 * 60 * 1e3;
    HEARTBEAT_INTERVAL_MS = 3e4;
    DEFAULT_RETRY_OPTIONS = {
      maxAttempts: 7,
      initialDelayMs: 1500,
      maxDelayMs: 3e4,
      // 30 seconds
      shouldRetryOnError: defaultShouldRetry
    };
    __name(defaultShouldRetry, "defaultShouldRetry");
    __name(isTransientCapacityError, "isTransientCapacityError");
    __name(isUnattendedMode, "isUnattendedMode");
    __name(delay, "delay");
    __name(sleepWithHeartbeat, "sleepWithHeartbeat");
    __name(retryWithBackoff, "retryWithBackoff");
    __name(getRetryAfterDelayMs, "getRetryAfterDelayMs");
    __name(logRetryAttempt, "logRetryAttempt");
  }
});

// packages/core/dist/src/utils/partUtils.js
function partToString(value, options2) {
  if (!value) {
    return "";
  }
  if (typeof value === "string") {
    return value;
  }
  if (Array.isArray(value)) {
    return value.map((part2) => partToString(part2, options2)).join("");
  }
  const part = value;
  if (options2?.verbose) {
    if (part.videoMetadata !== void 0) {
      return `[Video Metadata]`;
    }
    if (part.thought !== void 0) {
      return `[Thought: ${part.thought}]`;
    }
    if (part.codeExecutionResult !== void 0) {
      return `[Code Execution Result]`;
    }
    if (part.executableCode !== void 0) {
      return `[Executable Code]`;
    }
    if (part.fileData !== void 0) {
      return `[File Data]`;
    }
    if (part.functionCall !== void 0) {
      return `[Function Call: ${part.functionCall.name}]`;
    }
    if (part.functionResponse !== void 0) {
      return `[Function Response: ${part.functionResponse.name}]`;
    }
    if (part.inlineData !== void 0) {
      return `<${part.inlineData.mimeType}>`;
    }
  }
  return part.text ?? "";
}
function getResponseText(response) {
  if (response.candidates && response.candidates.length > 0) {
    const candidate = response.candidates[0];
    if (candidate.content && candidate.content.parts && candidate.content.parts.length > 0) {
      return candidate.content.parts.filter((part) => part.text && !part.thought).map((part) => part.text).join("");
    }
  }
  return null;
}
async function flatMapTextParts(parts2, transform2) {
  const result = [];
  const partArray = Array.isArray(parts2) ? parts2 : typeof parts2 === "string" ? [{ text: parts2 }] : [parts2];
  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(partToString, "partToString");
    __name(getResponseText, "getResponseText");
    __name(flatMapTextParts, "flatMapTextParts");
    __name(appendToLastTextPart, "appendToLastTextPart");
  }
});

// packages/core/dist/src/utils/generateContentResponseUtilities.js
function getResponseTextFromParts(parts2) {
  if (!parts2) {
    return void 0;
  }
  const textSegments = parts2.map((part) => part.text).filter((text) => typeof text === "string");
  if (textSegments.length === 0) {
    return void 0;
  }
  return textSegments.join("");
}
function getFunctionCalls(response) {
  const parts2 = response.candidates?.[0]?.content?.parts;
  if (!parts2) {
    return void 0;
  }
  const functionCallParts = parts2.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;
}
function getFunctionCallsFromParts(parts2) {
  if (!parts2) {
    return void 0;
  }
  const functionCallParts = parts2.filter((part) => !!part.functionCall).map((part) => part.functionCall);
  return functionCallParts.length > 0 ? functionCallParts : void 0;
}
function getFunctionCallsAsJson(response) {
  const functionCalls = getFunctionCalls(response);
  if (!functionCalls) {
    return void 0;
  }
  return JSON.stringify(functionCalls, null, 2);
}
function getFunctionCallsFromPartsAsJson(parts2) {
  const functionCalls = getFunctionCallsFromParts(parts2);
  if (!functionCalls) {
    return void 0;
  }
  return JSON.stringify(functionCalls, null, 2);
}
function getStructuredResponse(response) {
  const textContent2 = getResponseText(response);
  const functionCallsJson = getFunctionCallsAsJson(response);
  if (textContent2 && functionCallsJson) {
    return `${textContent2}
${functionCallsJson}`;
  }
  if (textContent2) {
    return textContent2;
  }
  if (functionCallsJson) {
    return functionCallsJson;
  }
  return void 0;
}
function getStructuredResponseFromParts(parts2) {
  const textContent2 = getResponseTextFromParts(parts2);
  const functionCallsJson = getFunctionCallsFromPartsAsJson(parts2);
  if (textContent2 && functionCallsJson) {
    return `${textContent2}
${functionCallsJson}`;
  }
  if (textContent2) {
    return textContent2;
  }
  if (functionCallsJson) {
    return functionCallsJson;
  }
  return 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");
    __name(getFunctionCallsFromParts, "getFunctionCallsFromParts");
    __name(getFunctionCallsAsJson, "getFunctionCallsAsJson");
    __name(getFunctionCallsFromPartsAsJson, "getFunctionCallsFromPartsAsJson");
    __name(getStructuredResponse, "getStructuredResponse");
    __name(getStructuredResponseFromParts, "getStructuredResponseFromParts");
  }
});

// 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,
            persistentMode: isUnattendedMode(),
            signal: abortSignal,
            heartbeatFn: /* @__PURE__ */ __name((info2) => {
              process.stderr.write(`[qwen-code] Waiting for API capacity... attempt ${info2.attempt}, retry in ${Math.ceil(info2.remainingMs / 1e3)}s
`);
            }, "heartbeatFn")
          });
          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 (error40) {
          if (abortSignal.aborted) {
            throw error40;
          }
          if (error40 instanceof Error && error40.message === "API returned an empty response for generateJson.") {
            throw error40;
          }
          await reportError2(error40, "Error generating JSON content via API.", contents, "generateJson-api");
          throw new Error(`Failed to generate JSON content: ${getErrorMessage(error40)}`);
        }
      }
      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/services/microcompaction/microcompact.js
function evaluateTimeBasedTrigger(lastApiCompletionTimestamp, settings) {
  const thresholdMin = settings.toolResultsThresholdMinutes ?? 60;
  if (thresholdMin < 0) {
    return null;
  }
  if (lastApiCompletionTimestamp === null) {
    return null;
  }
  const thresholdMs = thresholdMin * 6e4;
  const gapMs = Date.now() - lastApiCompletionTimestamp;
  if (!Number.isFinite(gapMs) || gapMs < thresholdMs) {
    return null;
  }
  return { gapMs };
}
function collectCompactablePartRefs(history) {
  const refs = [];
  for (let ci = 0; ci < history.length; ci++) {
    const content = history[ci];
    if (content.role !== "user" || !content.parts)
      continue;
    for (let pi = 0; pi < content.parts.length; pi++) {
      const part = content.parts[pi];
      if (part.functionResponse?.name && COMPACTABLE_TOOLS.has(part.functionResponse.name)) {
        refs.push({ contentIndex: ci, partIndex: pi });
      }
    }
  }
  return refs;
}
function isErrorResponse2(part) {
  return part.functionResponse?.response?.["error"] !== void 0;
}
function estimatePartTokens(part) {
  if (!part.functionResponse?.response)
    return 0;
  const output = part.functionResponse.response["output"];
  if (typeof output !== "string")
    return 0;
  return Math.ceil(output.length / 4);
}
function isAlreadyCleared(part) {
  return part.functionResponse?.response?.["output"] === MICROCOMPACT_CLEARED_MESSAGE;
}
function microcompactHistory(history, lastApiCompletionTimestamp, settings) {
  const trigger = evaluateTimeBasedTrigger(lastApiCompletionTimestamp, settings);
  if (!trigger) {
    return { history };
  }
  const { gapMs } = trigger;
  const envKeep = process.env["QWEN_MC_KEEP_RECENT"];
  const rawKeepRecent = envKeep !== void 0 && Number.isFinite(Number(envKeep)) ? Number(envKeep) : settings.toolResultsNumToKeep ?? 5;
  const keepRecent = Number.isFinite(rawKeepRecent) ? Math.max(1, rawKeepRecent) : 5;
  const allRefs = collectCompactablePartRefs(history);
  const keepRefs = new Set(allRefs.slice(-keepRecent).map((r5) => `${r5.contentIndex}:${r5.partIndex}`));
  const clearRefs = allRefs.filter((r5) => !keepRefs.has(`${r5.contentIndex}:${r5.partIndex}`));
  if (clearRefs.length === 0) {
    return { history };
  }
  const clearMap = /* @__PURE__ */ new Map();
  for (const ref of clearRefs) {
    let parts2 = clearMap.get(ref.contentIndex);
    if (!parts2) {
      parts2 = /* @__PURE__ */ new Set();
      clearMap.set(ref.contentIndex, parts2);
    }
    parts2.add(ref.partIndex);
  }
  let tokensSaved = 0;
  let toolsCleared = 0;
  const result = history.map((content, ci) => {
    const partsToClean = clearMap.get(ci);
    if (!partsToClean || !content.parts)
      return content;
    let touched = false;
    const newParts = content.parts.map((part, pi) => {
      if (partsToClean.has(pi) && part.functionResponse?.name && COMPACTABLE_TOOLS.has(part.functionResponse.name) && !isAlreadyCleared(part) && !isErrorResponse2(part)) {
        tokensSaved += estimatePartTokens(part);
        toolsCleared++;
        touched = true;
        return {
          functionResponse: {
            ...part.functionResponse,
            response: { output: MICROCOMPACT_CLEARED_MESSAGE }
          }
        };
      }
      return part;
    });
    if (!touched)
      return content;
    return { ...content, parts: newParts };
  });
  if (tokensSaved === 0) {
    return { history };
  }
  const thresholdMinutes = settings.toolResultsThresholdMinutes ?? 60;
  return {
    history: result,
    meta: {
      gapMinutes: Math.round(gapMs / 6e4),
      thresholdMinutes,
      toolsCleared,
      toolsKept: allRefs.length - clearRefs.length,
      keepRecent,
      tokensSaved
    }
  };
}
var MICROCOMPACT_CLEARED_MESSAGE, COMPACTABLE_TOOLS;
var init_microcompact = __esm({
  "packages/core/dist/src/services/microcompaction/microcompact.js"() {
    "use strict";
    init_esbuild_shims();
    init_tool_names();
    MICROCOMPACT_CLEARED_MESSAGE = "[Old tool result content cleared]";
    COMPACTABLE_TOOLS = /* @__PURE__ */ new Set([
      ToolNames.READ_FILE,
      ToolNames.SHELL,
      ToolNames.GREP,
      ToolNames.GLOB,
      ToolNames.WEB_FETCH,
      ToolNames.EDIT,
      ToolNames.WRITE_FILE
    ]);
    __name(evaluateTimeBasedTrigger, "evaluateTimeBasedTrigger");
    __name(collectCompactablePartRefs, "collectCompactablePartRefs");
    __name(isErrorResponse2, "isErrorResponse");
    __name(estimatePartTokens, "estimatePartTokens");
    __name(isAlreadyCleared, "isAlreadyCleared");
    __name(microcompactHistory, "microcompactHistory");
  }
});

// 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(error40, authType) {
  if (isStructuredError(error40)) {
    if (error40.message.startsWith("Qwen OAuth quota exceeded:") || error40.message.startsWith("Qwen OAuth free tier has been discontinued")) {
      return error40.message;
    }
    let text = `[API Error: ${error40.message}]`;
    if (error40.status === 429) {
      text += getRateLimitMessage(authType);
    }
    return text;
  }
  if (typeof error40 === "string") {
    const jsonStart = error40.indexOf("{");
    if (jsonStart === -1) {
      return `[API Error: ${error40}]`;
    }
    const jsonString = error40.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: ${error40}]`;
  }
  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(error40, extraCodes) {
  const code2 = getErrorCode2(error40);
  if (code2 === null)
    return false;
  if (RATE_LIMIT_ERROR_CODES.has(code2))
    return true;
  if (extraCodes && extraCodes.includes(code2))
    return true;
  return false;
}
function getErrorCode2(error40) {
  if (isApiError(error40)) {
    const n3 = Number(error40.error.code);
    if (Number.isFinite(n3) && n3 > 0)
      return n3;
  }
  const msg = error40 instanceof Error ? error40.message : typeof error40 === "string" ? error40 : null;
  if (msg) {
    const i4 = msg.indexOf("{");
    if (i4 !== -1) {
      try {
        const p2 = JSON.parse(msg.substring(i4));
        if (isApiError(p2)) {
          const n3 = Number(p2.error.code);
          if (Number.isFinite(n3) && n3 > 0)
            return n3;
        }
      } catch {
      }
    }
  }
  if (isStructuredError(error40) && typeof error40.status === "number") {
    return error40.status;
  }
  if (error40 instanceof Error && "status" in error40) {
    const s5 = error40.status;
    if (typeof s5 === "number")
      return s5;
  }
  return getErrorStatus(error40) ?? null;
}
var RATE_LIMIT_ERROR_CODES;
var init_rateLimit = __esm({
  "packages/core/dist/src/utils/rateLimit.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    init_quotaErrorDetection();
    RATE_LIMIT_ERROR_CODES = /* @__PURE__ */ new Set([429, 503, 1302, 1305]);
    __name(isRateLimitError, "isRateLimitError");
    __name(getErrorCode2, "getErrorCode");
  }
});

// node_modules/async-mutex/index.mjs
function insertSorted(a2, v2) {
  const i4 = findIndexFromEnd(a2, (other2) => v2.priority <= other2.priority);
  a2.splice(i4 + 1, 0, v2);
}
function findIndexFromEnd(a2, predicate) {
  for (let i4 = a2.length - 1; i4 >= 0; i4--) {
    if (predicate(a2[i4])) {
      return i4;
    }
  }
  return -1;
}
var E_TIMEOUT, E_ALREADY_LOCKED, E_CANCELED, __awaiter$2, Semaphore, __awaiter$1, Mutex;
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");
    __awaiter$2 = function(thisArg, _arguments, P2, generator) {
      function adopt(value) {
        return value instanceof P2 ? value : new P2(function(resolve42) {
          resolve42(value);
        });
      }
      __name(adopt, "adopt");
      return new (P2 || (P2 = Promise))(function(resolve42, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e4) {
            reject(e4);
          }
        }
        __name(fulfilled, "fulfilled");
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e4) {
            reject(e4);
          }
        }
        __name(rejected, "rejected");
        function step(result) {
          result.done ? resolve42(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        __name(step, "step");
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Semaphore = class {
      static {
        __name(this, "Semaphore");
      }
      constructor(_value, _cancelError = E_CANCELED) {
        this._value = _value;
        this._cancelError = _cancelError;
        this._queue = [];
        this._weightedWaiters = [];
      }
      acquire(weight = 1, priority = 0) {
        if (weight <= 0)
          throw new Error(`invalid weight ${weight}: must be positive`);
        return new Promise((resolve42, reject) => {
          const task = { resolve: resolve42, reject, weight, priority };
          const i4 = findIndexFromEnd(this._queue, (other2) => priority <= other2.priority);
          if (i4 === -1 && weight <= this._value) {
            this._dispatchItem(task);
          } else {
            this._queue.splice(i4 + 1, 0, task);
          }
        });
      }
      runExclusive(callback_1) {
        return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) {
          const [value, release3] = yield this.acquire(weight, priority);
          try {
            return yield callback(value);
          } finally {
            release3();
          }
        });
      }
      waitForUnlock(weight = 1, priority = 0) {
        if (weight <= 0)
          throw new Error(`invalid weight ${weight}: must be positive`);
        if (this._couldLockImmediately(weight, priority)) {
          return Promise.resolve();
        } else {
          return new Promise((resolve42) => {
            if (!this._weightedWaiters[weight - 1])
              this._weightedWaiters[weight - 1] = [];
            insertSorted(this._weightedWaiters[weight - 1], { resolve: resolve42, priority });
          });
        }
      }
      isLocked() {
        return this._value <= 0;
      }
      getValue() {
        return this._value;
      }
      setValue(value) {
        this._value = value;
        this._dispatchQueue();
      }
      release(weight = 1) {
        if (weight <= 0)
          throw new Error(`invalid weight ${weight}: must be positive`);
        this._value += weight;
        this._dispatchQueue();
      }
      cancel() {
        this._queue.forEach((entry) => entry.reject(this._cancelError));
        this._queue = [];
      }
      _dispatchQueue() {
        this._drainUnlockWaiters();
        while (this._queue.length > 0 && this._queue[0].weight <= this._value) {
          this._dispatchItem(this._queue.shift());
          this._drainUnlockWaiters();
        }
      }
      _dispatchItem(item) {
        const previousValue = this._value;
        this._value -= item.weight;
        item.resolve([previousValue, this._newReleaser(item.weight)]);
      }
      _newReleaser(weight) {
        let called = false;
        return () => {
          if (called)
            return;
          called = true;
          this.release(weight);
        };
      }
      _drainUnlockWaiters() {
        if (this._queue.length === 0) {
          for (let weight = this._value; weight > 0; weight--) {
            const waiters = this._weightedWaiters[weight - 1];
            if (!waiters)
              continue;
            waiters.forEach((waiter) => waiter.resolve());
            this._weightedWaiters[weight - 1] = [];
          }
        } else {
          const queuedPriority = this._queue[0].priority;
          for (let weight = this._value; weight > 0; weight--) {
            const waiters = this._weightedWaiters[weight - 1];
            if (!waiters)
              continue;
            const i4 = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);
            (i4 === -1 ? waiters : waiters.splice(0, i4)).forEach((waiter) => waiter.resolve());
          }
        }
      }
      _couldLockImmediately(weight, priority) {
        return (this._queue.length === 0 || this._queue[0].priority < priority) && weight <= this._value;
      }
    };
    __name(insertSorted, "insertSorted");
    __name(findIndexFromEnd, "findIndexFromEnd");
    __awaiter$1 = function(thisArg, _arguments, P2, generator) {
      function adopt(value) {
        return value instanceof P2 ? value : new P2(function(resolve42) {
          resolve42(value);
        });
      }
      __name(adopt, "adopt");
      return new (P2 || (P2 = Promise))(function(resolve42, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e4) {
            reject(e4);
          }
        }
        __name(fulfilled, "fulfilled");
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e4) {
            reject(e4);
          }
        }
        __name(rejected, "rejected");
        function step(result) {
          result.done ? resolve42(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        __name(step, "step");
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Mutex = class {
      static {
        __name(this, "Mutex");
      }
      constructor(cancelError) {
        this._semaphore = new Semaphore(1, cancelError);
      }
      acquire() {
        return __awaiter$1(this, arguments, void 0, function* (priority = 0) {
          const [, releaser] = yield this._semaphore.acquire(1, priority);
          return releaser;
        });
      }
      runExclusive(callback, priority = 0) {
        return this._semaphore.runExclusive(() => callback(), 1, priority);
      }
      isLocked() {
        return this._semaphore.isLocked();
      }
      waitForUnlock(priority = 0) {
        return this._semaphore.waitForUnlock(1, priority);
      }
      release() {
        if (this._semaphore.isLocked())
          this._semaphore.release();
      }
      cancel() {
        return this._semaphore.cancel();
      }
    };
  }
});

// packages/core/dist/src/utils/jsonl-utils.js
import fs28 from "node:fs";
import path21 from "node:path";
import readline from "node:readline";
function getFileLock(filePath) {
  if (!fileLocks.has(filePath)) {
    fileLocks.set(filePath, new Mutex());
  }
  return fileLocks.get(filePath);
}
function _recoverObjectsFromLine(line) {
  const out2 = [];
  let depth = 0;
  let inString = false;
  let escape7 = false;
  let start2 = -1;
  for (let i4 = 0; i4 < line.length; i4++) {
    const c4 = line[i4];
    if (escape7) {
      escape7 = false;
      continue;
    }
    if (inString) {
      if (c4 === "\\")
        escape7 = true;
      else if (c4 === '"')
        inString = false;
      continue;
    }
    if (c4 === '"') {
      inString = true;
      continue;
    }
    if (c4 === "{") {
      if (depth === 0)
        start2 = i4;
      depth++;
    } else if (c4 === "}") {
      depth--;
      if (depth === 0 && start2 >= 0) {
        const fragment = line.slice(start2, i4 + 1);
        try {
          out2.push(JSON.parse(fragment));
        } catch {
        }
        start2 = -1;
      } else if (depth < 0) {
        depth = 0;
        start2 = -1;
      }
    }
  }
  return out2;
}
function parseLineTolerant(line, filePath) {
  try {
    return [JSON.parse(line)];
  } catch {
    const fragments = _recoverObjectsFromLine(line);
    if (fragments.length === 0) {
      debugLogger20.warn(`Failed to parse line in ${filePath}`);
    } else {
      debugLogger20.warn(`Recovered ${fragments.length} record(s) from malformed line in ${filePath}`);
    }
    return fragments;
  }
}
async function readLines(filePath, count) {
  try {
    const fileStream = fs28.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)
        continue;
      for (const obj of parseLineTolerant(trimmed2, filePath)) {
        if (results.length >= count)
          break;
        results.push(obj);
      }
    }
    return results;
  } catch (error40) {
    if (error40.code !== "ENOENT") {
      debugLogger20.error(`Error reading first ${count} lines from ${filePath}:`, error40);
    }
    return [];
  }
}
async function read(filePath) {
  try {
    const fileStream = fs28.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)
        continue;
      for (const obj of parseLineTolerant(trimmed2, filePath)) {
        results.push(obj);
      }
    }
    return results;
  } catch (error40) {
    if (error40.code !== "ENOENT") {
      debugLogger20.error(`Error reading ${filePath}:`, error40);
    }
    return [];
  }
}
function _resetEnsuredDirsCacheForTest() {
  ensuredDirs.clear();
}
async function writeLine(filePath, data) {
  const lock = getFileLock(filePath);
  await lock.runExclusive(async () => {
    const line = `${JSON.stringify(data)}
`;
    const dir = path21.dirname(filePath);
    if (!ensuredDirs.has(dir)) {
      await fs28.promises.mkdir(dir, { recursive: true });
      ensuredDirs.add(dir);
    }
    await fs28.promises.appendFile(filePath, line, "utf8");
  });
}
function writeLineSync(filePath, data) {
  const line = `${JSON.stringify(data)}
`;
  const dir = path21.dirname(filePath);
  if (!fs28.existsSync(dir)) {
    fs28.mkdirSync(dir, { recursive: true });
  }
  fs28.appendFileSync(filePath, line, "utf8");
}
function write(filePath, data) {
  const lines = data.map((item) => JSON.stringify(item)).join("\n");
  const dir = path21.dirname(filePath);
  if (!fs28.existsSync(dir)) {
    fs28.mkdirSync(dir, { recursive: true });
  }
  fs28.writeFileSync(filePath, `${lines}
`, "utf8");
}
async function countLines(filePath) {
  try {
    const fileStream = fs28.createReadStream(filePath);
    const rl = readline.createInterface({
      input: fileStream,
      crlfDelay: Infinity
    });
    let count = 0;
    for await (const line of rl) {
      if (line.trim().length > 0) {
        count++;
      }
    }
    return count;
  } catch (error40) {
    if (error40.code !== "ENOENT") {
      debugLogger20.error(`Error counting lines in ${filePath}:`, error40);
    }
    return 0;
  }
}
function exists(filePath) {
  try {
    const stats = fs28.statSync(filePath);
    return stats.isFile() && stats.size > 0;
  } catch {
    return false;
  }
}
var debugLogger20, fileLocks, ensuredDirs;
var init_jsonl_utils = __esm({
  "packages/core/dist/src/utils/jsonl-utils.js"() {
    "use strict";
    init_esbuild_shims();
    init_async_mutex();
    init_debugLogger();
    debugLogger20 = createDebugLogger("JSONL");
    fileLocks = /* @__PURE__ */ new Map();
    __name(getFileLock, "getFileLock");
    __name(_recoverObjectsFromLine, "_recoverObjectsFromLine");
    __name(parseLineTolerant, "parseLineTolerant");
    __name(readLines, "readLines");
    __name(read, "read");
    ensuredDirs = /* @__PURE__ */ new Set();
    __name(_resetEnsuredDirsCacheForTest, "_resetEnsuredDirsCacheForTest");
    __name(writeLine, "writeLine");
    __name(writeLineSync, "writeLineSync");
    __name(write, "write");
    __name(countLines, "countLines");
    __name(exists, "exists");
  }
});

// packages/core/dist/src/utils/gitUtils.js
import * as fs29 from "node:fs";
import * as path22 from "node:path";
import { execSync as execSync2 } from "node:child_process";
function isGitRepository(directory) {
  try {
    let currentDir = path22.resolve(directory);
    while (true) {
      const gitDir = path22.join(currentDir, ".git");
      if (fs29.existsSync(gitDir)) {
        return true;
      }
      const parentDir = path22.dirname(currentDir);
      if (parentDir === currentDir) {
        break;
      }
      currentDir = parentDir;
    }
    return false;
  } catch (_error) {
    return false;
  }
}
function findGitRoot2(directory) {
  try {
    let currentDir = path22.resolve(directory);
    while (true) {
      const gitDir = path22.join(currentDir, ".git");
      if (fs29.existsSync(gitDir)) {
        return currentDir;
      }
      const parentDir = path22.dirname(currentDir);
      if (parentDir === currentDir) {
        break;
      }
      currentDir = parentDir;
    }
    return null;
  } catch (_error) {
    return null;
  }
}
var getGitBranch, getGitRepoName;
var init_gitUtils = __esm({
  "packages/core/dist/src/utils/gitUtils.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isGitRepository, "isGitRepository");
    __name(findGitRoot2, "findGitRoot");
    getGitBranch = /* @__PURE__ */ __name((cwd6) => {
      try {
        const branch = execSync2("git rev-parse --abbrev-ref HEAD", {
          cwd: cwd6,
          encoding: "utf8",
          stdio: ["pipe", "pipe", "pipe"]
        }).trim();
        return branch || void 0;
      } catch {
        return void 0;
      }
    }, "getGitBranch");
    getGitRepoName = /* @__PURE__ */ __name((cwd6) => {
      try {
        const remoteUrl = execSync2("git remote get-url origin", {
          cwd: cwd6,
          encoding: "utf8",
          stdio: ["pipe", "pipe", "pipe"]
        }).trim();
        if (remoteUrl) {
          let normalizedUrl = remoteUrl;
          if (remoteUrl.startsWith("git@")) {
            normalizedUrl = remoteUrl.replace(/^git@[^:]+:/, "https://host.com/");
          }
          try {
            const url3 = new URL(normalizedUrl);
            const pathParts = url3.pathname.replace(/\.git$/, "").split("/").filter(Boolean);
            if (pathParts.length >= 2) {
              return `${pathParts[0]}/${pathParts[1]}`;
            }
          } catch {
            const match2 = remoteUrl.match(/[:/]([^/]+)\/([^/]+?)(?:\.git)?$/);
            if (match2 && match2[1] && match2[2]) {
              return `${match2[1]}/${match2[2]}`;
            }
          }
        }
      } catch {
      }
      const gitRoot = findGitRoot2(cwd6);
      if (gitRoot) {
        return path22.basename(gitRoot);
      }
      return void 0;
    }, "getGitRepoName");
  }
});

// packages/core/dist/src/utils/terminalSafe.js
function stripTerminalControlSequences(s5) {
  return s5.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, " ").replace(/\x1b\[[\d;?]*[a-zA-Z]/g, " ").replace(/\x1b[NOP]/g, " ").replace(/[\x00-\x1f\x7f]/g, " ");
}
var init_terminalSafe = __esm({
  "packages/core/dist/src/utils/terminalSafe.js"() {
    "use strict";
    init_esbuild_shims();
    __name(stripTerminalControlSequences, "stripTerminalControlSequences");
  }
});

// packages/core/dist/src/utils/sessionStorageUtils.js
import fs30 from "node:fs";
function getReadOpenFlags() {
  const constants5 = fs30.constants;
  if (!constants5)
    return 0;
  return (constants5.O_RDONLY ?? 0) | (constants5.O_NOFOLLOW ?? 0);
}
function unescapeJsonString(raw2) {
  if (!raw2.includes("\\"))
    return raw2;
  try {
    return JSON.parse(`"${raw2}"`);
  } catch {
    return raw2;
  }
}
function extractJsonStringField(text, key) {
  const patterns = [`"${key}":"`, `"${key}": "`];
  for (const pattern of patterns) {
    const idx = text.indexOf(pattern);
    if (idx < 0)
      continue;
    const valueStart = idx + pattern.length;
    let i4 = valueStart;
    while (i4 < text.length) {
      if (text[i4] === "\\") {
        i4 += 2;
        continue;
      }
      if (text[i4] === '"') {
        return unescapeJsonString(text.slice(valueStart, i4));
      }
      i4++;
    }
  }
  return void 0;
}
function extractLastJsonStringFields(text, primaryKey, otherKeys, lineContains) {
  const out2 = { [primaryKey]: void 0 };
  for (const k2 of otherKeys)
    out2[k2] = void 0;
  const patterns = [`"${primaryKey}":"`, `"${primaryKey}": "`];
  let bestPrimaryValue;
  let bestLineStart = -1;
  let bestLineEnd = -1;
  let bestOffset = -1;
  for (const pattern of patterns) {
    let searchFrom = 0;
    while (true) {
      const idx = text.indexOf(pattern, searchFrom);
      if (idx < 0)
        break;
      searchFrom = idx + pattern.length;
      const lineStart = text.lastIndexOf("\n", idx) + 1;
      const eol = text.indexOf("\n", idx);
      const lineEnd = eol < 0 ? text.length : eol;
      if (lineContains) {
        const line2 = text.slice(lineStart, lineEnd);
        if (!line2.includes(lineContains))
          continue;
      }
      const valueStart = idx + pattern.length;
      let i4 = valueStart;
      let terminated = false;
      while (i4 < text.length) {
        if (text[i4] === "\\") {
          i4 += 2;
          continue;
        }
        if (text[i4] === '"') {
          terminated = true;
          break;
        }
        i4++;
      }
      if (!terminated)
        continue;
      if (idx > bestOffset) {
        bestOffset = idx;
        bestLineStart = lineStart;
        bestLineEnd = lineEnd;
        bestPrimaryValue = unescapeJsonString(text.slice(valueStart, i4));
      }
    }
  }
  if (bestOffset < 0)
    return out2;
  out2[primaryKey] = bestPrimaryValue;
  const line = text.slice(bestLineStart, bestLineEnd);
  for (const k2 of otherKeys) {
    out2[k2] = extractJsonStringField(line, k2);
  }
  return out2;
}
function extractLastJsonStringField(text, key, lineContains) {
  const patterns = [`"${key}":"`, `"${key}": "`];
  let lastValue;
  let lastOffset = -1;
  for (const pattern of patterns) {
    let searchFrom = 0;
    while (true) {
      const idx = text.indexOf(pattern, searchFrom);
      if (idx < 0)
        break;
      if (lineContains) {
        const lineStart = text.lastIndexOf("\n", idx) + 1;
        const lineEnd = text.indexOf("\n", idx);
        const line = text.slice(lineStart, lineEnd < 0 ? text.length : lineEnd);
        if (!line.includes(lineContains)) {
          searchFrom = idx + pattern.length;
          continue;
        }
      }
      const valueStart = idx + pattern.length;
      let i4 = valueStart;
      while (i4 < text.length) {
        if (text[i4] === "\\") {
          i4 += 2;
          continue;
        }
        if (text[i4] === '"') {
          if (idx > lastOffset) {
            lastValue = unescapeJsonString(text.slice(valueStart, i4));
            lastOffset = idx;
          }
          break;
        }
        i4++;
      }
      searchFrom = i4 + 1;
    }
  }
  return lastValue;
}
function readLastJsonStringFieldSync(filePath, key, lineContains) {
  let fd;
  try {
    const stats = fs30.statSync(filePath);
    const fileSize = stats.size;
    if (fileSize === 0)
      return void 0;
    fd = fs30.openSync(filePath, getReadOpenFlags());
    const tailLength = Math.min(fileSize, LITE_READ_BUF_SIZE);
    const tailOffset = fileSize - tailLength;
    const tailBuffer = Buffer.alloc(tailLength);
    const tailBytes = fs30.readSync(fd, tailBuffer, 0, tailLength, tailOffset);
    if (tailBytes > 0) {
      const tailText = tailBuffer.toString("utf-8", 0, tailBytes);
      const tailHit = extractLastJsonStringField(tailText, key, lineContains);
      if (tailHit !== void 0) {
        return tailHit;
      }
    }
    if (tailOffset === 0)
      return void 0;
    let lastHit;
    let readOffset = 0;
    let carry = "";
    const scanLimit = Math.min(fileSize, MAX_FULL_SCAN_BYTES);
    while (readOffset < scanLimit) {
      const toRead = Math.min(LITE_READ_BUF_SIZE, scanLimit - readOffset);
      const buf = Buffer.alloc(toRead);
      const bytesRead = fs30.readSync(fd, buf, 0, toRead, readOffset);
      if (bytesRead === 0)
        break;
      readOffset += bytesRead;
      const chunk = carry + buf.toString("utf-8", 0, bytesRead);
      const lastNewline = chunk.lastIndexOf("\n");
      if (lastNewline < 0) {
        carry = chunk;
        continue;
      }
      const complete = chunk.slice(0, lastNewline + 1);
      carry = chunk.slice(lastNewline + 1);
      const hit = extractLastJsonStringField(complete, key, lineContains);
      if (hit !== void 0)
        lastHit = hit;
    }
    if (carry) {
      const hit = extractLastJsonStringField(carry, key, lineContains);
      if (hit !== void 0)
        lastHit = hit;
    }
    return lastHit;
  } catch {
    return void 0;
  } finally {
    if (fd !== void 0) {
      try {
        fs30.closeSync(fd);
      } catch {
      }
    }
  }
}
function readLastJsonStringFieldsSync(filePath, primaryKey, otherKeys, lineContains) {
  const emptyResult = {};
  emptyResult[primaryKey] = void 0;
  for (const k2 of otherKeys)
    emptyResult[k2] = void 0;
  let fd;
  try {
    const stats = fs30.statSync(filePath);
    const fileSize = stats.size;
    if (fileSize === 0)
      return emptyResult;
    fd = fs30.openSync(filePath, getReadOpenFlags());
    const tailLength = Math.min(fileSize, LITE_READ_BUF_SIZE);
    const tailOffset = fileSize - tailLength;
    const tailBuffer = Buffer.alloc(tailLength);
    const tailBytes = fs30.readSync(fd, tailBuffer, 0, tailLength, tailOffset);
    if (tailBytes > 0) {
      const tailText = tailBuffer.toString("utf-8", 0, tailBytes);
      const hit = extractLastJsonStringFields(tailText, primaryKey, otherKeys, lineContains);
      if (hit[primaryKey] !== void 0)
        return hit;
    }
    if (tailOffset === 0)
      return emptyResult;
    let latest;
    let readOffset = 0;
    let carry = "";
    const scanLimit = Math.min(fileSize, MAX_FULL_SCAN_BYTES);
    while (readOffset < scanLimit) {
      const toRead = Math.min(LITE_READ_BUF_SIZE, scanLimit - readOffset);
      const buf = Buffer.alloc(toRead);
      const bytesRead = fs30.readSync(fd, buf, 0, toRead, readOffset);
      if (bytesRead === 0)
        break;
      readOffset += bytesRead;
      const chunk = carry + buf.toString("utf-8", 0, bytesRead);
      const lastNewline = chunk.lastIndexOf("\n");
      if (lastNewline < 0) {
        carry = chunk;
        continue;
      }
      const complete = chunk.slice(0, lastNewline + 1);
      carry = chunk.slice(lastNewline + 1);
      const hit = extractLastJsonStringFields(complete, primaryKey, otherKeys, lineContains);
      if (hit[primaryKey] !== void 0)
        latest = hit;
    }
    if (carry) {
      const hit = extractLastJsonStringFields(carry, primaryKey, otherKeys, lineContains);
      if (hit[primaryKey] !== void 0)
        latest = hit;
    }
    return latest ?? emptyResult;
  } catch {
    return emptyResult;
  } finally {
    if (fd !== void 0) {
      try {
        fs30.closeSync(fd);
      } catch {
      }
    }
  }
}
var LITE_READ_BUF_SIZE, MAX_FULL_SCAN_BYTES;
var init_sessionStorageUtils = __esm({
  "packages/core/dist/src/utils/sessionStorageUtils.js"() {
    "use strict";
    init_esbuild_shims();
    LITE_READ_BUF_SIZE = 64 * 1024;
    MAX_FULL_SCAN_BYTES = 64 * 1024 * 1024;
    __name(getReadOpenFlags, "getReadOpenFlags");
    __name(unescapeJsonString, "unescapeJsonString");
    __name(extractJsonStringField, "extractJsonStringField");
    __name(extractLastJsonStringFields, "extractLastJsonStringFields");
    __name(extractLastJsonStringField, "extractLastJsonStringField");
    __name(readLastJsonStringFieldSync, "readLastJsonStringFieldSync");
    __name(readLastJsonStringFieldsSync, "readLastJsonStringFieldsSync");
  }
});

// packages/core/dist/src/services/sessionService.js
import path23 from "node:path";
import fs31 from "node:fs";
import { randomUUID as randomUUID4 } from "node:crypto";
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 = false } = 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 i4 = lastCompressionIndex + 1; i4 < messages.length; i4++) {
      const record2 = messages[i4];
      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) {
  for (let i4 = conversation.messages.length - 1; i4 >= 0; i4--) {
    const record2 = conversation.messages[i4];
    if (record2.type === "assistant") {
      const usage2 = record2.usageMetadata;
      const candidate = usage2?.totalTokenCount ?? usage2?.promptTokenCount;
      if (candidate) {
        return candidate;
      }
    }
    if (record2.type === "system" && record2.subtype === "chat_compression") {
      const payload = record2.systemPayload;
      if (payload?.info) {
        return payload.info.newTokenCount;
      }
    }
  }
  return void 0;
}
var debugLogger21, MAX_FILES_TO_PROCESS, SESSION_TITLE_MAX_LENGTH, SESSION_FILE_PATTERN, MAX_PROMPT_SCAN_LINES, TAIL_READ_SIZE, 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();
    init_sessionStorageUtils();
    debugLogger21 = createDebugLogger("SESSION");
    MAX_FILES_TO_PROCESS = 1e4;
    SESSION_TITLE_MAX_LENGTH = 200;
    SESSION_FILE_PATTERN = /^[0-9a-fA-F-]{32,36}\.jsonl$/;
    MAX_PROMPT_SCAN_LINES = 10;
    TAIL_READ_SIZE = 64 * 1024;
    SessionService = class {
      static {
        __name(this, "SessionService");
      }
      storage;
      projectHash;
      constructor(cwd6) {
        this.storage = new Storage(cwd6);
        this.projectHash = getProjectHash(cwd6);
      }
      getChatsDir() {
        return path23.join(this.storage.getProjectDir(), "chats");
      }
      /**
       * Reads the session title from a JSONL file.
       *
       * Delegates to {@link readLastJsonStringFieldSync}, which scans the tail
       * window first (fast path; almost always hits because finalize() re-appends
       * the title on every lifecycle event) and falls back to a full-file scan
       * when the tail has no match. The `custom_title` line-marker guards against
       * false matches from user content that happens to include a `customTitle`
       * field.
       */
      readSessionTitleFromFile(filePath) {
        return readLastJsonStringFieldSync(filePath, "customTitle", '"subtype":"custom_title"');
      }
      /**
       * Reads both the custom title and its source from a session file in a
       * single pass — the helper extracts both fields from the same matching
       * `custom_title` line, so the pair is always consistent (never one field
       * from an old record and another from a new one).
       *
       * `titleSource` is absent on legacy records written before the field was
       * introduced — callers treat `undefined` as equivalent to `'manual'` so a
       * user's pre-upgrade rename is never displayed as if it were auto-generated.
       */
      readSessionTitleInfoFromFile(filePath) {
        const hit = readLastJsonStringFieldsSync(filePath, "customTitle", ["titleSource"], '"subtype":"custom_title"');
        const title = hit["customTitle"];
        if (!title)
          return {};
        const rawSource = hit["titleSource"];
        const source2 = rawSource === "auto" || rawSource === "manual" ? rawSource : void 0;
        return { title, source: source2 };
      }
      /**
       * Public accessor: returns both the current custom title and its source
       * for a given session. Used by `ChatRecordingService` on resume to
       * preserve the persisted `titleSource` rather than defaulting to manual.
       */
      getSessionTitleInfo(sessionId) {
        if (!SESSION_FILE_PATTERN.test(`${sessionId}.jsonl`)) {
          return {};
        }
        const chatsDir = this.getChatsDir();
        const filePath = path23.join(chatsDir, `${sessionId}.jsonl`);
        return this.readSessionTitleInfoFromFile(filePath);
      }
      /**
       * Reads the UUID of the last record in a session JSONL file.
       * Uses a tail-read strategy for efficiency.
       */
      readLastRecordUuid(filePath) {
        try {
          const stats = fs31.statSync(filePath);
          const fileSize = stats.size;
          const readStart = Math.max(0, fileSize - TAIL_READ_SIZE);
          const readLength = Math.min(fileSize, TAIL_READ_SIZE);
          const fd = fs31.openSync(filePath, "r");
          let buffer;
          try {
            buffer = Buffer.alloc(readLength);
            fs31.readSync(fd, buffer, 0, readLength, readStart);
          } finally {
            fs31.closeSync(fd);
          }
          const tail = buffer.toString("utf-8");
          const lines = tail.split("\n");
          for (let i4 = lines.length - 1; i4 >= 0; i4--) {
            const trimmed2 = lines[i4].trim();
            if (!trimmed2)
              continue;
            try {
              const record2 = JSON.parse(trimmed2);
              if (record2.uuid) {
                return record2.uuid;
              }
            } catch {
              continue;
            }
          }
          return null;
        } catch {
          return null;
        }
      }
      /**
       * 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 = fs31.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 = fs31.readdirSync(chatsDir);
          for (const name4 of fileNames) {
            if (!SESSION_FILE_PATTERN.test(name4))
              continue;
            const filePath = path23.join(chatsDir, name4);
            try {
              const stats = fs31.statSync(filePath);
              files.push({ name: name4, mtime: stats.mtimeMs });
            } catch {
              continue;
            }
          }
        } catch (error40) {
          if (error40.code === "ENOENT") {
            return { items: [], hasMore: false };
          }
          throw error40;
        }
        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 file2 of files) {
          if (filesProcessed >= MAX_FILES_TO_PROCESS) {
            hasMoreFiles = true;
            break;
          }
          if (items.length >= size) {
            hasMoreFiles = true;
            break;
          }
          filesProcessed++;
          lastProcessedMtime = file2.mtime;
          const filePath = path23.join(chatsDir, file2.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);
          const titleInfo = this.readSessionTitleInfoFromFile(filePath);
          items.push({
            sessionId: firstRecord.sessionId,
            cwd: firstRecord.cwd,
            startTime: firstRecord.timestamp,
            mtime: file2.mtime,
            prompt,
            gitBranch: firstRecord.gitBranch,
            filePath,
            messageCount,
            customTitle: titleInfo.title,
            titleSource: titleInfo.source
          });
        }
        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 (error40) {
          if (error40.code !== "ENOENT") {
            debugLogger21.error("Error reading session file:", error40);
          }
          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 i4 = 1; i4 < records.length; i4++) {
          const record2 = records[i4];
          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 uuid3 of uuidChain) {
          const recordsForUuid = recordsByUuid.get(uuid3);
          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 = path23.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 = fs31.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) {
        if (!SESSION_FILE_PATTERN.test(`${sessionId}.jsonl`)) {
          return false;
        }
        const chatsDir = this.getChatsDir();
        const filePath = path23.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;
          }
          fs31.unlinkSync(filePath);
          return true;
        } catch (error40) {
          if (error40.code === "ENOENT") {
            return false;
          }
          throw error40;
        }
      }
      /**
       * Renames a session by appending a custom_title system record to its JSONL file.
       *
       * @param sessionId The session ID to rename
       * @param title The new custom title
       * @param titleSource Where the title came from. Defaults to `'manual'` so
       *   existing callers are unchanged — pass `'auto'` only for titles produced
       *   by the auto-title generator.
       * @returns true if renamed successfully, false if session not found
       */
      async renameSession(sessionId, title, titleSource = "manual") {
        if (!SESSION_FILE_PATTERN.test(`${sessionId}.jsonl`)) {
          return false;
        }
        const chatsDir = this.getChatsDir();
        const filePath = path23.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;
          }
          const lastUuid = this.readLastRecordUuid(filePath);
          const titleRecord = {
            uuid: randomUUID4(),
            parentUuid: lastUuid,
            sessionId,
            timestamp: (/* @__PURE__ */ new Date()).toISOString(),
            type: "system",
            subtype: "custom_title",
            cwd: records[0].cwd,
            version: records[0].version,
            systemPayload: { customTitle: title, titleSource }
          };
          writeLineSync(filePath, titleRecord);
          return true;
        } catch (error40) {
          if (error40.code === "ENOENT") {
            return false;
          }
          throw error40;
        }
      }
      /**
       * Gets the custom title for a session by reading from its JSONL file.
       *
       * @param sessionId The session ID to look up
       * @returns The custom title, or undefined if none set
       */
      getSessionTitle(sessionId) {
        if (!SESSION_FILE_PATTERN.test(`${sessionId}.jsonl`)) {
          return void 0;
        }
        const chatsDir = this.getChatsDir();
        const filePath = path23.join(chatsDir, `${sessionId}.jsonl`);
        return this.readSessionTitleFromFile(filePath);
      }
      /**
       * Finds sessions by custom title.
       * Returns all matching sessions ordered by most recent first.
       *
       * @param title The custom title to search for (case-insensitive exact match)
       * @returns Array of matching session list items
       */
      async findSessionsByTitle(title) {
        const normalizedTitle = title.toLowerCase().trim();
        const matches2 = [];
        const chatsDir = this.getChatsDir();
        let fileNames;
        try {
          fileNames = fs31.readdirSync(chatsDir);
        } catch (error40) {
          if (error40.code === "ENOENT") {
            return matches2;
          }
          throw error40;
        }
        const files = [];
        for (const name4 of fileNames) {
          if (!SESSION_FILE_PATTERN.test(name4))
            continue;
          const filePath = path23.join(chatsDir, name4);
          try {
            const stats = fs31.statSync(filePath);
            files.push({ name: name4, mtime: stats.mtimeMs });
          } catch {
            continue;
          }
        }
        files.sort((a2, b2) => b2.mtime - a2.mtime || a2.name.localeCompare(b2.name));
        let filesProcessed = 0;
        for (const file2 of files) {
          if (filesProcessed >= MAX_FILES_TO_PROCESS)
            break;
          filesProcessed++;
          const filePath = path23.join(chatsDir, file2.name);
          const titleInfo = this.readSessionTitleInfoFromFile(filePath);
          if (titleInfo.title?.toLowerCase().trim() !== normalizedTitle)
            continue;
          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);
          matches2.push({
            sessionId: firstRecord.sessionId,
            cwd: firstRecord.cwd,
            startTime: firstRecord.timestamp,
            mtime: file2.mtime,
            prompt,
            gitBranch: firstRecord.gitBranch,
            filePath,
            messageCount,
            customTitle: titleInfo.title,
            titleSource: titleInfo.source
          });
        }
        return matches2;
      }
      /**
       * 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) {
        if (!SESSION_FILE_PATTERN.test(`${sessionId}.jsonl`)) {
          return false;
        }
        const chatsDir = this.getChatsDir();
        const filePath = path23.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/services/sessionTitle.js
async function tryGenerateSessionTitle(config2, abortSignal) {
  try {
    const model = config2.getFastModel();
    if (!model)
      return { ok: false, reason: "no_fast_model" };
    const geminiClient = config2.getGeminiClient();
    if (!geminiClient)
      return { ok: false, reason: "no_client" };
    const fullHistory = geminiClient.getChat().getHistory();
    if (fullHistory.length < 2)
      return { ok: false, reason: "empty_history" };
    const dialog = filterToDialog(fullHistory);
    const recentHistory = takeRecentDialog(dialog, RECENT_MESSAGE_WINDOW);
    if (recentHistory.length === 0) {
      return { ok: false, reason: "empty_history" };
    }
    const conversationText = flattenToTail(recentHistory, MAX_CONVERSATION_CHARS);
    if (!conversationText.trim())
      return { ok: false, reason: "empty_history" };
    const baseLlmClient = config2.getBaseLlmClient();
    if (!baseLlmClient)
      return { ok: false, reason: "no_client" };
    const result = await baseLlmClient.generateJson({
      model,
      systemInstruction: TITLE_SYSTEM_PROMPT,
      schema: TITLE_SCHEMA,
      contents: [
        {
          role: "user",
          parts: [
            {
              text: `Conversation so far:
${conversationText}

${TITLE_USER_PROMPT}`
            }
          ]
        }
      ],
      config: {
        temperature: 0.2,
        maxOutputTokens: 100
      },
      abortSignal,
      promptId: "session_title",
      // Titles are best-effort cosmetic metadata — one shot only, no long retry loop.
      maxAttempts: 1
    });
    if (abortSignal.aborted)
      return { ok: false, reason: "aborted" };
    const rawTitle = typeof result?.["title"] === "string" ? result["title"] : "";
    const title = sanitizeTitle(rawTitle);
    if (!title)
      return { ok: false, reason: "empty_result" };
    return { ok: true, title, modelUsed: model };
  } catch (err2) {
    debugLogger22.warn(`Session title generation failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
    if (abortSignal.aborted)
      return { ok: false, reason: "aborted" };
    return { ok: false, reason: "model_error" };
  }
}
function sanitizeTitle(s5) {
  let t5 = stripTerminalControlSequences(s5).trim();
  t5 = t5.replace(LEADING_PAIRED_BRACKETS_RE, "");
  t5 = t5.replace(TRAILING_PAIRED_BRACKETS_RE, "");
  t5 = t5.replace(LEADING_MARKERS_RE, "");
  t5 = t5.replace(TRAILING_MARKERS_RE, "");
  t5 = t5.replace(TRAILING_PUNCT_RE, "");
  t5 = t5.replace(/\s+/g, " ").trim();
  if (!t5)
    return "";
  if (t5.length > SESSION_TITLE_MAX_LENGTH) {
    t5 = t5.slice(0, SESSION_TITLE_MAX_LENGTH).trim();
    t5 = t5.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/g, "");
    t5 = t5.replace(/(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "");
  }
  return t5;
}
function filterToDialog(history) {
  const out2 = [];
  for (const msg of history) {
    if (msg.role !== "user" && msg.role !== "model")
      continue;
    const textParts = (msg.parts ?? []).filter((part) => typeof part?.text === "string" && part.text.trim() !== "" && !part.thought && !part.thoughtSignature);
    if (textParts.length === 0)
      continue;
    out2.push({ role: msg.role, parts: textParts });
  }
  return out2;
}
function takeRecentDialog(history, windowSize) {
  if (history.length <= windowSize)
    return history;
  let start2 = history.length - windowSize;
  while (start2 < history.length && history[start2]?.role !== "user") {
    start2++;
  }
  return history.slice(start2);
}
function flattenToTail(history, maxChars) {
  const lines = [];
  for (const msg of history) {
    const role = msg.role === "user" ? "User" : "Assistant";
    const text = (msg.parts ?? []).map((p2) => p2.text ?? "").join("").trim();
    if (!text)
      continue;
    lines.push(`${role}: ${text}`);
  }
  const joined = lines.join("\n");
  if (joined.length <= maxChars)
    return joined;
  let tail = joined.slice(-maxChars);
  if (tail.length > 0) {
    const firstCode = tail.charCodeAt(0);
    if (firstCode >= 56320 && firstCode <= 57343) {
      tail = tail.slice(1);
    }
  }
  return tail;
}
var debugLogger22, MAX_CONVERSATION_CHARS, RECENT_MESSAGE_WINDOW, TITLE_SYSTEM_PROMPT, TITLE_USER_PROMPT, TITLE_SCHEMA, LEADING_MARKERS_RE, TRAILING_MARKERS_RE, TRAILING_PUNCT_RE, LEADING_PAIRED_BRACKETS_RE, TRAILING_PAIRED_BRACKETS_RE;
var init_sessionTitle = __esm({
  "packages/core/dist/src/services/sessionTitle.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_terminalSafe();
    init_sessionService();
    debugLogger22 = createDebugLogger("SESSION_TITLE");
    MAX_CONVERSATION_CHARS = 1e3;
    RECENT_MESSAGE_WINDOW = 20;
    TITLE_SYSTEM_PROMPT = `Generate a concise, sentence-case title (3-7 words) that captures what this programming-assistant session is about. Think of it as a git commit subject for the session.

Rules:
- 3-7 words.
- Sentence case: capitalize only the first word and proper nouns. NOT Title Case.
- No trailing punctuation.
- No quotes, backticks, or markdown.
- Match the dominant language of the conversation (English or Chinese). For Chinese, treat as roughly 12-20 characters total; still no trailing punctuation.
- Be specific about the user's actual goal \u2014 name the feature, bug, or subject area. Avoid vague "Code changes", "Help request", "Conversation".

Good examples:
{"title": "Fix login button on mobile"}
{"title": "Add OAuth authentication flow"}
{"title": "Debug failing CI pipeline tests"}
{"title": "\u91CD\u6784\u7528\u6237\u9274\u6743\u4E2D\u95F4\u4EF6"}

Bad (too vague): {"title": "Code changes"}
Bad (too long): {"title": "Investigate and fix the session title generation issue in the chat recording service"}
Bad (wrong case): {"title": "Fix Login Button On Mobile"}
Bad (trailing punctuation): {"title": "Fix login button."}

Return ONLY a JSON object with a single "title" key. No preamble, no reasoning, no closing remarks.`;
    TITLE_USER_PROMPT = "Generate the session title now. Populate the schema with a single short title string.";
    TITLE_SCHEMA = {
      type: "object",
      properties: {
        title: {
          type: "string",
          description: "A concise sentence-case session title, 3-7 words, no trailing punctuation."
        }
      },
      required: ["title"]
    };
    LEADING_MARKERS_RE = /^[\s>*\-#`"'_]+/;
    TRAILING_MARKERS_RE = /[\s*`"'_]+$/;
    TRAILING_PUNCT_RE = /[.!?。！？,，;；:：]+$/;
    LEADING_PAIRED_BRACKETS_RE = /^\s*[「『【〈《][^」』】〉》]*[」』】〉》]\s*/;
    TRAILING_PAIRED_BRACKETS_RE = /\s*[「『【〈《][^」』】〉》]*[」』】〉》]\s*$/;
    __name(tryGenerateSessionTitle, "tryGenerateSessionTitle");
    __name(sanitizeTitle, "sanitizeTitle");
    __name(filterToDialog, "filterToDialog");
    __name(takeRecentDialog, "takeRecentDialog");
    __name(flattenToTail, "flattenToTail");
  }
});

// packages/core/dist/src/services/chatRecordingService.js
import path24 from "node:path";
import fs32 from "node:fs";
import { randomUUID as randomUUID5 } from "node:crypto";
function autoTitleDisabledByEnv() {
  const v2 = process.env["QWEN_DISABLE_AUTO_TITLE"];
  if (!v2)
    return false;
  const lowered = v2.trim().toLowerCase();
  return lowered !== "" && lowered !== "0" && lowered !== "false" && lowered !== "no" && lowered !== "off";
}
var debugLogger23, AUTO_TITLE_ATTEMPT_CAP, 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();
    init_sessionTitle();
    debugLogger23 = createDebugLogger("CHAT_RECORDING");
    AUTO_TITLE_ATTEMPT_CAP = 3;
    __name(autoTitleDisabledByEnv, "autoTitleDisabledByEnv");
    ChatRecordingService = class {
      static {
        __name(this, "ChatRecordingService");
      }
      /** UUID of the last written record in the chain */
      lastRecordUuid = null;
      config;
      /**
       * Tracks the `lastRecordUuid` value just before each user turn was recorded.
       * Used by {@link rewindRecording} to re-root the parentUuid chain so that
       * rewound messages end up on a dead branch in the tree, making
       * `reconstructHistory()` skip them automatically on resume.
       *
       * Index `i` holds the UUID of the last record written before the (i+1)th
       * user message was appended. For example, `turnParentUuids[0]` is the UUID
       * right before the very first user message (often `null` or the startup
       * context record).
       */
      turnParentUuids = [];
      /**
       * Cached chats-dir / conversation-file path so per-record appendRecord
       * doesn't re-stat them on every write. The first call performs the
       * mkdir / wx-create; subsequent calls short-circuit.
       */
      chatsDirEnsured = false;
      cachedConversationFile;
      /**
       * Serialized async write queue for appendRecord. We update lastRecordUuid
       * synchronously so the next createBaseRecord sees the right parentUuid,
       * but the actual fs write runs in this chain so the event loop is not
       * blocked. Must be flushed before process exit (see {@link flush}).
       */
      writeChain = Promise.resolve();
      /** In-memory cache of the current session's custom title (for re-append on exit) */
      currentCustomTitle;
      /**
       * Source of {@link currentCustomTitle}. `undefined` on legacy records that
       * pre-date the `titleSource` field — that's treated as manual everywhere
       * (safe default) without rewriting the persisted record.
       */
      currentTitleSource;
      /**
       * How many auto-title attempts have been made this process.
       *
       * We don't commit to "one attempt per session" because the first assistant
       * turn may be a pure tool-call with no user-visible text (e.g., the model
       * opens with a search) — the title service returns null, and we'd waste
       * the whole session's chance on a turn that never had a shot. Instead we
       * retry for a handful of turns until either the title lands or we hit the
       * cap, which protects against a persistently failing fast-model looping
       * on every turn. {@link AUTO_TITLE_ATTEMPT_CAP} sets the ceiling.
       */
      autoTitleAttempts = 0;
      /**
       * AbortController for the in-flight auto-title LLM call, or `undefined`
       * when no generation is pending. Doubles as the in-flight guard — a
       * defined controller means "one is running; don't launch another".
       * Stored on the instance so {@link finalize} (called on session switch
       * and shutdown) can cancel a pending call cleanly rather than letting
       * it burn tokens after the session has already moved on.
       */
      autoTitleController;
      constructor(config2) {
        this.config = config2;
        this.lastRecordUuid = config2.getResumedSessionData()?.lastCompletedUuid ?? null;
        if (config2.getResumedSessionData()) {
          try {
            const sessionService = config2.getSessionService();
            const info2 = sessionService.getSessionTitleInfo(config2.getSessionId());
            this.currentCustomTitle = info2.title;
            this.currentTitleSource = info2.source;
            this.finalize();
          } catch {
          }
        }
      }
      /**
       * Returns the current custom title, if any. Read-only accessor for
       * callers (e.g. auto-title trigger) that need to know whether a title is
       * already set before attempting generation.
       */
      getCurrentCustomTitle() {
        return this.currentCustomTitle;
      }
      /**
       * Returns the source of the current custom title, or `undefined` when no
       * title is set.
       */
      getCurrentTitleSource() {
        return this.currentTitleSource;
      }
      /**
       * 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 = path24.join(projectDir, "chats");
        if (this.chatsDirEnsured) {
          return chatsDir;
        }
        try {
          fs32.mkdirSync(chatsDir, { recursive: true });
          this.chatsDirEnsured = true;
        } catch {
        }
        return chatsDir;
      }
      /**
       * Ensures the conversation file exists, creating it if it doesn't exist.
       * Uses atomic file creation to avoid race conditions. Result is cached so
       * subsequent appendRecord calls skip the wx-create entirely.
       * @returns The path to the conversation file.
       * @throws Error if the file cannot be created or accessed.
       */
      ensureConversationFile() {
        if (this.cachedConversationFile) {
          return this.cachedConversationFile;
        }
        const chatsDir = this.ensureChatsDir();
        const sessionId = this.getSessionId();
        const safeFilename = `${sessionId}.jsonl`;
        const conversationFile = path24.join(chatsDir, safeFilename);
        try {
          fs32.writeFileSync(conversationFile, "", { flag: "wx", encoding: "utf8" });
        } catch (error40) {
          const nodeError = error40;
          if (nodeError.code !== "EEXIST") {
            const message = error40 instanceof Error ? error40.message : String(error40);
            throw new Error(`Failed to create conversation file at ${conversationFile}: ${message}`);
          }
        }
        this.cachedConversationFile = conversationFile;
        return conversationFile;
      }
      /**
       * Creates base fields for a ChatRecord.
       */
      createBaseRecord(type) {
        return {
          uuid: randomUUID5(),
          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.
       *
       * lastRecordUuid is updated synchronously so the next createBaseRecord sees
       * the correct parentUuid without waiting for the previous write. The actual
       * fs write is enqueued on {@link writeChain} and runs async; per-file
       * mutex inside {@link jsonl.writeLine} preserves on-disk ordering.
       *
       * **Known tradeoff (parentUuid chain integrity on write failure):** if the
       * enqueued write rejects (e.g., disk full, permission dropped), the error
       * is logged but subsequent records still claim the failed record's uuid
       * as their parent. On resume, readers that walk parentUuid (e.g.
       * sessionService.reconstructHistory) will silently drop records whose
       * ancestor is missing on disk. This matches the sync version's behavior
       * when its own throw was caught and logged by the caller — under normal
       * local-disk writes failures are rare enough to accept the fire-and-forget
       * simplification.
       */
      appendRecord(record2) {
        let conversationFile;
        try {
          conversationFile = this.ensureConversationFile();
        } catch (error40) {
          debugLogger23.error("Error appending record:", error40);
          throw error40;
        }
        this.lastRecordUuid = record2.uuid;
        this.writeChain = this.writeChain.catch(() => {
        }).then(() => writeLine(conversationFile, record2)).catch((err2) => {
          debugLogger23.error("Error appending record (async):", err2);
        });
      }
      /**
       * Awaits all queued async writes. Call before process exit / session
       * teardown to ensure no records are dropped.
       */
      async flush() {
        await this.writeChain;
      }
      /**
       * Records a user message.
       * Writes immediately to disk.
       *
       * @param message The raw PartListUnion object as used with the API
       */
      recordUserMessage(message) {
        try {
          this.turnParentUuids.push(this.lastRecordUuid);
          const record2 = {
            ...this.createBaseRecord("user"),
            message: createUserContent(message)
          };
          this.appendRecord(record2);
        } catch (error40) {
          debugLogger23.error("Error saving user message:", error40);
        }
      }
      /**
       * Records a cron-fired prompt.
       * Stored as a user-role message with subtype 'cron' so the UI
       * restores it as a notification item instead of a user turn.
       */
      recordCronPrompt(message, displayText) {
        this.recordNotificationLike(message, "cron", displayText);
      }
      /**
       * Records a background agent notification.
       * Stored as a user-role message with subtype 'notification' so the
       * UI restores it as an info item, not a user turn.
       */
      recordNotification(message, displayText) {
        this.recordNotificationLike(message, "notification", displayText);
      }
      recordNotificationLike(message, subtype, displayText) {
        try {
          const record2 = {
            ...this.createBaseRecord("user"),
            subtype,
            message: createUserContent(message),
            systemPayload: displayText ? { displayText } : void 0
          };
          this.appendRecord(record2);
        } catch (error40) {
          debugLogger23.error(`Error saving ${subtype} record:`, error40);
        }
      }
      /**
       * 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.contextWindowSize Context window size of the model
       * @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;
          }
          if (data.contextWindowSize !== void 0) {
            record2.contextWindowSize = data.contextWindowSize;
          }
          this.appendRecord(record2);
          this.maybeTriggerAutoTitle();
        } catch (error40) {
          debugLogger23.error("Error saving assistant turn:", error40);
        }
      }
      /**
       * Fire-and-forget: after an assistant turn is recorded, attempt to generate
       * a short session title from the conversation so far. Runs at most once per
       * process lifetime per session and only when:
       *
       * - No title is already set (auto must never overwrite a manual rename,
       *   and we don't need to regenerate an existing auto title mid-session).
       * - A fast model is configured — the service itself also guards this,
       *   but checking here avoids paying for the import/history load when
       *   there's no point.
       *
       * Errors are swallowed. The title is best-effort and must never surface
       * as a user-visible error or interrupt recording.
       */
      maybeTriggerAutoTitle() {
        if (this.currentCustomTitle)
          return;
        if (this.autoTitleController)
          return;
        if (this.autoTitleAttempts >= AUTO_TITLE_ATTEMPT_CAP)
          return;
        if (autoTitleDisabledByEnv())
          return;
        if (!this.config.isInteractive())
          return;
        if (!this.config.getFastModel())
          return;
        this.autoTitleAttempts++;
        const controller = new AbortController();
        this.autoTitleController = controller;
        void (async () => {
          try {
            const outcome = await tryGenerateSessionTitle(this.config, controller.signal);
            if (!outcome.ok)
              return;
            if (controller.signal.aborted)
              return;
            if (this.currentTitleSource === "manual")
              return;
            try {
              const sessionService = this.config.getSessionService();
              const onDisk = sessionService.getSessionTitleInfo(this.config.getSessionId());
              if (onDisk.source === "manual") {
                this.currentCustomTitle = onDisk.title;
                this.currentTitleSource = "manual";
                return;
              }
            } catch {
            }
            this.recordCustomTitle(outcome.title, "auto");
          } catch (err2) {
            debugLogger23.warn(`Auto-title generation failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
          } finally {
            if (this.autoTitleController === controller) {
              this.autoTitleController = void 0;
            }
          }
        })();
      }
      /**
       * 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 (error40) {
          debugLogger23.error("Error saving tool result:", error40);
        }
      }
      /**
       * 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 (error40) {
          debugLogger23.error("Error saving slash command record:", error40);
        }
      }
      /**
       * 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 (error40) {
          debugLogger23.error("Error saving chat compression record:", error40);
        }
      }
      /**
       * 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 (error40) {
          debugLogger23.error("Error saving ui telemetry record:", error40);
        }
      }
      /**
       * Records a conversation rewind and re-roots the parentUuid chain.
       *
       * Sets `lastRecordUuid` back to the UUID that was current just before the
       * target user turn was recorded, then appends a rewind system record.
       * This makes all messages after that point sit on a dead branch in the
       * UUID tree, so `reconstructHistory()` will skip them on resume.
       *
       * @param targetTurnIndex 0-based index of the user turn to rewind to.
       *   For example, 0 means rewind to the very first user message (keeping
       *   nothing before it), 1 means keep the first user turn, etc.
       * @param payload Additional metadata to persist with the rewind record.
       */
      rewindRecording(targetTurnIndex, payload) {
        try {
          this.lastRecordUuid = this.turnParentUuids[targetTurnIndex] ?? null;
          this.turnParentUuids = this.turnParentUuids.slice(0, targetTurnIndex);
          const record2 = {
            ...this.createBaseRecord("system"),
            type: "system",
            subtype: "rewind",
            systemPayload: payload
          };
          this.appendRecord(record2);
        } catch (error40) {
          debugLogger23.error("Error saving rewind record:", error40);
        }
      }
      /**
       * Rebuilds `turnParentUuids` from a reconstructed message list.
       *
       * Call this after resuming a session so that subsequent rewinds within
       * the resumed session have correct boundary data. Also updates
       * `lastRecordUuid` to the last record in the chain.
       */
      rebuildTurnBoundaries(messages) {
        this.turnParentUuids = [];
        let prevUuid = this.config.getResumedSessionData()?.lastCompletedUuid !== void 0 ? null : this.lastRecordUuid;
        for (let i4 = 0; i4 < messages.length; i4++) {
          const record2 = messages[i4];
          if (record2.type === "user" && record2.subtype !== "notification" && record2.subtype !== "cron") {
            this.turnParentUuids.push(prevUuid);
          }
          prevUuid = record2.uuid;
        }
        if (messages.length > 0) {
          this.lastRecordUuid = messages[messages.length - 1].uuid;
        }
      }
      /**
       * Records a custom title for the session.
       * Appended as a system record so it persists with the session data.
       * Also caches the title in memory for re-append on shutdown.
       *
       * @param customTitle The title text.
       * @param titleSource Where the title came from — defaults to `'manual'`
       *   so existing `/rename` call sites keep their behavior unchanged.
       * @returns true if the record was written successfully, false on I/O error.
       */
      recordCustomTitle(customTitle, titleSource = "manual") {
        try {
          const record2 = {
            ...this.createBaseRecord("system"),
            type: "system",
            subtype: "custom_title",
            systemPayload: { customTitle, titleSource }
          };
          this.appendRecord(record2);
          this.currentCustomTitle = customTitle;
          this.currentTitleSource = titleSource;
          return true;
        } catch (error40) {
          debugLogger23.error("Error saving custom title record:", error40);
          return false;
        }
      }
      /**
       * Finalizes the current session by re-appending cached metadata to EOF.
       *
       * Call this whenever leaving the current session — whether switching to
       * another session, shutting down the process, or any other transition.
       * This single entry point replaces scattered re-append calls and ensures
       * the custom_title record stays within the last 64KB tail window that
       * readSessionTitleFromFile() scans.
       *
       * Best-effort: errors are logged but never thrown.
       */
      finalize() {
        if (this.autoTitleController) {
          try {
            this.autoTitleController.abort();
          } catch {
          }
        }
        if (!this.currentCustomTitle) {
          return;
        }
        try {
          const record2 = {
            ...this.createBaseRecord("system"),
            type: "system",
            subtype: "custom_title",
            systemPayload: {
              customTitle: this.currentCustomTitle,
              ...this.currentTitleSource ? { titleSource: this.currentTitleSource } : {}
            }
          };
          this.appendRecord(record2);
        } catch (error40) {
          debugLogger23.error("Error finalizing session metadata:", error40);
        }
      }
      /**
       * 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 (error40) {
          debugLogger23.error("Error saving @-command record:", error40);
        }
      }
    };
  }
});

// packages/core/dist/src/core/geminiChat.js
function delay2(delayMs, signal) {
  let resolveRef;
  let timeoutId;
  const promise2 = new Promise((resolve42, reject) => {
    resolveRef = resolve42;
    if (signal?.aborted) {
      reject(signal.reason);
      return;
    }
    timeoutId = setTimeout(resolve42, delayMs);
    signal?.addEventListener("abort", () => {
      clearTimeout(timeoutId);
      reject(signal.reason);
    }, { once: true });
  });
  return {
    promise: promise2,
    skip: /* @__PURE__ */ __name(() => {
      clearTimeout(timeoutId);
      resolveRef();
    }, "skip")
  };
}
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 i4 = 0;
  while (i4 < length) {
    if (comprehensiveHistory[i4].role === "user") {
      curatedHistory.push(comprehensiveHistory[i4]);
      i4++;
    } else {
      const modelOutput = [];
      let isValid2 = true;
      while (i4 < length && comprehensiveHistory[i4].role === "model") {
        modelOutput.push(comprehensiveHistory[i4]);
        if (isValid2 && !isValidContent2(comprehensiveHistory[i4])) {
          isValid2 = false;
        }
        i4++;
      }
      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 debugLogger24, StreamEventType, INVALID_CONTENT_RETRY_OPTIONS, INVALID_STREAM_RETRY_CONFIG, MAX_OUTPUT_RECOVERY_ATTEMPTS, OUTPUT_RECOVERY_MESSAGE, 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_errors();
    init_debugLogger();
    init_errorParsing();
    init_rateLimit();
    init_tokenLimits();
    init_tools();
    init_loggers();
    init_chatRecordingService();
    init_types4();
    debugLogger24 = 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
    };
    INVALID_STREAM_RETRY_CONFIG = {
      maxRetries: 2,
      initialDelayMs: 2e3
    };
    MAX_OUTPUT_RECOVERY_ATTEMPTS = 3;
    OUTPUT_RECOVERY_MESSAGE = "Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.";
    RATE_LIMIT_RETRY_OPTIONS = {
      maxRetries: 10,
      delayMs: 6e4
    };
    __name(delay2, "delay");
    __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;
      telemetryService;
      // 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.
       * @param telemetryService - Optional UI telemetry service. When provided,
       *   prompt token counts are reported on each API response. Pass `undefined`
       *   for sub-agent chats to avoid overwriting the main agent's context usage.
       */
      constructor(config2, generationConfig = {}, history = [], chatRecordingService, telemetryService) {
        this.config = config2;
        this.generationConfig = generationConfig;
        this.history = history;
        this.chatRecordingService = chatRecordingService;
        this.telemetryService = telemetryService;
        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((resolve42) => {
          streamDoneResolver = resolve42;
        });
        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;
            let invalidStreamRetryCount = 0;
            const cgConfig = self2.config.getContentGeneratorConfig();
            const maxRateLimitRetries = cgConfig?.maxRetries ?? RATE_LIMIT_RETRY_OPTIONS.maxRetries;
            const extraRetryErrorCodes = cgConfig?.retryErrorCodes;
            let maxTokensEscalated = false;
            const hasUserMaxTokensOverride = cgConfig?.samplingParams?.max_tokens !== void 0 && cgConfig?.samplingParams?.max_tokens !== null || !!process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"];
            let lastFinishReason;
            for (let attempt = 0; attempt < INVALID_CONTENT_RETRY_OPTIONS.maxAttempts; attempt++) {
              try {
                if (attempt > 0 || rateLimitRetryCount > 0 || invalidStreamRetryCount > 0) {
                  yield { type: StreamEventType.RETRY };
                }
                const stream5 = await self2.makeApiCallAndProcessStream(model, requestContents, params, prompt_id);
                lastFinishReason = void 0;
                for await (const chunk of stream5) {
                  const fr2 = chunk.candidates?.[0]?.finishReason;
                  if (fr2)
                    lastFinishReason = fr2;
                  yield { type: StreamEventType.CHUNK, value: chunk };
                }
                lastError = null;
                break;
              } catch (error40) {
                lastError = error40;
                const isRateLimit = isRateLimitError(error40, extraRetryErrorCodes);
                if (isRateLimit && rateLimitRetryCount < maxRateLimitRetries) {
                  rateLimitRetryCount++;
                  const delayMs = RATE_LIMIT_RETRY_OPTIONS.delayMs;
                  const message = parseAndFormatApiError(error40 instanceof Error ? error40.message : String(error40));
                  debugLogger24.warn(`Rate limit throttling detected (retry ${rateLimitRetryCount}/${maxRateLimitRetries}). Waiting ${delayMs / 1e3}s before retrying...`);
                  const { promise: delayPromise, skip } = delay2(delayMs, params.config?.abortSignal);
                  yield {
                    type: StreamEventType.RETRY,
                    retryInfo: {
                      message,
                      attempt: rateLimitRetryCount,
                      maxRetries: maxRateLimitRetries,
                      delayMs,
                      skipDelay: skip
                    }
                  };
                  attempt--;
                  await delayPromise;
                  continue;
                }
                const isTransientStreamError = error40 instanceof InvalidStreamError;
                if (isTransientStreamError && invalidStreamRetryCount < INVALID_STREAM_RETRY_CONFIG.maxRetries) {
                  invalidStreamRetryCount++;
                  const delayMs = INVALID_STREAM_RETRY_CONFIG.initialDelayMs * invalidStreamRetryCount;
                  debugLogger24.warn(`Invalid stream [${error40.type}] (retry ${invalidStreamRetryCount}/${INVALID_STREAM_RETRY_CONFIG.maxRetries}). Waiting ${delayMs / 1e3}s before retrying...`);
                  logContentRetry(self2.config, new ContentRetryEvent(invalidStreamRetryCount - 1, error40.type, delayMs, model));
                  yield { type: StreamEventType.RETRY };
                  attempt--;
                  await delay2(delayMs, params.config?.abortSignal).promise;
                  continue;
                }
                if (isTransientStreamError) {
                  break;
                }
                const isContentError = error40 instanceof InvalidStreamError;
                if (isContentError) {
                  if (attempt < INVALID_CONTENT_RETRY_OPTIONS.maxAttempts - 1) {
                    logContentRetry(self2.config, new ContentRetryEvent(attempt, error40.type, INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs, model));
                    await delay2(INVALID_CONTENT_RETRY_OPTIONS.initialDelayMs * (attempt + 1), params.config?.abortSignal).promise;
                    continue;
                  }
                }
                break;
              }
            }
            if (lastError === null && lastFinishReason === FinishReason.MAX_TOKENS && !maxTokensEscalated && !hasUserMaxTokensOverride) {
              maxTokensEscalated = true;
              const escalatedLimit = Math.max(ESCALATED_MAX_TOKENS, tokenLimit(model, "output"));
              debugLogger24.info(`Output truncated at capped default. Escalating to ${escalatedLimit} tokens.`);
              if (self2.history.length > 0 && self2.history[self2.history.length - 1].role === "model") {
                self2.history.pop();
              }
              yield { type: StreamEventType.RETRY };
              const escalatedParams = {
                ...params,
                config: {
                  ...params.config,
                  maxOutputTokens: escalatedLimit
                }
              };
              let escalatedFinishReason;
              const escalatedStream = await self2.makeApiCallAndProcessStream(model, requestContents, escalatedParams, prompt_id);
              for await (const chunk of escalatedStream) {
                const fr2 = chunk.candidates?.[0]?.finishReason;
                if (fr2)
                  escalatedFinishReason = fr2;
                yield { type: StreamEventType.CHUNK, value: chunk };
              }
              let recoveryCount = 0;
              let successfulRecoveries = 0;
              while (escalatedFinishReason === FinishReason.MAX_TOKENS && recoveryCount < MAX_OUTPUT_RECOVERY_ATTEMPTS) {
                const lastEntry = self2.history[self2.history.length - 1];
                const hasFunctionCall = lastEntry?.role === "model" && lastEntry.parts?.some((p2) => p2.functionCall) === true;
                if (hasFunctionCall) {
                  debugLogger24.info("Skipping recovery: truncated turn contains functionCall; deferring to tool scheduler fallback.");
                  break;
                }
                recoveryCount++;
                debugLogger24.info(`Output still truncated after escalation. Recovery attempt ${recoveryCount}/${MAX_OUTPUT_RECOVERY_ATTEMPTS}.`);
                self2.history.push(createUserContent([{ text: OUTPUT_RECOVERY_MESSAGE }]));
                yield { type: StreamEventType.RETRY, isContinuation: true };
                const recoveryContents = self2.getHistory(true);
                escalatedFinishReason = void 0;
                try {
                  const recoveryStream = await self2.makeApiCallAndProcessStream(model, recoveryContents, escalatedParams, prompt_id);
                  for await (const chunk of recoveryStream) {
                    const fr2 = chunk.candidates?.[0]?.finishReason;
                    if (fr2)
                      escalatedFinishReason = fr2;
                    yield { type: StreamEventType.CHUNK, value: chunk };
                  }
                  successfulRecoveries++;
                } catch (recoveryError) {
                  if (self2.history.length > 0 && self2.history[self2.history.length - 1].role === "user") {
                    self2.history.pop();
                  }
                  debugLogger24.warn(`Recovery attempt ${recoveryCount} failed: ${recoveryError}`);
                  yield {
                    type: StreamEventType.CHUNK,
                    value: {
                      candidates: [
                        {
                          content: { role: "model", parts: [] },
                          finishReason: FinishReason.STOP
                        }
                      ]
                    }
                  };
                  break;
                }
              }
              if (successfulRecoveries > 0) {
                self2.coalesceRecoveryPairs(successfulRecoveries);
              }
            }
            if (lastError) {
              if (lastError instanceof InvalidStreamError) {
                const totalAttempts = invalidStreamRetryCount + 1;
                logContentRetryFailure(self2.config, new ContentRetryFailureEvent(totalAttempts, 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((error40) => {
            if (error40 instanceof Error) {
              if (isSchemaDepthError(error40.message))
                return false;
              if (isInvalidArgumentError(error40.message))
                return false;
            }
            const status = getErrorStatus(error40);
            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,
          persistentMode: isUnattendedMode(),
          signal: params.config?.abortSignal,
          heartbeatFn: /* @__PURE__ */ __name((info2) => {
            process.stderr.write(`[qwen-code] Waiting for API capacity... attempt ${info2.attempt}, retry in ${Math.ceil(info2.remainingMs / 1e3)}s
`);
          }, "heartbeatFn")
        });
        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;
      }
      truncateHistory(keepCount) {
        this.history = this.history.slice(0, keepCount);
      }
      /**
       * Pop all orphaned trailing user entries from chat history.
       * In a valid conversation the last entry is always a model response;
       * any trailing user entries are leftovers from a request that failed.
       */
      stripOrphanedUserEntriesFromHistory() {
        while (this.history.length > 0 && this.history[this.history.length - 1].role === "user") {
          this.history.pop();
        }
      }
      setTools(tools) {
        this.generationConfig.tools = tools;
      }
      /** Returns a shallow copy of the current generation config (for cache param snapshots). */
      getGenerationConfig() {
        return { ...this.generationConfig };
      }
      async maybeIncludeSchemaDepthContext(error40) {
        if (isSchemaDepthError(error40.message) || isInvalidArgumentError(error40.message)) {
          const toolRegistry = this.config.getToolRegistry();
          await toolRegistry.warmAll();
          const tools = toolRegistry.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(`
 - `) + `
`;
            error40.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 && this.telemetryService) {
              this.telemetryService.setLastPromptTokenCount(lastPromptTokenCount);
            }
            if (usageMetadata.cachedContentTokenCount && this.telemetryService) {
              this.telemetryService.setLastCachedContentTokenCount(usageMetadata.cachedContentTokenCount);
            }
          }
          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) {
          const contextWindowSize = this.config.getContentGeneratorConfig()?.contextWindowSize;
          this.chatRecordingService?.recordAssistantTurn({
            model,
            message: [
              ...thoughtContentPart ? [thoughtContentPart] : [],
              ...contentText ? [{ text: contentText }] : [],
              ...hasToolCall ? contentParts.filter((part) => part.functionCall).map((part) => ({ functionCall: part.functionCall })) : []
            ],
            tokens: usageMetadata,
            contextWindowSize
          });
        }
        const hasAnyContent = contentText || thoughtText;
        if (!hasToolCall && (!hasFinishReason || !hasAnyContent)) {
          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
          ]
        });
      }
      /**
       * Merge `pairCount` trailing (user_recovery, model_continuation) pairs back
       * into the model turn that precedes them. Used after the output-token
       * recovery loop so the internal OUTPUT_RECOVERY_MESSAGE control prompt
       * does not persist in durable history as if the user sent it.
       *
       * Expected tail shape per iteration (walking from the back):
       *   [..., precedingModel, userRecovery, modelContinuation]
       *
       * If any pair doesn't match that shape the method bails defensively
       * rather than corrupting history.
       */
      coalesceRecoveryPairs(pairCount) {
        for (let i4 = 0; i4 < pairCount; i4++) {
          const len = this.history.length;
          if (len < 3)
            return;
          const modelContinuation = this.history[len - 1];
          const userRecovery = this.history[len - 2];
          const precedingModel = this.history[len - 3];
          if (modelContinuation.role !== "model" || userRecovery.role !== "user" || precedingModel.role !== "model") {
            return;
          }
          precedingModel.parts = [
            ...precedingModel.parts ?? [],
            ...modelContinuation.parts ?? []
          ];
          this.history.splice(len - 2, 2);
        }
      }
    };
    __name(isSchemaDepthError, "isSchemaDepthError");
    __name(isInvalidArgumentError, "isInvalidArgumentError");
  }
});

// packages/core/dist/src/core/prompts.js
import path25 from "node:path";
import fs33 from "node:fs";
import os12 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 = os12.homedir();
      if (customPath === "~") {
        customPath = home;
      } else {
        customPath = path25.join(home, customPath.slice(2));
      }
    } catch (error40) {
      debugLogger25.warn(`Could not resolve home directory for path: ${trimmedEnvVar}`, error40);
      return { isSwitch: false, value: null, isDisabled: false };
    }
  }
  return {
    isSwitch: false,
    value: path25.resolve(customPath),
    isDisabled: false
  };
}
function getCustomSystemPrompt(customInstruction, userMemory, appendInstruction) {
  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 = buildSystemPromptSuffix(userMemory);
  return `${instructionText}${memorySuffix}${buildSystemPromptSuffix(appendInstruction)}`;
}
function buildSystemPromptSuffix(text) {
  const trimmed2 = text?.trim();
  return trimmed2 ? `

---

${trimmed2}` : "";
}
function getCoreSystemPrompt(userMemory, model, appendInstruction) {
  let systemMdEnabled = false;
  let systemMdPath = path25.resolve(path25.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 (!fs33.existsSync(systemMdPath)) {
      throw new Error(`missing system prompt file '${systemMdPath}'`);
    }
  }
  const basePrompt = systemMdEnabled ? fs33.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>

# Asking questions as you work

You have access to the ${ToolNames.ASK_USER_QUESTION} tool to ask the user questions when you need clarification, want to validate assumptions, or need to make a decision you're unsure about. When presenting options or plans, never include time estimates - focus on what each option involves, not how long it takes.

# 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. Use the ${ToolNames.ASK_USER_QUESTION} tool to ask questions, clarify and gather information as needed.
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.AGENT}' tool in order to reduce context usage. You should proactively use the '${ToolNames.AGENT}' tool with specialized agents when the task at hand matches the agent's description.
- **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.
`;
    }
  }()}

${getActionsSection()}

${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;
    fs33.mkdirSync(path25.dirname(writePath), { recursive: true });
    fs33.writeFileSync(writePath, basePrompt);
  }
  const memorySuffix = userMemory && userMemory.trim().length > 0 ? buildSystemPromptSuffix(userMemory) : "";
  const appendSuffix = buildSystemPromptSuffix(appendInstruction);
  return `${basePrompt}${memorySuffix}${appendSuffix}`;
}
function getActionsSection() {
  return `
# Executing actions with care

Carefully consider the reversibility and blast radius of actions. Generally you can freely take local, reversible actions like editing files or running tests. But for actions that are hard to reverse, affect shared systems beyond your local environment, or could otherwise be risky or destructive, check with the user before proceeding. The cost of pausing to confirm is low, while the cost of an unwanted action (lost work, unintended messages sent, deleted branches) can be very high. For actions like these, consider the context, the action, and user instructions, and by default transparently communicate the action and ask for confirmation before proceeding. This default can be changed by user instructions - if explicitly asked to operate more autonomously, then you may proceed without confirmation, but still attend to the risks and consequences when taking actions. A user approving an action (like a git push) once does NOT mean that they approve it in all contexts, so unless actions are authorized in advance in durable instructions like QWEN.md files, always confirm first. Authorization stands for the scope specified, not beyond. Match the scope of your actions to what was actually requested.

Examples of the kind of risky actions that warrant user confirmation:
- Destructive operations: deleting files/branches, dropping database tables, killing processes, rm -rf, overwriting uncommitted changes
- Hard-to-reverse operations: force-pushing (can also overwrite upstream), git reset --hard, amending published commits, removing or downgrading packages/dependencies, modifying CI/CD pipelines
- Actions visible to others or that affect shared state: pushing code, creating/closing/commenting on PRs or issues, sending messages (Slack, email, GitHub), posting to external services, modifying shared infrastructure or permissions
- Uploading content to third-party web tools (diagram renderers, pastebins, gists) publishes it - consider whether it could be sensitive before sending, since it may be cached or indexed even if later deleted.

When you encounter an obstacle, do not use destructive actions as a shortcut to simply make it go away. For instance, try to identify root causes and fix underlying issues rather than bypassing safety checks (e.g. --no-verify). If you discover unexpected state like unfamiliar files, branches, or configuration, investigate before deleting or overwriting, as it may represent the user's in-progress work. For example, typically resolve merge conflicts rather than discarding changes; similarly, if a lock file exists, investigate what process holds it rather than deleting it. In short: only take risky actions carefully, and when in doubt, ask before acting. Follow both the spirit and letter of these instructions - measure twice, cut once.`;
}
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:
        debugLogger25.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.AGENT} 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. Use ${ToolNames.ASK_USER_QUESTION} if you need to clarify approaches.
</system-reminder>`;
}
function getArenaSystemReminder(configFilePath2) {
  return `<system-reminder>An Arena session is active. For details, read: ${configFilePath2}. This message is for internal use only. Do not mention this to user in your response.</system-reminder>`;
}
function getInsightPrompt(type) {
  return INSIGHT_PROMPTS[type];
}
var debugLogger25, 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_const();
    init_debugLogger();
    debugLogger25 = createDebugLogger("PROMPTS");
    __name(resolvePathFromEnv, "resolvePathFromEnv");
    __name(getCustomSystemPrompt, "getCustomSystemPrompt");
    __name(buildSystemPromptSuffix, "buildSystemPromptSuffix");
    __name(getCoreSystemPrompt, "getCoreSystemPrompt");
    __name(getActionsSection, "getActionsSection");
    __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");
    __name(getArenaSystemReminder, "getArenaSystemReminder");
    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_node();
    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";
      GeminiEventType2["HookSystemMessage"] = "hook_system_message";
      GeminiEventType2["UserPromptSubmitBlocked"] = "user_prompt_submit_blocked";
      GeminiEventType2["StopHookLoop"] = "stop_hook_loop";
    })(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") {
              this.pendingToolCalls.length = 0;
              this.pendingCitations.clear();
              this.debugResponses = [];
              this.finishReason = void 0;
              yield {
                type: GeminiEventType.Retry,
                retryInfo: streamEvent.retryInfo,
                isContinuation: streamEvent.isContinuation
              };
              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 (finishReason === FinishReason.MAX_TOKENS) {
                for (const tc of this.pendingToolCalls) {
                  tc.wasOutputTruncated = true;
                }
              }
              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 error40 = toFriendlyError(e4);
          if (error40 instanceof UnauthorizedError) {
            throw error40;
          }
          const contextForReport = [...this.chat.getHistory(
            /*curated*/
            true
          ), req];
          await reportError2(error40, "Error when talking to API", contextForReport, "Turn.run-sendMessageStream");
          const status = typeof error40 === "object" && error40 !== null && "status" in error40 && typeof error40.status === "number" ? error40.status : void 0;
          const structuredError = {
            message: getErrorMessage(error40),
            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 name4 = fnCall.name || "undefined_tool_name";
        const args2 = fnCall.args || {};
        const toolCallRequest = {
          callId,
          name: name4,
          args: args2,
          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/hooks/types.js
function getHookKey(hook) {
  const name4 = hook.name ?? "";
  switch (hook.type) {
    case HookType.Command:
      return name4 ? `${name4}:${hook.command}` : hook.command;
    case HookType.Http:
      return name4 ? `${name4}:${hook.url}` : hook.url;
    case HookType.Function:
      return name4 ? `${name4}:${hook.id ?? "function"}` : hook.id ?? "function";
    default:
      return name4 || "unknown";
  }
}
function createHookOutput(eventName, data) {
  switch (eventName) {
    case HookEventName.PreToolUse:
      return new PreToolUseHookOutput(data);
    case HookEventName.PostToolUse:
      return new PostToolUseHookOutput(data);
    case HookEventName.PostToolUseFailure:
      return new PostToolUseFailureHookOutput(data);
    case HookEventName.Stop:
    case HookEventName.SubagentStop:
      return new StopHookOutput(data);
    case HookEventName.PermissionRequest:
      return new PermissionRequestHookOutput(data);
    default:
      return new DefaultHookOutput(data);
  }
}
var debugLogger26, HooksConfigSource, HookEventName, HOOKS_CONFIG_FIELDS, HookType, DefaultHookOutput, PreToolUseHookOutput, PostToolUseHookOutput, PostToolUseFailureHookOutput, StopHookOutput, PermissionRequestHookOutput, NotificationType, SessionStartSource, PermissionMode, SessionEndReason, PreCompactTrigger, PostCompactTrigger, AgentType;
var init_types6 = __esm({
  "packages/core/dist/src/hooks/types.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger26 = createDebugLogger("TRUSTED_HOOKS");
    (function(HooksConfigSource2) {
      HooksConfigSource2["Project"] = "project";
      HooksConfigSource2["User"] = "user";
      HooksConfigSource2["System"] = "system";
      HooksConfigSource2["Extensions"] = "extensions";
      HooksConfigSource2["Session"] = "session";
    })(HooksConfigSource || (HooksConfigSource = {}));
    (function(HookEventName2) {
      HookEventName2["PreToolUse"] = "PreToolUse";
      HookEventName2["PostToolUse"] = "PostToolUse";
      HookEventName2["PostToolUseFailure"] = "PostToolUseFailure";
      HookEventName2["Notification"] = "Notification";
      HookEventName2["UserPromptSubmit"] = "UserPromptSubmit";
      HookEventName2["SessionStart"] = "SessionStart";
      HookEventName2["Stop"] = "Stop";
      HookEventName2["SubagentStart"] = "SubagentStart";
      HookEventName2["SubagentStop"] = "SubagentStop";
      HookEventName2["PreCompact"] = "PreCompact";
      HookEventName2["PostCompact"] = "PostCompact";
      HookEventName2["SessionEnd"] = "SessionEnd";
      HookEventName2["PermissionRequest"] = "PermissionRequest";
      HookEventName2["StopFailure"] = "StopFailure";
    })(HookEventName || (HookEventName = {}));
    HOOKS_CONFIG_FIELDS = ["enabled", "disabled", "notifications"];
    (function(HookType2) {
      HookType2["Command"] = "command";
      HookType2["Http"] = "http";
      HookType2["Function"] = "function";
    })(HookType || (HookType = {}));
    __name(getHookKey, "getHookKey");
    __name(createHookOutput, "createHookOutput");
    DefaultHookOutput = class {
      static {
        __name(this, "DefaultHookOutput");
      }
      continue;
      stopReason;
      suppressOutput;
      systemMessage;
      decision;
      reason;
      hookSpecificOutput;
      constructor(data = {}) {
        this.continue = data.continue;
        this.stopReason = data.stopReason;
        this.suppressOutput = data.suppressOutput;
        this.systemMessage = data.systemMessage;
        this.decision = data.decision;
        this.reason = data.reason;
        this.hookSpecificOutput = data.hookSpecificOutput;
      }
      /**
       * Check if this output represents a blocking decision
       */
      isBlockingDecision() {
        return this.decision === "block" || this.decision === "deny";
      }
      /**
       * Check if this output requests to stop execution
       */
      shouldStopExecution() {
        return this.continue === false;
      }
      /**
       * Get the effective reason for blocking or stopping
       */
      getEffectiveReason() {
        return this.stopReason || this.reason || "No reason provided";
      }
      /**
       * Get sanitized additional context for adding to responses.
       */
      getAdditionalContext() {
        if (this.hookSpecificOutput && "additionalContext" in this.hookSpecificOutput) {
          const context2 = this.hookSpecificOutput["additionalContext"];
          if (typeof context2 !== "string") {
            return void 0;
          }
          return context2.replace(/</g, "&lt;").replace(/>/g, "&gt;");
        }
        return void 0;
      }
      /**
       * Check if execution should be blocked and return error info
       */
      getBlockingError() {
        if (this.isBlockingDecision()) {
          return {
            blocked: true,
            reason: this.getEffectiveReason()
          };
        }
        return { blocked: false, reason: "" };
      }
      /**
       * Check if context clearing was requested by hook.
       */
      shouldClearContext() {
        return false;
      }
    };
    PreToolUseHookOutput = class extends DefaultHookOutput {
      static {
        __name(this, "PreToolUseHookOutput");
      }
      /**
       * Get permission decision from hook output
       * @returns 'allow' | 'deny' | 'ask' | undefined
       */
      getPermissionDecision() {
        if (this.hookSpecificOutput && "permissionDecision" in this.hookSpecificOutput) {
          const decision = this.hookSpecificOutput["permissionDecision"];
          if (decision === "allow" || decision === "deny" || decision === "ask") {
            return decision;
          }
        }
        if (this.decision === "allow" || this.decision === "approve") {
          return "allow";
        }
        if (this.decision === "deny" || this.decision === "block") {
          return "deny";
        }
        if (this.decision === "ask") {
          return "ask";
        }
        return void 0;
      }
      /**
       * Get permission decision reason
       */
      getPermissionDecisionReason() {
        if (this.hookSpecificOutput && "permissionDecisionReason" in this.hookSpecificOutput) {
          const reason = this.hookSpecificOutput["permissionDecisionReason"];
          if (typeof reason === "string") {
            return reason;
          }
        }
        return this.reason;
      }
      /**
       * Check if permission was denied
       */
      isDenied() {
        return this.getPermissionDecision() === "deny";
      }
      /**
       * Check if user confirmation is required
       */
      isAsk() {
        return this.getPermissionDecision() === "ask";
      }
      /**
       * Check if permission was allowed
       */
      isAllowed() {
        return this.getPermissionDecision() === "allow";
      }
    };
    PostToolUseHookOutput = class extends DefaultHookOutput {
      static {
        __name(this, "PostToolUseHookOutput");
      }
      decision;
      reason;
      constructor(data = {}) {
        super(data);
        this.decision = data.decision ?? "allow";
        this.reason = data.reason ?? "No reason provided";
        if (data.decision === void 0) {
          debugLogger26.debug('PostToolUseHookOutput: No explicit decision set, defaulting to "allow"');
        }
        if (data.reason === void 0) {
          debugLogger26.debug('PostToolUseHookOutput: No explicit reason set, defaulting to "No reason provided"');
        }
      }
    };
    PostToolUseFailureHookOutput = class extends DefaultHookOutput {
      static {
        __name(this, "PostToolUseFailureHookOutput");
      }
      /**
       * Get additional context to provide error handling information
       */
      getAdditionalContext() {
        return super.getAdditionalContext();
      }
    };
    StopHookOutput = class extends DefaultHookOutput {
      static {
        __name(this, "StopHookOutput");
      }
      stopReason;
      constructor(data = {}) {
        super(data);
        this.stopReason = data.stopReason;
      }
      /**
       * Get the stop reason if provided
       */
      getStopReason() {
        if (!this.stopReason) {
          return void 0;
        }
        return `Stop hook feedback:
${this.stopReason}`;
      }
    };
    PermissionRequestHookOutput = class extends DefaultHookOutput {
      static {
        __name(this, "PermissionRequestHookOutput");
      }
      /**
       * Get the permission decision if provided by hook
       */
      getPermissionDecision() {
        if (this.hookSpecificOutput && "decision" in this.hookSpecificOutput) {
          const decision = this.hookSpecificOutput["decision"];
          if (typeof decision === "object" && decision !== null && !Array.isArray(decision)) {
            return decision;
          }
        }
        return void 0;
      }
      /**
       * Check if the permission was denied
       */
      isPermissionDenied() {
        const decision = this.getPermissionDecision();
        return decision?.behavior === "deny";
      }
      /**
       * Get the deny message if permission was denied
       */
      getDenyMessage() {
        const decision = this.getPermissionDecision();
        return decision?.message;
      }
      /**
       * Check if execution should be interrupted after denial
       */
      shouldInterrupt() {
        const decision = this.getPermissionDecision();
        return decision?.interrupt === true;
      }
      /**
       * Get updated tool input if permission was allowed with modifications
       */
      getUpdatedToolInput() {
        const decision = this.getPermissionDecision();
        return decision?.updatedInput;
      }
      /**
       * Get updated permissions if permission was allowed with permission updates
       */
      getUpdatedPermissions() {
        const decision = this.getPermissionDecision();
        return decision?.updatedPermissions;
      }
    };
    (function(NotificationType2) {
      NotificationType2["PermissionPrompt"] = "permission_prompt";
      NotificationType2["IdlePrompt"] = "idle_prompt";
      NotificationType2["AuthSuccess"] = "auth_success";
      NotificationType2["ElicitationDialog"] = "elicitation_dialog";
    })(NotificationType || (NotificationType = {}));
    (function(SessionStartSource2) {
      SessionStartSource2["Startup"] = "startup";
      SessionStartSource2["Resume"] = "resume";
      SessionStartSource2["Clear"] = "clear";
      SessionStartSource2["Compact"] = "compact";
    })(SessionStartSource || (SessionStartSource = {}));
    (function(PermissionMode2) {
      PermissionMode2["Default"] = "default";
      PermissionMode2["Plan"] = "plan";
      PermissionMode2["AutoEdit"] = "auto_edit";
      PermissionMode2["Yolo"] = "yolo";
    })(PermissionMode || (PermissionMode = {}));
    (function(SessionEndReason2) {
      SessionEndReason2["Clear"] = "clear";
      SessionEndReason2["Logout"] = "logout";
      SessionEndReason2["PromptInputExit"] = "prompt_input_exit";
      SessionEndReason2["Bypass_permissions_disabled"] = "bypass_permissions_disabled";
      SessionEndReason2["Other"] = "other";
    })(SessionEndReason || (SessionEndReason = {}));
    (function(PreCompactTrigger2) {
      PreCompactTrigger2["Manual"] = "manual";
      PreCompactTrigger2["Auto"] = "auto";
    })(PreCompactTrigger || (PreCompactTrigger = {}));
    (function(PostCompactTrigger2) {
      PostCompactTrigger2["Manual"] = "manual";
      PostCompactTrigger2["Auto"] = "auto";
    })(PostCompactTrigger || (PostCompactTrigger = {}));
    (function(AgentType2) {
      AgentType2["Bash"] = "Bash";
      AgentType2["Explorer"] = "Explorer";
      AgentType2["Plan"] = "Plan";
      AgentType2["Custom"] = "Custom";
    })(AgentType || (AgentType = {}));
  }
});

// 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 i4 = 0; i4 < contents.length; i4++) {
    const content = contents[i4];
    if (content.role === "user" && !content.parts?.some((part) => !!part.functionResponse)) {
      if (cumulativeCharCount >= targetCharCount) {
        return i4;
      }
      lastSplitPoint = i4;
    }
    cumulativeCharCount += charCounts[i4];
  }
  const lastContent = contents[contents.length - 1];
  if (lastContent?.role === "model" && !lastContent?.parts?.some((part) => part.functionCall)) {
    return contents.length;
  }
  if (lastContent?.role === "user" && lastContent?.parts?.some((part) => !!part.functionResponse)) {
    return contents.length;
  }
  return lastSplitPoint;
}
var COMPRESSION_TOKEN_THRESHOLD, COMPRESSION_PRESERVE_THRESHOLD, MIN_COMPRESSION_FRACTION, 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_types4();
    init_types6();
    COMPRESSION_TOKEN_THRESHOLD = 0.7;
    COMPRESSION_PRESERVE_THRESHOLD = 0.3;
    MIN_COMPRESSION_FRACTION = 0.05;
    __name(findCompressSplitPoint, "findCompressSplitPoint");
    ChatCompressionService = class {
      static {
        __name(this, "ChatCompressionService");
      }
      async compress(chat, promptId, force, model, config2, hasFailedCompressionAttempt, signal) {
        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 hookSystem = config2.getHookSystem();
        if (hookSystem) {
          const trigger = force ? PreCompactTrigger.Manual : PreCompactTrigger.Auto;
          try {
            await hookSystem.firePreCompactEvent(trigger, "", signal);
          } catch (err2) {
            config2.getDebugLogger().warn(`PreCompact hook failed: ${err2}`);
          }
        }
        const lastMessage = curatedHistory[curatedHistory.length - 1];
        const hasOrphanedFuncCall = force && lastMessage?.role === "model" && lastMessage.parts?.some((p2) => !!p2.functionCall);
        const historyForSplit = hasOrphanedFuncCall ? curatedHistory.slice(0, -1) : curatedHistory;
        const splitPoint = findCompressSplitPoint(historyForSplit, 1 - COMPRESSION_PRESERVE_THRESHOLD);
        const historyToCompress = historyForSplit.slice(0, splitPoint);
        const historyToKeep = historyForSplit.slice(splitPoint);
        if (historyToCompress.length === 0) {
          return {
            newHistory: null,
            info: {
              originalTokenCount,
              newTokenCount: originalTokenCount,
              compressionStatus: CompressionStatus.NOOP
            }
          };
        }
        const compressCharCount = historyToCompress.reduce((sum, c4) => sum + JSON.stringify(c4).length, 0);
        const totalCharCount = historyForSplit.reduce((sum, c4) => sum + JSON.stringify(c4).length, 0);
        if (totalCharCount > 0 && compressCharCount / totalCharCount < MIN_COMPRESSION_FRACTION) {
          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);
          try {
            const permissionMode = String(config2.getApprovalMode());
            await config2.getHookSystem()?.fireSessionStartEvent(SessionStartSource.Compact, model ?? "", permissionMode, void 0, signal);
          } catch (err2) {
            config2.getDebugLogger().warn(`SessionStart hook failed: ${err2}`);
          }
          try {
            const postCompactTrigger = force ? PostCompactTrigger.Manual : PostCompactTrigger.Auto;
            await config2.getHookSystem()?.firePostCompactEvent(postCompactTrigger, summary, signal);
          } catch (err2) {
            config2.getDebugLogger().warn(`PostCompact hook failed: ${err2}`);
          }
          return {
            newHistory: extraHistory,
            info: {
              originalTokenCount,
              newTokenCount,
              compressionStatus: CompressionStatus.COMPRESSED
            }
          };
        }
      }
    };
  }
});

// packages/core/dist/src/services/loopDetectionService.js
import { createHash as createHash2 } from "node:crypto";
var TOOL_CALL_LOOP_THRESHOLD, CONTENT_LOOP_THRESHOLD, CONTENT_CHUNK_SIZE, MAX_HISTORY_LENGTH, THOUGHT_REPEAT_THRESHOLD, MAX_THOUGHT_HISTORY, FILE_READ_THRESHOLD, FILE_READ_WINDOW, STAGNATION_THRESHOLD, LoopDetectionService;
var init_loopDetectionService = __esm({
  "packages/core/dist/src/services/loopDetectionService.js"() {
    "use strict";
    init_esbuild_shims();
    init_turn();
    init_loggers();
    init_types4();
    TOOL_CALL_LOOP_THRESHOLD = 5;
    CONTENT_LOOP_THRESHOLD = 10;
    CONTENT_CHUNK_SIZE = 50;
    MAX_HISTORY_LENGTH = 1e3;
    THOUGHT_REPEAT_THRESHOLD = 3;
    MAX_THOUGHT_HISTORY = 50;
    FILE_READ_THRESHOLD = 8;
    FILE_READ_WINDOW = 15;
    STAGNATION_THRESHOLD = 8;
    LoopDetectionService = class _LoopDetectionService {
      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;
      // Session-level disable flag
      disabledForSession = false;
      // Thought tracking
      thoughtHistory = [];
      // Tool call tracking (for read-file loop + stagnation detection)
      recentToolCalls = [];
      // Action stagnation tracking: consecutive calls to the same tool *name*
      // (regardless of args). Distinct from checkToolCallLoop, which requires
      // identical name AND args. This catches parameter-thrashing loops where
      // the model keeps calling one tool with varying arguments.
      sameNameStreak = 0;
      lastSeenToolName = null;
      // Cold-start gate for READ_FILE_LOOP: the opening exploration of a prompt
      // is almost always read-heavy (list + parallel reads). Until at least one
      // non-read-like tool fires, a window full of reads is treated as legitimate
      // exploration rather than loop evidence. Resets per-prompt in reset().
      hasSeenNonReadTool = false;
      // Loop type of the most recent firing. Bubbled up through the
      // LoopDetected event so callers (non-interactive CLI, telemetry) can tell
      // the user which detector actually fired.
      lastLoopType = null;
      constructor(config2) {
        this.config = config2;
      }
      /**
       * Returns the LoopType of the most recent detection, or null if no loop
       * has been detected in the current prompt.
       */
      getLastLoopType() {
        return this.lastLoopType;
      }
      /**
       * 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.thoughtHistory = [];
            const toolCallLoop = this.checkToolCallLoop(event.value);
            this.trackToolCall(event.value);
            const readFileLoop = this.checkReadFileLoop();
            const actionStagnation = this.checkActionStagnation();
            this.loopDetected = toolCallLoop || readFileLoop || actionStagnation;
            break;
          }
          case GeminiEventType.Content: {
            this.loopDetected = this.checkContentLoop(event.value);
            break;
          }
          case GeminiEventType.Thought: {
            this.trackThought(event.value);
            this.loopDetected = this.checkRepetitiveThoughts();
            break;
          }
          default:
            break;
        }
        return this.loopDetected;
      }
      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) {
          this.lastLoopType = LoopType.CONSECUTIVE_IDENTICAL_TOOL_CALLS;
          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)) {
            this.lastLoopType = LoopType.CHANTING_IDENTICAL_SENTENCES;
            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;
      }
      /**
       * Records a structured thought summary for repetition detection. Uses both
       * subject and description so two thoughts with the same subject but
       * diverging descriptions are correctly treated as distinct progress.
       */
      trackThought(summary) {
        const subject = summary.subject.trim().toLowerCase();
        const description = summary.description.trim().toLowerCase().substring(0, 200);
        const signature = `${subject}|${description}`;
        this.thoughtHistory.push(signature);
        if (this.thoughtHistory.length > MAX_THOUGHT_HISTORY) {
          this.thoughtHistory.shift();
        }
      }
      /**
       * Checks for repetitive thoughts pattern.
       *
       * Only fires when the last `THOUGHT_REPEAT_THRESHOLD` thoughts are the same
       * string. Earlier implementations counted repeats across the full retained
       * history, which caused false positives whenever the model revisited an
       * earlier phrase after making progress on an unrelated step.
       */
      checkRepetitiveThoughts() {
        if (this.thoughtHistory.length < THOUGHT_REPEAT_THRESHOLD) {
          return false;
        }
        const recentThoughts = this.thoughtHistory.slice(-THOUGHT_REPEAT_THRESHOLD);
        const firstThought = recentThoughts[0];
        if (recentThoughts.every((thought) => thought === firstThought)) {
          this.lastLoopType = LoopType.REPETITIVE_THOUGHTS;
          logLoopDetected(this.config, new LoopDetectedEvent(LoopType.REPETITIVE_THOUGHTS, this.promptId));
          return true;
        }
        return false;
      }
      // Exact tool names that read content from the filesystem. A plain substring
      // match on tokens like "view" or "list" is unsafe because unrelated tools
      // (e.g. "review", "checklist_update") can incidentally contain those
      // tokens and get miscounted as file reads.
      static READ_LIKE_TOOL_NAMES = /* @__PURE__ */ new Set([
        "read_file",
        "read_many_files",
        "list_directory"
      ]);
      // Prefix fallback for MCP-provided tools that follow the same naming
      // convention (e.g. `read_resource`, `list_projects`). The trailing
      // underscore anchors the match to a name segment so "review" and
      // "listener" are not treated as read-like.
      static READ_LIKE_NAME_PREFIXES = [
        "read_",
        "list_"
      ];
      isReadLikeTool(toolName) {
        if (_LoopDetectionService.READ_LIKE_TOOL_NAMES.has(toolName)) {
          return true;
        }
        return _LoopDetectionService.READ_LIKE_NAME_PREFIXES.some((prefix) => toolName.startsWith(prefix));
      }
      /**
       * Tracks tool calls for subsequent loop detection.
       */
      trackToolCall(toolCall) {
        this.recentToolCalls.push(toolCall);
        if (this.recentToolCalls.length > FILE_READ_WINDOW) {
          this.recentToolCalls.shift();
        }
        if (!this.hasSeenNonReadTool && !this.isReadLikeTool(toolCall.name)) {
          this.hasSeenNonReadTool = true;
        }
        if (this.lastSeenToolName === toolCall.name) {
          this.sameNameStreak++;
        } else {
          this.lastSeenToolName = toolCall.name;
          this.sameNameStreak = 1;
        }
      }
      /**
       * Checks for excessive file read operations without meaningful progress.
       */
      checkReadFileLoop() {
        if (!this.hasSeenNonReadTool) {
          return false;
        }
        if (this.recentToolCalls.length < FILE_READ_THRESHOLD) {
          return false;
        }
        const fileReadCount = this.recentToolCalls.filter((call) => this.isReadLikeTool(call.name)).length;
        if (fileReadCount >= FILE_READ_THRESHOLD) {
          this.lastLoopType = LoopType.READ_FILE_LOOP;
          logLoopDetected(this.config, new LoopDetectedEvent(LoopType.READ_FILE_LOOP, this.promptId));
          return true;
        }
        return false;
      }
      /**
       * Checks for action stagnation where the model performs different but equally unproductive actions.
       */
      checkActionStagnation() {
        if (this.sameNameStreak >= STAGNATION_THRESHOLD) {
          this.lastLoopType = LoopType.ACTION_STAGNATION;
          logLoopDetected(this.config, new LoopDetectedEvent(LoopType.ACTION_STAGNATION, this.promptId));
          return true;
        }
        return false;
      }
      /**
       * Resets all loop detection state.
       */
      reset(promptId) {
        this.promptId = promptId;
        this.resetToolCallCount();
        this.resetContentTracking();
        this.loopDetected = false;
        this.thoughtHistory = [];
        this.recentToolCalls = [];
        this.sameNameStreak = 0;
        this.lastSeenToolName = null;
        this.hasSeenNonReadTool = false;
        this.lastLoopType = null;
      }
      resetToolCallCount() {
        this.lastToolCallKey = null;
        this.toolCallRepetitionCount = 0;
      }
      resetContentTracking(resetHistory = true) {
        if (resetHistory) {
          this.streamContentHistory = "";
        }
        this.contentStats.clear();
        this.lastContentIndex = 0;
      }
    };
  }
});

// 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 env6 = options2.env ?? {};
  const settings = options2.settings ?? {};
  const enabled2 = argv.telemetry ?? parseBooleanEnvFlag(env6["QWEN_TELEMETRY_ENABLED"]) ?? settings.enabled;
  const rawTarget = argv.telemetryTarget ?? env6["QWEN_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 ?? env6["QWEN_TELEMETRY_OTLP_ENDPOINT"] ?? env6["OTEL_EXPORTER_OTLP_ENDPOINT"] ?? settings.otlpEndpoint;
  const rawProtocol = argv.telemetryOtlpProtocol ?? env6["QWEN_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(env6["QWEN_TELEMETRY_LOG_PROMPTS"]) ?? settings.logPrompts;
  const outfile = argv.telemetryOutfile ?? env6["QWEN_TELEMETRY_OUTFILE"] ?? settings.outfile;
  const useCollector = parseBooleanEnvFlag(env6["QWEN_TELEMETRY_USE_COLLECTOR"]) ?? settings.useCollector;
  return {
    enabled: enabled2,
    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_types4();
    init_types4();
    init_esm();
    init_esm2();
    init_uiTelemetry();
    init_metrics2();
    init_qwen_logger();
    init_sanitize();
    (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/agents/backends/types.js
var DISPLAY_MODE;
var init_types7 = __esm({
  "packages/core/dist/src/agents/backends/types.js"() {
    "use strict";
    init_esbuild_shims();
    DISPLAY_MODE = {
      IN_PROCESS: "in-process",
      TMUX: "tmux",
      ITERM2: "iterm2"
    };
  }
});

// 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_QUOTE = '"((\\\\"|[^"])*?)"';
    var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
    var hash = /^#$/;
    var SQ = "'";
    var DQ = '"';
    var DS = "$";
    var TOKEN = "";
    var mult = 4294967296;
    for (i4 = 0; i4 < 4; i4++) {
      TOKEN += (mult * Math.random()).toString(16);
    }
    var i4;
    var startsWithToken = new RegExp("^" + TOKEN);
    function matchAll2(s5, r5) {
      var origIndex = r5.lastIndex;
      var matches2 = [];
      var matchObj;
      while (matchObj = r5.exec(s5)) {
        matches2.push(matchObj);
        if (r5.lastIndex === matchObj.index) {
          r5.lastIndex += 1;
        }
      }
      r5.lastIndex = origIndex;
      return matches2;
    }
    __name(matchAll2, "matchAll");
    function getVar(env6, pre, key) {
      var r5 = typeof env6 === "function" ? env6(key) : env6[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, env6, opts) {
      if (!opts) {
        opts = {};
      }
      var BS = opts.escape || "\\";
      var BAREWORD = "(\\" + BS + `['"` + META2 + `]|[^\\s'"` + META2 + "])+";
      var chunker = new RegExp([
        "(" + CONTROL + ")",
        // control chars
        "(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"
      ].join("|"), "g");
      var matches2 = matchAll2(string4, chunker);
      if (matches2.length === 0) {
        return [];
      }
      if (!env6) {
        env6 = {};
      }
      var commented = false;
      return matches2.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 out2 = "";
        var isGlob = false;
        var i5;
        function parseEnvVar() {
          i5 += 1;
          var varend;
          var varname;
          var char = s5.charAt(i5);
          if (char === "{") {
            i5 += 1;
            if (s5.charAt(i5) === "}") {
              throw new Error("Bad substitution: " + s5.slice(i5 - 2, i5 + 1));
            }
            varend = s5.indexOf("}", i5);
            if (varend < 0) {
              throw new Error("Bad substitution: " + s5.slice(i5));
            }
            varname = s5.slice(i5, varend);
            i5 = varend;
          } else if (/[*@#?$!_-]/.test(char)) {
            varname = char;
            i5 += 1;
          } else {
            var slicedFromI = s5.slice(i5);
            varend = slicedFromI.match(/[^\w\d_]/);
            if (!varend) {
              varname = slicedFromI;
              i5 = s5.length;
            } else {
              varname = slicedFromI.slice(0, varend.index);
              i5 += varend.index - 1;
            }
          }
          return getVar(env6, "", varname);
        }
        __name(parseEnvVar, "parseEnvVar");
        for (i5 = 0; i5 < s5.length; i5++) {
          var c4 = s5.charAt(i5);
          isGlob = isGlob || !quote3 && (c4 === "*" || c4 === "?");
          if (esc2) {
            out2 += c4;
            esc2 = false;
          } else if (quote3) {
            if (c4 === quote3) {
              quote3 = false;
            } else if (quote3 == SQ) {
              out2 += c4;
            } else {
              if (c4 === BS) {
                i5 += 1;
                c4 = s5.charAt(i5);
                if (c4 === DQ || c4 === BS || c4 === DS) {
                  out2 += c4;
                } else {
                  out2 += BS + c4;
                }
              } else if (c4 === DS) {
                out2 += parseEnvVar();
              } else {
                out2 += 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 + i5 + 1) };
            if (out2.length) {
              return [out2, commentObj];
            }
            return [commentObj];
          } else if (c4 === BS) {
            esc2 = true;
          } else if (c4 === DS) {
            out2 += parseEnvVar();
          } else {
            out2 += c4;
          }
        }
        if (isGlob) {
          return { op: "glob", pattern: out2 };
        }
        return out2;
      }).reduce(function(prev, arg) {
        return typeof arg === "undefined" ? prev : prev.concat(arg);
      }, []);
    }
    __name(parseInternal, "parseInternal");
    module2.exports = /* @__PURE__ */ __name(function parse17(s5, env6, opts) {
      var mapped = parseInternal(s5, env6, opts);
      if (typeof env6 !== "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/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((name4) => SHELL_TOOL_NAMES.includes(name4))) {
    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 map3 = /* @__PURE__ */ new Map();
      const addAlias = /* @__PURE__ */ __name((set2, alias) => {
        if (!alias) {
          return;
        }
        set2.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);
          }
        }
        map3.set(canonicalName, aliases);
      }
      return map3;
    })();
    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");
  }
});

// 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(args2) {
  for (const arg of args2) {
    if (BLOCKED_GIT_REMOTE_ACTIONS.has(arg.toLowerCase())) {
      return false;
    }
  }
  return true;
}
function evaluateGitBranchArgs(args2) {
  for (const arg of args2) {
    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 args2 = tokens.slice(index + 1);
  if (subcommand === "remote") {
    return evaluateGitRemoteArgs(args2);
  }
  if (subcommand === "branch") {
    return evaluateGitBranchArgs(args2);
  }
  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: args2 } = 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, ...args2]);
  }
  if (normalizedRoot === "sed") {
    return evaluateSedCommand([normalizedRoot, ...args2]);
  }
  if (normalizedRoot === "awk") {
    return evaluateAwkCommand([normalizedRoot, ...args2]);
  }
  if (normalizedRoot === "git") {
    return evaluateGitCommand([normalizedRoot, ...args2]);
  }
  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 os13 from "node:os";
import path26 from "node:path";
import { execFile as execFile7, execFileSync as execFileSync2 } from "node:child_process";
import { accessSync, constants as fsConstants3 } from "node:fs";
function findGitBashPath() {
  if (cachedBashPath) {
    return cachedBashPath;
  }
  const pathEnv = process.env["PATH"] || "";
  const pathDirs = pathEnv.split(path26.delimiter).filter(Boolean);
  for (const dir of pathDirs) {
    const bashPath = path26.join(dir, "bash.exe");
    try {
      accessSync(bashPath, fsConstants3.X_OK);
      cachedBashPath = bashPath;
      return bashPath;
    } catch {
    }
  }
  const commonPaths = [
    path26.join("C:", "Program Files", "Git", "bin", "bash.exe"),
    path26.join("C:", "Program Files", "Git", "usr", "bin", "bash.exe"),
    path26.join("C:", "Program Files (x86)", "Git", "bin", "bash.exe"),
    path26.join("C:", "Program Files (x86)", "Git", "usr", "bin", "bash.exe"),
    path26.join(process.env["ProgramFiles"] || path26.join("C:", "Program Files"), "Git", "bin", "bash.exe"),
    path26.join(process.env["ProgramFiles(x86)"] || path26.join("C:", "Program Files (x86)"), "Git", "bin", "bash.exe")
  ];
  for (const bashPath of commonPaths) {
    try {
      accessSync(bashPath, fsConstants3.X_OK);
      cachedBashPath = bashPath;
      return bashPath;
    } catch {
    }
  }
  cachedBashPath = "bash";
  return "bash";
}
function getShellConfiguration() {
  if (isWindows()) {
    const msystem = process.env["MSYSTEM"];
    const term = process.env["TERM"] || "";
    const isGitBash = msystem?.startsWith("MINGW") || msystem?.startsWith("MSYS") || term.includes("msys") || term.includes("cygwin");
    if (isGitBash) {
      return {
        executable: findGitBashPath(),
        argsPrefix: ["-c"],
        shell: "bash"
      };
    }
    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 i4 = 0;
  const previousNonWhitespaceChar = /* @__PURE__ */ __name((index) => {
    for (let j2 = index - 1; j2 >= 0; j2--) {
      const ch = command2[j2];
      if (ch && !/\s/.test(ch)) {
        return ch;
      }
    }
    return void 0;
  }, "previousNonWhitespaceChar");
  while (i4 < command2.length) {
    const char = command2[i4];
    const nextChar = command2[i4 + 1];
    if (!inSingleQuotes && char === "\\" && nextChar === "\n") {
      i4 += 2;
      continue;
    }
    if (char === "\\" && i4 < command2.length - 1) {
      currentCommand += char + command2[i4 + 1];
      i4 += 2;
      continue;
    }
    if (char === "'" && !inDoubleQuotes) {
      inSingleQuotes = !inSingleQuotes;
    } else if (char === '"' && !inSingleQuotes) {
      inDoubleQuotes = !inDoubleQuotes;
    }
    if (!inSingleQuotes && !inDoubleQuotes) {
      if (char === "&" && nextChar === "&" || char === "|" && (nextChar === "|" || nextChar === "&")) {
        commands.push(currentCommand.trim());
        currentCommand = "";
        i4++;
      } else if (char === ";") {
        commands.push(currentCommand.trim());
        currentCommand = "";
      } else if (char === "&") {
        const prevChar = previousNonWhitespaceChar(i4);
        if (prevChar === ">" || prevChar === "<") {
          currentCommand += char;
        } else {
          commands.push(currentCommand.trim());
          currentCommand = "";
        }
      } else if (char === "|") {
        const prevChar = previousNonWhitespaceChar(i4);
        if (prevChar === ">") {
          currentCommand += char;
        } else {
          commands.push(currentCommand.trim());
          currentCommand = "";
        }
      } else if (char === "\r" && nextChar === "\n") {
        commands.push(currentCommand.trim());
        currentCommand = "";
        i4++;
      } else if (char === "\n") {
        commands.push(currentCommand.trim());
        currentCommand = "";
      } else {
        currentCommand += char;
      }
    } else {
      currentCommand += char;
    }
    i4++;
  }
  if (currentCommand.trim()) {
    commands.push(currentCommand.trim());
  }
  return commands.filter(Boolean);
}
function getCommandRoot(command2) {
  const trimmedCommand = command2.trim();
  if (!trimmedCommand) {
    return void 0;
  }
  try {
    const tokens = (0, import_shell_quote2.parse)(trimmedCommand).filter((token2) => typeof token2 === "string");
    let idx = 0;
    while (idx < tokens.length && ENV_ASSIGNMENT_REGEX2.test(tokens[idx])) {
      idx++;
    }
    const firstToken = tokens[idx];
    return firstToken ? firstToken.split(/[\\/]/).pop() : void 0;
  } catch {
    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 i5 = startIndex + 2;
    const stripLeadingTabs = command2[i5] === "-";
    if (stripLeadingTabs)
      i5++;
    while (i5 < command2.length && (command2[i5] === " " || command2[i5] === "	")) {
      i5++;
    }
    let delimiter2 = "";
    let isQuotedDelimiter = false;
    let inSingleQuotes2 = false;
    let inDoubleQuotes2 = false;
    while (i5 < command2.length) {
      const char = command2[i5];
      if (!inSingleQuotes2 && !inDoubleQuotes2 && isWordBoundary(char)) {
        break;
      }
      if (!inSingleQuotes2 && !inDoubleQuotes2) {
        if (char === "'") {
          isQuotedDelimiter = true;
          inSingleQuotes2 = true;
          i5++;
          continue;
        }
        if (char === '"') {
          isQuotedDelimiter = true;
          inDoubleQuotes2 = true;
          i5++;
          continue;
        }
        if (char === "\\") {
          isQuotedDelimiter = true;
          i5++;
          if (i5 >= command2.length)
            break;
          delimiter2 += command2[i5];
          i5++;
          continue;
        }
        delimiter2 += char;
        i5++;
        continue;
      }
      if (inSingleQuotes2) {
        if (char === "'") {
          inSingleQuotes2 = false;
          i5++;
          continue;
        }
        delimiter2 += char;
        i5++;
        continue;
      }
      if (char === '"') {
        inDoubleQuotes2 = false;
        i5++;
        continue;
      }
      if (char === "\\") {
        isQuotedDelimiter = true;
        i5++;
        if (i5 >= command2.length)
          break;
        delimiter2 += command2[i5];
        i5++;
        continue;
      }
      delimiter2 += char;
      i5++;
    }
    if (delimiter2.length === 0) {
      return null;
    }
    return {
      nextIndex: i5,
      heredoc: {
        delimiter: delimiter2,
        isQuotedDelimiter,
        stripLeadingTabs
      }
    };
  }, "parseHeredocOperator");
  const lineHasCommandSubstitution = /* @__PURE__ */ __name((line) => {
    for (let i5 = 0; i5 < line.length; i5++) {
      const char = line[i5];
      const nextChar = line[i5 + 1];
      if (char === "\\") {
        i5++;
        continue;
      }
      if (char === "$" && nextChar === "(") {
        return true;
      }
      if (char === "`") {
        return true;
      }
    }
    return false;
  }, "lineHasCommandSubstitution");
  const consumeHeredocBodies = /* @__PURE__ */ __name((startIndex, pending) => {
    let i5 = startIndex;
    for (const heredoc of pending) {
      let pendingDollarLineContinuation = false;
      while (i5 <= command2.length) {
        const lineStart = i5;
        while (i5 < command2.length && command2[i5] !== "\n" && command2[i5] !== "\r") {
          i5++;
        }
        const lineEnd = i5;
        let newlineLength = 0;
        if (i5 < command2.length && command2[i5] === "\r" && command2[i5 + 1] === "\n") {
          newlineLength = 2;
        } else if (i5 < command2.length && (command2[i5] === "\n" || command2[i5] === "\r")) {
          newlineLength = 1;
        }
        const rawLine = command2.slice(lineStart, lineEnd);
        const effectiveLine = heredoc.stripLeadingTabs ? rawLine.replace(/^\t+/, "") : rawLine;
        if (effectiveLine === heredoc.delimiter) {
          i5 = lineEnd + newlineLength;
          break;
        }
        if (!heredoc.isQuotedDelimiter) {
          if (pendingDollarLineContinuation && effectiveLine.startsWith("(")) {
            return { nextIndex: i5, hasSubstitution: true };
          }
          if (lineHasCommandSubstitution(effectiveLine)) {
            return { nextIndex: i5, 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;
          }
        }
        i5 = lineEnd + newlineLength;
        if (newlineLength === 0) {
          break;
        }
      }
    }
    return { nextIndex: i5, hasSubstitution: false };
  }, "consumeHeredocBodies");
  let inSingleQuotes = false;
  let inDoubleQuotes = false;
  let inBackticks = false;
  let inComment = false;
  const pendingHeredocs = [];
  let i4 = 0;
  while (i4 < command2.length) {
    const char = command2[i4];
    const nextChar = command2[i4 + 1];
    if (!inSingleQuotes && !inDoubleQuotes && !inBackticks) {
      if (char === "\r" && nextChar === "\n") {
        inComment = false;
        if (pendingHeredocs.length > 0) {
          const result = consumeHeredocBodies(i4 + 2, pendingHeredocs);
          if (result.hasSubstitution)
            return true;
          pendingHeredocs.length = 0;
          i4 = result.nextIndex;
          continue;
        }
      } else if (char === "\n" || char === "\r") {
        inComment = false;
        if (pendingHeredocs.length > 0) {
          const result = consumeHeredocBodies(i4 + 1, pendingHeredocs);
          if (result.hasSubstitution)
            return true;
          pendingHeredocs.length = 0;
          i4 = result.nextIndex;
          continue;
        }
      }
    }
    if (!inSingleQuotes && !inDoubleQuotes && !inBackticks) {
      if (!inComment && isCommentStart(i4)) {
        inComment = true;
        i4++;
        continue;
      }
      if (inComment) {
        i4++;
        continue;
      }
    }
    if (char === "\\" && !inSingleQuotes) {
      i4 += 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(i4);
      if (parsed) {
        pendingHeredocs.push(parsed.heredoc);
        i4 = 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;
      }
    }
    i4++;
  }
  return false;
}
async 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 normalize13 = /* @__PURE__ */ __name((cmd) => cmd.trim().replace(/\s+/g, " "), "normalize");
  const commandsToValidate = splitCommands(command2).map(normalize13);
  const invocation = {
    params: { command: "" }
  };
  const pm = config2.getPermissionManager?.();
  if (pm) {
    const disallowedCommands2 = [];
    for (const cmd of commandsToValidate) {
      if (sessionAllowlist) {
        invocation.params["command"] = cmd;
        const isSessionAllowed = doesToolInvocationMatch("run_shell_command", invocation, [...sessionAllowlist].flatMap((c4) => SHELL_TOOL_NAMES2.map((name4) => `${name4}(${c4})`)));
        if (isSessionAllowed)
          continue;
      }
      const decision = await pm.isCommandAllowed(cmd);
      if (decision === "deny") {
        return {
          allAllowed: false,
          disallowedCommands: [cmd],
          blockReason: `Command '${cmd}' is blocked by permission rules`,
          isHardDenial: true
        };
      }
      if (decision === "allow")
        continue;
      if (decision === "ask") {
        disallowedCommands2.push(cmd);
        continue;
      }
      if (sessionAllowlist !== void 0) {
        disallowedCommands2.push(cmd);
      }
    }
    if (disallowedCommands2.length > 0) {
      return {
        allAllowed: false,
        disallowedCommands: disallowedCommands2,
        blockReason: `Command(s) require confirmation. Disallowed commands: ${disallowedCommands2.map((c4) => JSON.stringify(c4)).join(", ")}`,
        isHardDenial: false
      };
    }
    return { allAllowed: true, disallowedCommands: [] };
  }
  const excludeTools = config2.getPermissionsDeny() || [];
  const isWildcardBlocked = SHELL_TOOL_NAMES2.some((name4) => excludeTools.includes(name4));
  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((name4) => coreTools.includes(name4));
  if (isWildcardAllowed) {
    return { allAllowed: true, disallowedCommands: [] };
  }
  const disallowedCommands = [];
  if (sessionAllowlist) {
    const normalizedSessionAllowlist = new Set([...sessionAllowlist].flatMap((cmd) => SHELL_TOOL_NAMES2.map((name4) => `${name4}(${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((name4) => tool.startsWith(`${name4}(`))).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 execCommand2(command2, args2, options2 = {}) {
  return new Promise((resolve42, reject) => {
    const child = execFile7(command2, args2, { encoding: "utf8", ...options2 }, (error40, stdout2, stderr) => {
      if (error40) {
        if (!options2.preserveOutputOnError) {
          reject(error40);
        } else {
          resolve42({
            stdout: String(stdout2 ?? ""),
            stderr: String(stderr ?? ""),
            code: typeof error40.code === "number" ? error40.code : 1
          });
        }
        return;
      }
      resolve42({
        stdout: String(stdout2 ?? ""),
        stderr: String(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 (error40) {
    return {
      path: null,
      error: error40 instanceof Error ? error40 : new Error(String(error40))
    };
  }
}
function isCommandAvailable(command2) {
  const { path: path150, error: error40 } = resolveCommandPath(command2);
  return { available: path150 !== null, error: error40 };
}
async function isCommandAllowed(command2, config2) {
  const { allAllowed, blockReason } = await 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."
  };
}
function checkArgumentSafety(args2) {
  const dangerousPatterns = [];
  if (args2.includes("$("))
    dangerousPatterns.push("$() command substitution");
  if (args2.includes("`"))
    dangerousPatterns.push("backtick command substitution");
  if (args2.includes("<("))
    dangerousPatterns.push("<() process substitution");
  if (args2.includes(">("))
    dangerousPatterns.push(">() process substitution");
  if (args2.includes(";"))
    dangerousPatterns.push("; command separator");
  if (args2.includes("|"))
    dangerousPatterns.push("| pipe");
  if (args2.includes("&&"))
    dangerousPatterns.push("&& AND operator");
  if (args2.includes("||"))
    dangerousPatterns.push("|| OR operator");
  if (args2.includes(" &") || args2.includes("& "))
    dangerousPatterns.push("& background operator");
  if (args2.includes(">") || args2.includes("<")) {
    if (/>\s|\d>/.test(args2))
      dangerousPatterns.push("> output redirection");
    if (/<\s|\d</.test(args2))
      dangerousPatterns.push("< input redirection");
  }
  return {
    isSafe: dangerousPatterns.length === 0,
    dangerousPatterns
  };
}
function shouldDefaultToNodePty() {
  if (os13.platform() !== "win32")
    return true;
  const build = parseInt(os13.release().split(".")[2] ?? "", 10);
  return !isNaN(build) && build >= CONPTY_MIN_WINDOWS_BUILD;
}
var import_shell_quote2, SHELL_TOOL_NAMES2, cachedBashPath, ENV_ASSIGNMENT_REGEX2, isWindows, CONPTY_MIN_WINDOWS_BUILD;
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"];
    ENV_ASSIGNMENT_REGEX2 = /^[A-Za-z_][A-Za-z0-9_]*=/;
    __name(findGitBashPath, "findGitBashPath");
    __name(getShellConfiguration, "getShellConfiguration");
    isWindows = /* @__PURE__ */ __name(() => os13.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(execCommand2, "execCommand");
    __name(resolveCommandPath, "resolveCommandPath");
    __name(isCommandAvailable, "isCommandAvailable");
    __name(isCommandAllowed, "isCommandAllowed");
    __name(isCommandNeedsPermission, "isCommandNeedsPermission");
    __name(checkArgumentSafety, "checkArgumentSafety");
    CONPTY_MIN_WINDOWS_BUILD = 19042;
    __name(shouldDefaultToNodePty, "shouldDefaultToNodePty");
  }
});

// packages/core/dist/src/agents/backends/tmux-commands.js
async function tmuxResult(args2, serverName) {
  const fullArgs = serverName ? ["-L", serverName, ...args2] : args2;
  debugLogger27.info(`tmux ${fullArgs.join(" ")}`);
  const result = await execCommand2("tmux", fullArgs, {
    preserveOutputOnError: true
  });
  if (result.code !== 0 && result.stderr.trim()) {
    debugLogger27.error(`tmux error: ${result.stderr.trim()}`);
  }
  return result;
}
async function tmux(args2, serverName) {
  const result = await tmuxResult(args2, serverName);
  if (result.code !== 0) {
    throw new Error(`tmux ${args2[0]} failed (exit ${result.code}): ${result.stderr.trim() || result.stdout.trim()}`);
  }
  return result.stdout;
}
function parseVersion(versionStr) {
  const match2 = versionStr.match(/(\d+)\.(\d+)/);
  if (!match2)
    return [0, 0];
  return [parseInt(match2[1], 10), parseInt(match2[2], 10)];
}
function isVersionAtLeast(current, minimum) {
  const [curMajor = 0, curMinor = 0] = parseVersion(current);
  const [minMajor = 0, minMinor = 0] = parseVersion(minimum);
  if (curMajor !== minMajor)
    return curMajor > minMajor;
  return curMinor >= minMinor;
}
function isTmuxAvailable() {
  return isCommandAvailable("tmux").available;
}
async function tmuxVersion() {
  const output = await tmux(["-V"]);
  return output.trim();
}
async function verifyTmux() {
  if (!isTmuxAvailable()) {
    throw new Error("tmux is not installed. Install tmux (version 3.0+) for split-pane mode.");
  }
  const version2 = await tmuxVersion();
  if (!isVersionAtLeast(version2, MIN_TMUX_VERSION)) {
    throw new Error(`tmux version ${MIN_TMUX_VERSION}+ required for split-pane mode (found: ${version2}).`);
  }
}
async function tmuxCurrentPaneId() {
  const output = await tmux(["display-message", "-p", "#{pane_id}"]);
  return output.trim();
}
async function tmuxCurrentWindowTarget() {
  const output = await tmux([
    "display-message",
    "-p",
    "#{session_name}:#{window_index}"
  ]);
  return output.trim();
}
async function tmuxHasSession(name4, serverName) {
  const result = await tmuxResult(["has-session", "-t", name4], serverName);
  return result.code === 0;
}
async function tmuxListWindows(sessionName, serverName) {
  const output = await tmux(["list-windows", "-t", sessionName, "-F", "#{window_name} #{window_id}"], serverName);
  const windows = [];
  for (const line of output.trim().split("\n")) {
    if (!line.trim())
      continue;
    const [name4, id] = line.trim().split(/\s+/, 2);
    if (!name4 || !id)
      continue;
    windows.push({ name: name4, id });
  }
  return windows;
}
async function tmuxHasWindow(sessionName, windowName, serverName) {
  const windows = await tmuxListWindows(sessionName, serverName);
  return windows.some((w2) => w2.name === windowName);
}
async function tmuxNewSession(name4, opts, serverName) {
  const args2 = ["new-session", "-d", "-s", name4];
  if (opts?.windowName)
    args2.push("-n", opts.windowName);
  if (opts?.cols)
    args2.push("-x", String(opts.cols));
  if (opts?.rows)
    args2.push("-y", String(opts.rows));
  await tmux(args2, serverName);
}
async function tmuxNewWindow(targetSession, windowName, serverName) {
  await tmux(["new-window", "-t", `${targetSession}:`, "-n", windowName], serverName);
}
async function tmuxSplitWindow(target, opts, serverName) {
  const args2 = ["split-window", "-t", target];
  if (opts?.horizontal) {
    args2.push("-h");
  }
  if (opts?.percent !== void 0) {
    args2.push("-l", `${opts.percent}%`);
  }
  args2.push("-P", "-F", "#{pane_id}");
  if (opts?.command) {
    args2.push(opts.command);
  }
  const output = await tmux(args2, serverName);
  return output.trim();
}
async function tmuxSendKeys(paneId, keys, opts, serverName) {
  const args2 = ["send-keys", "-t", paneId];
  if (opts?.literal) {
    args2.push("-l");
  }
  args2.push(keys);
  if (opts?.enter) {
    args2.push("Enter");
  }
  await tmux(args2, serverName);
}
async function tmuxSelectPane(paneId, serverName) {
  await tmux(["select-pane", "-t", paneId], serverName);
}
async function tmuxSelectPaneTitle(paneId, title, serverName) {
  await tmux(["select-pane", "-t", paneId, "-T", title], serverName);
}
async function tmuxSelectPaneStyle(paneId, style, serverName) {
  await tmux(["select-pane", "-t", paneId, "-P", style], serverName);
}
async function tmuxSelectLayout(target, layout, serverName) {
  await tmux(["select-layout", "-t", target, layout], serverName);
}
async function tmuxListPanes(target, serverName) {
  const output = await tmux([
    "list-panes",
    "-t",
    target,
    "-F",
    "#{pane_id} #{pane_dead} #{pane_dead_status}"
  ], serverName);
  return parseTmuxListPanes(output);
}
function parseTmuxListPanes(output) {
  const panes = [];
  for (const line of output.trim().split("\n")) {
    if (!line.trim())
      continue;
    const parts2 = line.trim().split(/\s+/);
    if (parts2.length < 2)
      continue;
    panes.push({
      paneId: parts2[0],
      dead: parts2[1] === "1",
      deadStatus: parts2[2] ? parseInt(parts2[2], 10) : 0
    });
  }
  return panes;
}
async function tmuxSetOption(target, option2, value, serverName) {
  await tmux(["set-option", "-t", target, option2, value], serverName);
}
async function tmuxRespawnPane(paneId, command2, serverName) {
  await tmux(["respawn-pane", "-k", "-t", paneId, command2], serverName);
}
async function tmuxKillPane(paneId, serverName) {
  await tmux(["kill-pane", "-t", paneId], serverName);
}
async function tmuxResizePane(paneId, opts, serverName) {
  const args2 = ["resize-pane", "-t", paneId];
  if (opts.height !== void 0) {
    args2.push("-y", String(opts.height));
  }
  if (opts.width !== void 0) {
    args2.push("-x", String(opts.width));
  }
  await tmux(args2, serverName);
}
async function tmuxKillSession(name4, serverName) {
  await tmux(["kill-session", "-t", name4], serverName);
}
async function tmuxGetFirstPaneId(target, serverName) {
  const output = await tmux(["list-panes", "-t", target, "-F", "#{pane_id}"], serverName);
  const firstLine = output.trim().split("\n")[0];
  if (!firstLine) {
    throw new Error(`No panes found in target: ${target}`);
  }
  return firstLine.trim();
}
var debugLogger27, MIN_TMUX_VERSION;
var init_tmux_commands = __esm({
  "packages/core/dist/src/agents/backends/tmux-commands.js"() {
    "use strict";
    init_esbuild_shims();
    init_shell_utils();
    init_debugLogger();
    debugLogger27 = createDebugLogger("TMUX_CMD");
    MIN_TMUX_VERSION = "3.0";
    __name(tmuxResult, "tmuxResult");
    __name(tmux, "tmux");
    __name(parseVersion, "parseVersion");
    __name(isVersionAtLeast, "isVersionAtLeast");
    __name(isTmuxAvailable, "isTmuxAvailable");
    __name(tmuxVersion, "tmuxVersion");
    __name(verifyTmux, "verifyTmux");
    __name(tmuxCurrentPaneId, "tmuxCurrentPaneId");
    __name(tmuxCurrentWindowTarget, "tmuxCurrentWindowTarget");
    __name(tmuxHasSession, "tmuxHasSession");
    __name(tmuxListWindows, "tmuxListWindows");
    __name(tmuxHasWindow, "tmuxHasWindow");
    __name(tmuxNewSession, "tmuxNewSession");
    __name(tmuxNewWindow, "tmuxNewWindow");
    __name(tmuxSplitWindow, "tmuxSplitWindow");
    __name(tmuxSendKeys, "tmuxSendKeys");
    __name(tmuxSelectPane, "tmuxSelectPane");
    __name(tmuxSelectPaneTitle, "tmuxSelectPaneTitle");
    __name(tmuxSelectPaneStyle, "tmuxSelectPaneStyle");
    __name(tmuxSelectLayout, "tmuxSelectLayout");
    __name(tmuxListPanes, "tmuxListPanes");
    __name(parseTmuxListPanes, "parseTmuxListPanes");
    __name(tmuxSetOption, "tmuxSetOption");
    __name(tmuxRespawnPane, "tmuxRespawnPane");
    __name(tmuxKillPane, "tmuxKillPane");
    __name(tmuxResizePane, "tmuxResizePane");
    __name(tmuxKillSession, "tmuxKillSession");
    __name(tmuxGetFirstPaneId, "tmuxGetFirstPaneId");
  }
});

// packages/core/dist/src/agents/backends/TmuxBackend.js
function shellQuote(value) {
  return `'${value.replace(/'/g, "'\\''")}'`;
}
var debugLogger28, EXIT_POLL_INTERVAL_MS, TMUX_SERVER_PREFIX, DEFAULT_TMUX_SESSION, DEFAULT_TMUX_WINDOW, DEFAULT_LEADER_WIDTH_PERCENT, DEFAULT_FIRST_SPLIT_PERCENT, DEFAULT_PANE_BORDER_FORMAT, INTERNAL_LAYOUT_SETTLE_MS, EXTERNAL_LAYOUT_SETTLE_MS, TmuxBackend;
var init_TmuxBackend = __esm({
  "packages/core/dist/src/agents/backends/TmuxBackend.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_types7();
    init_tmux_commands();
    debugLogger28 = createDebugLogger("TMUX_BACKEND");
    EXIT_POLL_INTERVAL_MS = 500;
    TMUX_SERVER_PREFIX = "arena-server";
    DEFAULT_TMUX_SESSION = "arena-view";
    DEFAULT_TMUX_WINDOW = "arena-view";
    DEFAULT_LEADER_WIDTH_PERCENT = 30;
    DEFAULT_FIRST_SPLIT_PERCENT = 70;
    DEFAULT_PANE_BORDER_FORMAT = "#{pane_title}";
    INTERNAL_LAYOUT_SETTLE_MS = 200;
    EXTERNAL_LAYOUT_SETTLE_MS = 120;
    TmuxBackend = class {
      static {
        __name(this, "TmuxBackend");
      }
      type = DISPLAY_MODE.TMUX;
      /** The pane ID where the main process runs (left side) */
      mainPaneId = "";
      /** Window target (session:window) */
      windowTarget = "";
      /** Whether we are running inside tmux */
      insideTmux = false;
      /** External tmux server name (when outside tmux) */
      serverName = null;
      /** External tmux session name (when outside tmux) */
      sessionName = null;
      /** External tmux window name (when outside tmux) */
      windowName = null;
      panes = /* @__PURE__ */ new Map();
      agentOrder = [];
      activeAgentId = null;
      onExitCallback = null;
      exitPollTimer = null;
      initialized = false;
      /** Whether cleanup() has been called */
      cleanedUp = false;
      /** Number of agents currently being spawned asynchronously */
      pendingSpawns = 0;
      /** Queue to serialize spawn operations (prevents race conditions) */
      spawnQueue = Promise.resolve();
      async init() {
        if (this.initialized)
          return;
        await verifyTmux();
        this.insideTmux = Boolean(process.env["TMUX"]);
        if (this.insideTmux) {
          this.mainPaneId = await tmuxCurrentPaneId();
          this.windowTarget = await tmuxCurrentWindowTarget();
          debugLogger28.info(`Initialized inside tmux: pane ${this.mainPaneId}, window ${this.windowTarget}`);
        } else {
          debugLogger28.info("Initialized outside tmux; will use external tmux server");
        }
        this.initialized = true;
      }
      // ─── Agent Lifecycle ────────────────────────────────────────
      async spawnAgent(config2) {
        if (!this.initialized) {
          throw new Error("TmuxBackend not initialized. Call init() first.");
        }
        if (this.panes.has(config2.agentId)) {
          throw new Error(`Agent "${config2.agentId}" already exists.`);
        }
        const cmd = this.buildShellCommand(config2);
        this.pendingSpawns++;
        const spawnPromise = this.spawnQueue.then(() => this.spawnAgentAsync(config2, cmd));
        this.spawnQueue = spawnPromise;
        await spawnPromise;
      }
      async spawnAgentAsync(config2, cmd) {
        const { agentId } = config2;
        const options2 = this.resolveTmuxOptions(config2);
        debugLogger28.info(`[spawnAgentAsync] Starting spawn for agent "${agentId}", mainPane="${this.mainPaneId}", currentPanesCount=${this.panes.size}`);
        try {
          let paneId = "";
          if (this.insideTmux) {
            paneId = await this.spawnInsideTmux(cmd, options2);
          } else {
            paneId = await this.spawnOutsideTmux(config2, cmd, options2);
          }
          const serverName = this.getServerName();
          await tmuxSetOption(paneId, "remain-on-exit", "on", serverName);
          await this.applyPaneDecorations(paneId, options2, serverName);
          if (this.insideTmux) {
            await this.applyInsideLayout(options2);
            await this.sleep(INTERNAL_LAYOUT_SETTLE_MS);
            await tmuxSelectPane(this.mainPaneId);
            this.triggerMainProcessRedraw();
          } else {
            await this.applyExternalLayout(serverName);
            await this.sleep(EXTERNAL_LAYOUT_SETTLE_MS);
          }
          const agentPane = {
            agentId,
            paneId,
            status: "running",
            exitCode: 0
          };
          this.panes.set(agentId, agentPane);
          this.agentOrder.push(agentId);
          if (this.activeAgentId === null) {
            this.activeAgentId = agentId;
          }
          this.startExitPolling();
          debugLogger28.info(`[spawnAgentAsync] Spawned agent "${agentId}" in pane ${paneId} \u2014 SUCCESS`);
        } catch (error40) {
          debugLogger28.error(`[spawnAgentAsync] Failed to spawn agent "${agentId}":`, error40);
          this.panes.set(agentId, {
            agentId,
            paneId: "",
            status: "exited",
            exitCode: 1
          });
          this.agentOrder.push(agentId);
          this.onExitCallback?.(agentId, 1, null);
        } finally {
          this.pendingSpawns--;
        }
      }
      /**
       * Trigger terminal redraw in main process after pane layout changes.
       * Uses multiple methods to ensure Ink picks up the new terminal size.
       */
      triggerMainProcessRedraw() {
        if (!this.insideTmux)
          return;
        setTimeout(() => {
          try {
            if (process.stdout.isTTY) {
              process.stdout.emit("resize");
              debugLogger28.info("[triggerMainProcessRedraw] Emitted stdout resize event");
            }
            process.kill(process.pid, "SIGWINCH");
            debugLogger28.info("[triggerMainProcessRedraw] Sent SIGWINCH");
          } catch (error40) {
            debugLogger28.info(`[triggerMainProcessRedraw] Failed: ${error40}`);
          }
        }, 100);
      }
      stopAgent(agentId) {
        const pane = this.panes.get(agentId);
        if (!pane || pane.status !== "running")
          return;
        if (pane.paneId) {
          void tmuxKillPane(pane.paneId, this.getServerName());
        }
        pane.status = "exited";
        debugLogger28.info(`Killed pane for agent "${agentId}"`);
      }
      stopAll() {
        for (const [agentId, pane] of this.panes.entries()) {
          if (pane.status === "running") {
            if (pane.paneId) {
              void tmuxKillPane(pane.paneId, this.getServerName());
            }
            pane.status = "exited";
            debugLogger28.info(`Killed pane for agent "${agentId}"`);
          }
        }
      }
      async cleanup() {
        this.cleanedUp = true;
        this.stopExitPolling();
        for (const pane of this.panes.values()) {
          if (pane.paneId) {
            try {
              await tmuxKillPane(pane.paneId, this.getServerName());
              debugLogger28.info(`Killed agent pane ${pane.paneId}`);
            } catch (_error) {
              debugLogger28.info(`Failed to kill pane ${pane.paneId} (may already be gone)`);
            }
          }
        }
        if (!this.insideTmux && this.sessionName && this.serverName) {
          try {
            await tmuxKillSession(this.sessionName, this.serverName);
            debugLogger28.info(`Killed external tmux session "${this.sessionName}" on server "${this.serverName}"`);
          } catch (_error) {
            debugLogger28.info(`Failed to kill external tmux session (may already be gone)`);
          }
        }
        this.panes.clear();
        this.agentOrder = [];
        this.activeAgentId = null;
        this.serverName = null;
        this.sessionName = null;
        this.windowName = null;
        this.windowTarget = "";
        this.mainPaneId = "";
      }
      setOnAgentExit(callback) {
        this.onExitCallback = callback;
      }
      async waitForAll(timeoutMs) {
        if (this.allExited() || this.cleanedUp)
          return this.allExited();
        return new Promise((resolve42) => {
          let timeoutHandle;
          const checkInterval = setInterval(() => {
            if (this.allExited() || this.cleanedUp) {
              clearInterval(checkInterval);
              if (timeoutHandle)
                clearTimeout(timeoutHandle);
              resolve42(this.allExited());
            }
          }, EXIT_POLL_INTERVAL_MS);
          if (timeoutMs !== void 0) {
            timeoutHandle = setTimeout(() => {
              clearInterval(checkInterval);
              resolve42(false);
            }, timeoutMs);
          }
        });
      }
      // ─── Active Agent & Navigation ──────────────────────────────
      switchTo(agentId) {
        if (!this.panes.has(agentId)) {
          throw new Error(`Agent "${agentId}" not found.`);
        }
        const pane = this.panes.get(agentId);
        this.activeAgentId = agentId;
        void tmuxSelectPane(pane.paneId, this.getServerName());
      }
      switchToNext() {
        if (this.agentOrder.length <= 1)
          return;
        const currentIndex = this.agentOrder.indexOf(this.activeAgentId ?? "");
        const nextIndex = (currentIndex + 1) % this.agentOrder.length;
        this.switchTo(this.agentOrder[nextIndex]);
      }
      switchToPrevious() {
        if (this.agentOrder.length <= 1)
          return;
        const currentIndex = this.agentOrder.indexOf(this.activeAgentId ?? "");
        const prevIndex = (currentIndex - 1 + this.agentOrder.length) % this.agentOrder.length;
        this.switchTo(this.agentOrder[prevIndex]);
      }
      getActiveAgentId() {
        return this.activeAgentId;
      }
      // ─── Screen Capture ─────────────────────────────────────────
      getActiveSnapshot() {
        if (!this.activeAgentId)
          return null;
        return this.getAgentSnapshot(this.activeAgentId);
      }
      getAgentSnapshot(agentId, _scrollOffset = 0) {
        return null;
      }
      getAgentScrollbackLength(_agentId) {
        return 0;
      }
      // ─── Input ──────────────────────────────────────────────────
      forwardInput(data) {
        if (!this.activeAgentId)
          return false;
        return this.writeToAgent(this.activeAgentId, data);
      }
      writeToAgent(agentId, data) {
        const pane = this.panes.get(agentId);
        if (!pane || pane.status !== "running")
          return false;
        void tmuxSendKeys(pane.paneId, data, { literal: true }, this.getServerName());
        return true;
      }
      // ─── Resize ─────────────────────────────────────────────────
      resizeAll(_cols, _rows) {
      }
      // ─── External Session Info ─────────────────────────────────
      getAttachHint() {
        if (this.insideTmux) {
          return null;
        }
        const server = this.serverName ?? `${TMUX_SERVER_PREFIX}-${process.pid}`;
        return `tmux -L ${server} a`;
      }
      // ─── Private ────────────────────────────────────────────────
      resolveTmuxOptions(config2) {
        const opts = config2.backend?.tmux ?? {};
        return {
          serverName: opts.serverName ?? `${TMUX_SERVER_PREFIX}-${process.pid}`,
          sessionName: opts.sessionName ?? DEFAULT_TMUX_SESSION,
          windowName: opts.windowName ?? DEFAULT_TMUX_WINDOW,
          paneTitle: opts.paneTitle ?? config2.agentId,
          paneBorderStyle: opts.paneBorderStyle,
          paneActiveBorderStyle: opts.paneActiveBorderStyle,
          paneBorderFormat: opts.paneBorderFormat ?? DEFAULT_PANE_BORDER_FORMAT,
          paneBorderStatus: opts.paneBorderStatus ?? (this.insideTmux ? void 0 : "top"),
          leaderPaneWidthPercent: opts.leaderPaneWidthPercent ?? DEFAULT_LEADER_WIDTH_PERCENT,
          firstSplitPercent: opts.firstSplitPercent ?? DEFAULT_FIRST_SPLIT_PERCENT
        };
      }
      getServerName() {
        return this.insideTmux ? void 0 : this.serverName ?? void 0;
      }
      async ensureExternalSession(config2, options2) {
        if (this.windowTarget && this.serverName && this.sessionName && this.windowName) {
          return;
        }
        this.serverName = options2.serverName;
        this.sessionName = options2.sessionName;
        this.windowName = options2.windowName;
        const serverName = this.serverName;
        const sessionExists = await tmuxHasSession(this.sessionName, serverName);
        if (!sessionExists) {
          await tmuxNewSession(this.sessionName, {
            cols: config2.cols,
            rows: config2.rows,
            windowName: this.windowName
          }, serverName);
        }
        const windowExists = sessionExists ? await tmuxHasWindow(this.sessionName, this.windowName, serverName) : true;
        if (!windowExists) {
          await tmuxNewWindow(this.sessionName, this.windowName, serverName);
        }
        this.windowTarget = `${this.sessionName}:${this.windowName}`;
        if (!this.mainPaneId) {
          this.mainPaneId = await tmuxGetFirstPaneId(this.windowTarget, serverName);
        }
      }
      async spawnInsideTmux(cmd, options2) {
        if (!this.windowTarget) {
          throw new Error("Tmux window target not initialized.");
        }
        const panes = await tmuxListPanes(this.windowTarget);
        const paneCount = panes.length;
        if (paneCount === 1) {
          debugLogger28.info(`[spawnInsideTmux] First agent \u2014 split -h -l ${options2.firstSplitPercent}% from ${this.mainPaneId}`);
          return await tmuxSplitWindow(this.mainPaneId, {
            horizontal: true,
            percent: options2.firstSplitPercent,
            command: cmd
          });
        }
        const splitTarget = this.pickMiddlePane(panes).paneId;
        const horizontal = this.shouldSplitHorizontally(paneCount);
        debugLogger28.info(`[spawnInsideTmux] Split from middle pane ${splitTarget} (${paneCount} panes, ${horizontal ? "horizontal" : "vertical"})`);
        return await tmuxSplitWindow(splitTarget, {
          horizontal,
          command: cmd
        });
      }
      async spawnOutsideTmux(config2, cmd, options2) {
        await this.ensureExternalSession(config2, options2);
        if (!this.windowTarget) {
          throw new Error("External tmux window target not initialized.");
        }
        const serverName = this.getServerName();
        if (this.panes.size === 0) {
          const firstPaneId = await tmuxGetFirstPaneId(this.windowTarget, serverName);
          this.mainPaneId = firstPaneId;
          debugLogger28.info(`[spawnOutsideTmux] First agent \u2014 respawn in pane ${firstPaneId}`);
          await tmuxRespawnPane(firstPaneId, cmd, serverName);
          return firstPaneId;
        }
        const panes = await tmuxListPanes(this.windowTarget, serverName);
        const splitTarget = this.pickMiddlePane(panes).paneId;
        const horizontal = this.shouldSplitHorizontally(panes.length);
        debugLogger28.info(`[spawnOutsideTmux] Split from middle pane ${splitTarget} (${panes.length} panes, ${horizontal ? "horizontal" : "vertical"})`);
        return await tmuxSplitWindow(splitTarget, { horizontal, command: cmd }, serverName);
      }
      pickMiddlePane(panes) {
        if (panes.length === 0) {
          throw new Error("No panes available to split.");
        }
        return panes[Math.floor(panes.length / 2)];
      }
      shouldSplitHorizontally(paneCount) {
        return paneCount % 2 === 1;
      }
      async applyPaneDecorations(paneId, options2, serverName) {
        if (!this.windowTarget)
          return;
        if (options2.paneBorderStatus) {
          await tmuxSetOption(this.windowTarget, "pane-border-status", options2.paneBorderStatus, serverName);
        }
        if (options2.paneBorderFormat) {
          await tmuxSetOption(this.windowTarget, "pane-border-format", options2.paneBorderFormat, serverName);
        }
        if (options2.paneBorderStyle) {
          await tmuxSetOption(this.windowTarget, "pane-border-style", options2.paneBorderStyle, serverName);
          await tmuxSelectPaneStyle(paneId, options2.paneBorderStyle, serverName);
        }
        if (options2.paneActiveBorderStyle) {
          await tmuxSetOption(this.windowTarget, "pane-active-border-style", options2.paneActiveBorderStyle, serverName);
        }
        await tmuxSelectPaneTitle(paneId, options2.paneTitle, serverName);
      }
      async applyInsideLayout(options2) {
        if (!this.windowTarget || !this.mainPaneId)
          return;
        await tmuxSelectLayout(this.windowTarget, "main-vertical");
        await tmuxResizePane(this.mainPaneId, {
          width: `${options2.leaderPaneWidthPercent}%`
        });
      }
      async applyExternalLayout(serverName) {
        if (!this.windowTarget)
          return;
        await tmuxSelectLayout(this.windowTarget, "tiled", serverName);
      }
      async sleep(ms) {
        await new Promise((resolve42) => setTimeout(resolve42, ms));
      }
      buildShellCommand(config2) {
        const envParts = [];
        if (config2.env) {
          for (const [key, value] of Object.entries(config2.env)) {
            envParts.push(`${key}=${shellQuote(value)}`);
          }
        }
        const cmdParts = [
          shellQuote(config2.command),
          ...config2.args.map(shellQuote)
        ];
        const parts2 = [`cd ${shellQuote(config2.cwd)}`];
        if (envParts.length > 0) {
          parts2.push(`env ${envParts.join(" ")} ${cmdParts.join(" ")}`);
        } else {
          parts2.push(cmdParts.join(" "));
        }
        const fullCommand = parts2.join(" && ");
        debugLogger28.info(`[buildShellCommand] agentId=${config2.agentId}, command=${config2.command}, args=${JSON.stringify(config2.args)}, cwd=${config2.cwd}`);
        debugLogger28.info(`[buildShellCommand] full shell command: ${fullCommand}`);
        return fullCommand;
      }
      allExited() {
        if (this.pendingSpawns > 0)
          return false;
        if (this.panes.size === 0)
          return true;
        for (const pane of this.panes.values()) {
          if (pane.status === "running")
            return false;
        }
        return true;
      }
      startExitPolling() {
        if (this.exitPollTimer)
          return;
        this.exitPollTimer = setInterval(() => {
          void this.pollPaneStatus();
        }, EXIT_POLL_INTERVAL_MS);
      }
      stopExitPolling() {
        if (this.exitPollTimer) {
          clearInterval(this.exitPollTimer);
          this.exitPollTimer = null;
        }
      }
      async pollPaneStatus() {
        let paneInfos;
        const serverName = this.getServerName();
        try {
          if (!this.windowTarget)
            return;
          paneInfos = await tmuxListPanes(this.windowTarget, serverName);
        } catch (err2) {
          debugLogger28.info(`[pollPaneStatus] Failed to list panes for window "${this.windowTarget}": ${err2}`);
          return;
        }
        const paneMap = /* @__PURE__ */ new Map();
        for (const info2 of paneInfos) {
          paneMap.set(info2.paneId, info2);
        }
        if (this.panes.size > 0) {
          debugLogger28.info(`[pollPaneStatus] paneCount=${paneInfos.length}, agentPanes=${JSON.stringify(Array.from(this.panes.values()).map((p2) => {
            const info2 = paneMap.get(p2.paneId);
            return {
              agentId: p2.agentId,
              paneId: p2.paneId,
              status: p2.status,
              dead: info2?.dead,
              deadStatus: info2?.deadStatus
            };
          }))}`);
        }
        for (const agent of this.panes.values()) {
          if (agent.status !== "running")
            continue;
          const info2 = paneMap.get(agent.paneId);
          if (!info2) {
            agent.status = "exited";
            agent.exitCode = 1;
            debugLogger28.info(`[pollPaneStatus] Agent "${agent.agentId}" pane ${agent.paneId} not found in tmux list \u2014 marking as exited`);
            this.onExitCallback?.(agent.agentId, 1, null);
            continue;
          }
          if (info2.dead) {
            agent.status = "exited";
            agent.exitCode = info2.deadStatus;
            debugLogger28.info(`[pollPaneStatus] Agent "${agent.agentId}" (pane ${agent.paneId}) detected as DEAD with exit code ${info2.deadStatus}`);
            this.onExitCallback?.(agent.agentId, info2.deadStatus, null);
          }
        }
        if (this.allExited()) {
          this.stopExitPolling();
        }
      }
    };
    __name(shellQuote, "shellQuote");
  }
});

// packages/core/dist/src/agents/backends/iterm-it2.js
async function it2Result(args2) {
  debugLogger29.info(`it2 ${args2.join(" ")}`);
  const result = await execCommand2("it2", args2, {
    preserveOutputOnError: true
  });
  if (result.code !== 0 && result.stderr.trim()) {
    debugLogger29.error(`it2 error: ${result.stderr.trim()}`);
  }
  return result;
}
async function it2(args2) {
  const result = await it2Result(args2);
  if (result.code !== 0) {
    const message = result.stderr.trim() || result.stdout.trim();
    throw new Error(message || "it2 command failed");
  }
  return result.stdout;
}
function parseCreatedPaneId(output) {
  const match2 = output.match(/Created new pane:\s*(\S+)/);
  if (!match2?.[1]) {
    throw new Error(`Unable to parse it2 split output: ${output.trim()}`);
  }
  return match2[1];
}
function isIt2Available() {
  return isCommandAvailable("it2").available;
}
async function tryInstallIt2(command2, args2) {
  if (!isCommandAvailable(command2).available)
    return false;
  const result = await execCommand2(command2, args2, {
    preserveOutputOnError: true
  });
  return result.code === 0;
}
async function ensureIt2Installed() {
  if (isIt2Available())
    return;
  const installers = [
    { cmd: "uv", args: ["tool", "install", "it2"] },
    { cmd: "pipx", args: ["install", "it2"] },
    { cmd: "pip", args: ["install", "--user", "it2"] }
  ];
  for (const installer of installers) {
    const installed2 = await tryInstallIt2(installer.cmd, installer.args);
    if (installed2 && isIt2Available())
      return;
  }
  throw new Error('it2 is not installed. Install it2 via "uv tool install it2", "pipx install it2", or "pip install --user it2".');
}
async function verifyITerm() {
  await ensureIt2Installed();
  const result = await it2Result(["session", "list"]);
  if (result.code === 0)
    return;
  const combined = `${result.stdout}
${result.stderr}`.toLowerCase();
  if (combined.includes("api") || combined.includes("python") || combined.includes("connection refused") || combined.includes("not enabled")) {
    throw new Error("iTerm2 Python API not enabled. Enable it in iTerm2 \u2192 Settings \u2192 General \u2192 Magic \u2192 Enable Python API, then restart iTerm2.");
  }
  throw new Error(`it2 session list failed: ${result.stderr.trim() || result.stdout.trim()}`);
}
async function itermSplitPane(sessionId) {
  const args2 = ["session", "split", "-v"];
  if (sessionId) {
    args2.push("-s", sessionId);
  }
  const output = await it2(args2);
  return parseCreatedPaneId(output);
}
async function itermRunCommand(sessionId, command2) {
  await it2(["session", "run", "-s", sessionId, command2]);
}
async function itermFocusSession(sessionId) {
  await it2(["session", "focus", sessionId]);
}
async function itermSendText(sessionId, text) {
  await it2(["session", "send", "-s", sessionId, text]);
}
async function itermCloseSession(sessionId) {
  await it2(["session", "close", "-s", sessionId]);
}
var debugLogger29;
var init_iterm_it2 = __esm({
  "packages/core/dist/src/agents/backends/iterm-it2.js"() {
    "use strict";
    init_esbuild_shims();
    init_shell_utils();
    init_debugLogger();
    debugLogger29 = createDebugLogger("ITERM_IT2");
    __name(it2Result, "it2Result");
    __name(it2, "it2");
    __name(parseCreatedPaneId, "parseCreatedPaneId");
    __name(isIt2Available, "isIt2Available");
    __name(tryInstallIt2, "tryInstallIt2");
    __name(ensureIt2Installed, "ensureIt2Installed");
    __name(verifyITerm, "verifyITerm");
    __name(itermSplitPane, "itermSplitPane");
    __name(itermRunCommand, "itermRunCommand");
    __name(itermFocusSession, "itermFocusSession");
    __name(itermSendText, "itermSendText");
    __name(itermCloseSession, "itermCloseSession");
  }
});

// packages/core/dist/src/agents/backends/ITermBackend.js
import * as fs34 from "node:fs/promises";
import * as path27 from "node:path";
import * as os14 from "node:os";
function shellQuote2(value) {
  return `'${value.replace(/'/g, "'\\''")}'`;
}
var debugLogger30, EXIT_POLL_INTERVAL_MS2, ITermBackend, VALID_ENV_KEY;
var init_ITermBackend = __esm({
  "packages/core/dist/src/agents/backends/ITermBackend.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_types7();
    init_iterm_it2();
    debugLogger30 = createDebugLogger("ITERM_BACKEND");
    EXIT_POLL_INTERVAL_MS2 = 500;
    ITermBackend = class {
      static {
        __name(this, "ITermBackend");
      }
      type = DISPLAY_MODE.ITERM2;
      /** Directory for exit marker files */
      exitMarkerDir;
      /** Session ID of the last agent pane (split source) */
      lastSplitSessionId = null;
      sessions = /* @__PURE__ */ new Map();
      agentOrder = [];
      activeAgentId = null;
      onExitCallback = null;
      exitPollTimer = null;
      initialized = false;
      /** Number of agents currently being spawned asynchronously */
      pendingSpawns = 0;
      /** Queue to serialize spawn operations (prevents split race conditions) */
      spawnQueue = Promise.resolve();
      constructor() {
        this.exitMarkerDir = path27.join(os14.tmpdir(), `agent-iterm-exit-${Date.now().toString(36)}`);
      }
      async init() {
        if (this.initialized)
          return;
        await verifyITerm();
        await fs34.mkdir(this.exitMarkerDir, { recursive: true });
        this.initialized = true;
        debugLogger30.info("ITermBackend initialized");
      }
      // ─── Agent Lifecycle ────────────────────────────────────────
      async spawnAgent(config2) {
        if (!this.initialized) {
          throw new Error("ITermBackend not initialized. Call init() first.");
        }
        if (this.sessions.has(config2.agentId)) {
          throw new Error(`Agent "${config2.agentId}" already exists.`);
        }
        const exitMarkerPath = path27.join(this.exitMarkerDir, config2.agentId);
        await fs34.mkdir(path27.dirname(exitMarkerPath), { recursive: true });
        const cmd = this.buildShellCommand(config2, exitMarkerPath);
        this.pendingSpawns++;
        const spawnPromise = this.spawnQueue.then(() => this.spawnAgentAsync(config2.agentId, cmd, exitMarkerPath));
        this.spawnQueue = spawnPromise;
        await spawnPromise;
      }
      async spawnAgentAsync(agentId, cmd, exitMarkerPath) {
        try {
          let sessionId;
          if (this.sessions.size === 0) {
            const leaderSessionId = process.env["ITERM_SESSION_ID"] || void 0;
            sessionId = await itermSplitPane(leaderSessionId);
            await itermRunCommand(sessionId, cmd);
          } else {
            sessionId = await itermSplitPane(this.lastSplitSessionId || void 0);
            await itermRunCommand(sessionId, cmd);
          }
          const agentSession = {
            agentId,
            sessionId,
            exitMarkerPath,
            status: "running",
            exitCode: 0
          };
          this.sessions.set(agentId, agentSession);
          this.agentOrder.push(agentId);
          this.lastSplitSessionId = sessionId;
          if (this.activeAgentId === null) {
            this.activeAgentId = agentId;
          }
          this.startExitPolling();
          debugLogger30.info(`Spawned agent "${agentId}" in session ${sessionId}`);
        } catch (error40) {
          debugLogger30.error(`Failed to spawn agent "${agentId}":`, error40);
          this.sessions.set(agentId, {
            agentId,
            sessionId: "",
            exitMarkerPath,
            status: "exited",
            exitCode: 1
          });
          this.agentOrder.push(agentId);
          this.onExitCallback?.(agentId, 1, null);
        } finally {
          this.pendingSpawns--;
        }
      }
      stopAgent(agentId) {
        const session = this.sessions.get(agentId);
        if (!session || session.status !== "running")
          return;
        itermCloseSession(session.sessionId).catch((e4) => debugLogger30.error(`Failed to close session for agent "${agentId}": ${e4}`));
        session.status = "exited";
        session.exitCode = 1;
        this.onExitCallback?.(agentId, 1, null);
        debugLogger30.info(`Closed iTerm2 session for agent "${agentId}"`);
      }
      stopAll() {
        for (const session of this.sessions.values()) {
          if (session.status === "running") {
            itermCloseSession(session.sessionId).catch((e4) => debugLogger30.error(`Failed to close session for agent "${session.agentId}": ${e4}`));
            session.status = "exited";
            session.exitCode = 1;
            this.onExitCallback?.(session.agentId, 1, null);
          }
        }
        this.activeAgentId = null;
      }
      async cleanup() {
        this.stopExitPolling();
        for (const session of this.sessions.values()) {
          if (!session.sessionId)
            continue;
          try {
            await itermCloseSession(session.sessionId);
          } catch (error40) {
            debugLogger30.error("Session cleanup error (ignored):", error40);
          }
        }
        try {
          await fs34.rm(this.exitMarkerDir, {
            recursive: true,
            force: true
          });
        } catch (error40) {
          debugLogger30.error("Exit marker cleanup error (ignored):", error40);
        }
        this.sessions.clear();
        this.agentOrder = [];
        this.activeAgentId = null;
        this.lastSplitSessionId = null;
      }
      setOnAgentExit(callback) {
        this.onExitCallback = callback;
      }
      async waitForAll(timeoutMs) {
        if (this.allExited())
          return true;
        return new Promise((resolve42) => {
          let timeoutHandle;
          const checkInterval = setInterval(() => {
            if (this.allExited()) {
              clearInterval(checkInterval);
              if (timeoutHandle)
                clearTimeout(timeoutHandle);
              resolve42(true);
            }
          }, EXIT_POLL_INTERVAL_MS2);
          if (timeoutMs !== void 0) {
            timeoutHandle = setTimeout(() => {
              clearInterval(checkInterval);
              resolve42(false);
            }, timeoutMs);
          }
        });
      }
      // ─── Active Agent & Navigation ──────────────────────────────
      switchTo(agentId) {
        if (!this.sessions.has(agentId)) {
          throw new Error(`Agent "${agentId}" not found.`);
        }
        const session = this.sessions.get(agentId);
        this.activeAgentId = agentId;
        itermFocusSession(session.sessionId).catch((e4) => debugLogger30.error(`Failed to focus session for agent "${agentId}": ${e4}`));
      }
      switchToNext() {
        if (this.agentOrder.length <= 1)
          return;
        const currentIndex = this.agentOrder.indexOf(this.activeAgentId ?? "");
        const nextIndex = (currentIndex + 1) % this.agentOrder.length;
        this.switchTo(this.agentOrder[nextIndex]);
      }
      switchToPrevious() {
        if (this.agentOrder.length <= 1)
          return;
        const currentIndex = this.agentOrder.indexOf(this.activeAgentId ?? "");
        const prevIndex = (currentIndex - 1 + this.agentOrder.length) % this.agentOrder.length;
        this.switchTo(this.agentOrder[prevIndex]);
      }
      getActiveAgentId() {
        return this.activeAgentId;
      }
      // ─── Screen Capture ─────────────────────────────────────────
      getActiveSnapshot() {
        return null;
      }
      getAgentSnapshot(_agentId, _scrollOffset = 0) {
        return null;
      }
      getAgentScrollbackLength(_agentId) {
        return 0;
      }
      // ─── Input ──────────────────────────────────────────────────
      forwardInput(data) {
        if (!this.activeAgentId)
          return false;
        return this.writeToAgent(this.activeAgentId, data);
      }
      writeToAgent(agentId, data) {
        const session = this.sessions.get(agentId);
        if (!session || session.status !== "running")
          return false;
        itermSendText(session.sessionId, data).catch((e4) => debugLogger30.error(`Failed to send text to agent "${agentId}": ${e4}`));
        return true;
      }
      // ─── Resize ─────────────────────────────────────────────────
      resizeAll(_cols, _rows) {
      }
      getAttachHint() {
        return null;
      }
      // ─── Private ────────────────────────────────────────────────
      /**
       * Build the shell command with exit marker wrapping.
       *
       * The command is wrapped so that its exit code is written to a temp file
       * when it completes. This allows the backend to detect agent exit via
       * file polling, since iTerm2 `write text` runs commands inside a shell
       * (the shell stays alive after the command exits).
       */
      buildShellCommand(config2, exitMarkerPath) {
        const envParts = [];
        if (config2.env) {
          for (const [key, value] of Object.entries(config2.env)) {
            if (!VALID_ENV_KEY.test(key)) {
              throw new Error(`Invalid environment variable name: "${key}". Names must match /^[A-Za-z_][A-Za-z0-9_]*$/.`);
            }
            envParts.push(`${key}=${shellQuote2(value)}`);
          }
        }
        const cmdParts = [
          shellQuote2(config2.command),
          ...config2.args.map(shellQuote2)
        ];
        const parts2 = [`cd ${shellQuote2(config2.cwd)}`];
        if (envParts.length > 0) {
          parts2.push(`env ${envParts.join(" ")} ${cmdParts.join(" ")}`);
        } else {
          parts2.push(cmdParts.join(" "));
        }
        const mainCmd = parts2.join(" && ");
        const tmpMarker = shellQuote2(exitMarkerPath + ".tmp");
        const finalMarker = shellQuote2(exitMarkerPath);
        return `${mainCmd}; echo $? > ${tmpMarker} && mv ${tmpMarker} ${finalMarker}`;
      }
      allExited() {
        if (this.pendingSpawns > 0)
          return false;
        if (this.sessions.size === 0)
          return true;
        for (const session of this.sessions.values()) {
          if (session.status === "running")
            return false;
        }
        return true;
      }
      startExitPolling() {
        if (this.exitPollTimer)
          return;
        this.exitPollTimer = setInterval(() => {
          void this.pollExitStatus();
        }, EXIT_POLL_INTERVAL_MS2);
        this.exitPollTimer.unref();
      }
      stopExitPolling() {
        if (this.exitPollTimer) {
          clearInterval(this.exitPollTimer);
          this.exitPollTimer = null;
        }
      }
      async pollExitStatus() {
        for (const agent of this.sessions.values()) {
          if (agent.status !== "running")
            continue;
          try {
            const content = await fs34.readFile(agent.exitMarkerPath, "utf8");
            const exitCode = parseInt(content.trim(), 10);
            agent.status = "exited";
            agent.exitCode = isNaN(exitCode) ? 1 : exitCode;
            debugLogger30.info(`Agent "${agent.agentId}" exited with code ${agent.exitCode}`);
            this.onExitCallback?.(agent.agentId, agent.exitCode, null);
          } catch {
          }
        }
        if (this.allExited()) {
          this.stopExitPolling();
        }
      }
    };
    VALID_ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
    __name(shellQuote2, "shellQuote");
  }
});

// packages/core/dist/src/utils/workspaceContext.js
import * as fs35 from "node:fs";
import * as path28 from "node:path";
import * as process10 from "node:process";
function isPathWithinRoot(pathToCheck, rootDirectory) {
  const relative14 = path28.relative(rootDirectory, pathToCheck);
  return !relative14.startsWith(`..${path28.sep}`) && relative14 !== ".." && !path28.isAbsolute(relative14);
}
var debugLogger31, WorkspaceContext;
var init_workspaceContext = __esm({
  "packages/core/dist/src/utils/workspaceContext.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    init_debugLogger();
    debugLogger31 = createDebugLogger("WORKSPACE");
    WorkspaceContext = class _WorkspaceContext {
      static {
        __name(this, "WorkspaceContext");
      }
      directories = /* @__PURE__ */ new Set();
      initialDirectories;
      onDirectoriesChangedListeners = /* @__PURE__ */ new Set();
      /**
       * Memoized realpath results. Every workspace-bounded tool call ultimately
       * routes through {@link fullyResolvedPath} → `fs.realpathSync`; without
       * this cache the same path gets re-resolved on every Read/Glob/Grep/Ls
       * invocation. Bounded so long sessions touching many files don't grow
       * without limit; FIFO eviction is good enough — the working set tends to
       * be the small set of paths the model is actively manipulating.
       */
      resolvedPathCache = /* @__PURE__ */ new Map();
      static RESOLVED_PATH_CACHE_MAX = 1024;
      /**
       * 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);
        this.initialDirectories = new Set(this.directories);
        for (const additionalDirectory of additionalDirectories) {
          this.addDirectory(additionalDirectory);
        }
      }
      /**
       * 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) {
            debugLogger31.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 = process10.cwd()) {
        try {
          const resolved = this.resolveAndValidateDir(directory, basePath);
          if (this.directories.has(resolved)) {
            return;
          }
          this.directories.add(resolved);
          this.notifyDirectoriesChanged();
        } catch (err2) {
          debugLogger31.warn(`Skipping unreadable directory: ${directory} (${err2 instanceof Error ? err2.message : String(err2)})`);
        }
      }
      resolveAndValidateDir(directory, basePath = process10.cwd()) {
        const absolutePath = path28.isAbsolute(directory) ? directory : path28.resolve(basePath, directory);
        if (!fs35.existsSync(absolutePath)) {
          throw new Error(`Directory does not exist: ${absolutePath}`);
        }
        const stats = fs35.statSync(absolutePath);
        if (!stats.isDirectory()) {
          throw new Error(`Path is not a directory: ${absolutePath}`);
        }
        return fs35.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);
      }
      /**
       * Removes a directory from the workspace.
       * Cannot remove initial directories (those set at construction time).
       * @param directory The directory path to remove
       * @returns True if the directory was removed, false if not found or is an initial directory
       */
      removeDirectory(directory) {
        let resolved;
        try {
          resolved = this.resolveAndValidateDir(directory);
        } catch {
          resolved = path28.isAbsolute(directory) ? directory : path28.resolve(process10.cwd(), directory);
        }
        if (this.initialDirectories.has(resolved)) {
          debugLogger31.warn(`Cannot remove initial directory: ${resolved}`);
          return false;
        }
        if (!this.directories.has(resolved)) {
          return false;
        }
        this.directories.delete(resolved);
        this.notifyDirectoriesChanged();
        return true;
      }
      /**
       * Checks whether a directory is an initial (non-removable) directory.
       */
      isInitialDirectory(directory) {
        try {
          const resolved = this.resolveAndValidateDir(directory);
          return this.initialDirectories.has(resolved);
        } catch {
          const absolutePath = path28.isAbsolute(directory) ? directory : path28.resolve(process10.cwd(), directory);
          return this.initialDirectories.has(absolutePath);
        }
      }
      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.
       *
       * Result is memoized in {@link resolvedPathCache}. Filesystem-state cache:
       * if a file is renamed / a symlink is retargeted mid-session the cache
       * goes stale, which is the same correctness profile as any single
       * `realpathSync` call (it captures a moment in time). The win is cutting
       * 8+ syscalls per tool-heavy prompt down to 1.
       */
      fullyResolvedPath(pathToCheck) {
        const cached2 = this.resolvedPathCache.get(pathToCheck);
        if (cached2 !== void 0) {
          return cached2;
        }
        let resolved;
        try {
          resolved = fs35.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)) {
            resolved = e4.path;
          } else {
            throw e4;
          }
        }
        if (this.resolvedPathCache.size >= _WorkspaceContext.RESOLVED_PATH_CACHE_MAX) {
          const oldest = this.resolvedPathCache.keys().next().value;
          if (oldest !== void 0)
            this.resolvedPathCache.delete(oldest);
        }
        this.resolvedPathCache.set(pathToCheck, resolved);
        return resolved;
      }
      /**
       * Checks if a file path is a symbolic link that points to a file.
       */
      isFileSymlink(filePath) {
        try {
          return !fs35.readlinkSync(filePath).endsWith("/");
        } catch (_error) {
          return false;
        }
      }
    };
    __name(isPathWithinRoot, "isPathWithinRoot");
  }
});

// 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 EMPTY3 = "";
    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 : EMPTY3
    ), "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/,
        () => EMPTY3
      ],
      // > 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 : EMPTY3)
      ],
      // 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 isString3 = /* @__PURE__ */ __name((subject) => typeof subject === "string", "isString");
    var checkPattern = /* @__PURE__ */ __name((pattern) => pattern && isString3(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, body2, ignoreCase, negative, prefix) {
        this.pattern = pattern;
        this.mark = mark;
        this.negative = negative;
        define2(this, "body", body2);
        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 body2 = pattern;
      if (body2.indexOf("!") === 0) {
        negative = true;
        body2 = body2.substr(1);
      }
      body2 = body2.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
      const regexPrefix = makeRegexPrefix(body2);
      return new IgnoreRule(
        pattern,
        mark,
        body2,
        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 (isString3(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(
          isString3(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(path150, 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(path150);
          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((path150, originalPath, doThrow) => {
      if (!isString3(path150)) {
        return doThrow(
          `path must be a string, but got \`${originalPath}\``,
          TypeError
        );
      }
      if (!path150) {
        return doThrow(`path must not be empty`, TypeError);
      }
      if (checkPath.isNotRelative(path150)) {
        const r5 = "`path.relative()`d";
        return doThrow(
          `path should be a ${r5} string, but got "${originalPath}"`,
          RangeError
        );
      }
      return true;
    }, "checkPath");
    var isNotRelative = /* @__PURE__ */ __name((path150) => REGEX_TEST_INVALID_PATH.test(path150), "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 path150 = originalPath && checkPath.convert(originalPath);
        checkPath(
          path150,
          originalPath,
          this._strictPathCheck ? throwError : RETURN_FALSE
        );
        return this._t(path150, cache5, checkUnignored, slices);
      }
      checkIgnore(path150) {
        if (!REGEX_TEST_TRAILING_SLASH.test(path150)) {
          return this.test(path150);
        }
        const slices = path150.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(path150, false, MODE_CHECK_IGNORE);
      }
      _t(path150, cache5, checkUnignored, slices) {
        if (path150 in cache5) {
          return cache5[path150];
        }
        if (!slices) {
          slices = path150.split(SLASH2).filter(Boolean);
        }
        slices.pop();
        if (!slices.length) {
          return cache5[path150] = this._rules.test(path150, checkUnignored, MODE_IGNORE);
        }
        const parent = this._t(
          slices.join(SLASH2) + SLASH2,
          cache5,
          checkUnignored,
          slices
        );
        return cache5[path150] = parent.ignored ? parent : this._rules.test(path150, checkUnignored, MODE_IGNORE);
      }
      ignores(path150) {
        return this._test(path150, this._ignoreCache, false).ignored;
      }
      createFilter() {
        return (path150) => !this.ignores(path150);
      }
      filter(paths) {
        return makeArray(paths).filter(this.createFilter());
      }
      // @returns {TestResult}
      test(path150) {
        return this._test(path150, this._testCache, true);
      }
    };
    var factory2 = /* @__PURE__ */ __name((options2) => new Ignore3(options2), "factory");
    var isPathValid = /* @__PURE__ */ __name((path150) => checkPath(path150 && checkPath.convert(path150), path150, 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 = (path150) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path150) || isNotRelative(path150);
    }, "setupWindows");
    if (
      // Detect `process` so that it can run in browsers.
      typeof process !== "undefined" && process.platform === "win32"
    ) {
      setupWindows();
    }
    module2.exports = factory2;
    factory2.default = factory2;
    module2.exports.isPathValid = isPathValid;
    define2(module2.exports, Symbol.for("setupWindows"), setupWindows);
  }
});

// packages/core/dist/src/utils/gitIgnoreParser.js
import * as fs36 from "node:fs";
import * as path29 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 = path29.resolve(projectRoot);
      }
      loadPatternsForFile(patternsFilePath) {
        let content;
        try {
          content = fs36.readFileSync(patternsFilePath, "utf-8");
        } catch (_error) {
          return [];
        }
        const isExcludeFile = patternsFilePath.endsWith(path29.join(".git", "info", "exclude"));
        const relativeBaseDir = isExcludeFile ? "." : path29.dirname(path29.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 = path29.join("**", p2);
            }
            newPattern = path29.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 = path29.resolve(this.projectRoot, filePath);
        if (!absoluteFilePath.startsWith(this.projectRoot)) {
          return false;
        }
        try {
          const resolved = path29.resolve(this.projectRoot, filePath);
          const relativePath = path29.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 = path29.join(this.projectRoot, ".git", "info", "exclude");
            this.globalPatterns = fs36.existsSync(excludeFile) ? this.loadPatternsForFile(excludeFile) : [];
          }
          ig.add(this.globalPatterns);
          const pathParts = relativePath.split(path29.sep);
          const dirsToVisit = [this.projectRoot];
          let currentAbsDir = this.projectRoot;
          for (let i4 = 0; i4 < pathParts.length - 1; i4++) {
            currentAbsDir = path29.join(currentAbsDir, pathParts[i4]);
            dirsToVisit.push(currentAbsDir);
          }
          for (const dir of dirsToVisit) {
            const relativeDir = path29.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 = path29.join(dir, ".gitignore");
              if (fs36.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 fs37 from "node:fs";
import * as path30 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 = path30.resolve(projectRoot);
        this.loadPatterns();
      }
      loadPatterns() {
        const patternsFilePath = path30.join(this.projectRoot, ".qwenignore");
        let content;
        try {
          content = fs37.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 = path30.resolve(this.projectRoot, filePath);
        const relativePath = path30.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 path31 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 = path31.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() ?? [];
      }
    };
  }
});

// packages/core/dist/src/models/content-generator-config.js
function buildAgentContentGeneratorConfig(base, modelId, authOverrides) {
  const parentConfig = base.getContentGeneratorConfig();
  const sameProvider = authOverrides.authType === parentConfig.authType;
  const modelsConfig = base.getModelsConfig();
  const resolvedModel = modelId ? modelsConfig.getResolvedModel(authOverrides.authType, modelId) : void 0;
  const nextConfig = {
    ...parentConfig,
    model: modelId ?? parentConfig.model,
    authType: authOverrides.authType
  };
  if (!sameProvider) {
    for (const field of MODEL_GENERATION_CONFIG_FIELDS) {
      nextConfig[field] = void 0;
    }
  }
  if (resolvedModel) {
    applyResolvedModelConfig(nextConfig, resolvedModel, parentConfig, authOverrides);
    return nextConfig;
  }
  nextConfig.apiKey = resolveCredentialField(authOverrides.apiKey, sameProvider ? parentConfig.apiKey : void 0, authOverrides.authType, "apiKey");
  nextConfig.baseUrl = authOverrides.baseUrl ?? resolveCredentialField(void 0, sameProvider ? parentConfig.baseUrl : void 0, authOverrides.authType, "baseUrl");
  nextConfig.apiKeyEnvKey = sameProvider ? parentConfig.apiKeyEnvKey : void 0;
  return nextConfig;
}
function applyResolvedModelConfig(targetConfig, resolvedModel, parentConfig, authOverrides) {
  const sameProvider = authOverrides.authType === parentConfig.authType;
  targetConfig.model = resolvedModel.id;
  targetConfig.authType = resolvedModel.authType;
  targetConfig.baseUrl = authOverrides.baseUrl ?? resolvedModel.baseUrl ?? (sameProvider ? parentConfig.baseUrl : void 0);
  if (resolvedModel.envKey) {
    targetConfig.apiKey = authOverrides.apiKey ?? process.env[resolvedModel.envKey] ?? (sameProvider ? parentConfig.apiKey : void 0);
    targetConfig.apiKeyEnvKey = resolvedModel.envKey;
  } else {
    targetConfig.apiKey = resolveCredentialField(authOverrides.apiKey, sameProvider ? parentConfig.apiKey : void 0, authOverrides.authType, "apiKey");
    targetConfig.apiKeyEnvKey = sameProvider ? parentConfig.apiKeyEnvKey : void 0;
  }
  for (const field of MODEL_GENERATION_CONFIG_FIELDS) {
    const registryValue = resolvedModel.generationConfig[field];
    if (registryValue !== void 0) {
      targetConfig[field] = registryValue;
    }
  }
}
function resolveCredentialField(explicitValue, inheritedValue, authType, field) {
  if (explicitValue)
    return explicitValue;
  if (inheritedValue)
    return inheritedValue;
  const envMapping = AUTH_ENV_MAPPINGS[authType];
  if (!envMapping)
    return void 0;
  for (const envKey of envMapping[field]) {
    const value = process.env[envKey];
    if (value)
      return value;
  }
  return void 0;
}
var init_content_generator_config = __esm({
  "packages/core/dist/src/models/content-generator-config.js"() {
    "use strict";
    init_esbuild_shims();
    init_contentGenerator();
    init_constants3();
    __name(buildAgentContentGeneratorConfig, "buildAgentContentGeneratorConfig");
    __name(applyResolvedModelConfig, "applyResolvedModelConfig");
    __name(resolveCredentialField, "resolveCredentialField");
  }
});

// packages/core/dist/src/confirmation-bus/types.js
var MessageBusType;
var init_types8 = __esm({
  "packages/core/dist/src/confirmation-bus/types.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    (function(MessageBusType2) {
      MessageBusType2["TOOL_CONFIRMATION_REQUEST"] = "tool-confirmation-request";
      MessageBusType2["TOOL_CONFIRMATION_RESPONSE"] = "tool-confirmation-response";
      MessageBusType2["TOOL_EXECUTION_SUCCESS"] = "tool-execution-success";
      MessageBusType2["TOOL_EXECUTION_FAILURE"] = "tool-execution-failure";
      MessageBusType2["HOOK_EXECUTION_REQUEST"] = "hook-execution-request";
      MessageBusType2["HOOK_EXECUTION_RESPONSE"] = "hook-execution-response";
    })(MessageBusType || (MessageBusType = {}));
  }
});

// packages/core/dist/src/core/toolHookTriggers.js
function generateToolUseId() {
  return `toolu_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
}
async function firePreToolUseHook(messageBus, toolName, toolInput, toolUseId, permissionMode, signal) {
  if (!messageBus) {
    return { shouldProceed: true };
  }
  try {
    const response = await messageBus.request({
      type: MessageBusType.HOOK_EXECUTION_REQUEST,
      eventName: "PreToolUse",
      input: {
        permission_mode: permissionMode,
        tool_name: toolName,
        tool_input: toolInput,
        tool_use_id: toolUseId
      },
      signal
    }, MessageBusType.HOOK_EXECUTION_RESPONSE);
    if (!response.success || !response.output) {
      return { shouldProceed: true };
    }
    const preToolOutput = createHookOutput("PreToolUse", response.output);
    if (preToolOutput.isDenied()) {
      return {
        shouldProceed: false,
        blockReason: preToolOutput.getPermissionDecisionReason() || preToolOutput.getEffectiveReason(),
        blockType: "denied"
      };
    }
    if (preToolOutput.isAsk()) {
      return {
        shouldProceed: false,
        blockReason: preToolOutput.getPermissionDecisionReason() || "User confirmation required",
        blockType: "ask"
      };
    }
    if (preToolOutput.shouldStopExecution()) {
      return {
        shouldProceed: false,
        blockReason: preToolOutput.getEffectiveReason(),
        blockType: "stop"
      };
    }
    const additionalContext = preToolOutput.getAdditionalContext();
    return {
      shouldProceed: true,
      additionalContext
    };
  } catch (error40) {
    debugLogger32.warn(`PreToolUse hook error for ${toolName}: ${error40 instanceof Error ? error40.message : String(error40)}`);
    return { shouldProceed: true };
  }
}
async function firePostToolUseHook(messageBus, toolName, toolInput, toolResponse, toolUseId, permissionMode, signal) {
  if (!messageBus) {
    return { shouldStop: false };
  }
  try {
    const response = await messageBus.request({
      type: MessageBusType.HOOK_EXECUTION_REQUEST,
      eventName: "PostToolUse",
      input: {
        permission_mode: permissionMode,
        tool_name: toolName,
        tool_input: toolInput,
        tool_response: toolResponse,
        tool_use_id: toolUseId
      },
      signal
    }, MessageBusType.HOOK_EXECUTION_RESPONSE);
    if (!response.success || !response.output) {
      return { shouldStop: false };
    }
    const postToolOutput = createHookOutput("PostToolUse", response.output);
    if (postToolOutput.shouldStopExecution()) {
      return {
        shouldStop: true,
        stopReason: postToolOutput.getEffectiveReason()
      };
    }
    const additionalContext = postToolOutput.getAdditionalContext();
    return {
      shouldStop: false,
      additionalContext
    };
  } catch (error40) {
    debugLogger32.warn(`PostToolUse hook error for ${toolName}: ${error40 instanceof Error ? error40.message : String(error40)}`);
    return { shouldStop: false };
  }
}
async function firePostToolUseFailureHook(messageBus, toolUseId, toolName, toolInput, errorMessage, isInterrupt, permissionMode, signal) {
  if (!messageBus) {
    return {};
  }
  try {
    const response = await messageBus.request({
      type: MessageBusType.HOOK_EXECUTION_REQUEST,
      eventName: "PostToolUseFailure",
      input: {
        permission_mode: permissionMode,
        tool_use_id: toolUseId,
        tool_name: toolName,
        tool_input: toolInput,
        error: errorMessage,
        is_interrupt: isInterrupt
      },
      signal
    }, MessageBusType.HOOK_EXECUTION_RESPONSE);
    if (!response.success || !response.output) {
      return {};
    }
    const failureOutput = createHookOutput("PostToolUseFailure", response.output);
    const additionalContext = failureOutput.getAdditionalContext();
    return {
      additionalContext
    };
  } catch (error40) {
    debugLogger32.warn(`PostToolUseFailure hook error for ${toolName}: ${error40 instanceof Error ? error40.message : String(error40)}`);
    return {};
  }
}
async function fireNotificationHook(messageBus, message, notificationType, title, signal) {
  if (!messageBus) {
    return {};
  }
  try {
    const response = await messageBus.request({
      type: MessageBusType.HOOK_EXECUTION_REQUEST,
      eventName: "Notification",
      input: {
        message,
        notification_type: notificationType,
        title
      },
      signal
    }, MessageBusType.HOOK_EXECUTION_RESPONSE);
    if (!response.success || !response.output) {
      return {};
    }
    const notificationOutput = createHookOutput("Notification", response.output);
    const additionalContext = notificationOutput.getAdditionalContext();
    return {
      additionalContext
    };
  } catch (error40) {
    debugLogger32.warn(`Notification hook error: ${error40 instanceof Error ? error40.message : String(error40)}`);
    return {};
  }
}
async function firePermissionRequestHook(messageBus, toolName, toolInput, permissionMode, permissionSuggestions, signal) {
  if (!messageBus) {
    return { hasDecision: false };
  }
  try {
    const response = await messageBus.request({
      type: MessageBusType.HOOK_EXECUTION_REQUEST,
      eventName: "PermissionRequest",
      input: {
        tool_name: toolName,
        tool_input: toolInput,
        permission_mode: permissionMode,
        permission_suggestions: permissionSuggestions
      },
      signal
    }, MessageBusType.HOOK_EXECUTION_RESPONSE);
    if (!response.success || !response.output) {
      return { hasDecision: false };
    }
    const permissionOutput = createHookOutput("PermissionRequest", response.output);
    const decision = permissionOutput.getPermissionDecision();
    if (!decision) {
      return { hasDecision: false };
    }
    if (decision.behavior === "allow") {
      return {
        hasDecision: true,
        shouldAllow: true,
        updatedInput: decision.updatedInput
      };
    }
    return {
      hasDecision: true,
      shouldAllow: false,
      denyMessage: decision.message,
      shouldInterrupt: decision.interrupt
    };
  } catch (error40) {
    debugLogger32.warn(`PermissionRequest hook error: ${error40 instanceof Error ? error40.message : String(error40)}`);
    return { hasDecision: false };
  }
}
function appendAdditionalContext(content, additionalContext) {
  if (!additionalContext) {
    return content;
  }
  if (typeof content === "string") {
    return content + "\n\n" + additionalContext;
  }
  if (Array.isArray(content)) {
    return [...content, { text: additionalContext }];
  }
  return content;
}
var debugLogger32;
var init_toolHookTriggers = __esm({
  "packages/core/dist/src/core/toolHookTriggers.js"() {
    "use strict";
    init_esbuild_shims();
    init_types8();
    init_types6();
    init_debugLogger();
    debugLogger32 = createDebugLogger("TOOL_HOOKS");
    __name(generateToolUseId, "generateToolUseId");
    __name(firePreToolUseHook, "firePreToolUseHook");
    __name(firePostToolUseHook, "firePostToolUseHook");
    __name(firePostToolUseFailureHook, "firePostToolUseFailureHook");
    __name(fireNotificationHook, "fireNotificationHook");
    __name(firePermissionRequestHook, "firePermissionRequestHook");
    __name(appendAdditionalContext, "appendAdditionalContext");
  }
});

// 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 SEP4 = "/";
    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: SEP4
    };
    var WINDOWS_CHARS = {
      ...POSIX_CHARS,
      SLASH_LITERAL: `[${WIN_SLASH}]`,
      QMARK: WIN_NO_SLASH,
      STAR: `${WIN_NO_SLASH}*?`,
      DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
      NO_DOT: `(?!${DOT_LITERAL})`,
      NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
      NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
      NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
      QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
      START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
      END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
      SEP: "\\"
    };
    var POSIX_REGEX_SOURCE = {
      alnum: "a-zA-Z0-9",
      alpha: "a-zA-Z",
      ascii: "\\x00-\\x7F",
      blank: " \\t",
      cntrl: "\\x00-\\x1F\\x7F",
      digit: "0-9",
      graph: "\\x21-\\x7E",
      lower: "a-z",
      print: "\\x20-\\x7E ",
      punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
      space: " \\t\\r\\n\\v\\f",
      upper: "A-Z",
      word: "A-Za-z0-9_",
      xdigit: "A-Fa-f0-9"
    };
    module2.exports = {
      MAX_LENGTH: 1024 * 64,
      POSIX_REGEX_SOURCE,
      // regular expressions
      REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
      REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
      REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
      REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
      REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
      REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
      // Replace globs with equivalent patterns to reduce parsing time.
      REPLACEMENTS: {
        __proto__: null,
        "***": "*",
        "**/**": "**",
        "**/**/**": "**"
      },
      // Digits
      CHAR_0: 48,
      /* 0 */
      CHAR_9: 57,
      /* 9 */
      // Alphabet chars.
      CHAR_UPPERCASE_A: 65,
      /* A */
      CHAR_LOWERCASE_A: 97,
      /* a */
      CHAR_UPPERCASE_Z: 90,
      /* Z */
      CHAR_LOWERCASE_Z: 122,
      /* z */
      CHAR_LEFT_PARENTHESES: 40,
      /* ( */
      CHAR_RIGHT_PARENTHESES: 41,
      /* ) */
      CHAR_ASTERISK: 42,
      /* * */
      // Non-alphabetic chars.
      CHAR_AMPERSAND: 38,
      /* & */
      CHAR_AT: 64,
      /* @ */
      CHAR_BACKWARD_SLASH: 92,
      /* \ */
      CHAR_CARRIAGE_RETURN: 13,
      /* \r */
      CHAR_CIRCUMFLEX_ACCENT: 94,
      /* ^ */
      CHAR_COLON: 58,
      /* : */
      CHAR_COMMA: 44,
      /* , */
      CHAR_DOT: 46,
      /* . */
      CHAR_DOUBLE_QUOTE: 34,
      /* " */
      CHAR_EQUAL: 61,
      /* = */
      CHAR_EXCLAMATION_MARK: 33,
      /* ! */
      CHAR_FORM_FEED: 12,
      /* \f */
      CHAR_FORWARD_SLASH: 47,
      /* / */
      CHAR_GRAVE_ACCENT: 96,
      /* ` */
      CHAR_HASH: 35,
      /* # */
      CHAR_HYPHEN_MINUS: 45,
      /* - */
      CHAR_LEFT_ANGLE_BRACKET: 60,
      /* < */
      CHAR_LEFT_CURLY_BRACE: 123,
      /* { */
      CHAR_LEFT_SQUARE_BRACKET: 91,
      /* [ */
      CHAR_LINE_FEED: 10,
      /* \n */
      CHAR_NO_BREAK_SPACE: 160,
      /* \u00A0 */
      CHAR_PERCENT: 37,
      /* % */
      CHAR_PLUS: 43,
      /* + */
      CHAR_QUESTION_MARK: 63,
      /* ? */
      CHAR_RIGHT_ANGLE_BRACKET: 62,
      /* > */
      CHAR_RIGHT_CURLY_BRACE: 125,
      /* } */
      CHAR_RIGHT_SQUARE_BRACKET: 93,
      /* ] */
      CHAR_SEMICOLON: 59,
      /* ; */
      CHAR_SINGLE_QUOTE: 39,
      /* ' */
      CHAR_SPACE: 32,
      /*   */
      CHAR_TAB: 9,
      /* \t */
      CHAR_UNDERSCORE: 95,
      /* _ */
      CHAR_VERTICAL_LINE: 124,
      /* | */
      CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
      /* \uFEFF */
      /**
       * Create EXTGLOB_CHARS
       */
      extglobChars(chars) {
        return {
          "!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` },
          "?": { type: "qmark", open: "(?:", close: ")?" },
          "+": { type: "plus", open: "(?:", close: ")+" },
          "*": { type: "star", open: "(?:", close: ")*" },
          "@": { type: "at", open: "(?:", close: ")" }
        };
      },
      /**
       * Create GLOB_CHARS
       */
      globChars(win323) {
        return win323 === true ? WINDOWS_CHARS : POSIX_CHARS;
      }
    };
  }
});

// packages/core/node_modules/picomatch/lib/utils.js
var require_utils14 = __commonJS({
  "packages/core/node_modules/picomatch/lib/utils.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var {
      REGEX_BACKSLASH,
      REGEX_REMOVE_BACKSLASH,
      REGEX_SPECIAL_CHARS,
      REGEX_SPECIAL_CHARS_GLOBAL
    } = require_constants11();
    exports2.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
    exports2.hasRegexChars = (str2) => REGEX_SPECIAL_CHARS.test(str2);
    exports2.isRegexChar = (str2) => str2.length === 1 && exports2.hasRegexChars(str2);
    exports2.escapeRegex = (str2) => str2.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
    exports2.toPosixSlashes = (str2) => str2.replace(REGEX_BACKSLASH, "/");
    exports2.isWindows = () => {
      if (typeof navigator !== "undefined" && navigator.platform) {
        const platform15 = navigator.platform.toLowerCase();
        return platform15 === "win32" || platform15 === "windows";
      }
      if (typeof process !== "undefined" && process.platform) {
        return process.platform === "win32";
      }
      return false;
    };
    exports2.removeBackslashes = (str2) => {
      return str2.replace(REGEX_REMOVE_BACKSLASH, (match2) => {
        return match2 === "\\" ? "" : match2;
      });
    };
    exports2.escapeLast = (input, char, lastIdx) => {
      const idx = input.lastIndexOf(char, lastIdx);
      if (idx === -1) return input;
      if (input[idx - 1] === "\\") return exports2.escapeLast(input, char, idx - 1);
      return `${input.slice(0, idx)}\\${input.slice(idx)}`;
    };
    exports2.removePrefix = (input, state = {}) => {
      let output = input;
      if (output.startsWith("./")) {
        output = output.slice(2);
        state.prefix = "./";
      }
      return output;
    };
    exports2.wrapOutput = (input, state = {}, options2 = {}) => {
      const prepend = options2.contains ? "" : "^";
      const append3 = options2.contains ? "" : "$";
      let output = `${prepend}(?:${input})${append3}`;
      if (state.negated === true) {
        output = `(?:^(?!${output}).*$)`;
      }
      return output;
    };
    exports2.basename = (path150, { windows } = {}) => {
      const segs = path150.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 parts2 = [];
      let str2 = input;
      let index = -1;
      let start2 = 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 === start2 + 1) {
            start2 += 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 === start2) {
              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 === start2) {
          negated = token2.negated = true;
          start2++;
          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 (start2 > 0) {
        prefix = str2.slice(0, start2);
        str2 = str2.slice(start2);
        lastIndex -= start2;
      }
      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: start2,
        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 : start2;
          const i4 = slashes[idx];
          const value = input.slice(n3, i4);
          if (opts.tokens) {
            if (idx === 0 && start2 !== 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 !== "") {
            parts2.push(value);
          }
          prevIndex = i4;
        }
        if (prevIndex && prevIndex + 1 < input.length) {
          const value = input.slice(prevIndex + 1);
          parts2.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 = parts2;
      }
      return state;
    }, "scan");
    module2.exports = scan;
  }
});

// packages/core/node_modules/picomatch/lib/parse.js
var require_parse5 = __commonJS({
  "packages/core/node_modules/picomatch/lib/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var constants5 = require_constants11();
    var utils = require_utils14();
    var {
      MAX_LENGTH: MAX_LENGTH2,
      POSIX_REGEX_SOURCE,
      REGEX_NON_SPECIAL_CHARS,
      REGEX_SPECIAL_CHARS_BACKREF,
      REPLACEMENTS
    } = constants5;
    var expandRange = /* @__PURE__ */ __name((args2, options2) => {
      if (typeof options2.expandRange === "function") {
        return options2.expandRange(...args2, options2);
      }
      args2.sort();
      const value = `[${args2.join("-")}]`;
      try {
        new RegExp(value);
      } catch (ex) {
        return args2.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 parse17 = /* @__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_LENGTH2, opts.maxLength) : MAX_LENGTH2;
      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 = constants5.globChars(opts.windows);
      const EXTGLOB_CHARS = constants5.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 append3 = /* @__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) append3(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 = parse17(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;
          append3({ value });
          continue;
        }
        if (state.quotes === 1 && value !== '"') {
          value = utils.escapeRegex(value);
          prev.value += value;
          append3({ 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;
          append3({ 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 i4 = arr.length - 1; i4 >= 0; i4--) {
              tokens.pop();
              if (arr[i4].type === "brace") {
                break;
              }
              if (arr[i4].type !== "dots") {
                range.unshift(arr[i4].value);
              }
            }
            output = expandRange(range, opts);
            state.backtrack = true;
          }
          if (brace.comma !== true && brace.dots !== true) {
            const out2 = state.output.slice(0, brace.outputIndex);
            const toks = state.tokens.slice(brace.tokensIndex);
            brace.value = brace.output = "\\{";
            value = output = "\\}";
            state.output = out2;
            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");
    parse17.fastpaths = (input, options2) => {
      const opts = { ...options2 };
      const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH2, opts.maxLength) : MAX_LENGTH2;
      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
      } = constants5.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 create4 = /* @__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 = create4(match2[1]);
            if (!source3) return;
            return source3 + DOT_LITERAL + match2[2];
          }
        }
      }, "create");
      const output = utils.removePrefix(input, state);
      let source2 = create4(output);
      if (source2 && opts.strictSlashes !== true) {
        source2 += `${SLASH_LITERAL}?`;
      }
      return source2;
    };
    module2.exports = parse17;
  }
});

// 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 parse17 = require_parse5();
    var utils = require_utils14();
    var constants5 = require_constants11();
    var isObject5 = /* @__PURE__ */ __name((val) => val && typeof val === "object" && !Array.isArray(val), "isObject");
    var picomatch5 = /* @__PURE__ */ __name((glob2, options2, returnState = false) => {
      if (Array.isArray(glob2)) {
        const fns = glob2.map((input) => picomatch5(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 = isObject5(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 ? picomatch5.compileRe(glob2, options2) : picomatch5.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 = picomatch5(opts.ignore, ignoreOpts, returnState);
      }
      const matcher = /* @__PURE__ */ __name((input, returnObject = false) => {
        const { isMatch, match: match2, output } = picomatch5.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");
    picomatch5.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 = picomatch5.matchBase(input, regex3, options2, posix3);
        } else {
          match2 = regex3.exec(output);
        }
      }
      return { isMatch: Boolean(match2), match: match2, output };
    };
    picomatch5.matchBase = (input, glob2, options2) => {
      const regex3 = glob2 instanceof RegExp ? glob2 : picomatch5.makeRe(glob2, options2);
      return regex3.test(utils.basename(input));
    };
    picomatch5.isMatch = (str2, patterns, options2) => picomatch5(patterns, options2)(str2);
    picomatch5.parse = (pattern, options2) => {
      if (Array.isArray(pattern)) return pattern.map((p2) => picomatch5.parse(p2, options2));
      return parse17(pattern, { ...options2, fastpaths: false });
    };
    picomatch5.scan = (input, options2) => scan(input, options2);
    picomatch5.compileRe = (state, options2, returnOutput = false, returnState = false) => {
      if (returnOutput === true) {
        return state.output;
      }
      const opts = options2 || {};
      const prepend = opts.contains ? "" : "^";
      const append3 = opts.contains ? "" : "$";
      let source2 = `${prepend}(?:${state.output})${append3}`;
      if (state && state.negated === true) {
        source2 = `^(?!${source2}).*$`;
      }
      const regex3 = picomatch5.toRegex(source2, options2);
      if (returnState === true) {
        regex3.state = state;
      }
      return regex3;
    };
    picomatch5.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 = parse17.fastpaths(input, options2);
      }
      if (!parsed.output) {
        parsed = parse17(input, options2);
      }
      return picomatch5.compileRe(parsed, options2, returnOutput, returnState);
    };
    picomatch5.toRegex = (source2, options2) => {
      try {
        const opts = options2 || {};
        return new RegExp(source2, opts.flags || (opts.nocase ? "i" : ""));
      } catch (err2) {
        if (options2 && options2.debug === true) throw err2;
        return /$^/;
      }
    };
    picomatch5.constants = constants5;
    module2.exports = picomatch5;
  }
});

// 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 picomatch5(glob2, options2, returnState = false) {
      if (options2 && (options2.windows === null || options2.windows === void 0)) {
        options2 = { ...options2, windows: utils.isWindows() };
      }
      return pico(glob2, options2, returnState);
    }
    __name(picomatch5, "picomatch");
    Object.assign(picomatch5, pico);
    module2.exports = picomatch5;
  }
});

// packages/core/dist/src/permissions/rule-parser.js
import path32 from "node:path";
import os15 from "node:os";
function toPosixPath(p2) {
  return p2.replace(/\\/g, "/");
}
function resolveToolName(rawName) {
  return TOOL_NAME_ALIASES[rawName] ?? rawName;
}
function getSpecifierKind(canonicalToolName) {
  if (SHELL_TOOL_NAMES3.has(canonicalToolName)) {
    return "command";
  }
  if (READ_TOOLS.has(canonicalToolName) || EDIT_TOOLS.has(canonicalToolName)) {
    return "path";
  }
  if (WEBFETCH_TOOLS.has(canonicalToolName)) {
    return "domain";
  }
  return "literal";
}
function toolMatchesRuleToolName(ruleToolName, contextToolName) {
  if (ruleToolName === contextToolName) {
    return true;
  }
  if (ruleToolName === "read_file" && READ_TOOLS.has(contextToolName)) {
    return true;
  }
  if (ruleToolName === "edit" && EDIT_TOOLS.has(contextToolName)) {
    return true;
  }
  return false;
}
function parseRule(raw2) {
  const trimmed2 = raw2.trim();
  const normalized2 = trimmed2.replace(/:(\*)/, " $1");
  const openParen = normalized2.indexOf("(");
  if (openParen === -1) {
    const canonicalName2 = resolveToolName(normalized2);
    return {
      raw: trimmed2,
      toolName: canonicalName2
    };
  }
  const toolPart = normalized2.substring(0, openParen).trim();
  if (!normalized2.endsWith(")")) {
    return { raw: trimmed2, toolName: resolveToolName(toolPart), invalid: true };
  }
  const specifier = normalized2.substring(openParen + 1, normalized2.length - 1);
  const canonicalName = resolveToolName(toolPart);
  const specifierKind = specifier ? getSpecifierKind(canonicalName) : void 0;
  return {
    raw: trimmed2,
    toolName: canonicalName,
    specifier,
    specifierKind
  };
}
function parseRules(raws) {
  return raws.filter((r5) => r5 && r5.trim()).map(parseRule).map((r5) => {
    if (r5.invalid) {
      debugLogger33.warn(`Ignoring malformed rule (unbalanced parentheses): ${r5.raw}`);
    }
    return r5;
  });
}
function getRuleDisplayName(canonicalToolName) {
  return CANONICAL_TO_RULE_DISPLAY[canonicalToolName] ?? canonicalToolName;
}
function buildPermissionRules(ctx) {
  const canonicalName = resolveToolName(ctx.toolName);
  const displayName = getRuleDisplayName(canonicalName);
  const kind2 = getSpecifierKind(canonicalName);
  switch (kind2) {
    case "command":
      if (ctx.command) {
        return [`${displayName}(${ctx.command})`];
      }
      return [displayName];
    case "path":
      if (ctx.filePath) {
        const dirPath = FILE_TARGETED_TOOLS.has(canonicalName) ? path32.dirname(ctx.filePath) : ctx.filePath;
        const specifier = dirPath.startsWith("/") ? `/${dirPath}/**` : `${dirPath}/**`;
        return [`${displayName}(${specifier})`];
      }
      return [displayName];
    case "domain":
      if (ctx.domain) {
        return [`${displayName}(${ctx.domain})`];
      }
      return [displayName];
    case "literal":
    default:
      if (ctx.specifier) {
        return [`${displayName}(${ctx.specifier})`];
      }
      return [displayName];
  }
}
function cleanPathSpecifier(specifier) {
  let cleaned = specifier;
  cleaned = cleaned.replace(/\/\*\*$/, "/").replace(/\/\*$/, "/");
  if (cleaned.startsWith("//")) {
    cleaned = cleaned.substring(1);
  }
  if (!cleaned.endsWith("/")) {
    cleaned += "/";
  }
  return cleaned;
}
function buildHumanReadableRuleLabel(rules) {
  if (!rules.length)
    return "";
  const parts2 = [];
  for (const rule of rules) {
    const parenIdx = rule.indexOf("(");
    if (parenIdx === -1) {
      const verb2 = DISPLAY_NAME_TO_VERB[rule] ?? rule.toLowerCase();
      parts2.push(verb2);
      continue;
    }
    const displayName = rule.substring(0, parenIdx);
    const specifier = rule.substring(parenIdx + 1, rule.length - 1);
    const verb = DISPLAY_NAME_TO_VERB[displayName] ?? displayName.toLowerCase();
    const canonicalName = Object.entries(CANONICAL_TO_RULE_DISPLAY).find(([, v2]) => v2 === displayName)?.[0];
    const kind2 = canonicalName ? getSpecifierKind(canonicalName) : "literal";
    switch (kind2) {
      case "path": {
        const cleanPath = cleanPathSpecifier(specifier);
        parts2.push(`${verb} in ${cleanPath}`);
        break;
      }
      case "command":
        parts2.push(`run '${specifier}' commands`);
        break;
      case "domain":
        parts2.push(`${verb} ${specifier}`);
        break;
      case "literal":
      default:
        parts2.push(`${verb} "${specifier}"`);
        break;
    }
  }
  return parts2.join(", ");
}
function splitCompoundCommand(command2) {
  const commands = [];
  let inSingle = false;
  let inDouble = false;
  let escaped = false;
  let lastSplit = 0;
  for (let i4 = 0; i4 < command2.length; i4++) {
    const ch = command2[i4];
    if (escaped) {
      escaped = false;
      continue;
    }
    if (ch === "\\") {
      escaped = true;
      continue;
    }
    if (ch === "'" && !inDouble) {
      inSingle = !inSingle;
      continue;
    }
    if (ch === '"' && !inSingle) {
      inDouble = !inDouble;
      continue;
    }
    if (inSingle || inDouble) {
      continue;
    }
    for (const op of SHELL_OPERATORS) {
      if (command2.substring(i4, i4 + op.length) === op) {
        const segment = command2.substring(lastSplit, i4).trim();
        if (segment) {
          commands.push(segment);
        }
        lastSplit = i4 + op.length;
        i4 = lastSplit - 1;
        break;
      }
    }
  }
  const lastSegment = command2.substring(lastSplit).trim();
  if (lastSegment) {
    commands.push(lastSegment);
  }
  return commands.length > 0 ? commands : [command2];
}
function matchesCommandPattern(pattern, command2) {
  const normalizedCommand = stripLeadingVariableAssignments(command2);
  if (pattern === "*") {
    return true;
  }
  if (!pattern.includes("*")) {
    return normalizedCommand === pattern || normalizedCommand.startsWith(pattern + " ");
  }
  let regex3 = "^";
  let pos2 = 0;
  while (pos2 < pattern.length) {
    const starIdx = pattern.indexOf("*", pos2);
    if (starIdx === -1) {
      regex3 += escapeRegex(pattern.substring(pos2));
      break;
    }
    const literalBefore = pattern.substring(pos2, starIdx);
    if (starIdx > 0 && pattern[starIdx - 1] === " ") {
      const literalWithoutTrailingSpace = literalBefore.slice(0, -1);
      regex3 += escapeRegex(literalWithoutTrailingSpace);
      regex3 += "( .*)?";
    } else {
      regex3 += escapeRegex(literalBefore);
      regex3 += ".*";
    }
    pos2 = starIdx + 1;
  }
  regex3 += "$";
  try {
    return new RegExp(regex3, "s").test(normalizedCommand);
  } catch {
    return normalizedCommand === pattern;
  }
}
function escapeRegex(s5) {
  return s5.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
}
function stripLeadingVariableAssignments(command2) {
  const trimmed2 = command2.trim();
  if (!trimmed2) {
    return trimmed2;
  }
  try {
    const tokens = [];
    for (const token2 of (0, import_shell_quote3.parse)(trimmed2)) {
      if (typeof token2 === "string") {
        tokens.push(token2);
      } else if (token2 && typeof token2 === "object" && "op" in token2 && typeof token2.op === "string") {
        tokens.push(token2.op);
      }
    }
    let firstCommandToken = 0;
    while (firstCommandToken < tokens.length && ENV_ASSIGNMENT_REGEX3.test(tokens[firstCommandToken])) {
      firstCommandToken++;
    }
    return tokens.slice(firstCommandToken).join(" ");
  } catch {
    return trimmed2;
  }
}
function resolvePathPattern(specifier, projectRoot, cwd6) {
  if (specifier.startsWith("//")) {
    return specifier.substring(1);
  }
  if (specifier.startsWith("~/")) {
    return toPosixPath(path32.join(os15.homedir(), specifier.substring(2)));
  }
  if (specifier.startsWith("/")) {
    return toPosixPath(path32.join(projectRoot, specifier.substring(1)));
  }
  if (specifier.startsWith("./")) {
    return toPosixPath(path32.join(cwd6, specifier.substring(2)));
  }
  return toPosixPath(path32.join(cwd6, specifier));
}
function matchesPathPattern(specifier, filePath, projectRoot, cwd6) {
  const resolvedPattern = resolvePathPattern(specifier, projectRoot, cwd6);
  const normalizedFilePath = toPosixPath(filePath);
  const isMatch = (0, import_picomatch.default)(resolvedPattern, {
    dot: true,
    // Match dotfiles (e.g. .env)
    nocase: false
    // Case-sensitive (filesystem convention)
    // Note: do NOT set bash: true — it makes `*` match across directories.
    // Default picomatch behavior is gitignore-style: `*` = single dir, `**` = recursive.
  });
  return isMatch(normalizedFilePath);
}
function matchesDomainPattern(specifier, domain2) {
  const pattern = specifier.startsWith("domain:") ? specifier.substring(7).trim() : specifier.trim();
  if (!pattern || !domain2) {
    return false;
  }
  const normalizedDomain = domain2.toLowerCase();
  const normalizedPattern = pattern.toLowerCase();
  if (normalizedDomain === normalizedPattern) {
    return true;
  }
  if (normalizedDomain.endsWith("." + normalizedPattern)) {
    return true;
  }
  return false;
}
function matchesMcpPattern(pattern, toolName) {
  if (pattern === toolName) {
    return true;
  }
  if (pattern.endsWith("*")) {
    const prefix = pattern.slice(0, -1);
    return toolName.startsWith(prefix);
  }
  const patternParts = pattern.split("__");
  const toolParts = toolName.split("__");
  if (patternParts.length === 2 && toolParts.length >= 3 && patternParts[0] === toolParts[0] && patternParts[1] === toolParts[1]) {
    return true;
  }
  return false;
}
function matchesRule(rule, toolName, command2, filePath, domain2, pathContext, specifier) {
  const canonicalCtxToolName = resolveToolName(toolName);
  if (rule.invalid) {
    return false;
  }
  if (rule.toolName.startsWith("mcp__") || canonicalCtxToolName.startsWith("mcp__")) {
    return matchesMcpPattern(rule.toolName, canonicalCtxToolName);
  }
  if (!toolMatchesRuleToolName(rule.toolName, canonicalCtxToolName)) {
    return false;
  }
  if (!rule.specifier) {
    return true;
  }
  const kind2 = rule.specifierKind ?? getSpecifierKind(rule.toolName);
  switch (kind2) {
    case "command": {
      if (command2 === void 0) {
        return false;
      }
      return matchesCommandPattern(rule.specifier, command2);
    }
    case "path": {
      if (filePath === void 0) {
        return false;
      }
      const ctx = pathContext ?? {
        projectRoot: process.cwd(),
        cwd: process.cwd()
      };
      return matchesPathPattern(rule.specifier, filePath, ctx.projectRoot, ctx.cwd);
    }
    case "domain": {
      if (domain2 === void 0) {
        return false;
      }
      return matchesDomainPattern(rule.specifier, domain2);
    }
    case "literal":
    default: {
      const value = command2 ?? specifier;
      if (value !== void 0) {
        return value === rule.specifier;
      }
      return false;
    }
  }
}
var import_picomatch, import_shell_quote3, debugLogger33, TOOL_NAME_ALIASES, SHELL_TOOL_NAMES3, READ_TOOLS, EDIT_TOOLS, WEBFETCH_TOOLS, CANONICAL_TO_RULE_DISPLAY, FILE_TARGETED_TOOLS, DISPLAY_NAME_TO_VERB, SHELL_OPERATORS, ENV_ASSIGNMENT_REGEX3;
var init_rule_parser = __esm({
  "packages/core/dist/src/permissions/rule-parser.js"() {
    "use strict";
    init_esbuild_shims();
    import_picomatch = __toESM(require_picomatch2(), 1);
    import_shell_quote3 = __toESM(require_shell_quote(), 1);
    init_debugLogger();
    debugLogger33 = createDebugLogger("PERMISSIONS");
    __name(toPosixPath, "toPosixPath");
    TOOL_NAME_ALIASES = {
      // Shell tool
      run_shell_command: "run_shell_command",
      Shell: "run_shell_command",
      ShellTool: "run_shell_command",
      Bash: "run_shell_command",
      // Claude Code compatibility
      // Edit tool — "Edit" is also a meta-category covering edit + write_file
      edit: "edit",
      Edit: "edit",
      EditTool: "edit",
      // Write File tool — also matched by "Edit" meta-category rules
      write_file: "write_file",
      WriteFile: "write_file",
      WriteFileTool: "write_file",
      Write: "write_file",
      // Read File tool — "Read" is also a meta-category covering read_file + grep + glob + list_directory
      read_file: "read_file",
      ReadFile: "read_file",
      ReadFileTool: "read_file",
      Read: "read_file",
      // Grep tool — also matched by "Read" meta-category rules
      grep_search: "grep_search",
      Grep: "grep_search",
      GrepTool: "grep_search",
      search_file_content: "grep_search",
      // legacy
      SearchFiles: "grep_search",
      // legacy display name
      // Glob tool — also matched by "Read" meta-category rules
      glob: "glob",
      Glob: "glob",
      GlobTool: "glob",
      FindFiles: "glob",
      // legacy display name
      // List Directory tool — also matched by "Read" meta-category rules
      list_directory: "list_directory",
      ListFiles: "list_directory",
      ListFilesTool: "list_directory",
      ReadFolder: "list_directory",
      // legacy display name
      // TodoWrite tool
      todo_write: "todo_write",
      TodoWrite: "todo_write",
      TodoWriteTool: "todo_write",
      // WebFetch tool
      web_fetch: "web_fetch",
      WebFetch: "web_fetch",
      WebFetchTool: "web_fetch",
      // Agent (subagent) tool
      agent: "agent",
      Agent: "agent",
      AgentTool: "agent",
      // Legacy aliases for the agent tool (renamed from "task")
      task: "agent",
      Task: "agent",
      TaskTool: "agent",
      // Skill tool
      skill: "skill",
      Skill: "skill",
      SkillTool: "skill",
      // ExitPlanMode tool
      exit_plan_mode: "exit_plan_mode",
      ExitPlanMode: "exit_plan_mode",
      ExitPlanModeTool: "exit_plan_mode",
      // LSP tool
      lsp: "lsp",
      Lsp: "lsp",
      LspTool: "lsp",
      // Legacy edit tool name
      replace: "edit"
    };
    SHELL_TOOL_NAMES3 = /* @__PURE__ */ new Set(["run_shell_command"]);
    READ_TOOLS = /* @__PURE__ */ new Set([
      "read_file",
      "grep_search",
      "glob",
      "list_directory"
    ]);
    EDIT_TOOLS = /* @__PURE__ */ new Set(["edit", "write_file"]);
    WEBFETCH_TOOLS = /* @__PURE__ */ new Set(["web_fetch"]);
    __name(resolveToolName, "resolveToolName");
    __name(getSpecifierKind, "getSpecifierKind");
    __name(toolMatchesRuleToolName, "toolMatchesRuleToolName");
    __name(parseRule, "parseRule");
    __name(parseRules, "parseRules");
    CANONICAL_TO_RULE_DISPLAY = {
      // Read meta-category
      read_file: "Read",
      grep_search: "Read",
      glob: "Read",
      list_directory: "Read",
      // Edit meta-category
      edit: "Edit",
      write_file: "Edit",
      // Shell
      run_shell_command: "Bash",
      // Web
      web_fetch: "WebFetch",
      // Agent / Skill
      agent: "Agent",
      skill: "Skill",
      // Others
      save_memory: "SaveMemory",
      todo_write: "TodoWrite",
      lsp: "Lsp",
      exit_plan_mode: "ExitPlanMode"
    };
    __name(getRuleDisplayName, "getRuleDisplayName");
    FILE_TARGETED_TOOLS = /* @__PURE__ */ new Set(["read_file", "edit", "write_file"]);
    __name(buildPermissionRules, "buildPermissionRules");
    DISPLAY_NAME_TO_VERB = {
      Read: "read files",
      Edit: "edit files",
      Bash: "run commands",
      WebFetch: "fetch from",
      Agent: "use agent",
      Skill: "use skill",
      SaveMemory: "save memory",
      TodoWrite: "write todos",
      Lsp: "use LSP",
      ExitPlanMode: "exit plan mode"
    };
    __name(cleanPathSpecifier, "cleanPathSpecifier");
    __name(buildHumanReadableRuleLabel, "buildHumanReadableRuleLabel");
    SHELL_OPERATORS = ["&&", "||", ";;", "|&", "|", ";"];
    __name(splitCompoundCommand, "splitCompoundCommand");
    __name(matchesCommandPattern, "matchesCommandPattern");
    __name(escapeRegex, "escapeRegex");
    ENV_ASSIGNMENT_REGEX3 = /^[A-Za-z_][A-Za-z0-9_]*=/;
    __name(stripLeadingVariableAssignments, "stripLeadingVariableAssignments");
    __name(resolvePathPattern, "resolvePathPattern");
    __name(matchesPathPattern, "matchesPathPattern");
    __name(matchesDomainPattern, "matchesDomainPattern");
    __name(matchesMcpPattern, "matchesMcpPattern");
    __name(matchesRule, "matchesRule");
  }
});

// packages/core/dist/src/core/permission-helpers.js
import * as path33 from "node:path";
function buildPermissionCheckContext(toolName, toolParams, targetDir) {
  const command2 = "command" in toolParams ? String(toolParams["command"]) : void 0;
  let filePath = typeof toolParams["file_path"] === "string" ? toolParams["file_path"] : void 0;
  if (filePath === void 0 && typeof toolParams["path"] === "string") {
    filePath = path33.isAbsolute(toolParams["path"]) ? toolParams["path"] : path33.resolve(targetDir, toolParams["path"]);
  }
  let domain2;
  if (typeof toolParams["url"] === "string") {
    try {
      domain2 = new URL(toolParams["url"]).hostname;
    } catch {
    }
  }
  const specifier = typeof toolParams["skill"] === "string" ? toolParams["skill"] : typeof toolParams["subagent_type"] === "string" ? toolParams["subagent_type"] : void 0;
  return { toolName, command: command2, filePath, domain: domain2, specifier };
}
async function evaluatePermissionRules(pm, defaultPermission, pmCtx) {
  let finalPermission = defaultPermission;
  let pmForcedAsk = false;
  if (pm && defaultPermission !== "deny") {
    if (pm.hasRelevantRules(pmCtx)) {
      const pmDecision = await pm.evaluate(pmCtx);
      if (pmDecision !== "default") {
        finalPermission = pmDecision;
        if (pmDecision === "ask" && pm.hasMatchingAskRule(pmCtx)) {
          pmForcedAsk = true;
        }
      }
    }
  }
  return { finalPermission, pmForcedAsk };
}
function injectPermissionRulesIfMissing(confirmationDetails, pmCtx) {
  if ((confirmationDetails.type === "exec" || confirmationDetails.type === "mcp" || confirmationDetails.type === "info") && !confirmationDetails.permissionRules) {
    confirmationDetails.permissionRules = buildPermissionRules(pmCtx);
  }
}
async function persistPermissionOutcome(outcome, confirmationDetails, persistFn, pm, payload) {
  if (outcome !== ToolConfirmationOutcome.ProceedAlways && outcome !== ToolConfirmationOutcome.ProceedAlwaysProject && outcome !== ToolConfirmationOutcome.ProceedAlwaysUser) {
    return;
  }
  const scope = outcome === ToolConfirmationOutcome.ProceedAlwaysUser ? "user" : "project";
  const detailsRules = confirmationDetails?.["permissionRules"];
  const payloadRules = payload?.permissionRules;
  const rules = payloadRules ?? detailsRules ?? [];
  if (rules.length > 0) {
    for (const rule of rules) {
      if (persistFn) {
        await persistFn(scope, "allow", rule);
      }
      pm?.addPersistentRule(rule, "allow");
    }
  }
}
var init_permission_helpers = __esm({
  "packages/core/dist/src/core/permission-helpers.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_rule_parser();
    __name(buildPermissionCheckContext, "buildPermissionCheckContext");
    __name(evaluatePermissionRules, "evaluatePermissionRules");
    __name(injectPermissionRulesIfMissing, "injectPermissionRulesIfMissing");
    __name(persistPermissionOutcome, "persistPermissionOutcome");
  }
});

// packages/core/dist/src/utils/editor.js
import { execSync as execSync3, spawn, spawnSync } from "node:child_process";
import { existsSync as existsSync6 } from "node:fs";
import { homedir as homedir8 } from "node:os";
import { join as join11 } from "node:path";
function isValidEditorType(editor) {
  return [
    "vscode",
    "vscodium",
    "windsurf",
    "cursor",
    "vim",
    "neovim",
    "zed",
    "emacs",
    "trae"
  ].includes(editor);
}
function commandExists(cmd) {
  try {
    execSync3(process.platform === "win32" ? `where.exe ${cmd}` : `command -v ${cmd}`, { stdio: "ignore" });
    return true;
  } catch {
    return false;
  }
}
function getZedAppPaths() {
  return ["/Applications/Zed.app", join11(homedir8(), "Applications/Zed.app")];
}
function getZedCommand() {
  const commands = editorCommands.zed.default;
  for (const cmd of commands) {
    if (commandExists(cmd)) {
      return cmd;
    }
  }
  if (process.platform === "darwin") {
    for (const appPath of getZedAppPaths()) {
      const cliPath = join11(appPath, "Contents/MacOS/cli");
      if (existsSync6(cliPath)) {
        return cliPath;
      }
    }
  }
  return null;
}
function getEditorExecutable(editorType) {
  const commandConfig = editorCommands[editorType];
  const commands = process.platform === "win32" ? commandConfig.win32 : commandConfig.default;
  const found = commands.find((cmd) => commandExists(cmd));
  if (found) {
    return found;
  }
  if (editorType === "zed" && process.platform === "darwin") {
    for (const appPath of getZedAppPaths()) {
      const cliPath = join11(appPath, "Contents/MacOS/cli");
      if (existsSync6(cliPath)) {
        return cliPath;
      }
    }
  }
  return null;
}
function checkHasEditorType(editor) {
  return getEditorExecutable(editor) !== null;
}
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;
  }
  if (editor === "zed") {
    const zedCmd = getZedCommand();
    if (!zedCmd) {
      return null;
    }
    return { command: zedCmd, args: ["--wait", "--diff", oldPath, newPath] };
  }
  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 "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) {
    debugLogger34.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((resolve42, reject) => {
      const childProcess3 = spawn(diffCommand.command, diffCommand.args, {
        stdio: "inherit",
        shell: process.platform === "win32"
      });
      childProcess3.on("close", (code2) => {
        if (code2 === 0) {
          resolve42();
        } else {
          reject(new Error(`${editor} exited with code ${code2}`));
        }
      });
      childProcess3.on("error", (error40) => {
        reject(error40);
      });
    });
  } catch (error40) {
    debugLogger34.error(error40);
    throw error40;
  }
}
var debugLogger34, editorCommands;
var init_editor = __esm({
  "packages/core/dist/src/utils/editor.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger34 = createDebugLogger("EDITOR");
    __name(isValidEditorType, "isValidEditorType");
    __name(commandExists, "commandExists");
    __name(getZedAppPaths, "getZedAppPaths");
    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(getZedCommand, "getZedCommand");
    __name(getEditorExecutable, "getEditorExecutable");
    __name(checkHasEditorType, "checkHasEditorType");
    __name(allowEditorTypeInSandbox, "allowEditorTypeInSandbox");
    __name(isEditorAvailable, "isEditorAvailable");
    __name(getDiffCommand, "getDiffCommand");
    __name(openDiff, "openDiff");
  }
});

// node_modules/diff/lib/index.mjs
function Diff() {
}
function buildValues(diff4, lastComponent, newString, oldString, useLongestToken) {
  var components = [];
  var nextComponent;
  while (lastComponent) {
    components.push(lastComponent);
    nextComponent = lastComponent.previousComponent;
    delete lastComponent.previousComponent;
    lastComponent = nextComponent;
  }
  components.reverse();
  var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
  for (; componentPos < componentLen; componentPos++) {
    var component = components[componentPos];
    if (!component.removed) {
      if (!component.added && useLongestToken) {
        var value = newString.slice(newPos, newPos + component.count);
        value = value.map(function(value2, i4) {
          var oldValue = oldString[oldPos + i4];
          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 i4;
  for (i4 = 0; i4 < str1.length && i4 < str2.length; i4++) {
    if (str1[i4] != str2[i4]) {
      return str1.slice(0, i4);
    }
  }
  return str1.slice(0, i4);
}
function longestCommonSuffix(str1, str2) {
  var i4;
  if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {
    return "";
  }
  for (i4 = 0; i4 < str1.length && i4 < str2.length; i4++) {
    if (str1[str1.length - (i4 + 1)] != str2[str2.length - (i4 + 1)]) {
      return str1.slice(-i4);
    }
  }
  return str1.slice(-i4);
}
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 map3 = Array(endB);
  var k2 = 0;
  map3[0] = 0;
  for (var j2 = 1; j2 < endB; j2++) {
    if (b2[j2] == b2[k2]) {
      map3[j2] = map3[k2];
    } else {
      map3[j2] = k2;
    }
    while (k2 > 0 && b2[j2] != b2[k2]) {
      k2 = map3[k2];
    }
    if (b2[j2] == b2[k2]) {
      k2++;
    }
  }
  k2 = 0;
  for (var i4 = startA; i4 < a2.length; i4++) {
    while (k2 > 0 && a2[i4] != b2[k2]) {
      k2 = map3[k2];
    }
    if (a2[i4] == 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 i4 = e4.call(t5, r5 || "default");
    if ("object" != typeof i4) return i4;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r5 ? String : Number)(t5);
}
function _toPropertyKey(t5) {
  var i4 = _toPrimitive(t5, "string");
  return "symbol" == typeof i4 ? i4 : i4 + "";
}
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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) arr2[i4] = arr[i4];
  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 i4;
  for (i4 = 0; i4 < stack.length; i4 += 1) {
    if (stack[i4] === obj) {
      return replacementStack[i4];
    }
  }
  var canonicalizedObj;
  if ("[object Array]" === Object.prototype.toString.call(obj)) {
    stack.push(obj);
    canonicalizedObj = new Array(obj.length);
    replacementStack.push(canonicalizedObj);
    for (i4 = 0; i4 < obj.length; i4 += 1) {
      canonicalizedObj[i4] = canonicalize(obj[i4], 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 (i4 = 0; i4 < sortedKeys.length; i4 += 1) {
      _key = sortedKeys[i4];
      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[i4], lines = current.lines || splitLines(current.value);
      current.lines = lines;
      if (current.added || current.removed) {
        var _curRange;
        if (!oldRangeStart) {
          var prev = diff4[i4 - 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 && i4 < 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 i4 = 0; i4 < diff4.length; i4++) {
      _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 i4 = 0; i4 < diff4.hunks.length; i4++) {
    var hunk = diff4.hunks[i4];
    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 exec6() {
            setTimeout(function() {
              if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
                return callback();
              }
              if (!execEditLength()) {
                exec6();
              }
            }, 0);
          }, "exec"))();
        } else {
          while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
            var ret = execEditLength();
            if (ret) {
              return ret;
            }
          }
        }
      }, "diff"),
      addToPath: /* @__PURE__ */ __name(function addToPath(path150, added, removed, oldPosInc, options2) {
        var last2 = path150.lastComponent;
        if (last2 && !options2.oneChangePerToken && last2.added === added && last2.removed === removed) {
          return {
            oldPos: path150.oldPos + oldPosInc,
            lastComponent: {
              count: last2.count + 1,
              added,
              removed,
              previousComponent: last2.previousComponent
            }
          };
        } else {
          return {
            oldPos: path150.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 i4 = 0; i4 < array2.length; i4++) {
          if (array2[i4]) {
            ret.push(array2[i4]);
          }
        }
        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 join12(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 parts2;
      if (options2.intlSegmenter) {
        if (options2.intlSegmenter.resolvedOptions().granularity != "word") {
          throw new Error('The segmenter passed must have a granularity of "word"');
        }
        parts2 = Array.from(options2.intlSegmenter.segment(value), function(segment) {
          return segment.segment;
        });
      } else {
        parts2 = value.match(tokenizeIncludingWhitespace) || [];
      }
      var tokens = [];
      var prevPart = null;
      parts2.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, i4) {
        if (i4 == 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 i4 = 0; i4 < linesAndNewlines.length; i4++) {
        var line = linesAndNewlines[i4];
        if (i4 % 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/modifiable-tool.js
import os16 from "node:os";
import path34 from "node:path";
import fs38 from "node:fs";
function isModifiableDeclarativeTool(tool) {
  return "getModifyContext" in tool;
}
function createTempFilesForModify(currentContent, proposedContent, file_path) {
  const tempDir = os16.tmpdir();
  const diffDir = path34.join(tempDir, "qwen-code-tool-modify-diffs");
  if (!fs38.existsSync(diffDir)) {
    fs38.mkdirSync(diffDir, { recursive: true });
  }
  const ext2 = path34.extname(file_path);
  const fileName = path34.basename(file_path, ext2);
  const timestamp = Date.now();
  const tempOldPath = path34.join(diffDir, `qwen-code-modify-${fileName}-old-${timestamp}${ext2}`);
  const tempNewPath = path34.join(diffDir, `qwen-code-modify-${fileName}-new-${timestamp}${ext2}`);
  fs38.writeFileSync(tempOldPath, currentContent, "utf8");
  fs38.writeFileSync(tempNewPath, proposedContent, "utf8");
  return { oldPath: tempOldPath, newPath: tempNewPath };
}
function getUpdatedParams(tmpOldPath, tempNewPath, originalParams, modifyContext) {
  let oldContent = "";
  let newContent = "";
  try {
    oldContent = fs38.readFileSync(tmpOldPath, "utf8");
  } catch (err2) {
    if (!isNodeError(err2) || err2.code !== "ENOENT")
      throw err2;
    oldContent = "";
  }
  try {
    newContent = fs38.readFileSync(tempNewPath, "utf8");
  } catch (err2) {
    if (!isNodeError(err2) || err2.code !== "ENOENT")
      throw err2;
    newContent = "";
  }
  const updatedParams = modifyContext.createUpdatedParams(oldContent, newContent, originalParams);
  const updatedDiff = createPatch(path34.basename(modifyContext.getFilePath(originalParams)), oldContent, newContent, "Current", "Proposed", DEFAULT_DIFF_OPTIONS);
  return { updatedParams, updatedDiff };
}
function deleteTempFiles(oldPath, newPath) {
  try {
    fs38.unlinkSync(oldPath);
  } catch {
    debugLogger35.warn(`Error deleting temp diff file: ${oldPath}`);
  }
  try {
    fs38.unlinkSync(newPath);
  } catch {
    debugLogger35.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 debugLogger35;
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();
    debugLogger35 = createDebugLogger("MODIFIABLE_TOOL");
    __name(isModifiableDeclarativeTool, "isModifiableDeclarativeTool");
    __name(createTempFilesForModify, "createTempFilesForModify");
    __name(getUpdatedParams, "getUpdatedParams");
    __name(deleteTempFiles, "deleteTempFiles");
    __name(modifyWithEditor, "modifyWithEditor");
  }
});

// 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 (err2) {
        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, i4, j2, tmp;
          for (i4 = 0; i4 < str2Len; ++i4) {
            prevRow[i4] = i4;
            str2Char[i4] = str2.charCodeAt(i4);
          }
          prevRow[str2Len] = str2Len;
          var strCmp;
          if (useCollator) {
            for (i4 = 0; i4 < str1Len; ++i4) {
              nextCol = i4 + 1;
              for (j2 = 0; j2 < str2Len; ++j2) {
                curCol = nextCol;
                strCmp = 0 === collator.compare(str1.charAt(i4), 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 (i4 = 0; i4 < str1Len; ++i4) {
              nextCol = i4 + 1;
              for (j2 = 0; j2 < str2Len; ++j2) {
                curCol = nextCol;
                strCmp = str1.charCodeAt(i4) === 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;
      }
    })();
  }
});

// node_modules/ansi-regex/index.js
var ansi_regex_exports = {};
__export(ansi_regex_exports, {
  default: () => ansiRegex
});
function ansiRegex({ onlyFirst = false } = {}) {
  const ST2 = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
  const osc2 = `(?:\\u001B\\][\\s\\S]*?${ST2})`;
  const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
  const pattern = `${osc2}|${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 stripAnsi2(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(stripAnsi2, "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");
  }
});

// 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;
}
function normalizeContent(content) {
  let normalized2 = content.replace(/^\uFEFF/, "");
  normalized2 = normalized2.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  return normalized2;
}
var init_textUtils = __esm({
  "packages/core/dist/src/utils/textUtils.js"() {
    "use strict";
    init_esbuild_shims();
    __name(safeLiteralReplace, "safeLiteralReplace");
    __name(isBinary, "isBinary");
    __name(normalizeContent, "normalizeContent");
  }
});

// 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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CircularList = void 0;
        const s6 = i5(460), r6 = i5(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 i6 = 0; i6 < Math.min(e6, this.length); i6++) t7[i6] = this._array[this._getCyclicIndex(i6)];
            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, ...i6) {
            if (t7) {
              for (let i7 = e6; i7 < this._length - t7; i7++) this._array[this._getCyclicIndex(i7)] = this._array[this._getCyclicIndex(i7 + 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 + i6.length)] = this._array[this._getCyclicIndex(t8)];
            for (let t8 = 0; t8 < i6.length; t8++) this._array[this._getCyclicIndex(e6 + t8)] = i6[t8];
            if (i6.length && this.onInsertEmitter.fire({ index: e6, amount: i6.length }), this._length + i6.length > this._maxLength) {
              const e7 = this._length + i6.length - this._maxLength;
              this._startIndex += e7, this._length = this._maxLength, this.onTrimEmitter.fire(e7);
            } else this._length += i6.length;
          }
          trimStart(e6) {
            e6 > this._length && (e6 = this._length), this._startIndex += e6, this._length -= e6, this.onTrimEmitter.fire(e6);
          }
          shiftElements(e6, t7, i6) {
            if (!(t7 <= 0)) {
              if (e6 < 0 || e6 >= this._length) throw new Error("start argument out of range");
              if (e6 + i6 < 0) throw new Error("Cannot shift elements in list beyond index 0");
              if (i6 > 0) {
                for (let s8 = t7 - 1; s8 >= 0; s8--) this.set(e6 + s8 + i6, this.get(e6 + s8));
                const s7 = e6 + t7 + i6 - 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 + i6, 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, i5 = 5) {
          if ("object" != typeof t7) return t7;
          const s6 = Array.isArray(t7) ? [] : {};
          for (const r6 in t7) s6[r6] = i5 <= 1 ? t7[r6] : t7[r6] && e6(t7[r6], i5 - 1);
          return s6;
        }, "e");
      }, 969: (e5, t6, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CoreTerminal = void 0;
        const s6 = i5(844), r6 = i5(585), n4 = i5(348), a2 = i5(866), o3 = i5(744), h3 = i5(302), c4 = i5(83), l3 = i5(460), _2 = i5(753), d2 = i5(480), f5 = i5(994), u2 = i5(282), p2 = i5(435), g2 = i5(981), v2 = i5(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, i6) {
            this._bufferService.scrollLines(e6, t7, i6);
          }
          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 i5 = [];
            for (let e7 = 0; e7 < this._listeners.length; e7++) i5.push(this._listeners[e7]);
            for (let s6 = 0; s6 < i5.length; s6++) i5[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, i5) {
        var s6 = this && this.__decorate || function(e6, t7, i6, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i6) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i6, s7);
          else for (var o4 = e6.length - 1; o4 >= 0; o4--) (r7 = e6[o4]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i6, a3) : r7(t7, i6)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i6, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i6, s7) {
            t7(i6, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.InputHandler = t6.WindowsOptionsReportType = void 0;
        const n4 = i5(584), a2 = i5(116), o3 = i5(15), h3 = i5(844), c4 = i5(482), l3 = i5(437), _2 = i5(460), d2 = i5(643), f5 = i5(511), u2 = i5(734), p2 = i5(585), g2 = i5(480), v2 = i5(242), b2 = i5(351), S4 = i5(941), m3 = { "(": 0, ")": 1, "*": 2, "+": 3, "-": 1, ".": 2 }, C3 = 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, i6, s7, r7, h4, d3, u3, p3 = new o3.EscapeSequenceParser()) {
            super(), this._bufferService = e6, this._charsetService = t7, this._coreService = i6, 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, i7) => {
              this._logService.debug("Unknown OSC code: ", { identifier: e7, action: t8, data: i7 });
            }), this._parser.setDcsHandlerFallback((e7, t8, i7) => {
              "HOOK" === t8 && (i7 = i7.toArray()), this._logService.debug("Unknown DCS code: ", { identifier: this._parser.identToString(e7), action: t8, payload: i7 });
            }), this._parser.setPrintHandler((e7, t8, i7) => this.print(e7, t8, i7)), 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, i6, s7) {
            this._parseStack.paused = true, this._parseStack.cursorStartX = e6, this._parseStack.cursorStartY = t7, this._parseStack.decodedLength = i6, 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 i6, s7 = this._activeBuffer.x, r7 = this._activeBuffer.y, n5 = 0;
            const a3 = this._parseStack.paused;
            if (a3) {
              if (i6 = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, t7)) return this._logSlowResolvingAsync(i6), i6;
              s7 = this._parseStack.cursorStartX, r7 = this._parseStack.cursorStartY, this._parseStack.paused = false, e6.length > C3 && (n5 = this._parseStack.position + C3);
            }
            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 < C3 && (this._parseBuffer = new Uint32Array(Math.min(e6.length, C3))), a3 || this._dirtyRowTracker.clearRange(), e6.length > C3) for (let t8 = n5; t8 < e6.length; t8 += C3) {
              const n6 = t8 + C3 < e6.length ? t8 + C3 : 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 (i6 = this._parser.parse(this._parseBuffer, a4)) return this._preserveStack(s7, r7, a4, t8), this._logSlowResolvingAsync(i6), i6;
            }
            else if (!a3) {
              const t8 = "string" == typeof e6 ? this._stringDecoder.decode(e6, this._parseBuffer) : this._utf8Decoder.decode(e6, this._parseBuffer);
              if (i6 = this._parser.parse(this._parseBuffer, t8)) return this._preserveStack(s7, r7, t8, 0), this._logSlowResolvingAsync(i6), i6;
            }
            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, i6) {
            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 && i6 - 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 < i6; ++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 i7 = g2.UnicodeService.extractShouldJoin(t8), b3 = i7 ? 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 (i7 && 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 && i6 - 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, i6, s7 = false, r7 = false) {
            const n5 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e6);
            n5.replaceCells(t7, i6, this._activeBuffer.getNullCell(this._eraseAttrData()), r7), s7 && (n5.isWrapped = false);
          }
          _resetBufferLine(e6, t7 = false) {
            const i6 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e6);
            i6 && (i6.fill(this._activeBuffer.getNullCell(this._eraseAttrData()), t7), this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase + e6), i6.isWrapped = false);
          }
          eraseInDisplay(e6, t7 = false) {
            let i6;
            switch (this._restrictCursor(this._bufferService.cols), e6.params[0]) {
              case 0:
                for (i6 = this._activeBuffer.y, this._dirtyRowTracker.markDirty(i6), this._eraseInBufferLine(i6++, this._activeBuffer.x, this._bufferService.cols, 0 === this._activeBuffer.x, t7); i6 < this._bufferService.rows; i6++) this._resetBufferLine(i6, t7);
                this._dirtyRowTracker.markDirty(i6);
                break;
              case 1:
                for (i6 = this._activeBuffer.y, this._dirtyRowTracker.markDirty(i6), this._eraseInBufferLine(i6, 0, this._activeBuffer.x + 1, true, t7), this._activeBuffer.x + 1 >= this._bufferService.cols && (this._activeBuffer.lines.get(i6 + 1).isWrapped = false); i6--; ) this._resetBufferLine(i6, t7);
                this._dirtyRowTracker.markDirty(0);
                break;
              case 2:
                for (i6 = this._bufferService.rows, this._dirtyRowTracker.markDirty(i6 - 1); i6--; ) this._resetBufferLine(i6, 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 i6 = 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(i6, 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 i6 = 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(i6, 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 i6 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e7);
              i6.deleteCells(0, t7, this._activeBuffer.getNullCell(this._eraseAttrData())), i6.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 i6 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e7);
              i6.insertCells(0, t7, this._activeBuffer.getNullCell(this._eraseAttrData())), i6.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 i6 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e7);
              i6.insertCells(this._activeBuffer.x, t7, this._activeBuffer.getNullCell(this._eraseAttrData())), i6.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 i6 = this._activeBuffer.lines.get(this._activeBuffer.ybase + e7);
              i6.deleteCells(this._activeBuffer.x, t7, this._activeBuffer.getNullCell(this._eraseAttrData())), i6.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 i6 = 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 * i6);
            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 < i6; ++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 i6 = 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(i6.applicationCursorKeys) : 3 === f6 ? _3.windowOptions.setWinLines ? 80 === h4 ? 2 : 132 === h4 ? 1 : 0 : 0 : 6 === f6 ? d3(i6.origin) : 7 === f6 ? d3(i6.wraparound) : 8 === f6 ? 3 : 9 === f6 ? d3("X10" === s7) : 12 === f6 ? d3(_3.cursorBlink) : 25 === f6 ? d3(!a3.isCursorHidden) : 45 === f6 ? d3(i6.reverseWraparound) : 66 === f6 ? d3(i6.applicationKeypad) : 67 === f6 ? 4 : 1e3 === f6 ? d3("VT200" === s7) : 1002 === f6 ? d3("DRAG" === s7) : 1003 === f6 ? d3("ANY" === s7) : 1004 === f6 ? d3(i6.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(i6.bracketedPasteMode) : 0, a3.triggerDataEvent(`${n4.C0.ESC}[${t7 ? "" : "?"}${u3};${p3}$y`), true;
            var u3, p3;
          }
          _updateAttrColor(e6, t7, i6, s7, r7) {
            return 2 === t7 ? (e6 |= 50331648, e6 &= -16777216, e6 |= u2.AttributeData.fromColorRGB([i6, s7, r7])) : 5 === t7 && (e6 &= -50331904, e6 |= 33554432 | 255 & i6), e6;
          }
          _extractColor(e6, t7, i6) {
            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 i7 = e6.getSubParams(t7 + n5);
                let a3 = 0;
                do {
                  5 === s7[1] && (r7 = 1), s7[n5 + a3 + 1 + r7] = i7[a3];
                } while (++a3 < i7.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:
                i6.fg = this._updateAttrColor(i6.fg, s7[1], s7[3], s7[4], s7[5]);
                break;
              case 48:
                i6.bg = this._updateAttrColor(i6.bg, s7[1], s7[3], s7[4], s7[5]);
                break;
              case 58:
                i6.extended = i6.extended.clone(), i6.extended.underlineColor = this._updateAttrColor(i6.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 i6;
            const s7 = this._curAttrData;
            for (let r7 = 0; r7 < t7; r7++) i6 = e6.params[r7], i6 >= 30 && i6 <= 37 ? (s7.fg &= -50331904, s7.fg |= 16777216 | i6 - 30) : i6 >= 40 && i6 <= 47 ? (s7.bg &= -50331904, s7.bg |= 16777216 | i6 - 40) : i6 >= 90 && i6 <= 97 ? (s7.fg &= -50331904, s7.fg |= 16777224 | i6 - 90) : i6 >= 100 && i6 <= 107 ? (s7.bg &= -50331904, s7.bg |= 16777224 | i6 - 100) : 0 === i6 ? this._processSGR0(s7) : 1 === i6 ? s7.fg |= 134217728 : 3 === i6 ? s7.bg |= 67108864 : 4 === i6 ? (s7.fg |= 268435456, this._processUnderline(e6.hasSubParams(r7) ? e6.getSubParams(r7)[0] : 1, s7)) : 5 === i6 ? s7.fg |= 536870912 : 7 === i6 ? s7.fg |= 67108864 : 8 === i6 ? s7.fg |= 1073741824 : 9 === i6 ? s7.fg |= 2147483648 : 2 === i6 ? s7.bg |= 134217728 : 21 === i6 ? this._processUnderline(2, s7) : 22 === i6 ? (s7.fg &= -134217729, s7.bg &= -134217729) : 23 === i6 ? s7.bg &= -67108865 : 24 === i6 ? (s7.fg &= -268435457, this._processUnderline(0, s7)) : 25 === i6 ? s7.fg &= -536870913 : 27 === i6 ? s7.fg &= -67108865 : 28 === i6 ? s7.fg &= -1073741825 : 29 === i6 ? s7.fg &= 2147483647 : 39 === i6 ? (s7.fg &= -67108864, s7.fg |= 16777215 & l3.DEFAULT_ATTR_DATA.fg) : 49 === i6 ? (s7.bg &= -67108864, s7.bg |= 16777215 & l3.DEFAULT_ATTR_DATA.bg) : 38 === i6 || 48 === i6 || 58 === i6 ? r7 += this._extractColor(e6, r7, s7) : 53 === i6 ? s7.bg |= 1073741824 : 55 === i6 ? s7.bg &= -1073741825 : 59 === i6 ? (s7.extended = s7.extended.clone(), s7.extended.underlineColor = -1, s7.updateExtended()) : 100 === i6 ? (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.", i6);
            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 i6 = t7 % 2 == 1;
            return this._optionsService.options.cursorBlink = i6, true;
          }
          setScrollRegion(e6) {
            const t7 = e6.params[0] || 1;
            let i6;
            return (e6.length < 2 || (i6 = e6.params[1]) > this._bufferService.rows || 0 === i6) && (i6 = this._bufferService.rows), i6 > t7 && (this._activeBuffer.scrollTop = t7 - 1, this._activeBuffer.scrollBottom = i6 - 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 = [], i6 = e6.split(";");
            for (; i6.length > 1; ) {
              const e7 = i6.shift(), s7 = i6.shift();
              if (/^\d+$/.exec(e7)) {
                const i7 = parseInt(e7);
                if (L2(i7)) if ("?" === s7) t7.push({ type: 0, index: i7 });
                else {
                  const e8 = (0, S4.parseColor)(s7);
                  e8 && t7.push({ type: 1, index: i7, 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 i6 = e6.split(":");
            let s7;
            const r7 = i6.findIndex((e7) => e7.startsWith("id="));
            return -1 !== r7 && (s7 = i6[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 i6 = e6.split(";");
            for (let e7 = 0; e7 < i6.length && !(t7 >= this._specialColors.length); ++e7, ++t7) if ("?" === i6[e7]) this._onColor.fire([{ type: 0, index: this._specialColors[t7] }]);
            else {
              const s7 = (0, S4.parseColor)(i6[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 = [], i6 = e6.split(";");
            for (let e7 = 0; e7 < i6.length; ++e7) if (/^\d+$/.exec(i6[e7])) {
              const s7 = parseInt(i6[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 i6 = this._activeBuffer.ybase + this._activeBuffer.y + t7, s7 = this._activeBuffer.lines.get(i6);
              s7 && (s7.fill(e6), s7.isWrapped = false);
            }
            return this._dirtyRowTracker.markAllDirty(), this._setCursor(0, 0), true;
          }
          requestStatusString(e6, t7) {
            const i6 = 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${i6.scrollTop + 1};${i6.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 i5(e6) {
          for (const t7 of e6) t7.dispose();
          e6.length = 0;
        }
        __name(i5, "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 = i5, t6.getDisposeArrayDisposable = function(e6) {
          return { dispose: /* @__PURE__ */ __name(() => i5(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 i5 = t6.isNode ? "node" : navigator.userAgent, s6 = t6.isNode ? "node" : navigator.platform;
        t6.isFirefox = i5.includes("Firefox"), t6.isLegacyEdge = i5.includes("Edge"), t6.isSafari = /^((?!chrome|android).)*safari/i.test(i5), t6.getSafariVersion = function() {
          if (!t6.isSafari) return 0;
          const e6 = i5.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(i5);
      }, 226: (e5, t6, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.DebouncedIdleTask = t6.IdleTaskQueue = t6.PriorityTaskQueue = void 0;
        const s6 = i5(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, i6 = 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), i6 = Math.max(t7, i6), r7 = e6.timeRemaining(), 1.5 * i6 > 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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.updateWindowsModeWrappedState = void 0;
        const s6 = i5(643);
        t6.updateWindowsModeWrappedState = function(e6) {
          const t7 = e6.buffer.lines.get(e6.buffer.ybase + e6.buffer.y - 1), i6 = t7?.get(e6.cols - 1), r6 = e6.buffer.lines.get(e6.buffer.ybase + e6.buffer.y);
          r6 && i6 && (r6.isWrapped = i6[s6.CHAR_DATA_CODE_INDEX] !== s6.NULL_CELL_CODE && i6[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 i5 {
          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 i5();
            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 = i5;
        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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.Buffer = t6.MAX_BUFFER_SIZE = void 0;
        const s6 = i5(349), r6 = i5(226), n4 = i5(734), a2 = i5(437), o3 = i5(634), h3 = i5(511), c4 = i5(643), l3 = i5(863), _2 = i5(116);
        t6.MAX_BUFFER_SIZE = 4294967295, t6.Buffer = class {
          constructor(e6, t7, i6) {
            this._hasScrollback = e6, this._optionsService = t7, this._bufferService = i6, 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 i6 = e6 + this._optionsService.rawOptions.scrollback;
            return i6 > t6.MAX_BUFFER_SIZE ? t6.MAX_BUFFER_SIZE : i6;
          }
          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 i6 = 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, i6);
              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, i6)) : 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, i6)));
              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, i6);
            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 i6 = (0, o3.reflowLargerGetLinesToRemove)(this.lines, this._cols, e6, this.ybase + this.y, this.getNullCell(a2.DEFAULT_ATTR_DATA));
            if (i6.length > 0) {
              const s7 = (0, o3.reflowLargerCreateNewLayout)(this.lines, i6);
              (0, o3.reflowLargerApplyNewLayout)(this.lines, s7.layout), this._reflowLargerAdjustViewport(e6, t7, s7.countRemoved);
            }
          }
          _reflowLargerAdjustViewport(e6, t7, i6) {
            const s7 = this.getNullCell(a2.DEFAULT_ATTR_DATA);
            let r7 = i6;
            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 - i6, 0);
          }
          _reflowSmaller(e6, t7) {
            const i6 = 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], i6);
              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 i7 = this.lines.length;
              let n5 = i7 - 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, i7 + 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, i7 + r7 - this.lines.maxLength);
              l4 > 0 && this.lines.onTrimEmitter.fire(l4);
            }
          }
          translateBufferLineToString(e6, t7, i6 = 0, s7) {
            const r7 = this.lines.get(e6);
            return r7 ? r7.translateToString(t7, i6, s7) : "";
          }
          getWrappedRangeForLine(e6) {
            let t7 = e6, i6 = e6;
            for (; t7 > 0 && this.lines.get(t7).isWrapped; ) t7--;
            for (; i6 + 1 < this.lines.length && this.lines.get(i6 + 1).isWrapped; ) i6++;
            return { first: t7, last: i6 };
          }
          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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferLine = t6.DEFAULT_ATTR_DATA = void 0;
        const s6 = i5(734), r6 = i5(511), n4 = i5(643), a2 = i5(482);
        t6.DEFAULT_ATTR_DATA = Object.freeze(new s6.AttributeData());
        let o3 = 0;
        class h3 {
          static {
            __name(this, "h");
          }
          constructor(e6, t7, i6 = false) {
            this.isWrapped = i6, 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], i6 = 2097151 & t7;
            return [this._data[3 * e6 + 1], 2097152 & t7 ? this._combined[e6] : i6 ? (0, a2.stringFromCodePoint)(i6) : "", t7 >> 22, 2097152 & t7 ? this._combined[e6].charCodeAt(this._combined[e6].length - 1) : i6];
          }
          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, i6, s7) {
            268435456 & s7.bg && (this._extendedAttrs[e6] = s7.extended), this._data[3 * e6 + 0] = t7 | i6 << 22, this._data[3 * e6 + 1] = s7.fg, this._data[3 * e6 + 2] = s7.bg;
          }
          addCodepointToCell(e6, t7, i6) {
            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, i6 && (s7 &= -12582913, s7 |= i6 << 22), this._data[3 * e6 + 0] = s7;
          }
          insertCells(e6, t7, i6) {
            if ((e6 %= this.length) && 2 === this.getWidth(e6 - 1) && this.setCellFromCodepoint(e6 - 1, 0, 1, i6), t7 < this.length - e6) {
              const s7 = new r6.CellData();
              for (let i7 = this.length - e6 - t7 - 1; i7 >= 0; --i7) this.setCell(e6 + t7 + i7, this.loadCell(e6 + i7, s7));
              for (let s8 = 0; s8 < t7; ++s8) this.setCell(e6 + s8, i6);
            } else for (let t8 = e6; t8 < this.length; ++t8) this.setCell(t8, i6);
            2 === this.getWidth(this.length - 1) && this.setCellFromCodepoint(this.length - 1, 0, 1, i6);
          }
          deleteCells(e6, t7, i6) {
            if (e6 %= this.length, t7 < this.length - e6) {
              const s7 = new r6.CellData();
              for (let i7 = 0; i7 < this.length - e6 - t7; ++i7) this.setCell(e6 + i7, this.loadCell(e6 + t7 + i7, s7));
              for (let e7 = this.length - t7; e7 < this.length; ++e7) this.setCell(e7, i6);
            } else for (let t8 = e6; t8 < this.length; ++t8) this.setCell(t8, i6);
            e6 && 2 === this.getWidth(e6 - 1) && this.setCellFromCodepoint(e6 - 1, 0, 1, i6), 0 !== this.getWidth(e6) || this.hasContent(e6) || this.setCellFromCodepoint(e6, 0, 1, i6);
          }
          replaceCells(e6, t7, i6, s7 = false) {
            if (s7) for (e6 && 2 === this.getWidth(e6 - 1) && !this.isProtected(e6 - 1) && this.setCellFromCodepoint(e6 - 1, 0, 1, i6), t7 < this.length && 2 === this.getWidth(t7 - 1) && !this.isProtected(t7) && this.setCellFromCodepoint(t7, 0, 1, i6); e6 < t7 && e6 < this.length; ) this.isProtected(e6) || this.setCell(e6, i6), e6++;
            else for (e6 && 2 === this.getWidth(e6 - 1) && this.setCellFromCodepoint(e6 - 1, 0, 1, i6), t7 < this.length && 2 === this.getWidth(t7 - 1) && this.setCellFromCodepoint(t7, 0, 1, i6); e6 < t7 && e6 < this.length; ) this.setCell(e6++, i6);
          }
          resize(e6, t7) {
            if (e6 === this.length) return 4 * this._data.length * 2 < this._data.buffer.byteLength;
            const i6 = 3 * e6;
            if (e6 > this.length) {
              if (this._data.buffer.byteLength >= 4 * i6) this._data = new Uint32Array(this._data.buffer, 0, i6);
              else {
                const e7 = new Uint32Array(i6);
                e7.set(this._data), this._data = e7;
              }
              for (let i7 = this.length; i7 < e6; ++i7) this.setCell(i7, t7);
            } else {
              this._data = this._data.subarray(0, i6);
              const t8 = Object.keys(this._combined);
              for (let i7 = 0; i7 < t8.length; i7++) {
                const s8 = parseInt(t8[i7], 10);
                s8 >= e6 && delete this._combined[s8];
              }
              const s7 = Object.keys(this._extendedAttrs);
              for (let t9 = 0; t9 < s7.length; t9++) {
                const i7 = parseInt(s7[t9], 10);
                i7 >= e6 && delete this._extendedAttrs[i7];
              }
            }
            return this.length = e6, 4 * i6 * 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, i6, 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 * (i6 + r8) + e7] = n5[3 * (t7 + r8) + e7];
              268435456 & n5[3 * (t7 + r8) + 2] && (this._extendedAttrs[i6 + r8] = e6._extendedAttrs[t7 + r8]);
            }
            else for (let r8 = 0; r8 < s7; r8++) {
              for (let e7 = 0; e7 < 3; e7++) this._data[3 * (i6 + r8) + e7] = n5[3 * (t7 + r8) + e7];
              268435456 & n5[3 * (t7 + r8) + 2] && (this._extendedAttrs[i6 + 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 + i6] = e6._combined[r8]);
            }
          }
          translateToString(e6, t7, i6, s7) {
            t7 = t7 ?? 0, i6 = i6 ?? this.length, e6 && (i6 = Math.min(i6, this.getTrimmedLength())), s7 && (s7.length = 0);
            let r7 = "";
            for (; t7 < i6; ) {
              const e7 = this._data[3 * t7 + 0], i7 = 2097151 & e7, o4 = 2097152 & e7 ? this._combined[t7] : i7 ? (0, a2.stringFromCodePoint)(i7) : 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 i5(e6, t7, i6) {
          if (t7 === e6.length - 1) return e6[t7].getTrimmedLength();
          const s6 = !e6[t7].hasContent(i6 - 1) && 1 === e6[t7].getWidth(i6 - 1), r6 = 2 === e6[t7 + 1].getWidth(0);
          return s6 && r6 ? i6 - 1 : i6;
        }
        __name(i5, "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 = i5(l3, _2, t7), f5 = 1, u2 = 0;
            for (; f5 < l3.length; ) {
              const e7 = i5(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 i6 = [];
          let s6 = 0, r6 = t7[s6], n4 = 0;
          for (let a2 = 0; a2 < e6.length; a2++) if (r6 === a2) {
            const i7 = t7[++s6];
            e6.onDeleteEmitter.fire({ index: a2 - n4, amount: i7 }), a2 += i7 - 1, n4 += i7, r6 = t7[++s6];
          } else i6.push(a2);
          return { layout: i6, countRemoved: n4 };
        }, t6.reflowLargerApplyNewLayout = function(e6, t7) {
          const i6 = [];
          for (let s6 = 0; s6 < t7.length; s6++) i6.push(e6.get(t7[s6]));
          for (let t8 = 0; t8 < i6.length; t8++) e6.set(t8, i6[t8]);
          e6.length = t7.length;
        }, t6.reflowSmallerGetNewLineLengths = function(e6, t7, s6) {
          const r6 = [], n4 = e6.map((s7, r7) => i5(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 = i5(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 = i5;
      }, 295: (e5, t6, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferSet = void 0;
        const s6 = i5(460), r6 = i5(844), n4 = i5(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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CellData = void 0;
        const s6 = i5(482), r6 = i5(643), n4 = i5(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 i6 = e6[r6.CHAR_DATA_CHAR_INDEX].charCodeAt(0);
              if (55296 <= i6 && i6 <= 56319) {
                const s7 = e6[r6.CHAR_DATA_CHAR_INDEX].charCodeAt(1);
                56320 <= s7 && s7 <= 57343 ? this.content = 1024 * (i6 - 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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.Marker = void 0;
        const s6 = i5(460), r6 = i5(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 i5, 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";
        }(i5 || (t6.C0 = i5 = {})), 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 = `${i5.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, i5 = e6.length) {
          let s6 = "";
          for (let r6 = t7; r6 < i5; ++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 i5 = e6.length;
            if (!i5) return 0;
            let s6 = 0, r6 = 0;
            if (this._interim) {
              const i6 = e6.charCodeAt(r6++);
              56320 <= i6 && i6 <= 57343 ? t7[s6++] = 1024 * (this._interim - 55296) + i6 - 56320 + 65536 : (t7[s6++] = this._interim, t7[s6++] = i6), this._interim = 0;
            }
            for (let n4 = r6; n4 < i5; ++n4) {
              const r7 = e6.charCodeAt(n4);
              if (55296 <= r7 && r7 <= 56319) {
                if (++n4 >= i5) 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 i5 = e6.length;
            if (!i5) 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 >= i5) 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 = i5 - 4;
            let _2 = c4;
            for (; _2 < i5; ) {
              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 >= i5) 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 >= i5) return this.interim[0] = s6, o3;
                if (r6 = e6[_2++], 128 != (192 & r6)) {
                  _2--;
                  continue;
                }
                if (_2 >= i5) 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 >= i5) return this.interim[0] = s6, o3;
                if (r6 = e6[_2++], 128 != (192 & r6)) {
                  _2--;
                  continue;
                }
                if (_2 >= i5) return this.interim[0] = s6, this.interim[1] = r6, o3;
                if (n4 = e6[_2++], 128 != (192 & n4)) {
                  _2--;
                  continue;
                }
                if (_2 >= i5) 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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.UnicodeV6 = void 0;
        const s6 = i5(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 i6, s7 = 0, r7 = t7.length - 1;
              if (e7 < t7[0][0] || e7 > t7[r7][1]) return false;
              for (; r7 >= s7; ) if (i6 = s7 + r7 >> 1, e7 > t7[i6][1]) s7 = i6 + 1;
              else {
                if (!(e7 < t7[i6][0])) return true;
                r7 = i6 - 1;
              }
              return false;
            }(e6, n4) ? 0 : e6 >= 131072 && e6 <= 196605 || e6 >= 196608 && e6 <= 262141 ? 2 : 1;
          }
          charProperties(e6, t7) {
            let i6 = this.wcwidth(e6), r7 = 0 === i6 && 0 !== t7;
            if (r7) {
              const e7 = s6.UnicodeService.extractWidth(t7);
              0 === e7 ? r7 = false : e7 > i6 && (i6 = e7);
            }
            return s6.UnicodeService.createPropertyValue(0, i6, r7);
          }
        };
      }, 981: (e5, t6, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.WriteBuffer = void 0;
        const s6 = i5(460), r6 = i5(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 i6;
            for (this._isSyncWriting = true; i6 = this._writeBuffer.shift(); ) {
              this._action(i6);
              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 i6 = 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() - i6 >= 12 ? setTimeout(() => this._innerWrite(0, e9)) : this._innerWrite(i6, 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() - i6 >= 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 i5 = /^([\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 i6 = e6.toString(16), s7 = i6.length < 2 ? "0" + i6 : i6;
          switch (t7) {
            case 4:
              return i6[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 = i5.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, i6 = [0, 0, 0];
            for (let s7 = 0; s7 < 3; ++s7) {
              const r7 = parseInt(t7.slice(e7 * s7, e7 * s7 + e7), 16);
              i6[s7] = 1 === e7 ? r7 << 4 : 2 === e7 ? r7 : 3 === e7 ? r7 >> 4 : r7 >> 8;
            }
            return i6;
          }
        }, t6.toRgbString = function(e6, t7 = 16) {
          const [i6, s7, n4] = e6;
          return `rgb:${r6(i6, 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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.DcsHandler = t6.DcsParser = void 0;
        const s6 = i5(482), r6 = i5(742), n4 = i5(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 i6 = this._handlers[e6];
            return i6.push(t7), { dispose: /* @__PURE__ */ __name(() => {
              const e7 = i6.indexOf(t7);
              -1 !== e7 && i6.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, i6) {
            if (this._active.length) for (let s7 = this._active.length - 1; s7 >= 0; s7--) this._active[s7].put(e6, t7, i6);
            else this._handlerFb(this._ident, "PUT", (0, s6.utf32ToString)(e6, t7, i6));
          }
          unhook(e6, t7 = true) {
            if (this._active.length) {
              let i6 = false, s7 = this._active.length - 1, r7 = false;
              if (this._stack.paused && (s7 = this._stack.loopPosition - 1, i6 = t7, r7 = this._stack.fallThrough, this._stack.paused = false), !r7 && false === i6) {
                for (; s7 >= 0 && (i6 = this._active[s7].unhook(e6), true !== i6); s7--) if (i6 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s7, this._stack.fallThrough = false, i6;
                s7--;
              }
              for (; s7 >= 0; s7--) if (i6 = this._active[s7].unhook(false), i6 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s7, this._stack.fallThrough = true, i6;
            } 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, i6) {
            this._hitLimit || (this._data += (0, s6.utf32ToString)(e6, t7, i6), 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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.EscapeSequenceParser = t6.VT500_TRANSITION_TABLE = t6.TransitionTable = void 0;
        const s6 = i5(844), r6 = i5(742), n4 = i5(242), a2 = i5(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, i6, s7) {
            this.table[t7 << 8 | e6] = i6 << 4 | s7;
          }
          addMany(e6, t7, i6, s7) {
            for (let r7 = 0; r7 < e6.length; r7++) this.table[t7 << 8 | e6[r7]] = i6 << 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), i6 = /* @__PURE__ */ __name((e7, i7) => t7.slice(e7, i7), "i"), s7 = i6(32, 127), r7 = i6(0, 24);
          r7.push(25), r7.push.apply(r7, i6(28, 32));
          const n5 = i6(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(i6(128, 144), a3, 3, 0), e6.addMany(i6(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(i6(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(i6(64, 127), 3, 7, 0), e6.addMany(i6(48, 60), 3, 8, 4), e6.addMany([60, 61, 62, 63], 3, 9, 4), e6.addMany(i6(48, 60), 4, 8, 4), e6.addMany(i6(64, 127), 4, 7, 0), e6.addMany([60, 61, 62, 63], 4, 0, 6), e6.addMany(i6(32, 64), 6, 0, 6), e6.add(127, 6, 0, 6), e6.addMany(i6(64, 127), 6, 0, 0), e6.addMany(i6(32, 48), 3, 9, 5), e6.addMany(i6(32, 48), 5, 9, 5), e6.addMany(i6(48, 64), 5, 0, 6), e6.addMany(i6(64, 127), 5, 7, 0), e6.addMany(i6(32, 48), 4, 9, 5), e6.addMany(i6(32, 48), 1, 9, 2), e6.addMany(i6(32, 48), 2, 9, 2), e6.addMany(i6(48, 127), 2, 10, 0), e6.addMany(i6(48, 80), 1, 10, 0), e6.addMany(i6(81, 88), 1, 10, 0), e6.addMany([89, 90, 92], 1, 10, 0), e6.addMany(i6(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(i6(28, 32), 9, 0, 9), e6.addMany(i6(32, 48), 9, 9, 12), e6.addMany(i6(48, 60), 9, 8, 10), e6.addMany([60, 61, 62, 63], 9, 9, 10), e6.addMany(r7, 11, 0, 11), e6.addMany(i6(32, 128), 11, 0, 11), e6.addMany(i6(28, 32), 11, 0, 11), e6.addMany(r7, 10, 0, 10), e6.add(127, 10, 0, 10), e6.addMany(i6(28, 32), 10, 0, 10), e6.addMany(i6(48, 60), 10, 8, 10), e6.addMany([60, 61, 62, 63], 10, 0, 11), e6.addMany(i6(32, 48), 10, 9, 12), e6.addMany(r7, 12, 0, 12), e6.add(127, 12, 0, 12), e6.addMany(i6(28, 32), 12, 0, 12), e6.addMany(i6(32, 48), 12, 9, 12), e6.addMany(i6(48, 64), 12, 0, 11), e6.addMany(i6(64, 127), 12, 12, 13), e6.addMany(i6(64, 127), 10, 12, 13), e6.addMany(i6(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, i6) => {
            }, 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 i6 = 0;
            if (e6.prefix) {
              if (e6.prefix.length > 1) throw new Error("only one byte as prefix supported");
              if (i6 = e6.prefix.charCodeAt(0), i6 && 60 > i6 || i6 > 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");
                i6 <<= 8, i6 |= 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 i6 <<= 8, i6 |= s7, i6;
          }
          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 i6 = this._identifier(e6, [48, 126]);
            void 0 === this._escHandlers[i6] && (this._escHandlers[i6] = []);
            const s7 = this._escHandlers[i6];
            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 i6 = this._identifier(e6);
            void 0 === this._csiHandlers[i6] && (this._csiHandlers[i6] = []);
            const s7 = this._csiHandlers[i6];
            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, i6, s7, r7) {
            this._parseStack.state = e6, this._parseStack.handlers = t7, this._parseStack.handlerPos = i6, this._parseStack.transition = s7, this._parseStack.chunkPos = r7;
          }
          parse(e6, t7, i6) {
            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 === i6 || 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 === i6 && 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 === i6 && 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, i6), 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, i6), 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 i7 = a3; i7 < t7; ++i7) {
              switch (r7 = e6[i7], n5 = this._transitions.table[this.currentState << 8 | (r7 < 160 ? r7 : h3)], n5 >> 4) {
                case 2:
                  for (let s8 = i7 + 1; ; ++s8) {
                    if (s8 >= t7 || (r7 = e6[s8]) < 32 || r7 > 126 && r7 < h3) {
                      this._printHandler(e6, i7, s8), i7 = s8 - 1;
                      break;
                    }
                    if (++s8 >= t7 || (r7 = e6[s8]) < 32 || r7 > 126 && r7 < h3) {
                      this._printHandler(e6, i7, s8), i7 = s8 - 1;
                      break;
                    }
                    if (++s8 >= t7 || (r7 = e6[s8]) < 32 || r7 > 126 && r7 < h3) {
                      this._printHandler(e6, i7, s8), i7 = s8 - 1;
                      break;
                    }
                    if (++s8 >= t7 || (r7 = e6[s8]) < 32 || r7 > 126 && r7 < h3) {
                      this._printHandler(e6, i7, s8), i7 = 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: i7, 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, i7), 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 (++i7 < t7 && (r7 = e6[i7]) > 47 && r7 < 60);
                  i7--;
                  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, i7), 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 = i7 + 1; ; ++s8) if (s8 >= t7 || 24 === (r7 = e6[s8]) || 26 === r7 || 27 === r7 || r7 > 127 && r7 < h3) {
                    this._dcsParser.put(e6, i7, s8), i7 = s8 - 1;
                    break;
                  }
                  break;
                case 14:
                  if (s7 = this._dcsParser.unhook(24 !== r7 && 26 !== r7), s7) return this._preserveStack(6, [], 0, n5, i7), 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 = i7 + 1; ; s8++) if (s8 >= t7 || (r7 = e6[s8]) < 32 || r7 > 127 && r7 < h3) {
                    this._oscParser.put(e6, i7, s8), i7 = s8 - 1;
                    break;
                  }
                  break;
                case 6:
                  if (s7 = this._oscParser.end(24 !== r7 && 26 !== r7), s7) return this._preserveStack(5, [], 0, n5, i7), 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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.OscHandler = t6.OscParser = void 0;
        const s6 = i5(770), r6 = i5(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 i6 = this._handlers[e6];
            return i6.push(t7), { dispose: /* @__PURE__ */ __name(() => {
              const e7 = i6.indexOf(t7);
              -1 !== e7 && i6.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, i6) {
            if (this._active.length) for (let s7 = this._active.length - 1; s7 >= 0; s7--) this._active[s7].put(e6, t7, i6);
            else this._handlerFb(this._id, "PUT", (0, r6.utf32ToString)(e6, t7, i6));
          }
          start() {
            this.reset(), this._state = 1;
          }
          put(e6, t7, i6) {
            if (3 !== this._state) {
              if (1 === this._state) for (; t7 < i6; ) {
                const i7 = e6[t7++];
                if (59 === i7) {
                  this._state = 2, this._start();
                  break;
                }
                if (i7 < 48 || 57 < i7) return void (this._state = 3);
                -1 === this._id && (this._id = 0), this._id = 10 * this._id + i7 - 48;
              }
              2 === this._state && i6 - t7 > 0 && this._put(e6, t7, i6);
            }
          }
          end(e6, t7 = true) {
            if (0 !== this._state) {
              if (3 !== this._state) if (1 === this._state && this._start(), this._active.length) {
                let i6 = false, s7 = this._active.length - 1, r7 = false;
                if (this._stack.paused && (s7 = this._stack.loopPosition - 1, i6 = t7, r7 = this._stack.fallThrough, this._stack.paused = false), !r7 && false === i6) {
                  for (; s7 >= 0 && (i6 = this._active[s7].end(e6), true !== i6); s7--) if (i6 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s7, this._stack.fallThrough = false, i6;
                  s7--;
                }
                for (; s7 >= 0; s7--) if (i6 = this._active[s7].end(false), i6 instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = s7, this._stack.fallThrough = true, i6;
              } 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, i6) {
            this._hitLimit || (this._data += (0, r6.utf32ToString)(e6, t7, i6), 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 i5 = 2147483647;
        class s6 {
          static {
            __name(this, "s");
          }
          static fromArray(e6) {
            const t7 = new s6();
            if (!e6.length) return t7;
            for (let i6 = Array.isArray(e6[0]) ? 1 : 0; i6 < e6.length; ++i6) {
              const s7 = e6[i6];
              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 i6 = this._subParamsIdx[t7] >> 8, s7 = 255 & this._subParamsIdx[t7];
              s7 - i6 > 0 && e6.push(Array.prototype.slice.call(this._subParams, i6, 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 > i5 ? i5 : 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 > i5 ? i5 : 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, i6 = 255 & this._subParamsIdx[e6];
            return i6 - t7 > 0 ? this._subParams.subarray(t7, i6) : null;
          }
          getSubParamsAll() {
            const e6 = {};
            for (let t7 = 0; t7 < this.length; ++t7) {
              const i6 = this._subParamsIdx[t7] >> 8, s7 = 255 & this._subParamsIdx[t7];
              s7 - i6 > 0 && (e6[t7] = this._subParams.slice(i6, 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, i5) : 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 i5 = { instance: t7, dispose: t7.dispose, isDisposed: false };
            this._addons.push(i5), t7.dispose = () => this._wrappedAddonDispose(i5), t7.activate(e6);
          }
          _wrappedAddonDispose(e6) {
            if (e6.isDisposed) return;
            let t7 = -1;
            for (let i5 = 0; i5 < this._addons.length; i5++) if (this._addons[i5] === e6) {
              t7 = i5;
              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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferApiView = void 0;
        const s6 = i5(785), r6 = i5(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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferLineApiView = void 0;
        const s6 = i5(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, i6) {
            return this._line.translateToString(e6, t7, i6);
          }
        };
      }, 285: (e5, t6, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferNamespaceApi = void 0;
        const s6 = i5(771), r6 = i5(460), n4 = i5(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, i5) => t7(e7, i5.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, i5) {
        var s6 = this && this.__decorate || function(e6, t7, i6, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i6) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i6, s7);
          else for (var o4 = e6.length - 1; o4 >= 0; o4--) (r7 = e6[o4]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i6, a3) : r7(t7, i6)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i6, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i6, s7) {
            t7(i6, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.BufferService = t6.MINIMUM_ROWS = t6.MINIMUM_COLS = void 0;
        const n4 = i5(460), a2 = i5(844), o3 = i5(295), h3 = i5(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 i6 = this.buffer;
            let s7;
            s7 = this._cachedBlankLine, s7 && s7.length === this.cols && s7.getFg(0) === e6.fg && s7.getBg(0) === e6.bg || (s7 = i6.getBlankLine(e6, t7), this._cachedBlankLine = s7), s7.isWrapped = t7;
            const r7 = i6.ybase + i6.scrollTop, n5 = i6.ybase + i6.scrollBottom;
            if (0 === i6.scrollTop) {
              const e7 = i6.lines.isFull;
              n5 === i6.lines.length - 1 ? e7 ? i6.lines.recycle().copyFrom(s7) : i6.lines.push(s7.clone()) : i6.lines.splice(n5 + 1, 0, s7.clone()), e7 ? this.isUserScrolling && (i6.ydisp = Math.max(i6.ydisp - 1, 0)) : (i6.ybase++, this.isUserScrolling || i6.ydisp++);
            } else {
              const e7 = n5 - r7 + 1;
              i6.lines.shiftElements(r7 + 1, e7 - 1, -1), i6.lines.set(n5, s7.clone());
            }
            this.isUserScrolling || (i6.ydisp = i6.ybase), this._onScroll.fire(i6.ydisp);
          }
          scrollLines(e6, t7, i6) {
            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, i5) {
        var s6 = this && this.__decorate || function(e6, t7, i6, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i6) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i6, s7);
          else for (var o4 = e6.length - 1; o4 >= 0; o4--) (r7 = e6[o4]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i6, a3) : r7(t7, i6)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i6, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i6, s7) {
            t7(i6, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CoreMouseService = void 0;
        const n4 = i5(585), a2 = i5(460), o3 = i5(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 i6 = (e6.ctrl ? 16 : 0) | (e6.shift ? 4 : 0) | (e6.alt ? 8 : 0);
          return 4 === e6.button ? (i6 |= 64, i6 |= e6.action) : (i6 |= 3 & e6.button, 4 & e6.button && (i6 |= 64), 8 & e6.button && (i6 |= 128), 32 === e6.action ? i6 |= 32 : 0 !== e6.action || t7 || (i6 |= 3)), i6;
        }
        __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, i6) {
            if (i6) {
              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, i5) {
        var s6 = this && this.__decorate || function(e6, t7, i6, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i6) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i6, s7);
          else for (var o4 = e6.length - 1; o4 >= 0; o4--) (r7 = e6[o4]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i6, a3) : r7(t7, i6)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i6, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i6, s7) {
            t7(i6, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.CoreService = void 0;
        const n4 = i5(439), a2 = i5(460), o3 = i5(844), h3 = i5(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, i6) {
            super(), this._bufferService = e6, this._logService = t7, this._optionsService = i6, 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 i6 = this._bufferService.buffer;
            t7 && this._optionsService.rawOptions.scrollOnUserInput && i6.ybase !== i6.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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.InstantiationService = t6.ServiceCollection = void 0;
        const s6 = i5(585), r6 = i5(343);
        class n4 {
          static {
            __name(this, "n");
          }
          constructor(...e6) {
            this._entries = /* @__PURE__ */ new Map();
            for (const [t7, i6] of e6) this.set(t7, i6);
          }
          set(e6, t7) {
            const i6 = this._entries.get(e6);
            return this._entries.set(e6, t7), i6;
          }
          forEach(e6) {
            for (const [t7, i6] of this._entries.entries()) e6(t7, i6);
          }
          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 i6 = (0, r6.getServiceDependencies)(e6).sort((e7, t8) => e7.index - t8.index), s7 = [];
            for (const t8 of i6) {
              const i7 = this._services.get(t8.id);
              if (!i7) throw new Error(`[createInstance] ${e6.name} depends on UNKNOWN service ${t8.id}.`);
              s7.push(i7);
            }
            const n5 = i6.length > 0 ? i6[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, i5) {
        var s6 = this && this.__decorate || function(e6, t7, i6, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i6) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i6, s7);
          else for (var o4 = e6.length - 1; o4 >= 0; o4--) (r7 = e6[o4]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i6, a3) : r7(t7, i6)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i6, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i6, s7) {
            t7(i6, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.traceCall = t6.setTraceLogger = t6.LogService = void 0;
        const n4 = i5(844), a2 = i5(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, i6) {
            this._evalLazyOptionalParams(i6), e6.call(console, (this._optionsService.options.logger ? "" : "xterm.js: ") + t7, ...i6);
          }
          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, i6) {
          if ("function" != typeof i6.value) throw new Error("not supported");
          const s7 = i6.value;
          i6.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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.OptionsService = t6.DEFAULT_OPTIONS = void 0;
        const s6 = i5(460), r6 = i5(844), n4 = i5(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 i6 = { ...t6.DEFAULT_OPTIONS };
            for (const t7 in e6) if (t7 in i6) try {
              const s7 = e6[t7];
              i6[t7] = this._sanitizeAndValidateOption(t7, s7);
            } catch (e7) {
              console.error(e7);
            }
            this.rawOptions = i6, this.options = { ...i6 }, this._setupOptions(), this.register((0, r6.toDisposable)(() => {
              this.rawOptions.linkHandler = null, this.rawOptions.documentOverride = null;
            }));
          }
          onSpecificOptionChange(e6, t7) {
            return this.onOptionChange((i6) => {
              i6 === e6 && t7(this.rawOptions[e6]);
            });
          }
          onMultipleOptionChange(e6, t7) {
            return this.onOptionChange((i6) => {
              -1 !== e6.indexOf(i6) && 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"), i6 = /* @__PURE__ */ __name((e7, i7) => {
              if (!(e7 in t6.DEFAULT_OPTIONS)) throw new Error(`No option with key "${e7}"`);
              i7 = this._sanitizeAndValidateOption(e7, i7), this.rawOptions[e7] !== i7 && (this.rawOptions[e7] = i7, this._onOptionChange.fire(e7));
            }, "i");
            for (const t7 in this.rawOptions) {
              const s7 = { get: e6.bind(this, t7), set: i6.bind(this, t7) };
              Object.defineProperty(this.options, t7, s7);
            }
          }
          _sanitizeAndValidateOption(e6, i6) {
            switch (e6) {
              case "cursorStyle":
                if (i6 || (i6 = t6.DEFAULT_OPTIONS[e6]), !/* @__PURE__ */ function(e7) {
                  return "block" === e7 || "underline" === e7 || "bar" === e7;
                }(i6)) throw new Error(`"${i6}" is not a valid value for ${e6}`);
                break;
              case "wordSeparator":
                i6 || (i6 = t6.DEFAULT_OPTIONS[e6]);
                break;
              case "fontWeight":
              case "fontWeightBold":
                if ("number" == typeof i6 && 1 <= i6 && i6 <= 1e3) break;
                i6 = a2.includes(i6) ? i6 : t6.DEFAULT_OPTIONS[e6];
                break;
              case "cursorWidth":
                i6 = Math.floor(i6);
              case "lineHeight":
              case "tabStopWidth":
                if (i6 < 1) throw new Error(`${e6} cannot be less than 1, value: ${i6}`);
                break;
              case "minimumContrastRatio":
                i6 = Math.max(1, Math.min(21, Math.round(10 * i6) / 10));
                break;
              case "scrollback":
                if ((i6 = Math.min(i6, 4294967295)) < 0) throw new Error(`${e6} cannot be less than 0, value: ${i6}`);
                break;
              case "fastScrollSensitivity":
              case "scrollSensitivity":
                if (i6 <= 0) throw new Error(`${e6} cannot be less than or equal to 0, value: ${i6}`);
                break;
              case "rows":
              case "cols":
                if (!i6 && 0 !== i6) throw new Error(`${e6} must be numeric, value: ${i6}`);
                break;
              case "windowsPty":
                i6 = i6 ?? {};
            }
            return i6;
          }
        }
        t6.OptionsService = o3;
      }, 660: function(e5, t6, i5) {
        var s6 = this && this.__decorate || function(e6, t7, i6, s7) {
          var r7, n5 = arguments.length, a3 = n5 < 3 ? t7 : null === s7 ? s7 = Object.getOwnPropertyDescriptor(t7, i6) : s7;
          if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a3 = Reflect.decorate(e6, t7, i6, s7);
          else for (var o3 = e6.length - 1; o3 >= 0; o3--) (r7 = e6[o3]) && (a3 = (n5 < 3 ? r7(a3) : n5 > 3 ? r7(t7, i6, a3) : r7(t7, i6)) || a3);
          return n5 > 3 && a3 && Object.defineProperty(t7, i6, a3), a3;
        }, r6 = this && this.__param || function(e6, t7) {
          return function(i6, s7) {
            t7(i6, s7, e6);
          };
        };
        Object.defineProperty(t6, "__esModule", { value: true }), t6.OscLinkService = void 0;
        const n4 = i5(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 i7 = t7.addMarker(t7.ybase + t7.y), s8 = { data: e6, id: this._nextId++, lines: [i7] };
              return i7.onDispose(() => this._removeMarkerFromLink(s8, i7)), this._dataByLinkId.set(s8.id, s8), s8.id;
            }
            const i6 = e6, s7 = this._getEntryIdKey(i6), 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(i6), data: i6, 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 i6 = this._dataByLinkId.get(e6);
            if (i6 && i6.lines.every((e7) => e7.line !== t7)) {
              const e7 = this._bufferService.buffer.addMarker(t7);
              i6.lines.push(e7), e7.onDispose(() => this._removeMarkerFromLink(i6, e7));
            }
          }
          getLinkData(e6) {
            return this._dataByLinkId.get(e6)?.data;
          }
          _getEntryIdKey(e6) {
            return `${e6.id};;${e6.uri}`;
          }
          _removeMarkerFromLink(e6, t7) {
            const i6 = e6.lines.indexOf(t7);
            -1 !== i6 && (e6.lines.splice(i6, 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 i5 = "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[i5] === t8 ? t8[s6].push({ id: e8, index: r7 }) : (t8[s6] = [{ id: e8, index: r7 }], t8[i5] = t8);
            }(r6, e7, n4);
          }, "r");
          return r6.toString = () => e6, t6.serviceRegistry.set(e6, r6), r6;
        };
      }, 585: (e5, t6, i5) => {
        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 = i5(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, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.UnicodeService = void 0;
        const s6 = i5(460), r6 = i5(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, i6 = false) {
            return (16777215 & e6) << 3 | (3 & t7) << 1 | (i6 ? 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, i6 = 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 i7 = e6.charCodeAt(r7);
                56320 <= i7 && i7 <= 57343 ? a2 = 1024 * (a2 - 55296) + i7 - 56320 + 65536 : t7 += this.wcwidth(i7);
              }
              const o3 = this.charProperties(a2, i6);
              let h3 = n4.extractWidth(o3);
              n4.extractShouldJoin(o3) && (h3 -= n4.extractWidth(i6)), t7 += h3, i6 = o3;
            }
            return t7;
          }
          charProperties(e6, t7) {
            return this._activeProvider.charProperties(e6, t7);
          }
        }
        t6.UnicodeService = n4;
      }, 781: (e5, t6, i5) => {
        Object.defineProperty(t6, "__esModule", { value: true }), t6.Terminal = void 0;
        const s6 = i5(437), r6 = i5(969), n4 = i5(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 i4(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, i4), n4.exports;
      }
      __name(i4, "i");
      var s5 = {};
      (() => {
        var e5 = s5;
        Object.defineProperty(e5, "__esModule", { value: true }), e5.Terminal = void 0;
        const t6 = i4(285), r6 = i4(975), n4 = i4(90), a2 = i4(781), o3 = i4(741), h3 = i4(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"), i5 = /* @__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: i5.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 serializeTerminalToText(terminal) {
  const buffer = terminal.buffer.active;
  const lines = [];
  for (let i4 = 0; i4 < buffer.length; i4++) {
    const line = buffer.getLine(i4);
    const lineContent = line ? line.translateToString(true) : "";
    if (line?.isWrapped && lines.length > 0) {
      lines[lines.length - 1] += lineContent;
      continue;
    }
    lines.push(lineContent);
  }
  return lines.join("\n").trimEnd();
}
function serializeTerminalToObject(terminal, scrollOffset = 0, options2 = {}) {
  const buffer = terminal.buffer.active;
  const defaultFg = "";
  const defaultBg = "";
  const clampedOffset = Math.max(0, Math.min(scrollOffset, buffer.viewportY));
  const startRow = buffer.viewportY - clampedOffset;
  const cursorX = clampedOffset === 0 ? buffer.cursorX : -1;
  const cursorY = clampedOffset === 0 ? buffer.cursorY : -1;
  const result = [];
  for (let y2 = 0; y2 < terminal.rows; y2++) {
    const line = buffer.getLine(startRow + 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);
    }
    if (options2.unwrapWrappedLines && line.isWrapped && result.length > 0) {
      appendAnsiLineTokens(result[result.length - 1], currentLine);
    } else {
      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 canMergeAnsiTokens, appendAnsiLineTokens, Attribute, ColorMode, Cell, ANSI_COLORS;
var init_terminalSerializer = __esm({
  "packages/core/dist/src/utils/terminalSerializer.js"() {
    "use strict";
    init_esbuild_shims();
    canMergeAnsiTokens = /* @__PURE__ */ __name((left3, right3) => left3.bold === right3.bold && left3.italic === right3.italic && left3.underline === right3.underline && left3.dim === right3.dim && left3.inverse === right3.inverse && left3.fg === right3.fg && left3.bg === right3.bg, "canMergeAnsiTokens");
    appendAnsiLineTokens = /* @__PURE__ */ __name((target, source2) => {
      for (const token2 of source2) {
        const previous = target[target.length - 1];
        if (previous && canMergeAnsiTokens(previous, token2)) {
          previous.text += token2.text;
        } else {
          target.push({ ...token2 });
        }
      }
    }, "appendAnsiLineTokens");
    __name(serializeTerminalToText, "serializeTerminalToText");
    (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/utils/windowsPath.js
function mergeWindowsPathValues(env6, pathKeys) {
  const mergedEntries = [];
  const seenEntries = /* @__PURE__ */ new Set();
  for (const key of pathKeys) {
    const value = env6[key];
    if (value === void 0) {
      continue;
    }
    for (const entry of value.split(WINDOWS_PATH_DELIMITER)) {
      if (seenEntries.has(entry)) {
        continue;
      }
      seenEntries.add(entry);
      mergedEntries.push(entry);
    }
  }
  return mergedEntries.length > 0 ? mergedEntries.join(WINDOWS_PATH_DELIMITER) : void 0;
}
function getWindowsPathFingerprint(env6, pathKeys) {
  return pathKeys.map((key) => `${key}=${env6[key] ?? ""}`).join("\0");
}
function sortPathKeys(pathKeys) {
  return [...pathKeys].sort((left3, right3) => {
    if (left3 === "PATH") {
      return -1;
    }
    if (right3 === "PATH") {
      return 1;
    }
    return left3.localeCompare(right3);
  });
}
function normalizePathEnvForWindows(env6) {
  if (process.platform !== "win32") {
    return env6;
  }
  const normalized2 = { ...env6 };
  const pathKeys = Object.keys(normalized2).filter((key) => key.toLowerCase() === "path");
  if (pathKeys.length === 0) {
    return normalized2;
  }
  const orderedPathKeys = sortPathKeys(pathKeys);
  const fingerprint = getWindowsPathFingerprint(normalized2, orderedPathKeys);
  const canonicalValue = fingerprint === cachedWindowsPathFingerprint ? cachedMergedWindowsPath : mergeWindowsPathValues(normalized2, orderedPathKeys);
  if (fingerprint !== cachedWindowsPathFingerprint) {
    cachedWindowsPathFingerprint = fingerprint;
    cachedMergedWindowsPath = canonicalValue;
  }
  for (const key of pathKeys) {
    if (key !== "PATH") {
      delete normalized2[key];
    }
  }
  if (canonicalValue !== void 0) {
    normalized2["PATH"] = canonicalValue;
  }
  return normalized2;
}
var WINDOWS_PATH_DELIMITER, cachedWindowsPathFingerprint, cachedMergedWindowsPath;
var init_windowsPath = __esm({
  "packages/core/dist/src/utils/windowsPath.js"() {
    "use strict";
    init_esbuild_shims();
    WINDOWS_PATH_DELIMITER = ";";
    __name(mergeWindowsPathValues, "mergeWindowsPathValues");
    __name(getWindowsPathFingerprint, "getWindowsPathFingerprint");
    __name(sortPathKeys, "sortPathKeys");
    __name(normalizePathEnvForWindows, "normalizePathEnvForWindows");
  }
});

// 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 os17 from "node:os";
function applyPowerShellUtf8Prefix(command2, shell2) {
  if (os17.platform() === "win32" && shell2 === "powershell") {
    return "[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;" + command2;
  }
  return command2;
}
var import_headless, Terminal, SIGKILL_TIMEOUT_MS, getErrnoCode, getErrorMessage2, isExpectedPtyReadExitError, isExpectedPtyExitRaceError, replayTerminalOutput, getLastNonEmptyAnsiLineIndex, trimTrailingEmptyAnsiLines, areAnsiOutputsEqual, createPlainAnsiLine, serializePlainViewportToAnsiOutput, 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();
    init_shell_utils();
    import_headless = __toESM(require_xterm_headless(), 1);
    init_terminalSerializer();
    init_windowsPath();
    ({ Terminal } = import_headless.default);
    SIGKILL_TIMEOUT_MS = 200;
    __name(applyPowerShellUtf8Prefix, "applyPowerShellUtf8Prefix");
    getErrnoCode = /* @__PURE__ */ __name((error40) => {
      if (!error40 || typeof error40 !== "object" || !("code" in error40)) {
        return void 0;
      }
      const code2 = error40.code;
      return typeof code2 === "string" ? code2 : void 0;
    }, "getErrnoCode");
    getErrorMessage2 = /* @__PURE__ */ __name((error40) => error40 instanceof Error ? error40.message : String(error40), "getErrorMessage");
    isExpectedPtyReadExitError = /* @__PURE__ */ __name((error40) => {
      const code2 = getErrnoCode(error40);
      if (code2 === "EIO" || code2 === "EAGAIN") {
        return true;
      }
      const message = getErrorMessage2(error40);
      return message.includes("read EIO") || message.includes("EAGAIN");
    }, "isExpectedPtyReadExitError");
    isExpectedPtyExitRaceError = /* @__PURE__ */ __name((error40) => {
      const code2 = getErrnoCode(error40);
      if (code2 === "ESRCH" || code2 === "EBADF") {
        return true;
      }
      const message = getErrorMessage2(error40);
      return message.includes("ioctl(2) failed, EBADF") || message.includes("Cannot resize a pty that has already exited");
    }, "isExpectedPtyExitRaceError");
    replayTerminalOutput = /* @__PURE__ */ __name(async (output, cols, rows) => {
      const replayTerminal = new Terminal({
        allowProposedApi: true,
        cols,
        rows,
        scrollback: 1e4,
        convertEol: true
      });
      await new Promise((resolve42) => {
        replayTerminal.write(output, () => resolve42());
      });
      return serializeTerminalToText(replayTerminal);
    }, "replayTerminalOutput");
    getLastNonEmptyAnsiLineIndex = /* @__PURE__ */ __name((output) => {
      for (let i4 = output.length - 1; i4 >= 0; i4--) {
        const line = output[i4];
        if (line.map((segment) => segment.text).join("").trim().length > 0) {
          return i4;
        }
      }
      return -1;
    }, "getLastNonEmptyAnsiLineIndex");
    trimTrailingEmptyAnsiLines = /* @__PURE__ */ __name((output) => output.slice(0, getLastNonEmptyAnsiLineIndex(output) + 1), "trimTrailingEmptyAnsiLines");
    areAnsiOutputsEqual = /* @__PURE__ */ __name((left3, right3) => {
      if (!left3 || left3.length !== right3.length) {
        return false;
      }
      return left3.every((leftLine, lineIndex) => {
        const rightLine = right3[lineIndex];
        if (leftLine.length !== rightLine.length) {
          return false;
        }
        return leftLine.every((leftToken, tokenIndex) => {
          const rightToken = rightLine[tokenIndex];
          return leftToken.text === rightToken.text && leftToken.bold === rightToken.bold && leftToken.italic === rightToken.italic && leftToken.underline === rightToken.underline && leftToken.dim === rightToken.dim && leftToken.inverse === rightToken.inverse && leftToken.fg === rightToken.fg && leftToken.bg === rightToken.bg;
        });
      });
    }, "areAnsiOutputsEqual");
    createPlainAnsiLine = /* @__PURE__ */ __name((text) => [
      {
        text,
        bold: false,
        italic: false,
        underline: false,
        dim: false,
        inverse: false,
        fg: "",
        bg: ""
      }
    ], "createPlainAnsiLine");
    serializePlainViewportToAnsiOutput = /* @__PURE__ */ __name((terminal, unwrapWrappedLines = false) => {
      const buffer = terminal.buffer.active;
      const lines = [];
      for (let y2 = 0; y2 < terminal.rows; y2++) {
        const line = buffer.getLine(buffer.viewportY + y2);
        const lineContent = line ? line.translateToString(true) : "";
        if (unwrapWrappedLines && line?.isWrapped && lines.length > 0) {
          lines[lines.length - 1][0].text += lineContent;
        } else {
          lines.push(createPlainAnsiLine(lineContent));
        }
      }
      return lines;
    }, "serializePlainViewportToAnsiOutput");
    windowsStrategy = {
      killPty: /* @__PURE__ */ __name((_pid, pty) => {
        pty.ptyProcess.kill();
      }, "killPty"),
      killChildProcesses: /* @__PURE__ */ __name((pids) => {
        if (pids.size > 0) {
          try {
            const args2 = ["/f", "/t"];
            for (const pid of pids) {
              args2.push("/pid", pid.toString());
            }
            spawnSync2("taskkill", args2);
          } 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(() => os17.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, cwd6, onOutputEvent, abortSignal, shouldUseNodePty, shellExecutionConfig, options2 = {}) {
        if (shouldUseNodePty) {
          const ptyInfo = await getPty();
          if (ptyInfo) {
            try {
              return this.executeWithPty(commandToExecute, cwd6, onOutputEvent, abortSignal, shellExecutionConfig, ptyInfo);
            } catch (_e2) {
            }
          }
        }
        return this.childProcessFallback(commandToExecute, cwd6, onOutputEvent, abortSignal, options2.streamStdout ?? false);
      }
      static childProcessFallback(commandToExecute, cwd6, onOutputEvent, abortSignal, streamStdout) {
        try {
          const isWindows9 = os17.platform() === "win32";
          const { executable, argsPrefix, shell: shell2 } = getShellConfiguration();
          commandToExecute = applyPowerShellUtf8Prefix(commandToExecute, shell2);
          const shellArgs = [...argsPrefix, commandToExecute];
          const child = cpSpawn(executable, shellArgs, {
            cwd: cwd6,
            stdio: ["ignore", "pipe", "pipe"],
            windowsVerbatimArguments: isWindows9 && shell2 === "cmd",
            detached: !isWindows9,
            windowsHide: isWindows9,
            env: {
              ...normalizePathEnvForWindows(process.env),
              QWEN_CODE: "1",
              TERM: "xterm-256color",
              PAGER: "cat"
            }
          });
          const result = new Promise((resolve42) => {
            let stdoutDecoder = null;
            let stderrDecoder = null;
            let stdout2 = "";
            let stderr = "";
            const outputChunks = [];
            let error40 = null;
            let exited = false;
            let isStreamingRawContent = true;
            const MAX_SNIFF_SIZE = 4096;
            let sniffedBytes = 0;
            const handleOutput = /* @__PURE__ */ __name((data, stream5) => {
              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");
                }
              }
              if (isStreamingRawContent && sniffedBytes < MAX_SNIFF_SIZE) {
                outputChunks.push(data);
                sniffedBytes += data.length;
                const sniffBuffer = Buffer.concat(outputChunks);
                if (isBinary(sniffBuffer)) {
                  isStreamingRawContent = false;
                  if (streamStdout) {
                    onOutputEvent({ type: "binary_detected" });
                    outputChunks.length = 0;
                  }
                } else if (streamStdout && sniffedBytes >= MAX_SNIFF_SIZE) {
                  outputChunks.length = 0;
                }
              } else if (!streamStdout) {
                outputChunks.push(data);
              }
              if (!isStreamingRawContent) {
                return;
              }
              const decoder = stream5 === "stdout" ? stdoutDecoder : stderrDecoder;
              const decodedChunk = decoder.decode(data, { stream: true });
              if (streamStdout) {
                onOutputEvent({ type: "data", chunk: decodedChunk });
                return;
              }
              if (stream5 === "stdout") {
                stdout2 += decodedChunk;
              } else {
                stderr += decodedChunk;
              }
            }, "handleOutput");
            const handleExit = /* @__PURE__ */ __name((code2, signal) => {
              const { finalBuffer } = cleanup();
              const separator = stdout2.endsWith("\n") ? "" : "\n";
              const combinedOutput = stdout2 + (stderr ? (stdout2 ? separator : "") + stderr : "");
              const finalStrippedOutput = stripAnsi2(combinedOutput).trim();
              if (isStreamingRawContent) {
                if (!streamStdout && finalStrippedOutput) {
                  onOutputEvent({ type: "data", chunk: finalStrippedOutput });
                }
              } else {
                onOutputEvent({ type: "binary_detected" });
              }
              resolve42({
                rawOutput: finalBuffer,
                output: finalStrippedOutput,
                exitCode: code2,
                signal: signal ? os17.constants.signals[signal] : null,
                error: error40,
                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", (err2) => {
              error40 = err2;
              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) {
                  stdout2 += remaining;
                }
              }
              if (stderrDecoder) {
                const remaining = stderrDecoder.decode();
                if (remaining) {
                  stderr += remaining;
                }
              }
              const finalBuffer = Buffer.concat(outputChunks);
              return { stdout: stdout2, stderr, finalBuffer };
            }
            __name(cleanup, "cleanup");
          });
          return { pid: child.pid, result };
        } catch (e4) {
          const error40 = e4;
          return {
            pid: void 0,
            result: Promise.resolve({
              error: error40,
              rawOutput: Buffer.from(""),
              output: "",
              exitCode: 1,
              signal: null,
              aborted: false,
              pid: void 0,
              executionMethod: "none"
            })
          };
        }
      }
      static executeWithPty(commandToExecute, cwd6, 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 { executable, argsPrefix, shell: shell2 } = getShellConfiguration();
          commandToExecute = applyPowerShellUtf8Prefix(commandToExecute, shell2);
          const args2 = os17.platform() === "win32" && shell2 === "cmd" ? [...argsPrefix, commandToExecute].join(" ") : [...argsPrefix, commandToExecute];
          const ptyProcess = ptyInfo.module.spawn(executable, args2, {
            cwd: cwd6,
            name: "xterm",
            cols,
            rows,
            env: {
              ...normalizePathEnvForWindows(process.env),
              QWEN_CODE: "1",
              TERM: "xterm-256color",
              PAGER: shellExecutionConfig.pager ?? "cat",
              GIT_PAGER: shellExecutionConfig.pager ?? "cat"
            },
            handleFlowControl: true
          });
          const result = new Promise((resolve42) => {
            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 outputComparison = null;
            const outputChunks = [];
            const error40 = null;
            let exited = false;
            let isStreamingRawContent = true;
            const MAX_SNIFF_SIZE = 4096;
            let sniffedBytes = 0;
            let totalBytesReceived = 0;
            let isWriting = false;
            let hasStartedOutput = false;
            let renderTimeout = null;
            const RENDER_THROTTLE_MS = 100;
            const renderFn = /* @__PURE__ */ __name(() => {
              if (!isStreamingRawContent) {
                return;
              }
              if (!shellExecutionConfig.disableDynamicLineTrimming) {
                if (!hasStartedOutput) {
                  const bufferText = serializeTerminalToText(headlessTerminal);
                  if (bufferText.trim().length === 0) {
                    return;
                  }
                  hasStartedOutput = true;
                }
              }
              let newOutput;
              let newOutputComparison;
              if (shellExecutionConfig.showColor) {
                newOutput = serializeTerminalToObject(headlessTerminal);
                newOutputComparison = serializeTerminalToObject(headlessTerminal, 0, { unwrapWrappedLines: true });
              } else {
                newOutput = serializePlainViewportToAnsiOutput(headlessTerminal);
                newOutputComparison = serializePlainViewportToAnsiOutput(headlessTerminal, true);
              }
              const trimmedOutput = trimTrailingEmptyAnsiLines(newOutput);
              const trimmedOutputComparison = trimTrailingEmptyAnsiLines(newOutputComparison);
              const finalOutput = shellExecutionConfig.disableDynamicLineTrimming ? newOutput : trimmedOutput;
              const finalOutputComparison = shellExecutionConfig.disableDynamicLineTrimming ? newOutputComparison : trimmedOutputComparison;
              if (!areAnsiOutputsEqual(outputComparison, finalOutputComparison)) {
                outputComparison = finalOutputComparison;
                onOutputEvent({
                  type: "data",
                  chunk: finalOutput
                });
              }
            }, "renderFn");
            let pendingTrailingRender = false;
            const render3 = /* @__PURE__ */ __name((finalRender = false) => {
              if (finalRender) {
                if (renderTimeout) {
                  clearTimeout(renderTimeout);
                  renderTimeout = null;
                }
                renderFn();
                return;
              }
              if (!renderTimeout) {
                renderFn();
                renderTimeout = setTimeout(() => {
                  renderTimeout = null;
                  if (pendingTrailingRender) {
                    pendingTrailingRender = false;
                    render3();
                  }
                }, RENDER_THROTTLE_MS);
              } else {
                pendingTrailingRender = true;
              }
            }, "render");
            headlessTerminal.onScroll(() => {
              if (!isWriting) {
                render3();
              }
            });
            const ensureDecoder = /* @__PURE__ */ __name((data) => {
              if (decoder) {
                return;
              }
              const encoding = getCachedEncodingForBuffer(data);
              try {
                decoder = new TextDecoder2(encoding);
              } catch {
                decoder = new TextDecoder2("utf-8");
              }
            }, "ensureDecoder");
            const handleOutput = /* @__PURE__ */ __name((data) => {
              ensureDecoder(data);
              outputChunks.push(data);
              totalBytesReceived += data.length;
              const bytesReceived = totalBytesReceived;
              processingChain = processingChain.then(() => new Promise((resolve43) => {
                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;
                    resolve43();
                  });
                } else {
                  onOutputEvent({
                    type: "binary_progress",
                    bytesReceived
                  });
                  resolve43();
                }
              }));
            }, "handleOutput");
            ptyProcess.onData((data) => {
              const bufferData = Buffer.from(data, "utf-8");
              handleOutput(bufferData);
            });
            ptyProcess.on("error", (err2) => {
              if (isExpectedPtyReadExitError(err2)) {
                return;
              }
              throw err2;
            });
            ptyProcess.onExit(({ exitCode, signal }) => {
              exited = true;
              abortSignal.removeEventListener("abort", abortHandler);
              this.activePtys.delete(ptyProcess.pid);
              const finalize = /* @__PURE__ */ __name(async () => {
                render3(true);
                const finalBuffer = Buffer.concat(outputChunks);
                let fullOutput = "";
                try {
                  if (isStreamingRawContent) {
                    const finalEncoding = getCachedEncodingForBuffer(finalBuffer);
                    const decodedOutput = new TextDecoder2(finalEncoding).decode(finalBuffer);
                    fullOutput = await replayTerminalOutput(decodedOutput, cols, rows);
                  } else {
                    fullOutput = serializeTerminalToText(headlessTerminal);
                  }
                } catch {
                  try {
                    fullOutput = serializeTerminalToText(headlessTerminal);
                  } catch {
                  }
                }
                resolve42({
                  rawOutput: finalBuffer,
                  output: fullOutput,
                  exitCode,
                  signal: signal ?? null,
                  error: error40,
                  aborted: abortSignal.aborted,
                  pid: ptyProcess.pid,
                  executionMethod: ptyInfo?.name ?? "node-pty"
                });
              }, "finalize");
              const flushChain = /* @__PURE__ */ __name(() => processingChain.then(() => {
              }), "flushChain");
              const deadline = new Promise((res) => setTimeout(res, SIGKILL_TIMEOUT_MS));
              const drain = /* @__PURE__ */ __name(() => new Promise((res) => setImmediate(res)).then(flushChain), "drain");
              void Promise.race([
                flushChain().then(drain).then(drain),
                deadline
              ]).then(() => {
                void finalize();
              });
            });
            const abortHandler = /* @__PURE__ */ __name(async () => {
              if (ptyProcess.pid && !exited) {
                if (os17.platform() === "win32") {
                  ptyProcess.kill();
                } else {
                  try {
                    process.kill(-ptyProcess.pid, "SIGTERM");
                    await new Promise((res) => setTimeout(res, SIGKILL_TIMEOUT_MS));
                    if (!exited) {
                      process.kill(-ptyProcess.pid, "SIGKILL");
                    }
                  } catch (_e2) {
                    if (!exited) {
                      ptyProcess.kill();
                    }
                  }
                }
              }
            }, "abortHandler");
            abortSignal.addEventListener("abort", abortHandler, { once: true });
          });
          return { pid: ptyProcess.pid, result };
        } catch (e4) {
          const error40 = e4;
          if (error40.message.includes("posix_spawnp failed")) {
            onOutputEvent({
              type: "data",
              chunk: "[WARNING] PTY execution failed, falling back to child_process. This may be due to sandbox restrictions.\n"
            });
            throw e4;
          } else {
            return {
              pid: void 0,
              result: Promise.resolve({
                error: error40,
                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 (isExpectedPtyExitRaceError(e4)) {
            } 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 (isExpectedPtyExitRaceError(e4)) {
            } 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/web-tree-sitter/tree-sitter.js
var require_tree_sitter = __commonJS({
  "node_modules/web-tree-sitter/tree-sitter.js"(exports, module) {
    init_esbuild_shims();
    var Module = typeof Module != "undefined" ? Module : {};
    var ENVIRONMENT_IS_WEB = typeof window == "object";
    var ENVIRONMENT_IS_WORKER = typeof importScripts == "function";
    var ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string";
    if (ENVIRONMENT_IS_NODE) {
    }
    var TreeSitter = function() {
      var initPromise;
      var document = typeof window == "object" ? {
        currentScript: window.document.currentScript
      } : null;
      class Parser {
        static {
          __name(this, "Parser");
        }
        constructor() {
          this.initialize();
        }
        initialize() {
          throw new Error("cannot construct a Parser before calling `init()`");
        }
        static init(moduleOptions) {
          if (initPromise) return initPromise;
          Module = Object.assign({}, Module, moduleOptions);
          return initPromise = new Promise((resolveInitPromise) => {
            var moduleOverrides = Object.assign({}, Module);
            var arguments_ = [];
            var thisProgram = "./this.program";
            var quit_ = /* @__PURE__ */ __name((status, toThrow) => {
              throw toThrow;
            }, "quit_");
            var scriptDirectory = "";
            function locateFile(path150) {
              if (Module["locateFile"]) {
                return Module["locateFile"](path150, scriptDirectory);
              }
              return scriptDirectory + path150;
            }
            __name(locateFile, "locateFile");
            var readAsync, readBinary;
            if (ENVIRONMENT_IS_NODE) {
              var fs = __require("fs");
              var nodePath = __require("path");
              scriptDirectory = __dirname + "/";
              readBinary = /* @__PURE__ */ __name((filename) => {
                filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
                var ret = fs.readFileSync(filename);
                return ret;
              }, "readBinary");
              readAsync = /* @__PURE__ */ __name((filename, binary2 = true) => {
                filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename);
                return new Promise((resolve42, reject) => {
                  fs.readFile(filename, binary2 ? void 0 : "utf8", (err2, data) => {
                    if (err2) reject(err2);
                    else resolve42(binary2 ? data.buffer : data);
                  });
                });
              }, "readAsync");
              if (!Module["thisProgram"] && process.argv.length > 1) {
                thisProgram = process.argv[1].replace(/\\/g, "/");
              }
              arguments_ = process.argv.slice(2);
              if (typeof module != "undefined") {
                module["exports"] = Module;
              }
              quit_ = /* @__PURE__ */ __name((status, toThrow) => {
                process.exitCode = status;
                throw toThrow;
              }, "quit_");
            } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
              if (ENVIRONMENT_IS_WORKER) {
                scriptDirectory = self.location.href;
              } else if (typeof document != "undefined" && document.currentScript) {
                scriptDirectory = document.currentScript.src;
              }
              if (scriptDirectory.startsWith("blob:")) {
                scriptDirectory = "";
              } else {
                scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1);
              }
              {
                if (ENVIRONMENT_IS_WORKER) {
                  readBinary = /* @__PURE__ */ __name((url3) => {
                    var xhr = new XMLHttpRequest();
                    xhr.open("GET", url3, false);
                    xhr.responseType = "arraybuffer";
                    xhr.send(null);
                    return new Uint8Array(
                      /** @type{!ArrayBuffer} */
                      xhr.response
                    );
                  }, "readBinary");
                }
                readAsync = /* @__PURE__ */ __name((url3) => {
                  if (isFileURI(url3)) {
                    return new Promise((reject, resolve42) => {
                      var xhr = new XMLHttpRequest();
                      xhr.open("GET", url3, true);
                      xhr.responseType = "arraybuffer";
                      xhr.onload = () => {
                        if (xhr.status == 200 || xhr.status == 0 && xhr.response) {
                          resolve42(xhr.response);
                        }
                        reject(xhr.status);
                      };
                      xhr.onerror = reject;
                      xhr.send(null);
                    });
                  }
                  return fetch(url3, {
                    credentials: "same-origin"
                  }).then((response) => {
                    if (response.ok) {
                      return response.arrayBuffer();
                    }
                    return Promise.reject(new Error(response.status + " : " + response.url));
                  });
                }, "readAsync");
              }
            } else {
            }
            var out = Module["print"] || console.log.bind(console);
            var err = Module["printErr"] || console.error.bind(console);
            Object.assign(Module, moduleOverrides);
            moduleOverrides = null;
            if (Module["arguments"]) arguments_ = Module["arguments"];
            if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
            if (Module["quit"]) quit_ = Module["quit"];
            var dynamicLibraries = Module["dynamicLibraries"] || [];
            var wasmBinary;
            if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"];
            var wasmMemory;
            var ABORT = false;
            var EXITSTATUS;
            var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
            var HEAP_DATA_VIEW;
            function updateMemoryViews() {
              var b2 = wasmMemory.buffer;
              Module["HEAP_DATA_VIEW"] = HEAP_DATA_VIEW = new DataView(b2);
              Module["HEAP8"] = HEAP8 = new Int8Array(b2);
              Module["HEAP16"] = HEAP16 = new Int16Array(b2);
              Module["HEAPU8"] = HEAPU8 = new Uint8Array(b2);
              Module["HEAPU16"] = HEAPU16 = new Uint16Array(b2);
              Module["HEAP32"] = HEAP32 = new Int32Array(b2);
              Module["HEAPU32"] = HEAPU32 = new Uint32Array(b2);
              Module["HEAPF32"] = HEAPF32 = new Float32Array(b2);
              Module["HEAPF64"] = HEAPF64 = new Float64Array(b2);
            }
            __name(updateMemoryViews, "updateMemoryViews");
            if (Module["wasmMemory"]) {
              wasmMemory = Module["wasmMemory"];
            } else {
              var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 33554432;
              wasmMemory = new WebAssembly.Memory({
                "initial": INITIAL_MEMORY / 65536,
                // In theory we should not need to emit the maximum if we want "unlimited"
                // or 4GB of memory, but VMs error on that atm, see
                // https://github.com/emscripten-core/emscripten/issues/14130
                // And in the pthreads case we definitely need to emit a maximum. So
                // always emit one.
                "maximum": 2147483648 / 65536
              });
            }
            updateMemoryViews();
            var __ATPRERUN__ = [];
            var __ATINIT__ = [];
            var __ATMAIN__ = [];
            var __ATPOSTRUN__ = [];
            var __RELOC_FUNCS__ = [];
            var runtimeInitialized = false;
            function preRun() {
              if (Module["preRun"]) {
                if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]];
                while (Module["preRun"].length) {
                  addOnPreRun(Module["preRun"].shift());
                }
              }
              callRuntimeCallbacks(__ATPRERUN__);
            }
            __name(preRun, "preRun");
            function initRuntime() {
              runtimeInitialized = true;
              callRuntimeCallbacks(__RELOC_FUNCS__);
              callRuntimeCallbacks(__ATINIT__);
            }
            __name(initRuntime, "initRuntime");
            function preMain() {
              callRuntimeCallbacks(__ATMAIN__);
            }
            __name(preMain, "preMain");
            function postRun() {
              if (Module["postRun"]) {
                if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]];
                while (Module["postRun"].length) {
                  addOnPostRun(Module["postRun"].shift());
                }
              }
              callRuntimeCallbacks(__ATPOSTRUN__);
            }
            __name(postRun, "postRun");
            function addOnPreRun(cb) {
              __ATPRERUN__.unshift(cb);
            }
            __name(addOnPreRun, "addOnPreRun");
            function addOnInit(cb) {
              __ATINIT__.unshift(cb);
            }
            __name(addOnInit, "addOnInit");
            function addOnPostRun(cb) {
              __ATPOSTRUN__.unshift(cb);
            }
            __name(addOnPostRun, "addOnPostRun");
            var runDependencies = 0;
            var runDependencyWatcher = null;
            var dependenciesFulfilled = null;
            function getUniqueRunDependency(id) {
              return id;
            }
            __name(getUniqueRunDependency, "getUniqueRunDependency");
            function addRunDependency(id) {
              runDependencies++;
              Module["monitorRunDependencies"]?.(runDependencies);
            }
            __name(addRunDependency, "addRunDependency");
            function removeRunDependency(id) {
              runDependencies--;
              Module["monitorRunDependencies"]?.(runDependencies);
              if (runDependencies == 0) {
                if (runDependencyWatcher !== null) {
                  clearInterval(runDependencyWatcher);
                  runDependencyWatcher = null;
                }
                if (dependenciesFulfilled) {
                  var callback = dependenciesFulfilled;
                  dependenciesFulfilled = null;
                  callback();
                }
              }
            }
            __name(removeRunDependency, "removeRunDependency");
            function abort(what) {
              Module["onAbort"]?.(what);
              what = "Aborted(" + what + ")";
              err(what);
              ABORT = true;
              EXITSTATUS = 1;
              what += ". Build with -sASSERTIONS for more info.";
              var e4 = new WebAssembly.RuntimeError(what);
              throw e4;
            }
            __name(abort, "abort");
            var dataURIPrefix = "data:application/octet-stream;base64,";
            var isDataURI = /* @__PURE__ */ __name((filename) => filename.startsWith(dataURIPrefix), "isDataURI");
            var isFileURI = /* @__PURE__ */ __name((filename) => filename.startsWith("file://"), "isFileURI");
            function findWasmBinary() {
              var f5 = "tree-sitter.wasm";
              if (!isDataURI(f5)) {
                return locateFile(f5);
              }
              return f5;
            }
            __name(findWasmBinary, "findWasmBinary");
            var wasmBinaryFile;
            function getBinarySync(file2) {
              if (file2 == wasmBinaryFile && wasmBinary) {
                return new Uint8Array(wasmBinary);
              }
              if (readBinary) {
                return readBinary(file2);
              }
              throw "both async and sync fetching of the wasm failed";
            }
            __name(getBinarySync, "getBinarySync");
            function getBinaryPromise(binaryFile) {
              if (!wasmBinary) {
                return readAsync(binaryFile).then(
                  (response) => new Uint8Array(
                    /** @type{!ArrayBuffer} */
                    response
                  ),
                  // Fall back to getBinarySync if readAsync fails
                  () => getBinarySync(binaryFile)
                );
              }
              return Promise.resolve().then(() => getBinarySync(binaryFile));
            }
            __name(getBinaryPromise, "getBinaryPromise");
            function instantiateArrayBuffer(binaryFile, imports, receiver) {
              return getBinaryPromise(binaryFile).then((binary2) => WebAssembly.instantiate(binary2, imports)).then(receiver, (reason) => {
                err(`failed to asynchronously prepare wasm: ${reason}`);
                abort(reason);
              });
            }
            __name(instantiateArrayBuffer, "instantiateArrayBuffer");
            function instantiateAsync(binary2, binaryFile, imports, callback) {
              if (!binary2 && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously.
              !isFileURI(binaryFile) && // Avoid instantiateStreaming() on Node.js environment for now, as while
              // Node.js v18.1.0 implements it, it does not have a full fetch()
              // implementation yet.
              // Reference:
              //   https://github.com/emscripten-core/emscripten/pull/16917
              !ENVIRONMENT_IS_NODE && typeof fetch == "function") {
                return fetch(binaryFile, {
                  credentials: "same-origin"
                }).then((response) => {
                  var result = WebAssembly.instantiateStreaming(response, imports);
                  return result.then(callback, function(reason) {
                    err(`wasm streaming compile failed: ${reason}`);
                    err("falling back to ArrayBuffer instantiation");
                    return instantiateArrayBuffer(binaryFile, imports, callback);
                  });
                });
              }
              return instantiateArrayBuffer(binaryFile, imports, callback);
            }
            __name(instantiateAsync, "instantiateAsync");
            function getWasmImports() {
              return {
                "env": wasmImports,
                "wasi_snapshot_preview1": wasmImports,
                "GOT.mem": new Proxy(wasmImports, GOTHandler),
                "GOT.func": new Proxy(wasmImports, GOTHandler)
              };
            }
            __name(getWasmImports, "getWasmImports");
            function createWasm() {
              var info2 = getWasmImports();
              function receiveInstance(instance2, module2) {
                wasmExports = instance2.exports;
                wasmExports = relocateExports(wasmExports, 1024);
                var metadata2 = getDylinkMetadata(module2);
                if (metadata2.neededDynlibs) {
                  dynamicLibraries = metadata2.neededDynlibs.concat(dynamicLibraries);
                }
                mergeLibSymbols(wasmExports, "main");
                LDSO.init();
                loadDylibs();
                addOnInit(wasmExports["__wasm_call_ctors"]);
                __RELOC_FUNCS__.push(wasmExports["__wasm_apply_data_relocs"]);
                removeRunDependency("wasm-instantiate");
                return wasmExports;
              }
              __name(receiveInstance, "receiveInstance");
              addRunDependency("wasm-instantiate");
              function receiveInstantiationResult(result) {
                receiveInstance(result["instance"], result["module"]);
              }
              __name(receiveInstantiationResult, "receiveInstantiationResult");
              if (Module["instantiateWasm"]) {
                try {
                  return Module["instantiateWasm"](info2, receiveInstance);
                } catch (e4) {
                  err(`Module.instantiateWasm callback failed with error: ${e4}`);
                  return false;
                }
              }
              if (!wasmBinaryFile) wasmBinaryFile = findWasmBinary();
              instantiateAsync(wasmBinary, wasmBinaryFile, info2, receiveInstantiationResult);
              return {};
            }
            __name(createWasm, "createWasm");
            var ASM_CONSTS = {};
            function ExitStatus(status) {
              this.name = "ExitStatus";
              this.message = `Program terminated with exit(${status})`;
              this.status = status;
            }
            __name(ExitStatus, "ExitStatus");
            var GOT = {};
            var currentModuleWeakSymbols = /* @__PURE__ */ new Set([]);
            var GOTHandler = {
              get(obj, symName) {
                var rtn = GOT[symName];
                if (!rtn) {
                  rtn = GOT[symName] = new WebAssembly.Global({
                    "value": "i32",
                    "mutable": true
                  });
                }
                if (!currentModuleWeakSymbols.has(symName)) {
                  rtn.required = true;
                }
                return rtn;
              }
            };
            var LE_HEAP_LOAD_F32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getFloat32(byteOffset, true), "LE_HEAP_LOAD_F32");
            var LE_HEAP_LOAD_F64 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getFloat64(byteOffset, true), "LE_HEAP_LOAD_F64");
            var LE_HEAP_LOAD_I16 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getInt16(byteOffset, true), "LE_HEAP_LOAD_I16");
            var LE_HEAP_LOAD_I32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getInt32(byteOffset, true), "LE_HEAP_LOAD_I32");
            var LE_HEAP_LOAD_U32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getUint32(byteOffset, true), "LE_HEAP_LOAD_U32");
            var LE_HEAP_STORE_F32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setFloat32(byteOffset, value, true), "LE_HEAP_STORE_F32");
            var LE_HEAP_STORE_F64 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setFloat64(byteOffset, value, true), "LE_HEAP_STORE_F64");
            var LE_HEAP_STORE_I16 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setInt16(byteOffset, value, true), "LE_HEAP_STORE_I16");
            var LE_HEAP_STORE_I32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setInt32(byteOffset, value, true), "LE_HEAP_STORE_I32");
            var LE_HEAP_STORE_U32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setUint32(byteOffset, value, true), "LE_HEAP_STORE_U32");
            var callRuntimeCallbacks = /* @__PURE__ */ __name((callbacks) => {
              while (callbacks.length > 0) {
                callbacks.shift()(Module);
              }
            }, "callRuntimeCallbacks");
            var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder() : void 0;
            var UTF8ArrayToString = /* @__PURE__ */ __name((heapOrArray, idx, maxBytesToRead) => {
              var endIdx = idx + maxBytesToRead;
              var endPtr = idx;
              while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
              if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
                return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
              }
              var str2 = "";
              while (idx < endPtr) {
                var u0 = heapOrArray[idx++];
                if (!(u0 & 128)) {
                  str2 += String.fromCharCode(u0);
                  continue;
                }
                var u1 = heapOrArray[idx++] & 63;
                if ((u0 & 224) == 192) {
                  str2 += String.fromCharCode((u0 & 31) << 6 | u1);
                  continue;
                }
                var u2 = heapOrArray[idx++] & 63;
                if ((u0 & 240) == 224) {
                  u0 = (u0 & 15) << 12 | u1 << 6 | u2;
                } else {
                  u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
                }
                if (u0 < 65536) {
                  str2 += String.fromCharCode(u0);
                } else {
                  var ch = u0 - 65536;
                  str2 += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
                }
              }
              return str2;
            }, "UTF8ArrayToString");
            var getDylinkMetadata = /* @__PURE__ */ __name((binary2) => {
              var offset = 0;
              var end = 0;
              function getU8() {
                return binary2[offset++];
              }
              __name(getU8, "getU8");
              function getLEB() {
                var ret = 0;
                var mul = 1;
                while (1) {
                  var byte = binary2[offset++];
                  ret += (byte & 127) * mul;
                  mul *= 128;
                  if (!(byte & 128)) break;
                }
                return ret;
              }
              __name(getLEB, "getLEB");
              function getString() {
                var len = getLEB();
                offset += len;
                return UTF8ArrayToString(binary2, offset - len, len);
              }
              __name(getString, "getString");
              function failIf(condition, message) {
                if (condition) throw new Error(message);
              }
              __name(failIf, "failIf");
              var name4 = "dylink.0";
              if (binary2 instanceof WebAssembly.Module) {
                var dylinkSection = WebAssembly.Module.customSections(binary2, name4);
                if (dylinkSection.length === 0) {
                  name4 = "dylink";
                  dylinkSection = WebAssembly.Module.customSections(binary2, name4);
                }
                failIf(dylinkSection.length === 0, "need dylink section");
                binary2 = new Uint8Array(dylinkSection[0]);
                end = binary2.length;
              } else {
                var int32View = new Uint32Array(new Uint8Array(binary2.subarray(0, 24)).buffer);
                var magicNumberFound = int32View[0] == 1836278016 || int32View[0] == 6386541;
                failIf(!magicNumberFound, "need to see wasm magic number");
                failIf(binary2[8] !== 0, "need the dylink section to be first");
                offset = 9;
                var section_size = getLEB();
                end = offset + section_size;
                name4 = getString();
              }
              var customSection = {
                neededDynlibs: [],
                tlsExports: /* @__PURE__ */ new Set(),
                weakImports: /* @__PURE__ */ new Set()
              };
              if (name4 == "dylink") {
                customSection.memorySize = getLEB();
                customSection.memoryAlign = getLEB();
                customSection.tableSize = getLEB();
                customSection.tableAlign = getLEB();
                var neededDynlibsCount = getLEB();
                for (var i4 = 0; i4 < neededDynlibsCount; ++i4) {
                  var libname = getString();
                  customSection.neededDynlibs.push(libname);
                }
              } else {
                failIf(name4 !== "dylink.0");
                var WASM_DYLINK_MEM_INFO = 1;
                var WASM_DYLINK_NEEDED = 2;
                var WASM_DYLINK_EXPORT_INFO = 3;
                var WASM_DYLINK_IMPORT_INFO = 4;
                var WASM_SYMBOL_TLS = 256;
                var WASM_SYMBOL_BINDING_MASK = 3;
                var WASM_SYMBOL_BINDING_WEAK = 1;
                while (offset < end) {
                  var subsectionType = getU8();
                  var subsectionSize = getLEB();
                  if (subsectionType === WASM_DYLINK_MEM_INFO) {
                    customSection.memorySize = getLEB();
                    customSection.memoryAlign = getLEB();
                    customSection.tableSize = getLEB();
                    customSection.tableAlign = getLEB();
                  } else if (subsectionType === WASM_DYLINK_NEEDED) {
                    var neededDynlibsCount = getLEB();
                    for (var i4 = 0; i4 < neededDynlibsCount; ++i4) {
                      libname = getString();
                      customSection.neededDynlibs.push(libname);
                    }
                  } else if (subsectionType === WASM_DYLINK_EXPORT_INFO) {
                    var count = getLEB();
                    while (count--) {
                      var symname = getString();
                      var flags2 = getLEB();
                      if (flags2 & WASM_SYMBOL_TLS) {
                        customSection.tlsExports.add(symname);
                      }
                    }
                  } else if (subsectionType === WASM_DYLINK_IMPORT_INFO) {
                    var count = getLEB();
                    while (count--) {
                      var modname = getString();
                      var symname = getString();
                      var flags2 = getLEB();
                      if ((flags2 & WASM_SYMBOL_BINDING_MASK) == WASM_SYMBOL_BINDING_WEAK) {
                        customSection.weakImports.add(symname);
                      }
                    }
                  } else {
                    offset += subsectionSize;
                  }
                }
              }
              return customSection;
            }, "getDylinkMetadata");
            function getValue(ptr, type = "i8") {
              if (type.endsWith("*")) type = "*";
              switch (type) {
                case "i1":
                  return HEAP8[ptr];
                case "i8":
                  return HEAP8[ptr];
                case "i16":
                  return LE_HEAP_LOAD_I16((ptr >> 1) * 2);
                case "i32":
                  return LE_HEAP_LOAD_I32((ptr >> 2) * 4);
                case "i64":
                  abort("to do getValue(i64) use WASM_BIGINT");
                case "float":
                  return LE_HEAP_LOAD_F32((ptr >> 2) * 4);
                case "double":
                  return LE_HEAP_LOAD_F64((ptr >> 3) * 8);
                case "*":
                  return LE_HEAP_LOAD_U32((ptr >> 2) * 4);
                default:
                  abort(`invalid type for getValue: ${type}`);
              }
            }
            __name(getValue, "getValue");
            var newDSO = /* @__PURE__ */ __name((name4, handle2, syms) => {
              var dso = {
                refcount: Infinity,
                name: name4,
                exports: syms,
                global: true
              };
              LDSO.loadedLibsByName[name4] = dso;
              if (handle2 != void 0) {
                LDSO.loadedLibsByHandle[handle2] = dso;
              }
              return dso;
            }, "newDSO");
            var LDSO = {
              loadedLibsByName: {},
              loadedLibsByHandle: {},
              init() {
                newDSO("__main__", 0, wasmImports);
              }
            };
            var ___heap_base = 78112;
            var zeroMemory = /* @__PURE__ */ __name((address, size) => {
              HEAPU8.fill(0, address, address + size);
              return address;
            }, "zeroMemory");
            var alignMemory = /* @__PURE__ */ __name((size, alignment) => Math.ceil(size / alignment) * alignment, "alignMemory");
            var getMemory = /* @__PURE__ */ __name((size) => {
              if (runtimeInitialized) {
                return zeroMemory(_malloc(size), size);
              }
              var ret = ___heap_base;
              var end = ret + alignMemory(size, 16);
              ___heap_base = end;
              GOT["__heap_base"].value = end;
              return ret;
            }, "getMemory");
            var isInternalSym = /* @__PURE__ */ __name((symName) => ["__cpp_exception", "__c_longjmp", "__wasm_apply_data_relocs", "__dso_handle", "__tls_size", "__tls_align", "__set_stack_limits", "_emscripten_tls_init", "__wasm_init_tls", "__wasm_call_ctors", "__start_em_asm", "__stop_em_asm", "__start_em_js", "__stop_em_js"].includes(symName) || symName.startsWith("__em_js__"), "isInternalSym");
            var uleb128Encode = /* @__PURE__ */ __name((n3, target) => {
              if (n3 < 128) {
                target.push(n3);
              } else {
                target.push(n3 % 128 | 128, n3 >> 7);
              }
            }, "uleb128Encode");
            var sigToWasmTypes = /* @__PURE__ */ __name((sig) => {
              var typeNames = {
                "i": "i32",
                "j": "i64",
                "f": "f32",
                "d": "f64",
                "e": "externref",
                "p": "i32"
              };
              var type = {
                parameters: [],
                results: sig[0] == "v" ? [] : [typeNames[sig[0]]]
              };
              for (var i4 = 1; i4 < sig.length; ++i4) {
                type.parameters.push(typeNames[sig[i4]]);
              }
              return type;
            }, "sigToWasmTypes");
            var generateFuncType = /* @__PURE__ */ __name((sig, target) => {
              var sigRet = sig.slice(0, 1);
              var sigParam = sig.slice(1);
              var typeCodes = {
                "i": 127,
                // i32
                "p": 127,
                // i32
                "j": 126,
                // i64
                "f": 125,
                // f32
                "d": 124,
                // f64
                "e": 111
              };
              target.push(96);
              uleb128Encode(sigParam.length, target);
              for (var i4 = 0; i4 < sigParam.length; ++i4) {
                target.push(typeCodes[sigParam[i4]]);
              }
              if (sigRet == "v") {
                target.push(0);
              } else {
                target.push(1, typeCodes[sigRet]);
              }
            }, "generateFuncType");
            var convertJsFunctionToWasm = /* @__PURE__ */ __name((func2, sig) => {
              if (typeof WebAssembly.Function == "function") {
                return new WebAssembly.Function(sigToWasmTypes(sig), func2);
              }
              var typeSectionBody = [1];
              generateFuncType(sig, typeSectionBody);
              var bytes = [
                0,
                97,
                115,
                109,
                // magic ("\0asm")
                1,
                0,
                0,
                0,
                // version: 1
                1
              ];
              uleb128Encode(typeSectionBody.length, bytes);
              bytes.push(...typeSectionBody);
              bytes.push(
                2,
                7,
                // import section
                // (import "e" "f" (func 0 (type 0)))
                1,
                1,
                101,
                1,
                102,
                0,
                0,
                7,
                5,
                // export section
                // (export "f" (func 0 (type 0)))
                1,
                1,
                102,
                0,
                0
              );
              var module2 = new WebAssembly.Module(new Uint8Array(bytes));
              var instance2 = new WebAssembly.Instance(module2, {
                "e": {
                  "f": func2
                }
              });
              var wrappedFunc = instance2.exports["f"];
              return wrappedFunc;
            }, "convertJsFunctionToWasm");
            var wasmTableMirror = [];
            var wasmTable = new WebAssembly.Table({
              "initial": 28,
              "element": "anyfunc"
            });
            var getWasmTableEntry = /* @__PURE__ */ __name((funcPtr) => {
              var func2 = wasmTableMirror[funcPtr];
              if (!func2) {
                if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;
                wasmTableMirror[funcPtr] = func2 = wasmTable.get(funcPtr);
              }
              return func2;
            }, "getWasmTableEntry");
            var updateTableMap = /* @__PURE__ */ __name((offset, count) => {
              if (functionsInTableMap) {
                for (var i4 = offset; i4 < offset + count; i4++) {
                  var item = getWasmTableEntry(i4);
                  if (item) {
                    functionsInTableMap.set(item, i4);
                  }
                }
              }
            }, "updateTableMap");
            var functionsInTableMap;
            var getFunctionAddress = /* @__PURE__ */ __name((func2) => {
              if (!functionsInTableMap) {
                functionsInTableMap = /* @__PURE__ */ new WeakMap();
                updateTableMap(0, wasmTable.length);
              }
              return functionsInTableMap.get(func2) || 0;
            }, "getFunctionAddress");
            var freeTableIndexes = [];
            var getEmptyTableSlot = /* @__PURE__ */ __name(() => {
              if (freeTableIndexes.length) {
                return freeTableIndexes.pop();
              }
              try {
                wasmTable.grow(1);
              } catch (err2) {
                if (!(err2 instanceof RangeError)) {
                  throw err2;
                }
                throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";
              }
              return wasmTable.length - 1;
            }, "getEmptyTableSlot");
            var setWasmTableEntry = /* @__PURE__ */ __name((idx, func2) => {
              wasmTable.set(idx, func2);
              wasmTableMirror[idx] = wasmTable.get(idx);
            }, "setWasmTableEntry");
            var addFunction = /* @__PURE__ */ __name((func2, sig) => {
              var rtn = getFunctionAddress(func2);
              if (rtn) {
                return rtn;
              }
              var ret = getEmptyTableSlot();
              try {
                setWasmTableEntry(ret, func2);
              } catch (err2) {
                if (!(err2 instanceof TypeError)) {
                  throw err2;
                }
                var wrapped = convertJsFunctionToWasm(func2, sig);
                setWasmTableEntry(ret, wrapped);
              }
              functionsInTableMap.set(func2, ret);
              return ret;
            }, "addFunction");
            var updateGOT = /* @__PURE__ */ __name((exports2, replace2) => {
              for (var symName in exports2) {
                if (isInternalSym(symName)) {
                  continue;
                }
                var value = exports2[symName];
                if (symName.startsWith("orig$")) {
                  symName = symName.split("$")[1];
                  replace2 = true;
                }
                GOT[symName] ||= new WebAssembly.Global({
                  "value": "i32",
                  "mutable": true
                });
                if (replace2 || GOT[symName].value == 0) {
                  if (typeof value == "function") {
                    GOT[symName].value = addFunction(value);
                  } else if (typeof value == "number") {
                    GOT[symName].value = value;
                  } else {
                    err(`unhandled export type for '${symName}': ${typeof value}`);
                  }
                }
              }
            }, "updateGOT");
            var relocateExports = /* @__PURE__ */ __name((exports2, memoryBase2, replace2) => {
              var relocated = {};
              for (var e4 in exports2) {
                var value = exports2[e4];
                if (typeof value == "object") {
                  value = value.value;
                }
                if (typeof value == "number") {
                  value += memoryBase2;
                }
                relocated[e4] = value;
              }
              updateGOT(relocated, replace2);
              return relocated;
            }, "relocateExports");
            var isSymbolDefined = /* @__PURE__ */ __name((symName) => {
              var existing = wasmImports[symName];
              if (!existing || existing.stub) {
                return false;
              }
              return true;
            }, "isSymbolDefined");
            var dynCallLegacy = /* @__PURE__ */ __name((sig, ptr, args2) => {
              sig = sig.replace(/p/g, "i");
              var f5 = Module["dynCall_" + sig];
              return f5(ptr, ...args2);
            }, "dynCallLegacy");
            var dynCall = /* @__PURE__ */ __name((sig, ptr, args2 = []) => {
              if (sig.includes("j")) {
                return dynCallLegacy(sig, ptr, args2);
              }
              var rtn = getWasmTableEntry(ptr)(...args2);
              return rtn;
            }, "dynCall");
            var stackSave = /* @__PURE__ */ __name(() => _emscripten_stack_get_current(), "stackSave");
            var stackRestore = /* @__PURE__ */ __name((val) => __emscripten_stack_restore(val), "stackRestore");
            var createInvokeFunction = /* @__PURE__ */ __name((sig) => (ptr, ...args2) => {
              var sp = stackSave();
              try {
                return dynCall(sig, ptr, args2);
              } catch (e4) {
                stackRestore(sp);
                if (e4 !== e4 + 0) throw e4;
                _setThrew(1, 0);
              }
            }, "createInvokeFunction");
            var resolveGlobalSymbol = /* @__PURE__ */ __name((symName, direct = false) => {
              var sym;
              if (direct && "orig$" + symName in wasmImports) {
                symName = "orig$" + symName;
              }
              if (isSymbolDefined(symName)) {
                sym = wasmImports[symName];
              } else if (symName.startsWith("invoke_")) {
                sym = wasmImports[symName] = createInvokeFunction(symName.split("_")[1]);
              }
              return {
                sym,
                name: symName
              };
            }, "resolveGlobalSymbol");
            var UTF8ToString = /* @__PURE__ */ __name((ptr, maxBytesToRead) => ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "", "UTF8ToString");
            var loadWebAssemblyModule = /* @__PURE__ */ __name((binary, flags, libName, localScope, handle) => {
              var metadata = getDylinkMetadata(binary);
              currentModuleWeakSymbols = metadata.weakImports;
              function loadModule() {
                var firstLoad = !handle || !HEAP8[handle + 8];
                if (firstLoad) {
                  var memAlign = Math.pow(2, metadata.memoryAlign);
                  var memoryBase = metadata.memorySize ? alignMemory(getMemory(metadata.memorySize + memAlign), memAlign) : 0;
                  var tableBase = metadata.tableSize ? wasmTable.length : 0;
                  if (handle) {
                    HEAP8[handle + 8] = 1;
                    LE_HEAP_STORE_U32((handle + 12 >> 2) * 4, memoryBase);
                    LE_HEAP_STORE_I32((handle + 16 >> 2) * 4, metadata.memorySize);
                    LE_HEAP_STORE_U32((handle + 20 >> 2) * 4, tableBase);
                    LE_HEAP_STORE_I32((handle + 24 >> 2) * 4, metadata.tableSize);
                  }
                } else {
                  memoryBase = LE_HEAP_LOAD_U32((handle + 12 >> 2) * 4);
                  tableBase = LE_HEAP_LOAD_U32((handle + 20 >> 2) * 4);
                }
                var tableGrowthNeeded = tableBase + metadata.tableSize - wasmTable.length;
                if (tableGrowthNeeded > 0) {
                  wasmTable.grow(tableGrowthNeeded);
                }
                var moduleExports;
                function resolveSymbol(sym) {
                  var resolved = resolveGlobalSymbol(sym).sym;
                  if (!resolved && localScope) {
                    resolved = localScope[sym];
                  }
                  if (!resolved) {
                    resolved = moduleExports[sym];
                  }
                  return resolved;
                }
                __name(resolveSymbol, "resolveSymbol");
                var proxyHandler = {
                  get(stubs, prop) {
                    switch (prop) {
                      case "__memory_base":
                        return memoryBase;
                      case "__table_base":
                        return tableBase;
                    }
                    if (prop in wasmImports && !wasmImports[prop].stub) {
                      return wasmImports[prop];
                    }
                    if (!(prop in stubs)) {
                      var resolved;
                      stubs[prop] = (...args2) => {
                        resolved ||= resolveSymbol(prop);
                        return resolved(...args2);
                      };
                    }
                    return stubs[prop];
                  }
                };
                var proxy = new Proxy({}, proxyHandler);
                var info = {
                  "GOT.mem": new Proxy({}, GOTHandler),
                  "GOT.func": new Proxy({}, GOTHandler),
                  "env": proxy,
                  "wasi_snapshot_preview1": proxy
                };
                function postInstantiation(module, instance) {
                  updateTableMap(tableBase, metadata.tableSize);
                  moduleExports = relocateExports(instance.exports, memoryBase);
                  if (!flags.allowUndefined) {
                    reportUndefinedSymbols();
                  }
                  function addEmAsm(addr, body) {
                    var args = [];
                    var arity = 0;
                    for (; arity < 16; arity++) {
                      if (body.indexOf("$" + arity) != -1) {
                        args.push("$" + arity);
                      } else {
                        break;
                      }
                    }
                    args = args.join(",");
                    var func = `(${args}) => { ${body} };`;
                    ASM_CONSTS[start] = eval(func);
                  }
                  __name(addEmAsm, "addEmAsm");
                  if ("__start_em_asm" in moduleExports) {
                    var start = moduleExports["__start_em_asm"];
                    var stop = moduleExports["__stop_em_asm"];
                    while (start < stop) {
                      var jsString = UTF8ToString(start);
                      addEmAsm(start, jsString);
                      start = HEAPU8.indexOf(0, start) + 1;
                    }
                  }
                  function addEmJs(name, cSig, body) {
                    var jsArgs = [];
                    cSig = cSig.slice(1, -1);
                    if (cSig != "void") {
                      cSig = cSig.split(",");
                      for (var i in cSig) {
                        var jsArg = cSig[i].split(" ").pop();
                        jsArgs.push(jsArg.replace("*", ""));
                      }
                    }
                    var func = `(${jsArgs}) => ${body};`;
                    moduleExports[name] = eval(func);
                  }
                  __name(addEmJs, "addEmJs");
                  for (var name in moduleExports) {
                    if (name.startsWith("__em_js__")) {
                      var start = moduleExports[name];
                      var jsString = UTF8ToString(start);
                      var parts = jsString.split("<::>");
                      addEmJs(name.replace("__em_js__", ""), parts[0], parts[1]);
                      delete moduleExports[name];
                    }
                  }
                  var applyRelocs = moduleExports["__wasm_apply_data_relocs"];
                  if (applyRelocs) {
                    if (runtimeInitialized) {
                      applyRelocs();
                    } else {
                      __RELOC_FUNCS__.push(applyRelocs);
                    }
                  }
                  var init = moduleExports["__wasm_call_ctors"];
                  if (init) {
                    if (runtimeInitialized) {
                      init();
                    } else {
                      __ATINIT__.push(init);
                    }
                  }
                  return moduleExports;
                }
                __name(postInstantiation, "postInstantiation");
                if (flags.loadAsync) {
                  if (binary instanceof WebAssembly.Module) {
                    var instance = new WebAssembly.Instance(binary, info);
                    return Promise.resolve(postInstantiation(binary, instance));
                  }
                  return WebAssembly.instantiate(binary, info).then((result) => postInstantiation(result.module, result.instance));
                }
                var module = binary instanceof WebAssembly.Module ? binary : new WebAssembly.Module(binary);
                var instance = new WebAssembly.Instance(module, info);
                return postInstantiation(module, instance);
              }
              __name(loadModule, "loadModule");
              if (flags.loadAsync) {
                return metadata.neededDynlibs.reduce((chain2, dynNeeded) => chain2.then(() => loadDynamicLibrary(dynNeeded, flags, localScope)), Promise.resolve()).then(loadModule);
              }
              metadata.neededDynlibs.forEach((needed) => loadDynamicLibrary(needed, flags, localScope));
              return loadModule();
            }, "loadWebAssemblyModule");
            var mergeLibSymbols = /* @__PURE__ */ __name((exports2, libName2) => {
              for (var [sym, exp] of Object.entries(exports2)) {
                const setImport = /* @__PURE__ */ __name((target) => {
                  if (!isSymbolDefined(target)) {
                    wasmImports[target] = exp;
                  }
                }, "setImport");
                setImport(sym);
                const main_alias = "__main_argc_argv";
                if (sym == "main") {
                  setImport(main_alias);
                }
                if (sym == main_alias) {
                  setImport("main");
                }
                if (sym.startsWith("dynCall_") && !Module.hasOwnProperty(sym)) {
                  Module[sym] = exp;
                }
              }
            }, "mergeLibSymbols");
            var asyncLoad = /* @__PURE__ */ __name((url3, onload, onerror, noRunDep) => {
              var dep = !noRunDep ? getUniqueRunDependency(`al ${url3}`) : "";
              readAsync(url3).then((arrayBuffer) => {
                onload(new Uint8Array(arrayBuffer));
                if (dep) removeRunDependency(dep);
              }, (err2) => {
                if (onerror) {
                  onerror();
                } else {
                  throw `Loading data file "${url3}" failed.`;
                }
              });
              if (dep) addRunDependency(dep);
            }, "asyncLoad");
            function loadDynamicLibrary(libName2, flags2 = {
              global: true,
              nodelete: true
            }, localScope2, handle2) {
              var dso = LDSO.loadedLibsByName[libName2];
              if (dso) {
                if (!flags2.global) {
                  if (localScope2) {
                    Object.assign(localScope2, dso.exports);
                  }
                } else if (!dso.global) {
                  dso.global = true;
                  mergeLibSymbols(dso.exports, libName2);
                }
                if (flags2.nodelete && dso.refcount !== Infinity) {
                  dso.refcount = Infinity;
                }
                dso.refcount++;
                if (handle2) {
                  LDSO.loadedLibsByHandle[handle2] = dso;
                }
                return flags2.loadAsync ? Promise.resolve(true) : true;
              }
              dso = newDSO(libName2, handle2, "loading");
              dso.refcount = flags2.nodelete ? Infinity : 1;
              dso.global = flags2.global;
              function loadLibData() {
                if (handle2) {
                  var data = LE_HEAP_LOAD_U32((handle2 + 28 >> 2) * 4);
                  var dataSize = LE_HEAP_LOAD_U32((handle2 + 32 >> 2) * 4);
                  if (data && dataSize) {
                    var libData = HEAP8.slice(data, data + dataSize);
                    return flags2.loadAsync ? Promise.resolve(libData) : libData;
                  }
                }
                var libFile = locateFile(libName2);
                if (flags2.loadAsync) {
                  return new Promise(function(resolve42, reject) {
                    asyncLoad(libFile, resolve42, reject);
                  });
                }
                if (!readBinary) {
                  throw new Error(`${libFile}: file not found, and synchronous loading of external files is not available`);
                }
                return readBinary(libFile);
              }
              __name(loadLibData, "loadLibData");
              function getExports() {
                if (flags2.loadAsync) {
                  return loadLibData().then((libData) => loadWebAssemblyModule(libData, flags2, libName2, localScope2, handle2));
                }
                return loadWebAssemblyModule(loadLibData(), flags2, libName2, localScope2, handle2);
              }
              __name(getExports, "getExports");
              function moduleLoaded(exports2) {
                if (dso.global) {
                  mergeLibSymbols(exports2, libName2);
                } else if (localScope2) {
                  Object.assign(localScope2, exports2);
                }
                dso.exports = exports2;
              }
              __name(moduleLoaded, "moduleLoaded");
              if (flags2.loadAsync) {
                return getExports().then((exports2) => {
                  moduleLoaded(exports2);
                  return true;
                });
              }
              moduleLoaded(getExports());
              return true;
            }
            __name(loadDynamicLibrary, "loadDynamicLibrary");
            var reportUndefinedSymbols = /* @__PURE__ */ __name(() => {
              for (var [symName, entry] of Object.entries(GOT)) {
                if (entry.value == 0) {
                  var value = resolveGlobalSymbol(symName, true).sym;
                  if (!value && !entry.required) {
                    continue;
                  }
                  if (typeof value == "function") {
                    entry.value = addFunction(value, value.sig);
                  } else if (typeof value == "number") {
                    entry.value = value;
                  } else {
                    throw new Error(`bad export type for '${symName}': ${typeof value}`);
                  }
                }
              }
            }, "reportUndefinedSymbols");
            var loadDylibs = /* @__PURE__ */ __name(() => {
              if (!dynamicLibraries.length) {
                reportUndefinedSymbols();
                return;
              }
              addRunDependency("loadDylibs");
              dynamicLibraries.reduce((chain2, lib) => chain2.then(() => loadDynamicLibrary(lib, {
                loadAsync: true,
                global: true,
                nodelete: true,
                allowUndefined: true
              })), Promise.resolve()).then(() => {
                reportUndefinedSymbols();
                removeRunDependency("loadDylibs");
              });
            }, "loadDylibs");
            var noExitRuntime = Module["noExitRuntime"] || true;
            function setValue(ptr, value, type = "i8") {
              if (type.endsWith("*")) type = "*";
              switch (type) {
                case "i1":
                  HEAP8[ptr] = value;
                  break;
                case "i8":
                  HEAP8[ptr] = value;
                  break;
                case "i16":
                  LE_HEAP_STORE_I16((ptr >> 1) * 2, value);
                  break;
                case "i32":
                  LE_HEAP_STORE_I32((ptr >> 2) * 4, value);
                  break;
                case "i64":
                  abort("to do setValue(i64) use WASM_BIGINT");
                case "float":
                  LE_HEAP_STORE_F32((ptr >> 2) * 4, value);
                  break;
                case "double":
                  LE_HEAP_STORE_F64((ptr >> 3) * 8, value);
                  break;
                case "*":
                  LE_HEAP_STORE_U32((ptr >> 2) * 4, value);
                  break;
                default:
                  abort(`invalid type for setValue: ${type}`);
              }
            }
            __name(setValue, "setValue");
            var ___memory_base = new WebAssembly.Global({
              "value": "i32",
              "mutable": false
            }, 1024);
            var ___stack_pointer = new WebAssembly.Global({
              "value": "i32",
              "mutable": true
            }, 78112);
            var ___table_base = new WebAssembly.Global({
              "value": "i32",
              "mutable": false
            }, 1);
            var __abort_js = /* @__PURE__ */ __name(() => {
              abort("");
            }, "__abort_js");
            __abort_js.sig = "v";
            var nowIsMonotonic = 1;
            var __emscripten_get_now_is_monotonic = /* @__PURE__ */ __name(() => nowIsMonotonic, "__emscripten_get_now_is_monotonic");
            __emscripten_get_now_is_monotonic.sig = "i";
            var __emscripten_memcpy_js = /* @__PURE__ */ __name((dest, src, num) => HEAPU8.copyWithin(dest, src, src + num), "__emscripten_memcpy_js");
            __emscripten_memcpy_js.sig = "vppp";
            var _emscripten_date_now = /* @__PURE__ */ __name(() => Date.now(), "_emscripten_date_now");
            _emscripten_date_now.sig = "d";
            var _emscripten_get_now;
            _emscripten_get_now = /* @__PURE__ */ __name(() => performance.now(), "_emscripten_get_now");
            _emscripten_get_now.sig = "d";
            var getHeapMax = /* @__PURE__ */ __name(() => (
              // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
              // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
              // for any code that deals with heap sizes, which would require special
              // casing all heap size related code to treat 0 specially.
              2147483648
            ), "getHeapMax");
            var growMemory = /* @__PURE__ */ __name((size) => {
              var b2 = wasmMemory.buffer;
              var pages = (size - b2.byteLength + 65535) / 65536;
              try {
                wasmMemory.grow(pages);
                updateMemoryViews();
                return 1;
              } catch (e4) {
              }
            }, "growMemory");
            var _emscripten_resize_heap = /* @__PURE__ */ __name((requestedSize) => {
              var oldSize = HEAPU8.length;
              requestedSize >>>= 0;
              var maxHeapSize = getHeapMax();
              if (requestedSize > maxHeapSize) {
                return false;
              }
              var alignUp = /* @__PURE__ */ __name((x3, multiple) => x3 + (multiple - x3 % multiple) % multiple, "alignUp");
              for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
                var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
                overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
                var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536));
                var replacement = growMemory(newSize);
                if (replacement) {
                  return true;
                }
              }
              return false;
            }, "_emscripten_resize_heap");
            _emscripten_resize_heap.sig = "ip";
            var _fd_close = /* @__PURE__ */ __name((fd) => 52, "_fd_close");
            _fd_close.sig = "ii";
            var convertI32PairToI53Checked = /* @__PURE__ */ __name((lo, hi) => hi + 2097152 >>> 0 < 4194305 - !!lo ? (lo >>> 0) + hi * 4294967296 : NaN, "convertI32PairToI53Checked");
            function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
              var offset = convertI32PairToI53Checked(offset_low, offset_high);
              return 70;
            }
            __name(_fd_seek, "_fd_seek");
            _fd_seek.sig = "iiiiip";
            var printCharBuffers = [null, [], []];
            var printChar = /* @__PURE__ */ __name((stream5, curr) => {
              var buffer = printCharBuffers[stream5];
              if (curr === 0 || curr === 10) {
                (stream5 === 1 ? out : err)(UTF8ArrayToString(buffer, 0));
                buffer.length = 0;
              } else {
                buffer.push(curr);
              }
            }, "printChar");
            var _fd_write = /* @__PURE__ */ __name((fd, iov, iovcnt, pnum) => {
              var num = 0;
              for (var i4 = 0; i4 < iovcnt; i4++) {
                var ptr = LE_HEAP_LOAD_U32((iov >> 2) * 4);
                var len = LE_HEAP_LOAD_U32((iov + 4 >> 2) * 4);
                iov += 8;
                for (var j2 = 0; j2 < len; j2++) {
                  printChar(fd, HEAPU8[ptr + j2]);
                }
                num += len;
              }
              LE_HEAP_STORE_U32((pnum >> 2) * 4, num);
              return 0;
            }, "_fd_write");
            _fd_write.sig = "iippp";
            function _tree_sitter_log_callback(isLexMessage, messageAddress) {
              if (currentLogCallback) {
                const message = UTF8ToString(messageAddress);
                currentLogCallback(message, isLexMessage !== 0);
              }
            }
            __name(_tree_sitter_log_callback, "_tree_sitter_log_callback");
            function _tree_sitter_parse_callback(inputBufferAddress, index, row, column, lengthAddress) {
              const INPUT_BUFFER_SIZE = 10 * 1024;
              const string4 = currentParseCallback(index, {
                row,
                column
              });
              if (typeof string4 === "string") {
                setValue(lengthAddress, string4.length, "i32");
                stringToUTF16(string4, inputBufferAddress, INPUT_BUFFER_SIZE);
              } else {
                setValue(lengthAddress, 0, "i32");
              }
            }
            __name(_tree_sitter_parse_callback, "_tree_sitter_parse_callback");
            var runtimeKeepaliveCounter = 0;
            var keepRuntimeAlive = /* @__PURE__ */ __name(() => noExitRuntime || runtimeKeepaliveCounter > 0, "keepRuntimeAlive");
            var _proc_exit = /* @__PURE__ */ __name((code2) => {
              EXITSTATUS = code2;
              if (!keepRuntimeAlive()) {
                Module["onExit"]?.(code2);
                ABORT = true;
              }
              quit_(code2, new ExitStatus(code2));
            }, "_proc_exit");
            _proc_exit.sig = "vi";
            var exitJS = /* @__PURE__ */ __name((status, implicit) => {
              EXITSTATUS = status;
              _proc_exit(status);
            }, "exitJS");
            var handleException = /* @__PURE__ */ __name((e4) => {
              if (e4 instanceof ExitStatus || e4 == "unwind") {
                return EXITSTATUS;
              }
              quit_(1, e4);
            }, "handleException");
            var lengthBytesUTF8 = /* @__PURE__ */ __name((str2) => {
              var len = 0;
              for (var i4 = 0; i4 < str2.length; ++i4) {
                var c4 = str2.charCodeAt(i4);
                if (c4 <= 127) {
                  len++;
                } else if (c4 <= 2047) {
                  len += 2;
                } else if (c4 >= 55296 && c4 <= 57343) {
                  len += 4;
                  ++i4;
                } else {
                  len += 3;
                }
              }
              return len;
            }, "lengthBytesUTF8");
            var stringToUTF8Array = /* @__PURE__ */ __name((str2, heap, outIdx, maxBytesToWrite) => {
              if (!(maxBytesToWrite > 0)) return 0;
              var startIdx = outIdx;
              var endIdx = outIdx + maxBytesToWrite - 1;
              for (var i4 = 0; i4 < str2.length; ++i4) {
                var u2 = str2.charCodeAt(i4);
                if (u2 >= 55296 && u2 <= 57343) {
                  var u1 = str2.charCodeAt(++i4);
                  u2 = 65536 + ((u2 & 1023) << 10) | u1 & 1023;
                }
                if (u2 <= 127) {
                  if (outIdx >= endIdx) break;
                  heap[outIdx++] = u2;
                } else if (u2 <= 2047) {
                  if (outIdx + 1 >= endIdx) break;
                  heap[outIdx++] = 192 | u2 >> 6;
                  heap[outIdx++] = 128 | u2 & 63;
                } else if (u2 <= 65535) {
                  if (outIdx + 2 >= endIdx) break;
                  heap[outIdx++] = 224 | u2 >> 12;
                  heap[outIdx++] = 128 | u2 >> 6 & 63;
                  heap[outIdx++] = 128 | u2 & 63;
                } else {
                  if (outIdx + 3 >= endIdx) break;
                  heap[outIdx++] = 240 | u2 >> 18;
                  heap[outIdx++] = 128 | u2 >> 12 & 63;
                  heap[outIdx++] = 128 | u2 >> 6 & 63;
                  heap[outIdx++] = 128 | u2 & 63;
                }
              }
              heap[outIdx] = 0;
              return outIdx - startIdx;
            }, "stringToUTF8Array");
            var stringToUTF8 = /* @__PURE__ */ __name((str2, outPtr, maxBytesToWrite) => stringToUTF8Array(str2, HEAPU8, outPtr, maxBytesToWrite), "stringToUTF8");
            var stackAlloc = /* @__PURE__ */ __name((sz) => __emscripten_stack_alloc(sz), "stackAlloc");
            var stringToUTF8OnStack = /* @__PURE__ */ __name((str2) => {
              var size = lengthBytesUTF8(str2) + 1;
              var ret = stackAlloc(size);
              stringToUTF8(str2, ret, size);
              return ret;
            }, "stringToUTF8OnStack");
            var stringToUTF16 = /* @__PURE__ */ __name((str2, outPtr, maxBytesToWrite) => {
              maxBytesToWrite ??= 2147483647;
              if (maxBytesToWrite < 2) return 0;
              maxBytesToWrite -= 2;
              var startPtr = outPtr;
              var numCharsToWrite = maxBytesToWrite < str2.length * 2 ? maxBytesToWrite / 2 : str2.length;
              for (var i4 = 0; i4 < numCharsToWrite; ++i4) {
                var codeUnit = str2.charCodeAt(i4);
                LE_HEAP_STORE_I16((outPtr >> 1) * 2, codeUnit);
                outPtr += 2;
              }
              LE_HEAP_STORE_I16((outPtr >> 1) * 2, 0);
              return outPtr - startPtr;
            }, "stringToUTF16");
            var AsciiToString = /* @__PURE__ */ __name((ptr) => {
              var str2 = "";
              while (1) {
                var ch = HEAPU8[ptr++];
                if (!ch) return str2;
                str2 += String.fromCharCode(ch);
              }
            }, "AsciiToString");
            var wasmImports = {
              /** @export */
              __heap_base: ___heap_base,
              /** @export */
              __indirect_function_table: wasmTable,
              /** @export */
              __memory_base: ___memory_base,
              /** @export */
              __stack_pointer: ___stack_pointer,
              /** @export */
              __table_base: ___table_base,
              /** @export */
              _abort_js: __abort_js,
              /** @export */
              _emscripten_get_now_is_monotonic: __emscripten_get_now_is_monotonic,
              /** @export */
              _emscripten_memcpy_js: __emscripten_memcpy_js,
              /** @export */
              emscripten_get_now: _emscripten_get_now,
              /** @export */
              emscripten_resize_heap: _emscripten_resize_heap,
              /** @export */
              fd_close: _fd_close,
              /** @export */
              fd_seek: _fd_seek,
              /** @export */
              fd_write: _fd_write,
              /** @export */
              memory: wasmMemory,
              /** @export */
              tree_sitter_log_callback: _tree_sitter_log_callback,
              /** @export */
              tree_sitter_parse_callback: _tree_sitter_parse_callback
            };
            var wasmExports = createWasm();
            var ___wasm_call_ctors = /* @__PURE__ */ __name(() => (___wasm_call_ctors = wasmExports["__wasm_call_ctors"])(), "___wasm_call_ctors");
            var ___wasm_apply_data_relocs = /* @__PURE__ */ __name(() => (___wasm_apply_data_relocs = wasmExports["__wasm_apply_data_relocs"])(), "___wasm_apply_data_relocs");
            var _malloc = Module["_malloc"] = (a0) => (_malloc = Module["_malloc"] = wasmExports["malloc"])(a0);
            var _calloc = Module["_calloc"] = (a0, a1) => (_calloc = Module["_calloc"] = wasmExports["calloc"])(a0, a1);
            var _realloc = Module["_realloc"] = (a0, a1) => (_realloc = Module["_realloc"] = wasmExports["realloc"])(a0, a1);
            var _free = Module["_free"] = (a0) => (_free = Module["_free"] = wasmExports["free"])(a0);
            var _ts_language_symbol_count = Module["_ts_language_symbol_count"] = (a0) => (_ts_language_symbol_count = Module["_ts_language_symbol_count"] = wasmExports["ts_language_symbol_count"])(a0);
            var _ts_language_state_count = Module["_ts_language_state_count"] = (a0) => (_ts_language_state_count = Module["_ts_language_state_count"] = wasmExports["ts_language_state_count"])(a0);
            var _ts_language_version = Module["_ts_language_version"] = (a0) => (_ts_language_version = Module["_ts_language_version"] = wasmExports["ts_language_version"])(a0);
            var _ts_language_field_count = Module["_ts_language_field_count"] = (a0) => (_ts_language_field_count = Module["_ts_language_field_count"] = wasmExports["ts_language_field_count"])(a0);
            var _ts_language_next_state = Module["_ts_language_next_state"] = (a0, a1, a2) => (_ts_language_next_state = Module["_ts_language_next_state"] = wasmExports["ts_language_next_state"])(a0, a1, a2);
            var _ts_language_symbol_name = Module["_ts_language_symbol_name"] = (a0, a1) => (_ts_language_symbol_name = Module["_ts_language_symbol_name"] = wasmExports["ts_language_symbol_name"])(a0, a1);
            var _ts_language_symbol_for_name = Module["_ts_language_symbol_for_name"] = (a0, a1, a2, a3) => (_ts_language_symbol_for_name = Module["_ts_language_symbol_for_name"] = wasmExports["ts_language_symbol_for_name"])(a0, a1, a2, a3);
            var _strncmp = Module["_strncmp"] = (a0, a1, a2) => (_strncmp = Module["_strncmp"] = wasmExports["strncmp"])(a0, a1, a2);
            var _ts_language_symbol_type = Module["_ts_language_symbol_type"] = (a0, a1) => (_ts_language_symbol_type = Module["_ts_language_symbol_type"] = wasmExports["ts_language_symbol_type"])(a0, a1);
            var _ts_language_field_name_for_id = Module["_ts_language_field_name_for_id"] = (a0, a1) => (_ts_language_field_name_for_id = Module["_ts_language_field_name_for_id"] = wasmExports["ts_language_field_name_for_id"])(a0, a1);
            var _ts_lookahead_iterator_new = Module["_ts_lookahead_iterator_new"] = (a0, a1) => (_ts_lookahead_iterator_new = Module["_ts_lookahead_iterator_new"] = wasmExports["ts_lookahead_iterator_new"])(a0, a1);
            var _ts_lookahead_iterator_delete = Module["_ts_lookahead_iterator_delete"] = (a0) => (_ts_lookahead_iterator_delete = Module["_ts_lookahead_iterator_delete"] = wasmExports["ts_lookahead_iterator_delete"])(a0);
            var _ts_lookahead_iterator_reset_state = Module["_ts_lookahead_iterator_reset_state"] = (a0, a1) => (_ts_lookahead_iterator_reset_state = Module["_ts_lookahead_iterator_reset_state"] = wasmExports["ts_lookahead_iterator_reset_state"])(a0, a1);
            var _ts_lookahead_iterator_reset = Module["_ts_lookahead_iterator_reset"] = (a0, a1, a2) => (_ts_lookahead_iterator_reset = Module["_ts_lookahead_iterator_reset"] = wasmExports["ts_lookahead_iterator_reset"])(a0, a1, a2);
            var _ts_lookahead_iterator_next = Module["_ts_lookahead_iterator_next"] = (a0) => (_ts_lookahead_iterator_next = Module["_ts_lookahead_iterator_next"] = wasmExports["ts_lookahead_iterator_next"])(a0);
            var _ts_lookahead_iterator_current_symbol = Module["_ts_lookahead_iterator_current_symbol"] = (a0) => (_ts_lookahead_iterator_current_symbol = Module["_ts_lookahead_iterator_current_symbol"] = wasmExports["ts_lookahead_iterator_current_symbol"])(a0);
            var _memset = Module["_memset"] = (a0, a1, a2) => (_memset = Module["_memset"] = wasmExports["memset"])(a0, a1, a2);
            var _memcpy = Module["_memcpy"] = (a0, a1, a2) => (_memcpy = Module["_memcpy"] = wasmExports["memcpy"])(a0, a1, a2);
            var _ts_parser_delete = Module["_ts_parser_delete"] = (a0) => (_ts_parser_delete = Module["_ts_parser_delete"] = wasmExports["ts_parser_delete"])(a0);
            var _ts_parser_reset = Module["_ts_parser_reset"] = (a0) => (_ts_parser_reset = Module["_ts_parser_reset"] = wasmExports["ts_parser_reset"])(a0);
            var _ts_parser_set_language = Module["_ts_parser_set_language"] = (a0, a1) => (_ts_parser_set_language = Module["_ts_parser_set_language"] = wasmExports["ts_parser_set_language"])(a0, a1);
            var _ts_parser_timeout_micros = Module["_ts_parser_timeout_micros"] = (a0) => (_ts_parser_timeout_micros = Module["_ts_parser_timeout_micros"] = wasmExports["ts_parser_timeout_micros"])(a0);
            var _ts_parser_set_timeout_micros = Module["_ts_parser_set_timeout_micros"] = (a0, a1, a2) => (_ts_parser_set_timeout_micros = Module["_ts_parser_set_timeout_micros"] = wasmExports["ts_parser_set_timeout_micros"])(a0, a1, a2);
            var _ts_parser_set_included_ranges = Module["_ts_parser_set_included_ranges"] = (a0, a1, a2) => (_ts_parser_set_included_ranges = Module["_ts_parser_set_included_ranges"] = wasmExports["ts_parser_set_included_ranges"])(a0, a1, a2);
            var _memmove = Module["_memmove"] = (a0, a1, a2) => (_memmove = Module["_memmove"] = wasmExports["memmove"])(a0, a1, a2);
            var _memcmp = Module["_memcmp"] = (a0, a1, a2) => (_memcmp = Module["_memcmp"] = wasmExports["memcmp"])(a0, a1, a2);
            var _ts_query_new = Module["_ts_query_new"] = (a0, a1, a2, a3, a4) => (_ts_query_new = Module["_ts_query_new"] = wasmExports["ts_query_new"])(a0, a1, a2, a3, a4);
            var _ts_query_delete = Module["_ts_query_delete"] = (a0) => (_ts_query_delete = Module["_ts_query_delete"] = wasmExports["ts_query_delete"])(a0);
            var _iswspace = Module["_iswspace"] = (a0) => (_iswspace = Module["_iswspace"] = wasmExports["iswspace"])(a0);
            var _iswalnum = Module["_iswalnum"] = (a0) => (_iswalnum = Module["_iswalnum"] = wasmExports["iswalnum"])(a0);
            var _ts_query_pattern_count = Module["_ts_query_pattern_count"] = (a0) => (_ts_query_pattern_count = Module["_ts_query_pattern_count"] = wasmExports["ts_query_pattern_count"])(a0);
            var _ts_query_capture_count = Module["_ts_query_capture_count"] = (a0) => (_ts_query_capture_count = Module["_ts_query_capture_count"] = wasmExports["ts_query_capture_count"])(a0);
            var _ts_query_string_count = Module["_ts_query_string_count"] = (a0) => (_ts_query_string_count = Module["_ts_query_string_count"] = wasmExports["ts_query_string_count"])(a0);
            var _ts_query_capture_name_for_id = Module["_ts_query_capture_name_for_id"] = (a0, a1, a2) => (_ts_query_capture_name_for_id = Module["_ts_query_capture_name_for_id"] = wasmExports["ts_query_capture_name_for_id"])(a0, a1, a2);
            var _ts_query_string_value_for_id = Module["_ts_query_string_value_for_id"] = (a0, a1, a2) => (_ts_query_string_value_for_id = Module["_ts_query_string_value_for_id"] = wasmExports["ts_query_string_value_for_id"])(a0, a1, a2);
            var _ts_query_predicates_for_pattern = Module["_ts_query_predicates_for_pattern"] = (a0, a1, a2) => (_ts_query_predicates_for_pattern = Module["_ts_query_predicates_for_pattern"] = wasmExports["ts_query_predicates_for_pattern"])(a0, a1, a2);
            var _ts_query_disable_capture = Module["_ts_query_disable_capture"] = (a0, a1, a2) => (_ts_query_disable_capture = Module["_ts_query_disable_capture"] = wasmExports["ts_query_disable_capture"])(a0, a1, a2);
            var _ts_tree_copy = Module["_ts_tree_copy"] = (a0) => (_ts_tree_copy = Module["_ts_tree_copy"] = wasmExports["ts_tree_copy"])(a0);
            var _ts_tree_delete = Module["_ts_tree_delete"] = (a0) => (_ts_tree_delete = Module["_ts_tree_delete"] = wasmExports["ts_tree_delete"])(a0);
            var _ts_init = Module["_ts_init"] = () => (_ts_init = Module["_ts_init"] = wasmExports["ts_init"])();
            var _ts_parser_new_wasm = Module["_ts_parser_new_wasm"] = () => (_ts_parser_new_wasm = Module["_ts_parser_new_wasm"] = wasmExports["ts_parser_new_wasm"])();
            var _ts_parser_enable_logger_wasm = Module["_ts_parser_enable_logger_wasm"] = (a0, a1) => (_ts_parser_enable_logger_wasm = Module["_ts_parser_enable_logger_wasm"] = wasmExports["ts_parser_enable_logger_wasm"])(a0, a1);
            var _ts_parser_parse_wasm = Module["_ts_parser_parse_wasm"] = (a0, a1, a2, a3, a4) => (_ts_parser_parse_wasm = Module["_ts_parser_parse_wasm"] = wasmExports["ts_parser_parse_wasm"])(a0, a1, a2, a3, a4);
            var _ts_parser_included_ranges_wasm = Module["_ts_parser_included_ranges_wasm"] = (a0) => (_ts_parser_included_ranges_wasm = Module["_ts_parser_included_ranges_wasm"] = wasmExports["ts_parser_included_ranges_wasm"])(a0);
            var _ts_language_type_is_named_wasm = Module["_ts_language_type_is_named_wasm"] = (a0, a1) => (_ts_language_type_is_named_wasm = Module["_ts_language_type_is_named_wasm"] = wasmExports["ts_language_type_is_named_wasm"])(a0, a1);
            var _ts_language_type_is_visible_wasm = Module["_ts_language_type_is_visible_wasm"] = (a0, a1) => (_ts_language_type_is_visible_wasm = Module["_ts_language_type_is_visible_wasm"] = wasmExports["ts_language_type_is_visible_wasm"])(a0, a1);
            var _ts_tree_root_node_wasm = Module["_ts_tree_root_node_wasm"] = (a0) => (_ts_tree_root_node_wasm = Module["_ts_tree_root_node_wasm"] = wasmExports["ts_tree_root_node_wasm"])(a0);
            var _ts_tree_root_node_with_offset_wasm = Module["_ts_tree_root_node_with_offset_wasm"] = (a0) => (_ts_tree_root_node_with_offset_wasm = Module["_ts_tree_root_node_with_offset_wasm"] = wasmExports["ts_tree_root_node_with_offset_wasm"])(a0);
            var _ts_tree_edit_wasm = Module["_ts_tree_edit_wasm"] = (a0) => (_ts_tree_edit_wasm = Module["_ts_tree_edit_wasm"] = wasmExports["ts_tree_edit_wasm"])(a0);
            var _ts_tree_included_ranges_wasm = Module["_ts_tree_included_ranges_wasm"] = (a0) => (_ts_tree_included_ranges_wasm = Module["_ts_tree_included_ranges_wasm"] = wasmExports["ts_tree_included_ranges_wasm"])(a0);
            var _ts_tree_get_changed_ranges_wasm = Module["_ts_tree_get_changed_ranges_wasm"] = (a0, a1) => (_ts_tree_get_changed_ranges_wasm = Module["_ts_tree_get_changed_ranges_wasm"] = wasmExports["ts_tree_get_changed_ranges_wasm"])(a0, a1);
            var _ts_tree_cursor_new_wasm = Module["_ts_tree_cursor_new_wasm"] = (a0) => (_ts_tree_cursor_new_wasm = Module["_ts_tree_cursor_new_wasm"] = wasmExports["ts_tree_cursor_new_wasm"])(a0);
            var _ts_tree_cursor_delete_wasm = Module["_ts_tree_cursor_delete_wasm"] = (a0) => (_ts_tree_cursor_delete_wasm = Module["_ts_tree_cursor_delete_wasm"] = wasmExports["ts_tree_cursor_delete_wasm"])(a0);
            var _ts_tree_cursor_reset_wasm = Module["_ts_tree_cursor_reset_wasm"] = (a0) => (_ts_tree_cursor_reset_wasm = Module["_ts_tree_cursor_reset_wasm"] = wasmExports["ts_tree_cursor_reset_wasm"])(a0);
            var _ts_tree_cursor_reset_to_wasm = Module["_ts_tree_cursor_reset_to_wasm"] = (a0, a1) => (_ts_tree_cursor_reset_to_wasm = Module["_ts_tree_cursor_reset_to_wasm"] = wasmExports["ts_tree_cursor_reset_to_wasm"])(a0, a1);
            var _ts_tree_cursor_goto_first_child_wasm = Module["_ts_tree_cursor_goto_first_child_wasm"] = (a0) => (_ts_tree_cursor_goto_first_child_wasm = Module["_ts_tree_cursor_goto_first_child_wasm"] = wasmExports["ts_tree_cursor_goto_first_child_wasm"])(a0);
            var _ts_tree_cursor_goto_last_child_wasm = Module["_ts_tree_cursor_goto_last_child_wasm"] = (a0) => (_ts_tree_cursor_goto_last_child_wasm = Module["_ts_tree_cursor_goto_last_child_wasm"] = wasmExports["ts_tree_cursor_goto_last_child_wasm"])(a0);
            var _ts_tree_cursor_goto_first_child_for_index_wasm = Module["_ts_tree_cursor_goto_first_child_for_index_wasm"] = (a0) => (_ts_tree_cursor_goto_first_child_for_index_wasm = Module["_ts_tree_cursor_goto_first_child_for_index_wasm"] = wasmExports["ts_tree_cursor_goto_first_child_for_index_wasm"])(a0);
            var _ts_tree_cursor_goto_first_child_for_position_wasm = Module["_ts_tree_cursor_goto_first_child_for_position_wasm"] = (a0) => (_ts_tree_cursor_goto_first_child_for_position_wasm = Module["_ts_tree_cursor_goto_first_child_for_position_wasm"] = wasmExports["ts_tree_cursor_goto_first_child_for_position_wasm"])(a0);
            var _ts_tree_cursor_goto_next_sibling_wasm = Module["_ts_tree_cursor_goto_next_sibling_wasm"] = (a0) => (_ts_tree_cursor_goto_next_sibling_wasm = Module["_ts_tree_cursor_goto_next_sibling_wasm"] = wasmExports["ts_tree_cursor_goto_next_sibling_wasm"])(a0);
            var _ts_tree_cursor_goto_previous_sibling_wasm = Module["_ts_tree_cursor_goto_previous_sibling_wasm"] = (a0) => (_ts_tree_cursor_goto_previous_sibling_wasm = Module["_ts_tree_cursor_goto_previous_sibling_wasm"] = wasmExports["ts_tree_cursor_goto_previous_sibling_wasm"])(a0);
            var _ts_tree_cursor_goto_descendant_wasm = Module["_ts_tree_cursor_goto_descendant_wasm"] = (a0, a1) => (_ts_tree_cursor_goto_descendant_wasm = Module["_ts_tree_cursor_goto_descendant_wasm"] = wasmExports["ts_tree_cursor_goto_descendant_wasm"])(a0, a1);
            var _ts_tree_cursor_goto_parent_wasm = Module["_ts_tree_cursor_goto_parent_wasm"] = (a0) => (_ts_tree_cursor_goto_parent_wasm = Module["_ts_tree_cursor_goto_parent_wasm"] = wasmExports["ts_tree_cursor_goto_parent_wasm"])(a0);
            var _ts_tree_cursor_current_node_type_id_wasm = Module["_ts_tree_cursor_current_node_type_id_wasm"] = (a0) => (_ts_tree_cursor_current_node_type_id_wasm = Module["_ts_tree_cursor_current_node_type_id_wasm"] = wasmExports["ts_tree_cursor_current_node_type_id_wasm"])(a0);
            var _ts_tree_cursor_current_node_state_id_wasm = Module["_ts_tree_cursor_current_node_state_id_wasm"] = (a0) => (_ts_tree_cursor_current_node_state_id_wasm = Module["_ts_tree_cursor_current_node_state_id_wasm"] = wasmExports["ts_tree_cursor_current_node_state_id_wasm"])(a0);
            var _ts_tree_cursor_current_node_is_named_wasm = Module["_ts_tree_cursor_current_node_is_named_wasm"] = (a0) => (_ts_tree_cursor_current_node_is_named_wasm = Module["_ts_tree_cursor_current_node_is_named_wasm"] = wasmExports["ts_tree_cursor_current_node_is_named_wasm"])(a0);
            var _ts_tree_cursor_current_node_is_missing_wasm = Module["_ts_tree_cursor_current_node_is_missing_wasm"] = (a0) => (_ts_tree_cursor_current_node_is_missing_wasm = Module["_ts_tree_cursor_current_node_is_missing_wasm"] = wasmExports["ts_tree_cursor_current_node_is_missing_wasm"])(a0);
            var _ts_tree_cursor_current_node_id_wasm = Module["_ts_tree_cursor_current_node_id_wasm"] = (a0) => (_ts_tree_cursor_current_node_id_wasm = Module["_ts_tree_cursor_current_node_id_wasm"] = wasmExports["ts_tree_cursor_current_node_id_wasm"])(a0);
            var _ts_tree_cursor_start_position_wasm = Module["_ts_tree_cursor_start_position_wasm"] = (a0) => (_ts_tree_cursor_start_position_wasm = Module["_ts_tree_cursor_start_position_wasm"] = wasmExports["ts_tree_cursor_start_position_wasm"])(a0);
            var _ts_tree_cursor_end_position_wasm = Module["_ts_tree_cursor_end_position_wasm"] = (a0) => (_ts_tree_cursor_end_position_wasm = Module["_ts_tree_cursor_end_position_wasm"] = wasmExports["ts_tree_cursor_end_position_wasm"])(a0);
            var _ts_tree_cursor_start_index_wasm = Module["_ts_tree_cursor_start_index_wasm"] = (a0) => (_ts_tree_cursor_start_index_wasm = Module["_ts_tree_cursor_start_index_wasm"] = wasmExports["ts_tree_cursor_start_index_wasm"])(a0);
            var _ts_tree_cursor_end_index_wasm = Module["_ts_tree_cursor_end_index_wasm"] = (a0) => (_ts_tree_cursor_end_index_wasm = Module["_ts_tree_cursor_end_index_wasm"] = wasmExports["ts_tree_cursor_end_index_wasm"])(a0);
            var _ts_tree_cursor_current_field_id_wasm = Module["_ts_tree_cursor_current_field_id_wasm"] = (a0) => (_ts_tree_cursor_current_field_id_wasm = Module["_ts_tree_cursor_current_field_id_wasm"] = wasmExports["ts_tree_cursor_current_field_id_wasm"])(a0);
            var _ts_tree_cursor_current_depth_wasm = Module["_ts_tree_cursor_current_depth_wasm"] = (a0) => (_ts_tree_cursor_current_depth_wasm = Module["_ts_tree_cursor_current_depth_wasm"] = wasmExports["ts_tree_cursor_current_depth_wasm"])(a0);
            var _ts_tree_cursor_current_descendant_index_wasm = Module["_ts_tree_cursor_current_descendant_index_wasm"] = (a0) => (_ts_tree_cursor_current_descendant_index_wasm = Module["_ts_tree_cursor_current_descendant_index_wasm"] = wasmExports["ts_tree_cursor_current_descendant_index_wasm"])(a0);
            var _ts_tree_cursor_current_node_wasm = Module["_ts_tree_cursor_current_node_wasm"] = (a0) => (_ts_tree_cursor_current_node_wasm = Module["_ts_tree_cursor_current_node_wasm"] = wasmExports["ts_tree_cursor_current_node_wasm"])(a0);
            var _ts_node_symbol_wasm = Module["_ts_node_symbol_wasm"] = (a0) => (_ts_node_symbol_wasm = Module["_ts_node_symbol_wasm"] = wasmExports["ts_node_symbol_wasm"])(a0);
            var _ts_node_field_name_for_child_wasm = Module["_ts_node_field_name_for_child_wasm"] = (a0, a1) => (_ts_node_field_name_for_child_wasm = Module["_ts_node_field_name_for_child_wasm"] = wasmExports["ts_node_field_name_for_child_wasm"])(a0, a1);
            var _ts_node_children_by_field_id_wasm = Module["_ts_node_children_by_field_id_wasm"] = (a0, a1) => (_ts_node_children_by_field_id_wasm = Module["_ts_node_children_by_field_id_wasm"] = wasmExports["ts_node_children_by_field_id_wasm"])(a0, a1);
            var _ts_node_first_child_for_byte_wasm = Module["_ts_node_first_child_for_byte_wasm"] = (a0) => (_ts_node_first_child_for_byte_wasm = Module["_ts_node_first_child_for_byte_wasm"] = wasmExports["ts_node_first_child_for_byte_wasm"])(a0);
            var _ts_node_first_named_child_for_byte_wasm = Module["_ts_node_first_named_child_for_byte_wasm"] = (a0) => (_ts_node_first_named_child_for_byte_wasm = Module["_ts_node_first_named_child_for_byte_wasm"] = wasmExports["ts_node_first_named_child_for_byte_wasm"])(a0);
            var _ts_node_grammar_symbol_wasm = Module["_ts_node_grammar_symbol_wasm"] = (a0) => (_ts_node_grammar_symbol_wasm = Module["_ts_node_grammar_symbol_wasm"] = wasmExports["ts_node_grammar_symbol_wasm"])(a0);
            var _ts_node_child_count_wasm = Module["_ts_node_child_count_wasm"] = (a0) => (_ts_node_child_count_wasm = Module["_ts_node_child_count_wasm"] = wasmExports["ts_node_child_count_wasm"])(a0);
            var _ts_node_named_child_count_wasm = Module["_ts_node_named_child_count_wasm"] = (a0) => (_ts_node_named_child_count_wasm = Module["_ts_node_named_child_count_wasm"] = wasmExports["ts_node_named_child_count_wasm"])(a0);
            var _ts_node_child_wasm = Module["_ts_node_child_wasm"] = (a0, a1) => (_ts_node_child_wasm = Module["_ts_node_child_wasm"] = wasmExports["ts_node_child_wasm"])(a0, a1);
            var _ts_node_named_child_wasm = Module["_ts_node_named_child_wasm"] = (a0, a1) => (_ts_node_named_child_wasm = Module["_ts_node_named_child_wasm"] = wasmExports["ts_node_named_child_wasm"])(a0, a1);
            var _ts_node_child_by_field_id_wasm = Module["_ts_node_child_by_field_id_wasm"] = (a0, a1) => (_ts_node_child_by_field_id_wasm = Module["_ts_node_child_by_field_id_wasm"] = wasmExports["ts_node_child_by_field_id_wasm"])(a0, a1);
            var _ts_node_next_sibling_wasm = Module["_ts_node_next_sibling_wasm"] = (a0) => (_ts_node_next_sibling_wasm = Module["_ts_node_next_sibling_wasm"] = wasmExports["ts_node_next_sibling_wasm"])(a0);
            var _ts_node_prev_sibling_wasm = Module["_ts_node_prev_sibling_wasm"] = (a0) => (_ts_node_prev_sibling_wasm = Module["_ts_node_prev_sibling_wasm"] = wasmExports["ts_node_prev_sibling_wasm"])(a0);
            var _ts_node_next_named_sibling_wasm = Module["_ts_node_next_named_sibling_wasm"] = (a0) => (_ts_node_next_named_sibling_wasm = Module["_ts_node_next_named_sibling_wasm"] = wasmExports["ts_node_next_named_sibling_wasm"])(a0);
            var _ts_node_prev_named_sibling_wasm = Module["_ts_node_prev_named_sibling_wasm"] = (a0) => (_ts_node_prev_named_sibling_wasm = Module["_ts_node_prev_named_sibling_wasm"] = wasmExports["ts_node_prev_named_sibling_wasm"])(a0);
            var _ts_node_descendant_count_wasm = Module["_ts_node_descendant_count_wasm"] = (a0) => (_ts_node_descendant_count_wasm = Module["_ts_node_descendant_count_wasm"] = wasmExports["ts_node_descendant_count_wasm"])(a0);
            var _ts_node_parent_wasm = Module["_ts_node_parent_wasm"] = (a0) => (_ts_node_parent_wasm = Module["_ts_node_parent_wasm"] = wasmExports["ts_node_parent_wasm"])(a0);
            var _ts_node_descendant_for_index_wasm = Module["_ts_node_descendant_for_index_wasm"] = (a0) => (_ts_node_descendant_for_index_wasm = Module["_ts_node_descendant_for_index_wasm"] = wasmExports["ts_node_descendant_for_index_wasm"])(a0);
            var _ts_node_named_descendant_for_index_wasm = Module["_ts_node_named_descendant_for_index_wasm"] = (a0) => (_ts_node_named_descendant_for_index_wasm = Module["_ts_node_named_descendant_for_index_wasm"] = wasmExports["ts_node_named_descendant_for_index_wasm"])(a0);
            var _ts_node_descendant_for_position_wasm = Module["_ts_node_descendant_for_position_wasm"] = (a0) => (_ts_node_descendant_for_position_wasm = Module["_ts_node_descendant_for_position_wasm"] = wasmExports["ts_node_descendant_for_position_wasm"])(a0);
            var _ts_node_named_descendant_for_position_wasm = Module["_ts_node_named_descendant_for_position_wasm"] = (a0) => (_ts_node_named_descendant_for_position_wasm = Module["_ts_node_named_descendant_for_position_wasm"] = wasmExports["ts_node_named_descendant_for_position_wasm"])(a0);
            var _ts_node_start_point_wasm = Module["_ts_node_start_point_wasm"] = (a0) => (_ts_node_start_point_wasm = Module["_ts_node_start_point_wasm"] = wasmExports["ts_node_start_point_wasm"])(a0);
            var _ts_node_end_point_wasm = Module["_ts_node_end_point_wasm"] = (a0) => (_ts_node_end_point_wasm = Module["_ts_node_end_point_wasm"] = wasmExports["ts_node_end_point_wasm"])(a0);
            var _ts_node_start_index_wasm = Module["_ts_node_start_index_wasm"] = (a0) => (_ts_node_start_index_wasm = Module["_ts_node_start_index_wasm"] = wasmExports["ts_node_start_index_wasm"])(a0);
            var _ts_node_end_index_wasm = Module["_ts_node_end_index_wasm"] = (a0) => (_ts_node_end_index_wasm = Module["_ts_node_end_index_wasm"] = wasmExports["ts_node_end_index_wasm"])(a0);
            var _ts_node_to_string_wasm = Module["_ts_node_to_string_wasm"] = (a0) => (_ts_node_to_string_wasm = Module["_ts_node_to_string_wasm"] = wasmExports["ts_node_to_string_wasm"])(a0);
            var _ts_node_children_wasm = Module["_ts_node_children_wasm"] = (a0) => (_ts_node_children_wasm = Module["_ts_node_children_wasm"] = wasmExports["ts_node_children_wasm"])(a0);
            var _ts_node_named_children_wasm = Module["_ts_node_named_children_wasm"] = (a0) => (_ts_node_named_children_wasm = Module["_ts_node_named_children_wasm"] = wasmExports["ts_node_named_children_wasm"])(a0);
            var _ts_node_descendants_of_type_wasm = Module["_ts_node_descendants_of_type_wasm"] = (a0, a1, a2, a3, a4, a5, a6) => (_ts_node_descendants_of_type_wasm = Module["_ts_node_descendants_of_type_wasm"] = wasmExports["ts_node_descendants_of_type_wasm"])(a0, a1, a2, a3, a4, a5, a6);
            var _ts_node_is_named_wasm = Module["_ts_node_is_named_wasm"] = (a0) => (_ts_node_is_named_wasm = Module["_ts_node_is_named_wasm"] = wasmExports["ts_node_is_named_wasm"])(a0);
            var _ts_node_has_changes_wasm = Module["_ts_node_has_changes_wasm"] = (a0) => (_ts_node_has_changes_wasm = Module["_ts_node_has_changes_wasm"] = wasmExports["ts_node_has_changes_wasm"])(a0);
            var _ts_node_has_error_wasm = Module["_ts_node_has_error_wasm"] = (a0) => (_ts_node_has_error_wasm = Module["_ts_node_has_error_wasm"] = wasmExports["ts_node_has_error_wasm"])(a0);
            var _ts_node_is_error_wasm = Module["_ts_node_is_error_wasm"] = (a0) => (_ts_node_is_error_wasm = Module["_ts_node_is_error_wasm"] = wasmExports["ts_node_is_error_wasm"])(a0);
            var _ts_node_is_missing_wasm = Module["_ts_node_is_missing_wasm"] = (a0) => (_ts_node_is_missing_wasm = Module["_ts_node_is_missing_wasm"] = wasmExports["ts_node_is_missing_wasm"])(a0);
            var _ts_node_is_extra_wasm = Module["_ts_node_is_extra_wasm"] = (a0) => (_ts_node_is_extra_wasm = Module["_ts_node_is_extra_wasm"] = wasmExports["ts_node_is_extra_wasm"])(a0);
            var _ts_node_parse_state_wasm = Module["_ts_node_parse_state_wasm"] = (a0) => (_ts_node_parse_state_wasm = Module["_ts_node_parse_state_wasm"] = wasmExports["ts_node_parse_state_wasm"])(a0);
            var _ts_node_next_parse_state_wasm = Module["_ts_node_next_parse_state_wasm"] = (a0) => (_ts_node_next_parse_state_wasm = Module["_ts_node_next_parse_state_wasm"] = wasmExports["ts_node_next_parse_state_wasm"])(a0);
            var _ts_query_matches_wasm = Module["_ts_query_matches_wasm"] = (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) => (_ts_query_matches_wasm = Module["_ts_query_matches_wasm"] = wasmExports["ts_query_matches_wasm"])(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
            var _ts_query_captures_wasm = Module["_ts_query_captures_wasm"] = (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) => (_ts_query_captures_wasm = Module["_ts_query_captures_wasm"] = wasmExports["ts_query_captures_wasm"])(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
            var _iswalpha = Module["_iswalpha"] = (a0) => (_iswalpha = Module["_iswalpha"] = wasmExports["iswalpha"])(a0);
            var _iswblank = Module["_iswblank"] = (a0) => (_iswblank = Module["_iswblank"] = wasmExports["iswblank"])(a0);
            var _iswdigit = Module["_iswdigit"] = (a0) => (_iswdigit = Module["_iswdigit"] = wasmExports["iswdigit"])(a0);
            var _iswlower = Module["_iswlower"] = (a0) => (_iswlower = Module["_iswlower"] = wasmExports["iswlower"])(a0);
            var _iswupper = Module["_iswupper"] = (a0) => (_iswupper = Module["_iswupper"] = wasmExports["iswupper"])(a0);
            var _iswxdigit = Module["_iswxdigit"] = (a0) => (_iswxdigit = Module["_iswxdigit"] = wasmExports["iswxdigit"])(a0);
            var _memchr = Module["_memchr"] = (a0, a1, a2) => (_memchr = Module["_memchr"] = wasmExports["memchr"])(a0, a1, a2);
            var _strlen = Module["_strlen"] = (a0) => (_strlen = Module["_strlen"] = wasmExports["strlen"])(a0);
            var _strcmp = Module["_strcmp"] = (a0, a1) => (_strcmp = Module["_strcmp"] = wasmExports["strcmp"])(a0, a1);
            var _strncat = Module["_strncat"] = (a0, a1, a2) => (_strncat = Module["_strncat"] = wasmExports["strncat"])(a0, a1, a2);
            var _strncpy = Module["_strncpy"] = (a0, a1, a2) => (_strncpy = Module["_strncpy"] = wasmExports["strncpy"])(a0, a1, a2);
            var _towlower = Module["_towlower"] = (a0) => (_towlower = Module["_towlower"] = wasmExports["towlower"])(a0);
            var _towupper = Module["_towupper"] = (a0) => (_towupper = Module["_towupper"] = wasmExports["towupper"])(a0);
            var _setThrew = /* @__PURE__ */ __name((a0, a1) => (_setThrew = wasmExports["setThrew"])(a0, a1), "_setThrew");
            var __emscripten_stack_restore = /* @__PURE__ */ __name((a0) => (__emscripten_stack_restore = wasmExports["_emscripten_stack_restore"])(a0), "__emscripten_stack_restore");
            var __emscripten_stack_alloc = /* @__PURE__ */ __name((a0) => (__emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"])(a0), "__emscripten_stack_alloc");
            var _emscripten_stack_get_current = /* @__PURE__ */ __name(() => (_emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"])(), "_emscripten_stack_get_current");
            var dynCall_jiji = Module["dynCall_jiji"] = (a0, a1, a2, a3, a4) => (dynCall_jiji = Module["dynCall_jiji"] = wasmExports["dynCall_jiji"])(a0, a1, a2, a3, a4);
            var _orig$ts_parser_timeout_micros = Module["_orig$ts_parser_timeout_micros"] = (a0) => (_orig$ts_parser_timeout_micros = Module["_orig$ts_parser_timeout_micros"] = wasmExports["orig$ts_parser_timeout_micros"])(a0);
            var _orig$ts_parser_set_timeout_micros = Module["_orig$ts_parser_set_timeout_micros"] = (a0, a1) => (_orig$ts_parser_set_timeout_micros = Module["_orig$ts_parser_set_timeout_micros"] = wasmExports["orig$ts_parser_set_timeout_micros"])(a0, a1);
            Module["AsciiToString"] = AsciiToString;
            Module["stringToUTF16"] = stringToUTF16;
            var calledRun;
            dependenciesFulfilled = /* @__PURE__ */ __name(function runCaller() {
              if (!calledRun) run();
              if (!calledRun) dependenciesFulfilled = runCaller;
            }, "runCaller");
            function callMain(args2 = []) {
              var entryFunction = resolveGlobalSymbol("main").sym;
              if (!entryFunction) return;
              args2.unshift(thisProgram);
              var argc = args2.length;
              var argv = stackAlloc((argc + 1) * 4);
              var argv_ptr = argv;
              args2.forEach((arg) => {
                LE_HEAP_STORE_U32((argv_ptr >> 2) * 4, stringToUTF8OnStack(arg));
                argv_ptr += 4;
              });
              LE_HEAP_STORE_U32((argv_ptr >> 2) * 4, 0);
              try {
                var ret = entryFunction(argc, argv);
                exitJS(
                  ret,
                  /* implicit = */
                  true
                );
                return ret;
              } catch (e4) {
                return handleException(e4);
              }
            }
            __name(callMain, "callMain");
            function run(args2 = arguments_) {
              if (runDependencies > 0) {
                return;
              }
              preRun();
              if (runDependencies > 0) {
                return;
              }
              function doRun() {
                if (calledRun) return;
                calledRun = true;
                Module["calledRun"] = true;
                if (ABORT) return;
                initRuntime();
                preMain();
                Module["onRuntimeInitialized"]?.();
                if (shouldRunNow) callMain(args2);
                postRun();
              }
              __name(doRun, "doRun");
              if (Module["setStatus"]) {
                Module["setStatus"]("Running...");
                setTimeout(function() {
                  setTimeout(function() {
                    Module["setStatus"]("");
                  }, 1);
                  doRun();
                }, 1);
              } else {
                doRun();
              }
            }
            __name(run, "run");
            if (Module["preInit"]) {
              if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]];
              while (Module["preInit"].length > 0) {
                Module["preInit"].pop()();
              }
            }
            var shouldRunNow = true;
            if (Module["noInitialRun"]) shouldRunNow = false;
            run();
            const C = Module;
            const INTERNAL = {};
            const SIZE_OF_INT = 4;
            const SIZE_OF_CURSOR = 4 * SIZE_OF_INT;
            const SIZE_OF_NODE = 5 * SIZE_OF_INT;
            const SIZE_OF_POINT = 2 * SIZE_OF_INT;
            const SIZE_OF_RANGE = 2 * SIZE_OF_INT + 2 * SIZE_OF_POINT;
            const ZERO_POINT = {
              row: 0,
              column: 0
            };
            const QUERY_WORD_REGEX = /[\w-.]*/g;
            const PREDICATE_STEP_TYPE_CAPTURE = 1;
            const PREDICATE_STEP_TYPE_STRING = 2;
            const LANGUAGE_FUNCTION_REGEX = /^_?tree_sitter_\w+/;
            let VERSION;
            let MIN_COMPATIBLE_VERSION;
            let TRANSFER_BUFFER;
            let currentParseCallback;
            let currentLogCallback;
            class ParserImpl {
              static {
                __name(this, "ParserImpl");
              }
              static init() {
                TRANSFER_BUFFER = C._ts_init();
                VERSION = getValue(TRANSFER_BUFFER, "i32");
                MIN_COMPATIBLE_VERSION = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
              }
              initialize() {
                C._ts_parser_new_wasm();
                this[0] = getValue(TRANSFER_BUFFER, "i32");
                this[1] = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
              }
              delete() {
                C._ts_parser_delete(this[0]);
                C._free(this[1]);
                this[0] = 0;
                this[1] = 0;
              }
              setLanguage(language) {
                let address;
                if (!language) {
                  address = 0;
                  language = null;
                } else if (language.constructor === Language) {
                  address = language[0];
                  const version2 = C._ts_language_version(address);
                  if (version2 < MIN_COMPATIBLE_VERSION || VERSION < version2) {
                    throw new Error(`Incompatible language version ${version2}. Compatibility range ${MIN_COMPATIBLE_VERSION} through ${VERSION}.`);
                  }
                } else {
                  throw new Error("Argument must be a Language");
                }
                this.language = language;
                C._ts_parser_set_language(this[0], address);
                return this;
              }
              getLanguage() {
                return this.language;
              }
              parse(callback, oldTree, options2) {
                if (typeof callback === "string") {
                  currentParseCallback = /* @__PURE__ */ __name((index, _2) => callback.slice(index), "currentParseCallback");
                } else if (typeof callback === "function") {
                  currentParseCallback = callback;
                } else {
                  throw new Error("Argument must be a string or a function");
                }
                if (this.logCallback) {
                  currentLogCallback = this.logCallback;
                  C._ts_parser_enable_logger_wasm(this[0], 1);
                } else {
                  currentLogCallback = null;
                  C._ts_parser_enable_logger_wasm(this[0], 0);
                }
                let rangeCount = 0;
                let rangeAddress = 0;
                if (options2?.includedRanges) {
                  rangeCount = options2.includedRanges.length;
                  rangeAddress = C._calloc(rangeCount, SIZE_OF_RANGE);
                  let address = rangeAddress;
                  for (let i4 = 0; i4 < rangeCount; i4++) {
                    marshalRange(address, options2.includedRanges[i4]);
                    address += SIZE_OF_RANGE;
                  }
                }
                const treeAddress = C._ts_parser_parse_wasm(this[0], this[1], oldTree ? oldTree[0] : 0, rangeAddress, rangeCount);
                if (!treeAddress) {
                  currentParseCallback = null;
                  currentLogCallback = null;
                  throw new Error("Parsing failed");
                }
                const result = new Tree(INTERNAL, treeAddress, this.language, currentParseCallback);
                currentParseCallback = null;
                currentLogCallback = null;
                return result;
              }
              reset() {
                C._ts_parser_reset(this[0]);
              }
              getIncludedRanges() {
                C._ts_parser_included_ranges_wasm(this[0]);
                const count = getValue(TRANSFER_BUFFER, "i32");
                const buffer = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                const result = new Array(count);
                if (count > 0) {
                  let address = buffer;
                  for (let i4 = 0; i4 < count; i4++) {
                    result[i4] = unmarshalRange(address);
                    address += SIZE_OF_RANGE;
                  }
                  C._free(buffer);
                }
                return result;
              }
              getTimeoutMicros() {
                return C._ts_parser_timeout_micros(this[0]);
              }
              setTimeoutMicros(timeout2) {
                C._ts_parser_set_timeout_micros(this[0], timeout2);
              }
              setLogger(callback) {
                if (!callback) {
                  callback = null;
                } else if (typeof callback !== "function") {
                  throw new Error("Logger callback must be a function");
                }
                this.logCallback = callback;
                return this;
              }
              getLogger() {
                return this.logCallback;
              }
            }
            class Tree {
              static {
                __name(this, "Tree");
              }
              constructor(internal, address, language, textCallback) {
                assertInternal(internal);
                this[0] = address;
                this.language = language;
                this.textCallback = textCallback;
              }
              copy() {
                const address = C._ts_tree_copy(this[0]);
                return new Tree(INTERNAL, address, this.language, this.textCallback);
              }
              delete() {
                C._ts_tree_delete(this[0]);
                this[0] = 0;
              }
              edit(edit2) {
                marshalEdit(edit2);
                C._ts_tree_edit_wasm(this[0]);
              }
              get rootNode() {
                C._ts_tree_root_node_wasm(this[0]);
                return unmarshalNode(this);
              }
              rootNodeWithOffset(offsetBytes, offsetExtent) {
                const address = TRANSFER_BUFFER + SIZE_OF_NODE;
                setValue(address, offsetBytes, "i32");
                marshalPoint(address + SIZE_OF_INT, offsetExtent);
                C._ts_tree_root_node_with_offset_wasm(this[0]);
                return unmarshalNode(this);
              }
              getLanguage() {
                return this.language;
              }
              walk() {
                return this.rootNode.walk();
              }
              getChangedRanges(other2) {
                if (other2.constructor !== Tree) {
                  throw new TypeError("Argument must be a Tree");
                }
                C._ts_tree_get_changed_ranges_wasm(this[0], other2[0]);
                const count = getValue(TRANSFER_BUFFER, "i32");
                const buffer = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                const result = new Array(count);
                if (count > 0) {
                  let address = buffer;
                  for (let i4 = 0; i4 < count; i4++) {
                    result[i4] = unmarshalRange(address);
                    address += SIZE_OF_RANGE;
                  }
                  C._free(buffer);
                }
                return result;
              }
              getIncludedRanges() {
                C._ts_tree_included_ranges_wasm(this[0]);
                const count = getValue(TRANSFER_BUFFER, "i32");
                const buffer = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                const result = new Array(count);
                if (count > 0) {
                  let address = buffer;
                  for (let i4 = 0; i4 < count; i4++) {
                    result[i4] = unmarshalRange(address);
                    address += SIZE_OF_RANGE;
                  }
                  C._free(buffer);
                }
                return result;
              }
            }
            class Node {
              static {
                __name(this, "Node");
              }
              constructor(internal, tree) {
                assertInternal(internal);
                this.tree = tree;
              }
              get typeId() {
                marshalNode(this);
                return C._ts_node_symbol_wasm(this.tree[0]);
              }
              get grammarId() {
                marshalNode(this);
                return C._ts_node_grammar_symbol_wasm(this.tree[0]);
              }
              get type() {
                return this.tree.language.types[this.typeId] || "ERROR";
              }
              get grammarType() {
                return this.tree.language.types[this.grammarId] || "ERROR";
              }
              get endPosition() {
                marshalNode(this);
                C._ts_node_end_point_wasm(this.tree[0]);
                return unmarshalPoint(TRANSFER_BUFFER);
              }
              get endIndex() {
                marshalNode(this);
                return C._ts_node_end_index_wasm(this.tree[0]);
              }
              get text() {
                return getText(this.tree, this.startIndex, this.endIndex);
              }
              get parseState() {
                marshalNode(this);
                return C._ts_node_parse_state_wasm(this.tree[0]);
              }
              get nextParseState() {
                marshalNode(this);
                return C._ts_node_next_parse_state_wasm(this.tree[0]);
              }
              get isNamed() {
                marshalNode(this);
                return C._ts_node_is_named_wasm(this.tree[0]) === 1;
              }
              get hasError() {
                marshalNode(this);
                return C._ts_node_has_error_wasm(this.tree[0]) === 1;
              }
              get hasChanges() {
                marshalNode(this);
                return C._ts_node_has_changes_wasm(this.tree[0]) === 1;
              }
              get isError() {
                marshalNode(this);
                return C._ts_node_is_error_wasm(this.tree[0]) === 1;
              }
              get isMissing() {
                marshalNode(this);
                return C._ts_node_is_missing_wasm(this.tree[0]) === 1;
              }
              get isExtra() {
                marshalNode(this);
                return C._ts_node_is_extra_wasm(this.tree[0]) === 1;
              }
              equals(other2) {
                return this.id === other2.id;
              }
              child(index) {
                marshalNode(this);
                C._ts_node_child_wasm(this.tree[0], index);
                return unmarshalNode(this.tree);
              }
              namedChild(index) {
                marshalNode(this);
                C._ts_node_named_child_wasm(this.tree[0], index);
                return unmarshalNode(this.tree);
              }
              childForFieldId(fieldId) {
                marshalNode(this);
                C._ts_node_child_by_field_id_wasm(this.tree[0], fieldId);
                return unmarshalNode(this.tree);
              }
              childForFieldName(fieldName) {
                const fieldId = this.tree.language.fields.indexOf(fieldName);
                if (fieldId !== -1) return this.childForFieldId(fieldId);
                return null;
              }
              fieldNameForChild(index) {
                marshalNode(this);
                const address = C._ts_node_field_name_for_child_wasm(this.tree[0], index);
                if (!address) {
                  return null;
                }
                const result = AsciiToString(address);
                return result;
              }
              childrenForFieldName(fieldName) {
                const fieldId = this.tree.language.fields.indexOf(fieldName);
                if (fieldId !== -1 && fieldId !== 0) return this.childrenForFieldId(fieldId);
                return [];
              }
              childrenForFieldId(fieldId) {
                marshalNode(this);
                C._ts_node_children_by_field_id_wasm(this.tree[0], fieldId);
                const count = getValue(TRANSFER_BUFFER, "i32");
                const buffer = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                const result = new Array(count);
                if (count > 0) {
                  let address = buffer;
                  for (let i4 = 0; i4 < count; i4++) {
                    result[i4] = unmarshalNode(this.tree, address);
                    address += SIZE_OF_NODE;
                  }
                  C._free(buffer);
                }
                return result;
              }
              firstChildForIndex(index) {
                marshalNode(this);
                const address = TRANSFER_BUFFER + SIZE_OF_NODE;
                setValue(address, index, "i32");
                C._ts_node_first_child_for_byte_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              firstNamedChildForIndex(index) {
                marshalNode(this);
                const address = TRANSFER_BUFFER + SIZE_OF_NODE;
                setValue(address, index, "i32");
                C._ts_node_first_named_child_for_byte_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              get childCount() {
                marshalNode(this);
                return C._ts_node_child_count_wasm(this.tree[0]);
              }
              get namedChildCount() {
                marshalNode(this);
                return C._ts_node_named_child_count_wasm(this.tree[0]);
              }
              get firstChild() {
                return this.child(0);
              }
              get firstNamedChild() {
                return this.namedChild(0);
              }
              get lastChild() {
                return this.child(this.childCount - 1);
              }
              get lastNamedChild() {
                return this.namedChild(this.namedChildCount - 1);
              }
              get children() {
                if (!this._children) {
                  marshalNode(this);
                  C._ts_node_children_wasm(this.tree[0]);
                  const count = getValue(TRANSFER_BUFFER, "i32");
                  const buffer = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                  this._children = new Array(count);
                  if (count > 0) {
                    let address = buffer;
                    for (let i4 = 0; i4 < count; i4++) {
                      this._children[i4] = unmarshalNode(this.tree, address);
                      address += SIZE_OF_NODE;
                    }
                    C._free(buffer);
                  }
                }
                return this._children;
              }
              get namedChildren() {
                if (!this._namedChildren) {
                  marshalNode(this);
                  C._ts_node_named_children_wasm(this.tree[0]);
                  const count = getValue(TRANSFER_BUFFER, "i32");
                  const buffer = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                  this._namedChildren = new Array(count);
                  if (count > 0) {
                    let address = buffer;
                    for (let i4 = 0; i4 < count; i4++) {
                      this._namedChildren[i4] = unmarshalNode(this.tree, address);
                      address += SIZE_OF_NODE;
                    }
                    C._free(buffer);
                  }
                }
                return this._namedChildren;
              }
              descendantsOfType(types7, startPosition, endPosition) {
                if (!Array.isArray(types7)) types7 = [types7];
                if (!startPosition) startPosition = ZERO_POINT;
                if (!endPosition) endPosition = ZERO_POINT;
                const symbols = [];
                const typesBySymbol = this.tree.language.types;
                for (let i4 = 0, n3 = typesBySymbol.length; i4 < n3; i4++) {
                  if (types7.includes(typesBySymbol[i4])) {
                    symbols.push(i4);
                  }
                }
                const symbolsAddress = C._malloc(SIZE_OF_INT * symbols.length);
                for (let i4 = 0, n3 = symbols.length; i4 < n3; i4++) {
                  setValue(symbolsAddress + i4 * SIZE_OF_INT, symbols[i4], "i32");
                }
                marshalNode(this);
                C._ts_node_descendants_of_type_wasm(this.tree[0], symbolsAddress, symbols.length, startPosition.row, startPosition.column, endPosition.row, endPosition.column);
                const descendantCount = getValue(TRANSFER_BUFFER, "i32");
                const descendantAddress = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                const result = new Array(descendantCount);
                if (descendantCount > 0) {
                  let address = descendantAddress;
                  for (let i4 = 0; i4 < descendantCount; i4++) {
                    result[i4] = unmarshalNode(this.tree, address);
                    address += SIZE_OF_NODE;
                  }
                }
                C._free(descendantAddress);
                C._free(symbolsAddress);
                return result;
              }
              get nextSibling() {
                marshalNode(this);
                C._ts_node_next_sibling_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              get previousSibling() {
                marshalNode(this);
                C._ts_node_prev_sibling_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              get nextNamedSibling() {
                marshalNode(this);
                C._ts_node_next_named_sibling_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              get previousNamedSibling() {
                marshalNode(this);
                C._ts_node_prev_named_sibling_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              get descendantCount() {
                marshalNode(this);
                return C._ts_node_descendant_count_wasm(this.tree[0]);
              }
              get parent() {
                marshalNode(this);
                C._ts_node_parent_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              descendantForIndex(start2, end = start2) {
                if (typeof start2 !== "number" || typeof end !== "number") {
                  throw new Error("Arguments must be numbers");
                }
                marshalNode(this);
                const address = TRANSFER_BUFFER + SIZE_OF_NODE;
                setValue(address, start2, "i32");
                setValue(address + SIZE_OF_INT, end, "i32");
                C._ts_node_descendant_for_index_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              namedDescendantForIndex(start2, end = start2) {
                if (typeof start2 !== "number" || typeof end !== "number") {
                  throw new Error("Arguments must be numbers");
                }
                marshalNode(this);
                const address = TRANSFER_BUFFER + SIZE_OF_NODE;
                setValue(address, start2, "i32");
                setValue(address + SIZE_OF_INT, end, "i32");
                C._ts_node_named_descendant_for_index_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              descendantForPosition(start2, end = start2) {
                if (!isPoint(start2) || !isPoint(end)) {
                  throw new Error("Arguments must be {row, column} objects");
                }
                marshalNode(this);
                const address = TRANSFER_BUFFER + SIZE_OF_NODE;
                marshalPoint(address, start2);
                marshalPoint(address + SIZE_OF_POINT, end);
                C._ts_node_descendant_for_position_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              namedDescendantForPosition(start2, end = start2) {
                if (!isPoint(start2) || !isPoint(end)) {
                  throw new Error("Arguments must be {row, column} objects");
                }
                marshalNode(this);
                const address = TRANSFER_BUFFER + SIZE_OF_NODE;
                marshalPoint(address, start2);
                marshalPoint(address + SIZE_OF_POINT, end);
                C._ts_node_named_descendant_for_position_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              walk() {
                marshalNode(this);
                C._ts_tree_cursor_new_wasm(this.tree[0]);
                return new TreeCursor(INTERNAL, this.tree);
              }
              toString() {
                marshalNode(this);
                const address = C._ts_node_to_string_wasm(this.tree[0]);
                const result = AsciiToString(address);
                C._free(address);
                return result;
              }
            }
            class TreeCursor {
              static {
                __name(this, "TreeCursor");
              }
              constructor(internal, tree) {
                assertInternal(internal);
                this.tree = tree;
                unmarshalTreeCursor(this);
              }
              delete() {
                marshalTreeCursor(this);
                C._ts_tree_cursor_delete_wasm(this.tree[0]);
                this[0] = this[1] = this[2] = 0;
              }
              reset(node) {
                marshalNode(node);
                marshalTreeCursor(this, TRANSFER_BUFFER + SIZE_OF_NODE);
                C._ts_tree_cursor_reset_wasm(this.tree[0]);
                unmarshalTreeCursor(this);
              }
              resetTo(cursor) {
                marshalTreeCursor(this, TRANSFER_BUFFER);
                marshalTreeCursor(cursor, TRANSFER_BUFFER + SIZE_OF_CURSOR);
                C._ts_tree_cursor_reset_to_wasm(this.tree[0], cursor.tree[0]);
                unmarshalTreeCursor(this);
              }
              get nodeType() {
                return this.tree.language.types[this.nodeTypeId] || "ERROR";
              }
              get nodeTypeId() {
                marshalTreeCursor(this);
                return C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]);
              }
              get nodeStateId() {
                marshalTreeCursor(this);
                return C._ts_tree_cursor_current_node_state_id_wasm(this.tree[0]);
              }
              get nodeId() {
                marshalTreeCursor(this);
                return C._ts_tree_cursor_current_node_id_wasm(this.tree[0]);
              }
              get nodeIsNamed() {
                marshalTreeCursor(this);
                return C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]) === 1;
              }
              get nodeIsMissing() {
                marshalTreeCursor(this);
                return C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]) === 1;
              }
              get nodeText() {
                marshalTreeCursor(this);
                const startIndex = C._ts_tree_cursor_start_index_wasm(this.tree[0]);
                const endIndex = C._ts_tree_cursor_end_index_wasm(this.tree[0]);
                return getText(this.tree, startIndex, endIndex);
              }
              get startPosition() {
                marshalTreeCursor(this);
                C._ts_tree_cursor_start_position_wasm(this.tree[0]);
                return unmarshalPoint(TRANSFER_BUFFER);
              }
              get endPosition() {
                marshalTreeCursor(this);
                C._ts_tree_cursor_end_position_wasm(this.tree[0]);
                return unmarshalPoint(TRANSFER_BUFFER);
              }
              get startIndex() {
                marshalTreeCursor(this);
                return C._ts_tree_cursor_start_index_wasm(this.tree[0]);
              }
              get endIndex() {
                marshalTreeCursor(this);
                return C._ts_tree_cursor_end_index_wasm(this.tree[0]);
              }
              get currentNode() {
                marshalTreeCursor(this);
                C._ts_tree_cursor_current_node_wasm(this.tree[0]);
                return unmarshalNode(this.tree);
              }
              get currentFieldId() {
                marshalTreeCursor(this);
                return C._ts_tree_cursor_current_field_id_wasm(this.tree[0]);
              }
              get currentFieldName() {
                return this.tree.language.fields[this.currentFieldId];
              }
              get currentDepth() {
                marshalTreeCursor(this);
                return C._ts_tree_cursor_current_depth_wasm(this.tree[0]);
              }
              get currentDescendantIndex() {
                marshalTreeCursor(this);
                return C._ts_tree_cursor_current_descendant_index_wasm(this.tree[0]);
              }
              gotoFirstChild() {
                marshalTreeCursor(this);
                const result = C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);
                unmarshalTreeCursor(this);
                return result === 1;
              }
              gotoLastChild() {
                marshalTreeCursor(this);
                const result = C._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);
                unmarshalTreeCursor(this);
                return result === 1;
              }
              gotoFirstChildForIndex(goalIndex) {
                marshalTreeCursor(this);
                setValue(TRANSFER_BUFFER + SIZE_OF_CURSOR, goalIndex, "i32");
                const result = C._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);
                unmarshalTreeCursor(this);
                return result === 1;
              }
              gotoFirstChildForPosition(goalPosition) {
                marshalTreeCursor(this);
                marshalPoint(TRANSFER_BUFFER + SIZE_OF_CURSOR, goalPosition);
                const result = C._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);
                unmarshalTreeCursor(this);
                return result === 1;
              }
              gotoNextSibling() {
                marshalTreeCursor(this);
                const result = C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);
                unmarshalTreeCursor(this);
                return result === 1;
              }
              gotoPreviousSibling() {
                marshalTreeCursor(this);
                const result = C._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);
                unmarshalTreeCursor(this);
                return result === 1;
              }
              gotoDescendant(goalDescendantindex) {
                marshalTreeCursor(this);
                C._ts_tree_cursor_goto_descendant_wasm(this.tree[0], goalDescendantindex);
                unmarshalTreeCursor(this);
              }
              gotoParent() {
                marshalTreeCursor(this);
                const result = C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);
                unmarshalTreeCursor(this);
                return result === 1;
              }
            }
            class Language {
              static {
                __name(this, "Language");
              }
              constructor(internal, address) {
                assertInternal(internal);
                this[0] = address;
                this.types = new Array(C._ts_language_symbol_count(this[0]));
                for (let i4 = 0, n3 = this.types.length; i4 < n3; i4++) {
                  if (C._ts_language_symbol_type(this[0], i4) < 2) {
                    this.types[i4] = UTF8ToString(C._ts_language_symbol_name(this[0], i4));
                  }
                }
                this.fields = new Array(C._ts_language_field_count(this[0]) + 1);
                for (let i4 = 0, n3 = this.fields.length; i4 < n3; i4++) {
                  const fieldName = C._ts_language_field_name_for_id(this[0], i4);
                  if (fieldName !== 0) {
                    this.fields[i4] = UTF8ToString(fieldName);
                  } else {
                    this.fields[i4] = null;
                  }
                }
              }
              get version() {
                return C._ts_language_version(this[0]);
              }
              get fieldCount() {
                return this.fields.length - 1;
              }
              get stateCount() {
                return C._ts_language_state_count(this[0]);
              }
              fieldIdForName(fieldName) {
                const result = this.fields.indexOf(fieldName);
                if (result !== -1) {
                  return result;
                } else {
                  return null;
                }
              }
              fieldNameForId(fieldId) {
                return this.fields[fieldId] || null;
              }
              idForNodeType(type, named) {
                const typeLength = lengthBytesUTF8(type);
                const typeAddress = C._malloc(typeLength + 1);
                stringToUTF8(type, typeAddress, typeLength + 1);
                const result = C._ts_language_symbol_for_name(this[0], typeAddress, typeLength, named);
                C._free(typeAddress);
                return result || null;
              }
              get nodeTypeCount() {
                return C._ts_language_symbol_count(this[0]);
              }
              nodeTypeForId(typeId) {
                const name4 = C._ts_language_symbol_name(this[0], typeId);
                return name4 ? UTF8ToString(name4) : null;
              }
              nodeTypeIsNamed(typeId) {
                return C._ts_language_type_is_named_wasm(this[0], typeId) ? true : false;
              }
              nodeTypeIsVisible(typeId) {
                return C._ts_language_type_is_visible_wasm(this[0], typeId) ? true : false;
              }
              nextState(stateId, typeId) {
                return C._ts_language_next_state(this[0], stateId, typeId);
              }
              lookaheadIterator(stateId) {
                const address = C._ts_lookahead_iterator_new(this[0], stateId);
                if (address) return new LookaheadIterable(INTERNAL, address, this);
                return null;
              }
              query(source2) {
                const sourceLength = lengthBytesUTF8(source2);
                const sourceAddress = C._malloc(sourceLength + 1);
                stringToUTF8(source2, sourceAddress, sourceLength + 1);
                const address = C._ts_query_new(this[0], sourceAddress, sourceLength, TRANSFER_BUFFER, TRANSFER_BUFFER + SIZE_OF_INT);
                if (!address) {
                  const errorId = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                  const errorByte = getValue(TRANSFER_BUFFER, "i32");
                  const errorIndex = UTF8ToString(sourceAddress, errorByte).length;
                  const suffix = source2.substr(errorIndex, 100).split("\n")[0];
                  let word = suffix.match(QUERY_WORD_REGEX)[0];
                  let error40;
                  switch (errorId) {
                    case 2:
                      error40 = new RangeError(`Bad node name '${word}'`);
                      break;
                    case 3:
                      error40 = new RangeError(`Bad field name '${word}'`);
                      break;
                    case 4:
                      error40 = new RangeError(`Bad capture name @${word}`);
                      break;
                    case 5:
                      error40 = new TypeError(`Bad pattern structure at offset ${errorIndex}: '${suffix}'...`);
                      word = "";
                      break;
                    default:
                      error40 = new SyntaxError(`Bad syntax at offset ${errorIndex}: '${suffix}'...`);
                      word = "";
                      break;
                  }
                  error40.index = errorIndex;
                  error40.length = word.length;
                  C._free(sourceAddress);
                  throw error40;
                }
                const stringCount = C._ts_query_string_count(address);
                const captureCount = C._ts_query_capture_count(address);
                const patternCount = C._ts_query_pattern_count(address);
                const captureNames = new Array(captureCount);
                const stringValues = new Array(stringCount);
                for (let i4 = 0; i4 < captureCount; i4++) {
                  const nameAddress = C._ts_query_capture_name_for_id(address, i4, TRANSFER_BUFFER);
                  const nameLength = getValue(TRANSFER_BUFFER, "i32");
                  captureNames[i4] = UTF8ToString(nameAddress, nameLength);
                }
                for (let i4 = 0; i4 < stringCount; i4++) {
                  const valueAddress = C._ts_query_string_value_for_id(address, i4, TRANSFER_BUFFER);
                  const nameLength = getValue(TRANSFER_BUFFER, "i32");
                  stringValues[i4] = UTF8ToString(valueAddress, nameLength);
                }
                const setProperties = new Array(patternCount);
                const assertedProperties = new Array(patternCount);
                const refutedProperties = new Array(patternCount);
                const predicates2 = new Array(patternCount);
                const textPredicates = new Array(patternCount);
                for (let i4 = 0; i4 < patternCount; i4++) {
                  const predicatesAddress = C._ts_query_predicates_for_pattern(address, i4, TRANSFER_BUFFER);
                  const stepCount = getValue(TRANSFER_BUFFER, "i32");
                  predicates2[i4] = [];
                  textPredicates[i4] = [];
                  const steps = [];
                  let stepAddress = predicatesAddress;
                  for (let j2 = 0; j2 < stepCount; j2++) {
                    const stepType = getValue(stepAddress, "i32");
                    stepAddress += SIZE_OF_INT;
                    const stepValueId = getValue(stepAddress, "i32");
                    stepAddress += SIZE_OF_INT;
                    if (stepType === PREDICATE_STEP_TYPE_CAPTURE) {
                      steps.push({
                        type: "capture",
                        name: captureNames[stepValueId]
                      });
                    } else if (stepType === PREDICATE_STEP_TYPE_STRING) {
                      steps.push({
                        type: "string",
                        value: stringValues[stepValueId]
                      });
                    } else if (steps.length > 0) {
                      if (steps[0].type !== "string") {
                        throw new Error("Predicates must begin with a literal value");
                      }
                      const operator2 = steps[0].value;
                      let isPositive = true;
                      let matchAll2 = true;
                      let captureName;
                      switch (operator2) {
                        case "any-not-eq?":
                        case "not-eq?":
                          isPositive = false;
                        case "any-eq?":
                        case "eq?":
                          if (steps.length !== 3) {
                            throw new Error(`Wrong number of arguments to \`#${operator2}\` predicate. Expected 2, got ${steps.length - 1}`);
                          }
                          if (steps[1].type !== "capture") {
                            throw new Error(`First argument of \`#${operator2}\` predicate must be a capture. Got "${steps[1].value}"`);
                          }
                          matchAll2 = !operator2.startsWith("any-");
                          if (steps[2].type === "capture") {
                            const captureName1 = steps[1].name;
                            const captureName2 = steps[2].name;
                            textPredicates[i4].push((captures) => {
                              const nodes1 = [];
                              const nodes2 = [];
                              for (const c4 of captures) {
                                if (c4.name === captureName1) nodes1.push(c4.node);
                                if (c4.name === captureName2) nodes2.push(c4.node);
                              }
                              const compare = /* @__PURE__ */ __name((n1, n22, positive) => positive ? n1.text === n22.text : n1.text !== n22.text, "compare");
                              return matchAll2 ? nodes1.every((n1) => nodes2.some((n22) => compare(n1, n22, isPositive))) : nodes1.some((n1) => nodes2.some((n22) => compare(n1, n22, isPositive)));
                            });
                          } else {
                            captureName = steps[1].name;
                            const stringValue = steps[2].value;
                            const matches2 = /* @__PURE__ */ __name((n3) => n3.text === stringValue, "matches");
                            const doesNotMatch = /* @__PURE__ */ __name((n3) => n3.text !== stringValue, "doesNotMatch");
                            textPredicates[i4].push((captures) => {
                              const nodes = [];
                              for (const c4 of captures) {
                                if (c4.name === captureName) nodes.push(c4.node);
                              }
                              const test2 = isPositive ? matches2 : doesNotMatch;
                              return matchAll2 ? nodes.every(test2) : nodes.some(test2);
                            });
                          }
                          break;
                        case "any-not-match?":
                        case "not-match?":
                          isPositive = false;
                        case "any-match?":
                        case "match?":
                          if (steps.length !== 3) {
                            throw new Error(`Wrong number of arguments to \`#${operator2}\` predicate. Expected 2, got ${steps.length - 1}.`);
                          }
                          if (steps[1].type !== "capture") {
                            throw new Error(`First argument of \`#${operator2}\` predicate must be a capture. Got "${steps[1].value}".`);
                          }
                          if (steps[2].type !== "string") {
                            throw new Error(`Second argument of \`#${operator2}\` predicate must be a string. Got @${steps[2].value}.`);
                          }
                          captureName = steps[1].name;
                          const regex3 = new RegExp(steps[2].value);
                          matchAll2 = !operator2.startsWith("any-");
                          textPredicates[i4].push((captures) => {
                            const nodes = [];
                            for (const c4 of captures) {
                              if (c4.name === captureName) nodes.push(c4.node.text);
                            }
                            const test2 = /* @__PURE__ */ __name((text, positive) => positive ? regex3.test(text) : !regex3.test(text), "test");
                            if (nodes.length === 0) return !isPositive;
                            return matchAll2 ? nodes.every((text) => test2(text, isPositive)) : nodes.some((text) => test2(text, isPositive));
                          });
                          break;
                        case "set!":
                          if (steps.length < 2 || steps.length > 3) {
                            throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`);
                          }
                          if (steps.some((s5) => s5.type !== "string")) {
                            throw new Error(`Arguments to \`#set!\` predicate must be a strings.".`);
                          }
                          if (!setProperties[i4]) setProperties[i4] = {};
                          setProperties[i4][steps[1].value] = steps[2] ? steps[2].value : null;
                          break;
                        case "is?":
                        case "is-not?":
                          if (steps.length < 2 || steps.length > 3) {
                            throw new Error(`Wrong number of arguments to \`#${operator2}\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`);
                          }
                          if (steps.some((s5) => s5.type !== "string")) {
                            throw new Error(`Arguments to \`#${operator2}\` predicate must be a strings.".`);
                          }
                          const properties = operator2 === "is?" ? assertedProperties : refutedProperties;
                          if (!properties[i4]) properties[i4] = {};
                          properties[i4][steps[1].value] = steps[2] ? steps[2].value : null;
                          break;
                        case "not-any-of?":
                          isPositive = false;
                        case "any-of?":
                          if (steps.length < 2) {
                            throw new Error(`Wrong number of arguments to \`#${operator2}\` predicate. Expected at least 1. Got ${steps.length - 1}.`);
                          }
                          if (steps[1].type !== "capture") {
                            throw new Error(`First argument of \`#${operator2}\` predicate must be a capture. Got "${steps[1].value}".`);
                          }
                          for (let i5 = 2; i5 < steps.length; i5++) {
                            if (steps[i5].type !== "string") {
                              throw new Error(`Arguments to \`#${operator2}\` predicate must be a strings.".`);
                            }
                          }
                          captureName = steps[1].name;
                          const values = steps.slice(2).map((s5) => s5.value);
                          textPredicates[i4].push((captures) => {
                            const nodes = [];
                            for (const c4 of captures) {
                              if (c4.name === captureName) nodes.push(c4.node.text);
                            }
                            if (nodes.length === 0) return !isPositive;
                            return nodes.every((text) => values.includes(text)) === isPositive;
                          });
                          break;
                        default:
                          predicates2[i4].push({
                            operator: operator2,
                            operands: steps.slice(1)
                          });
                      }
                      steps.length = 0;
                    }
                  }
                  Object.freeze(setProperties[i4]);
                  Object.freeze(assertedProperties[i4]);
                  Object.freeze(refutedProperties[i4]);
                }
                C._free(sourceAddress);
                return new Query(INTERNAL, address, captureNames, textPredicates, predicates2, Object.freeze(setProperties), Object.freeze(assertedProperties), Object.freeze(refutedProperties));
              }
              static load(input) {
                let bytes;
                if (input instanceof Uint8Array) {
                  bytes = Promise.resolve(input);
                } else {
                  const url3 = input;
                  if (typeof process !== "undefined" && process.versions && process.versions.node) {
                    const fs142 = __require("fs");
                    bytes = Promise.resolve(fs142.readFileSync(url3));
                  } else {
                    bytes = fetch(url3).then((response) => response.arrayBuffer().then((buffer) => {
                      if (response.ok) {
                        return new Uint8Array(buffer);
                      } else {
                        const body2 = new TextDecoder("utf-8").decode(buffer);
                        throw new Error(`Language.load failed with status ${response.status}.

${body2}`);
                      }
                    }));
                  }
                }
                return bytes.then((bytes2) => loadWebAssemblyModule(bytes2, {
                  loadAsync: true
                })).then((mod2) => {
                  const symbolNames = Object.keys(mod2);
                  const functionName = symbolNames.find((key) => LANGUAGE_FUNCTION_REGEX.test(key) && !key.includes("external_scanner_"));
                  if (!functionName) {
                    console.log(`Couldn't find language function in WASM file. Symbols:
${JSON.stringify(symbolNames, null, 2)}`);
                  }
                  const languageAddress = mod2[functionName]();
                  return new Language(INTERNAL, languageAddress);
                });
              }
            }
            class LookaheadIterable {
              static {
                __name(this, "LookaheadIterable");
              }
              constructor(internal, address, language) {
                assertInternal(internal);
                this[0] = address;
                this.language = language;
              }
              get currentTypeId() {
                return C._ts_lookahead_iterator_current_symbol(this[0]);
              }
              get currentType() {
                return this.language.types[this.currentTypeId] || "ERROR";
              }
              delete() {
                C._ts_lookahead_iterator_delete(this[0]);
                this[0] = 0;
              }
              resetState(stateId) {
                return C._ts_lookahead_iterator_reset_state(this[0], stateId);
              }
              reset(language, stateId) {
                if (C._ts_lookahead_iterator_reset(this[0], language[0], stateId)) {
                  this.language = language;
                  return true;
                }
                return false;
              }
              [Symbol.iterator]() {
                const self2 = this;
                return {
                  next() {
                    if (C._ts_lookahead_iterator_next(self2[0])) {
                      return {
                        done: false,
                        value: self2.currentType
                      };
                    }
                    return {
                      done: true,
                      value: ""
                    };
                  }
                };
              }
            }
            class Query {
              static {
                __name(this, "Query");
              }
              constructor(internal, address, captureNames, textPredicates, predicates2, setProperties, assertedProperties, refutedProperties) {
                assertInternal(internal);
                this[0] = address;
                this.captureNames = captureNames;
                this.textPredicates = textPredicates;
                this.predicates = predicates2;
                this.setProperties = setProperties;
                this.assertedProperties = assertedProperties;
                this.refutedProperties = refutedProperties;
                this.exceededMatchLimit = false;
              }
              delete() {
                C._ts_query_delete(this[0]);
                this[0] = 0;
              }
              matches(node, { startPosition = ZERO_POINT, endPosition = ZERO_POINT, startIndex = 0, endIndex = 0, matchLimit = 4294967295, maxStartDepth = 4294967295, timeoutMicros = 0 } = {}) {
                if (typeof matchLimit !== "number") {
                  throw new Error("Arguments must be numbers");
                }
                marshalNode(node);
                C._ts_query_matches_wasm(this[0], node.tree[0], startPosition.row, startPosition.column, endPosition.row, endPosition.column, startIndex, endIndex, matchLimit, maxStartDepth, timeoutMicros);
                const rawCount = getValue(TRANSFER_BUFFER, "i32");
                const startAddress = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                const didExceedMatchLimit = getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
                const result = new Array(rawCount);
                this.exceededMatchLimit = Boolean(didExceedMatchLimit);
                let filteredCount = 0;
                let address = startAddress;
                for (let i4 = 0; i4 < rawCount; i4++) {
                  const pattern = getValue(address, "i32");
                  address += SIZE_OF_INT;
                  const captureCount = getValue(address, "i32");
                  address += SIZE_OF_INT;
                  const captures = new Array(captureCount);
                  address = unmarshalCaptures(this, node.tree, address, captures);
                  if (this.textPredicates[pattern].every((p2) => p2(captures))) {
                    result[filteredCount] = {
                      pattern,
                      captures
                    };
                    const setProperties = this.setProperties[pattern];
                    if (setProperties) result[filteredCount].setProperties = setProperties;
                    const assertedProperties = this.assertedProperties[pattern];
                    if (assertedProperties) result[filteredCount].assertedProperties = assertedProperties;
                    const refutedProperties = this.refutedProperties[pattern];
                    if (refutedProperties) result[filteredCount].refutedProperties = refutedProperties;
                    filteredCount++;
                  }
                }
                result.length = filteredCount;
                C._free(startAddress);
                return result;
              }
              captures(node, { startPosition = ZERO_POINT, endPosition = ZERO_POINT, startIndex = 0, endIndex = 0, matchLimit = 4294967295, maxStartDepth = 4294967295, timeoutMicros = 0 } = {}) {
                if (typeof matchLimit !== "number") {
                  throw new Error("Arguments must be numbers");
                }
                marshalNode(node);
                C._ts_query_captures_wasm(this[0], node.tree[0], startPosition.row, startPosition.column, endPosition.row, endPosition.column, startIndex, endIndex, matchLimit, maxStartDepth, timeoutMicros);
                const count = getValue(TRANSFER_BUFFER, "i32");
                const startAddress = getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
                const didExceedMatchLimit = getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
                const result = [];
                this.exceededMatchLimit = Boolean(didExceedMatchLimit);
                const captures = [];
                let address = startAddress;
                for (let i4 = 0; i4 < count; i4++) {
                  const pattern = getValue(address, "i32");
                  address += SIZE_OF_INT;
                  const captureCount = getValue(address, "i32");
                  address += SIZE_OF_INT;
                  const captureIndex = getValue(address, "i32");
                  address += SIZE_OF_INT;
                  captures.length = captureCount;
                  address = unmarshalCaptures(this, node.tree, address, captures);
                  if (this.textPredicates[pattern].every((p2) => p2(captures))) {
                    const capture = captures[captureIndex];
                    const setProperties = this.setProperties[pattern];
                    if (setProperties) capture.setProperties = setProperties;
                    const assertedProperties = this.assertedProperties[pattern];
                    if (assertedProperties) capture.assertedProperties = assertedProperties;
                    const refutedProperties = this.refutedProperties[pattern];
                    if (refutedProperties) capture.refutedProperties = refutedProperties;
                    result.push(capture);
                  }
                }
                C._free(startAddress);
                return result;
              }
              predicatesForPattern(patternIndex) {
                return this.predicates[patternIndex];
              }
              disableCapture(captureName) {
                const captureNameLength = lengthBytesUTF8(captureName);
                const captureNameAddress = C._malloc(captureNameLength + 1);
                stringToUTF8(captureName, captureNameAddress, captureNameLength + 1);
                C._ts_query_disable_capture(this[0], captureNameAddress, captureNameLength);
                C._free(captureNameAddress);
              }
              didExceedMatchLimit() {
                return this.exceededMatchLimit;
              }
            }
            function getText(tree, startIndex, endIndex) {
              const length = endIndex - startIndex;
              let result = tree.textCallback(startIndex, null, endIndex);
              startIndex += result.length;
              while (startIndex < endIndex) {
                const string4 = tree.textCallback(startIndex, null, endIndex);
                if (string4 && string4.length > 0) {
                  startIndex += string4.length;
                  result += string4;
                } else {
                  break;
                }
              }
              if (startIndex > endIndex) {
                result = result.slice(0, length);
              }
              return result;
            }
            __name(getText, "getText");
            function unmarshalCaptures(query, tree, address, result) {
              for (let i4 = 0, n3 = result.length; i4 < n3; i4++) {
                const captureIndex = getValue(address, "i32");
                address += SIZE_OF_INT;
                const node = unmarshalNode(tree, address);
                address += SIZE_OF_NODE;
                result[i4] = {
                  name: query.captureNames[captureIndex],
                  node
                };
              }
              return address;
            }
            __name(unmarshalCaptures, "unmarshalCaptures");
            function assertInternal(x3) {
              if (x3 !== INTERNAL) throw new Error("Illegal constructor");
            }
            __name(assertInternal, "assertInternal");
            function isPoint(point) {
              return point && typeof point.row === "number" && typeof point.column === "number";
            }
            __name(isPoint, "isPoint");
            function marshalNode(node) {
              let address = TRANSFER_BUFFER;
              setValue(address, node.id, "i32");
              address += SIZE_OF_INT;
              setValue(address, node.startIndex, "i32");
              address += SIZE_OF_INT;
              setValue(address, node.startPosition.row, "i32");
              address += SIZE_OF_INT;
              setValue(address, node.startPosition.column, "i32");
              address += SIZE_OF_INT;
              setValue(address, node[0], "i32");
            }
            __name(marshalNode, "marshalNode");
            function unmarshalNode(tree, address = TRANSFER_BUFFER) {
              const id = getValue(address, "i32");
              address += SIZE_OF_INT;
              if (id === 0) return null;
              const index = getValue(address, "i32");
              address += SIZE_OF_INT;
              const row = getValue(address, "i32");
              address += SIZE_OF_INT;
              const column = getValue(address, "i32");
              address += SIZE_OF_INT;
              const other2 = getValue(address, "i32");
              const result = new Node(INTERNAL, tree);
              result.id = id;
              result.startIndex = index;
              result.startPosition = {
                row,
                column
              };
              result[0] = other2;
              return result;
            }
            __name(unmarshalNode, "unmarshalNode");
            function marshalTreeCursor(cursor, address = TRANSFER_BUFFER) {
              setValue(address + 0 * SIZE_OF_INT, cursor[0], "i32");
              setValue(address + 1 * SIZE_OF_INT, cursor[1], "i32");
              setValue(address + 2 * SIZE_OF_INT, cursor[2], "i32");
              setValue(address + 3 * SIZE_OF_INT, cursor[3], "i32");
            }
            __name(marshalTreeCursor, "marshalTreeCursor");
            function unmarshalTreeCursor(cursor) {
              cursor[0] = getValue(TRANSFER_BUFFER + 0 * SIZE_OF_INT, "i32");
              cursor[1] = getValue(TRANSFER_BUFFER + 1 * SIZE_OF_INT, "i32");
              cursor[2] = getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
              cursor[3] = getValue(TRANSFER_BUFFER + 3 * SIZE_OF_INT, "i32");
            }
            __name(unmarshalTreeCursor, "unmarshalTreeCursor");
            function marshalPoint(address, point) {
              setValue(address, point.row, "i32");
              setValue(address + SIZE_OF_INT, point.column, "i32");
            }
            __name(marshalPoint, "marshalPoint");
            function unmarshalPoint(address) {
              const result = {
                row: getValue(address, "i32") >>> 0,
                column: getValue(address + SIZE_OF_INT, "i32") >>> 0
              };
              return result;
            }
            __name(unmarshalPoint, "unmarshalPoint");
            function marshalRange(address, range) {
              marshalPoint(address, range.startPosition);
              address += SIZE_OF_POINT;
              marshalPoint(address, range.endPosition);
              address += SIZE_OF_POINT;
              setValue(address, range.startIndex, "i32");
              address += SIZE_OF_INT;
              setValue(address, range.endIndex, "i32");
              address += SIZE_OF_INT;
            }
            __name(marshalRange, "marshalRange");
            function unmarshalRange(address) {
              const result = {};
              result.startPosition = unmarshalPoint(address);
              address += SIZE_OF_POINT;
              result.endPosition = unmarshalPoint(address);
              address += SIZE_OF_POINT;
              result.startIndex = getValue(address, "i32") >>> 0;
              address += SIZE_OF_INT;
              result.endIndex = getValue(address, "i32") >>> 0;
              return result;
            }
            __name(unmarshalRange, "unmarshalRange");
            function marshalEdit(edit2) {
              let address = TRANSFER_BUFFER;
              marshalPoint(address, edit2.startPosition);
              address += SIZE_OF_POINT;
              marshalPoint(address, edit2.oldEndPosition);
              address += SIZE_OF_POINT;
              marshalPoint(address, edit2.newEndPosition);
              address += SIZE_OF_POINT;
              setValue(address, edit2.startIndex, "i32");
              address += SIZE_OF_INT;
              setValue(address, edit2.oldEndIndex, "i32");
              address += SIZE_OF_INT;
              setValue(address, edit2.newEndIndex, "i32");
              address += SIZE_OF_INT;
            }
            __name(marshalEdit, "marshalEdit");
            for (const name4 of Object.getOwnPropertyNames(ParserImpl.prototype)) {
              Object.defineProperty(Parser.prototype, name4, {
                value: ParserImpl.prototype[name4],
                enumerable: false,
                writable: false
              });
            }
            Parser.Language = Language;
            Module.onRuntimeInitialized = () => {
              ParserImpl.init();
              resolveInitPromise();
            };
          });
        }
      }
      return Parser;
    }();
    if (typeof exports === "object") {
      module.exports = TreeSitter;
    }
  }
});

// wasm-binary:/build/qwen-code/src/qwen-code/node_modules/web-tree-sitter/tree-sitter.wasm
var require_tree_sitter2 = __commonJS({
  "wasm-binary:/build/qwen-code/src/qwen-code/node_modules/web-tree-sitter/tree-sitter.wasm"(exports2, module2) {
    module2.exports = __toBinaryNode(" ");
  }
});

// wasm-binary:/build/qwen-code/src/qwen-code/node_modules/tree-sitter-wasms/out/tree-sitter-bash.wasm
var require_tree_sitter_bash = __commonJS({
  "wasm-binary:/build/qwen-code/src/qwen-code/node_modules/tree-sitter-wasms/out/tree-sitter-bash.wasm"(exports2, module2) {
    module2.exports = __toBinaryNode(" ");
  }
});

// packages/core/dist/src/utils/shellAstParser.js
import fs39 from "node:fs";
import { createRequire as createRequire2 } from "node:module";
import path35 from "node:path";
import { fileURLToPath as fileURLToPath3 } from "node:url";
async function loadWasmBinary(dynamicImport, fallbackSpecifier) {
  const nativeFs = process.getBuiltinModule?.("fs") ?? fs39;
  const moduleFilePath = fileURLToPath3(import.meta.url);
  const isBundleMode = !moduleFilePath.includes(path35.join("src", "")) && !moduleFilePath.includes(path35.join("dist", "src", ""));
  try {
    if (isBundleMode) {
      const mod2 = await dynamicImport();
      const wasmBinary2 = mod2.default;
      if (wasmBinary2 instanceof Uint8Array && wasmBinary2.byteLength > 0) {
        return wasmBinary2;
      }
    }
  } catch {
  }
  const require2 = createRequire2(import.meta.url);
  const filePath = require2.resolve(fallbackSpecifier);
  return new Uint8Array(nativeFs.readFileSync(filePath));
}
async function initParser() {
  if (parserInstance)
    return;
  if (parserInitFailed)
    throw new Error("tree-sitter WASM failed to initialise; using regex-based fallback");
  if (initPromise2)
    return initPromise2;
  initPromise2 = (async () => {
    const treeSitterWasm = await loadWasmBinary(() => Promise.resolve().then(() => __toESM(require_tree_sitter2(), 1)), "web-tree-sitter/tree-sitter.wasm");
    await import_web_tree_sitter.default.init({ wasmBinary: treeSitterWasm });
    parserInstance = new import_web_tree_sitter.default();
    const bashWasm = await loadWasmBinary(() => Promise.resolve().then(() => __toESM(require_tree_sitter_bash(), 1)), "tree-sitter-wasms/out/tree-sitter-bash.wasm");
    bashLanguage = await import_web_tree_sitter.default.Language.load(bashWasm);
    parserInstance.setLanguage(bashLanguage);
  })().catch((err2) => {
    parserInitFailed = true;
    initPromise2 = null;
    throw err2;
  });
  return initPromise2;
}
async function parseShellCommand(command2) {
  await initParser();
  return parserInstance.parse(command2);
}
function collectDescendants(node, types7) {
  const result = [];
  const stack = [node];
  while (stack.length > 0) {
    const current = stack.pop();
    if (types7.has(current.type)) {
      result.push(current);
    }
    for (let i4 = current.childCount - 1; i4 >= 0; i4--) {
      stack.push(current.child(i4));
    }
  }
  return result;
}
function containsCommandSubstitutionAST(node) {
  return collectDescendants(node, /* @__PURE__ */ new Set(["command_substitution", "process_substitution"])).length > 0;
}
function hasWriteRedirection(node) {
  if (node.type !== "redirected_statement")
    return false;
  for (let i4 = 0; i4 < node.childCount; i4++) {
    const child = node.child(i4);
    if (child.type === "file_redirect") {
      for (let j2 = 0; j2 < child.childCount; j2++) {
        const op = child.child(j2);
        if (op.type === "file_descriptor")
          continue;
        if (WRITE_REDIRECT_OPERATORS.has(op.type))
          return true;
        break;
      }
    }
  }
  return false;
}
function getCommandName(commandNode) {
  const nameNode = commandNode.childForFieldName("name");
  if (!nameNode)
    return null;
  return nameNode.text.toLowerCase();
}
function getArgumentNodes(commandNode) {
  const args2 = [];
  for (let i4 = 0; i4 < commandNode.childCount; i4++) {
    const fieldName = commandNode.fieldNameForChild(i4);
    if (fieldName === "argument") {
      args2.push(commandNode.child(i4));
    }
  }
  return args2;
}
function stripOuterQuotes(text) {
  if (text.length >= 2) {
    if (text.startsWith("'") && text.endsWith("'") || text.startsWith('"') && text.endsWith('"')) {
      return text.slice(1, -1);
    }
  }
  return text;
}
function evaluateCommandReadOnly(commandNode) {
  const root = getCommandName(commandNode);
  if (!root)
    return true;
  const argNodes = getArgumentNodes(commandNode);
  const argTexts = argNodes.map((n3) => stripOuterQuotes(n3.text));
  if (!READ_ONLY_ROOT_COMMANDS2.has(root))
    return false;
  if (root === "git")
    return evaluateGitReadOnly(argTexts);
  if (root === "find")
    return evaluateFindReadOnly(argTexts);
  if (root === "sed")
    return evaluateSedReadOnly(argTexts);
  if (root === "awk")
    return evaluateAwkReadOnly(argTexts);
  return true;
}
function evaluateGitReadOnly(args2) {
  let idx = 0;
  while (idx < args2.length && args2[idx].startsWith("-")) {
    const flag = args2[idx].toLowerCase();
    if (flag === "--version" || flag === "--help")
      return true;
    idx++;
  }
  if (idx >= args2.length)
    return true;
  const subcommand = args2[idx].toLowerCase();
  if (!READ_ONLY_GIT_SUBCOMMANDS2.has(subcommand))
    return false;
  const rest = args2.slice(idx + 1);
  if (subcommand === "remote") {
    return !rest.some((a2) => BLOCKED_GIT_REMOTE_ACTIONS2.has(a2.toLowerCase()));
  }
  if (subcommand === "branch") {
    return !rest.some((a2) => BLOCKED_GIT_BRANCH_FLAGS2.has(a2));
  }
  return true;
}
function evaluateFindReadOnly(args2) {
  for (const arg of args2) {
    const lower3 = arg.toLowerCase();
    if (BLOCKED_FIND_FLAGS2.has(lower3))
      return false;
    if (BLOCKED_FIND_PREFIXES2.some((p2) => lower3.startsWith(p2)))
      return false;
  }
  return true;
}
function evaluateSedReadOnly(args2) {
  for (const arg of args2) {
    if (BLOCKED_SED_PREFIXES2.some((p2) => arg.startsWith(p2)) || arg === "--in-place") {
      return false;
    }
  }
  const scriptContent = args2.join(" ");
  return !SED_SIDE_EFFECT_PATTERNS2.some((p2) => p2.test(scriptContent));
}
function evaluateAwkReadOnly(args2) {
  const scriptContent = args2.join(" ");
  return !AWK_SIDE_EFFECT_PATTERNS2.some((p2) => p2.test(scriptContent));
}
function evaluateStatementReadOnly(node) {
  switch (node.type) {
    case "command":
      if (containsCommandSubstitutionAST(node))
        return false;
      return evaluateCommandReadOnly(node);
    case "pipeline": {
      for (const child of node.namedChildren) {
        if (!evaluateStatementReadOnly(child))
          return false;
      }
      return true;
    }
    case "list": {
      for (const child of node.namedChildren) {
        if (!evaluateStatementReadOnly(child))
          return false;
      }
      return true;
    }
    case "redirected_statement": {
      if (hasWriteRedirection(node))
        return false;
      const body2 = node.namedChildren[0];
      return body2 ? evaluateStatementReadOnly(body2) : true;
    }
    case "subshell": {
      for (const child of node.namedChildren) {
        if (!evaluateStatementReadOnly(child))
          return false;
      }
      return true;
    }
    case "compound_statement": {
      for (const child of node.namedChildren) {
        if (!evaluateStatementReadOnly(child))
          return false;
      }
      return true;
    }
    case "variable_assignment":
    case "variable_assignments":
      return true;
    case "negated_command": {
      const inner = node.namedChildren[0];
      return inner ? evaluateStatementReadOnly(inner) : true;
    }
    case "function_definition":
      return false;
    case "if_statement":
    case "while_statement":
    case "for_statement":
    case "case_statement":
    case "c_style_for_statement":
      return false;
    case "declaration_command":
      return false;
    default:
      return false;
  }
}
async function isShellCommandReadOnlyAST(command2) {
  if (typeof command2 !== "string" || !command2.trim())
    return false;
  if (parserInitFailed) {
    return isShellCommandReadOnly(command2);
  }
  try {
    const tree = await parseShellCommand(command2);
    const root = tree.rootNode;
    if (root.namedChildCount === 0)
      return false;
    for (const stmt of root.namedChildren) {
      if (!evaluateStatementReadOnly(stmt)) {
        tree.delete();
        return false;
      }
    }
    tree.delete();
    return true;
  } catch {
    return isShellCommandReadOnly(command2);
  }
}
function extractRuleFromCommand(commandNode) {
  const rootName = getCommandName(commandNode);
  if (!rootName)
    return null;
  const argNodes = getArgumentNodes(commandNode);
  const argTexts = argNodes.map((n3) => n3.text);
  let idx = 0;
  while (idx < argTexts.length && argTexts[idx].startsWith("-")) {
    idx++;
  }
  const knownSubs = KNOWN_SUBCOMMANDS[rootName];
  let rule = rootName;
  if (knownSubs && knownSubs.size > 0 && idx < argTexts.length) {
    const potentialSub = argTexts[idx].toLowerCase();
    if (knownSubs.has(potentialSub)) {
      rule = `${rootName} ${argTexts[idx]}`;
      if (rootName === "docker" && potentialSub === "compose" && idx + 1 < argTexts.length) {
        const composeSub = argTexts[idx + 1].toLowerCase();
        if (DOCKER_COMPOSE_SUBCOMMANDS.has(composeSub)) {
          rule = `${rootName} compose ${argTexts[idx + 1]}`;
          if (idx + 2 < argTexts.length) {
            rule += " *";
          }
          return rule;
        }
      }
      if (idx + 1 < argTexts.length) {
        rule += " *";
      }
      return rule;
    }
  }
  if (argTexts.length > 0) {
    rule += " *";
  }
  return rule;
}
function extractRulesFromStatement(node) {
  switch (node.type) {
    case "command":
      return [extractRuleFromCommand(node)].filter(Boolean);
    case "pipeline":
    case "list":
    case "compound_statement":
    case "subshell": {
      const rules = [];
      for (const child of node.namedChildren) {
        rules.push(...extractRulesFromStatement(child));
      }
      return rules;
    }
    case "redirected_statement": {
      const body2 = node.namedChildren[0];
      return body2 ? extractRulesFromStatement(body2) : [];
    }
    case "negated_command": {
      const inner = node.namedChildren[0];
      return inner ? extractRulesFromStatement(inner) : [];
    }
    case "variable_assignment":
    case "variable_assignments":
      return [];
    default:
      return [];
  }
}
async function extractCommandRules(command2) {
  if (typeof command2 !== "string" || !command2.trim())
    return [];
  const tree = await parseShellCommand(command2);
  const root = tree.rootNode;
  const rules = [];
  for (const stmt of root.namedChildren) {
    rules.push(...extractRulesFromStatement(stmt));
  }
  tree.delete();
  return [...new Set(rules)];
}
var import_web_tree_sitter, READ_ONLY_ROOT_COMMANDS2, READ_ONLY_GIT_SUBCOMMANDS2, BLOCKED_GIT_REMOTE_ACTIONS2, BLOCKED_GIT_BRANCH_FLAGS2, BLOCKED_FIND_FLAGS2, BLOCKED_FIND_PREFIXES2, BLOCKED_SED_PREFIXES2, AWK_SIDE_EFFECT_PATTERNS2, SED_SIDE_EFFECT_PATTERNS2, WRITE_REDIRECT_OPERATORS, KNOWN_SUBCOMMANDS, DOCKER_COMPOSE_SUBCOMMANDS, parserInstance, bashLanguage, initPromise2, parserInitFailed;
var init_shellAstParser = __esm({
  "packages/core/dist/src/utils/shellAstParser.js"() {
    "use strict";
    init_esbuild_shims();
    import_web_tree_sitter = __toESM(require_tree_sitter(), 1);
    init_shellReadOnlyChecker();
    __name(loadWasmBinary, "loadWasmBinary");
    READ_ONLY_ROOT_COMMANDS2 = /* @__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"
    ]);
    READ_ONLY_GIT_SUBCOMMANDS2 = /* @__PURE__ */ new Set([
      "blame",
      "branch",
      "cat-file",
      "diff",
      "grep",
      "log",
      "ls-files",
      "remote",
      "rev-parse",
      "show",
      "status",
      "describe"
    ]);
    BLOCKED_GIT_REMOTE_ACTIONS2 = /* @__PURE__ */ new Set([
      "add",
      "remove",
      "rename",
      "set-url",
      "prune",
      "update"
    ]);
    BLOCKED_GIT_BRANCH_FLAGS2 = /* @__PURE__ */ new Set([
      "-d",
      "-D",
      "--delete",
      "--move",
      "-m"
    ]);
    BLOCKED_FIND_FLAGS2 = /* @__PURE__ */ new Set([
      "-delete",
      "-exec",
      "-execdir",
      "-ok",
      "-okdir"
    ]);
    BLOCKED_FIND_PREFIXES2 = ["-fprint", "-fprintf"];
    BLOCKED_SED_PREFIXES2 = ["-i"];
    AWK_SIDE_EFFECT_PATTERNS2 = [
      /system\s*\(/,
      /print\s+[^>|]*>\s*"[^"]*"/,
      /printf\s+[^>|]*>\s*"[^"]*"/,
      /print\s+[^>|]*>>\s*"[^"]*"/,
      /printf\s+[^>|]*>>\s*"[^"]*"/,
      /print\s+[^|]*\|\s*"[^"]*"/,
      /printf\s+[^|]*\|\s*"[^"]*"/,
      /getline\s*<\s*"[^"]*"/,
      /"[^"]*"\s*\|\s*getline/,
      /close\s*\(/
    ];
    SED_SIDE_EFFECT_PATTERNS2 = [
      /[^\\]e\s/,
      /^e\s/,
      /[^\\]w\s/,
      /^w\s/,
      /[^\\]r\s/,
      /^r\s/
    ];
    WRITE_REDIRECT_OPERATORS = /* @__PURE__ */ new Set([">", ">>", "&>", "&>>", ">|"]);
    KNOWN_SUBCOMMANDS = {
      git: /* @__PURE__ */ new Set([
        "add",
        "am",
        "archive",
        "bisect",
        "blame",
        "branch",
        "bundle",
        "cat-file",
        "checkout",
        "cherry-pick",
        "clean",
        "clone",
        "commit",
        "config",
        "describe",
        "diff",
        "fetch",
        "format-patch",
        "gc",
        "grep",
        "init",
        "log",
        "ls-files",
        "ls-remote",
        "merge",
        "mv",
        "notes",
        "pull",
        "push",
        "range-diff",
        "rebase",
        "reflog",
        "remote",
        "reset",
        "restore",
        "revert",
        "rev-parse",
        "rm",
        "shortlog",
        "show",
        "stash",
        "status",
        "submodule",
        "switch",
        "tag",
        "worktree"
      ]),
      npm: /* @__PURE__ */ new Set([
        "access",
        "adduser",
        "audit",
        "bugs",
        "cache",
        "ci",
        "completion",
        "config",
        "create",
        "dedupe",
        "deprecate",
        "diff",
        "dist-tag",
        "docs",
        "doctor",
        "edit",
        "exec",
        "explain",
        "explore",
        "find-dupes",
        "fund",
        "help",
        "hook",
        "init",
        "install",
        "install-ci-test",
        "install-test",
        "link",
        "login",
        "logout",
        "ls",
        "org",
        "outdated",
        "owner",
        "pack",
        "ping",
        "pkg",
        "prefix",
        "profile",
        "prune",
        "publish",
        "query",
        "rebuild",
        "repo",
        "restart",
        "root",
        "run",
        "run-script",
        "search",
        "set-script",
        "shrinkwrap",
        "star",
        "stars",
        "start",
        "stop",
        "team",
        "test",
        "token",
        "uninstall",
        "unpublish",
        "unstar",
        "update",
        "version",
        "view",
        "whoami"
      ]),
      yarn: /* @__PURE__ */ new Set([
        "add",
        "autoclean",
        "bin",
        "cache",
        "check",
        "config",
        "create",
        "generate-lock-entry",
        "global",
        "help",
        "import",
        "info",
        "init",
        "install",
        "licenses",
        "link",
        "list",
        "login",
        "logout",
        "outdated",
        "owner",
        "pack",
        "policies",
        "publish",
        "remove",
        "run",
        "tag",
        "team",
        "test",
        "unlink",
        "unplug",
        "upgrade",
        "upgrade-interactive",
        "version",
        "versions",
        "why",
        "workspace",
        "workspaces"
      ]),
      pnpm: /* @__PURE__ */ new Set([
        "add",
        "audit",
        "create",
        "dedupe",
        "deploy",
        "dlx",
        "env",
        "exec",
        "fetch",
        "import",
        "init",
        "install",
        "install-test",
        "licenses",
        "link",
        "list",
        "ls",
        "outdated",
        "pack",
        "patch",
        "patch-commit",
        "prune",
        "publish",
        "rebuild",
        "remove",
        "root",
        "run",
        "server",
        "setup",
        "store",
        "test",
        "uninstall",
        "unlink",
        "update",
        "why"
      ]),
      docker: /* @__PURE__ */ new Set([
        "attach",
        "build",
        "commit",
        "compose",
        "container",
        "context",
        "cp",
        "create",
        "diff",
        "events",
        "exec",
        "export",
        "history",
        "image",
        "images",
        "import",
        "info",
        "inspect",
        "kill",
        "load",
        "login",
        "logout",
        "logs",
        "manifest",
        "network",
        "node",
        "pause",
        "plugin",
        "port",
        "ps",
        "pull",
        "push",
        "rename",
        "restart",
        "rm",
        "rmi",
        "run",
        "save",
        "search",
        "secret",
        "service",
        "stack",
        "start",
        "stats",
        "stop",
        "swarm",
        "system",
        "tag",
        "top",
        "trust",
        "unpause",
        "update",
        "version",
        "volume",
        "wait"
      ]),
      pip: /* @__PURE__ */ new Set([
        "install",
        "download",
        "uninstall",
        "freeze",
        "inspect",
        "list",
        "show",
        "check",
        "config",
        "search",
        "cache",
        "index",
        "wheel",
        "hash",
        "completion",
        "debug",
        "help"
      ]),
      pip3: /* @__PURE__ */ new Set([
        "install",
        "download",
        "uninstall",
        "freeze",
        "inspect",
        "list",
        "show",
        "check",
        "config",
        "search",
        "cache",
        "index",
        "wheel",
        "hash",
        "completion",
        "debug",
        "help"
      ]),
      cargo: /* @__PURE__ */ new Set([
        "add",
        "bench",
        "build",
        "check",
        "clean",
        "clippy",
        "doc",
        "fetch",
        "fix",
        "fmt",
        "generate-lockfile",
        "init",
        "install",
        "locate-project",
        "login",
        "metadata",
        "new",
        "owner",
        "package",
        "pkgid",
        "publish",
        "read-manifest",
        "remove",
        "report",
        "run",
        "rustc",
        "rustdoc",
        "search",
        "test",
        "tree",
        "uninstall",
        "update",
        "vendor",
        "verify-project",
        "version",
        "yank"
      ]),
      kubectl: /* @__PURE__ */ new Set([
        "annotate",
        "api-resources",
        "api-versions",
        "apply",
        "attach",
        "auth",
        "autoscale",
        "certificate",
        "cluster-info",
        "completion",
        "config",
        "cordon",
        "cp",
        "create",
        "debug",
        "delete",
        "describe",
        "diff",
        "drain",
        "edit",
        "events",
        "exec",
        "explain",
        "expose",
        "get",
        "kustomize",
        "label",
        "logs",
        "patch",
        "plugin",
        "port-forward",
        "proxy",
        "replace",
        "rollout",
        "run",
        "scale",
        "set",
        "taint",
        "top",
        "uncordon",
        "version",
        "wait"
      ]),
      make: /* @__PURE__ */ new Set([])
      // make targets are positional, not subcommands
    };
    DOCKER_COMPOSE_SUBCOMMANDS = /* @__PURE__ */ new Set([
      "build",
      "config",
      "cp",
      "create",
      "down",
      "events",
      "exec",
      "images",
      "kill",
      "logs",
      "ls",
      "pause",
      "port",
      "ps",
      "pull",
      "push",
      "restart",
      "rm",
      "run",
      "start",
      "stop",
      "top",
      "unpause",
      "up",
      "version",
      "wait",
      "watch"
    ]);
    parserInstance = null;
    bashLanguage = null;
    initPromise2 = null;
    parserInitFailed = false;
    __name(initParser, "initParser");
    __name(parseShellCommand, "parseShellCommand");
    __name(collectDescendants, "collectDescendants");
    __name(containsCommandSubstitutionAST, "containsCommandSubstitutionAST");
    __name(hasWriteRedirection, "hasWriteRedirection");
    __name(getCommandName, "getCommandName");
    __name(getArgumentNodes, "getArgumentNodes");
    __name(stripOuterQuotes, "stripOuterQuotes");
    __name(evaluateCommandReadOnly, "evaluateCommandReadOnly");
    __name(evaluateGitReadOnly, "evaluateGitReadOnly");
    __name(evaluateFindReadOnly, "evaluateFindReadOnly");
    __name(evaluateSedReadOnly, "evaluateSedReadOnly");
    __name(evaluateAwkReadOnly, "evaluateAwkReadOnly");
    __name(evaluateStatementReadOnly, "evaluateStatementReadOnly");
    __name(isShellCommandReadOnlyAST, "isShellCommandReadOnlyAST");
    __name(extractRuleFromCommand, "extractRuleFromCommand");
    __name(extractRulesFromStatement, "extractRulesFromStatement");
    __name(extractCommandRules, "extractCommandRules");
  }
});

// packages/core/dist/src/tools/shell.js
var shell_exports = {};
__export(shell_exports, {
  OUTPUT_UPDATE_INTERVAL_MS: () => OUTPUT_UPDATE_INTERVAL_MS,
  ShellTool: () => ShellTool,
  ShellToolInvocation: () => ShellToolInvocation
});
import fs40 from "node:fs";
import path36 from "node:path";
import os18 from "node:os";
import crypto8 from "node:crypto";
function stripTrailingBackgroundAmp(command2) {
  const trimmed2 = command2.trimEnd();
  if (!trimmed2.endsWith("&"))
    return command2;
  if (trimmed2.endsWith("&&"))
    return command2;
  if (trimmed2.endsWith("\\&"))
    return command2;
  return trimmed2.slice(0, -1).trimEnd();
}
function getShellToolDescription() {
  const isWindows9 = os18.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)
- **Shell argument quoting and special characters**: When passing arguments that contain special characters (parentheses \`()\`, backticks \`\`\`\`, dollar signs \`$\`, backslashes \`\\\`, semicolons \`;\`, pipes \`|\`, angle brackets \`<>\`, ampersands \`&\`, exclamation marks \`!\`, etc.), you MUST ensure they are properly quoted to prevent the shell from misinterpreting them as shell syntax:
  - **Single quotes** \`'...'\` pass everything literally, but cannot contain a literal single quote.
  - **ANSI-C quoting** \`$'...'\` supports escape sequences (e.g. \`\\n\` for newline, \`\\'\` for single quote) and is the safest approach for multi-line strings or strings with single quotes.
  - **Heredoc** is the most robust approach for large, multi-line text with mixed quotes:
    \`\`\`bash
    gh pr create --title "My Title" --body "$(cat <<'HEREDOC'
    Multi-line body with (parentheses), \`backticks\`, and 'single-quotes'.
    HEREDOC
    )"
    \`\`\`
  - NEVER use unescaped single quotes inside single-quoted strings (e.g. \`'it\\'s'\` is wrong; use \`$'it\\'s'\` or \`"it's"\` instead).
  - If unsure, prefer double-quoting arguments and escape inner double-quotes as \`\\"\`.
- 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() {
  if (os18.platform() === "win32") {
    return "Exact command to execute as `cmd.exe /c <command>`";
  } else {
    return "Exact bash command to execute as `bash -c <command>`";
  }
}
var debugLogger36, 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_truncation();
    init_shellExecutionService();
    init_strip_ansi();
    init_formatters();
    init_paths();
    init_shell_utils();
    init_debugLogger();
    init_shellAstParser();
    debugLogger36 = createDebugLogger("SHELL");
    __name(stripTrailingBackgroundAmp, "stripTrailingBackgroundAmp");
    OUTPUT_UPDATE_INTERVAL_MS = 1e3;
    DEFAULT_FOREGROUND_TIMEOUT_MS = 12e4;
    ShellToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "ShellToolInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      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;
      }
      /**
       * AST-based permission check for the shell command.
       * - Read-only commands (via AST analysis) → 'allow'
       * - All other commands → 'ask'
       */
      async getDefaultPermission() {
        const command2 = stripShellWrapper(this.params.command);
        try {
          const isReadOnly = await isShellCommandReadOnlyAST(command2);
          if (isReadOnly) {
            return "allow";
          }
        } catch (e4) {
          debugLogger36.warn("AST read-only check failed, falling back to ask:", e4);
        }
        return "ask";
      }
      /**
       * Constructs confirmation dialog details for a shell command that needs
       * user approval.  For compound commands (e.g. `cd foo && npm run build`),
       * sub-commands that are already allowed (read-only) are excluded from both
       * the displayed root-command list and the suggested permission rules.
       */
      async getConfirmationDetails(_abortSignal) {
        const command2 = stripShellWrapper(this.params.command);
        const pm = this.config.getPermissionManager?.();
        const subCommands = splitCommands(command2);
        const confirmableSubCommands = [];
        for (const sub of subCommands) {
          let isReadOnly = false;
          try {
            isReadOnly = await isShellCommandReadOnlyAST(sub);
          } catch {
          }
          if (isReadOnly) {
            continue;
          }
          if (pm) {
            try {
              if (await pm.isCommandAllowed(sub) === "allow") {
                continue;
              }
            } catch (e4) {
              debugLogger36.warn("PermissionManager command check failed:", e4);
            }
          }
          confirmableSubCommands.push(sub);
        }
        const effectiveSubCommands = confirmableSubCommands.length > 0 ? confirmableSubCommands : subCommands;
        const rootCommands = [
          ...new Set(effectiveSubCommands.map((c4) => getCommandRoot(c4)).filter((c4) => !!c4))
        ];
        let permissionRules = [];
        try {
          const allRules = [];
          for (const sub of effectiveSubCommands) {
            const rules = await extractCommandRules(sub);
            allRules.push(...rules);
          }
          permissionRules = [...new Set(allRules)].map((rule) => `Bash(${rule})`);
        } catch (e4) {
          debugLogger36.warn("Failed to extract command rules:", e4);
        }
        const confirmationDetails = {
          type: "exec",
          title: "Confirm Shell Command",
          command: this.params.command,
          rootCommand: rootCommands.join(", "),
          permissionRules,
          onConfirm: /* @__PURE__ */ __name(async (_outcome, _payload) => {
          }, "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."
          };
        }
        if (this.params.is_background) {
          return this.executeBackground(signal, shellExecutionConfig);
        }
        const effectiveTimeout = this.params.timeout ?? DEFAULT_FOREGROUND_TIMEOUT_MS;
        let combinedSignal = signal;
        if (effectiveTimeout) {
          const timeoutSignal = AbortSignal.timeout(effectiveTimeout);
          combinedSignal = AbortSignal.any([signal, timeoutSignal]);
        }
        const processedCommand = this.addCoAuthorToGitCommit(strippedCommand);
        const commandToExecute = processedCommand;
        const cwd6 = this.params.directory || this.config.getTargetDir();
        let cumulativeOutput = "";
        let lastUpdateTime = Date.now();
        let isBinaryStream = false;
        let totalLines = 0;
        let totalBytes = 0;
        const { result: resultPromise, pid } = await ShellExecutionService.execute(commandToExecute, cwd6, (event) => {
          let shouldUpdate = false;
          switch (event.type) {
            case "data":
              if (isBinaryStream)
                break;
              cumulativeOutput = event.chunk;
              if (Array.isArray(event.chunk)) {
                totalLines = event.chunk.length;
                totalBytes = event.chunk.reduce((sum, line) => sum + line.reduce((ls, token2) => ls + Buffer.byteLength(token2.text, "utf-8"), 0), 0);
              }
              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) {
            if (typeof cumulativeOutput === "string") {
              updateOutput2(cumulativeOutput);
            } else {
              updateOutput2({
                ansiOutput: cumulativeOutput,
                totalLines,
                totalBytes,
                // Only include timeout when user explicitly set it
                ...this.params.timeout != null && {
                  timeoutMs: this.params.timeout
                }
              });
            }
            lastUpdateTime = Date.now();
          }
        }, combinedSignal, this.config.getShouldUseNodePtyShell(), shellExecutionConfig ?? {});
        if (pid && setPidCallback) {
          setPidCallback(pid);
        }
        const result = await resultPromise;
        let llmContent = "";
        if (result.aborted) {
          const wasTimeout = 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)"}`,
            `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 = 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}`;
            }
          }
        }
        if (typeof llmContent === "string") {
          const truncatedResult = await truncateToolOutput(this.config, ShellTool.Name, llmContent);
          if (truncatedResult.outputFile) {
            llmContent = truncatedResult.content;
            returnDisplayMessage += (returnDisplayMessage ? "\n" : "") + `Output too long and was saved to: ${truncatedResult.outputFile}`;
          }
        }
        const executionError = result.error ? {
          error: {
            message: result.error.message,
            type: ToolErrorType.SHELL_EXECUTE_ERROR
          }
        } : {};
        return {
          llmContent,
          returnDisplay: returnDisplayMessage,
          ...executionError
        };
      }
      /**
       * Background-execution path: spawn the command into a managed registry
       * entry instead of detaching with `&`. Output streams to a per-shell file
       * the agent can `Read`; cancellation flows through the entry's
       * AbortController; the registry's terminal status is set when the process
       * exits. Returns immediately so the agent's turn isn't blocked.
       */
      async executeBackground(signal, shellExecutionConfig) {
        const strippedCommand = stripShellWrapper(this.params.command);
        const noTrailingAmp = stripTrailingBackgroundAmp(strippedCommand);
        if (noTrailingAmp !== strippedCommand) {
          debugLogger36.warn("Stripped trailing & from background shell command \u2014 managed path handles backgrounding");
        }
        const processedCommand = this.addCoAuthorToGitCommit(noTrailingAmp);
        const cwd6 = this.params.directory || this.config.getTargetDir();
        const outputDir = path36.join(this.config.storage.getProjectTempDir(), "background-shells", this.config.getSessionId());
        fs40.mkdirSync(outputDir, { recursive: true });
        const shellId = `bg_${crypto8.randomBytes(4).toString("hex")}`;
        const outputPath = path36.join(outputDir, `shell-${shellId}.output`);
        const entryAc = new AbortController();
        const outputStream = fs40.createWriteStream(outputPath, { flags: "w" });
        outputStream.on("error", (err2) => {
          debugLogger36.warn(`background shell ${shellId} output write error: ${err2.message}`);
        });
        const startTime = Date.now();
        const entry = {
          shellId,
          command: processedCommand,
          cwd: cwd6,
          status: "running",
          startTime,
          outputPath,
          abortController: entryAc
        };
        const { result: resultPromise, pid } = await ShellExecutionService.execute(
          processedCommand,
          cwd6,
          (event) => {
            if (event.type === "data" && typeof event.chunk === "string") {
              outputStream.write(stripAnsi2(event.chunk));
            }
          },
          entryAc.signal,
          // Background shells are non-interactive by design — no terminal to
          // attach a PTY to, no human to type at it. Force the child_process
          // path so we don't pull in node-pty for fire-and-forget commands.
          false,
          shellExecutionConfig ?? {},
          // Stream stdout/stderr through to the output file as chunks arrive.
          // Default child_process mode buffers until exit, which would leave
          // dev-server / watcher output files empty until the process dies.
          { streamStdout: true }
        );
        if (pid !== void 0)
          entry.pid = pid;
        const registry3 = this.config.getBackgroundShellRegistry();
        registry3.register(entry);
        void resultPromise.then((result) => {
          outputStream.end();
          const endTime = Date.now();
          if (entryAc.signal.aborted) {
            if (registry3.get(shellId)?.status === "running") {
              registry3.cancel(shellId, endTime);
            }
          } else if (result.error || result.exitCode !== null && result.exitCode !== 0 || result.signal !== null) {
            const reason = result.error ? result.error.message : result.signal !== null ? `terminated by signal ${result.signal}` : `exited with code ${result.exitCode}`;
            registry3.fail(shellId, reason, endTime);
          } else {
            registry3.complete(shellId, result.exitCode ?? 0, endTime);
          }
        }, (err2) => {
          outputStream.end();
          registry3.fail(shellId, getErrorMessage(err2), Date.now());
        });
        const pidLine = pid !== void 0 ? `pid: ${pid}
` : "";
        return {
          llmContent: `Background shell started.
id: ${shellId}
` + pidLine + `output file: ${outputPath}
Use the /tasks command to list and inspect background shells, or Read the output file directly.`,
          returnDisplay: `Background shell ${shellId} started${pid !== void 0 ? ` (pid ${pid})` : ""}.`
        };
      }
      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;
      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) {
        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 (!path36.isAbsolute(params.directory)) {
            return "Directory must be an absolute path.";
          }
          const userSkillsDirs = this.config.storage.getUserSkillsDirs();
          const resolvedDirectoryPath = path36.resolve(params.directory);
          const isWithinUserSkills = isSubpaths(userSkillsDirs, 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);
      }
    };
  }
});

// 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/constants.js
var QWEN_CODE_COMPANION_EXTENSION_NAME, IDE_MAX_OPEN_FILES, IDE_MAX_SELECTED_TEXT_LENGTH, IDE_REQUEST_TIMEOUT_MS;
var init_constants4 = __esm({
  "packages/core/dist/src/ide/constants.js"() {
    "use strict";
    init_esbuild_shims();
    QWEN_CODE_COMPANION_EXTENSION_NAME = "Qwen Code Companion";
    IDE_MAX_OPEN_FILES = 10;
    IDE_MAX_SELECTED_TEXT_LENGTH = 16384;
    IDE_REQUEST_TIMEOUT_MS = 10 * 60 * 1e3;
  }
});

// packages/core/dist/src/ide/ideContext.js
var IdeContextStore, ideContextStore;
var init_ideContext = __esm({
  "packages/core/dist/src/ide/ideContext.js"() {
    "use strict";
    init_esbuild_shims();
    init_constants4();
    IdeContextStore = class {
      static {
        __name(this, "IdeContextStore");
      }
      ideContextState;
      subscribers = /* @__PURE__ */ new Set();
      /**
       * Notifies all registered subscribers about the current IDE context.
       */
      notifySubscribers() {
        for (const subscriber of this.subscribers) {
          subscriber(this.ideContextState);
        }
      }
      /**
       * Sets the IDE context and notifies all registered subscribers of the change.
       * @param newIdeContext The new IDE context from the IDE.
       */
      set(newIdeContext) {
        const { workspaceState } = newIdeContext;
        if (!workspaceState) {
          this.ideContextState = newIdeContext;
          this.notifySubscribers();
          return;
        }
        const { openFiles } = workspaceState;
        if (openFiles && openFiles.length > 0) {
          openFiles.sort((a2, b2) => b2.timestamp - a2.timestamp);
          const mostRecentFile = openFiles[0];
          if (!mostRecentFile.isActive) {
            openFiles.forEach((file2) => {
              file2.isActive = false;
              file2.cursor = void 0;
              file2.selectedText = void 0;
            });
          } else {
            openFiles.forEach((file2, index) => {
              if (index !== 0) {
                file2.isActive = false;
                file2.cursor = void 0;
                file2.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(util5) {
      util5.assertEqual = (_2) => {
      };
      function assertIs2(_arg) {
      }
      __name(assertIs2, "assertIs");
      util5.assertIs = assertIs2;
      function assertNever4(_x) {
        throw new Error();
      }
      __name(assertNever4, "assertNever");
      util5.assertNever = assertNever4;
      util5.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
          obj[item] = item;
        }
        return obj;
      };
      util5.getValidEnumValues = (obj) => {
        const validKeys = util5.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number");
        const filtered = {};
        for (const k2 of validKeys) {
          filtered[k2] = obj[k2];
        }
        return util5.objectValues(filtered);
      };
      util5.objectValues = (obj) => {
        return util5.objectKeys(obj).map(function(e4) {
          return obj[e4];
        });
      };
      util5.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;
      };
      util5.find = (arr, checker) => {
        for (const item of arr) {
          if (checker(item))
            return item;
        }
        return void 0;
      };
      util5.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");
      util5.joinValues = joinValues2;
      util5.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 json3 = JSON.stringify(obj, null, 2);
      return json3.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((error40) => {
          for (const issue2 of error40.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 i4 = 0;
              while (i4 < issue2.path.length) {
                const el = issue2.path[i4];
                const terminal = i4 === 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];
                i4++;
              }
            }
          }
        }, "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 error40 = new ZodError(issues);
      return error40;
    };
  }
});

// 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(map3) {
  overrideErrorMap = map3;
}
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: path150, errorMaps, issueData } = params;
      const fullPath = [...path150, ...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 map3 of maps) {
        errorMessage = map3(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(args2) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args2.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args2.precision}}`;
  } else if (args2.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args2.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args2) {
  return new RegExp(`^${timeRegexSource(args2)}$`);
}
function datetimeRegex(args2) {
  let regex3 = `${dateRegexSource}T${timeRegexSource(args2)}`;
  const opts = [];
  opts.push(args2.local ? `Z?` : `Z`);
  if (args2.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(jwt2, alg) {
  if (!jwtRegex.test(jwt2))
    return false;
  try {
    const [header] = jwt2.split(".");
    if (!header)
      return false;
    const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base643));
    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_types9 = __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, path150, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path150;
        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 error40 = new ZodError(ctx.common.issues);
            this._error = error40;
            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 (err2) {
            if (err2?.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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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, i4) => {
            return def2.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i4));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i4) => {
          return def2.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i4));
        });
        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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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, i4) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i4)));
        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(args2, error40) {
          return makeIssue({
            data: args2,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x3) => !!x3),
            issueData: {
              code: ZodIssueCode.invalid_arguments,
              argumentsError: error40
            }
          });
        }
        __name(makeArgsIssue, "makeArgsIssue");
        function makeReturnsIssue(returns, error40) {
          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: error40
            }
          });
        }
        __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(...args2) {
            const error40 = new ZodError([]);
            const parsedArgs = await me2._def.args.parseAsync(args2, params).catch((e4) => {
              error40.addIssue(makeArgsIssue(args2, e4));
              throw error40;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me2._def.returns._def.type.parseAsync(result, params).catch((e4) => {
              error40.addIssue(makeReturnsIssue(result, e4));
              throw error40;
            });
            return parsedReturns;
          });
        } else {
          const me2 = this;
          return OK(function(...args2) {
            const parsedArgs = me2._def.args.safeParse(args2, params);
            if (!parsedArgs.success) {
              throw new ZodError([makeArgsIssue(args2, 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(func2) {
        const validatedFunc = this.parse(func2);
        return validatedFunc;
      }
      strictImplement(func2) {
        const validatedFunc = this.parse(func2);
        return validatedFunc;
      }
      static create(args2, returns, params) {
        return new _ZodFunction({
          args: args2 ? args2 : 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 parsedType4 = this._getType(input);
        if (parsedType4 === 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 parsedType4 = this._getType(input);
        if (parsedType4 === 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 parsedType4 = this._getType(input);
        if (parsedType4 !== 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_types9();
    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_types10 = __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/ide/process-utils.js
import { exec, execFile as execFile8 } from "node:child_process";
import { promisify as promisify7 } from "node:util";
import os19 from "node:os";
import path37 from "node:path";
async function getProcessInfo(pid) {
  try {
    const command2 = `ps -o ppid=,command= -p ${pid}`;
    const { stdout: stdout2 } = await execAsync(command2);
    const trimmedStdout = stdout2.trim();
    if (!trimmedStdout) {
      return { parentPid: 0, name: "", command: "" };
    }
    const parts2 = trimmedStdout.split(/\s+/);
    const ppidString = parts2[0];
    const parentPid = parseInt(ppidString, 10);
    const fullCommand = trimmedStdout.substring(ppidString.length).trim();
    const processName = path37.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 i4 = 0; i4 < MAX_TRAVERSAL_DEPTH; i4++) {
    try {
      const { parentPid, name: name4 } = await getProcessInfo(currentPid);
      const isShell = shells.some((shell2) => name4 === 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: stdout2 } = await execFileAsync5("powershell", ["-NoProfile", "-NonInteractive", "-Command", powershellCommand], { maxBuffer: 10 * 1024 * 1024 });
    if (!stdout2.trim()) {
      return processMap;
    }
    let processes;
    try {
      processes = JSON.parse(stdout2);
    } 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 i4 = 0; i4 < MAX_TRAVERSAL_DEPTH && curr; i4++) {
    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 platform15 = os19.platform();
  if (platform15 === "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(execFile8);
    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(name4, initializer3, params) {
  function init2(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(name4);
    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(init2, "init");
  const Parent = params?.Parent ?? Object;
  class Definition extends Parent {
    static {
      __name(this, "Definition");
    }
  }
  Object.defineProperty(Definition, "name", { value: name4 });
  function _2(def2) {
    var _a7;
    const inst = params?.Parent ? new Definition() : this;
    init2(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: init2 });
  Object.defineProperty(_2, Symbol.hasInstance, {
    value: /* @__PURE__ */ __name((inst) => {
      if (params?.Parent && inst instanceof params.Parent)
        return true;
      return inst?._zod?.traits?.has(name4);
    }, "value")
  });
  Object.defineProperty(_2, "name", { value: name4 });
  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: () => escapeRegex2,
  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: () => pick,
  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 set2 = false;
  return {
    get value() {
      if (!set2) {
        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 start2 = source2.startsWith("^") ? 1 : 0;
  const end = source2.endsWith("$") ? source2.length - 1 : source2.length;
  return source2.slice(start2, 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 set2 = false;
  Object.defineProperty(object3, key, {
    get() {
      if (!set2) {
        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, path150) {
  if (!path150)
    return obj;
  return path150.reduce((acc, key) => acc?.[key], obj);
}
function promiseAllObject(promisesObj) {
  const keys = Object.keys(promisesObj);
  const promises9 = keys.map((key) => promisesObj[key]);
  return Promise.all(promises9).then((results) => {
    const resolvedObj = {};
    for (let i4 = 0; i4 < keys.length; i4++) {
      resolvedObj[keys[i4]] = results[i4];
    }
    return resolvedObj;
  });
}
function randomString(length = 10) {
  const chars = "abcdefghijklmnopqrstuvwxyz";
  let str2 = "";
  for (let i4 = 0; i4 < length; i4++) {
    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 escapeRegex2(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 pick(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 i4 = startIndex; i4 < x3.issues.length; i4++) {
    if (x3.issues[i4]?.continue !== true)
      return true;
  }
  return false;
}
function prefixIssues(path150, issues) {
  return issues.map((iss) => {
    var _a7;
    (_a7 = iss).path ?? (_a7.path = []);
    iss.path.unshift(path150);
    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(...args2) {
  const [iss, input, inst] = args2;
  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_util3 = __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(escapeRegex2, "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(pick, "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(error40, mapper = (issue2) => issue2.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error40.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(error40, _mapper) {
  const mapper = _mapper || function(issue2) {
    return issue2.message;
  };
  const fieldErrors = { _errors: [] };
  const processError = /* @__PURE__ */ __name((error41) => {
    for (const issue2 of error41.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 i4 = 0;
        while (i4 < issue2.path.length) {
          const el = issue2.path[i4];
          const terminal = i4 === 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];
          i4++;
        }
      }
    }
  }, "processError");
  processError(error40);
  return fieldErrors;
}
function treeifyError(error40, _mapper) {
  const mapper = _mapper || function(issue2) {
    return issue2.message;
  };
  const result = { errors: [] };
  const processError = /* @__PURE__ */ __name((error41, path150 = []) => {
    var _a7, _b2;
    for (const issue2 of error41.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }, issue2.path));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues }, issue2.path);
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues }, issue2.path);
      } else {
        const fullpath = [...path150, ...issue2.path];
        if (fullpath.length === 0) {
          result.errors.push(mapper(issue2));
          continue;
        }
        let curr = result;
        let i4 = 0;
        while (i4 < fullpath.length) {
          const el = fullpath[i4];
          const terminal = i4 === fullpath.length - 1;
          if (typeof el === "string") {
            curr.properties ?? (curr.properties = {});
            (_a7 = curr.properties)[el] ?? (_a7[el] = { errors: [] });
            curr = curr.properties[el];
          } else {
            curr.items ?? (curr.items = []);
            (_b2 = curr.items)[el] ?? (_b2[el] = { errors: [] });
            curr = curr.items[el];
          }
          if (terminal) {
            curr.errors.push(mapper(issue2));
          }
          i4++;
        }
      }
    }
  }, "processError");
  processError(error40);
  return result;
}
function toDotPath(path150) {
  const segs = [];
  for (const seg of path150) {
    if (typeof seg === "number")
      segs.push(`[${seg}]`);
    else if (typeof seg === "symbol")
      segs.push(`[${JSON.stringify(String(seg))}]`);
    else if (/[^\w$]/.test(seg))
      segs.push(`[${JSON.stringify(seg)}]`);
    else {
      if (segs.length)
        segs.push(".");
      segs.push(seg);
    }
  }
  return segs.join("");
}
function prettifyError(error40) {
  const lines = [];
  const issues = [...error40.issues].sort((a2, b2) => a2.path.length - b2.path.length);
  for (const issue2 of issues) {
    lines.push(`\u2716 ${issue2.message}`);
    if (issue2.path?.length)
      lines.push(`  \u2192 at ${toDotPath(issue2.path)}`);
  }
  return lines.join("\n");
}
var initializer, $ZodError, $ZodRealError;
var init_errors4 = __esm({
  "node_modules/zod/v4/core/errors.js"() {
    init_esbuild_shims();
    init_core2();
    init_util3();
    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");
    __name(treeifyError, "treeifyError");
    __name(toDotPath, "toDotPath");
    __name(prettifyError, "prettifyError");
  }
});

// node_modules/zod/v4/core/parse.js
var _parse, parse4, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync;
var init_parse2 = __esm({
  "node_modules/zod/v4/core/parse.js"() {
    init_esbuild_shims();
    init_core2();
    init_errors4();
    init_util3();
    _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");
    parse4 = /* @__PURE__ */ _parse($ZodRealError);
    _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");
    parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);
    _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
var regexes_exports = {};
__export(regexes_exports, {
  _emoji: () => _emoji,
  base64: () => base64,
  base64url: () => base64url,
  bigint: () => bigint,
  boolean: () => boolean,
  browserEmail: () => browserEmail,
  cidrv4: () => cidrv4,
  cidrv6: () => cidrv6,
  cuid: () => cuid,
  cuid2: () => cuid2,
  date: () => date,
  datetime: () => datetime,
  domain: () => domain,
  duration: () => duration,
  e164: () => e164,
  email: () => email,
  emoji: () => emoji,
  extendedDuration: () => extendedDuration,
  guid: () => guid,
  hostname: () => hostname2,
  html5Email: () => html5Email,
  integer: () => integer,
  ipv4: () => ipv4,
  ipv6: () => ipv6,
  ksuid: () => ksuid,
  lowercase: () => lowercase,
  nanoid: () => nanoid,
  null: () => _null,
  number: () => number,
  rfc5322Email: () => rfc5322Email,
  string: () => string,
  time: () => time,
  ulid: () => ulid,
  undefined: () => _undefined,
  unicodeEmail: () => unicodeEmail,
  uppercase: () => uppercase,
  uuid: () => uuid,
  uuid4: () => uuid43,
  uuid6: () => uuid6,
  uuid7: () => uuid7,
  xid: () => xid
});
function emoji() {
  return new RegExp(_emoji, "u");
}
function timeSource(args2) {
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
  const regex3 = typeof args2.precision === "number" ? args2.precision === -1 ? `${hhmm}` : args2.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args2.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
  return regex3;
}
function time(args2) {
  return new RegExp(`^${timeSource(args2)}$`);
}
function datetime(args2) {
  const time3 = timeSource({ precision: args2.precision });
  const opts = ["Z"];
  if (args2.local)
    opts.push("");
  if (args2.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, extendedDuration, guid, uuid, uuid43, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, browserEmail, _emoji, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, hostname2, domain, e164, dateSource, date, string, bigint, integer, number, boolean, _null, _undefined, 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)?)?)$/;
    extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    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");
    uuid43 = /* @__PURE__ */ uuid(4);
    uuid6 = /* @__PURE__ */ uuid(6);
    uuid7 = /* @__PURE__ */ uuid(7);
    email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
    html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
    browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
    _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-]+$/;
    domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
    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;
    _undefined = /undefined/i;
    lowercase = /^[^A-Z]*$/;
    uppercase = /^[^a-z]*$/;
  }
});

// node_modules/zod/v4/core/checks.js
function handleCheckPropertyResult(result, payload, property) {
  if (result.issues.length) {
    payload.issues.push(...prefixIssues(property, result.issues));
  }
}
var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite;
var init_checks = __esm({
  "node_modules/zod/v4/core/checks.js"() {
    init_esbuild_shims();
    init_core2();
    init_regexes();
    init_util3();
    $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 origin2 = 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: origin2,
          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 origin2 = 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: origin2,
          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 origin2 = 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: origin2,
              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: origin2,
                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: origin2,
                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
          });
        }
      };
    });
    $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      const [minimum, maximum] = BIGINT_FORMAT_RANGES[def2.format];
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.format = def2.format;
        bag.minimum = minimum;
        bag.maximum = maximum;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        if (input < minimum) {
          payload.issues.push({
            origin: "bigint",
            input,
            code: "too_small",
            minimum,
            inclusive: true,
            inst,
            continue: !def2.abort
          });
        }
        if (input > maximum) {
          payload.issues.push({
            origin: "bigint",
            input,
            code: "too_big",
            maximum,
            inst
          });
        }
      };
    });
    $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def2) => {
      var _a7;
      $ZodCheck.init(inst, def2);
      (_a7 = inst._zod.def).when ?? (_a7.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.size !== 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 size = input.size;
        if (size <= def2.maximum)
          return;
        payload.issues.push({
          origin: getSizableOrigin(input),
          code: "too_big",
          maximum: def2.maximum,
          input,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def2) => {
      var _a7;
      $ZodCheck.init(inst, def2);
      (_a7 = inst._zod.def).when ?? (_a7.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.size !== 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 size = input.size;
        if (size >= def2.minimum)
          return;
        payload.issues.push({
          origin: getSizableOrigin(input),
          code: "too_small",
          minimum: def2.minimum,
          input,
          inst,
          continue: !def2.abort
        });
      };
    });
    $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def2) => {
      var _a7;
      $ZodCheck.init(inst, def2);
      (_a7 = inst._zod.def).when ?? (_a7.when = (payload) => {
        const val = payload.value;
        return !nullish(val) && val.size !== void 0;
      });
      inst._zod.onattach.push((inst2) => {
        const bag = inst2._zod.bag;
        bag.minimum = def2.size;
        bag.maximum = def2.size;
        bag.size = def2.size;
      });
      inst._zod.check = (payload) => {
        const input = payload.value;
        const size = input.size;
        if (size === def2.size)
          return;
        const tooBig = size > def2.size;
        payload.issues.push({
          origin: getSizableOrigin(input),
          ...tooBig ? { code: "too_big", maximum: def2.size } : { code: "too_small", minimum: def2.size },
          inclusive: true,
          exact: true,
          input: payload.value,
          inst,
          continue: !def2.abort
        });
      };
    });
    $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 origin2 = getLengthableOrigin(input);
        payload.issues.push({
          origin: origin2,
          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 origin2 = getLengthableOrigin(input);
        payload.issues.push({
          origin: origin2,
          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 origin2 = getLengthableOrigin(input);
        const tooBig = length > def2.length;
        payload.issues.push({
          origin: origin2,
          ...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 = escapeRegex2(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(`^${escapeRegex2(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(`.*${escapeRegex2(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
        });
      };
    });
    __name(handleCheckPropertyResult, "handleCheckPropertyResult");
    $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      inst._zod.check = (payload) => {
        const result = def2.schema._zod.run({
          value: payload.value[def2.property],
          issues: []
        }, {});
        if (result instanceof Promise) {
          return result.then((result2) => handleCheckPropertyResult(result2, payload, def2.property));
        }
        handleCheckPropertyResult(result, payload, def2.property);
        return;
      };
    });
    $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def2) => {
      $ZodCheck.init(inst, def2);
      const mimeSet = new Set(def2.mime);
      inst._zod.onattach.push((inst2) => {
        inst2._zod.bag.mime = def2.mime;
      });
      inst._zod.check = (payload) => {
        if (mimeSet.has(payload.value.type))
          return;
        payload.issues.push({
          code: "invalid_value",
          values: def2.mime,
          input: payload.value.type,
          inst
        });
      };
    });
    $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(args2 = []) {
        this.content = [];
        this.indent = 0;
        if (this)
          this.args = args2;
      }
      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 args2 = this?.args;
        const content = this?.content ?? [``];
        const lines = [...content.map((x3) => `  ${x3}`)];
        return new F4(...args2, 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 base643 = data.replace(/[-_]/g, (c4) => c4 === "-" ? "+" : "/");
  const padded = base643.padEnd(Math.ceil(base643.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 handleTupleResult(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}
function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
  if (keyResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, keyResult.issues));
    } else {
      final.issues.push({
        origin: "map",
        code: "invalid_key",
        input,
        inst,
        issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  if (valueResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, valueResult.issues));
    } else {
      final.issues.push({
        origin: "map",
        code: "invalid_element",
        input,
        inst,
        key,
        issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  final.value.set(keyResult.value, valueResult.value);
}
function handleSetResult(result, final) {
  if (result.issues.length) {
    final.issues.push(...result.issues);
  }
  final.value.add(result.value);
}
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, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodReadonly, $ZodTemplateLiteral, $ZodPromise, $ZodLazy, $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_util3();
    init_versions();
    init_util3();
    $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 url3 = new URL(orig);
          const href = url3.href;
          if (def2.hostname) {
            def2.hostname.lastIndex = 0;
            if (!def2.hostname.test(url3.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(url3.protocol.endsWith(":") ? url3.protocol.slice(0, -1) : url3.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
        });
      };
    });
    $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def2) => {
      $ZodStringFormat.init(inst, def2);
      inst._zod.check = (payload) => {
        if (def2.fn(payload.value))
          return;
        payload.issues.push({
          code: "invalid_format",
          format: def2.format,
          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;
      };
    });
    $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def2) => {
      $ZodCheckBigIntFormat.init(inst, def2);
      $ZodBigInt.init(inst, def2);
    });
    $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (typeof input === "symbol")
          return payload;
        payload.issues.push({
          expected: "symbol",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.pattern = _undefined;
      inst._zod.values = /* @__PURE__ */ new Set([void 0]);
      inst._zod.optin = "optional";
      inst._zod.optout = "optional";
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (typeof input === "undefined")
          return payload;
        payload.issues.push({
          expected: "undefined",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $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;
      };
    });
    $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (typeof input === "undefined")
          return payload;
        payload.issues.push({
          expected: "void",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $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 isDate2 = input instanceof Date;
        const isValidDate = isDate2 && !Number.isNaN(input.getTime());
        if (isValidDate)
          return payload;
        payload.issues.push({
          expected: "date",
          code: "invalid_type",
          input,
          ...isDate2 ? { 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 i4 = 0; i4 < input.length; i4++) {
          const item = input[i4];
          const result = def2.element._zod.run({
            value: item,
            issues: []
          }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => handleArrayResult(result2, payload, i4)));
          } else {
            handleArrayResult(result, payload, i4);
          }
        }
        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 isObject5 = 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 (!isObject5(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 map3 = /* @__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 (map3.has(v2)) {
              throw new Error(`Duplicate discriminator value "${String(v2)}"`);
            }
            map3.set(v2, o3);
          }
        }
        return map3;
      });
      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");
    $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def2) => {
      $ZodType.init(inst, def2);
      const items = def2.items;
      const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional");
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!Array.isArray(input)) {
          payload.issues.push({
            input,
            inst,
            expected: "tuple",
            code: "invalid_type"
          });
          return payload;
        }
        payload.value = [];
        const proms = [];
        if (!def2.rest) {
          const tooBig = input.length > items.length;
          const tooSmall = input.length < optStart - 1;
          if (tooBig || tooSmall) {
            payload.issues.push({
              input,
              inst,
              origin: "array",
              ...tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }
            });
            return payload;
          }
        }
        let i4 = -1;
        for (const item of items) {
          i4++;
          if (i4 >= input.length) {
            if (i4 >= optStart)
              continue;
          }
          const result = item._zod.run({
            value: input[i4],
            issues: []
          }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => handleTupleResult(result2, payload, i4)));
          } else {
            handleTupleResult(result, payload, i4);
          }
        }
        if (def2.rest) {
          const rest = input.slice(items.length);
          for (const el of rest) {
            i4++;
            const result = def2.rest._zod.run({
              value: el,
              issues: []
            }, ctx);
            if (result instanceof Promise) {
              proms.push(result.then((result2) => handleTupleResult(result2, payload, i4)));
            } else {
              handleTupleResult(result, payload, i4);
            }
          }
        }
        if (proms.length)
          return Promise.all(proms).then(() => payload);
        return payload;
      };
    });
    __name(handleTupleResult, "handleTupleResult");
    $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;
      };
    });
    $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!(input instanceof Map)) {
          payload.issues.push({
            expected: "map",
            code: "invalid_type",
            input,
            inst
          });
          return payload;
        }
        const proms = [];
        payload.value = /* @__PURE__ */ new Map();
        for (const [key, value] of input) {
          const keyResult = def2.keyType._zod.run({ value: key, issues: [] }, ctx);
          const valueResult = def2.valueType._zod.run({ value, issues: [] }, ctx);
          if (keyResult instanceof Promise || valueResult instanceof Promise) {
            proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
              handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
            }));
          } else {
            handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
          }
        }
        if (proms.length)
          return Promise.all(proms).then(() => payload);
        return payload;
      };
    });
    __name(handleMapResult, "handleMapResult");
    $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, ctx) => {
        const input = payload.value;
        if (!(input instanceof Set)) {
          payload.issues.push({
            input,
            inst,
            expected: "set",
            code: "invalid_type"
          });
          return payload;
        }
        const proms = [];
        payload.value = /* @__PURE__ */ new Set();
        for (const item of input) {
          const result = def2.valueType._zod.run({ value: item, issues: [] }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => handleSetResult(result2, payload)));
          } else
            handleSetResult(result, payload);
        }
        if (proms.length)
          return Promise.all(proms).then(() => payload);
        return payload;
      };
    });
    __name(handleSetResult, "handleSetResult");
    $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" ? escapeRegex2(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" ? escapeRegex2(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;
      };
    });
    $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, _ctx) => {
        const input = payload.value;
        if (input instanceof File)
          return payload;
        payload.issues.push({
          expected: "file",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      };
    });
    $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");
    $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, ctx) => {
        const result = def2.innerType._zod.run(payload, ctx);
        if (result instanceof Promise) {
          return result.then((result2) => {
            payload.value = result2.issues.length === 0;
            return payload;
          });
        }
        payload.value = result.issues.length === 0;
        return payload;
      };
    });
    $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;
      };
    });
    $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, _ctx) => {
        if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
          payload.issues.push({
            input: payload.value,
            inst,
            expected: "nan",
            code: "invalid_type"
          });
          return payload;
        }
        return payload;
      };
    });
    $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");
    $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def2) => {
      $ZodType.init(inst, def2);
      const regexParts = [];
      for (const part of def2.parts) {
        if (part instanceof $ZodType) {
          if (!part._zod.pattern) {
            throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
          }
          const source2 = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
          if (!source2)
            throw new Error(`Invalid template literal part: ${part._zod.traits}`);
          const start2 = source2.startsWith("^") ? 1 : 0;
          const end = source2.endsWith("$") ? source2.length - 1 : source2.length;
          regexParts.push(source2.slice(start2, end));
        } else if (part === null || primitiveTypes.has(typeof part)) {
          regexParts.push(escapeRegex2(`${part}`));
        } else {
          throw new Error(`Invalid template literal part: ${part}`);
        }
      }
      inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
      inst._zod.parse = (payload, _ctx) => {
        if (typeof payload.value !== "string") {
          payload.issues.push({
            input: payload.value,
            inst,
            expected: "template_literal",
            code: "invalid_type"
          });
          return payload;
        }
        inst._zod.pattern.lastIndex = 0;
        if (!inst._zod.pattern.test(payload.value)) {
          payload.issues.push({
            input: payload.value,
            inst,
            code: "invalid_format",
            format: "template_literal",
            pattern: inst._zod.pattern.source
          });
          return payload;
        }
        return payload;
      };
    });
    $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def2) => {
      $ZodType.init(inst, def2);
      inst._zod.parse = (payload, ctx) => {
        return Promise.resolve(payload.value).then((inner) => def2.innerType._zod.run({ value: inner, issues: [] }, ctx));
      };
    });
    $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def2) => {
      $ZodType.init(inst, def2);
      defineLazy(inst._zod, "innerType", () => def2.getter());
      defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern);
      defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues);
      defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin);
      defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout);
      inst._zod.parse = (payload, ctx) => {
        const inner = inst._zod.innerType;
        return inner._zod.run(payload, ctx);
      };
    });
    $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/ar.js
function ar_default() {
  return {
    localeError: error()
  };
}
var error;
var init_ar = __esm({
  "node_modules/zod/v4/locales/ar.js"() {
    init_esbuild_shims();
    init_util3();
    error = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
        file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
        array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
        set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__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");
      const Nouns = {
        regex: "\u0645\u062F\u062E\u0644",
        email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",
        url: "\u0631\u0627\u0628\u0637",
        emoji: "\u0625\u064A\u0645\u0648\u062C\u064A",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
        date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
        time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
        duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
        ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4",
        ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6",
        cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",
        cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",
        base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",
        base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",
        json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",
        e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",
        jwt: "JWT",
        template_literal: "\u0645\u062F\u062E\u0644"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`;
            return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`;
            return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`;
            if (_issue.format === "ends_with")
              return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`;
          }
          case "not_multiple_of":
            return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
          case "invalid_key":
            return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
          case "invalid_union":
            return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
          case "invalid_element":
            return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
          default:
            return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
        }
      };
    }, "error");
    __name(ar_default, "default");
  }
});

// node_modules/zod/v4/locales/az.js
function az_default() {
  return {
    localeError: error2()
  };
}
var error2;
var init_az = __esm({
  "node_modules/zod/v4/locales/az.js"() {
    init_esbuild_shims();
    init_util3();
    error2 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "simvol", verb: "olmal\u0131d\u0131r" },
        file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
        array: { unit: "element", verb: "olmal\u0131d\u0131r" },
        set: { unit: "element", verb: "olmal\u0131d\u0131r" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__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");
      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 `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${issue2.expected}, daxil olan ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`;
            return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
            return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;
            if (_issue.format === "ends_with")
              return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`;
            if (_issue.format === "includes")
              return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`;
            if (_issue.format === "regex")
              return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;
            return `Yanl\u0131\u015F ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;
          case "unrecognized_keys":
            return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;
          case "invalid_union":
            return "Yanl\u0131\u015F d\u0259y\u0259r";
          case "invalid_element":
            return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;
          default:
            return `Yanl\u0131\u015F d\u0259y\u0259r`;
        }
      };
    }, "error");
    __name(az_default, "default");
  }
});

// node_modules/zod/v4/locales/be.js
function getBelarusianPlural(count, one, few, many2) {
  const absCount = Math.abs(count);
  const lastDigit = absCount % 10;
  const lastTwoDigits = absCount % 100;
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
    return many2;
  }
  if (lastDigit === 1) {
    return one;
  }
  if (lastDigit >= 2 && lastDigit <= 4) {
    return few;
  }
  return many2;
}
function be_default() {
  return {
    localeError: error3()
  };
}
var error3;
var init_be = __esm({
  "node_modules/zod/v4/locales/be.js"() {
    init_esbuild_shims();
    init_util3();
    __name(getBelarusianPlural, "getBelarusianPlural");
    error3 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: {
          unit: {
            one: "\u0441\u0456\u043C\u0432\u0430\u043B",
            few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B",
            many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"
          },
          verb: "\u043C\u0435\u0446\u044C"
        },
        array: {
          unit: {
            one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
            few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
            many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
          },
          verb: "\u043C\u0435\u0446\u044C"
        },
        set: {
          unit: {
            one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
            few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
            many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
          },
          verb: "\u043C\u0435\u0446\u044C"
        },
        file: {
          unit: {
            one: "\u0431\u0430\u0439\u0442",
            few: "\u0431\u0430\u0439\u0442\u044B",
            many: "\u0431\u0430\u0439\u0442\u0430\u045E"
          },
          verb: "\u043C\u0435\u0446\u044C"
        }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u043B\u0456\u043A";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u043C\u0430\u0441\u0456\u045E";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u0443\u0432\u043E\u0434",
        email: "email \u0430\u0434\u0440\u0430\u0441",
        url: "URL",
        emoji: "\u044D\u043C\u043E\u0434\u0437\u0456",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",
        date: "ISO \u0434\u0430\u0442\u0430",
        time: "ISO \u0447\u0430\u0441",
        duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",
        ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441",
        ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441",
        cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
        cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
        base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",
        base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",
        json_string: "JSON \u0440\u0430\u0434\u043E\u043A",
        e164: "\u043D\u0443\u043C\u0430\u0440 E.164",
        jwt: "JWT",
        template_literal: "\u0443\u0432\u043E\u0434"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              const maxValue = Number(issue2.maximum);
              const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
              return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`;
            }
            return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              const minValue = Number(issue2.minimum);
              const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
              return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`;
            }
            return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
          case "invalid_union":
            return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";
          case "invalid_element":
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`;
          default:
            return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`;
        }
      };
    }, "error");
    __name(be_default, "default");
  }
});

// node_modules/zod/v4/locales/ca.js
function ca_default() {
  return {
    localeError: error4()
  };
}
var error4;
var init_ca = __esm({
  "node_modules/zod/v4/locales/ca.js"() {
    init_esbuild_shims();
    init_util3();
    error4 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "car\xE0cters", verb: "contenir" },
        file: { unit: "bytes", verb: "contenir" },
        array: { unit: "elements", verb: "contenir" },
        set: { unit: "elements", verb: "contenir" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__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");
      const Nouns = {
        regex: "entrada",
        email: "adre\xE7a electr\xF2nica",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "data i hora ISO",
        date: "data ISO",
        time: "hora ISO",
        duration: "durada ISO",
        ipv4: "adre\xE7a IPv4",
        ipv6: "adre\xE7a IPv6",
        cidrv4: "rang IPv4",
        cidrv6: "rang IPv6",
        base64: "cadena codificada en base64",
        base64url: "cadena codificada en base64url",
        json_string: "cadena JSON",
        e164: "n\xFAmero E.164",
        jwt: "JWT",
        template_literal: "entrada"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Tipus inv\xE0lid: s'esperava ${issue2.expected}, s'ha rebut ${parsedType4(issue2.input)}`;
          // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;
            return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
            return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`;
            return `Format inv\xE0lid per a ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Clau inv\xE0lida a ${issue2.origin}`;
          case "invalid_union":
            return "Entrada inv\xE0lida";
          // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general
          case "invalid_element":
            return `Element inv\xE0lid a ${issue2.origin}`;
          default:
            return `Entrada inv\xE0lida`;
        }
      };
    }, "error");
    __name(ca_default, "default");
  }
});

// node_modules/zod/v4/locales/cs.js
function cs_default() {
  return {
    localeError: error5()
  };
}
var error5;
var init_cs = __esm({
  "node_modules/zod/v4/locales/cs.js"() {
    init_esbuild_shims();
    init_util3();
    error5 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "znak\u016F", verb: "m\xEDt" },
        file: { unit: "bajt\u016F", verb: "m\xEDt" },
        array: { unit: "prvk\u016F", verb: "m\xEDt" },
        set: { unit: "prvk\u016F", verb: "m\xEDt" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u010D\xEDslo";
          }
          case "string": {
            return "\u0159et\u011Bzec";
          }
          case "boolean": {
            return "boolean";
          }
          case "bigint": {
            return "bigint";
          }
          case "function": {
            return "funkce";
          }
          case "symbol": {
            return "symbol";
          }
          case "undefined": {
            return "undefined";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "pole";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "regul\xE1rn\xED v\xFDraz",
        email: "e-mailov\xE1 adresa",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "datum a \u010Das ve form\xE1tu ISO",
        date: "datum ve form\xE1tu ISO",
        time: "\u010Das ve form\xE1tu ISO",
        duration: "doba trv\xE1n\xED ISO",
        ipv4: "IPv4 adresa",
        ipv6: "IPv6 adresa",
        cidrv4: "rozsah IPv4",
        cidrv6: "rozsah IPv6",
        base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",
        base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",
        json_string: "\u0159et\u011Bzec ve form\xE1tu JSON",
        e164: "\u010D\xEDslo E.164",
        jwt: "JWT",
        template_literal: "vstup"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${issue2.expected}, obdr\u017Eeno ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`;
            return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
            }
            return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
            }
            return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`;
            return `Neplatn\xFD form\xE1t ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`;
          case "invalid_union":
            return "Neplatn\xFD vstup";
          case "invalid_element":
            return `Neplatn\xE1 hodnota v ${issue2.origin}`;
          default:
            return `Neplatn\xFD vstup`;
        }
      };
    }, "error");
    __name(cs_default, "default");
  }
});

// node_modules/zod/v4/locales/de.js
function de_default() {
  return {
    localeError: error6()
  };
}
var error6;
var init_de = __esm({
  "node_modules/zod/v4/locales/de.js"() {
    init_esbuild_shims();
    init_util3();
    error6 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "Zeichen", verb: "zu haben" },
        file: { unit: "Bytes", verb: "zu haben" },
        array: { unit: "Elemente", verb: "zu haben" },
        set: { unit: "Elemente", verb: "zu haben" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "Zahl";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "Array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "Eingabe",
        email: "E-Mail-Adresse",
        url: "URL",
        emoji: "Emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO-Datum und -Uhrzeit",
        date: "ISO-Datum",
        time: "ISO-Uhrzeit",
        duration: "ISO-Dauer",
        ipv4: "IPv4-Adresse",
        ipv6: "IPv6-Adresse",
        cidrv4: "IPv4-Bereich",
        cidrv6: "IPv6-Bereich",
        base64: "Base64-codierter String",
        base64url: "Base64-URL-codierter String",
        json_string: "JSON-String",
        e164: "E.164-Nummer",
        jwt: "JWT",
        template_literal: "Eingabe"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Ung\xFCltige Eingabe: erwartet ${issue2.expected}, erhalten ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;
            return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`;
            return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;
            }
            return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`;
            if (_issue.format === "ends_with")
              return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`;
            if (_issue.format === "includes")
              return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`;
            if (_issue.format === "regex")
              return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`;
            return `Ung\xFCltig: ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;
          case "unrecognized_keys":
            return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`;
          case "invalid_union":
            return "Ung\xFCltige Eingabe";
          case "invalid_element":
            return `Ung\xFCltiger Wert in ${issue2.origin}`;
          default:
            return `Ung\xFCltige Eingabe`;
        }
      };
    }, "error");
    __name(de_default, "default");
  }
});

// node_modules/zod/v4/locales/en.js
function en_default2() {
  return {
    localeError: error7()
  };
}
var parsedType, error7;
var init_en2 = __esm({
  "node_modules/zod/v4/locales/en.js"() {
    init_esbuild_shims();
    init_util3();
    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");
    error7 = /* @__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(origin2) {
        return Sizable[origin2] ?? 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/eo.js
function eo_default() {
  return {
    localeError: error8()
  };
}
var parsedType2, error8;
var init_eo = __esm({
  "node_modules/zod/v4/locales/eo.js"() {
    init_esbuild_shims();
    init_util3();
    parsedType2 = /* @__PURE__ */ __name((data) => {
      const t5 = typeof data;
      switch (t5) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "nombro";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "tabelo";
          }
          if (data === null) {
            return "senvalora";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t5;
    }, "parsedType");
    error8 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "karaktrojn", verb: "havi" },
        file: { unit: "bajtojn", verb: "havi" },
        array: { unit: "elementojn", verb: "havi" },
        set: { unit: "elementojn", verb: "havi" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const Nouns = {
        regex: "enigo",
        email: "retadreso",
        url: "URL",
        emoji: "emo\u011Dio",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO-datotempo",
        date: "ISO-dato",
        time: "ISO-tempo",
        duration: "ISO-da\u016Dro",
        ipv4: "IPv4-adreso",
        ipv6: "IPv6-adreso",
        cidrv4: "IPv4-rango",
        cidrv6: "IPv6-rango",
        base64: "64-ume kodita karaktraro",
        base64url: "URL-64-ume kodita karaktraro",
        json_string: "JSON-karaktraro",
        e164: "E.164-nombro",
        jwt: "JWT",
        template_literal: "enigo"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Nevalida enigo: atendi\u011Dis ${issue2.expected}, ricevi\u011Dis ${parsedType2(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`;
            return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`;
            return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;
            return `Nevalida ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Nevalida \u015Dlosilo en ${issue2.origin}`;
          case "invalid_union":
            return "Nevalida enigo";
          case "invalid_element":
            return `Nevalida valoro en ${issue2.origin}`;
          default:
            return `Nevalida enigo`;
        }
      };
    }, "error");
    __name(eo_default, "default");
  }
});

// node_modules/zod/v4/locales/es.js
function es_default() {
  return {
    localeError: error9()
  };
}
var error9;
var init_es = __esm({
  "node_modules/zod/v4/locales/es.js"() {
    init_esbuild_shims();
    init_util3();
    error9 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "caracteres", verb: "tener" },
        file: { unit: "bytes", verb: "tener" },
        array: { unit: "elementos", verb: "tener" },
        set: { unit: "elementos", verb: "tener" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "n\xFAmero";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "arreglo";
            }
            if (data === null) {
              return "nulo";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "entrada",
        email: "direcci\xF3n de correo electr\xF3nico",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "fecha y hora ISO",
        date: "fecha ISO",
        time: "hora ISO",
        duration: "duraci\xF3n ISO",
        ipv4: "direcci\xF3n IPv4",
        ipv6: "direcci\xF3n IPv6",
        cidrv4: "rango IPv4",
        cidrv6: "rango IPv6",
        base64: "cadena codificada en base64",
        base64url: "URL codificada en base64",
        json_string: "cadena JSON",
        e164: "n\xFAmero E.164",
        jwt: "JWT",
        template_literal: "entrada"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Entrada inv\xE1lida: se esperaba ${issue2.expected}, recibido ${parsedType4(issue2.input)}`;
          // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;
            return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Demasiado grande: se esperaba que ${issue2.origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
            return `Demasiado grande: se esperaba que ${issue2.origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Demasiado peque\xF1o: se esperaba que ${issue2.origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Demasiado peque\xF1o: se esperaba que ${issue2.origin} fuera ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`;
            return `Inv\xE1lido ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Llave inv\xE1lida en ${issue2.origin}`;
          case "invalid_union":
            return "Entrada inv\xE1lida";
          case "invalid_element":
            return `Valor inv\xE1lido en ${issue2.origin}`;
          default:
            return `Entrada inv\xE1lida`;
        }
      };
    }, "error");
    __name(es_default, "default");
  }
});

// node_modules/zod/v4/locales/fa.js
function fa_default() {
  return {
    localeError: error10()
  };
}
var error10;
var init_fa = __esm({
  "node_modules/zod/v4/locales/fa.js"() {
    init_esbuild_shims();
    init_util3();
    error10 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
        file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
        array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
        set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u0622\u0631\u0627\u06CC\u0647";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u0648\u0631\u0648\u062F\u06CC",
        email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",
        url: "URL",
        emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
        date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",
        time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
        duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
        ipv4: "IPv4 \u0622\u062F\u0631\u0633",
        ipv6: "IPv6 \u0622\u062F\u0631\u0633",
        cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647",
        cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647",
        base64: "base64-encoded \u0631\u0634\u062A\u0647",
        base64url: "base64url-encoded \u0631\u0634\u062A\u0647",
        json_string: "JSON \u0631\u0634\u062A\u0647",
        e164: "E.164 \u0639\u062F\u062F",
        jwt: "JWT",
        template_literal: "\u0648\u0631\u0648\u062F\u06CC"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${parsedType4(issue2.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;
          case "invalid_value":
            if (issue2.values.length === 1) {
              return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;
            }
            return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;
            }
            return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`;
            }
            return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;
            }
            if (_issue.format === "ends_with") {
              return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;
            }
            if (_issue.format === "includes") {
              return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`;
            }
            if (_issue.format === "regex") {
              return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;
            }
            return `${Nouns[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
          }
          case "not_multiple_of":
            return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`;
          case "unrecognized_keys":
            return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`;
          case "invalid_union":
            return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
          case "invalid_element":
            return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`;
          default:
            return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
        }
      };
    }, "error");
    __name(fa_default, "default");
  }
});

// node_modules/zod/v4/locales/fi.js
function fi_default() {
  return {
    localeError: error11()
  };
}
var error11;
var init_fi = __esm({
  "node_modules/zod/v4/locales/fi.js"() {
    init_esbuild_shims();
    init_util3();
    error11 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "merkki\xE4", subject: "merkkijonon" },
        file: { unit: "tavua", subject: "tiedoston" },
        array: { unit: "alkiota", subject: "listan" },
        set: { unit: "alkiota", subject: "joukon" },
        number: { unit: "", subject: "luvun" },
        bigint: { unit: "", subject: "suuren kokonaisluvun" },
        int: { unit: "", subject: "kokonaisluvun" },
        date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__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");
      const Nouns = {
        regex: "s\xE4\xE4nn\xF6llinen lauseke",
        email: "s\xE4hk\xF6postiosoite",
        url: "URL-osoite",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO-aikaleima",
        date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",
        time: "ISO-aika",
        duration: "ISO-kesto",
        ipv4: "IPv4-osoite",
        ipv6: "IPv6-osoite",
        cidrv4: "IPv4-alue",
        cidrv6: "IPv6-alue",
        base64: "base64-koodattu merkkijono",
        base64url: "base64url-koodattu merkkijono",
        json_string: "JSON-merkkijono",
        e164: "E.164-luku",
        jwt: "JWT",
        template_literal: "templaattimerkkijono"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Virheellinen tyyppi: odotettiin ${issue2.expected}, oli ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`;
            return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();
            }
            return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();
            }
            return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`;
            if (_issue.format === "regex") {
              return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`;
            }
            return `Virheellinen ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`;
          case "unrecognized_keys":
            return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return "Virheellinen avain tietueessa";
          case "invalid_union":
            return "Virheellinen unioni";
          case "invalid_element":
            return "Virheellinen arvo joukossa";
          default:
            return `Virheellinen sy\xF6te`;
        }
      };
    }, "error");
    __name(fi_default, "default");
  }
});

// node_modules/zod/v4/locales/fr.js
function fr_default() {
  return {
    localeError: error12()
  };
}
var error12;
var init_fr = __esm({
  "node_modules/zod/v4/locales/fr.js"() {
    init_esbuild_shims();
    init_util3();
    error12 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "caract\xE8res", verb: "avoir" },
        file: { unit: "octets", verb: "avoir" },
        array: { unit: "\xE9l\xE9ments", verb: "avoir" },
        set: { unit: "\xE9l\xE9ments", verb: "avoir" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "nombre";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "tableau";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "entr\xE9e",
        email: "adresse e-mail",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "date et heure ISO",
        date: "date ISO",
        time: "heure ISO",
        duration: "dur\xE9e ISO",
        ipv4: "adresse IPv4",
        ipv6: "adresse IPv6",
        cidrv4: "plage IPv4",
        cidrv6: "plage IPv6",
        base64: "cha\xEEne encod\xE9e en base64",
        base64url: "cha\xEEne encod\xE9e en base64url",
        json_string: "cha\xEEne JSON",
        e164: "num\xE9ro E.164",
        jwt: "JWT",
        template_literal: "entr\xE9e"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Entr\xE9e invalide : ${issue2.expected} attendu, ${parsedType4(issue2.input)} re\xE7u`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;
            return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`;
            return `Trop grand : ${issue2.origin ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} invalide`;
          }
          case "not_multiple_of":
            return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Cl\xE9 invalide dans ${issue2.origin}`;
          case "invalid_union":
            return "Entr\xE9e invalide";
          case "invalid_element":
            return `Valeur invalide dans ${issue2.origin}`;
          default:
            return `Entr\xE9e invalide`;
        }
      };
    }, "error");
    __name(fr_default, "default");
  }
});

// node_modules/zod/v4/locales/fr-CA.js
function fr_CA_default() {
  return {
    localeError: error13()
  };
}
var error13;
var init_fr_CA = __esm({
  "node_modules/zod/v4/locales/fr-CA.js"() {
    init_esbuild_shims();
    init_util3();
    error13 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "caract\xE8res", verb: "avoir" },
        file: { unit: "octets", verb: "avoir" },
        array: { unit: "\xE9l\xE9ments", verb: "avoir" },
        set: { unit: "\xE9l\xE9ments", verb: "avoir" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__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");
      const Nouns = {
        regex: "entr\xE9e",
        email: "adresse courriel",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "date-heure ISO",
        date: "date ISO",
        time: "heure ISO",
        duration: "dur\xE9e ISO",
        ipv4: "adresse IPv4",
        ipv6: "adresse IPv6",
        cidrv4: "plage IPv4",
        cidrv6: "plage IPv6",
        base64: "cha\xEEne encod\xE9e en base64",
        base64url: "cha\xEEne encod\xE9e en base64url",
        json_string: "cha\xEEne JSON",
        e164: "num\xE9ro E.164",
        jwt: "JWT",
        template_literal: "entr\xE9e"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Entr\xE9e invalide : attendu ${issue2.expected}, re\xE7u ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;
            return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "\u2264" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
            return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? "\u2265" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} invalide`;
          }
          case "not_multiple_of":
            return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Cl\xE9 invalide dans ${issue2.origin}`;
          case "invalid_union":
            return "Entr\xE9e invalide";
          case "invalid_element":
            return `Valeur invalide dans ${issue2.origin}`;
          default:
            return `Entr\xE9e invalide`;
        }
      };
    }, "error");
    __name(fr_CA_default, "default");
  }
});

// node_modules/zod/v4/locales/he.js
function he_default() {
  return {
    localeError: error14()
  };
}
var error14;
var init_he = __esm({
  "node_modules/zod/v4/locales/he.js"() {
    init_esbuild_shims();
    init_util3();
    error14 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" },
        file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" },
        array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" },
        set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__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");
      const Nouns = {
        regex: "\u05E7\u05DC\u05D8",
        email: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",
        url: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",
        emoji: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",
        date: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO",
        time: "\u05D6\u05DE\u05DF ISO",
        duration: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",
        ipv4: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",
        ipv6: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",
        cidrv4: "\u05D8\u05D5\u05D5\u05D7 IPv4",
        cidrv6: "\u05D8\u05D5\u05D5\u05D7 IPv6",
        base64: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",
        base64url: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",
        json_string: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",
        e164: "\u05DE\u05E1\u05E4\u05E8 E.164",
        jwt: "JWT",
        template_literal: "\u05E7\u05DC\u05D8"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${parsedType4(issue2.input)}`;
          // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${stringifyPrimitive(issue2.values[0])}`;
            return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA  ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue2.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
            return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue2.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
          }
          case "not_multiple_of":
            return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`;
          case "invalid_union":
            return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";
          case "invalid_element":
            return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`;
          default:
            return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
        }
      };
    }, "error");
    __name(he_default, "default");
  }
});

// node_modules/zod/v4/locales/hu.js
function hu_default() {
  return {
    localeError: error15()
  };
}
var error15;
var init_hu = __esm({
  "node_modules/zod/v4/locales/hu.js"() {
    init_esbuild_shims();
    init_util3();
    error15 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "karakter", verb: "legyen" },
        file: { unit: "byte", verb: "legyen" },
        array: { unit: "elem", verb: "legyen" },
        set: { unit: "elem", verb: "legyen" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "sz\xE1m";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "t\xF6mb";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "bemenet",
        email: "email c\xEDm",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO id\u0151b\xE9lyeg",
        date: "ISO d\xE1tum",
        time: "ISO id\u0151",
        duration: "ISO id\u0151intervallum",
        ipv4: "IPv4 c\xEDm",
        ipv6: "IPv6 c\xEDm",
        cidrv4: "IPv4 tartom\xE1ny",
        cidrv6: "IPv6 tartom\xE1ny",
        base64: "base64-k\xF3dolt string",
        base64url: "base64url-k\xF3dolt string",
        json_string: "JSON string",
        e164: "E.164 sz\xE1m",
        jwt: "JWT",
        template_literal: "bemenet"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${issue2.expected}, a kapott \xE9rt\xE9k ${parsedType4(issue2.input)}`;
          // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`;
            return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`;
            return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;
            if (_issue.format === "ends_with")
              return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;
            if (_issue.format === "includes")
              return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`;
            if (_issue.format === "regex")
              return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`;
            return `\xC9rv\xE9nytelen ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;
          case "unrecognized_keys":
            return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`;
          case "invalid_union":
            return "\xC9rv\xE9nytelen bemenet";
          case "invalid_element":
            return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`;
          default:
            return `\xC9rv\xE9nytelen bemenet`;
        }
      };
    }, "error");
    __name(hu_default, "default");
  }
});

// node_modules/zod/v4/locales/id.js
function id_default() {
  return {
    localeError: error16()
  };
}
var error16;
var init_id = __esm({
  "node_modules/zod/v4/locales/id.js"() {
    init_esbuild_shims();
    init_util3();
    error16 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "karakter", verb: "memiliki" },
        file: { unit: "byte", verb: "memiliki" },
        array: { unit: "item", verb: "memiliki" },
        set: { unit: "item", verb: "memiliki" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__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");
      const Nouns = {
        regex: "input",
        email: "alamat email",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "tanggal dan waktu format ISO",
        date: "tanggal format ISO",
        time: "jam format ISO",
        duration: "durasi format ISO",
        ipv4: "alamat IPv4",
        ipv6: "alamat IPv6",
        cidrv4: "rentang alamat IPv4",
        cidrv6: "rentang alamat IPv6",
        base64: "string dengan enkode base64",
        base64url: "string dengan enkode base64url",
        json_string: "string JSON",
        e164: "angka E.164",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Input tidak valid: diharapkan ${issue2.expected}, diterima ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;
            return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
            return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `String tidak valid: harus menyertakan "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `String tidak valid: harus sesuai pola ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} tidak valid`;
          }
          case "not_multiple_of":
            return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Kunci tidak valid di ${issue2.origin}`;
          case "invalid_union":
            return "Input tidak valid";
          case "invalid_element":
            return `Nilai tidak valid di ${issue2.origin}`;
          default:
            return `Input tidak valid`;
        }
      };
    }, "error");
    __name(id_default, "default");
  }
});

// node_modules/zod/v4/locales/it.js
function it_default() {
  return {
    localeError: error17()
  };
}
var error17;
var init_it = __esm({
  "node_modules/zod/v4/locales/it.js"() {
    init_esbuild_shims();
    init_util3();
    error17 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "caratteri", verb: "avere" },
        file: { unit: "byte", verb: "avere" },
        array: { unit: "elementi", verb: "avere" },
        set: { unit: "elementi", verb: "avere" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "numero";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "vettore";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "input",
        email: "indirizzo email",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "data e ora ISO",
        date: "data ISO",
        time: "ora ISO",
        duration: "durata ISO",
        ipv4: "indirizzo IPv4",
        ipv6: "indirizzo IPv6",
        cidrv4: "intervallo IPv4",
        cidrv6: "intervallo IPv6",
        base64: "stringa codificata in base64",
        base64url: "URL codificata in base64",
        json_string: "stringa JSON",
        e164: "numero E.164",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Input non valido: atteso ${issue2.expected}, ricevuto ${parsedType4(issue2.input)}`;
          // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;
            return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`;
            return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Stringa non valida: deve includere "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
            return `Invalid ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Chiave non valida in ${issue2.origin}`;
          case "invalid_union":
            return "Input non valido";
          case "invalid_element":
            return `Valore non valido in ${issue2.origin}`;
          default:
            return `Input non valido`;
        }
      };
    }, "error");
    __name(it_default, "default");
  }
});

// node_modules/zod/v4/locales/ja.js
function ja_default() {
  return {
    localeError: error18()
  };
}
var error18;
var init_ja = __esm({
  "node_modules/zod/v4/locales/ja.js"() {
    init_esbuild_shims();
    init_util3();
    error18 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" },
        file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" },
        array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" },
        set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u6570\u5024";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u914D\u5217";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u5165\u529B\u5024",
        email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",
        url: "URL",
        emoji: "\u7D75\u6587\u5B57",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO\u65E5\u6642",
        date: "ISO\u65E5\u4ED8",
        time: "ISO\u6642\u523B",
        duration: "ISO\u671F\u9593",
        ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9",
        ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9",
        cidrv4: "IPv4\u7BC4\u56F2",
        cidrv6: "IPv6\u7BC4\u56F2",
        base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
        base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
        json_string: "JSON\u6587\u5B57\u5217",
        e164: "E.164\u756A\u53F7",
        jwt: "JWT",
        template_literal: "\u5165\u529B\u5024"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u7121\u52B9\u306A\u5165\u529B: ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${parsedType4(issue2.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;
            return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
          case "too_big": {
            const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            if (_issue.format === "ends_with")
              return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            if (_issue.format === "includes")
              return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            if (_issue.format === "regex")
              return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
            return `\u7121\u52B9\u306A${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
          case "unrecognized_keys":
            return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`;
          case "invalid_key":
            return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;
          case "invalid_union":
            return "\u7121\u52B9\u306A\u5165\u529B";
          case "invalid_element":
            return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;
          default:
            return `\u7121\u52B9\u306A\u5165\u529B`;
        }
      };
    }, "error");
    __name(ja_default, "default");
  }
});

// node_modules/zod/v4/locales/kh.js
function kh_default() {
  return {
    localeError: error19()
  };
}
var error19;
var init_kh = __esm({
  "node_modules/zod/v4/locales/kh.js"() {
    init_esbuild_shims();
    init_util3();
    error19 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
        file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
        array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
        set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)" : "\u179B\u17C1\u1781";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u17A2\u17B6\u179A\u17C1 (Array)";
            }
            if (data === null) {
              return "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",
        email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",
        url: "URL",
        emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",
        date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",
        time: "\u1798\u17C9\u17C4\u1784 ISO",
        duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",
        ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
        ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
        cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
        cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
        base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",
        base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",
        json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",
        e164: "\u179B\u17C1\u1781 E.164",
        jwt: "JWT",
        template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`;
            return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`;
            return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`;
            return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
          case "invalid_union":
            return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
          case "invalid_element":
            return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
          default:
            return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
        }
      };
    }, "error");
    __name(kh_default, "default");
  }
});

// node_modules/zod/v4/locales/ko.js
function ko_default() {
  return {
    localeError: error20()
  };
}
var error20;
var init_ko = __esm({
  "node_modules/zod/v4/locales/ko.js"() {
    init_esbuild_shims();
    init_util3();
    error20 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\uBB38\uC790", verb: "to have" },
        file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" },
        array: { unit: "\uAC1C", verb: "to have" },
        set: { unit: "\uAC1C", verb: "to have" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__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");
      const Nouns = {
        regex: "\uC785\uB825",
        email: "\uC774\uBA54\uC77C \uC8FC\uC18C",
        url: "URL",
        emoji: "\uC774\uBAA8\uC9C0",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04",
        date: "ISO \uB0A0\uC9DC",
        time: "ISO \uC2DC\uAC04",
        duration: "ISO \uAE30\uAC04",
        ipv4: "IPv4 \uC8FC\uC18C",
        ipv6: "IPv6 \uC8FC\uC18C",
        cidrv4: "IPv4 \uBC94\uC704",
        cidrv6: "IPv6 \uBC94\uC704",
        base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
        base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
        json_string: "JSON \uBB38\uC790\uC5F4",
        e164: "E.164 \uBC88\uD638",
        jwt: "JWT",
        template_literal: "\uC785\uB825"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${parsedType4(issue2.input)}\uC785\uB2C8\uB2E4`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;
            return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
          case "too_big": {
            const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC";
            const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
            const sizing = getSizing(issue2.origin);
            const unit = sizing?.unit ?? "\uC694\uC18C";
            if (sizing)
              return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`;
            return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC";
            const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
            const sizing = getSizing(issue2.origin);
            const unit = sizing?.unit ?? "\uC694\uC18C";
            if (sizing) {
              return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`;
            }
            return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;
            }
            if (_issue.format === "ends_with")
              return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;
            if (_issue.format === "includes")
              return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;
            if (_issue.format === "regex")
              return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;
            return `\uC798\uBABB\uB41C ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
          case "unrecognized_keys":
            return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`;
          case "invalid_union":
            return `\uC798\uBABB\uB41C \uC785\uB825`;
          case "invalid_element":
            return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`;
          default:
            return `\uC798\uBABB\uB41C \uC785\uB825`;
        }
      };
    }, "error");
    __name(ko_default, "default");
  }
});

// node_modules/zod/v4/locales/mk.js
function mk_default() {
  return {
    localeError: error21()
  };
}
var error21;
var init_mk = __esm({
  "node_modules/zod/v4/locales/mk.js"() {
    init_esbuild_shims();
    init_util3();
    error21 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
        file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
        array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
        set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0431\u0440\u043E\u0458";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u043D\u0438\u0437\u0430";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u0432\u043D\u0435\u0441",
        email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",
        url: "URL",
        emoji: "\u0435\u043C\u043E\u045F\u0438",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",
        date: "ISO \u0434\u0430\u0442\u0443\u043C",
        time: "ISO \u0432\u0440\u0435\u043C\u0435",
        duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",
        ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",
        ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",
        cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433",
        cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433",
        base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
        base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
        json_string: "JSON \u043D\u0438\u0437\u0430",
        e164: "E.164 \u0431\u0440\u043E\u0458",
        jwt: "JWT",
        template_literal: "\u0432\u043D\u0435\u0441"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${parsedType4(issue2.input)}`;
          // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
            return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;
            return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`;
            return `Invalid ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`;
          case "unrecognized_keys":
            return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`;
          case "invalid_union":
            return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";
          case "invalid_element":
            return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`;
          default:
            return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;
        }
      };
    }, "error");
    __name(mk_default, "default");
  }
});

// node_modules/zod/v4/locales/ms.js
function ms_default() {
  return {
    localeError: error22()
  };
}
var error22;
var init_ms = __esm({
  "node_modules/zod/v4/locales/ms.js"() {
    init_esbuild_shims();
    init_util3();
    error22 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "aksara", verb: "mempunyai" },
        file: { unit: "bait", verb: "mempunyai" },
        array: { unit: "elemen", verb: "mempunyai" },
        set: { unit: "elemen", verb: "mempunyai" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "nombor";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "input",
        email: "alamat e-mel",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "tarikh masa ISO",
        date: "tarikh ISO",
        time: "masa ISO",
        duration: "tempoh ISO",
        ipv4: "alamat IPv4",
        ipv6: "alamat IPv6",
        cidrv4: "julat IPv4",
        cidrv6: "julat IPv6",
        base64: "string dikodkan base64",
        base64url: "string dikodkan base64url",
        json_string: "string JSON",
        e164: "nombor E.164",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Input tidak sah: dijangka ${issue2.expected}, diterima ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;
            return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
            return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `String tidak sah: mesti mengandungi "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} tidak sah`;
          }
          case "not_multiple_of":
            return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Kunci tidak sah dalam ${issue2.origin}`;
          case "invalid_union":
            return "Input tidak sah";
          case "invalid_element":
            return `Nilai tidak sah dalam ${issue2.origin}`;
          default:
            return `Input tidak sah`;
        }
      };
    }, "error");
    __name(ms_default, "default");
  }
});

// node_modules/zod/v4/locales/nl.js
function nl_default() {
  return {
    localeError: error23()
  };
}
var error23;
var init_nl = __esm({
  "node_modules/zod/v4/locales/nl.js"() {
    init_esbuild_shims();
    init_util3();
    error23 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "tekens" },
        file: { unit: "bytes" },
        array: { unit: "elementen" },
        set: { unit: "elementen" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "getal";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "invoer",
        email: "emailadres",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO datum en tijd",
        date: "ISO datum",
        time: "ISO tijd",
        duration: "ISO duur",
        ipv4: "IPv4-adres",
        ipv6: "IPv6-adres",
        cidrv4: "IPv4-bereik",
        cidrv6: "IPv6-bereik",
        base64: "base64-gecodeerde tekst",
        base64url: "base64 URL-gecodeerde tekst",
        json_string: "JSON string",
        e164: "E.164-nummer",
        jwt: "JWT",
        template_literal: "invoer"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Ongeldige invoer: verwacht ${issue2.expected}, ontving ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;
            return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Te lang: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} bevat`;
            return `Te lang: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} bevat`;
            }
            return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;
            }
            if (_issue.format === "ends_with")
              return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;
            if (_issue.format === "includes")
              return `Ongeldige tekst: moet "${_issue.includes}" bevatten`;
            if (_issue.format === "regex")
              return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;
            return `Ongeldig: ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;
          case "unrecognized_keys":
            return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Ongeldige key in ${issue2.origin}`;
          case "invalid_union":
            return "Ongeldige invoer";
          case "invalid_element":
            return `Ongeldige waarde in ${issue2.origin}`;
          default:
            return `Ongeldige invoer`;
        }
      };
    }, "error");
    __name(nl_default, "default");
  }
});

// node_modules/zod/v4/locales/no.js
function no_default() {
  return {
    localeError: error24()
  };
}
var error24;
var init_no = __esm({
  "node_modules/zod/v4/locales/no.js"() {
    init_esbuild_shims();
    init_util3();
    error24 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "tegn", verb: "\xE5 ha" },
        file: { unit: "bytes", verb: "\xE5 ha" },
        array: { unit: "elementer", verb: "\xE5 inneholde" },
        set: { unit: "elementer", verb: "\xE5 inneholde" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "tall";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "liste";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "input",
        email: "e-postadresse",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO dato- og klokkeslett",
        date: "ISO-dato",
        time: "ISO-klokkeslett",
        duration: "ISO-varighet",
        ipv4: "IPv4-omr\xE5de",
        ipv6: "IPv6-omr\xE5de",
        cidrv4: "IPv4-spekter",
        cidrv6: "IPv6-spekter",
        base64: "base64-enkodet streng",
        base64url: "base64url-enkodet streng",
        json_string: "JSON-streng",
        e164: "E.164-nummer",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Ugyldig input: forventet ${issue2.expected}, fikk ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;
            return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`;
            return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`;
            return `Ugyldig ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`;
          case "unrecognized_keys":
            return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Ugyldig n\xF8kkel i ${issue2.origin}`;
          case "invalid_union":
            return "Ugyldig input";
          case "invalid_element":
            return `Ugyldig verdi i ${issue2.origin}`;
          default:
            return `Ugyldig input`;
        }
      };
    }, "error");
    __name(no_default, "default");
  }
});

// node_modules/zod/v4/locales/ota.js
function ota_default() {
  return {
    localeError: error25()
  };
}
var error25;
var init_ota = __esm({
  "node_modules/zod/v4/locales/ota.js"() {
    init_esbuild_shims();
    init_util3();
    error25 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "harf", verb: "olmal\u0131d\u0131r" },
        file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
        array: { unit: "unsur", verb: "olmal\u0131d\u0131r" },
        set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "numara";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "saf";
            }
            if (data === null) {
              return "gayb";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "giren",
        email: "epostag\xE2h",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO heng\xE2m\u0131",
        date: "ISO tarihi",
        time: "ISO zaman\u0131",
        duration: "ISO m\xFCddeti",
        ipv4: "IPv4 ni\u015F\xE2n\u0131",
        ipv6: "IPv6 ni\u015F\xE2n\u0131",
        cidrv4: "IPv4 menzili",
        cidrv6: "IPv6 menzili",
        base64: "base64-\u015Fifreli metin",
        base64url: "base64url-\u015Fifreli metin",
        json_string: "JSON metin",
        e164: "E.164 say\u0131s\u0131",
        jwt: "JWT",
        template_literal: "giren"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `F\xE2sit giren: umulan ${issue2.expected}, al\u0131nan ${parsedType4(issue2.input)}`;
          // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;
            return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`;
            return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`;
            }
            return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`;
            if (_issue.format === "ends_with")
              return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`;
            if (_issue.format === "includes")
              return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`;
            if (_issue.format === "regex")
              return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`;
            return `F\xE2sit ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`;
          case "unrecognized_keys":
            return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`;
          case "invalid_union":
            return "Giren tan\u0131namad\u0131.";
          case "invalid_element":
            return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;
          default:
            return `K\u0131ymet tan\u0131namad\u0131.`;
        }
      };
    }, "error");
    __name(ota_default, "default");
  }
});

// node_modules/zod/v4/locales/ps.js
function ps_default() {
  return {
    localeError: error26()
  };
}
var error26;
var init_ps = __esm({
  "node_modules/zod/v4/locales/ps.js"() {
    init_esbuild_shims();
    init_util3();
    error26 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
        file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" },
        array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
        set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u0627\u0631\u06D0";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u0648\u0631\u0648\u062F\u064A",
        email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",
        url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644",
        emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",
        date: "\u0646\u06D0\u067C\u0647",
        time: "\u0648\u062E\u062A",
        duration: "\u0645\u0648\u062F\u0647",
        ipv4: "\u062F IPv4 \u067E\u062A\u0647",
        ipv6: "\u062F IPv6 \u067E\u062A\u0647",
        cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647",
        cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647",
        base64: "base64-encoded \u0645\u062A\u0646",
        base64url: "base64url-encoded \u0645\u062A\u0646",
        json_string: "JSON \u0645\u062A\u0646",
        e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",
        jwt: "JWT",
        template_literal: "\u0648\u0631\u0648\u062F\u064A"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${parsedType4(issue2.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;
          case "invalid_value":
            if (issue2.values.length === 1) {
              return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`;
            }
            return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;
            }
            return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`;
            }
            return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;
            }
            if (_issue.format === "ends_with") {
              return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;
            }
            if (_issue.format === "includes") {
              return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`;
            }
            if (_issue.format === "regex") {
              return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;
            }
            return `${Nouns[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;
          }
          case "not_multiple_of":
            return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;
          case "unrecognized_keys":
            return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
          case "invalid_union":
            return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
          case "invalid_element":
            return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
          default:
            return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
        }
      };
    }, "error");
    __name(ps_default, "default");
  }
});

// node_modules/zod/v4/locales/pl.js
function pl_default() {
  return {
    localeError: error27()
  };
}
var error27;
var init_pl = __esm({
  "node_modules/zod/v4/locales/pl.js"() {
    init_esbuild_shims();
    init_util3();
    error27 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "znak\xF3w", verb: "mie\u0107" },
        file: { unit: "bajt\xF3w", verb: "mie\u0107" },
        array: { unit: "element\xF3w", verb: "mie\u0107" },
        set: { unit: "element\xF3w", verb: "mie\u0107" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "liczba";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "tablica";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "wyra\u017Cenie",
        email: "adres email",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "data i godzina w formacie ISO",
        date: "data w formacie ISO",
        time: "godzina w formacie ISO",
        duration: "czas trwania ISO",
        ipv4: "adres IPv4",
        ipv6: "adres IPv6",
        cidrv4: "zakres IPv4",
        cidrv6: "zakres IPv6",
        base64: "ci\u0105g znak\xF3w zakodowany w formacie base64",
        base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url",
        json_string: "ci\u0105g znak\xF3w w formacie JSON",
        e164: "liczba E.164",
        jwt: "JWT",
        template_literal: "wej\u015Bcie"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${issue2.expected}, otrzymano ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;
            return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`;
            }
            return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`;
            }
            return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`;
            return `Nieprawid\u0142ow(y/a/e) ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Nieprawid\u0142owy klucz w ${issue2.origin}`;
          case "invalid_union":
            return "Nieprawid\u0142owe dane wej\u015Bciowe";
          case "invalid_element":
            return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`;
          default:
            return `Nieprawid\u0142owe dane wej\u015Bciowe`;
        }
      };
    }, "error");
    __name(pl_default, "default");
  }
});

// node_modules/zod/v4/locales/pt.js
function pt_default() {
  return {
    localeError: error28()
  };
}
var error28;
var init_pt = __esm({
  "node_modules/zod/v4/locales/pt.js"() {
    init_esbuild_shims();
    init_util3();
    error28 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "caracteres", verb: "ter" },
        file: { unit: "bytes", verb: "ter" },
        array: { unit: "itens", verb: "ter" },
        set: { unit: "itens", verb: "ter" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "n\xFAmero";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "array";
            }
            if (data === null) {
              return "nulo";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "padr\xE3o",
        email: "endere\xE7o de e-mail",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "data e hora ISO",
        date: "data ISO",
        time: "hora ISO",
        duration: "dura\xE7\xE3o ISO",
        ipv4: "endere\xE7o IPv4",
        ipv6: "endere\xE7o IPv6",
        cidrv4: "faixa de IPv4",
        cidrv6: "faixa de IPv6",
        base64: "texto codificado em base64",
        base64url: "URL codificada em base64",
        json_string: "texto JSON",
        e164: "n\xFAmero E.164",
        jwt: "JWT",
        template_literal: "entrada"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Tipo inv\xE1lido: esperado ${issue2.expected}, recebido ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`;
            return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
            return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} inv\xE1lido`;
          }
          case "not_multiple_of":
            return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Chave inv\xE1lida em ${issue2.origin}`;
          case "invalid_union":
            return "Entrada inv\xE1lida";
          case "invalid_element":
            return `Valor inv\xE1lido em ${issue2.origin}`;
          default:
            return `Campo inv\xE1lido`;
        }
      };
    }, "error");
    __name(pt_default, "default");
  }
});

// node_modules/zod/v4/locales/ru.js
function getRussianPlural(count, one, few, many2) {
  const absCount = Math.abs(count);
  const lastDigit = absCount % 10;
  const lastTwoDigits = absCount % 100;
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
    return many2;
  }
  if (lastDigit === 1) {
    return one;
  }
  if (lastDigit >= 2 && lastDigit <= 4) {
    return few;
  }
  return many2;
}
function ru_default() {
  return {
    localeError: error29()
  };
}
var error29;
var init_ru = __esm({
  "node_modules/zod/v4/locales/ru.js"() {
    init_esbuild_shims();
    init_util3();
    __name(getRussianPlural, "getRussianPlural");
    error29 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: {
          unit: {
            one: "\u0441\u0438\u043C\u0432\u043E\u043B",
            few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430",
            many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"
          },
          verb: "\u0438\u043C\u0435\u0442\u044C"
        },
        file: {
          unit: {
            one: "\u0431\u0430\u0439\u0442",
            few: "\u0431\u0430\u0439\u0442\u0430",
            many: "\u0431\u0430\u0439\u0442"
          },
          verb: "\u0438\u043C\u0435\u0442\u044C"
        },
        array: {
          unit: {
            one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
            few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
            many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
          },
          verb: "\u0438\u043C\u0435\u0442\u044C"
        },
        set: {
          unit: {
            one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
            few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
            many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
          },
          verb: "\u0438\u043C\u0435\u0442\u044C"
        }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u043C\u0430\u0441\u0441\u0438\u0432";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u0432\u0432\u043E\u0434",
        email: "email \u0430\u0434\u0440\u0435\u0441",
        url: "URL",
        emoji: "\u044D\u043C\u043E\u0434\u0437\u0438",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",
        date: "ISO \u0434\u0430\u0442\u0430",
        time: "ISO \u0432\u0440\u0435\u043C\u044F",
        duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",
        ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441",
        ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441",
        cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
        cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
        base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",
        base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",
        json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430",
        e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
        jwt: "JWT",
        template_literal: "\u0432\u0432\u043E\u0434"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`;
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              const maxValue = Number(issue2.maximum);
              const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
              return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`;
            }
            return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              const minValue = Number(issue2.minimum);
              const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
              return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`;
            }
            return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;
          case "invalid_union":
            return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";
          case "invalid_element":
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`;
          default:
            return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`;
        }
      };
    }, "error");
    __name(ru_default, "default");
  }
});

// node_modules/zod/v4/locales/sl.js
function sl_default() {
  return {
    localeError: error30()
  };
}
var error30;
var init_sl = __esm({
  "node_modules/zod/v4/locales/sl.js"() {
    init_esbuild_shims();
    init_util3();
    error30 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "znakov", verb: "imeti" },
        file: { unit: "bajtov", verb: "imeti" },
        array: { unit: "elementov", verb: "imeti" },
        set: { unit: "elementov", verb: "imeti" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0161tevilo";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "tabela";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "vnos",
        email: "e-po\u0161tni naslov",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO datum in \u010Das",
        date: "ISO datum",
        time: "ISO \u010Das",
        duration: "ISO trajanje",
        ipv4: "IPv4 naslov",
        ipv6: "IPv6 naslov",
        cidrv4: "obseg IPv4",
        cidrv6: "obseg IPv6",
        base64: "base64 kodiran niz",
        base64url: "base64url kodiran niz",
        json_string: "JSON niz",
        e164: "E.164 \u0161tevilka",
        jwt: "JWT",
        template_literal: "vnos"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Neveljaven vnos: pri\u010Dakovano ${issue2.expected}, prejeto ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`;
            return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`;
            return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Neveljaven niz: mora vsebovati "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;
            return `Neveljaven ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Neveljaven klju\u010D v ${issue2.origin}`;
          case "invalid_union":
            return "Neveljaven vnos";
          case "invalid_element":
            return `Neveljavna vrednost v ${issue2.origin}`;
          default:
            return "Neveljaven vnos";
        }
      };
    }, "error");
    __name(sl_default, "default");
  }
});

// node_modules/zod/v4/locales/sv.js
function sv_default() {
  return {
    localeError: error31()
  };
}
var error31;
var init_sv = __esm({
  "node_modules/zod/v4/locales/sv.js"() {
    init_esbuild_shims();
    init_util3();
    error31 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "tecken", verb: "att ha" },
        file: { unit: "bytes", verb: "att ha" },
        array: { unit: "objekt", verb: "att inneh\xE5lla" },
        set: { unit: "objekt", verb: "att inneh\xE5lla" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "antal";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "lista";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "regulj\xE4rt uttryck",
        email: "e-postadress",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO-datum och tid",
        date: "ISO-datum",
        time: "ISO-tid",
        duration: "ISO-varaktighet",
        ipv4: "IPv4-intervall",
        ipv6: "IPv6-intervall",
        cidrv4: "IPv4-spektrum",
        cidrv6: "IPv6-spektrum",
        base64: "base64-kodad str\xE4ng",
        base64url: "base64url-kodad str\xE4ng",
        json_string: "JSON-str\xE4ng",
        e164: "E.164-nummer",
        jwt: "JWT",
        template_literal: "mall-literal"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Ogiltig inmatning: f\xF6rv\xE4ntat ${issue2.expected}, fick ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`;
            return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
            }
            return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`;
            return `Ogiltig(t) ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`;
          case "unrecognized_keys":
            return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`;
          case "invalid_union":
            return "Ogiltig input";
          case "invalid_element":
            return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`;
          default:
            return `Ogiltig input`;
        }
      };
    }, "error");
    __name(sv_default, "default");
  }
});

// node_modules/zod/v4/locales/ta.js
function ta_default() {
  return {
    localeError: error32()
  };
}
var error32;
var init_ta = __esm({
  "node_modules/zod/v4/locales/ta.js"() {
    init_esbuild_shims();
    init_util3();
    error32 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
        file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
        array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
        set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1" : "\u0B8E\u0BA3\u0BCD";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u0B85\u0BA3\u0BBF";
            }
            if (data === null) {
              return "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",
        email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
        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 \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
        date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF",
        time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
        duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",
        ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
        ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
        cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
        cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
        base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
        base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
        json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD",
        e164: "E.164 \u0B8E\u0BA3\u0BCD",
        jwt: "JWT",
        template_literal: "input"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`;
            return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            }
            return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            }
            return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            if (_issue.format === "ends_with")
              return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            if (_issue.format === "includes")
              return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            if (_issue.format === "regex")
              return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
            return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
          case "unrecognized_keys":
            return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;
          case "invalid_union":
            return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";
          case "invalid_element":
            return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;
          default:
            return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`;
        }
      };
    }, "error");
    __name(ta_default, "default");
  }
});

// node_modules/zod/v4/locales/th.js
function th_default() {
  return {
    localeError: error33()
  };
}
var error33;
var init_th = __esm({
  "node_modules/zod/v4/locales/th.js"() {
    init_esbuild_shims();
    init_util3();
    error33 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
        file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
        array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
        set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)" : "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";
            }
            if (data === null) {
              return "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",
        email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",
        url: "URL",
        emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
        date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",
        time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
        duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
        ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",
        ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",
        cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",
        cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",
        base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",
        base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",
        json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",
        e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",
        jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",
        template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`;
            return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
            return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`;
            }
            if (_issue.format === "ends_with")
              return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;
            if (_issue.format === "regex")
              return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`;
            return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;
          case "unrecognized_keys":
            return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
          case "invalid_union":
            return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";
          case "invalid_element":
            return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
          default:
            return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`;
        }
      };
    }, "error");
    __name(th_default, "default");
  }
});

// node_modules/zod/v4/locales/tr.js
function tr_default() {
  return {
    localeError: error34()
  };
}
var parsedType3, error34;
var init_tr = __esm({
  "node_modules/zod/v4/locales/tr.js"() {
    init_esbuild_shims();
    init_util3();
    parsedType3 = /* @__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");
    error34 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "karakter", verb: "olmal\u0131" },
        file: { unit: "bayt", verb: "olmal\u0131" },
        array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" },
        set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const Nouns = {
        regex: "girdi",
        email: "e-posta adresi",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO tarih ve saat",
        date: "ISO tarih",
        time: "ISO saat",
        duration: "ISO s\xFCre",
        ipv4: "IPv4 adresi",
        ipv6: "IPv6 adresi",
        cidrv4: "IPv4 aral\u0131\u011F\u0131",
        cidrv6: "IPv6 aral\u0131\u011F\u0131",
        base64: "base64 ile \u015Fifrelenmi\u015F metin",
        base64url: "base64url ile \u015Fifrelenmi\u015F metin",
        json_string: "JSON dizesi",
        e164: "E.164 say\u0131s\u0131",
        jwt: "JWT",
        template_literal: "\u015Eablon dizesi"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `Ge\xE7ersiz de\u011Fer: beklenen ${issue2.expected}, al\u0131nan ${parsedType3(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`;
            return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`;
            return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`;
            if (_issue.format === "ends_with")
              return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`;
            if (_issue.format === "includes")
              return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`;
            if (_issue.format === "regex")
              return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`;
            return `Ge\xE7ersiz ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`;
          case "unrecognized_keys":
            return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`;
          case "invalid_union":
            return "Ge\xE7ersiz de\u011Fer";
          case "invalid_element":
            return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;
          default:
            return `Ge\xE7ersiz de\u011Fer`;
        }
      };
    }, "error");
    __name(tr_default, "default");
  }
});

// node_modules/zod/v4/locales/ua.js
function ua_default() {
  return {
    localeError: error35()
  };
}
var error35;
var init_ua = __esm({
  "node_modules/zod/v4/locales/ua.js"() {
    init_esbuild_shims();
    init_util3();
    error35 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
        file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
        array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
        set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u043C\u0430\u0441\u0438\u0432";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",
        email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",
        url: "URL",
        emoji: "\u0435\u043C\u043E\u0434\u0437\u0456",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",
        date: "\u0434\u0430\u0442\u0430 ISO",
        time: "\u0447\u0430\u0441 ISO",
        duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",
        ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",
        ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",
        cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",
        cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",
        base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",
        base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",
        json_string: "\u0440\u044F\u0434\u043E\u043A JSON",
        e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
        jwt: "JWT",
        template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${parsedType4(issue2.input)}`;
          // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;
            return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`;
          case "unrecognized_keys":
            return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
          case "invalid_union":
            return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";
          case "invalid_element":
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`;
          default:
            return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`;
        }
      };
    }, "error");
    __name(ua_default, "default");
  }
});

// node_modules/zod/v4/locales/ur.js
function ur_default() {
  return {
    localeError: error36()
  };
}
var error36;
var init_ur = __esm({
  "node_modules/zod/v4/locales/ur.js"() {
    init_esbuild_shims();
    init_util3();
    error36 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" },
        file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" },
        array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" },
        set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "\u0646\u0645\u0628\u0631";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u0622\u0631\u06D2";
            }
            if (data === null) {
              return "\u0646\u0644";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u0627\u0646 \u067E\u0679",
        email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",
        url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",
        emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
        uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
        uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",
        uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",
        nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",
        guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
        cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
        cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",
        ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",
        xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",
        ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
        datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",
        date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",
        time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",
        duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",
        ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",
        ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",
        cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",
        cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",
        base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
        base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
        json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",
        e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631",
        jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",
        template_literal: "\u0627\u0646 \u067E\u0679"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${parsedType4(issue2.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
            return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
            return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
            }
            return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
            }
            if (_issue.format === "ends_with")
              return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
            if (_issue.format === "includes")
              return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
            if (_issue.format === "regex")
              return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
            return `\u063A\u0644\u0637 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
          case "unrecognized_keys":
            return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
          case "invalid_key":
            return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;
          case "invalid_union":
            return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
          case "invalid_element":
            return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;
          default:
            return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`;
        }
      };
    }, "error");
    __name(ur_default, "default");
  }
});

// node_modules/zod/v4/locales/vi.js
function vi_default() {
  return {
    localeError: error37()
  };
}
var error37;
var init_vi = __esm({
  "node_modules/zod/v4/locales/vi.js"() {
    init_esbuild_shims();
    init_util3();
    error37 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" },
        file: { unit: "byte", verb: "c\xF3" },
        array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" },
        set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "NaN" : "s\u1ED1";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "m\u1EA3ng";
            }
            if (data === null) {
              return "null";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u0111\u1EA7u v\xE0o",
        email: "\u0111\u1ECBa ch\u1EC9 email",
        url: "URL",
        emoji: "emoji",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ng\xE0y gi\u1EDD ISO",
        date: "ng\xE0y ISO",
        time: "gi\u1EDD ISO",
        duration: "kho\u1EA3ng th\u1EDDi gian ISO",
        ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4",
        ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6",
        cidrv4: "d\u1EA3i IPv4",
        cidrv6: "d\u1EA3i IPv6",
        base64: "chu\u1ED7i m\xE3 h\xF3a base64",
        base64url: "chu\u1ED7i m\xE3 h\xF3a base64url",
        json_string: "chu\u1ED7i JSON",
        e164: "s\u1ED1 E.164",
        jwt: "JWT",
        template_literal: "\u0111\u1EA7u v\xE0o"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`;
            return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`;
            return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`;
            if (_issue.format === "ends_with")
              return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`;
            if (_issue.format === "includes")
              return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`;
            return `${Nouns[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`;
          }
          case "not_multiple_of":
            return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`;
          case "unrecognized_keys":
            return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
          case "invalid_union":
            return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";
          case "invalid_element":
            return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
          default:
            return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`;
        }
      };
    }, "error");
    __name(vi_default, "default");
  }
});

// node_modules/zod/v4/locales/zh-CN.js
function zh_CN_default() {
  return {
    localeError: error38()
  };
}
var error38;
var init_zh_CN = __esm({
  "node_modules/zod/v4/locales/zh-CN.js"() {
    init_esbuild_shims();
    init_util3();
    error38 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" },
        file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" },
        array: { unit: "\u9879", verb: "\u5305\u542B" },
        set: { unit: "\u9879", verb: "\u5305\u542B" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__PURE__ */ __name((data) => {
        const t5 = typeof data;
        switch (t5) {
          case "number": {
            return Number.isNaN(data) ? "\u975E\u6570\u5B57(NaN)" : "\u6570\u5B57";
          }
          case "object": {
            if (Array.isArray(data)) {
              return "\u6570\u7EC4";
            }
            if (data === null) {
              return "\u7A7A\u503C(null)";
            }
            if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
              return data.constructor.name;
            }
          }
        }
        return t5;
      }, "parsedType");
      const Nouns = {
        regex: "\u8F93\u5165",
        email: "\u7535\u5B50\u90AE\u4EF6",
        url: "URL",
        emoji: "\u8868\u60C5\u7B26\u53F7",
        uuid: "UUID",
        uuidv4: "UUIDv4",
        uuidv6: "UUIDv6",
        nanoid: "nanoid",
        guid: "GUID",
        cuid: "cuid",
        cuid2: "cuid2",
        ulid: "ULID",
        xid: "XID",
        ksuid: "KSUID",
        datetime: "ISO\u65E5\u671F\u65F6\u95F4",
        date: "ISO\u65E5\u671F",
        time: "ISO\u65F6\u95F4",
        duration: "ISO\u65F6\u957F",
        ipv4: "IPv4\u5730\u5740",
        ipv6: "IPv6\u5730\u5740",
        cidrv4: "IPv4\u7F51\u6BB5",
        cidrv6: "IPv6\u7F51\u6BB5",
        base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32",
        base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32",
        json_string: "JSON\u5B57\u7B26\u4E32",
        e164: "E.164\u53F7\u7801",
        jwt: "JWT",
        template_literal: "\u8F93\u5165"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`;
            return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`;
            return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with")
              return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`;
            if (_issue.format === "ends_with")
              return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`;
            if (_issue.format === "includes")
              return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`;
            return `\u65E0\u6548${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`;
          case "unrecognized_keys":
            return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`;
          case "invalid_key":
            return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;
          case "invalid_union":
            return "\u65E0\u6548\u8F93\u5165";
          case "invalid_element":
            return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;
          default:
            return `\u65E0\u6548\u8F93\u5165`;
        }
      };
    }, "error");
    __name(zh_CN_default, "default");
  }
});

// node_modules/zod/v4/locales/zh-TW.js
function zh_TW_default() {
  return {
    localeError: error39()
  };
}
var error39;
var init_zh_TW = __esm({
  "node_modules/zod/v4/locales/zh-TW.js"() {
    init_esbuild_shims();
    init_util3();
    error39 = /* @__PURE__ */ __name(() => {
      const Sizable = {
        string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" },
        file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" },
        array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" },
        set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }
      };
      function getSizing(origin2) {
        return Sizable[origin2] ?? null;
      }
      __name(getSizing, "getSizing");
      const parsedType4 = /* @__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");
      const Nouns = {
        regex: "\u8F38\u5165",
        email: "\u90F5\u4EF6\u5730\u5740",
        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 \u65E5\u671F\u6642\u9593",
        date: "ISO \u65E5\u671F",
        time: "ISO \u6642\u9593",
        duration: "ISO \u671F\u9593",
        ipv4: "IPv4 \u4F4D\u5740",
        ipv6: "IPv6 \u4F4D\u5740",
        cidrv4: "IPv4 \u7BC4\u570D",
        cidrv6: "IPv6 \u7BC4\u570D",
        base64: "base64 \u7DE8\u78BC\u5B57\u4E32",
        base64url: "base64url \u7DE8\u78BC\u5B57\u4E32",
        json_string: "JSON \u5B57\u4E32",
        e164: "E.164 \u6578\u503C",
        jwt: "JWT",
        template_literal: "\u8F38\u5165"
      };
      return (issue2) => {
        switch (issue2.code) {
          case "invalid_type":
            return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${parsedType4(issue2.input)}`;
          case "invalid_value":
            if (issue2.values.length === 1)
              return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`;
            return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
          case "too_big": {
            const adj = issue2.inclusive ? "<=" : "<";
            const sizing = getSizing(issue2.origin);
            if (sizing)
              return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`;
            return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`;
          }
          case "too_small": {
            const adj = issue2.inclusive ? ">=" : ">";
            const sizing = getSizing(issue2.origin);
            if (sizing) {
              return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
            }
            return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`;
          }
          case "invalid_format": {
            const _issue = issue2;
            if (_issue.format === "starts_with") {
              return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`;
            }
            if (_issue.format === "ends_with")
              return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`;
            if (_issue.format === "includes")
              return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`;
            if (_issue.format === "regex")
              return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`;
            return `\u7121\u6548\u7684 ${Nouns[_issue.format] ?? issue2.format}`;
          }
          case "not_multiple_of":
            return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`;
          case "unrecognized_keys":
            return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`;
          case "invalid_key":
            return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;
          case "invalid_union":
            return "\u7121\u6548\u7684\u8F38\u5165\u503C";
          case "invalid_element":
            return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;
          default:
            return `\u7121\u6548\u7684\u8F38\u5165\u503C`;
        }
      };
    }, "error");
    __name(zh_TW_default, "default");
  }
});

// node_modules/zod/v4/locales/index.js
var locales_exports = {};
__export(locales_exports, {
  ar: () => ar_default,
  az: () => az_default,
  be: () => be_default,
  ca: () => ca_default,
  cs: () => cs_default,
  de: () => de_default,
  en: () => en_default2,
  eo: () => eo_default,
  es: () => es_default,
  fa: () => fa_default,
  fi: () => fi_default,
  fr: () => fr_default,
  frCA: () => fr_CA_default,
  he: () => he_default,
  hu: () => hu_default,
  id: () => id_default,
  it: () => it_default,
  ja: () => ja_default,
  kh: () => kh_default,
  ko: () => ko_default,
  mk: () => mk_default,
  ms: () => ms_default,
  nl: () => nl_default,
  no: () => no_default,
  ota: () => ota_default,
  pl: () => pl_default,
  ps: () => ps_default,
  pt: () => pt_default,
  ru: () => ru_default,
  sl: () => sl_default,
  sv: () => sv_default,
  ta: () => ta_default,
  th: () => th_default,
  tr: () => tr_default,
  ua: () => ua_default,
  ur: () => ur_default,
  vi: () => vi_default,
  zhCN: () => zh_CN_default,
  zhTW: () => zh_TW_default
});
var init_locales = __esm({
  "node_modules/zod/v4/locales/index.js"() {
    init_esbuild_shims();
    init_ar();
    init_az();
    init_be();
    init_ca();
    init_cs();
    init_de();
    init_en2();
    init_eo();
    init_es();
    init_fa();
    init_fi();
    init_fr();
    init_fr_CA();
    init_he();
    init_hu();
    init_id();
    init_it();
    init_ja();
    init_kh();
    init_ko();
    init_mk();
    init_ms();
    init_nl();
    init_no();
    init_ota();
    init_ps();
    init_pl();
    init_pt();
    init_ru();
    init_sl();
    init_sv();
    init_ta();
    init_th();
    init_tr();
    init_ua();
    init_ur();
    init_vi();
    init_zh_CN();
    init_zh_TW();
  }
});

// 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 _float32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float32",
    ...normalizeParams(params)
  });
}
function _float64(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float64",
    ...normalizeParams(params)
  });
}
function _int32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "int32",
    ...normalizeParams(params)
  });
}
function _uint32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "uint32",
    ...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 _bigint(Class2, params) {
  return new Class2({
    type: "bigint",
    ...normalizeParams(params)
  });
}
function _coercedBigint(Class2, params) {
  return new Class2({
    type: "bigint",
    coerce: true,
    ...normalizeParams(params)
  });
}
function _int64(Class2, params) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "int64",
    ...normalizeParams(params)
  });
}
function _uint64(Class2, params) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "uint64",
    ...normalizeParams(params)
  });
}
function _symbol(Class2, params) {
  return new Class2({
    type: "symbol",
    ...normalizeParams(params)
  });
}
function _undefined2(Class2, params) {
  return new Class2({
    type: "undefined",
    ...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 _void(Class2, params) {
  return new Class2({
    type: "void",
    ...normalizeParams(params)
  });
}
function _date(Class2, params) {
  return new Class2({
    type: "date",
    ...normalizeParams(params)
  });
}
function _coercedDate(Class2, params) {
  return new Class2({
    type: "date",
    coerce: true,
    ...normalizeParams(params)
  });
}
function _nan(Class2, params) {
  return new Class2({
    type: "nan",
    ...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 _positive(params) {
  return _gt(0, params);
}
function _negative(params) {
  return _lt(0, params);
}
function _nonpositive(params) {
  return _lte(0, params);
}
function _nonnegative(params) {
  return _gte(0, params);
}
function _multipleOf(value, params) {
  return new $ZodCheckMultipleOf({
    check: "multiple_of",
    ...normalizeParams(params),
    value
  });
}
function _maxSize(maximum, params) {
  return new $ZodCheckMaxSize({
    check: "max_size",
    ...normalizeParams(params),
    maximum
  });
}
function _minSize(minimum, params) {
  return new $ZodCheckMinSize({
    check: "min_size",
    ...normalizeParams(params),
    minimum
  });
}
function _size(size, params) {
  return new $ZodCheckSizeEquals({
    check: "size_equals",
    ...normalizeParams(params),
    size
  });
}
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 _property(property, schema, params) {
  return new $ZodCheckProperty({
    check: "property",
    property,
    schema,
    ...normalizeParams(params)
  });
}
function _mime(types7, params) {
  return new $ZodCheckMimeType({
    check: "mime_type",
    mime: types7,
    ...normalizeParams(params)
  });
}
function _overwrite(tx) {
  return new $ZodCheckOverwrite({
    check: "overwrite",
    tx
  });
}
function _normalize(form) {
  return _overwrite((input) => input.normalize(form));
}
function _trim() {
  return _overwrite((input) => input.trim());
}
function _toLowerCase() {
  return _overwrite((input) => input.toLowerCase());
}
function _toUpperCase() {
  return _overwrite((input) => input.toUpperCase());
}
function _array(Class2, element, params) {
  return new Class2({
    type: "array",
    element,
    // get element() {
    //   return element;
    // },
    ...normalizeParams(params)
  });
}
function _union(Class2, options2, params) {
  return new Class2({
    type: "union",
    options: options2,
    ...normalizeParams(params)
  });
}
function _discriminatedUnion(Class2, discriminator, options2, params) {
  return new Class2({
    type: "union",
    options: options2,
    discriminator,
    ...normalizeParams(params)
  });
}
function _intersection(Class2, left3, right3) {
  return new Class2({
    type: "intersection",
    left: left3,
    right: right3
  });
}
function _tuple(Class2, items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new Class2({
    type: "tuple",
    items,
    rest,
    ...normalizeParams(params)
  });
}
function _record(Class2, keyType, valueType, params) {
  return new Class2({
    type: "record",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
function _map(Class2, keyType, valueType, params) {
  return new Class2({
    type: "map",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
function _set(Class2, valueType, params) {
  return new Class2({
    type: "set",
    valueType,
    ...normalizeParams(params)
  });
}
function _enum(Class2, values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values;
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
function _nativeEnum(Class2, entries, params) {
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
function _literal(Class2, value, params) {
  return new Class2({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...normalizeParams(params)
  });
}
function _file(Class2, params) {
  return new Class2({
    type: "file",
    ...normalizeParams(params)
  });
}
function _transform(Class2, fn) {
  return new Class2({
    type: "transform",
    transform: fn
  });
}
function _optional(Class2, innerType) {
  return new Class2({
    type: "optional",
    innerType
  });
}
function _nullable(Class2, innerType) {
  return new Class2({
    type: "nullable",
    innerType
  });
}
function _default(Class2, innerType, defaultValue) {
  return new Class2({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : defaultValue;
    }
  });
}
function _nonoptional(Class2, innerType, params) {
  return new Class2({
    type: "nonoptional",
    innerType,
    ...normalizeParams(params)
  });
}
function _success(Class2, innerType) {
  return new Class2({
    type: "success",
    innerType
  });
}
function _catch(Class2, innerType, catchValue) {
  return new Class2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
function _pipe(Class2, in_, out2) {
  return new Class2({
    type: "pipe",
    in: in_,
    out: out2
  });
}
function _readonly(Class2, innerType) {
  return new Class2({
    type: "readonly",
    innerType
  });
}
function _templateLiteral(Class2, parts2, params) {
  return new Class2({
    type: "template_literal",
    parts: parts2,
    ...normalizeParams(params)
  });
}
function _lazy(Class2, getter) {
  return new Class2({
    type: "lazy",
    getter
  });
}
function _promise(Class2, innerType) {
  return new Class2({
    type: "promise",
    innerType
  });
}
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;
}
function _stringbool(Classes, _params) {
  const params = normalizeParams(_params);
  let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"];
  let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"];
  if (params.case !== "sensitive") {
    truthyArray = truthyArray.map((v2) => typeof v2 === "string" ? v2.toLowerCase() : v2);
    falsyArray = falsyArray.map((v2) => typeof v2 === "string" ? v2.toLowerCase() : v2);
  }
  const truthySet = new Set(truthyArray);
  const falsySet = new Set(falsyArray);
  const _Pipe = Classes.Pipe ?? $ZodPipe;
  const _Boolean = Classes.Boolean ?? $ZodBoolean;
  const _String = Classes.String ?? $ZodString;
  const _Transform = Classes.Transform ?? $ZodTransform;
  const tx = new _Transform({
    type: "transform",
    transform: /* @__PURE__ */ __name((input, payload) => {
      let data = input;
      if (params.case !== "sensitive")
        data = data.toLowerCase();
      if (truthySet.has(data)) {
        return true;
      } else if (falsySet.has(data)) {
        return false;
      } else {
        payload.issues.push({
          code: "invalid_value",
          expected: "stringbool",
          values: [...truthySet, ...falsySet],
          input: payload.value,
          inst: tx
        });
        return {};
      }
    }, "transform"),
    error: params.error
  });
  const innerPipe = new _Pipe({
    type: "pipe",
    in: new _String({ type: "string", error: params.error }),
    out: tx,
    error: params.error
  });
  const outerPipe = new _Pipe({
    type: "pipe",
    in: innerPipe,
    out: new _Boolean({
      type: "boolean",
      error: params.error
    }),
    error: params.error
  });
  return outerPipe;
}
function _stringFormat(Class2, format4, fnOrRegex, _params = {}) {
  const params = normalizeParams(_params);
  const def2 = {
    ...normalizeParams(_params),
    check: "string_format",
    type: "string",
    format: format4,
    fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
    ...params
  };
  if (fnOrRegex instanceof RegExp) {
    def2.pattern = fnOrRegex;
  }
  const inst = new Class2(def2);
  return inst;
}
var TimePrecision;
var init_api = __esm({
  "node_modules/zod/v4/core/api.js"() {
    init_esbuild_shims();
    init_checks();
    init_schemas();
    init_util3();
    __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");
    TimePrecision = {
      Any: null,
      Minute: -1,
      Second: 0,
      Millisecond: 3,
      Microsecond: 6
    };
    __name(_isoDateTime, "_isoDateTime");
    __name(_isoDate, "_isoDate");
    __name(_isoTime, "_isoTime");
    __name(_isoDuration, "_isoDuration");
    __name(_number, "_number");
    __name(_coercedNumber, "_coercedNumber");
    __name(_int, "_int");
    __name(_float32, "_float32");
    __name(_float64, "_float64");
    __name(_int32, "_int32");
    __name(_uint32, "_uint32");
    __name(_boolean, "_boolean");
    __name(_coercedBoolean, "_coercedBoolean");
    __name(_bigint, "_bigint");
    __name(_coercedBigint, "_coercedBigint");
    __name(_int64, "_int64");
    __name(_uint64, "_uint64");
    __name(_symbol, "_symbol");
    __name(_undefined2, "_undefined");
    __name(_null2, "_null");
    __name(_any, "_any");
    __name(_unknown, "_unknown");
    __name(_never, "_never");
    __name(_void, "_void");
    __name(_date, "_date");
    __name(_coercedDate, "_coercedDate");
    __name(_nan, "_nan");
    __name(_lt, "_lt");
    __name(_lte, "_lte");
    __name(_gt, "_gt");
    __name(_gte, "_gte");
    __name(_positive, "_positive");
    __name(_negative, "_negative");
    __name(_nonpositive, "_nonpositive");
    __name(_nonnegative, "_nonnegative");
    __name(_multipleOf, "_multipleOf");
    __name(_maxSize, "_maxSize");
    __name(_minSize, "_minSize");
    __name(_size, "_size");
    __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(_property, "_property");
    __name(_mime, "_mime");
    __name(_overwrite, "_overwrite");
    __name(_normalize, "_normalize");
    __name(_trim, "_trim");
    __name(_toLowerCase, "_toLowerCase");
    __name(_toUpperCase, "_toUpperCase");
    __name(_array, "_array");
    __name(_union, "_union");
    __name(_discriminatedUnion, "_discriminatedUnion");
    __name(_intersection, "_intersection");
    __name(_tuple, "_tuple");
    __name(_record, "_record");
    __name(_map, "_map");
    __name(_set, "_set");
    __name(_enum, "_enum");
    __name(_nativeEnum, "_nativeEnum");
    __name(_literal, "_literal");
    __name(_file, "_file");
    __name(_transform, "_transform");
    __name(_optional, "_optional");
    __name(_nullable, "_nullable");
    __name(_default, "_default");
    __name(_nonoptional, "_nonoptional");
    __name(_success, "_success");
    __name(_catch, "_catch");
    __name(_pipe, "_pipe");
    __name(_readonly, "_readonly");
    __name(_templateLiteral, "_templateLiteral");
    __name(_lazy, "_lazy");
    __name(_promise, "_promise");
    __name(_custom2, "_custom");
    __name(_refine, "_refine");
    __name(_stringbool, "_stringbool");
    __name(_stringFormat, "_stringFormat");
  }
});

// node_modules/zod/v4/core/function.js
function _function(params) {
  return new $ZodFunction({
    type: "function",
    input: Array.isArray(params?.input) ? _tuple($ZodTuple, params?.input) : params?.input ?? _array($ZodArray, _unknown($ZodUnknown)),
    output: params?.output ?? _unknown($ZodUnknown)
  });
}
var $ZodFunction;
var init_function = __esm({
  "node_modules/zod/v4/core/function.js"() {
    init_esbuild_shims();
    init_api();
    init_parse2();
    init_schemas();
    init_schemas();
    $ZodFunction = class {
      static {
        __name(this, "$ZodFunction");
      }
      constructor(def2) {
        this._def = def2;
        this.def = def2;
      }
      implement(func2) {
        if (typeof func2 !== "function") {
          throw new Error("implement() must be called with a function");
        }
        const impl = /* @__PURE__ */ __name((...args2) => {
          const parsedArgs = this._def.input ? parse4(this._def.input, args2, void 0, { callee: impl }) : args2;
          if (!Array.isArray(parsedArgs)) {
            throw new Error("Invalid arguments schema: not an array or tuple schema.");
          }
          const output = func2(...parsedArgs);
          return this._def.output ? parse4(this._def.output, output, void 0, { callee: impl }) : output;
        }, "impl");
        return impl;
      }
      implementAsync(func2) {
        if (typeof func2 !== "function") {
          throw new Error("implement() must be called with a function");
        }
        const impl = /* @__PURE__ */ __name(async (...args2) => {
          const parsedArgs = this._def.input ? await parseAsync(this._def.input, args2, void 0, { callee: impl }) : args2;
          if (!Array.isArray(parsedArgs)) {
            throw new Error("Invalid arguments schema: not an array or tuple schema.");
          }
          const output = await func2(...parsedArgs);
          return this._def.output ? parseAsync(this._def.output, output, void 0, { callee: impl }) : output;
        }, "impl");
        return impl;
      }
      input(...args2) {
        const F4 = this.constructor;
        if (Array.isArray(args2[0])) {
          return new F4({
            type: "function",
            input: new $ZodTuple({
              type: "tuple",
              items: args2[0],
              rest: args2[1]
            }),
            output: this._def.output
          });
        }
        return new F4({
          type: "function",
          input: args2[0],
          output: this._def.output
        });
      }
      output(output) {
        const F4 = this.constructor;
        return new F4({
          type: "function",
          input: this._def.input,
          output
        });
      }
    };
    __name(_function, "_function");
  }
});

// node_modules/zod/v4/core/to-json-schema.js
function toJSONSchema(input, _params) {
  if (input instanceof $ZodRegistry) {
    const gen2 = new JSONSchemaGenerator(_params);
    const defs = {};
    for (const entry of input._idmap.entries()) {
      const [_2, schema] = entry;
      gen2.process(schema);
    }
    const schemas = {};
    const external = {
      registry: input,
      uri: _params?.uri,
      defs
    };
    for (const entry of input._idmap.entries()) {
      const [key, schema] = entry;
      schemas[key] = gen2.emit(schema, {
        ..._params,
        external
      });
    }
    if (Object.keys(defs).length > 0) {
      const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions";
      schemas.__shared = {
        [defsSegment]: defs
      };
    }
    return { schemas };
  }
  const gen = new JSONSchemaGenerator(_params);
  gen.process(input);
  return gen.emit(input, _params);
}
function isTransforming(_schema, _ctx) {
  const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
  if (ctx.seen.has(_schema))
    return false;
  ctx.seen.add(_schema);
  const schema = _schema;
  const def2 = schema._zod.def;
  switch (def2.type) {
    case "string":
    case "number":
    case "bigint":
    case "boolean":
    case "date":
    case "symbol":
    case "undefined":
    case "null":
    case "any":
    case "unknown":
    case "never":
    case "void":
    case "literal":
    case "enum":
    case "nan":
    case "file":
    case "template_literal":
      return false;
    case "array": {
      return isTransforming(def2.element, ctx);
    }
    case "object": {
      for (const key in def2.shape) {
        if (isTransforming(def2.shape[key], ctx))
          return true;
      }
      return false;
    }
    case "union": {
      for (const option2 of def2.options) {
        if (isTransforming(option2, ctx))
          return true;
      }
      return false;
    }
    case "intersection": {
      return isTransforming(def2.left, ctx) || isTransforming(def2.right, ctx);
    }
    case "tuple": {
      for (const item of def2.items) {
        if (isTransforming(item, ctx))
          return true;
      }
      if (def2.rest && isTransforming(def2.rest, ctx))
        return true;
      return false;
    }
    case "record": {
      return isTransforming(def2.keyType, ctx) || isTransforming(def2.valueType, ctx);
    }
    case "map": {
      return isTransforming(def2.keyType, ctx) || isTransforming(def2.valueType, ctx);
    }
    case "set": {
      return isTransforming(def2.valueType, ctx);
    }
    // inner types
    case "promise":
    case "optional":
    case "nonoptional":
    case "nullable":
    case "readonly":
      return isTransforming(def2.innerType, ctx);
    case "lazy":
      return isTransforming(def2.getter(), ctx);
    case "default": {
      return isTransforming(def2.innerType, ctx);
    }
    case "prefault": {
      return isTransforming(def2.innerType, ctx);
    }
    case "custom": {
      return false;
    }
    case "transform": {
      return true;
    }
    case "pipe": {
      return isTransforming(def2.in, ctx) || isTransforming(def2.out, ctx);
    }
    case "success": {
      return false;
    }
    case "catch": {
      return false;
    }
    default:
      def2;
  }
  throw new Error(`Unknown schema type: ${def2.type}`);
}
var JSONSchemaGenerator;
var init_to_json_schema = __esm({
  "node_modules/zod/v4/core/to-json-schema.js"() {
    init_esbuild_shims();
    init_registries();
    init_util3();
    JSONSchemaGenerator = class {
      static {
        __name(this, "JSONSchemaGenerator");
      }
      constructor(params) {
        this.counter = 0;
        this.metadataRegistry = params?.metadata ?? globalRegistry;
        this.target = params?.target ?? "draft-2020-12";
        this.unrepresentable = params?.unrepresentable ?? "throw";
        this.override = params?.override ?? (() => {
        });
        this.io = params?.io ?? "output";
        this.seen = /* @__PURE__ */ new Map();
      }
      process(schema, _params = { path: [], schemaPath: [] }) {
        var _a7;
        const def2 = schema._zod.def;
        const formatMap2 = {
          guid: "uuid",
          url: "uri",
          datetime: "date-time",
          json_string: "json-string",
          regex: ""
          // do not set
        };
        const seen = this.seen.get(schema);
        if (seen) {
          seen.count++;
          const isCycle = _params.schemaPath.includes(schema);
          if (isCycle) {
            seen.cycle = _params.path;
          }
          return seen.schema;
        }
        const result = { schema: {}, count: 1, cycle: void 0, path: _params.path };
        this.seen.set(schema, result);
        const overrideSchema = schema._zod.toJSONSchema?.();
        if (overrideSchema) {
          result.schema = overrideSchema;
        } else {
          const params = {
            ..._params,
            schemaPath: [..._params.schemaPath, schema],
            path: _params.path
          };
          const parent = schema._zod.parent;
          if (parent) {
            result.ref = parent;
            this.process(parent, params);
            this.seen.get(parent).isParent = true;
          } else {
            const _json = result.schema;
            switch (def2.type) {
              case "string": {
                const json3 = _json;
                json3.type = "string";
                const { minimum, maximum, format: format4, patterns, contentEncoding } = schema._zod.bag;
                if (typeof minimum === "number")
                  json3.minLength = minimum;
                if (typeof maximum === "number")
                  json3.maxLength = maximum;
                if (format4) {
                  json3.format = formatMap2[format4] ?? format4;
                  if (json3.format === "")
                    delete json3.format;
                }
                if (contentEncoding)
                  json3.contentEncoding = contentEncoding;
                if (patterns && patterns.size > 0) {
                  const regexes = [...patterns];
                  if (regexes.length === 1)
                    json3.pattern = regexes[0].source;
                  else if (regexes.length > 1) {
                    result.schema.allOf = [
                      ...regexes.map((regex3) => ({
                        ...this.target === "draft-7" ? { type: "string" } : {},
                        pattern: regex3.source
                      }))
                    ];
                  }
                }
                break;
              }
              case "number": {
                const json3 = _json;
                const { minimum, maximum, format: format4, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
                if (typeof format4 === "string" && format4.includes("int"))
                  json3.type = "integer";
                else
                  json3.type = "number";
                if (typeof exclusiveMinimum === "number")
                  json3.exclusiveMinimum = exclusiveMinimum;
                if (typeof minimum === "number") {
                  json3.minimum = minimum;
                  if (typeof exclusiveMinimum === "number") {
                    if (exclusiveMinimum >= minimum)
                      delete json3.minimum;
                    else
                      delete json3.exclusiveMinimum;
                  }
                }
                if (typeof exclusiveMaximum === "number")
                  json3.exclusiveMaximum = exclusiveMaximum;
                if (typeof maximum === "number") {
                  json3.maximum = maximum;
                  if (typeof exclusiveMaximum === "number") {
                    if (exclusiveMaximum <= maximum)
                      delete json3.maximum;
                    else
                      delete json3.exclusiveMaximum;
                  }
                }
                if (typeof multipleOf === "number")
                  json3.multipleOf = multipleOf;
                break;
              }
              case "boolean": {
                const json3 = _json;
                json3.type = "boolean";
                break;
              }
              case "bigint": {
                if (this.unrepresentable === "throw") {
                  throw new Error("BigInt cannot be represented in JSON Schema");
                }
                break;
              }
              case "symbol": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Symbols cannot be represented in JSON Schema");
                }
                break;
              }
              case "null": {
                _json.type = "null";
                break;
              }
              case "any": {
                break;
              }
              case "unknown": {
                break;
              }
              case "undefined": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Undefined cannot be represented in JSON Schema");
                }
                break;
              }
              case "void": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Void cannot be represented in JSON Schema");
                }
                break;
              }
              case "never": {
                _json.not = {};
                break;
              }
              case "date": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Date cannot be represented in JSON Schema");
                }
                break;
              }
              case "array": {
                const json3 = _json;
                const { minimum, maximum } = schema._zod.bag;
                if (typeof minimum === "number")
                  json3.minItems = minimum;
                if (typeof maximum === "number")
                  json3.maxItems = maximum;
                json3.type = "array";
                json3.items = this.process(def2.element, { ...params, path: [...params.path, "items"] });
                break;
              }
              case "object": {
                const json3 = _json;
                json3.type = "object";
                json3.properties = {};
                const shape = def2.shape;
                for (const key in shape) {
                  json3.properties[key] = this.process(shape[key], {
                    ...params,
                    path: [...params.path, "properties", key]
                  });
                }
                const allKeys = new Set(Object.keys(shape));
                const requiredKeys = new Set([...allKeys].filter((key) => {
                  const v2 = def2.shape[key]._zod;
                  if (this.io === "input") {
                    return v2.optin === void 0;
                  } else {
                    return v2.optout === void 0;
                  }
                }));
                if (requiredKeys.size > 0) {
                  json3.required = Array.from(requiredKeys);
                }
                if (def2.catchall?._zod.def.type === "never") {
                  json3.additionalProperties = false;
                } else if (!def2.catchall) {
                  if (this.io === "output")
                    json3.additionalProperties = false;
                } else if (def2.catchall) {
                  json3.additionalProperties = this.process(def2.catchall, {
                    ...params,
                    path: [...params.path, "additionalProperties"]
                  });
                }
                break;
              }
              case "union": {
                const json3 = _json;
                json3.anyOf = def2.options.map((x3, i4) => this.process(x3, {
                  ...params,
                  path: [...params.path, "anyOf", i4]
                }));
                break;
              }
              case "intersection": {
                const json3 = _json;
                const a2 = this.process(def2.left, {
                  ...params,
                  path: [...params.path, "allOf", 0]
                });
                const b2 = this.process(def2.right, {
                  ...params,
                  path: [...params.path, "allOf", 1]
                });
                const isSimpleIntersection = /* @__PURE__ */ __name((val) => "allOf" in val && Object.keys(val).length === 1, "isSimpleIntersection");
                const allOf = [
                  ...isSimpleIntersection(a2) ? a2.allOf : [a2],
                  ...isSimpleIntersection(b2) ? b2.allOf : [b2]
                ];
                json3.allOf = allOf;
                break;
              }
              case "tuple": {
                const json3 = _json;
                json3.type = "array";
                const prefixItems = def2.items.map((x3, i4) => this.process(x3, { ...params, path: [...params.path, "prefixItems", i4] }));
                if (this.target === "draft-2020-12") {
                  json3.prefixItems = prefixItems;
                } else {
                  json3.items = prefixItems;
                }
                if (def2.rest) {
                  const rest = this.process(def2.rest, {
                    ...params,
                    path: [...params.path, "items"]
                  });
                  if (this.target === "draft-2020-12") {
                    json3.items = rest;
                  } else {
                    json3.additionalItems = rest;
                  }
                }
                if (def2.rest) {
                  json3.items = this.process(def2.rest, {
                    ...params,
                    path: [...params.path, "items"]
                  });
                }
                const { minimum, maximum } = schema._zod.bag;
                if (typeof minimum === "number")
                  json3.minItems = minimum;
                if (typeof maximum === "number")
                  json3.maxItems = maximum;
                break;
              }
              case "record": {
                const json3 = _json;
                json3.type = "object";
                json3.propertyNames = this.process(def2.keyType, { ...params, path: [...params.path, "propertyNames"] });
                json3.additionalProperties = this.process(def2.valueType, {
                  ...params,
                  path: [...params.path, "additionalProperties"]
                });
                break;
              }
              case "map": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Map cannot be represented in JSON Schema");
                }
                break;
              }
              case "set": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Set cannot be represented in JSON Schema");
                }
                break;
              }
              case "enum": {
                const json3 = _json;
                const values = getEnumValues(def2.entries);
                if (values.every((v2) => typeof v2 === "number"))
                  json3.type = "number";
                if (values.every((v2) => typeof v2 === "string"))
                  json3.type = "string";
                json3.enum = values;
                break;
              }
              case "literal": {
                const json3 = _json;
                const vals = [];
                for (const val of def2.values) {
                  if (val === void 0) {
                    if (this.unrepresentable === "throw") {
                      throw new Error("Literal `undefined` cannot be represented in JSON Schema");
                    } else {
                    }
                  } else if (typeof val === "bigint") {
                    if (this.unrepresentable === "throw") {
                      throw new Error("BigInt literals cannot be represented in JSON Schema");
                    } else {
                      vals.push(Number(val));
                    }
                  } else {
                    vals.push(val);
                  }
                }
                if (vals.length === 0) {
                } else if (vals.length === 1) {
                  const val = vals[0];
                  json3.type = val === null ? "null" : typeof val;
                  json3.const = val;
                } else {
                  if (vals.every((v2) => typeof v2 === "number"))
                    json3.type = "number";
                  if (vals.every((v2) => typeof v2 === "string"))
                    json3.type = "string";
                  if (vals.every((v2) => typeof v2 === "boolean"))
                    json3.type = "string";
                  if (vals.every((v2) => v2 === null))
                    json3.type = "null";
                  json3.enum = vals;
                }
                break;
              }
              case "file": {
                const json3 = _json;
                const file2 = {
                  type: "string",
                  format: "binary",
                  contentEncoding: "binary"
                };
                const { minimum, maximum, mime } = schema._zod.bag;
                if (minimum !== void 0)
                  file2.minLength = minimum;
                if (maximum !== void 0)
                  file2.maxLength = maximum;
                if (mime) {
                  if (mime.length === 1) {
                    file2.contentMediaType = mime[0];
                    Object.assign(json3, file2);
                  } else {
                    json3.anyOf = mime.map((m3) => {
                      const mFile = { ...file2, contentMediaType: m3 };
                      return mFile;
                    });
                  }
                } else {
                  Object.assign(json3, file2);
                }
                break;
              }
              case "transform": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Transforms cannot be represented in JSON Schema");
                }
                break;
              }
              case "nullable": {
                const inner = this.process(def2.innerType, params);
                _json.anyOf = [inner, { type: "null" }];
                break;
              }
              case "nonoptional": {
                this.process(def2.innerType, params);
                result.ref = def2.innerType;
                break;
              }
              case "success": {
                const json3 = _json;
                json3.type = "boolean";
                break;
              }
              case "default": {
                this.process(def2.innerType, params);
                result.ref = def2.innerType;
                _json.default = JSON.parse(JSON.stringify(def2.defaultValue));
                break;
              }
              case "prefault": {
                this.process(def2.innerType, params);
                result.ref = def2.innerType;
                if (this.io === "input")
                  _json._prefault = JSON.parse(JSON.stringify(def2.defaultValue));
                break;
              }
              case "catch": {
                this.process(def2.innerType, params);
                result.ref = def2.innerType;
                let catchValue;
                try {
                  catchValue = def2.catchValue(void 0);
                } catch {
                  throw new Error("Dynamic catch values are not supported in JSON Schema");
                }
                _json.default = catchValue;
                break;
              }
              case "nan": {
                if (this.unrepresentable === "throw") {
                  throw new Error("NaN cannot be represented in JSON Schema");
                }
                break;
              }
              case "template_literal": {
                const json3 = _json;
                const pattern = schema._zod.pattern;
                if (!pattern)
                  throw new Error("Pattern not found in template literal");
                json3.type = "string";
                json3.pattern = pattern.source;
                break;
              }
              case "pipe": {
                const innerType = this.io === "input" ? def2.in._zod.def.type === "transform" ? def2.out : def2.in : def2.out;
                this.process(innerType, params);
                result.ref = innerType;
                break;
              }
              case "readonly": {
                this.process(def2.innerType, params);
                result.ref = def2.innerType;
                _json.readOnly = true;
                break;
              }
              // passthrough types
              case "promise": {
                this.process(def2.innerType, params);
                result.ref = def2.innerType;
                break;
              }
              case "optional": {
                this.process(def2.innerType, params);
                result.ref = def2.innerType;
                break;
              }
              case "lazy": {
                const innerType = schema._zod.innerType;
                this.process(innerType, params);
                result.ref = innerType;
                break;
              }
              case "custom": {
                if (this.unrepresentable === "throw") {
                  throw new Error("Custom types cannot be represented in JSON Schema");
                }
                break;
              }
              default: {
                def2;
              }
            }
          }
        }
        const meta = this.metadataRegistry.get(schema);
        if (meta)
          Object.assign(result.schema, meta);
        if (this.io === "input" && isTransforming(schema)) {
          delete result.schema.examples;
          delete result.schema.default;
        }
        if (this.io === "input" && result.schema._prefault)
          (_a7 = result.schema).default ?? (_a7.default = result.schema._prefault);
        delete result.schema._prefault;
        const _result = this.seen.get(schema);
        return _result.schema;
      }
      emit(schema, _params) {
        const params = {
          cycles: _params?.cycles ?? "ref",
          reused: _params?.reused ?? "inline",
          // unrepresentable: _params?.unrepresentable ?? "throw",
          // uri: _params?.uri ?? ((id) => `${id}`),
          external: _params?.external ?? void 0
        };
        const root = this.seen.get(schema);
        if (!root)
          throw new Error("Unprocessed schema. This is a bug in Zod.");
        const makeURI = /* @__PURE__ */ __name((entry) => {
          const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";
          if (params.external) {
            const externalId = params.external.registry.get(entry[0])?.id;
            const uriGenerator = params.external.uri ?? ((id2) => id2);
            if (externalId) {
              return { ref: uriGenerator(externalId) };
            }
            const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;
            entry[1].defId = id;
            return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
          }
          if (entry[1] === root) {
            return { ref: "#" };
          }
          const uriPrefix = `#`;
          const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
          const defId = entry[1].schema.id ?? `__schema${this.counter++}`;
          return { defId, ref: defUriPrefix + defId };
        }, "makeURI");
        const extractToDef = /* @__PURE__ */ __name((entry) => {
          if (entry[1].schema.$ref) {
            return;
          }
          const seen = entry[1];
          const { ref, defId } = makeURI(entry);
          seen.def = { ...seen.schema };
          if (defId)
            seen.defId = defId;
          const schema2 = seen.schema;
          for (const key in schema2) {
            delete schema2[key];
          }
          schema2.$ref = ref;
        }, "extractToDef");
        if (params.cycles === "throw") {
          for (const entry of this.seen.entries()) {
            const seen = entry[1];
            if (seen.cycle) {
              throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
            }
          }
        }
        for (const entry of this.seen.entries()) {
          const seen = entry[1];
          if (schema === entry[0]) {
            extractToDef(entry);
            continue;
          }
          if (params.external) {
            const ext2 = params.external.registry.get(entry[0])?.id;
            if (schema !== entry[0] && ext2) {
              extractToDef(entry);
              continue;
            }
          }
          const id = this.metadataRegistry.get(entry[0])?.id;
          if (id) {
            extractToDef(entry);
            continue;
          }
          if (seen.cycle) {
            extractToDef(entry);
            continue;
          }
          if (seen.count > 1) {
            if (params.reused === "ref") {
              extractToDef(entry);
              continue;
            }
          }
        }
        const flattenRef = /* @__PURE__ */ __name((zodSchema, params2) => {
          const seen = this.seen.get(zodSchema);
          const schema2 = seen.def ?? seen.schema;
          const _cached = { ...schema2 };
          if (seen.ref === null) {
            return;
          }
          const ref = seen.ref;
          seen.ref = null;
          if (ref) {
            flattenRef(ref, params2);
            const refSchema = this.seen.get(ref).schema;
            if (refSchema.$ref && params2.target === "draft-7") {
              schema2.allOf = schema2.allOf ?? [];
              schema2.allOf.push(refSchema);
            } else {
              Object.assign(schema2, refSchema);
              Object.assign(schema2, _cached);
            }
          }
          if (!seen.isParent)
            this.override({
              zodSchema,
              jsonSchema: schema2,
              path: seen.path ?? []
            });
        }, "flattenRef");
        for (const entry of [...this.seen.entries()].reverse()) {
          flattenRef(entry[0], { target: this.target });
        }
        const result = {};
        if (this.target === "draft-2020-12") {
          result.$schema = "https://json-schema.org/draft/2020-12/schema";
        } else if (this.target === "draft-7") {
          result.$schema = "http://json-schema.org/draft-07/schema#";
        } else {
          console.warn(`Invalid target: ${this.target}`);
        }
        if (params.external?.uri) {
          const id = params.external.registry.get(schema)?.id;
          if (!id)
            throw new Error("Schema is missing an `id` property");
          result.$id = params.external.uri(id);
        }
        Object.assign(result, root.def);
        const defs = params.external?.defs ?? {};
        for (const entry of this.seen.entries()) {
          const seen = entry[1];
          if (seen.def && seen.defId) {
            defs[seen.defId] = seen.def;
          }
        }
        if (params.external) {
        } else {
          if (Object.keys(defs).length > 0) {
            if (this.target === "draft-2020-12") {
              result.$defs = defs;
            } else {
              result.definitions = defs;
            }
          }
        }
        try {
          return JSON.parse(JSON.stringify(result));
        } catch (_err) {
          throw new Error("Error converting schema to JSON.");
        }
      }
    };
    __name(toJSONSchema, "toJSONSchema");
    __name(isTransforming, "isTransforming");
  }
});

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

// node_modules/zod/v4/core/index.js
var core_exports3 = {};
__export(core_exports3, {
  $ZodAny: () => $ZodAny,
  $ZodArray: () => $ZodArray,
  $ZodAsyncError: () => $ZodAsyncError,
  $ZodBase64: () => $ZodBase64,
  $ZodBase64URL: () => $ZodBase64URL,
  $ZodBigInt: () => $ZodBigInt,
  $ZodBigIntFormat: () => $ZodBigIntFormat,
  $ZodBoolean: () => $ZodBoolean,
  $ZodCIDRv4: () => $ZodCIDRv4,
  $ZodCIDRv6: () => $ZodCIDRv6,
  $ZodCUID: () => $ZodCUID,
  $ZodCUID2: () => $ZodCUID2,
  $ZodCatch: () => $ZodCatch,
  $ZodCheck: () => $ZodCheck,
  $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat,
  $ZodCheckEndsWith: () => $ZodCheckEndsWith,
  $ZodCheckGreaterThan: () => $ZodCheckGreaterThan,
  $ZodCheckIncludes: () => $ZodCheckIncludes,
  $ZodCheckLengthEquals: () => $ZodCheckLengthEquals,
  $ZodCheckLessThan: () => $ZodCheckLessThan,
  $ZodCheckLowerCase: () => $ZodCheckLowerCase,
  $ZodCheckMaxLength: () => $ZodCheckMaxLength,
  $ZodCheckMaxSize: () => $ZodCheckMaxSize,
  $ZodCheckMimeType: () => $ZodCheckMimeType,
  $ZodCheckMinLength: () => $ZodCheckMinLength,
  $ZodCheckMinSize: () => $ZodCheckMinSize,
  $ZodCheckMultipleOf: () => $ZodCheckMultipleOf,
  $ZodCheckNumberFormat: () => $ZodCheckNumberFormat,
  $ZodCheckOverwrite: () => $ZodCheckOverwrite,
  $ZodCheckProperty: () => $ZodCheckProperty,
  $ZodCheckRegex: () => $ZodCheckRegex,
  $ZodCheckSizeEquals: () => $ZodCheckSizeEquals,
  $ZodCheckStartsWith: () => $ZodCheckStartsWith,
  $ZodCheckStringFormat: () => $ZodCheckStringFormat,
  $ZodCheckUpperCase: () => $ZodCheckUpperCase,
  $ZodCustom: () => $ZodCustom,
  $ZodCustomStringFormat: () => $ZodCustomStringFormat,
  $ZodDate: () => $ZodDate,
  $ZodDefault: () => $ZodDefault,
  $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion,
  $ZodE164: () => $ZodE164,
  $ZodEmail: () => $ZodEmail,
  $ZodEmoji: () => $ZodEmoji,
  $ZodEnum: () => $ZodEnum,
  $ZodError: () => $ZodError,
  $ZodFile: () => $ZodFile,
  $ZodFunction: () => $ZodFunction,
  $ZodGUID: () => $ZodGUID,
  $ZodIPv4: () => $ZodIPv4,
  $ZodIPv6: () => $ZodIPv6,
  $ZodISODate: () => $ZodISODate,
  $ZodISODateTime: () => $ZodISODateTime,
  $ZodISODuration: () => $ZodISODuration,
  $ZodISOTime: () => $ZodISOTime,
  $ZodIntersection: () => $ZodIntersection,
  $ZodJWT: () => $ZodJWT,
  $ZodKSUID: () => $ZodKSUID,
  $ZodLazy: () => $ZodLazy,
  $ZodLiteral: () => $ZodLiteral,
  $ZodMap: () => $ZodMap,
  $ZodNaN: () => $ZodNaN,
  $ZodNanoID: () => $ZodNanoID,
  $ZodNever: () => $ZodNever,
  $ZodNonOptional: () => $ZodNonOptional,
  $ZodNull: () => $ZodNull,
  $ZodNullable: () => $ZodNullable,
  $ZodNumber: () => $ZodNumber,
  $ZodNumberFormat: () => $ZodNumberFormat,
  $ZodObject: () => $ZodObject,
  $ZodOptional: () => $ZodOptional,
  $ZodPipe: () => $ZodPipe,
  $ZodPrefault: () => $ZodPrefault,
  $ZodPromise: () => $ZodPromise,
  $ZodReadonly: () => $ZodReadonly,
  $ZodRealError: () => $ZodRealError,
  $ZodRecord: () => $ZodRecord,
  $ZodRegistry: () => $ZodRegistry,
  $ZodSet: () => $ZodSet,
  $ZodString: () => $ZodString,
  $ZodStringFormat: () => $ZodStringFormat,
  $ZodSuccess: () => $ZodSuccess,
  $ZodSymbol: () => $ZodSymbol,
  $ZodTemplateLiteral: () => $ZodTemplateLiteral,
  $ZodTransform: () => $ZodTransform,
  $ZodTuple: () => $ZodTuple,
  $ZodType: () => $ZodType,
  $ZodULID: () => $ZodULID,
  $ZodURL: () => $ZodURL,
  $ZodUUID: () => $ZodUUID,
  $ZodUndefined: () => $ZodUndefined,
  $ZodUnion: () => $ZodUnion,
  $ZodUnknown: () => $ZodUnknown,
  $ZodVoid: () => $ZodVoid,
  $ZodXID: () => $ZodXID,
  $brand: () => $brand,
  $constructor: () => $constructor,
  $input: () => $input,
  $output: () => $output,
  Doc: () => Doc,
  JSONSchema: () => json_schema_exports,
  JSONSchemaGenerator: () => JSONSchemaGenerator,
  NEVER: () => NEVER2,
  TimePrecision: () => TimePrecision,
  _any: () => _any,
  _array: () => _array,
  _base64: () => _base64,
  _base64url: () => _base64url,
  _bigint: () => _bigint,
  _boolean: () => _boolean,
  _catch: () => _catch,
  _cidrv4: () => _cidrv4,
  _cidrv6: () => _cidrv6,
  _coercedBigint: () => _coercedBigint,
  _coercedBoolean: () => _coercedBoolean,
  _coercedDate: () => _coercedDate,
  _coercedNumber: () => _coercedNumber,
  _coercedString: () => _coercedString,
  _cuid: () => _cuid,
  _cuid2: () => _cuid2,
  _custom: () => _custom2,
  _date: () => _date,
  _default: () => _default,
  _discriminatedUnion: () => _discriminatedUnion,
  _e164: () => _e164,
  _email: () => _email,
  _emoji: () => _emoji2,
  _endsWith: () => _endsWith,
  _enum: () => _enum,
  _file: () => _file,
  _float32: () => _float32,
  _float64: () => _float64,
  _gt: () => _gt,
  _gte: () => _gte,
  _guid: () => _guid,
  _includes: () => _includes,
  _int: () => _int,
  _int32: () => _int32,
  _int64: () => _int64,
  _intersection: () => _intersection,
  _ipv4: () => _ipv4,
  _ipv6: () => _ipv6,
  _isoDate: () => _isoDate,
  _isoDateTime: () => _isoDateTime,
  _isoDuration: () => _isoDuration,
  _isoTime: () => _isoTime,
  _jwt: () => _jwt,
  _ksuid: () => _ksuid,
  _lazy: () => _lazy,
  _length: () => _length,
  _literal: () => _literal,
  _lowercase: () => _lowercase,
  _lt: () => _lt,
  _lte: () => _lte,
  _map: () => _map,
  _max: () => _lte,
  _maxLength: () => _maxLength,
  _maxSize: () => _maxSize,
  _mime: () => _mime,
  _min: () => _gte,
  _minLength: () => _minLength,
  _minSize: () => _minSize,
  _multipleOf: () => _multipleOf,
  _nan: () => _nan,
  _nanoid: () => _nanoid,
  _nativeEnum: () => _nativeEnum,
  _negative: () => _negative,
  _never: () => _never,
  _nonnegative: () => _nonnegative,
  _nonoptional: () => _nonoptional,
  _nonpositive: () => _nonpositive,
  _normalize: () => _normalize,
  _null: () => _null2,
  _nullable: () => _nullable,
  _number: () => _number,
  _optional: () => _optional,
  _overwrite: () => _overwrite,
  _parse: () => _parse,
  _parseAsync: () => _parseAsync,
  _pipe: () => _pipe,
  _positive: () => _positive,
  _promise: () => _promise,
  _property: () => _property,
  _readonly: () => _readonly,
  _record: () => _record,
  _refine: () => _refine,
  _regex: () => _regex,
  _safeParse: () => _safeParse,
  _safeParseAsync: () => _safeParseAsync,
  _set: () => _set,
  _size: () => _size,
  _startsWith: () => _startsWith,
  _string: () => _string,
  _stringFormat: () => _stringFormat,
  _stringbool: () => _stringbool,
  _success: () => _success,
  _symbol: () => _symbol,
  _templateLiteral: () => _templateLiteral,
  _toLowerCase: () => _toLowerCase,
  _toUpperCase: () => _toUpperCase,
  _transform: () => _transform,
  _trim: () => _trim,
  _tuple: () => _tuple,
  _uint32: () => _uint32,
  _uint64: () => _uint64,
  _ulid: () => _ulid,
  _undefined: () => _undefined2,
  _union: () => _union,
  _unknown: () => _unknown,
  _uppercase: () => _uppercase,
  _url: () => _url,
  _uuid: () => _uuid,
  _uuidv4: () => _uuidv4,
  _uuidv6: () => _uuidv6,
  _uuidv7: () => _uuidv7,
  _void: () => _void,
  _xid: () => _xid,
  clone: () => clone2,
  config: () => config,
  flattenError: () => flattenError,
  formatError: () => formatError,
  function: () => _function,
  globalConfig: () => globalConfig,
  globalRegistry: () => globalRegistry,
  isValidBase64: () => isValidBase64,
  isValidBase64URL: () => isValidBase64URL,
  isValidJWT: () => isValidJWT2,
  locales: () => locales_exports,
  parse: () => parse4,
  parseAsync: () => parseAsync,
  prettifyError: () => prettifyError,
  regexes: () => regexes_exports,
  registry: () => registry,
  safeParse: () => safeParse,
  safeParseAsync: () => safeParseAsync,
  toDotPath: () => toDotPath,
  toJSONSchema: () => toJSONSchema,
  treeifyError: () => treeifyError,
  util: () => util_exports,
  version: () => version
});
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_util3();
    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 parse5, parseAsync2, safeParse3, safeParseAsync2;
var init_parse4 = __esm({
  "node_modules/zod/v4/classic/parse.js"() {
    init_esbuild_shims();
    init_core3();
    init_errors5();
    parse5 = /* @__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 email2(params) {
  return _email(ZodEmail, params);
}
function guid2(params) {
  return _guid(ZodGUID, params);
}
function uuid2(params) {
  return _uuid(ZodUUID, params);
}
function uuidv4(params) {
  return _uuidv4(ZodUUID, params);
}
function uuidv6(params) {
  return _uuidv6(ZodUUID, params);
}
function uuidv7(params) {
  return _uuidv7(ZodUUID, params);
}
function url(params) {
  return _url(ZodURL, params);
}
function emoji2(params) {
  return _emoji2(ZodEmoji, params);
}
function nanoid2(params) {
  return _nanoid(ZodNanoID, params);
}
function cuid3(params) {
  return _cuid(ZodCUID, params);
}
function cuid22(params) {
  return _cuid2(ZodCUID2, params);
}
function ulid2(params) {
  return _ulid(ZodULID, params);
}
function xid2(params) {
  return _xid(ZodXID, params);
}
function ksuid2(params) {
  return _ksuid(ZodKSUID, params);
}
function ipv42(params) {
  return _ipv4(ZodIPv4, params);
}
function ipv62(params) {
  return _ipv6(ZodIPv6, params);
}
function cidrv42(params) {
  return _cidrv4(ZodCIDRv4, params);
}
function cidrv62(params) {
  return _cidrv6(ZodCIDRv6, params);
}
function base642(params) {
  return _base64(ZodBase64, params);
}
function base64url2(params) {
  return _base64url(ZodBase64URL, params);
}
function e1642(params) {
  return _e164(ZodE164, params);
}
function jwt(params) {
  return _jwt(ZodJWT, params);
}
function stringFormat(format4, fnOrRegex, _params = {}) {
  return _stringFormat(ZodCustomStringFormat, format4, fnOrRegex, _params);
}
function number2(params) {
  return _number(ZodNumber2, params);
}
function int(params) {
  return _int(ZodNumberFormat, params);
}
function float32(params) {
  return _float32(ZodNumberFormat, params);
}
function float64(params) {
  return _float64(ZodNumberFormat, params);
}
function int32(params) {
  return _int32(ZodNumberFormat, params);
}
function uint32(params) {
  return _uint32(ZodNumberFormat, params);
}
function boolean2(params) {
  return _boolean(ZodBoolean2, params);
}
function bigint2(params) {
  return _bigint(ZodBigInt2, params);
}
function int64(params) {
  return _int64(ZodBigIntFormat, params);
}
function uint64(params) {
  return _uint64(ZodBigIntFormat, params);
}
function symbol(params) {
  return _symbol(ZodSymbol2, params);
}
function _undefined3(params) {
  return _undefined2(ZodUndefined2, params);
}
function _null3(params) {
  return _null2(ZodNull2, params);
}
function any() {
  return _any(ZodAny2);
}
function unknown() {
  return _unknown(ZodUnknown2);
}
function never(params) {
  return _never(ZodNever2, params);
}
function _void2(params) {
  return _void(ZodVoid2, params);
}
function date3(params) {
  return _date(ZodDate2, params);
}
function array(element, params) {
  return _array(ZodArray2, element, params);
}
function keyof(schema) {
  const shape = schema._zod.def.shape;
  return literal(Object.keys(shape));
}
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 strictObject(shape, params) {
  return new ZodObject2({
    type: "object",
    get shape() {
      util_exports.assignProp(this, "shape", { ...shape });
      return this.shape;
    },
    catchall: never(),
    ...util_exports.normalizeParams(params)
  });
}
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 tuple(items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new ZodTuple2({
    type: "tuple",
    items,
    rest,
    ...util_exports.normalizeParams(params)
  });
}
function record(keyType, valueType, params) {
  return new ZodRecord2({
    type: "record",
    keyType,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function partialRecord(keyType, valueType, params) {
  return new ZodRecord2({
    type: "record",
    keyType: union([keyType, never()]),
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function map(keyType, valueType, params) {
  return new ZodMap2({
    type: "map",
    keyType,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function set(valueType, params) {
  return new ZodSet2({
    type: "set",
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function _enum2(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 nativeEnum(entries, params) {
  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 file(params) {
  return _file(ZodFile, 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 nullish2(innerType) {
  return optional(nullable(innerType));
}
function _default2(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 success(innerType) {
  return new ZodSuccess({
    type: "success",
    innerType
  });
}
function _catch2(innerType, catchValue) {
  return new ZodCatch2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
function nan(params) {
  return _nan(ZodNaN2, params);
}
function pipe(in_, out2) {
  return new ZodPipe({
    type: "pipe",
    in: in_,
    out: out2
    // ...util.normalizeParams(params),
  });
}
function readonly(innerType) {
  return new ZodReadonly2({
    type: "readonly",
    innerType
  });
}
function templateLiteral(parts2, params) {
  return new ZodTemplateLiteral({
    type: "template_literal",
    parts: parts2,
    ...util_exports.normalizeParams(params)
  });
}
function lazy(getter) {
  return new ZodLazy2({
    type: "lazy",
    getter
  });
}
function promise(innerType) {
  return new ZodPromise2({
    type: "promise",
    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 _instanceof(cls, params = {
  error: `Input not instance of ${cls.name}`
}) {
  const inst = new ZodCustom({
    type: "custom",
    check: "custom",
    fn: /* @__PURE__ */ __name((data) => data instanceof cls, "fn"),
    abort: true,
    ...util_exports.normalizeParams(params)
  });
  inst._zod.bag.Class = cls;
  return inst;
}
function json(params) {
  const jsonSchema = lazy(() => {
    return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]);
  });
  return jsonSchema;
}
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, ZodCustomStringFormat, ZodNumber2, ZodNumberFormat, ZodBoolean2, ZodBigInt2, ZodBigIntFormat, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodDate2, ZodArray2, ZodObject2, ZodUnion2, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodEnum2, ZodLiteral2, ZodFile, ZodTransform, ZodOptional2, ZodNullable2, ZodDefault2, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch2, ZodNaN2, ZodPipe, ZodReadonly2, ZodTemplateLiteral, ZodLazy2, ZodPromise2, ZodCustom, stringbool;
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) => parse5(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) => _default2(inst, def3);
      inst.prefault = (def3) => prefault(inst, def3);
      inst.catch = (params) => _catch2(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 = (...args2) => {
        if (args2.length === 0) {
          return globalRegistry.get(inst);
        }
        const cl = inst.clone();
        globalRegistry.add(cl, args2[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 = (...args2) => inst.check(_regex(...args2));
      inst.includes = (...args2) => inst.check(_includes(...args2));
      inst.startsWith = (...args2) => inst.check(_startsWith(...args2));
      inst.endsWith = (...args2) => inst.check(_endsWith(...args2));
      inst.min = (...args2) => inst.check(_minLength(...args2));
      inst.max = (...args2) => inst.check(_maxLength(...args2));
      inst.length = (...args2) => inst.check(_length(...args2));
      inst.nonempty = (...args2) => inst.check(_minLength(1, ...args2));
      inst.lowercase = (params) => inst.check(_lowercase(params));
      inst.uppercase = (params) => inst.check(_uppercase(params));
      inst.trim = () => inst.check(_trim());
      inst.normalize = (...args2) => inst.check(_normalize(...args2));
      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);
    });
    __name(email2, "email");
    ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def2) => {
      $ZodGUID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(guid2, "guid");
    ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def2) => {
      $ZodUUID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(uuid2, "uuid");
    __name(uuidv4, "uuidv4");
    __name(uuidv6, "uuidv6");
    __name(uuidv7, "uuidv7");
    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);
    });
    __name(emoji2, "emoji");
    ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def2) => {
      $ZodNanoID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(nanoid2, "nanoid");
    ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def2) => {
      $ZodCUID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(cuid3, "cuid");
    ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def2) => {
      $ZodCUID2.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(cuid22, "cuid2");
    ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def2) => {
      $ZodULID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(ulid2, "ulid");
    ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def2) => {
      $ZodXID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(xid2, "xid");
    ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def2) => {
      $ZodKSUID.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(ksuid2, "ksuid");
    ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def2) => {
      $ZodIPv4.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(ipv42, "ipv4");
    ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def2) => {
      $ZodIPv6.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(ipv62, "ipv6");
    ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def2) => {
      $ZodCIDRv4.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(cidrv42, "cidrv4");
    ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def2) => {
      $ZodCIDRv6.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(cidrv62, "cidrv6");
    ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def2) => {
      $ZodBase64.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(base642, "base64");
    ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def2) => {
      $ZodBase64URL.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(base64url2, "base64url");
    ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def2) => {
      $ZodE164.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(e1642, "e164");
    ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def2) => {
      $ZodJWT.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(jwt, "jwt");
    ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def2) => {
      $ZodCustomStringFormat.init(inst, def2);
      ZodStringFormat.init(inst, def2);
    });
    __name(stringFormat, "stringFormat");
    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");
    __name(float32, "float32");
    __name(float64, "float64");
    __name(int32, "int32");
    __name(uint32, "uint32");
    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;
    });
    __name(bigint2, "bigint");
    ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def2) => {
      $ZodBigIntFormat.init(inst, def2);
      ZodBigInt2.init(inst, def2);
    });
    __name(int64, "int64");
    __name(uint64, "uint64");
    ZodSymbol2 = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def2) => {
      $ZodSymbol.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(symbol, "symbol");
    ZodUndefined2 = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def2) => {
      $ZodUndefined.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(_undefined3, "_undefined");
    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(never, "never");
    ZodVoid2 = /* @__PURE__ */ $constructor("ZodVoid", (inst, def2) => {
      $ZodVoid.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(_void2, "_void");
    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;
    });
    __name(date3, "date");
    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");
    __name(keyof, "keyof");
    ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def2) => {
      $ZodObject.init(inst, def2);
      ZodType2.init(inst, def2);
      util_exports.defineLazy(inst, "shape", () => def2.shape);
      inst.keyof = () => _enum2(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: never() });
      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 = (...args2) => util_exports.partial(ZodOptional2, inst, args2[0]);
      inst.required = (...args2) => util_exports.required(ZodNonOptional, inst, args2[0]);
    });
    __name(object2, "object");
    __name(strictObject, "strictObject");
    __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");
    ZodTuple2 = /* @__PURE__ */ $constructor("ZodTuple", (inst, def2) => {
      $ZodTuple.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.rest = (rest) => inst.clone({
        ...inst._zod.def,
        rest
      });
    });
    __name(tuple, "tuple");
    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");
    __name(partialRecord, "partialRecord");
    ZodMap2 = /* @__PURE__ */ $constructor("ZodMap", (inst, def2) => {
      $ZodMap.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.keyType = def2.keyType;
      inst.valueType = def2.valueType;
    });
    __name(map, "map");
    ZodSet2 = /* @__PURE__ */ $constructor("ZodSet", (inst, def2) => {
      $ZodSet.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.min = (...args2) => inst.check(_minSize(...args2));
      inst.nonempty = (params) => inst.check(_minSize(1, params));
      inst.max = (...args2) => inst.check(_maxSize(...args2));
      inst.size = (...args2) => inst.check(_size(...args2));
    });
    __name(set, "set");
    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(_enum2, "_enum");
    __name(nativeEnum, "nativeEnum");
    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");
    ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def2) => {
      $ZodFile.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.min = (size, params) => inst.check(_minSize(size, params));
      inst.max = (size, params) => inst.check(_maxSize(size, params));
      inst.mime = (types7, params) => inst.check(_mime(Array.isArray(types7) ? types7 : [types7], params));
    });
    __name(file, "file");
    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");
    __name(nullish2, "nullish");
    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(_default2, "_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");
    ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def2) => {
      $ZodSuccess.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    __name(success, "success");
    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(_catch2, "_catch");
    ZodNaN2 = /* @__PURE__ */ $constructor("ZodNaN", (inst, def2) => {
      $ZodNaN.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(nan, "nan");
    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");
    ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def2) => {
      $ZodTemplateLiteral.init(inst, def2);
      ZodType2.init(inst, def2);
    });
    __name(templateLiteral, "templateLiteral");
    ZodLazy2 = /* @__PURE__ */ $constructor("ZodLazy", (inst, def2) => {
      $ZodLazy.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.unwrap = () => inst._zod.def.getter();
    });
    __name(lazy, "lazy");
    ZodPromise2 = /* @__PURE__ */ $constructor("ZodPromise", (inst, def2) => {
      $ZodPromise.init(inst, def2);
      ZodType2.init(inst, def2);
      inst.unwrap = () => inst._zod.def.innerType;
    });
    __name(promise, "promise");
    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(_instanceof, "_instanceof");
    stringbool = /* @__PURE__ */ __name((...args2) => _stringbool({
      Pipe: ZodPipe,
      Boolean: ZodBoolean2,
      String: ZodString2,
      Transform: ZodTransform
    }, ...args2), "stringbool");
    __name(json, "json");
    __name(preprocess, "preprocess");
  }
});

// node_modules/zod/v4/classic/compat.js
function setErrorMap2(map3) {
  config({
    customError: map3
  });
}
function getErrorMap2() {
  return config().customError;
}
var ZodIssueCode2;
var init_compat = __esm({
  "node_modules/zod/v4/classic/compat.js"() {
    init_esbuild_shims();
    init_core3();
    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"
    };
    __name(setErrorMap2, "setErrorMap");
    __name(getErrorMap2, "getErrorMap");
  }
});

// node_modules/zod/v4/classic/coerce.js
var coerce_exports2 = {};
__export(coerce_exports2, {
  bigint: () => bigint3,
  boolean: () => boolean3,
  date: () => date4,
  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 bigint3(params) {
  return _coercedBigint(ZodBigInt2, params);
}
function date4(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(bigint3, "bigint");
    __name(date4, "date");
  }
});

// node_modules/zod/v4/classic/external.js
var external_exports2 = {};
__export(external_exports2, {
  $brand: () => $brand,
  $input: () => $input,
  $output: () => $output,
  NEVER: () => NEVER2,
  TimePrecision: () => TimePrecision,
  ZodAny: () => ZodAny2,
  ZodArray: () => ZodArray2,
  ZodBase64: () => ZodBase64,
  ZodBase64URL: () => ZodBase64URL,
  ZodBigInt: () => ZodBigInt2,
  ZodBigIntFormat: () => ZodBigIntFormat,
  ZodBoolean: () => ZodBoolean2,
  ZodCIDRv4: () => ZodCIDRv4,
  ZodCIDRv6: () => ZodCIDRv6,
  ZodCUID: () => ZodCUID,
  ZodCUID2: () => ZodCUID2,
  ZodCatch: () => ZodCatch2,
  ZodCustom: () => ZodCustom,
  ZodCustomStringFormat: () => ZodCustomStringFormat,
  ZodDate: () => ZodDate2,
  ZodDefault: () => ZodDefault2,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2,
  ZodE164: () => ZodE164,
  ZodEmail: () => ZodEmail,
  ZodEmoji: () => ZodEmoji,
  ZodEnum: () => ZodEnum2,
  ZodError: () => ZodError2,
  ZodFile: () => ZodFile,
  ZodGUID: () => ZodGUID,
  ZodIPv4: () => ZodIPv4,
  ZodIPv6: () => ZodIPv6,
  ZodISODate: () => ZodISODate,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODuration: () => ZodISODuration,
  ZodISOTime: () => ZodISOTime,
  ZodIntersection: () => ZodIntersection2,
  ZodIssueCode: () => ZodIssueCode2,
  ZodJWT: () => ZodJWT,
  ZodKSUID: () => ZodKSUID,
  ZodLazy: () => ZodLazy2,
  ZodLiteral: () => ZodLiteral2,
  ZodMap: () => ZodMap2,
  ZodNaN: () => ZodNaN2,
  ZodNanoID: () => ZodNanoID,
  ZodNever: () => ZodNever2,
  ZodNonOptional: () => ZodNonOptional,
  ZodNull: () => ZodNull2,
  ZodNullable: () => ZodNullable2,
  ZodNumber: () => ZodNumber2,
  ZodNumberFormat: () => ZodNumberFormat,
  ZodObject: () => ZodObject2,
  ZodOptional: () => ZodOptional2,
  ZodPipe: () => ZodPipe,
  ZodPrefault: () => ZodPrefault,
  ZodPromise: () => ZodPromise2,
  ZodReadonly: () => ZodReadonly2,
  ZodRealError: () => ZodRealError,
  ZodRecord: () => ZodRecord2,
  ZodSet: () => ZodSet2,
  ZodString: () => ZodString2,
  ZodStringFormat: () => ZodStringFormat,
  ZodSuccess: () => ZodSuccess,
  ZodSymbol: () => ZodSymbol2,
  ZodTemplateLiteral: () => ZodTemplateLiteral,
  ZodTransform: () => ZodTransform,
  ZodTuple: () => ZodTuple2,
  ZodType: () => ZodType2,
  ZodULID: () => ZodULID,
  ZodURL: () => ZodURL,
  ZodUUID: () => ZodUUID,
  ZodUndefined: () => ZodUndefined2,
  ZodUnion: () => ZodUnion2,
  ZodUnknown: () => ZodUnknown2,
  ZodVoid: () => ZodVoid2,
  ZodXID: () => ZodXID,
  _ZodString: () => _ZodString,
  _default: () => _default2,
  any: () => any,
  array: () => array,
  base64: () => base642,
  base64url: () => base64url2,
  bigint: () => bigint2,
  boolean: () => boolean2,
  catch: () => _catch2,
  check: () => check,
  cidrv4: () => cidrv42,
  cidrv6: () => cidrv62,
  clone: () => clone2,
  coerce: () => coerce_exports2,
  config: () => config,
  core: () => core_exports3,
  cuid: () => cuid3,
  cuid2: () => cuid22,
  custom: () => custom2,
  date: () => date3,
  discriminatedUnion: () => discriminatedUnion,
  e164: () => e1642,
  email: () => email2,
  emoji: () => emoji2,
  endsWith: () => _endsWith,
  enum: () => _enum2,
  file: () => file,
  flattenError: () => flattenError,
  float32: () => float32,
  float64: () => float64,
  formatError: () => formatError,
  function: () => _function,
  getErrorMap: () => getErrorMap2,
  globalRegistry: () => globalRegistry,
  gt: () => _gt,
  gte: () => _gte,
  guid: () => guid2,
  includes: () => _includes,
  instanceof: () => _instanceof,
  int: () => int,
  int32: () => int32,
  int64: () => int64,
  intersection: () => intersection,
  ipv4: () => ipv42,
  ipv6: () => ipv62,
  iso: () => iso_exports2,
  json: () => json,
  jwt: () => jwt,
  keyof: () => keyof,
  ksuid: () => ksuid2,
  lazy: () => lazy,
  length: () => _length,
  literal: () => literal,
  locales: () => locales_exports,
  looseObject: () => looseObject,
  lowercase: () => _lowercase,
  lt: () => _lt,
  lte: () => _lte,
  map: () => map,
  maxLength: () => _maxLength,
  maxSize: () => _maxSize,
  mime: () => _mime,
  minLength: () => _minLength,
  minSize: () => _minSize,
  multipleOf: () => _multipleOf,
  nan: () => nan,
  nanoid: () => nanoid2,
  nativeEnum: () => nativeEnum,
  negative: () => _negative,
  never: () => never,
  nonnegative: () => _nonnegative,
  nonoptional: () => nonoptional,
  nonpositive: () => _nonpositive,
  normalize: () => _normalize,
  null: () => _null3,
  nullable: () => nullable,
  nullish: () => nullish2,
  number: () => number2,
  object: () => object2,
  optional: () => optional,
  overwrite: () => _overwrite,
  parse: () => parse5,
  parseAsync: () => parseAsync2,
  partialRecord: () => partialRecord,
  pipe: () => pipe,
  positive: () => _positive,
  prefault: () => prefault,
  preprocess: () => preprocess,
  prettifyError: () => prettifyError,
  promise: () => promise,
  property: () => _property,
  readonly: () => readonly,
  record: () => record,
  refine: () => refine,
  regex: () => _regex,
  regexes: () => regexes_exports,
  registry: () => registry,
  safeParse: () => safeParse3,
  safeParseAsync: () => safeParseAsync2,
  set: () => set,
  setErrorMap: () => setErrorMap2,
  size: () => _size,
  startsWith: () => _startsWith,
  strictObject: () => strictObject,
  string: () => string2,
  stringFormat: () => stringFormat,
  stringbool: () => stringbool,
  success: () => success,
  superRefine: () => superRefine,
  symbol: () => symbol,
  templateLiteral: () => templateLiteral,
  toJSONSchema: () => toJSONSchema,
  toLowerCase: () => _toLowerCase,
  toUpperCase: () => _toUpperCase,
  transform: () => transform,
  treeifyError: () => treeifyError,
  trim: () => _trim,
  tuple: () => tuple,
  uint32: () => uint32,
  uint64: () => uint64,
  ulid: () => ulid2,
  undefined: () => _undefined3,
  union: () => union,
  unknown: () => unknown,
  uppercase: () => _uppercase,
  url: () => url,
  uuid: () => uuid2,
  uuidv4: () => uuidv4,
  uuidv6: () => uuidv6,
  uuidv7: () => uuidv7,
  void: () => _void2,
  xid: () => xid2
});
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_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();
    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_types11 = __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: _enum2(["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 = _enum2(["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 = _enum2(["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: _enum2(["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 = _enum2(["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: _enum2(["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: _enum2(["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(_enum2(["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(_enum2(["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: _enum2(["email", "uri", "date", "date-time"]).optional(),
      default: string2().optional()
    });
    NumberSchemaSchema = object2({
      type: _enum2(["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: _enum2(["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_esm7 = __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_esm7();
    __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_types11();
    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 error40 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
                        resolver(error40);
                      }
                    } 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 (error40) {
              throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error40 instanceof Error ? error40.message : String(error40)}`);
            }
          });
          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 (error40) {
              if (error40 instanceof McpError) {
                throw error40;
              }
              throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error40 instanceof Error ? error40.message : String(error40)}`);
            }
          });
        }
      }
      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 info2 = this._timeoutInfo.get(messageId);
        if (!info2)
          return false;
        const totalElapsed = Date.now() - info2.startTime;
        if (info2.maxTotalTimeout && totalElapsed >= info2.maxTotalTimeout) {
          this._timeoutInfo.delete(messageId);
          throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
            maxTotalTimeout: info2.maxTotalTimeout,
            totalElapsed
          });
        }
        clearTimeout(info2.timeoutId);
        info2.timeoutId = setTimeout(info2.onTimeout, info2.timeout);
        return true;
      }
      _cleanupTimeout(messageId) {
        const info2 = this._timeoutInfo.get(messageId);
        if (info2) {
          clearTimeout(info2.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 = (error40) => {
          _onerror2?.(error40);
          this._onerror(error40);
        };
        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 error40 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
        this._transport = void 0;
        this.onclose?.();
        for (const handler of responseHandlers.values()) {
          handler(error40);
        }
      }
      _onerror(error40) {
        this.onerror?.(error40);
      }
      _onnotification(notification) {
        const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
        if (handler === void 0) {
          return;
        }
        Promise.resolve().then(() => handler(notification)).catch((error40) => this._onerror(new Error(`Uncaught error in notification handler: ${error40}`)));
      }
      _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((error40) => this._onerror(new Error(`Failed to enqueue error response: ${error40}`)));
          } else {
            capturedTransport?.send(errorResponse).catch((error40) => this._onerror(new Error(`Failed to send an error response: ${error40}`)));
          }
          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 (error40) => {
          if (abortController.signal.aborted) {
            return;
          }
          const errorResponse = {
            jsonrpc: "2.0",
            id: request4.id,
            error: {
              code: Number.isSafeInteger(error40["code"]) ? error40["code"] : ErrorCode.InternalError,
              message: error40.message ?? "Internal error",
              ...error40["data"] !== void 0 && { data: error40["data"] }
            }
          };
          if (relatedTaskId && this._taskMessageQueue) {
            await this._enqueueTaskMessage(relatedTaskId, {
              type: "error",
              message: errorResponse,
              timestamp: Date.now()
            }, capturedTransport?.sessionId);
          } else {
            await capturedTransport?.send(errorResponse);
          }
        }).catch((error40) => this._onerror(new Error(`Failed to send response: ${error40}`))).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 (error40) {
            this._responseHandlers.delete(messageId);
            this._progressHandlers.delete(messageId);
            this._cleanupTimeout(messageId);
            responseHandler(error40);
            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 error40 = new McpError(response.error.code, response.error.message, response.error.data);
            resolver(error40);
          }
          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 error40 = McpError.fromError(response.error.code, response.error.message, response.error.data);
          handler(error40);
        }
      }
      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 (error40) {
            yield {
              type: "error",
              error: error40 instanceof McpError ? error40 : new McpError(ErrorCode.InternalError, String(error40))
            };
          }
          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((resolve42) => setTimeout(resolve42, pollInterval));
            options2?.signal?.throwIfAborted();
          }
        } catch (error40) {
          yield {
            type: "error",
            error: error40 instanceof McpError ? error40 : new McpError(ErrorCode.InternalError, String(error40))
          };
        }
      }
      /**
       * 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((resolve42, reject) => {
          const earlyReject = /* @__PURE__ */ __name((error40) => {
            reject(error40);
          }, "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((error41) => this._onerror(new Error(`Failed to send cancellation: ${error41}`)));
            const error40 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
            reject(error40);
          }, "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 {
                resolve42(parseResult.data);
              }
            } catch (error40) {
              reject(error40);
            }
          });
          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((error40) => {
              this._cleanupTimeout(messageId);
              reject(error40);
            });
          } else {
            this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error40) => {
              this._cleanupTimeout(messageId);
              reject(error40);
            });
          }
        });
      }
      /**
       * 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((error40) => this._onerror(error40));
          });
          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((resolve42, reject) => {
          if (signal.aborted) {
            reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
            return;
          }
          const timeoutId = setTimeout(resolve42, 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_dist(), 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_client2 = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js"() {
    init_esbuild_shims();
    init_types11();
    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 stream5 = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
        const validator = clientInternal.getToolOutputValidator(params.name);
        for await (const message of stream5) {
          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 (error40) {
                if (error40 instanceof McpError) {
                  yield { type: "error", error: error40 };
                  return;
                }
                yield {
                  type: "error",
                  error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error40 instanceof Error ? error40.message : String(error40)}`)
                };
                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_client3 = __esm({
  "packages/core/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"() {
    init_esbuild_shims();
    init_protocol();
    init_types11();
    init_ajv_provider();
    init_zod_compat();
    init_client2();
    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 (error40) {
          void this.close();
          throw error40;
        }
      }
      /**
       * 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 (error40) {
              if (error40 instanceof McpError) {
                throw error40;
              }
              throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error40 instanceof Error ? error40.message : String(error40)}`);
            }
          }
        }
        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 error40 = e4 instanceof Error ? e4 : new Error(String(e4));
            onChanged(error40, 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 (url3, init2) => {
    const mergedInit = {
      ...baseInit,
      ...init2,
      // Headers need special handling - merge instead of replace
      headers: init2?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init2.headers) } : baseInit.headers
    };
    return baseFetch(url3, 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 crypto9).getRandomValues(new Uint8Array(size));
}
async function random(size) {
  const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
  let result = "";
  const randomUints = await getRandomValues(size);
  for (let i4 = 0; i4 < size; i4++) {
    const randomIndex = randomUints[i4] % mask.length;
    result += mask[randomIndex];
  }
  return result;
}
async function generateVerifier(length) {
  return await random(length);
}
async function generateChallenge(code_verifier) {
  const buffer = await (await crypto9).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 crypto9;
var init_index_node = __esm({
  "node_modules/pkce-challenge/dist/index.node.js"() {
    init_esbuild_shims();
    crypto9 = 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((url3) => {
      const u2 = new URL(url3);
      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(url3) {
  const resourceURL = typeof url3 === "string" ? new URL(url3) : new URL(url3.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 body2 = input instanceof Response ? await input.text() : input;
  try {
    const result = OAuthErrorResponseSchema.parse(JSON.parse(body2));
    const { error: error40, error_description, error_uri } = result;
    const errorClass = OAUTH_ERRORS[error40] || ServerError;
    return new errorClass(error_description || "", error_uri);
  } catch (error40) {
    const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error40}. Raw body: ${body2}`;
    return new ServerError(errorMessage);
  }
}
async function auth(provider, options2) {
  try {
    return await authInternal(provider, options2);
  } catch (error40) {
    if (error40 instanceof InvalidClientError || error40 instanceof UnauthorizedClientError) {
      await provider.invalidateCredentials?.("all");
      return await authInternal(provider, options2);
    } else if (error40 instanceof InvalidGrantError) {
      await provider.invalidateCredentials?.("tokens");
      return await authInternal(provider, options2);
    }
    throw error40;
  }
}
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 metadata2 = 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 = metadata2?.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: metadata2,
        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: metadata2,
      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: metadata2,
        clientInformation,
        refreshToken: tokens.refresh_token,
        resource,
        addClientAuthentication: provider.addClientAuthentication,
        fetchFn
      });
      await provider.saveTokens(newTokens);
      return "AUTHORIZED";
    } catch (error40) {
      if (!(error40 instanceof OAuthError) || error40 instanceof ServerError) {
      } else {
        throw error40;
      }
    }
  }
  const state = provider.state ? await provider.state() : void 0;
  const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
    metadata: metadata2,
    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 url3 = new URL(value);
    return url3.protocol === "https:" && url3.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 error40 = extractFieldFromWwwAuth(res, "error") || void 0;
  return {
    resourceMetadataUrl,
    scope,
    error: error40
  };
}
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(url3, headers, fetchFn = fetch) {
  try {
    return await fetchFn(url3, { headers });
  } catch (error40) {
    if (error40 instanceof TypeError) {
      if (headers) {
        return fetchWithCorsRetry(url3, void 0, fetchFn);
      } else {
        return void 0;
      }
    }
    throw error40;
  }
}
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(url3, protocolVersion, fetchFn = fetch) {
  const headers = {
    "MCP-Protocol-Version": protocolVersion
  };
  return await fetchWithCorsRetry(url3, 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 url3;
  if (opts?.metadataUrl) {
    url3 = new URL(opts.metadataUrl);
  } else {
    const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
    url3 = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
    url3.search = issuer.search;
  }
  let response = await tryMetadataDiscovery(url3, 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 url3 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
  const hasPath = url3.pathname !== "/";
  const urlsToTry = [];
  if (!hasPath) {
    urlsToTry.push({
      url: new URL("/.well-known/oauth-authorization-server", url3.origin),
      type: "oauth"
    });
    urlsToTry.push({
      url: new URL(`/.well-known/openid-configuration`, url3.origin),
      type: "oidc"
    });
    return urlsToTry;
  }
  let pathname = url3.pathname;
  if (pathname.endsWith("/")) {
    pathname = pathname.slice(0, -1);
  }
  urlsToTry.push({
    url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url3.origin),
    type: "oauth"
  });
  urlsToTry.push({
    url: new URL(`/.well-known/openid-configuration${pathname}`, url3.origin),
    type: "oidc"
  });
  urlsToTry.push({
    url: new URL(`${pathname}/.well-known/openid-configuration`, url3.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: metadata2, clientInformation, redirectUrl, scope, state, resource }) {
  let authorizationUrl;
  if (metadata2) {
    authorizationUrl = new URL(metadata2.authorization_endpoint);
    if (!metadata2.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {
      throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
    }
    if (metadata2.code_challenge_methods_supported && !metadata2.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: metadata2, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
  const tokenUrl = metadata2?.token_endpoint ? new URL(metadata2.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, metadata2);
  } else if (clientInformation) {
    const supportedMethods = metadata2?.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: metadata2, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
  const tokenRequestParams = new URLSearchParams({
    grant_type: "refresh_token",
    refresh_token: refreshToken
  });
  const tokens = await executeTokenRequest(authorizationServerUrl, {
    metadata: metadata2,
    tokenRequestParams,
    clientInformation,
    addClientAuthentication,
    resource,
    fetchFn
  });
  return { refresh_token: refreshToken, ...tokens };
}
async function fetchToken(provider, authorizationServerUrl, { metadata: metadata2, 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: metadata2,
    tokenRequestParams,
    clientInformation: clientInformation ?? void 0,
    addClientAuthentication: provider.addClientAuthentication,
    resource,
    fetchFn
  });
}
async function registerClient(authorizationServerUrl, { metadata: metadata2, clientMetadata, fetchFn }) {
  let registrationUrl;
  if (metadata2) {
    if (!metadata2.registration_endpoint) {
      throw new Error("Incompatible auth server: does not support dynamic client registration");
    }
    registrationUrl = new URL(metadata2.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_types11();
    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(error40) {
                onError2 === "terminate" ? controller.error(error40) : typeof onError2 == "function" && onError2(error40);
              },
              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_types11();
    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(url3, opts) {
        this._hasCompletedAuthFlow = false;
        this._url = url3;
        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 (error40) {
          this.onerror?.(error40);
          throw error40;
        }
        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 (error40) {
          this.onerror?.(error40);
          throw error40;
        }
      }
      /**
       * 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 delay5 = this._getNextReconnectionDelay(attemptCount);
        this._reconnectionTimeout = setTimeout(() => {
          this._startOrAuthSse(options2).catch((error40) => {
            this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error40 instanceof Error ? error40.message : String(error40)}`));
            this._scheduleReconnection(options2, attemptCount + 1);
          });
        }, delay5);
      }
      _handleSseStream(stream5, options2, isReconnectable) {
        if (!stream5) {
          return;
        }
        const { onresumptiontoken, replayMessageId } = options2;
        let lastEventId;
        let hasPrimingEvent = false;
        let receivedResponse = false;
        const processStream = /* @__PURE__ */ __name(async () => {
          try {
            const reader = stream5.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 (error40) {
                  this.onerror?.(error40);
                }
              }
            }
            const canResume = isReconnectable || hasPrimingEvent;
            const needsReconnect = canResume && !receivedResponse;
            if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
              this._scheduleReconnection({
                resumptionToken: lastEventId,
                onresumptiontoken,
                replayMessageId
              }, 0);
            }
          } catch (error40) {
            this.onerror?.(new Error(`SSE stream disconnected: ${error40}`));
            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 (error41) {
                this.onerror?.(new Error(`Failed to reconnect: ${error41 instanceof Error ? error41.message : String(error41)}`));
              }
            }
          }
        }, "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((err2) => this.onerror?.(err2));
            return;
          }
          const headers = await this._commonHeaders();
          headers.set("content-type", "application/json");
          headers.set("accept", "application/json, text/event-stream");
          const init2 = {
            ...this._requestInit,
            method: "POST",
            headers,
            body: JSON.stringify(message),
            signal: this._abortController?.signal
          };
          const response = await (this._fetch ?? fetch)(this._url, init2);
          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: error40 } = extractWWWAuthenticateParams(response);
              if (error40 === "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((err2) => this.onerror?.(err2));
            }
            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 (error40) {
          this.onerror?.(error40);
          throw error40;
        }
      }
      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 init2 = {
            ...this._requestInit,
            method: "DELETE",
            headers,
            signal: this._abortController?.signal
          };
          const response = await (this._fetch ?? fetch)(this._url, init2);
          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 (error40) {
          this.onerror?.(error40);
          throw error40;
        }
      }
      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 fs142 = __require("fs");
    function checkPathExt(path150, 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 i4 = 0; i4 < pathext.length; i4++) {
        var p2 = pathext[i4].toLowerCase();
        if (p2 && path150.substr(-p2.length).toLowerCase() === p2) {
          return true;
        }
      }
      return false;
    }
    __name(checkPathExt, "checkPathExt");
    function checkStat(stat14, path150, options2) {
      if (!stat14.isSymbolicLink() && !stat14.isFile()) {
        return false;
      }
      return checkPathExt(path150, options2);
    }
    __name(checkStat, "checkStat");
    function isexe(path150, options2, cb) {
      fs142.stat(path150, function(er2, stat14) {
        cb(er2, er2 ? false : checkStat(stat14, path150, options2));
      });
    }
    __name(isexe, "isexe");
    function sync2(path150, options2) {
      return checkStat(fs142.statSync(path150), path150, 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 fs142 = __require("fs");
    function isexe(path150, options2, cb) {
      fs142.stat(path150, function(er2, stat14) {
        cb(er2, er2 ? false : checkStat(stat14, options2));
      });
    }
    __name(isexe, "isexe");
    function sync2(path150, options2) {
      return checkStat(fs142.statSync(path150), options2);
    }
    __name(sync2, "sync");
    function checkStat(stat14, options2) {
      return stat14.isFile() && checkMode(stat14, options2);
    }
    __name(checkStat, "checkStat");
    function checkMode(stat14, options2) {
      var mod2 = stat14.mode;
      var uid = stat14.uid;
      var gid = stat14.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 fs142 = __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(path150, 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(resolve42, reject) {
          isexe(path150, options2 || {}, function(er2, is) {
            if (er2) {
              reject(er2);
            } else {
              resolve42(is);
            }
          });
        });
      }
      core(path150, 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(path150, options2) {
      try {
        return core.sync(path150, 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 path150 = __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((i4) => new Promise((resolve42, reject) => {
        if (i4 === pathEnv.length)
          return opt.all && found.length ? resolve42(found) : reject(getNotFoundError(cmd));
        const ppRaw = pathEnv[i4];
        const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
        const pCmd = path150.join(pathPart, cmd);
        const p2 = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
        resolve42(subStep(p2, i4, 0));
      }), "step");
      const subStep = /* @__PURE__ */ __name((p2, i4, ii) => new Promise((resolve42, reject) => {
        if (ii === pathExt.length)
          return resolve42(step(i4 + 1));
        const ext2 = pathExt[ii];
        isexe(p2 + ext2, { pathExt: pathExtExe }, (er2, is) => {
          if (!er2 && is) {
            if (opt.all)
              found.push(p2 + ext2);
            else
              return resolve42(p2 + ext2);
          }
          return resolve42(subStep(p2, i4, 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 i4 = 0; i4 < pathEnv.length; i4++) {
        const ppRaw = pathEnv[i4];
        const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
        const pCmd = path150.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 platform15 = options2.platform || process.platform;
      if (platform15 !== "win32") {
        return "PATH";
      }
      return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
    }, "pathKey");
    module2.exports = pathKey;
    module2.exports.default = pathKey;
  }
});

// node_modules/cross-spawn/lib/util/resolveCommand.js
var require_resolveCommand = __commonJS({
  "node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var path150 = __require("path");
    var which = require_which();
    var getPathKey = require_path_key();
    function resolveCommandAttempt(parsed, withoutPathExt) {
      const env6 = parsed.options.env || process.env;
      const cwd6 = 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 (err2) {
        }
      }
      let resolved;
      try {
        resolved = which.sync(parsed.command, {
          path: env6[getPathKey({ env: env6 })],
          pathExt: withoutPathExt ? path150.delimiter : void 0
        });
      } catch (e4) {
      } finally {
        if (shouldSwitchCwd) {
          process.chdir(cwd6);
        }
      }
      if (resolved) {
        resolved = path150.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 [path150, argument] = match2[0].replace(/#! ?/, "").split(" ");
      const binary2 = path150.split("/").pop();
      if (binary2 === "env") {
        return argument;
      }
      return argument ? `${binary2} ${argument}` : binary2;
    };
  }
});

// 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 fs142 = __require("fs");
    var shebangCommand = require_shebang_command();
    function readShebang(command2) {
      const size = 150;
      const buffer = Buffer.alloc(size);
      let fd;
      try {
        fd = fs142.openSync(command2, "r");
        fs142.readSync(fd, buffer, 0, size, 0);
        fs142.closeSync(fd);
      } catch (e4) {
      }
      return shebangCommand(buffer.toString());
    }
    __name(readShebang, "readShebang");
    module2.exports = readShebang;
  }
});

// node_modules/cross-spawn/lib/parse.js
var require_parse6 = __commonJS({
  "node_modules/cross-spawn/lib/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var path150 = __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 = path150.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 parse17(command2, args2, options2) {
      if (args2 && !Array.isArray(args2)) {
        options2 = args2;
        args2 = null;
      }
      args2 = args2 ? args2.slice(0) : [];
      options2 = Object.assign({}, options2);
      const parsed = {
        command: command2,
        args: args2,
        options: options2,
        file: void 0,
        original: {
          command: command2,
          args: args2
        }
      };
      return options2.shell ? parsed : parseNonShell(parsed);
    }
    __name(parse17, "parse");
    module2.exports = parse17;
  }
});

// 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(name4, arg1) {
        if (name4 === "exit") {
          const err2 = verifyENOENT(arg1, parsed);
          if (err2) {
            return originalEmit.call(cp3, "error", err2);
          }
        }
        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 parse17 = require_parse6();
    var enoent = require_enoent();
    function spawn15(command2, args2, options2) {
      const parsed = parse17(command2, args2, options2);
      const spawned = cp3.spawn(parsed.command, parsed.args, parsed.options);
      enoent.hookChildProcess(spawned, parsed);
      return spawned;
    }
    __name(spawn15, "spawn");
    function spawnSync7(command2, args2, options2) {
      const parsed = parse17(command2, args2, options2);
      const result = cp3.spawnSync(parsed.command, parsed.args, parsed.options);
      result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
      return result;
    }
    __name(spawnSync7, "spawnSync");
    module2.exports = spawn15;
    module2.exports.spawn = spawn15;
    module2.exports.sync = spawnSync7;
    module2.exports._parse = parse17;
    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_types11();
    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 process11 from "node:process";
import { PassThrough as PassThrough3 } from "node:stream";
function getDefaultEnvironment() {
  const env6 = {};
  for (const key of DEFAULT_INHERITED_ENV_VARS) {
    const value = process11.env[key];
    if (value === void 0) {
      continue;
    }
    if (value.startsWith("()")) {
      continue;
    }
    env6[key] = value;
  }
  return env6;
}
function isElectron() {
  return "type" in process11;
}
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 = process11.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((resolve42, 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: process11.platform === "win32" && isElectron(),
            cwd: this._serverParams.cwd
          });
          this._process.on("error", (error40) => {
            reject(error40);
            this.onerror?.(error40);
          });
          this._process.on("spawn", () => {
            resolve42();
          });
          this._process.on("close", (_code) => {
            this._process = void 0;
            this.onclose?.();
          });
          this._process.stdin?.on("error", (error40) => {
            this.onerror?.(error40);
          });
          this._process.stdout?.on("data", (chunk) => {
            this._readBuffer.append(chunk);
            this.processReadBuffer();
          });
          this._process.stdout?.on("error", (error40) => {
            this.onerror?.(error40);
          });
          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 (error40) {
            this.onerror?.(error40);
          }
        }
      }
      async close() {
        if (this._process) {
          const processToClose = this._process;
          this._process = void 0;
          const closePromise = new Promise((resolve42) => {
            processToClose.once("close", () => {
              resolve42();
            });
          });
          try {
            processToClose.stdin?.end();
          } catch {
          }
          await Promise.race([closePromise, new Promise((resolve42) => setTimeout(resolve42, 2e3).unref())]);
          if (processToClose.exitCode === null) {
            try {
              processToClose.kill("SIGTERM");
            } catch {
            }
            await Promise.race([closePromise, new Promise((resolve42) => setTimeout(resolve42, 2e3).unref())]);
          }
          if (processToClose.exitCode === null) {
            try {
              processToClose.kill("SIGKILL");
            } catch {
            }
          }
        }
        this._readBuffer.clear();
      }
      send(message) {
        return new Promise((resolve42) => {
          if (!this._process?.stdin) {
            throw new Error("Not connected");
          }
          const json3 = serializeMessage(message);
          if (this._process.stdin.write(json3)) {
            resolve42();
          } else {
            this._process.stdin.once("drain", resolve42);
          }
        });
      }
    };
    __name(isElectron, "isElectron");
  }
});

// packages/core/dist/src/ide/ide-client.js
import * as dns from "node:dns";
import * as fs41 from "node:fs";
import * as os20 from "node:os";
import * as path38 from "node:path";
function getRealPath(path150) {
  try {
    return fs41.realpathSync(path150);
  } catch (_e2) {
    return path150;
  }
}
function _resetCachedIdeServerHost() {
  hostPromise = void 0;
}
async function isHostResolvable(hostname4) {
  return new Promise((resolve42) => {
    let settled = false;
    const timeout2 = setTimeout(() => {
      if (settled)
        return;
      settled = true;
      resolve42(false);
    }, DNS_LOOKUP_TIMEOUT_MS);
    timeout2.unref?.();
    dns.lookup(hostname4, (err2) => {
      if (settled)
        return;
      settled = true;
      clearTimeout(timeout2);
      resolve42(!err2);
    });
  });
}
async function resolveIdeServerHost() {
  const isInContainer = fs41.existsSync("/.dockerenv") || fs41.existsSync("/run/.containerenv");
  if (!isInContainer) {
    return LOCAL_HOST;
  }
  const reachable = await isHostResolvable(CONTAINER_HOST);
  if (reachable) {
    debugLogger37.debug("Container detected, host.docker.internal is reachable");
    return CONTAINER_HOST;
  }
  debugLogger37.debug("Container detected, but host.docker.internal is NOT reachable, falling back to 127.0.0.1");
  return LOCAL_HOST;
}
async function getIdeServerHost() {
  if (!hostPromise) {
    hostPromise = resolveIdeServerHost();
  }
  return hostPromise;
}
var import_undici2, debugLogger37, IDEConnectionStatus, IdeClient, CONTAINER_HOST, LOCAL_HOST, DNS_LOOKUP_TIMEOUT_MS, hostPromise;
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_types10();
    init_process_utils();
    init_client3();
    init_streamableHttp();
    init_stdio2();
    init_types11();
    import_undici2 = __toESM(require_undici(), 1);
    init_types11();
    init_constants4();
    init_debugLogger();
    debugLogger37 = 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: error40 } = _IdeClient.validateWorkspacePath(workspacePath, process.cwd());
        if (!isValid2) {
          this.setState(IDEConnectionStatus.Disconnected, error40, true);
          return;
        }
        if (this.connectionConfig) {
          if (this.connectionConfig.port) {
            const connected = await this.establishHttpConnection(this.connectionConfig.port);
            if (connected) {
              return;
            }
            const fallbackConnected = await this.tryFallbackPorts();
            if (fallbackConnected) {
              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 promise2 = new Promise((resolve42, reject) => {
          if (!this.client) {
            return reject(new Error("IDE client is not connected."));
          }
          this.diffResponses.set(filePath, resolve42);
          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.`;
              debugLogger37.debug(`Request for openDiff ${filePath} failed with isError:`, errorMessage);
              this.diffResponses.delete(filePath);
              reject(new Error(errorMessage));
            }
          }).catch((err2) => {
            debugLogger37.debug(`Request for openDiff ${filePath} failed:`, err2);
            this.diffResponses.delete(filePath);
            reject(err2);
          });
        });
        promise2.finally(release3);
        return promise2;
      }
      /**
       * 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((resolve42) => {
          release3 = resolve42;
        });
        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.`;
            debugLogger37.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) {
              debugLogger37.debug(`Invalid JSON in closeDiff response for ${filePath}:`, textPart.text);
            }
          }
        } catch (err2) {
          debugLogger37.debug(`Request for closeDiff ${filePath} failed:`, err2);
        }
        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 {
          debugLogger37.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) {
            debugLogger37.debug(`Discovered ${this.availableTools.length} tools from IDE: ${this.availableTools.join(", ")}`);
          } else {
            debugLogger37.debug("IDE supports tool discovery, but no tools are available.");
          }
        } catch (error40) {
          if (error40 instanceof Error && !error40.message?.includes("Method not found")) {
            debugLogger37.error(`Error discovering tools from IDE: ${error40.message}`);
          } else {
            debugLogger37.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) {
              debugLogger37.error(details);
            } else {
              debugLogger37.debug(details);
            }
          }
        }
        if (status === IDEConnectionStatus.Disconnected) {
          ideContextStore.clear();
        }
      }
      static validateWorkspacePath(ideWorkspacePath, cwd6) {
        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(path38.delimiter);
        const realCwd = getRealPath(cwd6);
        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 args2 = [];
        if (argsStr) {
          try {
            const parsedArgs = JSON.parse(argsStr);
            if (Array.isArray(parsedArgs)) {
              args2 = parsedArgs;
            } else {
              debugLogger37.error("QWEN_CODE_IDE_SERVER_STDIO_ARGS must be a JSON array string.");
            }
          } catch (e4) {
            debugLogger37.error("Failed to parse QWEN_CODE_IDE_SERVER_STDIO_ARGS:", e4);
          }
        }
        return { command: command2, args: args2 };
      }
      async getConnectionConfigFromFile() {
        const portFromEnv = this.getPortFromEnv();
        if (portFromEnv) {
          try {
            const ideDir2 = Storage.getGlobalIdeDir();
            const lockFile = path38.join(ideDir2, `${portFromEnv}.lock`);
            const lockFileContents = await fs41.promises.readFile(lockFile, "utf8");
            return JSON.parse(lockFileContents);
          } catch (_2) {
          }
        }
        const legacyConfig = await this.getLegacyConnectionConfig(portFromEnv);
        if (legacyConfig) {
          return legacyConfig;
        }
        const ideDir = Storage.getGlobalIdeDir();
        const configs = await this.getAllConnectionConfigs(ideDir);
        const cwd6 = process.cwd();
        return configs.find((config2) => config2.workspacePath !== void 0 && _IdeClient.validateWorkspacePath(config2.workspacePath, cwd6).isValid);
      }
      // Legacy connection files were written in the global temp directory.
      async getLegacyConnectionConfig(portFromEnv) {
        if (this.ideProcessInfo) {
          try {
            const portFile = path38.join(os20.tmpdir(), `qwen-code-ide-server-${this.ideProcessInfo.pid}.json`);
            const portFileContents = await fs41.promises.readFile(portFile, "utf8");
            return JSON.parse(portFileContents);
          } catch (_2) {
          }
        }
        if (portFromEnv) {
          try {
            const portFile = path38.join(os20.tmpdir(), `qwen-code-ide-server-${portFromEnv}.json`);
            const portFileContents = await fs41.promises.readFile(portFile, "utf8");
            return JSON.parse(portFileContents);
          } catch (_2) {
          }
        }
        return void 0;
      }
      async getAllConnectionConfigs(ideDir) {
        const fileRegex = /^\d+\.lock$/;
        let lockFiles;
        try {
          lockFiles = (await fs41.promises.readdir(ideDir)).map((file2) => file2.toString()).filter((file2) => fileRegex.test(file2));
        } catch (e4) {
          debugLogger37.debug("Failed to read IDE connection directory:", e4);
          return [];
        }
        const fileContents = await Promise.all(lockFiles.map(async (file2) => {
          const fullPath = path38.join(ideDir, file2);
          try {
            const stat14 = await fs41.promises.stat(fullPath);
            const content = await fs41.promises.readFile(fullPath, "utf8");
            try {
              return {
                file: file2,
                fullPath,
                mtimeMs: stat14.mtimeMs,
                parsed: JSON.parse(content)
              };
            } catch (error40) {
              debugLogger37.debug("Failed to parse JSON from lock file: ", error40);
              return void 0;
            }
          } catch (error40) {
            debugLogger37.debug("Failed to read/stat IDE lock file:", error40);
            return void 0;
          }
        }));
        const parsedLockFiles = fileContents.filter((lockFile) => lockFile !== void 0);
        const activeLockFiles = await Promise.all(parsedLockFiles.map(async (lockFile) => ({
          lockFile,
          isStale: await this.cleanupStaleLockFile(lockFile)
        })));
        const staleCount = activeLockFiles.filter(({ isStale }) => isStale).length;
        if (staleCount > 0) {
          debugLogger37.debug(`[cleanupStaleLockFiles] Cleaned up ${staleCount} stale lock file(s)`);
        }
        return activeLockFiles.filter(({ isStale }) => !isStale).map(({ lockFile }) => lockFile).sort((a2, b2) => b2.mtimeMs - a2.mtimeMs).map(({ parsed }) => parsed);
      }
      async cleanupStaleLockFile({ file: file2, fullPath, parsed }) {
        try {
          if (parsed.ppid) {
            try {
              process.kill(parsed.ppid, 0);
              return false;
            } catch {
              debugLogger37.debug(`[cleanupStaleLockFiles] Removing lock file "${file2}" - ppid ${parsed.ppid} no longer exists`);
              await fs41.promises.unlink(fullPath);
              return true;
            }
          }
          if (parsed.workspacePath) {
            if (fs41.existsSync(parsed.workspacePath)) {
              return false;
            }
            debugLogger37.debug(`[cleanupStaleLockFiles] Removing lock file "${file2}" - workspace doesn't exist`);
            await fs41.promises.unlink(fullPath);
            return true;
          }
          return false;
        } catch (error40) {
          debugLogger37.debug(`[cleanupStaleLockFiles] Error checking lock file "${file2}":`, error40);
          return false;
        }
      }
      async tryFallbackPorts() {
        const cwd6 = process.cwd();
        const currentPort = this.connectionConfig?.port;
        const configs = await this.getAllConnectionConfigs(Storage.getGlobalIdeDir());
        const workspaceMatches = [];
        const otherConfigs = [];
        for (const config2 of configs) {
          if (!config2.port || config2.port === currentPort) {
            continue;
          }
          if (config2.workspacePath !== void 0 && _IdeClient.validateWorkspacePath(config2.workspacePath, cwd6).isValid) {
            workspaceMatches.push(config2);
          } else {
            otherConfigs.push(config2);
          }
        }
        for (const config2 of [...workspaceMatches, ...otherConfigs]) {
          const port = config2.port;
          if (!port) {
            continue;
          }
          if (config2.authToken) {
            this.authToken = config2.authToken;
          }
          const connected = await this.establishHttpConnection(port);
          if (connected) {
            this.connectionConfig = config2;
            return true;
          }
        }
        return false;
      }
      createProxyAwareFetch(ideHost) {
        const existingNoProxy = process.env["NO_PROXY"] || "";
        const noProxyHosts = [existingNoProxy, ideHost];
        const agent = new import_undici2.EnvHttpProxyAgent({
          noProxy: noProxyHosts.filter(Boolean).join(",")
        });
        const undiciPromise = Promise.resolve().then(() => __toESM(require_undici(), 1));
        return async (url3, init2) => {
          const { fetch: fetchFn } = await undiciPromise;
          const fetchOptions = {
            ...init2,
            dispatcher: agent
          };
          const options2 = fetchOptions;
          const response = await fetchFn(url3, 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 {
            debugLogger37.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 {
            debugLogger37.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 {
            debugLogger37.debug(`No resolver found for ${filePath}`);
          }
        });
      }
      async establishHttpConnection(port) {
        const connected = await this.tryHttpConnect(port, LOCAL_HOST);
        if (connected) {
          return true;
        }
        const ideHost = await getIdeServerHost();
        if (ideHost === CONTAINER_HOST) {
          debugLogger37.debug(`Connection to ${LOCAL_HOST}:${port} failed, retrying with ${CONTAINER_HOST}`);
          return this.tryHttpConnect(port, CONTAINER_HOST);
        }
        return false;
      }
      async tryHttpConnect(port, host) {
        let transport;
        try {
          debugLogger37.debug(`Attempting to connect to IDE via HTTP at ${host}:${port}`);
          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://${host}:${port}/mcp`), {
            fetch: this.createProxyAwareFetch(host),
            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 (error40) {
          debugLogger37.debug(`HTTP connection to ${host}:${port} failed:`, error40);
          if (transport) {
            try {
              await transport.close();
            } catch (closeError) {
              debugLogger37.debug("Failed to close transport:", closeError);
            }
          }
          return false;
        }
      }
      async establishStdioConnection({ command: command2, args: args2 }) {
        let transport;
        try {
          debugLogger37.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: args2
          });
          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) {
              debugLogger37.debug("Failed to close transport:", closeError);
            }
          }
          return false;
        }
      }
    };
    CONTAINER_HOST = "host.docker.internal";
    LOCAL_HOST = "127.0.0.1";
    DNS_LOOKUP_TIMEOUT_MS = 3e3;
    __name(_resetCachedIdeServerHost, "_resetCachedIdeServerHost");
    __name(isHostResolvable, "isHostResolvable");
    __name(resolveIdeServerHost, "resolveIdeServerHost");
    __name(getIdeServerHost, "getIdeServerHost");
  }
});

// packages/core/dist/src/core/coreToolScheduler.js
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 parts2 = [];
  for (const part of Array.isArray(input) ? input : [input]) {
    if (typeof part === "string") {
      parts2.push({ text: part });
    } else if (part) {
      parts2.push(part);
    }
  }
  return parts2;
}
function isConcurrencySafe(call) {
  if (call.request.name === ToolNames.AGENT)
    return true;
  if (call.tool.kind === Kind.Execute) {
    const command2 = call.request.args.command;
    if (typeof command2 !== "string")
      return false;
    try {
      return isShellCommandReadOnly(stripShellWrapper(command2));
    } catch {
      return false;
    }
  }
  return CONCURRENCY_SAFE_KINDS.has(call.tool.kind);
}
function partitionToolCalls(calls) {
  return calls.reduce((batches, call) => {
    const safe = isConcurrencySafe(call);
    const lastBatch = batches[batches.length - 1];
    if (safe && lastBatch?.concurrent) {
      lastBatch.calls.push(call);
    } else {
      batches.push({ concurrent: safe, calls: [call] });
    }
    return batches;
  }, []);
}
var import_fast_levenshtein, debugLogger38, TRUNCATION_PARAM_GUIDANCE, TRUNCATION_EDIT_REJECTION, VALIDATION_RETRY_LOOP_THRESHOLD, RETRY_LOOP_STOP_DIRECTIVE, createErrorResponse, CoreToolScheduler;
var init_coreToolScheduler = __esm({
  "packages/core/dist/src/core/coreToolScheduler.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_toolHookTriggers();
    init_types6();
    init_src2();
    init_tool_names();
    init_tools();
    init_shellReadOnlyChecker();
    init_shell_utils();
    init_permission_helpers();
    init_generateContentResponseUtilities();
    init_modifiable_tool();
    init_lib();
    import_fast_levenshtein = __toESM(require_levenshtein(), 1);
    init_prompts();
    init_shell();
    init_ide_client();
    debugLogger38 = createDebugLogger("TOOL_SCHEDULER");
    TRUNCATION_PARAM_GUIDANCE = "Note: Your previous response was truncated due to max_tokens limit, which caused incomplete tool call parameters. Please retry the tool call with complete parameters. If the content is too large for a single response, you MUST split it into smaller parts: first write_file with a skeleton/partial content, then use edit to add the remaining sections incrementally.";
    TRUNCATION_EDIT_REJECTION = "Your previous response was truncated due to max_tokens limit, which produced incomplete file content. The tool call has been rejected to prevent writing truncated content to the file. You MUST split the content into smaller parts: first write_file with a skeleton/partial content, then use edit to add the remaining sections incrementally. Do NOT retry with the same large content.";
    __name(createFunctionResponsePart, "createFunctionResponsePart");
    __name(convertToFunctionResponse, "convertToFunctionResponse");
    __name(toParts, "toParts");
    VALIDATION_RETRY_LOOP_THRESHOLD = 3;
    RETRY_LOOP_STOP_DIRECTIVE = "\n\n\u26A0\uFE0F RETRY LOOP DETECTED: This tool call has failed validation multiple times with the same error. STOP retrying the same approach. Re-examine the tool schema and parameter requirements, then try a fundamentally different approach. If you cannot resolve the validation error, explain the issue to the user instead of retrying.";
    createErrorResponse = /* @__PURE__ */ __name((request4, error40, errorType) => ({
      callId: request4.callId,
      error: error40,
      responseParts: [
        {
          functionResponse: {
            id: request4.callId,
            name: request4.name,
            response: { error: error40.message }
          }
        }
      ],
      resultDisplay: error40.message,
      errorType,
      contentLength: error40.message.length
    }), "createErrorResponse");
    __name(isConcurrencySafe, "isConcurrencySafe");
    __name(partitionToolCalls, "partitionToolCalls");
    CoreToolScheduler = class {
      static {
        __name(this, "CoreToolScheduler");
      }
      toolRegistry;
      toolCalls = [];
      outputUpdateHandler;
      onAllToolCallsComplete;
      onToolCallsUpdate;
      getPreferredEditor;
      config;
      onEditorClose;
      chatRecordingService;
      isFinalizingToolCalls = false;
      isScheduling = false;
      validationRetryCounts = /* @__PURE__ */ new Map();
      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": {
              this.clearRetryCountsForTool(currentCall.request.name);
              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 (waitingCall.confirmationDetails.type === "plan") {
                  resultDisplay = {
                    type: "plan_summary",
                    message: "Plan was rejected. Remaining in plan mode.",
                    plan: waitingCall.confirmationDetails.plan,
                    rejected: true
                  };
                }
              } 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,
                executionStartTime: Date.now(),
                outcome,
                invocation
              };
            default: {
              const exhaustiveCheck = newStatus;
              return exhaustiveCheck;
            }
          }
        });
        this.notifyToolCallsUpdate();
        this.checkAndNotifyCompletion();
      }
      setArgsInternal(targetCallId, args2) {
        this.toolCalls = this.toolCalls.map((call) => {
          if (call.request.callId !== targetCallId || call.status === "error") {
            return call;
          }
          const invocationOrError = this.buildInvocation(call.tool, args2, targetCallId);
          if (invocationOrError instanceof Error) {
            const response = createErrorResponse(call.request, invocationOrError, ToolErrorType.INVALID_TOOL_PARAMS);
            return {
              request: { ...call.request, args: args2 },
              status: "error",
              tool: call.tool,
              response
            };
          }
          return {
            ...call,
            request: { ...call.request, args: args2 },
            invocation: invocationOrError
          };
        });
      }
      isRunning() {
        return this.isFinalizingToolCalls || this.toolCalls.some((call) => call.status === "executing" || call.status === "awaiting_approval");
      }
      buildInvocation(tool, args2, callId) {
        try {
          const invocation = tool.build(structuredClone(args2));
          if (callId) {
            const maybeAware = invocation;
            if (typeof maybeAware.setCallId === "function") {
              maybeAware.setCallId(callId);
            }
          }
          return invocation;
        } 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.
       */
      async getToolNotFoundMessage(unknownToolName, topN = 3) {
        const skillTool = await this.toolRegistry.ensureTool(ToolNames.SKILL);
        if (skillTool && "getAvailableSkillNames" in 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 matches2 = allToolNames.map((toolName) => ({
          name: toolName,
          distance: import_fast_levenshtein.default.get(unknownToolName, toolName)
        }));
        matches2.sort((a2, b2) => a2.distance - b2.distance);
        const topNResults = matches2.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((resolve42, 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);
                resolve42();
              }, "resolve"),
              reject: /* @__PURE__ */ __name((reason) => {
                signal.removeEventListener("abort", abortHandler);
                reject(reason);
              }, "reject")
            });
          });
        }
        return this._schedule(request4, signal);
      }
      /**
       * Removes all validation retry counters for the given tool. Keys are
       * "<toolName>:<errorMessage>", so a plain `Map.delete(toolName)` would not
       * match anything.
       */
      clearRetryCountsForTool(toolName) {
        const prefix = `${toolName}:`;
        for (const key of this.validationRetryCounts.keys()) {
          if (key.startsWith(prefix)) {
            this.validationRetryCounts.delete(key);
          }
        }
      }
      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];
          if (this.validationRetryCounts.size > 0) {
            const currentToolNames = new Set(requestsToProcess.map((r5) => r5.name));
            for (const key of [...this.validationRetryCounts.keys()]) {
              const sep13 = key.indexOf(":");
              const toolName = sep13 === -1 ? key : key.slice(0, sep13);
              if (!currentToolNames.has(toolName)) {
                this.validationRetryCounts.delete(key);
              }
            }
          }
          const newToolCalls = [];
          for (const reqInfo of requestsToProcess) {
            const pm = this.config.getPermissionManager?.();
            if (pm && !await pm.isToolEnabled(reqInfo.name)) {
              const matchingRule = pm.findMatchingDenyRule({
                toolName: reqInfo.name
              });
              const ruleInfo = matchingRule ? ` Matching deny rule: "${matchingRule}".` : "";
              const permissionErrorMessage = `Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined.${ruleInfo}`;
              newToolCalls.push({
                status: "error",
                request: reqInfo,
                response: createErrorResponse(reqInfo, new Error(permissionErrorMessage), ToolErrorType.EXECUTION_DENIED),
                durationMs: 0
              });
              continue;
            }
            if (!pm) {
              const excludeTools = this.config.getPermissionsDeny?.() ?? 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.`;
                  newToolCalls.push({
                    status: "error",
                    request: reqInfo,
                    response: createErrorResponse(reqInfo, new Error(permissionErrorMessage), ToolErrorType.EXECUTION_DENIED),
                    durationMs: 0
                  });
                  continue;
                }
              }
            }
            const toolInstance = await this.toolRegistry.ensureTool(reqInfo.name);
            if (!toolInstance) {
              const errorMessage = await this.getToolNotFoundMessage(reqInfo.name);
              newToolCalls.push({
                status: "error",
                request: reqInfo,
                response: createErrorResponse(reqInfo, new Error(errorMessage), ToolErrorType.TOOL_NOT_REGISTERED),
                durationMs: 0
              });
              continue;
            }
            if (reqInfo.wasOutputTruncated && toolInstance.kind === Kind.Edit) {
              const truncationError = new Error(TRUNCATION_EDIT_REJECTION);
              newToolCalls.push({
                status: "error",
                request: reqInfo,
                tool: toolInstance,
                response: createErrorResponse(reqInfo, truncationError, ToolErrorType.OUTPUT_TRUNCATED),
                durationMs: 0
              });
              continue;
            }
            const invocationOrError = this.buildInvocation(toolInstance, reqInfo.args, reqInfo.callId);
            if (invocationOrError instanceof Error) {
              const baseError = reqInfo.wasOutputTruncated ? new Error(`${invocationOrError.message} ${TRUNCATION_PARAM_GUIDANCE}`) : invocationOrError;
              const errorKey = `${reqInfo.name}:${baseError.message}`;
              const count = (this.validationRetryCounts.get(errorKey) ?? 0) + 1;
              for (const key of this.validationRetryCounts.keys()) {
                if (key.startsWith(`${reqInfo.name}:`) && key !== errorKey) {
                  this.validationRetryCounts.delete(key);
                }
              }
              this.validationRetryCounts.set(errorKey, count);
              const finalError = count >= VALIDATION_RETRY_LOOP_THRESHOLD ? new Error(`${baseError.message}${RETRY_LOOP_STOP_DIRECTIVE}`) : baseError;
              newToolCalls.push({
                status: "error",
                request: reqInfo,
                tool: toolInstance,
                response: createErrorResponse(reqInfo, finalError, ToolErrorType.INVALID_TOOL_PARAMS),
                durationMs: 0
              });
              continue;
            }
            this.clearRetryCountsForTool(reqInfo.name);
            newToolCalls.push({
              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 defaultPermission = await invocation.getDefaultPermission();
              const pm = this.config.getPermissionManager?.();
              const toolParams = invocation.params;
              const pmCtx = buildPermissionCheckContext(reqInfo.name, toolParams, this.config.getTargetDir?.() ?? "");
              const { finalPermission, pmForcedAsk } = await evaluatePermissionRules(pm, defaultPermission, pmCtx);
              const approvalMode = this.config.getApprovalMode();
              const isPlanMode = approvalMode === ApprovalMode.PLAN;
              const isExitPlanModeTool = reqInfo.name === "exit_plan_mode";
              if (finalPermission === "allow") {
                this.setToolCallOutcome(reqInfo.callId, ToolConfirmationOutcome.ProceedAlways);
                this.setStatusInternal(reqInfo.callId, "scheduled");
                continue;
              }
              if (finalPermission === "deny") {
                let denyMessage;
                if (defaultPermission === "deny") {
                  denyMessage = `Tool "${reqInfo.name}" is denied: command substitution is not allowed for security reasons.`;
                } else {
                  const matchingRule = pm?.findMatchingDenyRule(pmCtx);
                  const ruleInfo = matchingRule ? ` Matching deny rule: "${matchingRule}".` : "";
                  denyMessage = `Tool "${reqInfo.name}" is denied by permission rules.${ruleInfo}`;
                }
                this.setStatusInternal(reqInfo.callId, "error", createErrorResponse(reqInfo, new Error(denyMessage), ToolErrorType.EXECUTION_DENIED));
                continue;
              }
              const isAskUserQuestionTool = reqInfo.name === ToolNames.ASK_USER_QUESTION;
              let confirmationDetails;
              if (approvalMode === ApprovalMode.YOLO && !isAskUserQuestionTool) {
                this.setToolCallOutcome(reqInfo.callId, ToolConfirmationOutcome.ProceedAlways);
                this.setStatusInternal(reqInfo.callId, "scheduled");
              } else {
                confirmationDetails = await invocation.getConfirmationDetails(signal);
                injectPermissionRulesIfMissing(confirmationDetails, pmCtx);
                if (isPlanMode && !isExitPlanModeTool && !isAskUserQuestionTool && confirmationDetails.type !== "info") {
                  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
                  });
                  continue;
                }
                if (approvalMode === ApprovalMode.AUTO_EDIT && (confirmationDetails.type === "edit" || confirmationDetails.type === "info")) {
                  this.setToolCallOutcome(reqInfo.callId, ToolConfirmationOutcome.ProceedAlways);
                  this.setStatusInternal(reqInfo.callId, "scheduled");
                  continue;
                }
                const isNonInteractiveDeny = !this.config.isInteractive() && !this.config.getExperimentalZedIntegration() && this.config.getInputFormat() !== InputFormat.STREAM_JSON;
                if (isNonInteractiveDeny) {
                  const errorMessage = `Qwen Code requires permission to use "${reqInfo.name}", but that permission was declined (non-interactive mode cannot prompt for confirmation).`;
                  this.setStatusInternal(reqInfo.callId, "error", createErrorResponse(reqInfo, new Error(errorMessage), ToolErrorType.EXECUTION_DENIED));
                  continue;
                }
                const messageBus = this.config.getMessageBus();
                const hooksEnabled = !this.config.getDisableAllHooks();
                if (hooksEnabled && messageBus) {
                  const permissionMode = String(this.config.getApprovalMode());
                  const hookResult = await firePermissionRequestHook(messageBus, reqInfo.name, reqInfo.args || {}, permissionMode);
                  if (hookResult.hasDecision) {
                    if (hookResult.shouldAllow) {
                      if (hookResult.updatedInput && typeof reqInfo.args === "object") {
                        this.setArgsInternal(reqInfo.callId, hookResult.updatedInput);
                      }
                      await confirmationDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce);
                      this.setToolCallOutcome(reqInfo.callId, ToolConfirmationOutcome.ProceedOnce);
                      this.setStatusInternal(reqInfo.callId, "scheduled");
                    } else {
                      const cancelPayload = hookResult.denyMessage ? { cancelMessage: hookResult.denyMessage } : void 0;
                      await confirmationDetails.onConfirm(ToolConfirmationOutcome.Cancel, cancelPayload);
                      this.setToolCallOutcome(reqInfo.callId, ToolConfirmationOutcome.Cancel);
                      this.setStatusInternal(reqInfo.callId, "error", createErrorResponse(reqInfo, new Error(hookResult.denyMessage || `Permission denied by hook for "${reqInfo.name}"`), ToolErrorType.EXECUTION_DENIED));
                    }
                    continue;
                  }
                }
                if (this.config.getShouldAvoidPermissionPrompts?.()) {
                  const errorMessage = `Tool "${reqInfo.name}" requires permission, but background agents cannot prompt for confirmation. The tool call was denied.`;
                  this.setStatusInternal(reqInfo.callId, "error", createErrorResponse(reqInfo, new Error(errorMessage), ToolErrorType.EXECUTION_DENIED));
                  continue;
                }
                this.openIdeDiffIfEnabled(confirmationDetails, reqInfo.callId, signal);
                const originalOnConfirm = confirmationDetails.onConfirm;
                const wrappedConfirmationDetails = {
                  ...confirmationDetails,
                  // When PM has an explicit 'ask' rule, 'always allow' would be
                  // ineffective because ask takes priority over allow.
                  // Hide the option so users aren't misled.
                  ...pmForcedAsk ? { hideAlwaysAllow: true } : {},
                  onConfirm: /* @__PURE__ */ __name((outcome, payload) => this.handleConfirmationResponse(reqInfo.callId, originalOnConfirm, outcome, signal, payload), "onConfirm")
                };
                this.setStatusInternal(reqInfo.callId, "awaiting_approval", wrappedConfirmationDetails);
                if (hooksEnabled && messageBus) {
                  fireNotificationHook(messageBus, `Qwen Code needs your permission to use ${reqInfo.name}`, NotificationType.PermissionPrompt, "Permission needed").catch((error40) => {
                    debugLogger38.warn(`Permission prompt notification hook failed: ${error40 instanceof Error ? error40.message : String(error40)}`);
                  });
                }
              }
            } catch (error40) {
              if (signal.aborted) {
                this.setStatusInternal(reqInfo.callId, "cancelled", "Tool call cancelled by user.");
                continue;
              }
              this.setStatusInternal(reqInfo.callId, "error", createErrorResponse(reqInfo, error40 instanceof Error ? error40 : new Error(String(error40)), 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");
        if (!toolCall)
          return;
        await originalOnConfirm(outcome, payload);
        if (outcome === ToolConfirmationOutcome.ProceedAlways || outcome === ToolConfirmationOutcome.ProceedAlwaysProject || outcome === ToolConfirmationOutcome.ProceedAlwaysUser) {
          await persistPermissionOutcome(outcome, toolCall.confirmationDetails, this.config.getOnPersistPermissionRule?.(), this.config.getPermissionManager?.(), payload);
          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);
      }
      /**
       * Opens an IDE diff view for edit-type tools when IDE mode is active.
       * The IDE resolution is handled asynchronously — if the user accepts or
       * rejects from the IDE, it triggers handleConfirmationResponse.
       *
       * Uses confirmationDetails.filePath / newContent (the same data shown in
       * CLI diff) rather than ModifyContext so that the IDE diff is always
       * consistent with the CLI and with resolveDiffFromCli.
       */
      async openIdeDiffIfEnabled(confirmationDetails, callId, signal) {
        if (confirmationDetails.type !== "edit" || !this.config.getIdeMode()) {
          return;
        }
        let resolution;
        try {
          const ideClient = await IdeClient.getInstance();
          if (!ideClient.isDiffingEnabled())
            return;
          resolution = await ideClient.openDiff(confirmationDetails.filePath, confirmationDetails.newContent);
        } catch (error40) {
          if (!signal.aborted) {
            debugLogger38.warn(`IDE diff open failed for ${callId}: ${error40 instanceof Error ? error40.message : String(error40)}`);
          }
          return;
        }
        const still = this.toolCalls.find((c4) => c4.request.callId === callId && c4.status === "awaiting_approval");
        if (!still)
          return;
        if (resolution.status === "accepted") {
          const userEdited = resolution.content != null && resolution.content !== confirmationDetails.newContent;
          await this.handleConfirmationResponse(callId, confirmationDetails.onConfirm, ToolConfirmationOutcome.ProceedOnce, signal, userEdited ? { newContent: resolution.content } : void 0);
        } else {
          await this.handleConfirmationResponse(callId, confirmationDetails.onConfirm, ToolConfirmationOutcome.Cancel, 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) {
        const confirmDetails = toolCall.confirmationDetails;
        if (confirmDetails.type !== "edit" || !isModifiableDeclarativeTool(toolCall.tool) || !payload.newContent) {
          return;
        }
        const currentContent = confirmDetails.originalContent ?? "";
        const modifyContext = toolCall.tool.getModifyContext(signal);
        const updatedParams = modifyContext.createUpdatedParams(currentContent, payload.newContent, toolCall.request.args);
        const updatedDiff = createPatch(confirmDetails.filePath, currentContent, payload.newContent, "Current", "Proposed");
        this.setArgsInternal(toolCall.request.callId, updatedParams);
        this.setStatusInternal(toolCall.request.callId, "awaiting_approval", {
          ...confirmDetails,
          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");
          const batches = partitionToolCalls(callsToExecute);
          for (const batch of batches) {
            if (batch.concurrent && batch.calls.length > 1) {
              await this.runConcurrently(batch.calls, signal);
            } else {
              for (const call of batch.calls) {
                await this.executeSingleToolCall(call, signal);
              }
            }
          }
        }
      }
      /**
       * Execute multiple tool calls concurrently with a concurrency cap.
       */
      async runConcurrently(calls, signal) {
        const parsed = parseInt(process.env["QWEN_CODE_MAX_TOOL_CONCURRENCY"] || "", 10);
        const maxConcurrency = Number.isFinite(parsed) && parsed >= 1 ? parsed : 10;
        const executing = /* @__PURE__ */ new Set();
        for (const call of calls) {
          const p2 = this.executeSingleToolCall(call, signal).finally(() => {
            executing.delete(p2);
          });
          executing.add(p2);
          if (executing.size >= maxConcurrency) {
            await Promise.race(executing);
          }
        }
        await Promise.all(executing);
      }
      async executeSingleToolCall(toolCall, signal) {
        if (toolCall.status !== "scheduled")
          return;
        const scheduledCall = toolCall;
        const { callId, name: toolName } = scheduledCall.request;
        const invocation = scheduledCall.invocation;
        const toolInput = scheduledCall.request.args;
        const toolUseId = generateToolUseId();
        const messageBus = this.config.getMessageBus();
        const hooksEnabled = !this.config.getDisableAllHooks();
        if (hooksEnabled && messageBus) {
          const permissionMode = this.config.getApprovalMode();
          const preHookResult = await firePreToolUseHook(messageBus, toolName, toolInput, toolUseId, permissionMode);
          if (!preHookResult.shouldProceed) {
            const blockMessage = preHookResult.blockReason || "Tool execution blocked by hook";
            const errorResponse = createErrorResponse(scheduledCall.request, new Error(blockMessage), ToolErrorType.EXECUTION_DENIED);
            this.setStatusInternal(callId, "error", errorResponse);
            return;
          }
        }
        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 promise2;
        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");
          promise2 = invocation.execute(signal, liveOutputCallback, shellExecutionConfig, setPidCallback);
        } else {
          promise2 = invocation.execute(signal, liveOutputCallback, shellExecutionConfig);
        }
        try {
          const toolResult = await promise2;
          if (signal.aborted) {
            if (hooksEnabled && messageBus) {
              const failureHookResult = await firePostToolUseFailureHook(messageBus, toolUseId, toolName, toolInput, "User cancelled tool execution.", true, this.config.getApprovalMode());
              let cancelMessage = "User cancelled tool execution.";
              if (failureHookResult.additionalContext) {
                cancelMessage += `

${failureHookResult.additionalContext}`;
              }
              this.setStatusInternal(callId, "cancelled", cancelMessage);
            } else {
              this.setStatusInternal(callId, "cancelled", "User cancelled tool execution.");
            }
            return;
          }
          if (toolResult.error === void 0) {
            let content = toolResult.llmContent;
            const contentLength = typeof content === "string" ? content.length : void 0;
            if (hooksEnabled && messageBus) {
              const toolResponse = {
                llmContent: content,
                returnDisplay: toolResult.returnDisplay
              };
              const permissionMode = this.config.getApprovalMode();
              const postHookResult = await firePostToolUseHook(messageBus, toolName, toolInput, toolResponse, toolUseId, permissionMode);
              if (postHookResult.additionalContext) {
                content = appendAdditionalContext(content, postHookResult.additionalContext);
              }
              if (postHookResult.shouldStop) {
                const stopMessage = postHookResult.stopReason || "Execution stopped by hook";
                const errorResponse = createErrorResponse(scheduledCall.request, new Error(stopMessage), ToolErrorType.EXECUTION_DENIED);
                this.setStatusInternal(callId, "error", errorResponse);
                return;
              }
            }
            const filePath = toolInput?.["file_path"];
            if (typeof filePath === "string") {
              const rulesCtx = this.config.getConditionalRulesRegistry()?.matchAndConsume(filePath);
              if (rulesCtx) {
                content = appendAdditionalContext(content, `<system-reminder>
${rulesCtx}
</system-reminder>`);
              }
            }
            const response = convertToFunctionResponse(toolName, callId, content);
            const successResponse = {
              callId,
              responseParts: response,
              resultDisplay: toolResult.returnDisplay,
              error: void 0,
              errorType: void 0,
              contentLength,
              // Propagate modelOverride from skill tools. Use `in` to distinguish
              // "skill returned undefined (inherit)" from "non-skill tool (no field)".
              ..."modelOverride" in toolResult ? { modelOverride: toolResult.modelOverride } : {}
            };
            this.setStatusInternal(callId, "success", successResponse);
          } else {
            let errorMessage = toolResult.error.message;
            if (hooksEnabled && messageBus) {
              const failureHookResult = await firePostToolUseFailureHook(messageBus, toolUseId, toolName, toolInput, toolResult.error.message, false, this.config.getApprovalMode());
              if (failureHookResult.additionalContext) {
                errorMessage += `

${failureHookResult.additionalContext}`;
              }
            }
            const error40 = new Error(errorMessage);
            const errorResponse = createErrorResponse(scheduledCall.request, error40, toolResult.error.type);
            this.setStatusInternal(callId, "error", errorResponse);
          }
        } catch (executionError) {
          const errorMessage = executionError instanceof Error ? executionError.message : String(executionError);
          if (signal.aborted) {
            if (hooksEnabled && messageBus) {
              const failureHookResult = await firePostToolUseFailureHook(messageBus, toolUseId, toolName, toolInput, "User cancelled tool execution.", true, this.config.getApprovalMode());
              let cancelMessage = "User cancelled tool execution.";
              if (failureHookResult.additionalContext) {
                cancelMessage += `

${failureHookResult.additionalContext}`;
              }
              this.setStatusInternal(callId, "cancelled", cancelMessage);
            } else {
              this.setStatusInternal(callId, "cancelled", "User cancelled tool execution.");
            }
            return;
          } else {
            let exceptionErrorMessage = errorMessage;
            if (hooksEnabled && messageBus) {
              const failureHookResult = await firePostToolUseFailureHook(messageBus, toolUseId, toolName, toolInput, errorMessage, false, this.config.getApprovalMode());
              if (failureHookResult.additionalContext) {
                exceptionErrorMessage += `

${failureHookResult.additionalContext}`;
              }
            }
            this.setStatusInternal(callId, "error", createErrorResponse(scheduledCall.request, executionError instanceof Error ? new Error(exceptionErrorMessage) : 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 defaultPermission = await pendingTool.invocation.getDefaultPermission();
            const toolParams = pendingTool.invocation.params;
            const pmCtx = buildPermissionCheckContext(pendingTool.request.name, toolParams, this.config.getTargetDir?.() ?? "");
            const { finalPermission } = await evaluatePermissionRules(this.config.getPermissionManager?.(), defaultPermission, pmCtx);
            if (finalPermission === "allow") {
              this.setToolCallOutcome(pendingTool.request.callId, ToolConfirmationOutcome.ProceedAlways);
              this.setStatusInternal(pendingTool.request.callId, "scheduled");
            }
          } catch (error40) {
            debugLogger38.error(`Error checking confirmation for tool ${pendingTool.request.callId}:`, error40);
          }
        }
      }
    };
  }
});

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

// packages/core/dist/src/utils/getFolderStructure.js
import * as fs42 from "node:fs/promises";
import * as path39 from "node:path";
async function readFullStructure(rootPath, options2) {
  const rootName = path39.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 fs42.readdir(currentPath, { withFileTypes: true });
      entries = rawEntries.sort((a2, b2) => a2.name.localeCompare(b2.name));
    } catch (error40) {
      if (isNodeError(error40) && (error40.code === "EACCES" || error40.code === "ENOENT")) {
        debugLogger39.warn(`Warning: Could not read directory ${currentPath}: ${error40.message}`);
        if (currentPath === rootPath && error40.code === "ENOENT") {
          return null;
        }
        continue;
      }
      throw error40;
    }
    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 = path39.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 = path39.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}${path39.sep}${node.isIgnored ? TRUNCATION_INDICATOR : ""}`);
  }
  const indentForChildren = isProcessingRootNode ? "" : currentIndent + (isLastChildOfParent ? "    " : "\u2502   ");
  const fileCount = node.files.length;
  for (let i4 = 0; i4 < fileCount; i4++) {
    const isLastFileAmongSiblings = i4 === 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[i4]}`);
  }
  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 i4 = 0; i4 < subFolderCount; i4++) {
    const isLastSubfolderAmongSiblings = i4 === subFolderCount - 1 && !node.hasMoreSubfolders;
    formatStructure(node.subFolders[i4], indentForChildren, isLastSubfolderAmongSiblings, false, builder);
  }
  if (node.hasMoreSubfolders) {
    builder.push(`${indentForChildren}\u2514\u2500\u2500\u2500${TRUNCATION_INDICATOR}`);
  }
}
async function getFolderStructure(directory, options2) {
  const resolvedPath = path39.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}${path39.sep}
${structureLines.join("\n")}`;
  } catch (error40) {
    debugLogger39.error(`Error getting folder structure for ${resolvedPath}:`, error40);
    return `Error processing directory "${resolvedPath}": ${getErrorMessage(error40)}`;
  }
}
var debugLogger39, 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_constants5();
    init_debugLogger();
    debugLogger39 = 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 platform15 = 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: ${platform15}
${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: STARTUP_CONTEXT_MODEL_ACK }]
    },
    ...extraHistory ?? []
  ];
}
function stripStartupContext(history) {
  if (history.length < 2)
    return history;
  const secondEntry = history[1];
  const ackText = secondEntry?.parts?.[0]?.text;
  if (secondEntry?.role === "model" && ackText === STARTUP_CONTEXT_MODEL_ACK) {
    return history.slice(2);
  }
  return history;
}
var STARTUP_CONTEXT_MODEL_ACK;
var init_environmentContext = __esm({
  "packages/core/dist/src/utils/environmentContext.js"() {
    "use strict";
    init_esbuild_shims();
    init_getFolderStructure();
    __name(getDirectoryContextString, "getDirectoryContextString");
    __name(getEnvironmentContext, "getEnvironmentContext");
    STARTUP_CONTEXT_MODEL_ACK = "Got it. Thanks for the context!";
    __name(getInitialChatHistory, "getInitialChatHistory");
    __name(stripStartupContext, "stripStartupContext");
  }
});

// packages/core/dist/src/agents/runtime/agent-events.js
import { EventEmitter as EventEmitter3 } from "events";
var AgentEventType, AgentEventEmitter;
var init_agent_events = __esm({
  "packages/core/dist/src/agents/runtime/agent-events.js"() {
    "use strict";
    init_esbuild_shims();
    (function(AgentEventType2) {
      AgentEventType2["START"] = "start";
      AgentEventType2["ROUND_START"] = "round_start";
      AgentEventType2["ROUND_END"] = "round_end";
      AgentEventType2["ROUND_TEXT"] = "round_text";
      AgentEventType2["STREAM_TEXT"] = "stream_text";
      AgentEventType2["TOOL_CALL"] = "tool_call";
      AgentEventType2["TOOL_RESULT"] = "tool_result";
      AgentEventType2["TOOL_OUTPUT_UPDATE"] = "tool_output_update";
      AgentEventType2["TOOL_WAITING_APPROVAL"] = "tool_waiting_approval";
      AgentEventType2["USAGE_METADATA"] = "usage_metadata";
      AgentEventType2["EXTERNAL_MESSAGE"] = "external_message";
      AgentEventType2["FINISH"] = "finish";
      AgentEventType2["ERROR"] = "error";
      AgentEventType2["STATUS_CHANGE"] = "status_change";
    })(AgentEventType || (AgentEventType = {}));
    AgentEventEmitter = class {
      static {
        __name(this, "AgentEventEmitter");
      }
      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/agents/runtime/agent-headless.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 debugLogger40, ContextState, AgentHeadless;
var init_agent_headless = __esm({
  "packages/core/dist/src/agents/runtime/agent-headless.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_agent_events();
    init_agent_types();
    init_loggers();
    init_types4();
    init_agent_core();
    init_models();
    debugLogger40 = 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");
    AgentHeadless = class _AgentHeadless {
      static {
        __name(this, "AgentHeadless");
      }
      core;
      finalText = "";
      terminateMode = AgentTerminateMode.ERROR;
      externalMessageProvider;
      constructor(core) {
        this.core = core;
      }
      /**
       * Creates a new AgentHeadless 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.
       * @param eventEmitter - Optional event emitter for streaming events to UI.
       * @param hooks - Optional lifecycle hooks.
       */
      static async create(name4, runtimeContext, promptConfig, modelConfig, runConfig, toolConfig, eventEmitter, hooks) {
        const core = new AgentCore(name4, runtimeContext, promptConfig, modelConfig, runConfig, toolConfig, eventEmitter, hooks);
        return new _AgentHeadless(core);
      }
      /**
       * Executes the task in headless mode.
       *
       * This method orchestrates the subagent's execution lifecycle:
       * 1. Creates a chat session
       * 2. Prepares tools
       * 3. Runs the reasoning loop until completion/termination
       * 4. Emits start/finish/error events
       * 5. Records telemetry
       *
       * @param context - The current context state containing variables for prompt templating.
       * @param externalSignal - Optional abort signal for external cancellation.
       */
      async execute(context2, externalSignal) {
        const initialTaskText = String(context2.get("task_prompt") ?? "Get Started!");
        this.core.pushMessage("user", initialTaskText);
        const chat = await this.core.createChat(context2);
        if (!chat) {
          this.terminateMode = AgentTerminateMode.ERROR;
          return;
        }
        const abortController = new AbortController();
        const onExternalAbort = /* @__PURE__ */ __name(() => {
          abortController.abort();
        }, "onExternalAbort");
        if (externalSignal) {
          externalSignal.addEventListener("abort", onExternalAbort);
        }
        if (externalSignal?.aborted) {
          abortController.abort();
        }
        const toolsList = await this.core.prepareTools();
        const initialMessages = [
          { role: "user", parts: [{ text: initialTaskText }] }
        ];
        const startTime = Date.now();
        this.core.executionStats.startTimeMs = startTime;
        this.core.stats.start(startTime);
        try {
          this.core.eventEmitter?.emit(AgentEventType.START, {
            subagentId: this.core.subagentId,
            name: this.core.name,
            model: this.core.modelConfig.model || this.core.runtimeContext.getModel() || DEFAULT_QWEN_MODEL,
            tools: (this.core.toolConfig?.tools || ["*"]).map((t5) => typeof t5 === "string" ? t5 : t5.name),
            timestamp: Date.now()
          });
          const startEvent = new SubagentExecutionEvent(this.core.name, "started");
          logSubagentExecution(this.core.runtimeContext, startEvent);
          const result = await this.core.runReasoningLoop(chat, initialMessages, toolsList, abortController, {
            maxTurns: this.core.runConfig.max_turns,
            maxTimeMinutes: this.core.runConfig.max_time_minutes,
            startTimeMs: startTime,
            getExternalMessages: this.externalMessageProvider
          });
          this.finalText = result.text;
          this.terminateMode = result.terminateMode ?? AgentTerminateMode.GOAL;
        } catch (error40) {
          debugLogger40.error("Error during subagent execution:", error40);
          this.terminateMode = AgentTerminateMode.ERROR;
          this.core.eventEmitter?.emit(AgentEventType.ERROR, {
            subagentId: this.core.subagentId,
            error: error40 instanceof Error ? error40.message : String(error40),
            timestamp: Date.now()
          });
          throw error40;
        } finally {
          if (externalSignal) {
            externalSignal.removeEventListener("abort", onExternalAbort);
          }
          this.core.executionStats.totalDurationMs = Date.now() - startTime;
          const summary = this.core.stats.getSummary(Date.now());
          this.core.eventEmitter?.emit(AgentEventType.FINISH, {
            subagentId: this.core.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.core.name, this.terminateMode === AgentTerminateMode.GOAL ? "completed" : "failed", {
            terminate_reason: this.terminateMode,
            result: this.finalText,
            execution_summary: this.core.stats.formatCompact("Subagent execution completed")
          });
          logSubagentExecution(this.core.runtimeContext, completionEvent);
          await this.core.hooks?.onStop?.({
            subagentId: this.core.subagentId,
            name: this.core.name,
            terminateReason: this.terminateMode,
            summary,
            timestamp: Date.now()
          });
        }
      }
      // ─── Accessors ─────────────────────────────────────────────
      /**
       * Provides access to the underlying AgentCore for advanced use cases.
       * Used by AgentInteractive and InProcessBackend.
       */
      getCore() {
        return this.core;
      }
      get executionStats() {
        return this.core.executionStats;
      }
      set executionStats(value) {
        this.core.executionStats = value;
      }
      getEventEmitter() {
        return this.core.getEventEmitter();
      }
      getStatistics() {
        return this.core.getStatistics();
      }
      getExecutionSummary() {
        return this.core.getExecutionSummary();
      }
      getFinalText() {
        return this.finalText;
      }
      getTerminateMode() {
        return this.terminateMode;
      }
      /**
       * Sets a callback that the reasoning loop calls between tool rounds
       * to drain external messages (e.g. from SendMessage tool).
       */
      setExternalMessageProvider(provider) {
        this.externalMessageProvider = provider;
      }
      get name() {
        return this.core.name;
      }
      get runtimeContext() {
        return this.core.runtimeContext;
      }
    };
  }
});

// packages/core/dist/src/agents/runtime/agent-core.js
var EXCLUDED_TOOLS_FOR_SUBAGENTS, EXTERNAL_MESSAGE_PREFIX, AgentCore;
var init_agent_core = __esm({
  "packages/core/dist/src/agents/runtime/agent-core.js"() {
    "use strict";
    init_esbuild_shims();
    init_errorReporting();
    init_subagentNameContext();
    init_turn();
    init_coreToolScheduler();
    init_environmentContext();
    init_node();
    init_geminiChat();
    init_agent_types();
    init_agent_events();
    init_agent_statistics();
    init_rule_parser();
    init_tool_names();
    init_models();
    init_agent_headless();
    EXCLUDED_TOOLS_FOR_SUBAGENTS = /* @__PURE__ */ new Set([
      ToolNames.AGENT,
      ToolNames.CRON_CREATE,
      ToolNames.CRON_LIST,
      ToolNames.CRON_DELETE,
      ToolNames.TASK_STOP,
      ToolNames.SEND_MESSAGE
    ]);
    EXTERNAL_MESSAGE_PREFIX = "[Message from parent agent]:";
    AgentCore = class {
      static {
        __name(this, "AgentCore");
      }
      subagentId;
      name;
      runtimeContext;
      promptConfig;
      modelConfig;
      runConfig;
      toolConfig;
      /**
       * Event emitter for this agent. Always present — if the caller doesn't
       * pass one, AgentCore allocates its own so the observable state below
       * is populated regardless of who constructs the agent.
       */
      eventEmitter;
      hooks;
      stats = new AgentStatistics();
      // Observable state lives on Core (not a wrapper) so headless and
      // background agents can be observed with the same accessors as
      // interactive ones. Populated by listeners set up in the constructor.
      messages = [];
      pendingApprovals = /* @__PURE__ */ new Map();
      liveOutputs = /* @__PURE__ */ new Map();
      shellPids = /* @__PURE__ */ new Map();
      /**
       * Legacy execution stats maintained for aggregate tracking.
       */
      executionStats = {
        startTimeMs: 0,
        totalDurationMs: 0,
        rounds: 0,
        totalToolCalls: 0,
        successfulToolCalls: 0,
        failedToolCalls: 0,
        inputTokens: 0,
        outputTokens: 0,
        totalTokens: 0
      };
      /**
       * The prompt token count from the most recent model response.
       * Exposed so UI hooks can seed initial state without waiting for events.
       */
      lastPromptTokenCount = 0;
      toolUsage = /* @__PURE__ */ new Map();
      constructor(name4, runtimeContext, promptConfig, modelConfig, runConfig, toolConfig, eventEmitter, hooks) {
        const randomPart = Math.random().toString(36).slice(2, 8);
        this.subagentId = `${name4}-${randomPart}`;
        this.name = name4;
        this.runtimeContext = runtimeContext;
        this.promptConfig = promptConfig;
        this.modelConfig = modelConfig;
        this.runConfig = runConfig;
        this.toolConfig = toolConfig;
        this.eventEmitter = eventEmitter ?? new AgentEventEmitter();
        this.hooks = hooks;
        this.setupStateListeners();
      }
      // ─── Chat Creation ────────────────────────────────────────
      /**
       * Creates a GeminiChat instance configured for this agent.
       *
       * @param context - Context state for template variable substitution.
       * @param options - Chat creation options.
       *   - `interactive`: When true, omits the "non-interactive mode" system prompt suffix.
       * @returns A configured GeminiChat, or undefined if initialization fails.
       */
      async createChat(context2, options2) {
        if (!this.promptConfig.systemPrompt && !this.promptConfig.renderedSystemPrompt && !this.promptConfig.initialMessages) {
          throw new Error("PromptConfig must have `systemPrompt`, `renderedSystemPrompt`, or `initialMessages` defined.");
        }
        if (this.promptConfig.systemPrompt && this.promptConfig.renderedSystemPrompt) {
          throw new Error("PromptConfig cannot have both `systemPrompt` and `renderedSystemPrompt` defined.");
        }
        const hasInitialMessages = !!this.promptConfig.initialMessages && this.promptConfig.initialMessages.length > 0;
        const envHistory = hasInitialMessages ? [] : await getInitialChatHistory(this.runtimeContext);
        const startHistory = [
          ...envHistory,
          ...options2?.extraHistory ?? [],
          ...this.promptConfig.initialMessages ?? []
        ];
        const generationConfig = {};
        if (this.promptConfig.renderedSystemPrompt !== void 0) {
          generationConfig.systemInstruction = this.promptConfig.renderedSystemPrompt;
        } else if (this.promptConfig.systemPrompt) {
          const systemInstruction = this.buildChatSystemPrompt(context2, options2);
          if (systemInstruction) {
            generationConfig.systemInstruction = systemInstruction;
          }
        }
        try {
          return new GeminiChat(this.runtimeContext, generationConfig, startHistory);
        } catch (error40) {
          await reportError2(error40, "Error initializing chat session.", startHistory, "startChat");
          return void 0;
        }
      }
      // ─── Tool Preparation ─────────────────────────────────────
      /**
       * Prepares the list of tools available to this agent.
       *
       * If no explicit toolConfig or it contains "*" or is empty,
       * inherits all tools (excluding AgentTool to prevent recursion).
       */
      async prepareTools() {
        const toolRegistry = this.runtimeContext.getToolRegistry();
        await toolRegistry.warmAll();
        const toolsList = [];
        const excludedFromSubagents = EXCLUDED_TOOLS_FOR_SUBAGENTS;
        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 && onlyInlineDecls.length === 0) {
            toolsList.push(...toolRegistry.getFunctionDeclarations().filter((t5) => !(t5.name && excludedFromSubagents.has(t5.name))));
          } else {
            toolsList.push(...toolRegistry.getFunctionDeclarationsFiltered(asStrings.filter((name4) => !excludedFromSubagents.has(name4))));
          }
          toolsList.push(...onlyInlineDecls);
        } else {
          toolsList.push(...toolRegistry.getFunctionDeclarations().filter((t5) => !(t5.name && excludedFromSubagents.has(t5.name))));
        }
        if (this.toolConfig?.disallowedTools?.length) {
          const disallowed = this.toolConfig.disallowedTools;
          return toolsList.filter((t5) => {
            if (!t5.name)
              return true;
            return !disallowed.some((pattern) => t5.name.startsWith("mcp__") ? matchesMcpPattern(pattern, t5.name) : pattern === t5.name);
          });
        }
        return toolsList;
      }
      // ─── Reasoning Loop ───────────────────────────────────────
      /**
       * Runs the inner model reasoning loop.
       *
       * This is the core execution cycle:
       * send messages → stream response → collect tool calls → execute tools → repeat.
       *
       * The loop terminates when:
       * - The model produces a text response without tool calls (normal completion)
       * - maxTurns is reached
       * - maxTimeMinutes is exceeded
       * - The abortController signal fires
       *
       * @param chat - The GeminiChat session to use.
       * @param initialMessages - The first messages to send (e.g., user task prompt).
       * @param toolsList - Available tool declarations.
       * @param abortController - Controls cancellation of the current loop.
       * @param options - Optional limits (maxTurns, maxTimeMinutes).
       * @returns ReasoningLoopResult with the final text, terminate mode, and turns used.
       */
      async runReasoningLoop(chat, initialMessages, toolsList, abortController, options2) {
        return subagentNameContext.run(this.name, () => this._runReasoningLoopInner(chat, initialMessages, toolsList, abortController, options2));
      }
      async _runReasoningLoopInner(chat, initialMessages, toolsList, abortController, options2) {
        const startTime = options2?.startTimeMs ?? Date.now();
        let currentMessages = initialMessages;
        let turnCounter = 0;
        let finalText = "";
        let terminateMode = null;
        while (true) {
          if (abortController.signal.aborted) {
            terminateMode = AgentTerminateMode.CANCELLED;
            break;
          }
          if (options2?.maxTurns && turnCounter >= options2.maxTurns) {
            terminateMode = AgentTerminateMode.MAX_TURNS;
            break;
          }
          let durationMin = (Date.now() - startTime) / (1e3 * 60);
          if (options2?.maxTimeMinutes && durationMin >= options2.maxTimeMinutes) {
            terminateMode = AgentTerminateMode.TIMEOUT;
            break;
          }
          const roundAbortController = new AbortController();
          const onParentAbort = /* @__PURE__ */ __name(() => roundAbortController.abort(), "onParentAbort");
          abortController.signal.addEventListener("abort", onParentAbort);
          if (abortController.signal.aborted) {
            roundAbortController.abort();
          }
          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(AgentEventType.ROUND_START, {
            subagentId: this.subagentId,
            round: turnCounter,
            promptId,
            timestamp: Date.now()
          });
          const functionCalls = [];
          let roundText = "";
          let roundThoughtText = "";
          let lastUsage = void 0;
          let currentResponseId = void 0;
          let wasOutputTruncated = false;
          for await (const streamEvent of responseStream) {
            if (roundAbortController.signal.aborted) {
              abortController.signal.removeEventListener("abort", onParentAbort);
              return {
                text: finalText,
                terminateMode: AgentTerminateMode.CANCELLED,
                turnsUsed: turnCounter
              };
            }
            if (streamEvent.type === "retry") {
              functionCalls.length = 0;
              roundText = "";
              roundThoughtText = "";
              lastUsage = void 0;
              currentResponseId = void 0;
              wasOutputTruncated = false;
              continue;
            }
            if (streamEvent.type === "chunk") {
              const resp = streamEvent.value;
              if (resp.responseId) {
                currentResponseId = resp.responseId;
              }
              if (resp.functionCalls)
                functionCalls.push(...resp.functionCalls);
              if (resp.candidates?.[0]?.finishReason === FinishReason.MAX_TOKENS) {
                wasOutputTruncated = true;
              }
              const content = resp.candidates?.[0]?.content;
              const parts2 = content?.parts || [];
              for (const p2 of parts2) {
                const txt = p2.text;
                const isThought = p2.thought ?? false;
                if (txt && isThought)
                  roundThoughtText += txt;
                if (txt && !isThought)
                  roundText += txt;
                if (txt)
                  this.eventEmitter?.emit(AgentEventType.STREAM_TEXT, {
                    subagentId: this.subagentId,
                    round: turnCounter,
                    text: txt,
                    thought: isThought,
                    timestamp: Date.now()
                  });
              }
              if (resp.usageMetadata)
                lastUsage = resp.usageMetadata;
            }
          }
          if (roundText || roundThoughtText) {
            this.eventEmitter?.emit(AgentEventType.ROUND_TEXT, {
              subagentId: this.subagentId,
              round: turnCounter,
              text: roundText,
              thoughtText: roundThoughtText,
              timestamp: Date.now()
            });
          }
          this.executionStats.rounds = turnCounter;
          this.stats.setRounds(turnCounter);
          durationMin = (Date.now() - startTime) / (1e3 * 60);
          if (options2?.maxTimeMinutes && durationMin >= options2.maxTimeMinutes) {
            abortController.signal.removeEventListener("abort", onParentAbort);
            terminateMode = AgentTerminateMode.TIMEOUT;
            break;
          }
          if (lastUsage) {
            this.recordTokenUsage(lastUsage, turnCounter, roundStreamStart);
          }
          if (functionCalls.length > 0) {
            currentMessages = await this.processFunctionCalls(functionCalls, roundAbortController, promptId, turnCounter, toolsList, currentResponseId, wasOutputTruncated);
            const externalMsgs = options2?.getExternalMessages?.() ?? [];
            if (externalMsgs.length > 0) {
              const last2 = currentMessages[currentMessages.length - 1];
              last2.parts.push(...externalMsgs.map((text) => ({
                text: `
${EXTERNAL_MESSAGE_PREFIX} ${text}`
              })));
              for (const text of externalMsgs) {
                this.eventEmitter?.emit(AgentEventType.EXTERNAL_MESSAGE, {
                  subagentId: this.subagentId,
                  text,
                  timestamp: Date.now()
                });
              }
            }
          } else {
            if (roundText && roundText.trim().length > 0) {
              finalText = roundText.trim();
              this.eventEmitter?.emit(AgentEventType.ROUND_END, {
                subagentId: this.subagentId,
                round: turnCounter,
                promptId,
                timestamp: Date.now()
              });
              abortController.signal.removeEventListener("abort", onParentAbort);
              break;
            }
            currentMessages = [
              {
                role: "user",
                parts: [
                  {
                    text: "Please provide the final result now and stop calling tools."
                  }
                ]
              }
            ];
          }
          this.eventEmitter?.emit(AgentEventType.ROUND_END, {
            subagentId: this.subagentId,
            round: turnCounter,
            promptId,
            timestamp: Date.now()
          });
          abortController.signal.removeEventListener("abort", onParentAbort);
        }
        return {
          text: finalText,
          terminateMode,
          turnsUsed: turnCounter
        };
      }
      // ─── Tool Execution ───────────────────────────────────────
      /**
       * Processes a list of function calls via CoreToolScheduler.
       *
       * Validates each call against the allowed tools list, schedules authorized
       * calls, collects results, and emits events for each call/result.
       *
       * Validates each call, schedules authorized calls, collects results, and emits events.
       */
      async processFunctionCalls(functionCalls, abortController, promptId, currentRound, toolsList, responseId, wasOutputTruncated = false) {
        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(AgentEventType.TOOL_CALL, {
              subagentId: this.subagentId,
              round: currentRound,
              callId,
              name: toolName,
              args: fc.args ?? {},
              description: `Tool "${toolName}" not found`,
              isOutputMarkdown: false,
              timestamp: Date.now()
            });
            const functionResponsePart = {
              functionResponse: {
                id: callId,
                name: toolName,
                response: { error: errorMessage }
              }
            };
            this.eventEmitter?.emit(AgentEventType.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 emittedCallIds = /* @__PURE__ */ new Set();
        const pidMap = /* @__PURE__ */ new Map();
        const executionStartedEmitted = /* @__PURE__ */ new Set();
        const scheduler = new CoreToolScheduler({
          config: this.runtimeContext,
          outputUpdateHandler: /* @__PURE__ */ __name((callId, outputChunk) => {
            this.eventEmitter?.emit(AgentEventType.TOOL_OUTPUT_UPDATE, {
              subagentId: this.subagentId,
              round: currentRound,
              callId,
              outputChunk,
              pid: pidMap.get(callId),
              timestamp: Date.now()
            });
          }, "outputUpdateHandler"),
          onAllToolCallsComplete: /* @__PURE__ */ __name(async (completedCalls) => {
            for (const call of completedCalls) {
              if (emittedCallIds.has(call.request.callId))
                continue;
              emittedCallIds.add(call.request.callId);
              const toolName = call.request.name;
              const duration3 = call.durationMs ?? 0;
              const success2 = call.status === "success";
              const errorMessage = call.status === "error" || call.status === "cancelled" ? call.response.error?.message : void 0;
              this.recordToolCallStats(toolName, success2, duration3, errorMessage);
              this.eventEmitter?.emit(AgentEventType.TOOL_RESULT, {
                subagentId: this.subagentId,
                round: currentRound,
                callId: call.request.callId,
                name: toolName,
                success: success2,
                error: errorMessage,
                responseParts: call.response.responseParts,
                resultDisplay: call.response.resultDisplay,
                durationMs: duration3,
                timestamp: Date.now()
              });
              await this.hooks?.postToolUse?.({
                subagentId: this.subagentId,
                name: this.name,
                toolName,
                args: call.request.args,
                success: success2,
                durationMs: duration3,
                errorMessage,
                timestamp: Date.now()
              });
              const respParts = call.response.responseParts;
              if (respParts) {
                const parts2 = Array.isArray(respParts) ? respParts : [respParts];
                for (const part of parts2) {
                  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 === "executing") {
                const executing = call;
                const pid = executing.pid;
                const isNewPid = pid !== void 0 && !pidMap.has(call.request.callId);
                if (pid !== void 0) {
                  pidMap.set(call.request.callId, pid);
                }
                const needsExecutionStartEmit = executing.executionStartTime !== void 0 && !executionStartedEmitted.has(call.request.callId);
                if (needsExecutionStartEmit) {
                  executionStartedEmitted.add(call.request.callId);
                }
                if (isNewPid || needsExecutionStartEmit) {
                  this.eventEmitter?.emit(AgentEventType.TOOL_OUTPUT_UPDATE, {
                    subagentId: this.subagentId,
                    round: currentRound,
                    callId: call.request.callId,
                    outputChunk: executing.liveOutput ?? "",
                    pid,
                    executionStartTime: executing.executionStartTime,
                    timestamp: Date.now()
                  });
                }
              }
              if (call.status !== "awaiting_approval")
                continue;
              const waiting = call;
              try {
                const { confirmationDetails } = waiting;
                const { onConfirm: _onConfirm, ...rest } = confirmationDetails;
                this.eventEmitter?.emit(AgentEventType.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 args2 = fc.args ?? {};
          const request4 = {
            callId,
            name: toolName,
            args: args2,
            isClientInitiated: true,
            prompt_id: promptId,
            response_id: responseId,
            wasOutputTruncated
          };
          const description = this.getToolDescription(toolName, args2);
          const isOutputMarkdown = this.getToolIsOutputMarkdown(toolName);
          this.eventEmitter?.emit(AgentEventType.TOOL_CALL, {
            subagentId: this.subagentId,
            round: currentRound,
            callId,
            name: toolName,
            args: args2,
            description,
            isOutputMarkdown,
            timestamp: Date.now()
          });
          void this.hooks?.preToolUse?.({
            subagentId: this.subagentId,
            name: this.name,
            toolName,
            args: args2,
            timestamp: Date.now()
          });
          return request4;
        });
        if (requests.length > 0) {
          const batchDone = new Promise((resolve42) => {
            resolveBatch = /* @__PURE__ */ __name(() => {
              resolve42();
              resolveBatch = null;
            }, "resolveBatch");
          });
          const onAbort = /* @__PURE__ */ __name(() => {
            resolveBatch?.();
            for (const req of requests) {
              if (emittedCallIds.has(req.callId))
                continue;
              emittedCallIds.add(req.callId);
              const errorMessage = "Tool call cancelled by user abort.";
              this.recordToolCallStats(req.name, false, 0, errorMessage);
              this.eventEmitter?.emit(AgentEventType.TOOL_RESULT, {
                subagentId: this.subagentId,
                round: currentRound,
                callId: req.callId,
                name: req.name,
                success: false,
                error: errorMessage,
                responseParts: [
                  {
                    functionResponse: {
                      id: req.callId,
                      name: req.name,
                      response: { error: errorMessage }
                    }
                  }
                ],
                resultDisplay: errorMessage,
                durationMs: 0,
                timestamp: Date.now()
              });
            }
          }, "onAbort");
          abortController.signal.addEventListener("abort", onAbort, { once: true });
          if (abortController.signal.aborted) {
            onAbort();
          }
          await scheduler.schedule(requests, abortController.signal);
          await batchDone;
          abortController.signal.removeEventListener("abort", onAbort);
        }
        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 }];
      }
      // ─── Observable state accessors ────────────────────────────
      getMessages() {
        return this.messages;
      }
      /**
       * Tool calls currently awaiting user approval. Mutated by
       * AgentInteractive's TOOL_WAITING_APPROVAL handler; headless agents
       * never populate this because they run with
       * `getShouldAvoidPermissionPrompts === true`.
       */
      getPendingApprovals() {
        return this.pendingApprovals;
      }
      getLiveOutputs() {
        return this.liveOutputs;
      }
      getShellPids() {
        return this.shellPids;
      }
      pushMessage(role, content, options2) {
        const message = {
          role,
          content,
          timestamp: Date.now()
        };
        if (options2?.thought) {
          message.thought = true;
        }
        if (options2?.metadata) {
          message.metadata = options2.metadata;
        }
        this.messages.push(message);
      }
      setPendingApproval(callId, details) {
        this.pendingApprovals.set(callId, details);
      }
      deletePendingApproval(callId) {
        this.pendingApprovals.delete(callId);
      }
      clearPendingApprovals() {
        this.pendingApprovals.clear();
      }
      // ─── Stats & Events ───────────────────────────────────────
      getEventEmitter() {
        return this.eventEmitter;
      }
      getExecutionSummary() {
        return this.stats.getSummary();
      }
      /**
       * Returns legacy execution statistics and per-tool usage.
       * Returns legacy execution statistics and per-tool usage.
       */
      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(([name4, v2]) => ({
            name: name4,
            ...v2
          }))
        };
      }
      /**
       * Safely retrieves the description of a tool by attempting to build it.
       * Returns an empty string if any error occurs during the process.
       * Note: Assumes tools are warmed via warmAll() before the reasoning loop.
       */
      getToolDescription(toolName, args2) {
        try {
          const toolRegistry = this.runtimeContext.getToolRegistry();
          const tool = toolRegistry.getTool(toolName);
          if (!tool) {
            return "";
          }
          const toolInstance = tool.build(args2);
          return toolInstance.getDescription() || "";
        } catch {
          return "";
        }
      }
      getToolIsOutputMarkdown(toolName) {
        try {
          const toolRegistry = this.runtimeContext.getToolRegistry();
          return toolRegistry.getTool(toolName)?.isOutputMarkdown ?? false;
        } catch {
          return false;
        }
      }
      /**
       * Records tool call statistics for both successful and failed tool calls.
       */
      recordToolCallStats(toolName, success2, durationMs, errorMessage) {
        this.executionStats.totalToolCalls += 1;
        if (success2) {
          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 (success2) {
          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, success2, durationMs, this.toolUsage.get(toolName)?.lastError);
      }
      // ─── Private Helpers ──────────────────────────────────────
      /**
       * TOOL_WAITING_APPROVAL is deliberately NOT listened to here because
       * the correct response depends on whether the consumer is interactive
       * (needs to wrap onConfirm with cancel-round behavior) or headless
       * (approvals never fire). AgentInteractive owns that listener and
       * writes into `pendingApprovals` via the public mutator API.
       */
      setupStateListeners() {
        const emitter = this.eventEmitter;
        emitter.on(AgentEventType.ROUND_TEXT, (event) => {
          if (event.thoughtText) {
            this.pushMessage("assistant", event.thoughtText, { thought: true });
          }
          if (event.text) {
            this.pushMessage("assistant", event.text);
          }
        });
        emitter.on(AgentEventType.TOOL_CALL, (event) => {
          this.pushMessage("tool_call", `Tool call: ${event.name}`, {
            metadata: {
              callId: event.callId,
              toolName: event.name,
              args: event.args,
              description: event.description,
              renderOutputAsMarkdown: event.isOutputMarkdown,
              round: event.round
            }
          });
        });
        emitter.on(AgentEventType.TOOL_OUTPUT_UPDATE, (event) => {
          this.liveOutputs.set(event.callId, event.outputChunk);
          if (event.pid !== void 0) {
            this.shellPids.set(event.callId, event.pid);
          }
        });
        emitter.on(AgentEventType.TOOL_RESULT, (event) => {
          this.liveOutputs.delete(event.callId);
          this.shellPids.delete(event.callId);
          this.pendingApprovals.delete(event.callId);
          const statusText = event.success ? "succeeded" : "failed";
          const summary = event.error ? `Tool ${event.name} ${statusText}: ${event.error}` : `Tool ${event.name} ${statusText}`;
          this.pushMessage("tool_result", summary, {
            metadata: {
              callId: event.callId,
              toolName: event.name,
              success: event.success,
              resultDisplay: event.resultDisplay,
              outputFile: event.outputFile,
              round: event.round
            }
          });
        });
        emitter.on(AgentEventType.EXTERNAL_MESSAGE, (event) => {
          this.pushMessage("user", event.text);
        });
      }
      /**
       * Builds the system prompt with template substitution and optional
       * non-interactive instructions suffix.
       */
      buildChatSystemPrompt(context2, options2) {
        if (!this.promptConfig.systemPrompt) {
          return "";
        }
        let finalPrompt = templateString(this.promptConfig.systemPrompt, context2);
        if (!options2?.interactive) {
          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.`;
        }
        const userMemory = this.runtimeContext.getUserMemory();
        if (userMemory && userMemory.trim().length > 0) {
          finalPrompt += `

---

${userMemory.trim()}`;
        }
        return finalPrompt;
      }
      /**
       * Records token usage from model response metadata.
       */
      recordTokenUsage(usage2, turnCounter, roundStreamStart) {
        const inTok = Number(usage2.promptTokenCount || 0);
        const outTok = Number(usage2.candidatesTokenCount || 0);
        const thoughtTok = Number(usage2.thoughtsTokenCount || 0);
        const cachedTok = Number(usage2.cachedContentTokenCount || 0);
        const totalTok = Number(usage2.totalTokenCount || 0);
        const contextTok = isFinite(totalTok) && totalTok > 0 ? totalTok : inTok;
        if (isFinite(contextTok) && contextTok > 0) {
          this.lastPromptTokenCount = contextTok;
        }
        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, isFinite(totalTok) ? totalTok : 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.totalTokens || 0) + (isFinite(totalTok) ? totalTok : 0);
        }
        this.eventEmitter?.emit(AgentEventType.USAGE_METADATA, {
          subagentId: this.subagentId,
          round: turnCounter,
          usage: usage2,
          durationMs: Date.now() - roundStreamStart,
          timestamp: Date.now()
        });
      }
    };
  }
});

// packages/core/dist/src/utils/asyncMessageQueue.js
var AsyncMessageQueue;
var init_asyncMessageQueue = __esm({
  "packages/core/dist/src/utils/asyncMessageQueue.js"() {
    "use strict";
    init_esbuild_shims();
    AsyncMessageQueue = class {
      static {
        __name(this, "AsyncMessageQueue");
      }
      items = [];
      drained = false;
      /** Add an item to the queue. Dropped silently after drain. */
      enqueue(item) {
        if (this.drained)
          return;
        this.items.push(item);
      }
      /** Remove and return the next item, or null if empty. */
      dequeue() {
        if (this.items.length > 0) {
          return this.items.shift();
        }
        return null;
      }
      /** Signal that no more items will be enqueued. */
      drain() {
        this.drained = true;
      }
      /** Number of items currently in the queue. */
      get size() {
        return this.items.length;
      }
      /** Whether `drain()` has been called. */
      get isDrained() {
        return this.drained;
      }
    };
  }
});

// packages/core/dist/src/agents/runtime/agent-interactive.js
function terminateModeMessage(mode) {
  switch (mode) {
    case AgentTerminateMode.MAX_TURNS:
      return {
        text: "Agent stopped: maximum turns reached.",
        level: "warning"
      };
    case AgentTerminateMode.TIMEOUT:
      return { text: "Agent stopped: time limit reached.", level: "warning" };
    case AgentTerminateMode.ERROR:
      return { text: "Agent stopped due to an error.", level: "error" };
    case AgentTerminateMode.CANCELLED:
    case AgentTerminateMode.SHUTDOWN:
      return null;
    default:
      return null;
  }
}
var debugLogger41, AgentInteractive;
var init_agent_interactive = __esm({
  "packages/core/dist/src/agents/runtime/agent-interactive.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_agent_events();
    init_tools();
    init_asyncMessageQueue();
    init_agent_types();
    debugLogger41 = createDebugLogger("AGENT_INTERACTIVE");
    AgentInteractive = class {
      static {
        __name(this, "AgentInteractive");
      }
      config;
      core;
      queue = new AsyncMessageQueue();
      status = AgentStatus.INITIALIZING;
      error;
      lastRoundError;
      executionPromise;
      masterAbortController = new AbortController();
      roundAbortController;
      chat;
      toolsList = [];
      processing = false;
      roundCancelledByUser = false;
      // Wall-clock timestamp when each currently-executing tool transitioned into
      // the scheduler's `executing` state. Keyed by callId. First TOOL_OUTPUT_UPDATE
      // carrying executionStartTime wins; later events that re-carry it are ignored
      // so the timer is stable. Lives on InteractiveAgent (not AgentCore) because
      // it's only consumed by the interactive UI's elapsed-time indicator.
      executionStartTimes = /* @__PURE__ */ new Map();
      constructor(config2, core) {
        this.config = config2;
        this.core = core;
        this.setupEventListeners();
      }
      // ─── Lifecycle ──────────────────────────────────────────────
      /**
       * Start the agent. Initializes the chat session, then kicks off
       * processing if an initialTask is configured.
       */
      async start(context2) {
        this.setStatus(AgentStatus.INITIALIZING);
        this.chat = await this.core.createChat(context2, {
          interactive: true,
          extraHistory: this.config.chatHistory
        });
        if (!this.chat) {
          this.error = "Failed to create chat session";
          this.setStatus(AgentStatus.FAILED);
          return;
        }
        this.toolsList = await this.core.prepareTools();
        this.core.stats.start(Date.now());
        if (this.config.chatHistory?.length) {
          this.addMessage("info", `History context from parent session included (${this.config.chatHistory.length} messages)`);
        }
        if (this.config.initialTask) {
          this.queue.enqueue(this.config.initialTask);
          this.executionPromise = this.runLoop();
        }
      }
      /**
       * Run loop: process all pending messages, then settle status.
       * Exits when the queue is empty or the agent is aborted.
       */
      async runLoop() {
        this.processing = true;
        try {
          let message = this.queue.dequeue();
          while (message !== null && !this.masterAbortController.signal.aborted) {
            this.addMessage("user", message);
            await this.runOneRound(message);
            message = this.queue.dequeue();
          }
          if (this.masterAbortController.signal.aborted) {
            this.setStatus(AgentStatus.CANCELLED);
          } else {
            this.settleRoundStatus();
          }
        } catch (err2) {
          this.error = err2 instanceof Error ? err2.message : String(err2);
          this.setStatus(AgentStatus.FAILED);
          debugLogger41.error("AgentInteractive processing failed:", err2);
        } finally {
          this.processing = false;
        }
      }
      /**
       * Run a single reasoning round for one message.
       * Creates a per-round AbortController so cancellation is scoped.
       */
      async runOneRound(message) {
        if (!this.chat)
          return;
        this.setStatus(AgentStatus.RUNNING);
        this.lastRoundError = void 0;
        this.roundCancelledByUser = false;
        this.roundAbortController = new AbortController();
        const onMasterAbort = /* @__PURE__ */ __name(() => this.roundAbortController?.abort(), "onMasterAbort");
        this.masterAbortController.signal.addEventListener("abort", onMasterAbort);
        if (this.masterAbortController.signal.aborted) {
          this.roundAbortController.abort();
        }
        try {
          const initialMessages = [
            { role: "user", parts: [{ text: message }] }
          ];
          const result = await this.core.runReasoningLoop(this.chat, initialMessages, this.toolsList, this.roundAbortController, {
            maxTurns: this.config.maxTurnsPerMessage,
            maxTimeMinutes: this.config.maxTimeMinutesPerMessage
          });
          if (result.terminateMode && result.terminateMode !== AgentTerminateMode.GOAL) {
            const msg = terminateModeMessage(result.terminateMode);
            if (msg) {
              this.addMessage("info", msg.text, { metadata: { level: msg.level } });
            }
            this.lastRoundError = `Terminated: ${result.terminateMode}`;
          }
        } catch (err2) {
          if (this.roundCancelledByUser)
            return;
          const errorMessage = err2 instanceof Error ? err2.message : String(err2);
          this.lastRoundError = errorMessage;
          debugLogger41.error("AgentInteractive round error:", err2);
          this.addMessage("info", errorMessage, { metadata: { level: "error" } });
        } finally {
          this.masterAbortController.signal.removeEventListener("abort", onMasterAbort);
          this.roundAbortController = void 0;
        }
      }
      // ─── Cancellation ──────────────────────────────────────────
      /**
       * Cancel only the current reasoning round.
       * Adds a visible "cancelled" info message and clears pending approvals.
       */
      cancelCurrentRound() {
        this.roundCancelledByUser = true;
        this.roundAbortController?.abort();
        this.core.clearPendingApprovals();
        this.addMessage("info", "Agent round cancelled.", {
          metadata: { level: "warning" }
        });
      }
      /**
       * Graceful shutdown: stop accepting messages and wait for current
       * processing to finish.
       */
      async shutdown() {
        this.queue.drain();
        if (this.executionPromise) {
          await this.executionPromise;
        }
        if (!isTerminalStatus(this.status)) {
          this.setStatus(AgentStatus.COMPLETED);
        }
      }
      /**
       * Immediate abort: cancel everything and set status to cancelled.
       */
      abort() {
        this.masterAbortController.abort();
        this.queue.drain();
        this.core.clearPendingApprovals();
      }
      // ─── Message Queue ─────────────────────────────────────────
      /**
       * Enqueue a message for the agent to process.
       */
      enqueueMessage(message) {
        this.queue.enqueue(message);
        if (!this.processing) {
          this.executionPromise = this.runLoop();
        }
      }
      // ─── State Accessors (delegates to AgentCore) ──────────────
      getMessages() {
        return this.core.getMessages();
      }
      getStatus() {
        return this.status;
      }
      getError() {
        return this.error;
      }
      getLastRoundError() {
        return this.lastRoundError;
      }
      getStats() {
        return this.core.getExecutionSummary();
      }
      /** The prompt token count from the most recent model call. */
      getLastPromptTokenCount() {
        return this.core.lastPromptTokenCount;
      }
      getCore() {
        return this.core;
      }
      getEventEmitter() {
        return this.core.getEventEmitter();
      }
      /**
       * Returns tool calls currently awaiting user approval.
       * Keyed by callId → full ToolCallConfirmationDetails (with onConfirm).
       * The UI reads this to render confirmation dialogs inside ToolGroupMessage.
       */
      getPendingApprovals() {
        return this.core.getPendingApprovals();
      }
      /**
       * Returns live output for currently-executing tools.
       * Keyed by callId → latest ToolResultDisplay (replaces on each update).
       * Entries are cleared when TOOL_RESULT arrives for the call.
       */
      getLiveOutputs() {
        return this.core.getLiveOutputs();
      }
      /**
       * Returns PTY PIDs for currently-executing interactive shell tools.
       * Keyed by callId → PID. Populated from TOOL_OUTPUT_UPDATE when pid is
       * present; cleared when TOOL_RESULT arrives. The UI uses this to enable
       * interactive shell input via HistoryItemDisplay's activeShellPtyId prop.
       */
      getShellPids() {
        return this.core.getShellPids();
      }
      /**
       * Returns wall-clock start timestamps (ms since epoch) for currently-
       * executing tools, from the scheduler's `→ executing` transition.
       * Keyed by callId; entries are cleared when TOOL_RESULT arrives. The UI
       * uses this to render an elapsed-time indicator that excludes approval
       * and scheduling wait.
       */
      getExecutionStartTimes() {
        return this.executionStartTimes;
      }
      /**
       * Wait for the run loop to finish (used by InProcessBackend).
       */
      async waitForCompletion() {
        if (this.executionPromise) {
          await this.executionPromise;
        }
      }
      // ─── Private Helpers ───────────────────────────────────────
      /**
       * Settle status after the run loop empties.
       * On success → IDLE (agent stays alive for follow-up messages).
       * On error → FAILED (terminal).
       */
      settleRoundStatus() {
        if (this.lastRoundError && !this.roundCancelledByUser) {
          this.setStatus(AgentStatus.FAILED);
        } else {
          this.setStatus(AgentStatus.IDLE);
        }
      }
      setStatus(newStatus) {
        const previousStatus = this.status;
        if (previousStatus === newStatus)
          return;
        this.status = newStatus;
        this.core.eventEmitter?.emit(AgentEventType.STATUS_CHANGE, {
          agentId: this.config.agentId,
          previousStatus,
          newStatus,
          roundCancelledByUser: this.roundCancelledByUser || void 0,
          timestamp: Date.now()
        });
      }
      addMessage(role, content, options2) {
        this.core.pushMessage(role, content, options2);
      }
      /**
       * Wraps TOOL_WAITING_APPROVAL's onConfirm so a Cancel outcome aborts
       * the current round (headless agents bypass this path entirely).
       * Core already owns the message / live-output / shell-PID listeners.
       */
      setupEventListeners() {
        const emitter = this.core.eventEmitter;
        emitter.on(AgentEventType.TOOL_OUTPUT_UPDATE, (event) => {
          if (event.executionStartTime !== void 0 && !this.executionStartTimes.has(event.callId)) {
            this.executionStartTimes.set(event.callId, event.executionStartTime);
          }
        });
        emitter.on(AgentEventType.TOOL_RESULT, (event) => {
          this.executionStartTimes.delete(event.callId);
        });
        emitter.on(AgentEventType.TOOL_WAITING_APPROVAL, (event) => {
          const fullDetails = {
            ...event.confirmationDetails,
            onConfirm: /* @__PURE__ */ __name(async (outcome, payload) => {
              this.core.deletePendingApproval(event.callId);
              this.core.eventEmitter.emit(AgentEventType.TOOL_OUTPUT_UPDATE, {
                subagentId: this.core.subagentId,
                round: event.round,
                callId: event.callId,
                outputChunk: "",
                timestamp: Date.now()
              });
              await event.respond(outcome, payload);
              if (outcome === ToolConfirmationOutcome.Cancel) {
                this.cancelCurrentRound();
              }
            }, "onConfirm")
          };
          this.core.setPendingApproval(event.callId, fullDetails);
        });
      }
    };
    __name(terminateModeMessage, "terminateModeMessage");
  }
});

// packages/core/dist/src/agents/backends/InProcessBackend.js
async function createPerAgentConfig(base, cwd6, modelId, authOverrides) {
  const override = Object.create(base);
  let dedicatedContentGenerator;
  override.getWorkingDir = () => cwd6;
  override.getTargetDir = () => cwd6;
  override.getProjectRoot = () => cwd6;
  const agentWorkspace = new WorkspaceContext(cwd6);
  override.getWorkspaceContext = () => agentWorkspace;
  const agentFileService = new FileDiscoveryService(cwd6);
  override.getFileService = () => agentFileService;
  const agentRegistry = await override.createToolRegistry(void 0, { skipDiscovery: true });
  agentRegistry.copyDiscoveredToolsFrom(base.getToolRegistry());
  override.getToolRegistry = () => agentRegistry;
  if (authOverrides?.authType) {
    try {
      const agentGeneratorConfig = buildAgentContentGeneratorConfig(base, modelId, authOverrides);
      const agentGenerator = await createContentGenerator(agentGeneratorConfig, override);
      dedicatedContentGenerator = agentGenerator;
      override.getContentGenerator = () => agentGenerator;
      override.getContentGeneratorConfig = () => agentGeneratorConfig;
      override.getAuthType = () => agentGeneratorConfig.authType;
      override.getModel = () => agentGeneratorConfig.model;
      debugLogger42.info(`Created per-agent ContentGenerator: authType=${authOverrides.authType}, model=${agentGeneratorConfig.model}`);
    } catch (error40) {
      debugLogger42.error("Failed to create per-agent ContentGenerator, falling back to parent:", error40);
    }
  }
  return {
    config: override,
    contentGenerator: dedicatedContentGenerator ?? (authOverrides?.authType ? void 0 : base.getContentGenerator())
  };
}
var debugLogger42, InProcessBackend;
var init_InProcessBackend = __esm({
  "packages/core/dist/src/agents/backends/InProcessBackend.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_contentGenerator();
    init_workspaceContext();
    init_fileDiscoveryService();
    init_content_generator_config();
    init_agent_types();
    init_agent_core();
    init_agent_events();
    init_agent_headless();
    init_agent_interactive();
    init_types7();
    debugLogger42 = createDebugLogger("IN_PROCESS_BACKEND");
    InProcessBackend = class {
      static {
        __name(this, "InProcessBackend");
      }
      type = DISPLAY_MODE.IN_PROCESS;
      runtimeContext;
      agents = /* @__PURE__ */ new Map();
      agentContentGenerators = /* @__PURE__ */ new Map();
      agentRegistries = [];
      agentOrder = [];
      activeAgentId = null;
      exitCallback = null;
      /** Whether cleanup() has been called */
      cleanedUp = false;
      constructor(runtimeContext) {
        this.runtimeContext = runtimeContext;
      }
      // ─── Backend Interface ─────────────────────────────────────
      async init() {
        debugLogger42.info("InProcessBackend initialized");
      }
      async spawnAgent(config2) {
        const inProcessConfig = config2.inProcess;
        if (!inProcessConfig) {
          throw new Error(`InProcessBackend requires inProcess config for agent ${config2.agentId}`);
        }
        if (this.agents.has(config2.agentId)) {
          throw new Error(`Agent "${config2.agentId}" already exists.`);
        }
        const { promptConfig, modelConfig, runConfig, toolConfig } = inProcessConfig.runtimeConfig;
        const eventEmitter = new AgentEventEmitter();
        const perAgent = await createPerAgentConfig(this.runtimeContext, config2.cwd, inProcessConfig.runtimeConfig.modelConfig.model, inProcessConfig.authOverrides);
        const agentContext = perAgent.config;
        if (perAgent.contentGenerator) {
          this.agentContentGenerators.set(config2.agentId, perAgent.contentGenerator);
        }
        this.agentRegistries.push(agentContext.getToolRegistry());
        const core = new AgentCore(inProcessConfig.agentName, agentContext, promptConfig, modelConfig, runConfig, toolConfig, eventEmitter);
        const interactive = new AgentInteractive({
          agentId: config2.agentId,
          agentName: inProcessConfig.agentName,
          initialTask: inProcessConfig.initialTask,
          maxTurnsPerMessage: runConfig.max_turns,
          maxTimeMinutesPerMessage: runConfig.max_time_minutes,
          chatHistory: inProcessConfig.chatHistory
        }, core);
        this.agents.set(config2.agentId, interactive);
        this.agentOrder.push(config2.agentId);
        if (this.activeAgentId === null) {
          this.activeAgentId = config2.agentId;
        }
        try {
          const context2 = new ContextState();
          await interactive.start(context2);
          void interactive.waitForCompletion().then(() => {
            const status = interactive.getStatus();
            if (!isTerminalStatus(status)) {
              return;
            }
            const exitCode = status === AgentStatus.COMPLETED ? 0 : status === AgentStatus.FAILED ? 1 : null;
            this.exitCallback?.(config2.agentId, exitCode, null);
          });
          debugLogger42.info(`Spawned in-process agent: ${config2.agentId}`);
        } catch (error40) {
          debugLogger42.error(`Failed to start in-process agent "${config2.agentId}":`, error40);
          this.exitCallback?.(config2.agentId, 1, null);
        }
      }
      stopAgent(agentId) {
        const agent = this.agents.get(agentId);
        if (agent) {
          agent.abort();
          debugLogger42.info(`Stopped agent: ${agentId}`);
        }
      }
      stopAll() {
        for (const agent of this.agents.values()) {
          agent.abort();
        }
        debugLogger42.info("Stopped all in-process agents");
      }
      async cleanup() {
        this.cleanedUp = true;
        for (const agent of this.agents.values()) {
          agent.abort();
        }
        const CLEANUP_TIMEOUT_MS = 3e3;
        const promises9 = Array.from(this.agents.values()).map((a2) => a2.waitForCompletion().catch(() => {
        }));
        let timerId;
        const timeout2 = new Promise((resolve42) => {
          timerId = setTimeout(resolve42, CLEANUP_TIMEOUT_MS);
        });
        await Promise.race([Promise.allSettled(promises9), timeout2]);
        clearTimeout(timerId);
        for (const registry3 of this.agentRegistries) {
          await registry3.stop().catch(() => {
          });
        }
        this.agentRegistries.length = 0;
        this.agents.clear();
        this.agentContentGenerators.clear();
        this.agentOrder.length = 0;
        this.activeAgentId = null;
        debugLogger42.info("InProcessBackend cleaned up");
      }
      setOnAgentExit(callback) {
        this.exitCallback = callback;
      }
      async waitForAll(timeoutMs) {
        if (this.cleanedUp)
          return true;
        const promises9 = Array.from(this.agents.values()).map((a2) => a2.waitForCompletion());
        if (timeoutMs === void 0) {
          await Promise.allSettled(promises9);
          return true;
        }
        let timerId;
        const timeout2 = new Promise((resolve42) => {
          timerId = setTimeout(() => resolve42("timeout"), timeoutMs);
        });
        const result = await Promise.race([
          Promise.allSettled(promises9).then(() => "done"),
          timeout2
        ]);
        clearTimeout(timerId);
        return result === "done";
      }
      // ─── Navigation ────────────────────────────────────────────
      switchTo(agentId) {
        if (this.agents.has(agentId)) {
          this.activeAgentId = agentId;
        }
      }
      switchToNext() {
        this.activeAgentId = this.navigate(1);
      }
      switchToPrevious() {
        this.activeAgentId = this.navigate(-1);
      }
      getActiveAgentId() {
        return this.activeAgentId;
      }
      // ─── Screen Capture (no-op for in-process) ─────────────────
      getActiveSnapshot() {
        return null;
      }
      getAgentSnapshot(_agentId, _scrollOffset) {
        return null;
      }
      getAgentScrollbackLength(_agentId) {
        return 0;
      }
      // ─── Input ─────────────────────────────────────────────────
      forwardInput(data) {
        if (!this.activeAgentId)
          return false;
        return this.writeToAgent(this.activeAgentId, data);
      }
      writeToAgent(agentId, data) {
        const agent = this.agents.get(agentId);
        if (!agent)
          return false;
        agent.enqueueMessage(data);
        return true;
      }
      // ─── Resize (no-op) ───────────────────────────────────────
      resizeAll(_cols, _rows) {
      }
      // ─── External Session ──────────────────────────────────────
      getAttachHint() {
        return null;
      }
      // ─── Extra: Direct Access ──────────────────────────────────
      /**
       * Get an AgentInteractive instance by agent ID.
       * Used by ArenaManager for direct event subscription.
       */
      getAgent(agentId) {
        return this.agents.get(agentId);
      }
      /**
       * Get the ContentGenerator this agent can use for summary generation.
       * If auth overrides created an isolated generator, this returns that
       * generator. If no override was requested, this returns the inherited
       * generator the agent already runs with. If override creation failed, this is
       * undefined so callers can avoid sending agent data through a fallback
       * provider.
       */
      getAgentContentGenerator(agentId) {
        return this.agentContentGenerators.get(agentId);
      }
      // ─── Private ───────────────────────────────────────────────
      navigate(direction) {
        if (this.agentOrder.length === 0)
          return null;
        if (!this.activeAgentId)
          return this.agentOrder[0] ?? null;
        const currentIndex = this.agentOrder.indexOf(this.activeAgentId);
        if (currentIndex === -1)
          return this.agentOrder[0] ?? null;
        const nextIndex = (currentIndex + direction + this.agentOrder.length) % this.agentOrder.length;
        return this.agentOrder[nextIndex] ?? null;
      }
    };
    __name(createPerAgentConfig, "createPerAgentConfig");
  }
});

// packages/core/dist/src/agents/backends/detect.js
async function detectBackend(preference, runtimeContext) {
  const warning = preference && preference !== DISPLAY_MODE.IN_PROCESS ? `Display mode "${preference}" is not currently supported. Using in-process mode instead.` : void 0;
  debugLogger43.info("Using InProcessBackend");
  return { backend: new InProcessBackend(runtimeContext), warning };
}
var debugLogger43;
var init_detect = __esm({
  "packages/core/dist/src/agents/backends/detect.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_InProcessBackend();
    init_types7();
    debugLogger43 = createDebugLogger("BACKEND_DETECT");
    __name(detectBackend, "detectBackend");
  }
});

// packages/core/dist/src/agents/backends/index.js
var init_backends = __esm({
  "packages/core/dist/src/agents/backends/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_types7();
    init_TmuxBackend();
    init_ITermBackend();
    init_InProcessBackend();
    init_detect();
  }
});

// packages/core/dist/src/agents/arena/arena-events.js
import { EventEmitter as EventEmitter4 } from "events";
var ArenaEventType, ArenaEventEmitter;
var init_arena_events = __esm({
  "packages/core/dist/src/agents/arena/arena-events.js"() {
    "use strict";
    init_esbuild_shims();
    (function(ArenaEventType2) {
      ArenaEventType2["SESSION_START"] = "session_start";
      ArenaEventType2["SESSION_UPDATE"] = "session_update";
      ArenaEventType2["SESSION_COMPLETE"] = "session_complete";
      ArenaEventType2["SESSION_ERROR"] = "session_error";
      ArenaEventType2["AGENT_START"] = "agent_start";
      ArenaEventType2["AGENT_STATUS_CHANGE"] = "agent_status_change";
      ArenaEventType2["AGENT_COMPLETE"] = "agent_complete";
      ArenaEventType2["AGENT_ERROR"] = "agent_error";
    })(ArenaEventType || (ArenaEventType = {}));
    ArenaEventEmitter = class {
      static {
        __name(this, "ArenaEventEmitter");
      }
      ee = new EventEmitter4();
      on(event, listener) {
        this.ee.on(event, listener);
      }
      off(event, listener) {
        this.ee.off(event, listener);
      }
      emit(event, payload) {
        this.ee.emit(event, payload);
      }
      once(event, listener) {
        this.ee.once(event, listener);
      }
      removeAllListeners(event) {
        if (event) {
          this.ee.removeAllListeners(event);
        } else {
          this.ee.removeAllListeners();
        }
      }
    };
  }
});

// packages/core/dist/src/agents/arena/diff-summary.js
function summarizeUnifiedDiff(diff4) {
  if (!diff4) {
    return { files: [], additions: 0, deletions: 0 };
  }
  const files = [];
  let current;
  const finishFile = /* @__PURE__ */ __name(() => {
    if (!current)
      return;
    files.push(current);
    current = void 0;
  }, "finishFile");
  const ensureFile = /* @__PURE__ */ __name((path150) => {
    if (!current) {
      current = { path: path150, additions: 0, deletions: 0 };
      return;
    }
    current.path = path150;
  }, "ensureFile");
  for (const line of diff4.split("\n")) {
    const gitPath = parseDiffGitPath(line);
    if (gitPath) {
      finishFile();
      current = {
        path: gitPath,
        additions: 0,
        deletions: 0
      };
      continue;
    }
    if (line.startsWith("+++ ")) {
      const path150 = normalizeDiffPath(line.slice(4));
      if (path150 !== "/dev/null") {
        ensureFile(path150);
      }
      continue;
    }
    if (line.startsWith("--- ")) {
      const path150 = normalizeDiffPath(line.slice(4));
      if (!current && path150 !== "/dev/null") {
        ensureFile(path150);
      }
      continue;
    }
    if (!current)
      continue;
    if (line.startsWith("+")) {
      current.additions++;
    } else if (line.startsWith("-")) {
      current.deletions++;
    }
  }
  finishFile();
  return {
    files,
    additions: files.reduce((sum, file2) => sum + file2.additions, 0),
    deletions: files.reduce((sum, file2) => sum + file2.deletions, 0)
  };
}
function buildFallbackApproachSummary(result) {
  if (!isSuccessStatus(result.status)) {
    const suffix = result.error ? `: ${result.error}` : "";
    return `Did not produce an applicable result${suffix}.`;
  }
  const diffSummary = result.diffSummary ?? summarizeUnifiedDiff(result.diff ?? "");
  if (diffSummary.files.length === 0) {
    return "No code changes detected.";
  }
  const fileWord = diffSummary.files.length === 1 ? "file" : "files";
  const toolWord = result.stats.toolCalls === 1 ? "tool call" : "tool calls";
  return `Changed ${diffSummary.files.length} ${fileWord} with ${result.stats.toolCalls} ${toolWord} (${formatLineStats(diffSummary.additions, diffSummary.deletions)}).`;
}
function formatLineStats(additions, deletions) {
  if (additions === 0 && deletions === 0) {
    return "no line changes";
  }
  return `+${additions}/-${deletions}`;
}
function normalizeDiffPath(path150) {
  const trimmed2 = path150.trim();
  if (trimmed2 === "/dev/null") {
    return trimmed2;
  }
  return trimmed2.replace(/^[ab]\//, "");
}
function parseDiffGitPath(line) {
  const prefix = "diff --git a/";
  const separator = " b/";
  if (!line.startsWith(prefix)) {
    return void 0;
  }
  const separatorIndex = line.lastIndexOf(separator);
  if (separatorIndex < prefix.length) {
    return void 0;
  }
  const pathStart = separatorIndex + separator.length;
  if (pathStart >= line.length) {
    return void 0;
  }
  return line.slice(pathStart);
}
var init_diff_summary = __esm({
  "packages/core/dist/src/agents/arena/diff-summary.js"() {
    "use strict";
    init_esbuild_shims();
    init_agent_types();
    __name(summarizeUnifiedDiff, "summarizeUnifiedDiff");
    __name(buildFallbackApproachSummary, "buildFallbackApproachSummary");
    __name(formatLineStats, "formatLineStats");
    __name(normalizeDiffPath, "normalizeDiffPath");
    __name(parseDiffGitPath, "parseDiffGitPath");
  }
});

// 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(path150, isFile4, isDirectory) {
      log(`checking %s`, path150);
      try {
        const stat14 = fs_1.statSync(path150);
        if (stat14.isFile() && isFile4) {
          log(`[OK] path represents a file`);
          return true;
        }
        if (stat14.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 exists3(path150, type = exports2.READABLE) {
      return check2(path150, (type & exports2.FILE) > 0, (type & exports2.FOLDER) > 0);
    }
    __name(exists3, "exists");
    exports2.exists = exists3;
    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 promise2 = new Promise((_done, _fail) => {
        done = _done;
        fail = _fail;
      });
      return {
        promise: promise2,
        done(result) {
          if (status === "pending") {
            status = "resolved";
            done(result);
          }
        },
        fail(error40) {
          if (status === "pending") {
            status = "rejected";
            fail(error40);
          }
        },
        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 spawn3 } 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(path150) {
  return path150 instanceof String && cache.has(path150);
}
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(path150) {
  return (0, import_file_exists.exists)(path150, 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 i4 = 0, max = input.length; i4 < max; i4++) {
    output.push(prefix, input[i4]);
  }
  return output;
}
function bufferToString(input) {
  return (Array.isArray(input) ? Buffer22.concat(input) : input).toString("utf-8");
}
function pick2(source2, properties) {
  return Object.assign(
    {},
    ...properties.map((property) => property in source2 ? { [property]: source2[property] } : {})
  );
}
function delay3(duration3 = 0) {
  return new Promise((done) => setTimeout(done, duration3));
}
function orVoid(input) {
  if (input === false) {
    return void 0;
  }
  return input;
}
function filterType(input, filter5, def2) {
  if (filter5(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(args2, initialPrimitive = 0, objectOnly = false) {
  const command2 = [];
  for (let i4 = 0, max = initialPrimitive < 0 ? args2.length : initialPrimitive; i4 < max; i4++) {
    if ("string|number".includes(typeof args2[i4])) {
      command2.push(String(args2[i4]));
    }
  }
  appendTaskOptions(trailingOptionsArgument(args2), command2);
  if (!objectOnly) {
    command2.push(...trailingArrayArgument(args2));
  }
  return command2;
}
function trailingArrayArgument(args2) {
  const hasTrailingCallback = typeof last(args2) === "function";
  return filterType(last(args2, hasTrailingCallback ? 1 : 0), filterArray, []);
}
function trailingOptionsArgument(args2) {
  const hasTrailingCallback = filterFunction(last(args2));
  return filterType(last(args2, hasTrailingCallback ? 1 : 0), filterPlainObject);
}
function trailingFunctionArgument(args2, includeNoop = true) {
  const callback = asFunction(last(args2));
  return includeNoop || isUserFunction(callback) ? callback : void 0;
}
function callTaskParser(parser42, streams) {
  return parser42(streams.stdOut, streams.stdErr);
}
function parseStringResponse(result, parsers12, texts, trim2 = true) {
  asArray(texts).forEach((text) => {
    for (let lines = toLinesWithContent(text, trim2), i4 = 0, max = lines.length; i4 < max; i4++) {
      const line = /* @__PURE__ */ __name((offset = 0) => {
        if (i4 + offset >= max) {
          return;
        }
        return lines[i4 + offset];
      }, "line");
      parsers12.some(({ parse: parse17 }) => parse17(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(path150) {
      return /^\.(git)?$/.test(path150.trim());
    }
  };
}
function checkIsBareRepoTask() {
  const commands = ["rev-parse", "--is-bare-repository"];
  return {
    commands,
    format: "utf-8",
    onError,
    parser
  };
}
function isNotRepoMessage(error40) {
  return /(Not a git repository|Kein Git-Repository)/i.test(String(error40));
}
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(error40) {
  return {
    commands: EMPTY_COMMANDS,
    format: "empty",
    parser() {
      throw typeof error40 === "string" ? new TaskConfigurationError(error40) : error40;
    }
  };
}
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((test2) => CleanOptionValues.has(test2));
}
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 i4 = 0, max = lines.length - 1; i4 < max; ) {
    const file2 = configFilePath(lines[i4++]);
    let value = lines[i4++];
    let key = requestedKey;
    if (value.includes("\n")) {
      const line = splitOn(value, "\n");
      key = line[0];
      value = line[1];
    }
    yield { file: file2, key, value };
  }
}
function asConfigScope(scope, fallback) {
  if (typeof scope === "string" && GitConfigScope.hasOwnProperty(scope)) {
    return scope;
  }
  return fallback;
}
function addConfigTask(key, value, append22, scope) {
  const commands = ["config", `--${scope}`];
  if (append22) {
    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 [path150, line, preview] = input.split(NULL2);
    paths.add(path150);
    (results[path150] = results[path150] || []).push({
      line: asNumber(line),
      path: path150,
      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, ...args2) => {
      to(message, ...args2);
      forward(message, ...args2);
    };
  }
  return (message, ...args2) => {
    to(`%s ${message}`, prefix, ...args2);
    if (forward) {
      forward(message, ...args2);
    }
  };
}
function childLoggerName(name4, childDebugger, { namespace: parentNamespace }) {
  if (typeof name4 === "string") {
    return name4;
  }
  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(name4, initial) {
    return append(
      spawned,
      createLogger(label, key.replace(/^[^:]+/, name4), initial, infoDebugger)
    );
  }
  __name(sibling, "sibling");
  function step(phase) {
    const stepPrefix = phase && `[${phase}]` || "";
    const debug22 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP;
    const info2 = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug22);
    return Object.assign(debugDebugger ? debug22 : info2, {
      label,
      sibling,
      info: info2,
      step
    });
  }
  __name(step, "step");
}
function pluginContext(task, commands) {
  return {
    method: first(task.commands) || "",
    commands
  };
}
function onErrorReceived(target, logger6) {
  return (err2) => {
    logger6(`[ERROR] child process exception %o`, err2);
    target.push(Buffer.from(String(err2.stack), "ascii"));
  };
}
function onDataReceived(target, name4, logger6, output) {
  return (buffer) => {
    logger6(`%s received %L bytes`, name4, 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((err2) => {
    if (err2?.task === task) {
      callback(
        err2 instanceof GitResponseError ? addDeprecationNoticeToError(err2) : err2,
        void 0
      );
    }
  }, "onError2");
  response.then(onSuccess, onError2);
}
function addDeprecationNoticeToError(err2) {
  let log = /* @__PURE__ */ __name((name4) => {
    console.warn(
      `simple-git deprecation notice: accessing GitResponseError.${name4} should be GitResponseError.git.${name4}, this will no longer be available in version 3`
    );
    log = NOOP;
  }, "log");
  return Object.create(err2, Object.getOwnPropertyNames(err2.git).reduce(descriptorReducer, {}));
  function descriptorReducer(all4, name4) {
    if (name4 in err2) {
      return all4;
    }
    all4[name4] = {
      enumerable: false,
      configurable: false,
      get() {
        log(name4);
        return err2.git[name4];
      }
    };
    return all4;
  }
  __name(descriptorReducer, "descriptorReducer");
}
function changeWorkingDirectoryTask(directory, root) {
  return adhocExecTask((instance2) => {
    if (!folderExists(directory)) {
      throw new Error(`Git.cwd: cannot change to non-directory "${directory}"`);
    }
    return (root || instance2).cwd = directory;
  });
}
function checkoutTask(args2) {
  const commands = ["checkout", ...args2];
  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, write3) {
  const commands = ["hash-object", filePath];
  if (write3) {
    commands.push("-w");
  }
  return straightThroughStringTask(commands, true);
}
function parseInit(bare, path150, text) {
  const response = String(text).trim();
  let result;
  if (result = initResponseRegex.exec(response)) {
    return new InitSummary(bare, path150, false, result[1]);
  }
  if (result = reInitResponseRegex.exec(response)) {
    return new InitSummary(bare, path150, 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, path150, /^re/i.test(response), gitDir);
}
function hasBareCommand(command2) {
  return command2.includes(bareCommand);
}
function initTask(bare = false, path150, 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"), path150, text);
    }
  };
}
function logFormatFromCommand(customArgs) {
  for (let i4 = 0; i4 < customArgs.length; i4++) {
    const format4 = logFormatRegex.exec(customArgs[i4]);
    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 all4 = 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: all4,
      latest: all4.length && all4[0] || null,
      total: all4.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 flags2 = customArgs.filter(isLogFormat);
  if (flags2.length > 1) {
    return configurationErrorTask(
      `Summary flags are mutually exclusive - pick one of ${flags2.join(",")}`
    );
  }
  if (flags2.length && customArgs.includes("-z")) {
    return configurationErrorTask(
      `Summary flag ${flags2} 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((out2, key) => {
    if (!(key in excludeOptions)) {
      out2[key] = input[key];
    }
    return out2;
  }, {});
}
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 merge5 = parseMergeResult(stdOut, stdErr);
      if (merge5.failed) {
        throw new GitResponseError(merge5);
      }
      return merge5;
    }
  };
}
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, file2) => append(result.conflicted, file2)));
}
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, path150) {
    const raw2 = `${index}${workingDir}`;
    const handler = parsers6.get(raw2);
    if (handler) {
      handler(result, path150);
    }
    if (raw2 !== "##" && raw2 !== "!!") {
      result.files.push(new FileStatusSummary(path150, 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 = "", installed2 = true) {
  return Object.defineProperty(
    {
      major: major2,
      minor,
      patch,
      agent,
      installed: installed2
    },
    "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, error40, done, fail) {
          if (result.exitCode === -2) {
            return done(Buffer.from(NOT_INSTALLED));
          }
          fail(error40);
        }
      });
    }
  };
}
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 }, error40, done, fail) {
      if (!hasBranchDeletionError(String(error40), exitCode)) {
        return fail(error40);
      }
      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 }, error40, _2, fail) {
      if (!hasBranchDeletionError(String(error40), exitCode)) {
        return fail(error40);
      }
      throw new GitResponseError(
        task.parser(bufferToString(stdOut), bufferToString(stdErr)),
        String(error40)
      );
    }
  };
  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, ([name4]) => remotes[name4] = { name: name4 });
  return Object.values(remotes);
}
function parseGetRemotesVerbose(text) {
  const remotes = {};
  forEach(text, ([name4, url3, purpose]) => {
    if (!remotes.hasOwnProperty(name4)) {
      remotes[name4] = {
        name: name4,
        refs: { fetch: "", push: "" }
      };
    }
    if (purpose && url3) {
      remotes[name4].refs[purpose.replace(/[^a-z]/g, "")] = url3;
    }
  });
  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, path150) {
  return subModuleTask(["add", repo, path150]);
}
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(name4) {
  return {
    format: "utf-8",
    commands: ["tag", name4],
    parser() {
      return { name: name4 };
    }
  };
}
function addAnnotatedTagTask(name4, tagMessage) {
  return {
    format: "utf-8",
    commands: ["tag", "-a", "-m", tagMessage, name4],
    parser() {
      return { name: name4 };
    }
  };
}
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(args2, context2) {
      args2.forEach((current, index) => {
        const next = index < args2.length ? args2[index + 1] : "";
        allowUnsafeProtocolOverride || preventProtocolOverride(current, next);
        allowUnsafePack || preventUploadPack(current, context2.method);
      });
      return args2;
    }
  };
}
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 ? never2 : events.closeTimeout.promise,
      onExit === false ? never2 : 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(() => delay3(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 delay3(50);
        }
        close(events.exitCode);
      } catch (err2) {
        close(events.exitCode, err2);
      }
    }
  };
}
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 [binary2, prefix] = input;
  return {
    binary: binary2,
    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 getErrorMessage3(result) {
  return Buffer.concat([...result.stdOut, ...result.stdErr]);
}
function errorDetectionHandler(overwrite = false, isError = isTaskError, errorMessage = getErrorMessage3) {
  return (error40, result) => {
    if (!overwrite && error40 || !isError(result)) {
      return error40;
    }
    return errorMessage(result);
  };
}
function errorDetectionPlugin(config2) {
  return {
    type: "task.error",
    action(data, context2) {
      const error40 = config2(data.error, {
        stdErr: context2.stdErr,
        stdOut: context2.stdOut,
        exitCode: context2.exitCode
      });
      if (Buffer.isBuffer(error40)) {
        return { error: new GitError(void 0, error40.toString("utf-8")) };
      }
      return {
        error: error40
      };
    }
  };
}
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(args2, context2) {
      if (!progressMethods.includes(context2.method)) {
        return args2;
      }
      return including(args2, progressCommand);
    }
  };
  return [onArgs, onProgress];
}
function progressEventStage(input) {
  return String(input.toLowerCase().split(" ", 1)) || "unknown";
}
function spawnOptionsPlugin(spawnOptions) {
  const options2 = pick2(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 stop3() {
          context2.spawned.stdout?.off("data", wait);
          context2.spawned.stderr?.off("data", wait);
          context2.spawned.off("exit", stop3);
          context2.spawned.off("close", stop3);
          timeout2 && clearTimeout(timeout2);
        }
        __name(stop3, "stop");
        function kill() {
          stop3();
          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", stop3);
        context2.spawned.on("close", stop3);
        wait();
      }
    };
  }
}
function suffixPathsPlugin() {
  return {
    type: "spawn.args",
    action(data) {
      const prefix = [];
      let suffix;
      function append22(args2) {
        (suffix = suffix || []).push(...args2);
      }
      __name(append22, "append2");
      for (let i4 = 0; i4 < data.length; i4++) {
        const param = data[i4];
        if (isPathSpec(param)) {
          append22(toPaths(param));
          continue;
        }
        if (param === "--") {
          append22(
            data.slice(i4 + 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_util4, 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_task, 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, Query2, _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, never2, WRONG_NUMBER_ERR, WRONG_CHARS_ERR, PluginStore, Git, simpleGit;
var init_esm8 = __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, all4) => {
      for (var name4 in all4)
        __defProp2(target, name4, { get: all4[name4], 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(pick2, "pick");
    __name(delay3, "delay");
    __name(orVoid, "orVoid");
    init_util4 = __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_util4();
        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_util4();
        init_pathspec();
      }
    });
    __name(callTaskParser, "callTaskParser");
    __name(parseStringResponse, "parseStringResponse");
    init_task_parser = __esm2({
      "src/lib/utils/task-parser.ts"() {
        "use strict";
        init_util4();
      }
    });
    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(() => delay3, "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(() => pick2, "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_util4();
      }
    });
    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 }, error40, done, fail) => {
          if (exitCode === 128 && isNotRepoMessage(error40)) {
            return done(Buffer.from("false"));
          }
          fail(error40);
        }, "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_task = __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_task();
        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((all4, file2) => {
                return Object.assign(all4, this.values[file2]);
              }, {});
            }
            return this._all;
          }
          addFile(file2) {
            if (!(file2 in this.values)) {
              const latest = last(this.files);
              this.values[file2] = latest ? Object.create(this.values[latest]) : {};
              this.files.push(file2);
            }
            return this.values[file2];
          }
          addValue(file2, key, value) {
            const values = this.addFile(file2);
            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_task();
        disallowedOptions = ["-h"];
        Query2 = Symbol("grepQuery");
        GrepQuery = class {
          static {
            __name(this, "GrepQuery");
          }
          constructor() {
            this[_a4] = [];
          }
          *[(_a4 = Query2, Symbol.iterator)]() {
            for (const query of this[Query2]) {
              yield query;
            }
          }
          and(...and) {
            and.length && this[Query2].push("--and", "(", ...prefixedArray(and, "-e"), ")");
            return this;
          }
          param(...param) {
            this[Query2].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_task();
        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 name4 = _TasksPendingQueue.getName(task.commands[0]);
            const logger6 = createLogger(this.logLabel, name4);
            return {
              task,
              logger: logger6,
              name: name4
            };
          }
          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(err2) {
            for (const [task, { logger: logger6 }] of Array.from(this._queue.entries())) {
              if (task === err2.task) {
                logger6.info(`Failed %o`, err2);
                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`,
                  err2.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(name4 = "empty") {
            return `task:${name4}:${++_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_task();
        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(cwd6) {
            this._cwd = cwd6;
          }
          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 binary2 = this._plugins.exec("spawn.binary", "", pluginContext(task, task.commands));
            const args2 = this._plugins.exec(
              "spawn.args",
              [...task.commands],
              pluginContext(task, task.commands)
            );
            const raw2 = await this.gitResponse(
              task,
              binary2,
              args2,
              this.outputHandler,
              logger6.step("SPAWN")
            );
            const outputStreams = await this.handleTaskData(task, args2, 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, args2, 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: error40 } = this._plugins.exec(
                "task.error",
                { error: rejection },
                {
                  ...pluginContext(task, args2),
                  ...result
                }
              );
              if (error40 && task.onError) {
                logger6.info(`exitCode=%s handling with custom error handler`);
                return task.onError(
                  result,
                  error40,
                  (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 (error40) {
                logger6.info(
                  `handling as error: exitCode=%s stdErr=%s rejection=%o`,
                  exitCode,
                  stdErr.length,
                  rejection
                );
                return fail(error40);
              }
              logger6.info(`retrieving task output complete`);
              done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr)));
            });
          }
          async gitResponse(task, command2, args2, 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, args2);
              logger6("%O", spawnOptions);
              let rejection = this._beforeSpawn(task, args2);
              if (rejection) {
                return done({
                  stdOut,
                  stdErr,
                  exitCode: 9901,
                  rejection
                });
              }
              this._plugins.exec("spawn.before", void 0, {
                ...pluginContext(task, args2),
                kill(reason) {
                  rejection = reason || rejection;
                }
              });
              const spawned = spawn3(command2, args2, 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, [...args2]);
              }
              this._plugins.exec("spawn.after", void 0, {
                ...pluginContext(task, args2),
                spawned,
                close(exitCode, reason) {
                  done({
                    stdOut,
                    stdErr,
                    exitCode,
                    rejection: rejection || reason
                  });
                },
                kill(reason) {
                  if (spawned.killed) {
                    return;
                  }
                  rejection = reason;
                  spawned.kill("SIGINT");
                }
              });
            });
          }
          _beforeSpawn(task, args2) {
            let rejection;
            this._plugins.exec("spawn.before", void 0, {
              ...pluginContext(task, args2),
              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(cwd6, _scheduler, _plugins) {
            this.cwd = cwd6;
            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_task();
      }
    });
    __name(checkoutTask, "checkoutTask");
    __name(checkout_default, "checkout_default");
    init_checkout = __esm2({
      "src/lib/tasks/checkout.ts"() {
        "use strict";
        init_utils6();
        init_task();
      }
    });
    __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 parts2 = author.split("<");
            const email3 = parts2.pop();
            if (!email3 || !email3.includes("@")) {
              return;
            }
            result.author = {
              email: email3.substr(0, email3.length - 1),
              name: parts2.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_task();
      }
    });
    __name(first_commit_default, "first_commit_default");
    init_first_commit = __esm2({
      "src/lib/tasks/first-commit.ts"() {
        "use strict";
        init_utils6();
        init_task();
      }
    });
    __name(hashObjectTask, "hashObjectTask");
    init_hash_object = __esm2({
      "src/lib/tasks/hash-object.ts"() {
        "use strict";
        init_task();
      }
    });
    __name(parseInit, "parseInit");
    init_InitSummary = __esm2({
      "src/lib/responses/InitSummary.ts"() {
        "use strict";
        InitSummary = class {
          static {
            __name(this, "InitSummary");
          }
          constructor(bare, path150, existing, gitDir) {
            this.bare = bare;
            this.path = path150;
            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, [file2, changes, alterations = ""]) => {
              result.files.push({
                file: file2.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, [file2, before, after]) => {
              result.files.push({
                file: file2.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, file2]) => {
              const insertions = asNumber(changesInsert);
              const deletions = asNumber(changesDelete);
              result.changed++;
              result.insertions += insertions;
              result.deletions += deletions;
              result.files.push({
                file: file2,
                changes: insertions + deletions,
                insertions,
                deletions,
                binary: false
              });
            }
          ),
          new LineParser(/-\t-\t(.+)$/, (result, [file2]) => {
            result.changed++;
            result.files.push({
              file: file2,
              after: 0,
              before: 0,
              binary: true
            });
          })
        ];
        nameOnlyParser = [
          new LineParser(/(.+)$/, (result, [file2]) => {
            result.changed++;
            result.files.push({
              file: file2,
              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_task();
      }
    });
    __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_task();
        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, file2 = null, meta) {
            this.reason = reason;
            this.file = file2;
            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, url3]) => {
              result.remoteMessages.vulnerabilities = {
                count: asNumber(count),
                summary,
                url: url3
              };
            }
          )
        ];
        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, [file2, insertions, deletions]) => {
            result.files.push(file2);
            if (insertions) {
              result.insertions[file2] = insertions.length;
            }
            if (deletions) {
              result.deletions[file2] = 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, file2]) => {
            append(result.files, file2);
            append(action === "create" ? result.created : result.deleted, file2);
          })
        ];
        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, file2]) => {
            summary.conflicts.push(new MergeSummaryConflict(reason, file2));
          }),
          new LineParser(
            /^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,
            (summary, [reason, file2, deleteRef]) => {
              summary.conflicts.push(new MergeSummaryConflict(reason, file2, { 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_task();
      }
    });
    __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_task();
      }
    });
    init_FileStatusSummary = __esm2({
      "src/lib/responses/FileStatusSummary.ts"() {
        "use strict";
        fromPathRegex = /^(.+)\0(.+)$/;
        FileStatusSummary = class {
          static {
            __name(this, "FileStatusSummary");
          }
          constructor(path150, index, working_dir) {
            this.path = path150;
            this.index = index;
            this.working_dir = working_dir;
            if (index === "R" || working_dir === "R") {
              const detail = fromPathRegex.exec(path150) || [null, path150, path150];
              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, file2) => append(result.created, file2)
          ),
          parser3(
            " ",
            "D",
            (result, file2) => append(result.deleted, file2)
          ),
          parser3(
            " ",
            "M",
            (result, file2) => append(result.modified, file2)
          ),
          parser3(
            "A",
            " ",
            (result, file2) => append(result.created, file2) && append(result.staged, file2)
          ),
          parser3(
            "A",
            "M",
            (result, file2) => append(result.created, file2) && append(result.staged, file2) && append(result.modified, file2)
          ),
          parser3(
            "D",
            " ",
            (result, file2) => append(result.deleted, file2) && append(result.staged, file2)
          ),
          parser3(
            "M",
            " ",
            (result, file2) => append(result.modified, file2) && append(result.staged, file2)
          ),
          parser3(
            "M",
            "M",
            (result, file2) => append(result.modified, file2) && append(result.staged, file2)
          ),
          parser3("R", " ", (result, file2) => {
            append(result.renamed, renamedFile(file2));
          }),
          parser3("R", "M", (result, file2) => {
            const renamed = renamedFile(file2);
            append(result.renamed, renamed);
            append(result.modified, renamed.to);
          }),
          parser3("!", "!", (_result, _file2) => {
            append(_result.ignored = _result.ignored || [], _file2);
          }),
          parser3(
            "?",
            "?",
            (result, file2) => append(result.not_added, file2)
          ),
          ...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 i4 = 0, l3 = lines.length; i4 < l3; ) {
            let line = lines[i4++].trim();
            if (!line) {
              continue;
            }
            if (line.charAt(0) === "R") {
              line += NULL2 + (lines[i4++] || "");
            }
            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_task();
        init_version4();
        init_utils6();
        SimpleGitApi = class {
          static {
            __name(this, "SimpleGitApi");
          }
          constructor(_executor) {
            this._executor = _executor;
          }
          _runTask(task, then) {
            const chain2 = this._executor.chain();
            const promise2 = chain2.push(task);
            if (then) {
              taskCallback(task, promise2, then);
            }
            return Object.create(this, {
              then: { value: promise2.then.bind(promise2) },
              catch: { value: promise2.catch.bind(promise2) },
              _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(path150, write3) {
            return this._runTask(
              hashObjectTask(path150, write3 === 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: promise2, done } = (0, import_promise_deferred.createDeferred)();
            return {
              promise: promise2,
              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: promise2, id } = append(this.pending, createScheduledTask());
            this.logger(`Scheduling id=%s`, id);
            this.schedule();
            return promise2;
          }
        };
      }
    });
    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_task();
      }
    });
    __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, name4, commit, label) {
            if (status === "*") {
              this.detached = detached;
              this.current = name4;
            }
            this.all.push(name4);
            this.branches[name4] = {
              current: status === "*",
              linkedWorkTree: status === "+",
              name: name4,
              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, name4, commit, label]) => {
              result.push(branchStatus(current), true, name4, commit, label);
            }
          ),
          new LineParser(
            /^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,
            (result, [current, name4, commit, label]) => {
              result.push(branchStatus(current), false, name4, 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((file2) => !!file2);
        }, "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_task();
        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, [name4, tracking]) => {
            result.branches.push({
              name: name4,
              tracking
            });
          }),
          new LineParser(/\* \[new tag]\s+(\S+)\s*-> (.+)$/, (result, [name4, tracking]) => {
            result.tags.push({
              name: name4,
              tracking
            });
          }),
          new LineParser(/- \[deleted]\s+\S+\s*-> (.+)$/, (result, [tracking]) => {
            result.deleted.push({
              tracking
            });
          }),
          new LineParser(
            /\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,
            (result, [from, to, name4, tracking]) => {
              result.updated.push({
                name: name4,
                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_task();
      }
    });
    __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_task();
      }
    });
    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_task();
      }
    });
    __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(all4, latest) {
            this.all = all4;
            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 i4 = 0, l3 = Math.max(partsA.length, partsB.length); i4 < l3; i4++) {
                const diff4 = sorted(toNumber(partsA[i4]), toNumber(partsB[i4]));
                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_task(), __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_task(), __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(name4, value) {
          if (arguments.length === 1 && typeof name4 === "object") {
            this._executor.env = name4;
          } else {
            (this._executor.env = this._executor.env || {})[name4] = 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(err2, 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(name4) {
          const task = typeof name4 === "string" ? addTagTask2(name4) : 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 i4 = 0; i4 < command2.length && createRestCommands; i4++) {
            if (!filterPrimitives2(command2[i4])) {
              command2.splice(i4, command2.length - i4);
              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, path150, then) {
          return this._runTask(addSubModuleTask2(repo, path150), trailingFunctionArgument2(arguments));
        };
        Git2.prototype.submoduleUpdate = function(args2, then) {
          return this._runTask(
            updateSubModuleTask2(getTrailingOptions2(arguments, true)),
            trailingFunctionArgument2(arguments)
          );
        };
        Git2.prototype.submoduleInit = function(args2, 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, args2) {
          var handler = trailingFunctionArgument2(args2);
          var command2 = ["cat-file"];
          var options2 = args2[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, plugin4, message) {
        super(task, message);
        this.task = task;
        this.plugin = plugin4;
        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();
    never2 = (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(getErrorMessage3, "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 plugin4 = append(this.plugins, { type, action });
        return () => this.plugins.delete(plugin4);
      }
      add(plugin4) {
        const plugins = [];
        asArray(plugin4).forEach((plugin22) => plugin22 && this.plugins.add(append(plugins, plugin22)));
        return () => {
          plugins.forEach((plugin22) => this.plugins.delete(plugin22));
        };
      }
      exec(type, data, context2) {
        let output = data;
        const contextual = Object.freeze(Object.create(context2));
        for (const plugin4 of this.plugins) {
          if (plugin4.type === type) {
            output = plugin4.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/gitInit.js
async function initRepositoryWithMainBranch(git) {
  await git.init(false);
  await git.raw(["symbolic-ref", "HEAD", "refs/heads/main"]);
}
var init_gitInit = __esm({
  "packages/core/dist/src/services/gitInit.js"() {
    "use strict";
    init_esbuild_shims();
    __name(initRepositoryWithMainBranch, "initRepositoryWithMainBranch");
  }
});

// packages/core/dist/src/services/gitWorktreeService.js
import * as fs43 from "node:fs/promises";
import * as path40 from "node:path";
import { execSync as execSync4 } from "node:child_process";
var BASELINE_COMMIT_MESSAGE, WORKTREES_DIR, GitWorktreeService;
var init_gitWorktreeService = __esm({
  "packages/core/dist/src/services/gitWorktreeService.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm8();
    init_storage();
    init_shell_utils();
    init_errors();
    init_gitInit();
    BASELINE_COMMIT_MESSAGE = "baseline (dirty state overlay)";
    WORKTREES_DIR = "worktrees";
    GitWorktreeService = class _GitWorktreeService {
      static {
        __name(this, "GitWorktreeService");
      }
      sourceRepoPath;
      git;
      customBaseDir;
      constructor(sourceRepoPath, customBaseDir) {
        this.sourceRepoPath = path40.resolve(sourceRepoPath);
        this.git = simpleGit(this.sourceRepoPath);
        this.customBaseDir = customBaseDir;
      }
      /**
       * Gets the directory where worktrees are stored.
       * @param customDir - Optional custom base directory override
       */
      static getBaseDir(customDir) {
        if (customDir) {
          return path40.resolve(customDir);
        }
        return path40.join(Storage.getGlobalQwenDir(), WORKTREES_DIR);
      }
      /**
       * Gets the directory for a specific session.
       * @param customBaseDir - Optional custom base directory override
       */
      static getSessionDir(sessionId, customBaseDir) {
        return path40.join(_GitWorktreeService.getBaseDir(customBaseDir), sessionId);
      }
      /**
       * Gets the worktrees directory for a specific session.
       * @param customBaseDir - Optional custom base directory override
       */
      static getWorktreesDir(sessionId, customBaseDir) {
        return path40.join(_GitWorktreeService.getSessionDir(sessionId, customBaseDir), WORKTREES_DIR);
      }
      /**
       * Instance-level base dir, using the custom dir if provided at construction.
       */
      getBaseDirForInstance() {
        return _GitWorktreeService.getBaseDir(this.customBaseDir);
      }
      /**
       * Checks if git is available on the system.
       */
      async checkGitAvailable() {
        const { available } = isCommandAvailable("git");
        if (!available) {
          return {
            available: false,
            error: "Git is not installed. Please install Git."
          };
        }
        return { available: true };
      }
      /**
       * Checks if the source path is a git repository.
       */
      async isGitRepository() {
        try {
          const isRoot = await this.git.checkIsRepo(CheckRepoActions.IS_REPO_ROOT);
          if (isRoot) {
            return true;
          }
        } catch {
        }
        try {
          return await this.git.checkIsRepo();
        } catch {
          return false;
        }
      }
      /**
       * Initializes the source directory as a git repository.
       * Returns true if initialization was performed, false if already a repo.
       */
      async initializeRepository() {
        const isRepo = await this.isGitRepository();
        if (isRepo) {
          return { initialized: false };
        }
        try {
          await initRepositoryWithMainBranch(this.git);
          await this.git.add(".");
          await this.git.commit("Initial commit", {
            "--allow-empty": null
          });
          return { initialized: true };
        } catch (error40) {
          return {
            initialized: false,
            error: `Failed to initialize git repository: ${error40 instanceof Error ? error40.message : "Unknown error"}`
          };
        }
      }
      /**
       * Gets the current branch name.
       */
      async getCurrentBranch() {
        const branch = await this.git.revparse(["--abbrev-ref", "HEAD"]);
        return branch.trim();
      }
      /**
       * Gets the current commit hash.
       */
      async getCurrentCommitHash() {
        const hash = await this.git.revparse(["HEAD"]);
        return hash.trim();
      }
      /**
       * Creates a single worktree.
       */
      async createWorktree(sessionId, name4, baseBranch) {
        try {
          const worktreesDir = _GitWorktreeService.getWorktreesDir(sessionId, this.customBaseDir);
          await fs43.mkdir(worktreesDir, { recursive: true });
          const sanitizedName = this.sanitizeName(name4);
          const worktreePath = path40.join(worktreesDir, sanitizedName);
          const exists3 = await this.pathExists(worktreePath);
          if (exists3) {
            return {
              success: false,
              error: `Worktree already exists at ${worktreePath}`
            };
          }
          const base = baseBranch || await this.getCurrentBranch();
          const shortSession = sessionId.slice(0, 6);
          const branchName = `${base}-${shortSession}-${sanitizedName}`;
          await this.git.raw([
            "worktree",
            "add",
            "-b",
            branchName,
            worktreePath,
            base
          ]);
          const worktree = {
            id: `${sessionId}/${sanitizedName}`,
            name: name4,
            path: worktreePath,
            branch: branchName,
            isActive: true,
            createdAt: Date.now()
          };
          return { success: true, worktree };
        } catch (error40) {
          return {
            success: false,
            error: `Failed to create worktree for "${name4}": ${error40 instanceof Error ? error40.message : "Unknown error"}`
          };
        }
      }
      /**
       * Sets up all worktrees for a session.
       * This is the main entry point for worktree creation.
       */
      async setupWorktrees(config2) {
        const result = {
          success: false,
          sessionId: config2.sessionId,
          worktrees: [],
          worktreesByName: {},
          errors: []
        };
        const sanitizedNames = /* @__PURE__ */ new Map();
        for (const name4 of config2.worktreeNames) {
          const sanitized = this.sanitizeName(name4);
          if (!sanitized) {
            result.errors.push({
              name: name4,
              error: "Worktree name becomes empty after sanitization"
            });
            continue;
          }
          const existing = sanitizedNames.get(sanitized);
          if (existing) {
            result.errors.push({
              name: name4,
              error: `Worktree name collides with "${existing}" after sanitization`
            });
            continue;
          }
          sanitizedNames.set(sanitized, name4);
        }
        if (result.errors.length > 0) {
          return result;
        }
        const gitCheck = await this.checkGitAvailable();
        if (!gitCheck.available) {
          result.errors.push({ name: "system", error: gitCheck.error });
          return result;
        }
        const isRepo = await this.isGitRepository();
        if (!isRepo) {
          result.errors.push({
            name: "repository",
            error: "Source path is not a git repository."
          });
          return result;
        }
        const sessionDir = _GitWorktreeService.getSessionDir(config2.sessionId, this.customBaseDir);
        await fs43.mkdir(sessionDir, { recursive: true });
        const configPath = path40.join(sessionDir, "config.json");
        const configFile = {
          sessionId: config2.sessionId,
          sourceRepoPath: config2.sourceRepoPath,
          worktreeNames: config2.worktreeNames,
          baseBranch: config2.baseBranch,
          createdAt: Date.now(),
          ...config2.metadata
        };
        await fs43.writeFile(configPath, JSON.stringify(configFile, null, 2));
        let dirtyStateSnapshot = "";
        try {
          dirtyStateSnapshot = (await this.git.stash(["create"])).trim();
        } catch {
        }
        let untrackedFiles = [];
        try {
          const raw2 = await this.git.raw([
            "ls-files",
            "--others",
            "--exclude-standard"
          ]);
          untrackedFiles = raw2.trim().split("\n").filter(Boolean);
        } catch {
        }
        for (const name4 of config2.worktreeNames) {
          const createResult = await this.createWorktree(config2.sessionId, name4, config2.baseBranch);
          if (createResult.success && createResult.worktree) {
            result.worktrees.push(createResult.worktree);
            result.worktreesByName[name4] = createResult.worktree;
          } else {
            result.errors.push({
              name: name4,
              error: createResult.error || "Unknown error"
            });
          }
        }
        if (result.errors.length > 0) {
          try {
            await this.cleanupSession(config2.sessionId);
          } catch (error40) {
            result.errors.push({
              name: "cleanup",
              error: `Failed to cleanup after partial worktree creation: ${error40 instanceof Error ? error40.message : "Unknown error"}`
            });
          }
          result.success = false;
          return result;
        }
        result.success = result.worktrees.length === config2.worktreeNames.length;
        if (result.success) {
          for (const worktree of result.worktrees) {
            const wtGit = simpleGit(worktree.path);
            if (dirtyStateSnapshot) {
              try {
                await wtGit.raw(["stash", "apply", dirtyStateSnapshot]);
              } catch {
              }
            }
            for (const relPath of untrackedFiles) {
              try {
                const src = path40.join(this.sourceRepoPath, relPath);
                const dst = path40.join(worktree.path, relPath);
                await fs43.mkdir(path40.dirname(dst), { recursive: true });
                await fs43.copyFile(src, dst);
              } catch {
              }
            }
            try {
              await wtGit.add(["--all"]);
              await wtGit.commit(BASELINE_COMMIT_MESSAGE, {
                "--allow-empty": null,
                "--no-verify": null
              });
            } catch {
            }
          }
        }
        return result;
      }
      /**
       * Lists all worktrees for a session.
       */
      async listWorktrees(sessionId) {
        const worktreesDir = _GitWorktreeService.getWorktreesDir(sessionId, this.customBaseDir);
        try {
          const entries = await fs43.readdir(worktreesDir, { withFileTypes: true });
          const worktrees = [];
          for (const entry of entries) {
            if (entry.isDirectory()) {
              const worktreePath = path40.join(worktreesDir, entry.name);
              let branchName = "";
              try {
                branchName = execSync4("git rev-parse --abbrev-ref HEAD", {
                  cwd: worktreePath,
                  encoding: "utf8",
                  stdio: ["pipe", "pipe", "pipe"]
                }).trim();
              } catch {
              }
              let createdAt = Date.now();
              try {
                const stats = await fs43.stat(worktreePath);
                createdAt = stats.birthtimeMs;
              } catch {
              }
              worktrees.push({
                id: `${sessionId}/${entry.name}`,
                name: entry.name,
                path: worktreePath,
                branch: branchName,
                isActive: true,
                createdAt
              });
            }
          }
          return worktrees;
        } catch (error40) {
          if (isNodeError(error40) && error40.code === "ENOENT") {
            return [];
          }
          throw error40;
        }
      }
      /**
       * Removes a single worktree.
       */
      async removeWorktree(worktreePath) {
        try {
          await this.git.raw(["worktree", "remove", worktreePath, "--force"]);
          return { success: true };
        } catch (error40) {
          try {
            await fs43.rm(worktreePath, { recursive: true, force: true });
            await this.git.raw(["worktree", "prune"]);
            return { success: true };
          } catch (_rmError) {
            return {
              success: false,
              error: `Failed to remove worktree: ${error40 instanceof Error ? error40.message : "Unknown error"}`
            };
          }
        }
      }
      /**
       * Cleans up all worktrees and branches for a session.
       */
      async cleanupSession(sessionId) {
        const result = {
          success: true,
          removedWorktrees: [],
          removedBranches: [],
          errors: []
        };
        const worktrees = await this.listWorktrees(sessionId);
        const worktreeBranches = new Set(worktrees.map((w2) => w2.branch).filter(Boolean));
        for (const worktree of worktrees) {
          const removeResult = await this.removeWorktree(worktree.path);
          if (removeResult.success) {
            result.removedWorktrees.push(worktree.name);
          } else {
            result.errors.push(removeResult.error || `Failed to remove ${worktree.name}`);
            result.success = false;
          }
        }
        const sessionDir = _GitWorktreeService.getSessionDir(sessionId, this.customBaseDir);
        try {
          await fs43.rm(sessionDir, { recursive: true, force: true });
        } catch (error40) {
          result.errors.push(`Failed to remove session directory: ${error40 instanceof Error ? error40.message : "Unknown error"}`);
        }
        try {
          for (const branchName of worktreeBranches) {
            try {
              await this.git.branch(["-D", branchName]);
              result.removedBranches.push(branchName);
            } catch {
            }
          }
        } catch {
        }
        try {
          await this.git.raw(["worktree", "prune"]);
        } catch {
        }
        return result;
      }
      /**
       * Gets the diff between a worktree and its baseline state.
       * Prefers the baseline commit (which includes the dirty state overlay)
       * so the diff only shows the agent's changes. Falls back to the base branch
       * when no baseline commit exists.
       */
      async getWorktreeDiff(worktreePath, baseBranch) {
        const worktreeGit = simpleGit(worktreePath);
        const base = await this.resolveBaseline(worktreeGit) ?? baseBranch ?? await this.getCurrentBranch();
        try {
          return await this.withStagedChanges(worktreeGit, () => worktreeGit.diff(["--binary", "--cached", base]));
        } catch (error40) {
          return `Error getting diff: ${error40 instanceof Error ? error40.message : "Unknown error"}`;
        }
      }
      /**
       * Applies raw changes from a worktree back to the target working directory.
       *
       * Diffs from the baseline commit (which already includes the user's
       * dirty state) so the patch only contains the agent's new changes.
       * Falls back to merge-base when no baseline commit exists.
       */
      async applyWorktreeChanges(worktreePath, targetPath) {
        const target = targetPath || this.sourceRepoPath;
        const worktreeGit = simpleGit(worktreePath);
        const targetGit = simpleGit(target);
        try {
          let base = await this.resolveBaseline(worktreeGit);
          const hasBaseline = !!base;
          if (!base) {
            const targetHead = (await targetGit.revparse(["HEAD"])).trim();
            base = (await worktreeGit.raw(["merge-base", "HEAD", targetHead])).trim();
          }
          const patch = await this.withStagedChanges(worktreeGit, () => worktreeGit.diff(["--binary", "--cached", base]));
          if (!patch.trim()) {
            return { success: true };
          }
          const patchFile = path40.join(this.getBaseDirForInstance(), `.worktree-apply-${Date.now()}-${Math.random().toString(16).slice(2)}.patch`);
          await fs43.mkdir(path40.dirname(patchFile), { recursive: true });
          await fs43.writeFile(patchFile, patch, "utf-8");
          try {
            const applyArgs = hasBaseline ? ["apply", "--whitespace=nowarn", patchFile] : ["apply", "--3way", "--whitespace=nowarn", patchFile];
            await targetGit.raw(applyArgs);
          } finally {
            await fs43.rm(patchFile, { force: true });
          }
          return { success: true };
        } catch (error40) {
          return {
            success: false,
            error: `Failed to apply worktree changes: ${error40 instanceof Error ? error40.message : "Unknown error"}`
          };
        }
      }
      /**
       * Lists all sessions stored in the worktree base directory.
       */
      static async listSessions(customBaseDir) {
        const baseDir = _GitWorktreeService.getBaseDir(customBaseDir);
        const sessions = [];
        try {
          const entries = await fs43.readdir(baseDir, { withFileTypes: true });
          for (const entry of entries) {
            if (entry.isDirectory()) {
              const configPath = path40.join(baseDir, entry.name, "config.json");
              try {
                const configContent = await fs43.readFile(configPath, "utf-8");
                const config2 = JSON.parse(configContent);
                const worktreesDir = path40.join(baseDir, entry.name, WORKTREES_DIR);
                let worktreeCount = 0;
                try {
                  const worktreeEntries = await fs43.readdir(worktreesDir);
                  worktreeCount = worktreeEntries.length;
                } catch {
                }
                sessions.push({
                  sessionId: entry.name,
                  createdAt: config2.createdAt || Date.now(),
                  sourceRepoPath: config2.sourceRepoPath || "",
                  worktreeCount
                });
              } catch {
              }
            }
          }
          return sessions.sort((a2, b2) => b2.createdAt - a2.createdAt);
        } catch {
          return [];
        }
      }
      /**
       * Finds the baseline commit in a worktree, if one exists.
       * Returns the commit SHA, or null if not found.
       */
      async resolveBaseline(worktreeGit) {
        try {
          const sha = (await worktreeGit.raw([
            "log",
            "--grep",
            BASELINE_COMMIT_MESSAGE,
            "--format=%H",
            "-1"
          ])).trim();
          return sha || null;
        } catch {
          return null;
        }
      }
      /** Stages all changes, runs a callback, then resets the index. */
      async withStagedChanges(git, fn) {
        await git.add(["--all"]);
        try {
          return await fn();
        } finally {
          try {
            await git.raw(["reset"]);
          } catch {
          }
        }
      }
      sanitizeName(name4) {
        return name4.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
      }
      async pathExists(p2) {
        try {
          await fs43.access(p2);
          return true;
        } catch {
          return false;
        }
      }
    };
  }
});

// packages/core/dist/src/agents/arena/ArenaManager.js
import * as fs44 from "node:fs/promises";
import * as path41 from "node:path";
function truncateForPrompt(text, maxChars) {
  if (text.length <= maxChars)
    return text;
  return `${text.slice(0, maxChars)}
...[truncated]`;
}
function formatTranscript(transcript) {
  if (!transcript || transcript.length === 0) {
    return "";
  }
  const lines = [];
  for (const entry of transcript) {
    if (entry.thought)
      continue;
    const metadata2 = entry.metadata ?? {};
    const toolName = typeof metadata2["toolName"] === "string" ? metadata2["toolName"] : void 0;
    const success2 = typeof metadata2["success"] === "boolean" ? metadata2["success"] : void 0;
    const label = toolName ? `${entry.role}:${toolName}` : entry.role;
    const suffix = success2 === void 0 ? "" : ` (${success2 ? "ok" : "failed"})`;
    lines.push(`${label}${suffix}: ${entry.content}`);
  }
  return truncateForPrompt(lines.join("\n"), ARENA_SUMMARY_MAX_TRANSCRIPT_CHARS);
}
function parseApproachSummaryResponse(text) {
  const jsonText = extractJsonObject(text);
  if (!jsonText) {
    return void 0;
  }
  try {
    const parsed = JSON.parse(jsonText);
    if (!isRecord(parsed)) {
      return void 0;
    }
    const summary = parsed["summary"];
    if (typeof summary === "string") {
      return summary;
    }
  } catch {
    return void 0;
  }
  return void 0;
}
function extractJsonObject(text) {
  const firstBrace = text.indexOf("{");
  const lastBrace = text.lastIndexOf("}");
  if (firstBrace < 0 || lastBrace <= firstBrace) {
    return null;
  }
  return text.slice(firstBrace, lastBrace + 1);
}
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
var debugLogger44, ARENA_POLL_INTERVAL_MS, ARENA_SUMMARY_TIMEOUT_MS, ARENA_SUMMARY_MAX_DIFF_CHARS, ARENA_SUMMARY_MAX_TRANSCRIPT_CHARS, ArenaManager;
var init_ArenaManager = __esm({
  "packages/core/dist/src/agents/arena/ArenaManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_gitWorktreeService();
    init_storage();
    init_prompts();
    init_debugLogger();
    init_errors();
    init_atomicFileWrite();
    init_partUtils();
    init_arena_events();
    init_agents();
    init_agent_events();
    init_types();
    init_agent_types();
    init_telemetry();
    init_diff_summary();
    debugLogger44 = createDebugLogger("ARENA");
    ARENA_POLL_INTERVAL_MS = 500;
    ARENA_SUMMARY_TIMEOUT_MS = 2e4;
    ARENA_SUMMARY_MAX_DIFF_CHARS = 6e3;
    ARENA_SUMMARY_MAX_TRANSCRIPT_CHARS = 6e3;
    ArenaManager = class {
      static {
        __name(this, "ArenaManager");
      }
      config;
      eventEmitter;
      worktreeService;
      arenaBaseDir;
      callbacks;
      backend = null;
      cachedResult = null;
      sessionId;
      /** Short directory name used for worktree paths (derived from sessionId). */
      worktreeDirName;
      sessionStatus = ArenaSessionStatus.INITIALIZING;
      agents = /* @__PURE__ */ new Map();
      arenaConfig;
      startedAt;
      masterAbortController;
      terminalCols;
      terminalRows;
      pollingInterval = null;
      lifecyclePromise = null;
      /** Cleanup functions for in-process event bridge listeners. */
      eventBridgeCleanups = [];
      /** Guard to prevent double-emitting the session-ended telemetry event. */
      sessionEndedLogged = false;
      constructor(config2, callbacks = {}) {
        this.config = config2;
        this.callbacks = callbacks;
        this.eventEmitter = new ArenaEventEmitter();
        const arenaSettings = config2.getAgentsSettings().arena;
        this.arenaBaseDir = arenaSettings?.worktreeBaseDir ?? path41.join(Storage.getGlobalQwenDir(), "arena");
        this.worktreeService = new GitWorktreeService(config2.getWorkingDir(), this.arenaBaseDir);
        this.terminalCols = process.stdout.columns || 120;
        this.terminalRows = process.stdout.rows || 40;
      }
      // ─── Public API ────────────────────────────────────────────────
      /**
       * Get the event emitter for subscribing to Arena events.
       */
      getEventEmitter() {
        return this.eventEmitter;
      }
      /**
       * Get the current session ID.
       */
      getSessionId() {
        return this.sessionId;
      }
      /**
       * Get the current session status.
       */
      getSessionStatus() {
        return this.sessionStatus;
      }
      /**
       * Get the current task description (available while session is active).
       */
      getTask() {
        return this.arenaConfig?.task;
      }
      /**
       * Get all agent states.
       */
      getAgentStates() {
        return Array.from(this.agents.values());
      }
      /**
       * Get a specific agent state.
       */
      getAgentState(agentId) {
        return this.agents.get(agentId);
      }
      /**
       * Get the cached session result (available after session completes).
       */
      getResult() {
        return this.cachedResult;
      }
      /**
       * Get the underlying backend for direct access.
       * Returns null before the session initializes a backend.
       */
      getBackend() {
        return this.backend;
      }
      /**
       * Store the outer lifecycle promise so cancel/stop can wait for start()
       * to fully unwind before proceeding with cleanup.
       */
      setLifecyclePromise(p2) {
        this.lifecyclePromise = p2;
      }
      /**
       * Wait for the start lifecycle to fully settle (including error handling
       * and listener teardown). Resolves immediately if no lifecycle is active.
       */
      async waitForSettled() {
        if (this.lifecyclePromise) {
          await this.lifecyclePromise;
        }
      }
      // ─── PTY Interaction ───────────────────────────────────────────
      /**
       * Switch the active agent for screen display and input routing.
       */
      switchToAgent(agentId) {
        this.backend?.switchTo(agentId);
      }
      /**
       * Switch to the next agent in order.
       */
      switchToNextAgent() {
        this.backend?.switchToNext();
      }
      /**
       * Switch to the previous agent in order.
       */
      switchToPreviousAgent() {
        this.backend?.switchToPrevious();
      }
      /**
       * Get the ID of the currently active agent.
       */
      getActiveAgentId() {
        return this.backend?.getActiveAgentId() ?? null;
      }
      /**
       * Get the screen snapshot for the currently active agent.
       */
      getActiveSnapshot() {
        return this.backend?.getActiveSnapshot() ?? null;
      }
      /**
       * Get the screen snapshot for a specific agent.
       */
      getAgentSnapshot(agentId, scrollOffset = 0) {
        return this.backend?.getAgentSnapshot(agentId, scrollOffset) ?? null;
      }
      /**
       * Get the maximum scrollback length for an agent's terminal buffer.
       */
      getAgentScrollbackLength(agentId) {
        return this.backend?.getAgentScrollbackLength(agentId) ?? 0;
      }
      /**
       * Forward keyboard input to the currently active agent.
       */
      forwardInput(data) {
        return this.backend?.forwardInput(data) ?? false;
      }
      /**
       * Resize all agent terminals.
       */
      resizeAgents(cols, rows) {
        this.terminalCols = cols;
        this.terminalRows = rows;
        this.backend?.resizeAll(cols, rows);
      }
      // ─── Session Lifecycle ─────────────────────────────────────────
      /**
       * Start an Arena session.
       *
       * @param options - Arena start options
       * @returns Promise resolving to the session result
       */
      async start(options2) {
        this.validateStartOptions(options2);
        if (options2.cols && options2.cols > 0) {
          this.terminalCols = options2.cols;
        }
        if (options2.rows && options2.rows > 0) {
          this.terminalRows = options2.rows;
        }
        this.sessionId = this.config.getSessionId();
        this.worktreeDirName = await this.deriveWorktreeDirName(this.sessionId);
        this.startedAt = Date.now();
        this.sessionStatus = ArenaSessionStatus.INITIALIZING;
        this.masterAbortController = new AbortController();
        const sourceRepoPath = this.config.getWorkingDir();
        const arenaSettings = this.config.getAgentsSettings().arena;
        this.arenaConfig = {
          sessionId: this.sessionId,
          task: options2.task,
          models: options2.models,
          maxRoundsPerAgent: options2.maxRoundsPerAgent ?? arenaSettings?.maxRoundsPerAgent,
          timeoutSeconds: options2.timeoutSeconds ?? arenaSettings?.timeoutSeconds,
          approvalMode: options2.approvalMode,
          sourceRepoPath,
          chatHistory: options2.chatHistory
        };
        debugLogger44.info(`Starting Arena session: ${this.sessionId}`);
        debugLogger44.info(`Task: ${options2.task}`);
        debugLogger44.info(`Models: ${options2.models.map((m3) => m3.modelId).join(", ")}`);
        const gitCheck = await this.worktreeService.checkGitAvailable();
        if (!gitCheck.available) {
          throw new Error(gitCheck.error);
        }
        const isRepo = await this.worktreeService.isGitRepository();
        if (!isRepo) {
          throw new Error("Failed to start arena: current directory is not a git repository.");
        }
        this.eventEmitter.emit(ArenaEventType.SESSION_START, {
          sessionId: this.sessionId,
          task: options2.task,
          models: options2.models,
          timestamp: Date.now()
        });
        logArenaSessionStarted(this.config, makeArenaSessionStartedEvent({
          arena_session_id: this.sessionId,
          model_ids: options2.models.map((m3) => m3.modelId),
          task_length: options2.task.length
        }));
        try {
          const displayMode = options2.displayMode ?? this.config.getAgentsSettings().displayMode;
          await this.initializeBackend(displayMode);
          if (this.masterAbortController?.signal.aborted) {
            this.sessionStatus = ArenaSessionStatus.CANCELLED;
            const result2 = await this.collectResults();
            this.emitSessionEnded("cancelled");
            return result2;
          }
          this.emitProgress(`Setting up environment for agents\u2026`);
          await this.setupWorktrees();
          if (this.masterAbortController?.signal.aborted) {
            this.sessionStatus = ArenaSessionStatus.CANCELLED;
            const result2 = await this.collectResults();
            this.emitSessionEnded("cancelled");
            return result2;
          }
          const worktreeInfo = Array.from(this.agents.values()).map((agent, i4) => `  ${i4 + 1}. ${agent.model.modelId} \u2192 ${agent.worktree.path}`).join("\n");
          this.emitProgress(`Environment ready. Agent worktrees:
${worktreeInfo}`);
          this.emitProgress("Launching agents\u2026");
          this.sessionStatus = ArenaSessionStatus.RUNNING;
          await this.runAgents();
          if (this.sessionStatus === ArenaSessionStatus.RUNNING) {
            this.sessionStatus = ArenaSessionStatus.IDLE;
          }
          const result = await this.collectResults();
          this.cachedResult = result;
          this.eventEmitter.emit(ArenaEventType.SESSION_COMPLETE, {
            sessionId: this.sessionId,
            result,
            timestamp: Date.now()
          });
          this.callbacks.onArenaComplete?.(result);
          return result;
        } catch (error40) {
          this.sessionStatus = ArenaSessionStatus.FAILED;
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          this.eventEmitter.emit(ArenaEventType.SESSION_ERROR, {
            sessionId: this.sessionId,
            error: errorMessage,
            timestamp: Date.now()
          });
          this.emitSessionEnded("failed");
          this.callbacks.onArenaError?.(error40 instanceof Error ? error40 : new Error(errorMessage));
          throw error40;
        }
      }
      /**
       * Cancel the current Arena session.
       */
      async cancel() {
        if (!this.sessionId) {
          return;
        }
        debugLogger44.info(`Cancelling Arena session: ${this.sessionId}`);
        this.stopPolling();
        this.masterAbortController?.abort();
        this.backend?.stopAll();
        await this.pollAgentStatuses().catch(() => {
        });
        for (const agent of this.agents.values()) {
          if (!isTerminalStatus(agent.status)) {
            agent.syncStats?.();
          }
        }
        for (const agent of this.agents.values()) {
          if (!isTerminalStatus(agent.status)) {
            agent.abortController.abort();
            agent.stats.durationMs = Date.now() - agent.startedAt;
            this.updateAgentStatus(agent.agentId, AgentStatus.CANCELLED);
          }
        }
        this.sessionStatus = ArenaSessionStatus.CANCELLED;
      }
      /**
       * Clean up the Arena session (remove worktrees, kill processes, etc.).
       */
      async cleanup() {
        if (!this.sessionId) {
          return;
        }
        debugLogger44.info(`Cleaning up Arena session: ${this.sessionId}`);
        this.emitSessionEnded(this.sessionStatus === ArenaSessionStatus.CANCELLED ? "cancelled" : "discarded");
        this.stopPolling();
        this.teardownEventBridge();
        if (this.backend) {
          await this.backend.cleanup();
        }
        await this.worktreeService.cleanupSession(this.worktreeDirName);
        this.agents.clear();
        this.cachedResult = null;
        this.sessionId = void 0;
        this.worktreeDirName = void 0;
        this.arenaConfig = void 0;
        this.backend = null;
        this.sessionEndedLogged = false;
      }
      /**
       * Clean up runtime resources (processes, backend, memory) without removing
       * worktrees or session files on disk. Used when preserveArtifacts is enabled.
       */
      async cleanupRuntime() {
        if (!this.sessionId) {
          return;
        }
        debugLogger44.info(`Cleaning up Arena runtime (preserving artifacts): ${this.sessionId}`);
        this.emitSessionEnded(this.sessionStatus === ArenaSessionStatus.CANCELLED ? "cancelled" : "discarded");
        this.stopPolling();
        this.teardownEventBridge();
        if (this.backend) {
          await this.backend.cleanup();
        }
        this.agents.clear();
        this.cachedResult = null;
        this.sessionId = void 0;
        this.worktreeDirName = void 0;
        this.arenaConfig = void 0;
        this.backend = null;
        this.sessionEndedLogged = false;
      }
      /**
       * Apply the result from a specific agent to the main working directory.
       */
      async applyAgentResult(agentId) {
        const agent = this.agents.get(agentId);
        if (!agent) {
          return { success: false, error: `Agent ${agentId} not found` };
        }
        if (!isSuccessStatus(agent.status)) {
          return {
            success: false,
            error: `Agent ${agentId} has not completed (current status: ${agent.status})`
          };
        }
        const applyResult = await this.worktreeService.applyWorktreeChanges(agent.worktree.path);
        if (applyResult.success) {
          this.emitSessionEnded("selected", agent.model.modelId);
        }
        return applyResult;
      }
      /**
       * Get the diff for a specific agent's changes.
       */
      async getAgentDiff(agentId) {
        const agent = this.agents.get(agentId);
        if (!agent) {
          return `Agent ${agentId} not found`;
        }
        return this.worktreeService.getWorktreeDiff(agent.worktree.path);
      }
      // ─── Private: Telemetry ───────────────────────────────────────
      /**
       * Emit the `arena_session_ended` telemetry event exactly once.
       *
       * Called from:
       *  - start() early-cancel paths → 'cancelled'
       *  - start() catch block → 'failed'
       *  - applyAgentResult() on success → 'selected' (with winner)
       *  - cleanup() / cleanupRuntime() → 'discarded' (user left without picking)
       */
      emitSessionEnded(status, winnerModelId) {
        if (this.sessionEndedLogged)
          return;
        this.sessionEndedLogged = true;
        const agents = Array.from(this.agents.values());
        logArenaSessionEnded(this.config, makeArenaSessionEndedEvent({
          arena_session_id: this.sessionId ?? "",
          status,
          duration_ms: this.startedAt ? Date.now() - this.startedAt : 0,
          display_backend: this.backend?.type,
          agent_count: agents.length,
          completed_agents: agents.filter((a2) => a2.status === AgentStatus.COMPLETED).length,
          failed_agents: agents.filter((a2) => a2.status === AgentStatus.FAILED).length,
          cancelled_agents: agents.filter((a2) => a2.status === AgentStatus.CANCELLED).length,
          winner_model_id: winnerModelId
        }));
      }
      // ─── Private: Progress ─────────────────────────────────────────
      /**
       * Emit a progress message via SESSION_UPDATE so the UI can display
       * setup status.
       */
      emitProgress(message, type = "info") {
        if (!this.sessionId)
          return;
        this.eventEmitter.emit(ArenaEventType.SESSION_UPDATE, {
          sessionId: this.sessionId,
          type,
          message,
          timestamp: Date.now()
        });
      }
      // ─── Private: Validation ───────────────────────────────────────
      validateStartOptions(options2) {
        if (!options2.models || options2.models.length < 2) {
          throw new Error("Arena requires at least 2 models to compare");
        }
        if (options2.models.length > ARENA_MAX_AGENTS) {
          throw new Error(`Arena supports a maximum of ${ARENA_MAX_AGENTS} models`);
        }
        if (!options2.task || options2.task.trim().length === 0) {
          throw new Error("Arena requires a task/prompt");
        }
        const modelIds = options2.models.map((m3) => m3.modelId);
        const uniqueIds = new Set(modelIds);
        if (uniqueIds.size !== modelIds.length) {
          throw new Error("Arena models must have unique identifiers");
        }
        const safeIds = modelIds.map((id) => safeAgentId(id));
        const uniqueSafeIds = new Set(safeIds);
        if (uniqueSafeIds.size !== safeIds.length) {
          const collisions = modelIds.filter((id, i4) => safeIds.indexOf(safeIds[i4]) !== i4);
          throw new Error(`Arena model IDs collide after path normalization: ${collisions.join(", ")}. Choose model IDs that remain unique when special characters (/ \\ : etc.) are replaced.`);
        }
      }
      // ─── Private: Backend Initialization ───────────────────────────
      /**
       * Initialize the backend.
       */
      async initializeBackend(displayMode) {
        const { backend, warning } = await detectBackend(displayMode, this.config);
        await backend.init();
        this.backend = backend;
        if (warning && this.sessionId) {
          this.eventEmitter.emit(ArenaEventType.SESSION_UPDATE, {
            sessionId: this.sessionId,
            type: "warning",
            message: warning,
            timestamp: Date.now()
          });
        }
        const attachHint = backend.getAttachHint();
        if (attachHint && this.sessionId) {
          this.eventEmitter.emit(ArenaEventType.SESSION_UPDATE, {
            sessionId: this.sessionId,
            type: "info",
            message: `To view agent panes, run: ${attachHint}`,
            timestamp: Date.now()
          });
        }
      }
      // ─── Private: Worktree Setup ───────────────────────────────────
      /**
       * Derive a short, filesystem-friendly directory name from the full session ID.
       * Uses the first 8 hex characters of the UUID. If that path already exists,
       * appends a numeric suffix (-2, -3, …) until an unused name is found.
       */
      async deriveWorktreeDirName(sessionId) {
        const shortId = sessionId.replaceAll("-", "").slice(0, 8);
        let candidate = shortId;
        let suffix = 2;
        while (true) {
          const candidatePath = path41.join(this.arenaBaseDir, candidate);
          try {
            await fs44.access(candidatePath);
            candidate = `${shortId}-${suffix}`;
            suffix++;
          } catch {
            return candidate;
          }
        }
      }
      async setupWorktrees() {
        if (!this.arenaConfig) {
          throw new Error("Arena config not initialized");
        }
        debugLogger44.info("Setting up worktrees for Arena agents");
        const worktreeNames = this.arenaConfig.models.map((m3) => m3.modelId);
        const result = await this.worktreeService.setupWorktrees({
          sessionId: this.worktreeDirName,
          sourceRepoPath: this.arenaConfig.sourceRepoPath,
          worktreeNames,
          metadata: { arenaSessionId: this.arenaConfig.sessionId }
        });
        if (!result.success) {
          const errorMessages = result.errors.map((e4) => `${e4.name}: ${e4.error}`).join("; ");
          throw new Error(`Failed to set up worktrees: ${errorMessages}`);
        }
        for (let i4 = 0; i4 < this.arenaConfig.models.length; i4++) {
          const model = this.arenaConfig.models[i4];
          const worktreeName = worktreeNames[i4];
          const worktree = result.worktreesByName[worktreeName];
          if (!worktree) {
            throw new Error(`No worktree created for model ${model.modelId} (name: ${worktreeName})`);
          }
          const agentId = model.modelId;
          const agentState = {
            agentId,
            model,
            status: AgentStatus.INITIALIZING,
            worktree,
            abortController: new AbortController(),
            agentSessionId: `${this.sessionId}#${agentId}`,
            stats: {
              rounds: 0,
              totalTokens: 0,
              inputTokens: 0,
              outputTokens: 0,
              durationMs: 0,
              toolCalls: 0,
              successfulToolCalls: 0,
              failedToolCalls: 0
            },
            startedAt: 0,
            accumulatedText: ""
          };
          this.agents.set(agentId, agentState);
        }
        debugLogger44.info(`Created ${this.agents.size} agent worktrees`);
      }
      // ─── Private: Agent Execution ──────────────────────────────────
      async runAgents() {
        if (!this.arenaConfig) {
          throw new Error("Arena config not initialized");
        }
        debugLogger44.info("Starting Arena agents sequentially via backend");
        const backend = this.requireBackend();
        backend.setOnAgentExit((agentId, exitCode, signal) => {
          this.handleAgentExit(agentId, exitCode, signal);
        });
        const isInProcess = backend.type === DISPLAY_MODE.IN_PROCESS;
        for (const agent of this.agents.values()) {
          await this.spawnAgentPty(agent);
        }
        this.emitProgress("All agents are now live and working on the task.");
        if (isInProcess) {
          this.setupInProcessEventBridge(backend);
        } else {
          this.startPolling();
        }
        const timeoutSeconds = this.arenaConfig.timeoutSeconds;
        const allSettled = await this.waitForAllAgentsSettled(timeoutSeconds ? timeoutSeconds * 1e3 : void 0);
        if (!isInProcess) {
          this.stopPolling();
        }
        if (!allSettled) {
          debugLogger44.info("Arena session timed out, stopping remaining agents");
          this.sessionStatus = ArenaSessionStatus.CANCELLED;
          for (const agent of this.agents.values()) {
            if (!isTerminalStatus(agent.status)) {
              backend.stopAgent(agent.agentId);
              agent.abortController.abort();
              agent.stats.durationMs = Date.now() - agent.startedAt;
              this.updateAgentStatus(agent.agentId, AgentStatus.CANCELLED);
            }
          }
        }
        debugLogger44.info("All Arena agents settled or timed out");
      }
      async spawnAgentPty(agent) {
        if (!this.arenaConfig) {
          return;
        }
        const backend = this.requireBackend();
        const { agentId, model, worktree } = agent;
        debugLogger44.info(`Spawning agent PTY: ${agentId}`);
        agent.startedAt = Date.now();
        this.updateAgentStatus(agentId, AgentStatus.RUNNING);
        this.eventEmitter.emit(ArenaEventType.AGENT_START, {
          sessionId: this.arenaConfig.sessionId,
          agentId,
          model,
          worktreePath: worktree.path,
          timestamp: Date.now()
        });
        this.callbacks.onAgentStart?.(agentId, model);
        const spawnConfig = this.buildAgentSpawnConfig(agent);
        try {
          await backend.spawnAgent(spawnConfig);
        } catch (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          agent.error = errorMessage;
          this.updateAgentStatus(agentId, AgentStatus.FAILED);
          this.eventEmitter.emit(ArenaEventType.AGENT_ERROR, {
            sessionId: this.requireConfig().sessionId,
            agentId,
            error: errorMessage,
            timestamp: Date.now()
          });
          debugLogger44.error(`Failed to spawn agent: ${agentId}`, error40);
        }
      }
      requireBackend() {
        if (!this.backend) {
          throw new Error("Arena backend not initialized.");
        }
        return this.backend;
      }
      requireConfig() {
        if (!this.arenaConfig) {
          throw new Error("Arena config not initialized");
        }
        return this.arenaConfig;
      }
      handleAgentExit(agentId, exitCode, _signal) {
        const agent = this.agents.get(agentId);
        if (!agent) {
          return;
        }
        if (isTerminalStatus(agent.status)) {
          return;
        }
        agent.stats.durationMs = Date.now() - agent.startedAt;
        if (exitCode !== 0 && exitCode !== null && !agent.abortController.signal.aborted) {
          agent.error = `Process exited with code ${exitCode}`;
          this.eventEmitter.emit(ArenaEventType.AGENT_ERROR, {
            sessionId: this.requireConfig().sessionId,
            agentId,
            error: agent.error,
            timestamp: Date.now()
          });
        }
        this.updateAgentStatus(agentId, agent.abortController.signal.aborted ? AgentStatus.CANCELLED : AgentStatus.FAILED);
        debugLogger44.info(`Agent exited: ${agentId} (exit code: ${exitCode})`);
      }
      /**
       * Build the spawn configuration for an agent subprocess.
       *
       * The agent is launched as a full interactive CLI instance, running in
       * its own worktree with the specified model. The task is passed via
       * the --prompt argument so the CLI enters interactive mode and
       * immediately starts working on the task.
       */
      buildAgentSpawnConfig(agent) {
        const { agentId, model, worktree } = agent;
        const args2 = [];
        args2.push("--model", model.modelId);
        args2.push("--auth-type", model.authType);
        if (this.arenaConfig?.task) {
          args2.push("--prompt-interactive", this.arenaConfig.task);
        }
        if (this.arenaConfig?.approvalMode) {
          args2.push("--approval-mode", this.arenaConfig.approvalMode);
        }
        args2.push("--session-id", agent.agentSessionId);
        const arenaSessionDir = this.getArenaSessionDir();
        const env6 = {
          QWEN_CODE: "1",
          ARENA_AGENT_ID: agentId,
          ARENA_SESSION_ID: this.arenaConfig?.sessionId ?? "",
          ARENA_SESSION_DIR: arenaSessionDir
        };
        if (model.apiKey) {
          env6["QWEN_API_KEY"] = model.apiKey;
        }
        if (model.baseUrl) {
          env6["QWEN_BASE_URL"] = model.baseUrl;
        }
        const spawnConfig = {
          agentId,
          command: process.execPath,
          // Use the same Node.js binary
          args: [path41.resolve(process.argv[1]), ...args2],
          // Re-launch the CLI entry point (must be absolute path since cwd changes)
          cwd: worktree.path,
          env: env6,
          cols: this.terminalCols,
          rows: this.terminalRows,
          inProcess: {
            agentName: model.modelId,
            initialTask: this.arenaConfig?.task,
            runtimeConfig: {
              promptConfig: {
                systemPrompt: getCoreSystemPrompt(this.config.getUserMemory(), model.modelId)
              },
              modelConfig: { model: model.modelId },
              runConfig: {
                max_turns: this.arenaConfig?.maxRoundsPerAgent,
                max_time_minutes: this.arenaConfig?.timeoutSeconds ? Math.ceil(this.arenaConfig.timeoutSeconds / 60) : void 0
              }
            },
            authOverrides: {
              authType: model.authType,
              apiKey: model.apiKey,
              baseUrl: model.baseUrl
            },
            chatHistory: this.arenaConfig?.chatHistory
          }
        };
        debugLogger44.info(`[buildAgentSpawnConfig] agentId=${agentId}, command=${spawnConfig.command}, cliEntry=${process.argv[1]}, resolvedEntry=${path41.resolve(process.argv[1])}`);
        debugLogger44.info(`[buildAgentSpawnConfig] args=${JSON.stringify(spawnConfig.args)}`);
        debugLogger44.info(`[buildAgentSpawnConfig] cwd=${spawnConfig.cwd}, env keys=${Object.keys(env6).join(",")}`);
        return spawnConfig;
      }
      // ─── Private: Status & Results ─────────────────────────────────
      /** Decide whether a status transition is valid. Returns the new status or null. */
      resolveTransition(current, incoming) {
        if (current === incoming)
          return null;
        if (isTerminalStatus(current)) {
          if (current === AgentStatus.COMPLETED && incoming === AgentStatus.RUNNING) {
            return incoming;
          }
          return null;
        }
        return incoming;
      }
      updateAgentStatus(agentId, newStatus, options2) {
        const agent = this.agents.get(agentId);
        if (!agent) {
          return;
        }
        const previousStatus = agent.status;
        agent.status = newStatus;
        this.eventEmitter.emit(ArenaEventType.AGENT_STATUS_CHANGE, {
          sessionId: this.requireConfig().sessionId,
          agentId,
          previousStatus,
          newStatus,
          timestamp: Date.now()
        });
        const label = agent.model.modelId;
        if (this.sessionStatus === ArenaSessionStatus.RUNNING && previousStatus === AgentStatus.RUNNING && newStatus === AgentStatus.IDLE) {
          if (options2?.roundCancelledByUser) {
            this.emitProgress(`Agent ${label} is cancelled by user.`, "warning");
          } else {
            this.emitProgress(`Agent ${label} finished initial task.`, "success");
          }
        }
        if (this.sessionStatus === ArenaSessionStatus.IDLE) {
          if (previousStatus === AgentStatus.IDLE && newStatus === AgentStatus.RUNNING) {
            this.emitProgress(`Agent ${label} is working on a follow-up task\u2026`);
          } else if (previousStatus === AgentStatus.RUNNING && newStatus === AgentStatus.IDLE) {
            if (options2?.roundCancelledByUser) {
              this.emitProgress(`Agent ${label} is cancelled by user.`, "warning");
            } else {
              this.emitProgress(`Agent ${label} finished follow-up task.`, "success");
            }
          }
        }
        if (isTerminalStatus(newStatus)) {
          const result = this.buildAgentResult(agent);
          this.eventEmitter.emit(ArenaEventType.AGENT_COMPLETE, {
            sessionId: this.requireConfig().sessionId,
            agentId,
            result,
            timestamp: Date.now()
          });
          const agentTelemetryStatus = newStatus === AgentStatus.COMPLETED ? "completed" : newStatus === AgentStatus.FAILED ? "failed" : "cancelled";
          logArenaAgentCompleted(this.config, makeArenaAgentCompletedEvent({
            arena_session_id: this.sessionId ?? "",
            agent_session_id: agent.agentSessionId,
            agent_model_id: agent.model.modelId,
            status: agentTelemetryStatus,
            duration_ms: agent.stats.durationMs,
            rounds: agent.stats.rounds,
            total_tokens: agent.stats.totalTokens,
            input_tokens: agent.stats.inputTokens,
            output_tokens: agent.stats.outputTokens,
            tool_calls: agent.stats.toolCalls,
            successful_tool_calls: agent.stats.successfulToolCalls,
            failed_tool_calls: agent.stats.failedToolCalls
          }));
          this.callbacks.onAgentComplete?.(result);
        }
      }
      buildAgentResult(agent) {
        return {
          agentId: agent.agentId,
          model: agent.model,
          status: agent.status,
          worktree: agent.worktree,
          finalText: agent.accumulatedText || void 0,
          error: agent.error,
          stats: { ...agent.stats },
          startedAt: agent.startedAt,
          endedAt: Date.now()
        };
      }
      // ─── Arena Session Directory ──────────────────────────────────
      /**
       * Get the arena session directory for the current session.
       * All status and control files are stored here.
       *
       * Returns the absolute path to the session directory, e.g.
       * `~/.qwen/worktrees/<sessionId>/`.  The directory contains:
       * - `config.json` — consolidated session config + per-agent status
       * - `agents/<safeAgentId>.json` — individual agent status files
       * - `control/` — control signals (shutdown, cancel)
       */
      getArenaSessionDir() {
        if (!this.arenaConfig) {
          throw new Error("Arena config not initialized");
        }
        return GitWorktreeService.getSessionDir(this.worktreeDirName, this.arenaBaseDir);
      }
      // ─── Private: Polling & Control Signals ──────────────────────
      /**
       * Wait for all agents to reach IDLE or TERMINATED state.
       * Returns true if all agents settled, false if timeout was reached.
       */
      waitForAllAgentsSettled(timeoutMs) {
        return new Promise((resolve42) => {
          const checkSettled = /* @__PURE__ */ __name(() => {
            for (const agent of this.agents.values()) {
              if (!isSettledStatus(agent.status)) {
                return false;
              }
            }
            return true;
          }, "checkSettled");
          if (checkSettled()) {
            resolve42(true);
            return;
          }
          let timeoutHandle;
          if (timeoutMs !== void 0) {
            timeoutHandle = setTimeout(() => {
              clearInterval(pollHandle);
              resolve42(false);
            }, timeoutMs);
          }
          const pollHandle = setInterval(() => {
            if (checkSettled()) {
              clearInterval(pollHandle);
              if (timeoutHandle)
                clearTimeout(timeoutHandle);
              resolve42(true);
            }
          }, ARENA_POLL_INTERVAL_MS);
        });
      }
      /**
       * Start polling agent status files at a fixed interval.
       */
      startPolling() {
        if (this.pollingInterval) {
          return;
        }
        this.pollingInterval = setInterval(() => {
          this.pollAgentStatuses().catch((error40) => {
            debugLogger44.error("Error polling agent statuses:", error40);
          });
        }, ARENA_POLL_INTERVAL_MS);
      }
      /**
       * Stop the polling interval.
       */
      stopPolling() {
        if (this.pollingInterval) {
          clearInterval(this.pollingInterval);
          this.pollingInterval = null;
        }
      }
      /**
       * Set up event bridges for in-process agents.
       * Subscribes to each AgentInteractive's events to update ArenaManager state.
       * Listeners are tracked in `eventBridgeCleanups` for teardown.
       */
      setupInProcessEventBridge(backend) {
        for (const agent of this.agents.values()) {
          const interactive = backend.getAgent(agent.agentId);
          if (!interactive)
            continue;
          const emitter = interactive.getEventEmitter();
          if (!emitter)
            continue;
          const syncStats = /* @__PURE__ */ __name(() => {
            const { totalToolCalls, totalDurationMs, ...rest } = interactive.getStats();
            Object.assign(agent.stats, rest, {
              toolCalls: totalToolCalls,
              durationMs: totalDurationMs
            });
          }, "syncStats");
          agent.syncStats = syncStats;
          const applyStatus = /* @__PURE__ */ __name((incoming, options2) => {
            const resolved = this.resolveTransition(agent.status, incoming);
            if (!resolved)
              return;
            if (resolved === AgentStatus.FAILED) {
              agent.error = interactive.getLastRoundError() || interactive.getError();
            }
            if (isSettledStatus(resolved)) {
              agent.stats.durationMs = Date.now() - agent.startedAt;
            }
            this.updateAgentStatus(agent.agentId, resolved, options2);
          }, "applyStatus");
          const onStatusChange = /* @__PURE__ */ __name((event) => {
            syncStats();
            applyStatus(event.newStatus, {
              roundCancelledByUser: event.roundCancelledByUser
            });
            this.flushInProcessStatusFiles().catch((err2) => debugLogger44.error("Failed to flush in-process status files:", err2));
          }, "onStatusChange");
          const onUsageMetadata = /* @__PURE__ */ __name(() => {
            syncStats();
            this.flushInProcessStatusFiles().catch((err2) => debugLogger44.error("Failed to flush in-process status files:", err2));
          }, "onUsageMetadata");
          emitter.on(AgentEventType.STATUS_CHANGE, onStatusChange);
          emitter.on(AgentEventType.USAGE_METADATA, onUsageMetadata);
          this.eventBridgeCleanups.push(() => {
            emitter.off(AgentEventType.STATUS_CHANGE, onStatusChange);
            emitter.off(AgentEventType.USAGE_METADATA, onUsageMetadata);
          });
          syncStats();
          applyStatus(interactive.getStatus());
        }
        this.flushInProcessStatusFiles().catch((err2) => debugLogger44.error("Failed to flush in-process status files:", err2));
      }
      /**
       * Remove all event bridge listeners registered by setupInProcessEventBridge.
       */
      teardownEventBridge() {
        for (const cleanup of this.eventBridgeCleanups) {
          cleanup();
        }
        this.eventBridgeCleanups.length = 0;
      }
      /**
       * Read per-agent status files from `<arenaSessionDir>/agents/` directory.
       * Updates agent stats, emits AGENT_STATS_UPDATE events, and writes a
       * consolidated `status.json` at the arena session root.
       */
      async pollAgentStatuses() {
        const sessionDir = this.getArenaSessionDir();
        const agentsDir = path41.join(sessionDir, "agents");
        const consolidatedAgents = {};
        for (const agent of this.agents.values()) {
          if (isSettledStatus(agent.status) || agent.status === AgentStatus.INITIALIZING) {
            continue;
          }
          try {
            const statusPath = path41.join(agentsDir, `${safeAgentId(agent.agentId)}.json`);
            const content = await fs44.readFile(statusPath, "utf-8");
            const statusFile = JSON.parse(content);
            consolidatedAgents[agent.agentId] = statusFile;
            agent.stats = {
              ...agent.stats,
              ...statusFile.stats
            };
            if (statusFile.finalSummary) {
              agent.accumulatedText = statusFile.finalSummary;
            }
            const resolved = this.resolveTransition(agent.status, statusFile.status);
            if (resolved) {
              if (resolved === AgentStatus.FAILED && statusFile.error) {
                agent.error = statusFile.error;
              }
              this.updateAgentStatus(agent.agentId, resolved);
            }
            this.callbacks.onAgentStatsUpdate?.(agent.agentId, statusFile.stats);
          } catch (error40) {
            if (isNodeError(error40) && error40.code === "ENOENT") {
              continue;
            }
            debugLogger44.error(`Error reading status for agent ${agent.agentId}:`, error40);
          }
        }
        if (Object.keys(consolidatedAgents).length > 0) {
          await this.writeConsolidatedStatus(consolidatedAgents);
        }
      }
      /**
       * Merge agent status data into the arena session's config.json.
       * Reads the existing config, adds/updates `updatedAt` and `agents`,
       * then writes back atomically (temp file → rename).
       */
      async writeConsolidatedStatus(agents) {
        const sessionDir = this.getArenaSessionDir();
        const configPath = path41.join(sessionDir, "config.json");
        try {
          let config2;
          try {
            const content = await fs44.readFile(configPath, "utf-8");
            config2 = JSON.parse(content);
          } catch {
            const arenaConfig = this.requireConfig();
            config2 = {
              arenaSessionId: arenaConfig.sessionId,
              sourceRepoPath: arenaConfig.sourceRepoPath,
              worktreeNames: arenaConfig.models.map((m3) => m3.displayName || m3.modelId),
              createdAt: this.startedAt
            };
          }
          config2.updatedAt = Date.now();
          config2.agents = agents;
          await atomicWriteJSON(configPath, config2);
        } catch (error40) {
          debugLogger44.error("Failed to write consolidated status to config.json:", error40);
        }
      }
      /**
       * Build an ArenaStatusFile snapshot from in-memory agent state.
       */
      buildStatusFile(agent) {
        return {
          agentId: agent.agentId,
          status: agent.status,
          updatedAt: Date.now(),
          rounds: agent.stats.rounds,
          stats: { ...agent.stats },
          finalSummary: null,
          error: agent.error ?? null
        };
      }
      /**
       * Write status files for all in-process agents and update the
       * consolidated config.json.
       *
       * In PTY mode these files are written by ArenaAgentClient inside each
       * child process. In in-process mode there is no child process, so the
       * ArenaManager writes them directly so that external consumers
       * (e.g. an orchestrating agent) get a consistent file-based view
       * regardless of backend.
       */
      async flushInProcessStatusFiles() {
        const sessionDir = this.getArenaSessionDir();
        const agentsDir = path41.join(sessionDir, "agents");
        await fs44.mkdir(agentsDir, { recursive: true });
        const consolidatedAgents = {};
        for (const agent of this.agents.values()) {
          const statusFile = this.buildStatusFile(agent);
          const filePath = path41.join(agentsDir, `${safeAgentId(agent.agentId)}.json`);
          await atomicWriteJSON(filePath, statusFile);
          consolidatedAgents[agent.agentId] = statusFile;
        }
        if (Object.keys(consolidatedAgents).length > 0) {
          await this.writeConsolidatedStatus(consolidatedAgents);
        }
      }
      /**
       * Write a control signal to the arena session's control/ directory.
       * The child agent consumes (reads + deletes) this file.
       */
      async sendControlSignal(agentId, type, reason) {
        const agent = this.agents.get(agentId);
        if (!agent) {
          debugLogger44.error(`Cannot send control signal: agent ${agentId} not found`);
          return;
        }
        const controlSignal = {
          type,
          reason,
          timestamp: Date.now()
        };
        const sessionDir = this.getArenaSessionDir();
        const controlDir = path41.join(sessionDir, "control");
        const controlPath = path41.join(controlDir, `${safeAgentId(agentId)}.json`);
        try {
          await fs44.mkdir(controlDir, { recursive: true });
          await fs44.writeFile(controlPath, JSON.stringify(controlSignal, null, 2), "utf-8");
          debugLogger44.info(`Sent ${type} control signal to agent ${agentId}: ${reason}`);
        } catch (error40) {
          debugLogger44.error(`Failed to send control signal to agent ${agentId}:`, error40);
        }
      }
      getAgentTranscript(agentId) {
        if (this.backend?.type !== DISPLAY_MODE.IN_PROCESS) {
          return void 0;
        }
        const interactive = this.backend.getAgent(agentId);
        const messages = interactive?.getMessages();
        if (!messages || messages.length === 0) {
          return void 0;
        }
        return messages.map((message) => ({
          role: message.role,
          content: message.content,
          thought: message.thought,
          metadata: message.metadata,
          timestamp: message.timestamp
        }));
      }
      getFinalTextFromTranscript(transcript) {
        if (!transcript)
          return void 0;
        for (let i4 = transcript.length - 1; i4 >= 0; i4--) {
          const message = transcript[i4];
          if (message.role === "assistant" && !message.thought && message.content.trim()) {
            return message.content.trim();
          }
        }
        return void 0;
      }
      async addApproachSummaries(summaryInputs) {
        await Promise.all(summaryInputs.map(async (summaryInput) => {
          summaryInput.result.approachSummary = await this.generateAgentApproachSummary(summaryInput);
        }));
      }
      getAgentSummaryGenerator(agentId) {
        if (this.backend?.type !== DISPLAY_MODE.IN_PROCESS) {
          return void 0;
        }
        return this.backend.getAgentContentGenerator(agentId);
      }
      async generateAgentApproachSummary(summaryInput) {
        const { result } = summaryInput;
        const generator = this.getAgentSummaryGenerator(result.agentId);
        if (!generator) {
          return buildFallbackApproachSummary(result);
        }
        const abortController = new AbortController();
        const timeout2 = setTimeout(() => abortController.abort(), ARENA_SUMMARY_TIMEOUT_MS);
        try {
          const response = await generator.generateContent({
            model: result.model.modelId,
            contents: [
              {
                role: "user",
                parts: [
                  {
                    text: this.buildAgentApproachSummaryPrompt(summaryInput)
                  }
                ]
              }
            ],
            config: {
              abortSignal: abortController.signal,
              thinkingConfig: { includeThoughts: false }
            }
          }, "arena_approach_summary");
          return parseApproachSummaryResponse(getResponseText(response) ?? "")?.trim() || buildFallbackApproachSummary(result);
        } catch (error40) {
          debugLogger44.error(`Failed to generate Arena approach summary for ${result.agentId}:`, error40);
          return buildFallbackApproachSummary(result);
        } finally {
          clearTimeout(timeout2);
        }
      }
      buildAgentApproachSummaryPrompt({ result: agent, transcript }) {
        const payload = {
          task: this.arenaConfig?.task ?? "",
          instruction: 'Summarize this Arena agent approach for user comparison. Use git diff as the source of truth for what changed. Use transcript/finalText only to infer intent and architectural decisions. Do not pick a winner. Return only compact JSON: {"summary":"one sentence summary"}.',
          agent: {
            agentId: agent.agentId,
            model: agent.model.modelId,
            status: agent.status,
            metrics: {
              files: agent.diffSummary?.files.length ?? 0,
              additions: agent.diffSummary?.additions ?? 0,
              deletions: agent.diffSummary?.deletions ?? 0,
              tokens: agent.stats.totalTokens,
              durationMs: agent.stats.durationMs,
              toolCalls: agent.stats.toolCalls
            },
            files: agent.diffSummary?.files ?? [],
            finalText: truncateForPrompt(agent.finalText ?? "", 2e3),
            transcript: truncateForPrompt(formatTranscript(transcript), 6e3),
            diff: truncateForPrompt(agent.diff ?? "", ARENA_SUMMARY_MAX_DIFF_CHARS)
          }
        };
        return JSON.stringify(payload, null, 2);
      }
      async collectResults() {
        if (!this.arenaConfig) {
          throw new Error("Arena config not initialized");
        }
        const agents = [];
        const summaryInputs = [];
        for (const agent of this.agents.values()) {
          const result = this.buildAgentResult(agent);
          const transcript = this.getAgentTranscript(agent.agentId);
          result.finalText = result.finalText ?? this.getFinalTextFromTranscript(transcript);
          if (isSuccessStatus(agent.status)) {
            try {
              result.diff = await this.worktreeService.getWorktreeDiff(agent.worktree.path);
              result.diffSummary = summarizeUnifiedDiff(result.diff);
              result.modifiedFiles = result.diffSummary.files.map((file2) => file2.path);
            } catch (error40) {
              debugLogger44.error(`Failed to get diff for agent ${agent.agentId}:`, error40);
            }
          }
          result.diffSummary ??= summarizeUnifiedDiff(result.diff);
          result.modifiedFiles ??= result.diffSummary.files.map((file2) => file2.path);
          agents.push(result);
          summaryInputs.push({ result, transcript });
        }
        await this.addApproachSummaries(summaryInputs);
        const endedAt = Date.now();
        return {
          sessionId: this.arenaConfig.sessionId,
          task: this.arenaConfig.task,
          status: this.sessionStatus,
          agents,
          startedAt: this.startedAt,
          endedAt,
          totalDurationMs: endedAt - this.startedAt,
          wasRepoInitialized: false
        };
      }
    };
    __name(truncateForPrompt, "truncateForPrompt");
    __name(formatTranscript, "formatTranscript");
    __name(parseApproachSummaryResponse, "parseApproachSummaryResponse");
    __name(extractJsonObject, "extractJsonObject");
    __name(isRecord, "isRecord");
  }
});

// packages/core/dist/src/agents/arena/index.js
var init_arena = __esm({
  "packages/core/dist/src/agents/arena/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_types();
    init_arena_events();
    init_diff_summary();
    init_ArenaManager();
    init_ArenaAgentClient();
    init_backends();
  }
});

// packages/core/dist/src/agents/runtime/index.js
var init_runtime = __esm({
  "packages/core/dist/src/agents/runtime/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_agent_types();
    init_agent_core();
    init_agent_headless();
    init_agent_interactive();
    init_agent_events();
    init_agent_statistics();
    init_asyncMessageQueue();
  }
});

// packages/core/dist/src/agents/background-tasks.js
function buildBackgroundEntryLabel(entry, options2 = {}) {
  const { includePrefix = true } = options2;
  let raw2 = entry.description;
  if (entry.subagentType && raw2.toLowerCase().startsWith(entry.subagentType.toLowerCase() + ":")) {
    raw2 = raw2.slice(entry.subagentType.length + 1).trimStart();
  }
  const truncated = raw2.length > MAX_DESCRIPTION_LENGTH ? raw2.slice(0, MAX_DESCRIPTION_LENGTH - 1) + "\u2026" : raw2;
  return includePrefix && entry.subagentType ? `${entry.subagentType}: ${truncated}` : truncated;
}
function escapeXml(text) {
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
var debugLogger45, MAX_DESCRIPTION_LENGTH, MAX_RECENT_ACTIVITIES, CANCEL_GRACE_MS, BackgroundTaskRegistry;
var init_background_tasks = __esm({
  "packages/core/dist/src/agents/background-tasks.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger45 = createDebugLogger("BACKGROUND_TASKS");
    MAX_DESCRIPTION_LENGTH = 40;
    MAX_RECENT_ACTIVITIES = 5;
    CANCEL_GRACE_MS = 5e3;
    __name(buildBackgroundEntryLabel, "buildBackgroundEntryLabel");
    __name(escapeXml, "escapeXml");
    BackgroundTaskRegistry = class {
      static {
        __name(this, "BackgroundTaskRegistry");
      }
      agents = /* @__PURE__ */ new Map();
      notificationCallback;
      registerCallback;
      statusChangeCallback;
      activityChangeCallback;
      register(entry) {
        if (!entry.pendingMessages)
          entry.pendingMessages = [];
        this.agents.set(entry.agentId, entry);
        debugLogger45.info(`Registered background agent: ${entry.agentId}`);
        if (this.registerCallback) {
          try {
            this.registerCallback(entry);
          } catch (error40) {
            debugLogger45.error("Failed to emit register callback:", error40);
          }
        }
        this.emitStatusChange(entry);
      }
      // Transition a still-running entry to 'completed' and emit the terminal
      // notification. No-op if the entry is already terminal *and* has been
      // notified — protects against duplicate emission when cancel aborts the
      // signal and the natural handler also races to completion.
      complete(agentId, result, stats) {
        const entry = this.agents.get(agentId);
        if (!entry)
          return;
        if (entry.status !== "running" && entry.status !== "cancelled")
          return;
        if (entry.notified)
          return;
        entry.status = "completed";
        entry.endTime = Date.now();
        entry.result = result;
        entry.stats = stats;
        debugLogger45.info(`Background agent completed: ${agentId}`);
        this.emitNotification(entry);
        this.emitStatusChange(entry);
      }
      // See complete() for the cancelled → terminal path rationale.
      fail(agentId, error40, stats) {
        const entry = this.agents.get(agentId);
        if (!entry)
          return;
        if (entry.status !== "running" && entry.status !== "cancelled")
          return;
        if (entry.notified)
          return;
        entry.status = "failed";
        entry.endTime = Date.now();
        entry.error = error40;
        entry.stats = stats;
        debugLogger45.info(`Background agent failed: ${agentId}`);
        this.emitNotification(entry);
        this.emitStatusChange(entry);
      }
      // Cancellation aborts the signal and marks the entry as cancelled, but
      // does *not* emit the terminal notification immediately. The natural
      // completion path (bgBody) fires complete()/fail()/finalizeCancelled()
      // with the real partial/final result, which carries far more information
      // than a bare "cancelled" message. A deferred fallback handles the rare
      // case where a tool ignores AbortSignal and bgBody never settles — the
      // timeout lands on finalizeCancellationIfPending(), which is a no-op
      // once the natural handler has already emitted.
      cancel(agentId) {
        const entry = this.agents.get(agentId);
        if (!entry || entry.status !== "running")
          return;
        entry.abortController.abort();
        entry.status = "cancelled";
        entry.endTime = Date.now();
        debugLogger45.info(`Background agent cancelled: ${agentId}`);
        this.emitStatusChange(entry);
        const timer = setTimeout(() => {
          this.finalizeCancellationIfPending(agentId);
        }, CANCEL_GRACE_MS);
        timer.unref?.();
      }
      // Emit the terminal cancelled notification once the agent's natural
      // handler has confirmed that the reasoning loop ended because of the
      // abort (terminateMode === CANCELLED). Attaches the partial result and
      // stats so the parent model still sees whatever work the agent had
      // captured before the abort landed, instead of a bare "cancelled" line.
      finalizeCancelled(agentId, partialResult, stats) {
        const entry = this.agents.get(agentId);
        if (!entry)
          return;
        if (entry.status !== "running" && entry.status !== "cancelled")
          return;
        if (entry.notified)
          return;
        entry.status = "cancelled";
        entry.endTime ??= Date.now();
        if (partialResult)
          entry.result = partialResult;
        entry.stats = stats;
        this.emitNotification(entry);
        this.emitStatusChange(entry);
      }
      // Emit the terminal cancelled notification for entries that were cancelled
      // but for which no natural handler delivered a follow-up complete()/fail()/
      // finalizeCancelled(). Used by shutdown paths (abortAll) to guarantee the
      // SDK contract (every registered agent produces exactly one
      // task-notification).
      finalizeCancellationIfPending(agentId) {
        const entry = this.agents.get(agentId);
        if (!entry || entry.status !== "cancelled" || entry.notified)
          return;
        this.emitNotification(entry);
        this.emitStatusChange(entry);
      }
      /**
       * Append a recent tool activity to a running entry's rolling buffer.
       * No-op if the entry is not running — late events after a cancellation
       * shouldn't leak into the Progress section.
       */
      appendActivity(agentId, activity) {
        const entry = this.agents.get(agentId);
        if (!entry || entry.status !== "running")
          return;
        const prior = entry.recentActivities ?? [];
        const next = [...prior, activity];
        if (next.length > MAX_RECENT_ACTIVITIES) {
          next.splice(0, next.length - MAX_RECENT_ACTIVITIES);
        }
        entry.recentActivities = next;
        this.emitActivityChange(entry);
      }
      get(agentId) {
        return this.agents.get(agentId);
      }
      /**
       * Snapshot of every entry regardless of status. Used by the TUI
       * footer/dialog to render rows for still-running AND terminal-state
       * tasks; the headless holdback loop keys off `hasUnfinalizedTasks`
       * instead, so callers that only need the running slice can filter
       * this snapshot at the call site.
       */
      getAll() {
        return Array.from(this.agents.values());
      }
      /**
       * True if any registered task has not yet emitted its terminal
       * task-notification. Covers `running` (still executing) and
       * `cancelled`-but-not-finalized (cancel requested, but the natural
       * handler hasn't fired finalizeCancelled() yet). Headless callers
       * must keep their event loop alive while this returns true, so every
       * task_started is paired with a matching task_notification.
       */
      hasUnfinalizedTasks() {
        for (const entry of this.agents.values()) {
          if (!entry.notified)
            return true;
        }
        return false;
      }
      /**
       * Enqueue a message for delivery to a running background agent.
       * The agent drains this queue between tool rounds.
       */
      queueMessage(agentId, message) {
        const entry = this.agents.get(agentId);
        if (!entry || entry.status !== "running")
          return false;
        const queue = entry.pendingMessages;
        queue.push(message);
        debugLogger45.info(`Queued message for background agent ${agentId} (${queue.length} pending)`);
        return true;
      }
      /**
       * Drain all pending messages for an agent. Returns the messages
       * and clears the queue. Called by the agent's reasoning loop.
       */
      drainMessages(agentId) {
        const entry = this.agents.get(agentId);
        if (!entry || !entry.pendingMessages.length)
          return [];
        const messages = entry.pendingMessages.splice(0);
        debugLogger45.info(`Drained ${messages.length} message(s) for background agent ${agentId}`);
        return messages;
      }
      setNotificationCallback(cb) {
        this.notificationCallback = cb;
      }
      setRegisterCallback(cb) {
        this.registerCallback = cb;
      }
      setStatusChangeCallback(cb) {
        this.statusChangeCallback = cb;
      }
      setActivityChangeCallback(cb) {
        this.activityChangeCallback = cb;
      }
      abortAll() {
        for (const entry of Array.from(this.agents.values())) {
          this.cancel(entry.agentId);
          this.finalizeCancellationIfPending(entry.agentId);
        }
        debugLogger45.info("Aborted all background agents");
      }
      buildDisplayLabel(entry) {
        return buildBackgroundEntryLabel(entry);
      }
      emitNotification(entry) {
        if (entry.notified)
          return;
        entry.notified = true;
        if (!this.notificationCallback)
          return;
        const statusText = entry.status === "completed" ? "completed" : entry.status === "failed" ? "failed" : "was cancelled";
        const label = this.buildDisplayLabel(entry);
        const displayLine = `Background agent "${label}" ${statusText}.`;
        const xmlParts = [
          "<task-notification>",
          `<task-id>${escapeXml(entry.agentId)}</task-id>`
        ];
        if (entry.toolUseId) {
          xmlParts.push(`<tool-use-id>${escapeXml(entry.toolUseId)}</tool-use-id>`);
        }
        xmlParts.push(`<status>${escapeXml(entry.status)}</status>`, `<summary>Agent "${escapeXml(entry.description)}" ${statusText}.</summary>`);
        if (entry.result) {
          xmlParts.push(`<result>${escapeXml(entry.result)}</result>`);
        }
        if (entry.error) {
          xmlParts.push(`<result>Error: ${escapeXml(entry.error)}</result>`);
        }
        if (entry.outputFile) {
          xmlParts.push(`<output-file>${escapeXml(entry.outputFile)}</output-file>`);
        }
        if (entry.stats) {
          xmlParts.push("<usage>", `<total_tokens>${entry.stats.totalTokens}</total_tokens>`, `<tool_uses>${entry.stats.toolUses}</tool_uses>`, `<duration_ms>${entry.stats.durationMs}</duration_ms>`, "</usage>");
        }
        xmlParts.push("</task-notification>");
        const meta = {
          agentId: entry.agentId,
          status: entry.status,
          stats: entry.stats,
          toolUseId: entry.toolUseId
        };
        try {
          this.notificationCallback(displayLine, xmlParts.join("\n"), meta);
        } catch (error40) {
          debugLogger45.error("Failed to emit background notification:", error40);
        }
      }
      emitStatusChange(entry) {
        if (!this.statusChangeCallback)
          return;
        try {
          this.statusChangeCallback(entry);
        } catch (error40) {
          debugLogger45.error("Failed to emit background status change:", error40);
        }
      }
      emitActivityChange(entry) {
        if (!this.activityChangeCallback)
          return;
        try {
          this.activityChangeCallback(entry);
        } catch (error40) {
          debugLogger45.error("Failed to emit background activity change:", error40);
        }
      }
    };
  }
});

// packages/core/dist/src/agents/index.js
var init_agents = __esm({
  "packages/core/dist/src/agents/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_backends();
    init_arena();
    init_runtime();
    init_background_tasks();
  }
});

// packages/core/dist/src/utils/forkedAgent.js
function saveCacheSafeParams(generationConfig, history, model) {
  const prevConfig = currentCacheSafeParams?.generationConfig;
  const sysChanged = !prevConfig || JSON.stringify(prevConfig.systemInstruction) !== JSON.stringify(generationConfig.systemInstruction);
  const toolsChanged = !prevConfig || JSON.stringify(prevConfig.tools) !== JSON.stringify(generationConfig.tools);
  if (sysChanged || toolsChanged) {
    currentVersion++;
  }
  currentCacheSafeParams = {
    generationConfig: structuredClone(generationConfig),
    history,
    model,
    version: currentVersion
  };
}
function getCacheSafeParams() {
  return currentCacheSafeParams ? structuredClone(currentCacheSafeParams) : null;
}
function clearCacheSafeParams() {
  currentCacheSafeParams = null;
}
function createForkedChat(config2, params) {
  const maxHistoryEntries = 40;
  const history = params.history.length > maxHistoryEntries ? params.history.slice(-maxHistoryEntries) : params.history;
  return new GeminiChat(
    config2,
    {
      ...params.generationConfig,
      // Disable thinking for forked queries — no reasoning tokens needed,
      // and it doesn't affect the cache prefix.
      thinkingConfig: { includeThoughts: false }
    },
    [...history],
    void 0,
    // no chatRecordingService
    void 0
  );
}
function extractQueryUsage(metadata2) {
  return {
    inputTokens: metadata2?.promptTokenCount ?? 0,
    outputTokens: metadata2?.candidatesTokenCount ?? 0,
    cacheHitTokens: metadata2?.cachedContentTokenCount ?? 0
  };
}
function createYoloConfig(config2) {
  const yoloConfig = Object.create(config2);
  yoloConfig.getApprovalMode = () => ApprovalMode.YOLO;
  return yoloConfig;
}
function extractFilePathsFromArgs(args2) {
  const matches2 = /* @__PURE__ */ new Set();
  const visit = /* @__PURE__ */ __name((value, key) => {
    if (typeof value === "string") {
      const normalizedKey = key?.toLowerCase() ?? "";
      if (normalizedKey.includes("path") || normalizedKey.includes("file") || normalizedKey.includes("target")) {
        matches2.add(value);
      }
      return;
    }
    if (Array.isArray(value)) {
      for (const item of value)
        visit(item, key);
      return;
    }
    if (value && typeof value === "object") {
      for (const [k2, v2] of Object.entries(value)) {
        visit(v2, k2);
      }
    }
  }, "visit");
  visit(args2);
  return [...matches2];
}
async function runForkedAgent(params) {
  if ("cacheSafeParams" in params) {
    const { config: config2, userMessage, cacheSafeParams, jsonSchema, abortSignal } = params;
    const model = params.model ?? cacheSafeParams.model;
    const chat = createForkedChat(config2, cacheSafeParams);
    const requestConfig = { ...NO_TOOLS };
    if (abortSignal)
      requestConfig.abortSignal = abortSignal;
    if (jsonSchema) {
      requestConfig.responseMimeType = "application/json";
      requestConfig.responseJsonSchema = jsonSchema;
    }
    const stream5 = await chat.sendMessageStream(model, { message: [{ text: userMessage }], config: requestConfig }, "forked_query");
    let fullText = "";
    let usage2 = {
      inputTokens: 0,
      outputTokens: 0,
      cacheHitTokens: 0
    };
    for await (const event of stream5) {
      if (event.type !== StreamEventType.CHUNK)
        continue;
      const response = event.value;
      const text = response.candidates?.[0]?.content?.parts?.filter((p2) => !p2["thought"]).map((p2) => p2.text ?? "").join("");
      if (text)
        fullText += text;
      if (response.usageMetadata)
        usage2 = extractQueryUsage(response.usageMetadata);
    }
    const trimmed2 = fullText.trim() || null;
    let jsonResult;
    if (jsonSchema && trimmed2) {
      try {
        jsonResult = JSON.parse(trimmed2);
      } catch {
      }
    }
    return { text: trimmed2, jsonResult, usage: usage2 };
  }
  const yoloConfig = createYoloConfig(params.config);
  const filesTouched = /* @__PURE__ */ new Set();
  const emitter = new AgentEventEmitter();
  emitter.on(AgentEventType.TOOL_CALL, (event) => {
    for (const filePath of extractFilePathsFromArgs(event.args)) {
      filesTouched.add(filePath);
    }
  });
  const promptConfig = {
    systemPrompt: params.systemPrompt,
    initialMessages: params.extraHistory
  };
  const modelConfig = {
    model: params.model ?? params.config.getFastModel() ?? params.config.getModel()
  };
  const runConfig = {
    max_turns: params.maxTurns,
    max_time_minutes: params.maxTimeMinutes
  };
  const toolConfig = params.tools !== void 0 ? { tools: params.tools } : void 0;
  const headless = await AgentHeadless.create(params.name, yoloConfig, promptConfig, modelConfig, runConfig, toolConfig, emitter);
  const context2 = new ContextState();
  context2.set("task_prompt", params.taskPrompt);
  await headless.execute(context2, params.abortSignal);
  const terminateReason = headless.getTerminateMode();
  const finalText = headless.getFinalText() || void 0;
  const touched = [...filesTouched];
  if (terminateReason === AgentTerminateMode.CANCELLED) {
    return {
      status: "cancelled",
      terminateReason,
      finalText,
      filesTouched: touched
    };
  }
  if (terminateReason === AgentTerminateMode.ERROR || terminateReason === AgentTerminateMode.TIMEOUT) {
    return {
      status: "failed",
      terminateReason,
      finalText,
      filesTouched: touched
    };
  }
  return {
    status: "completed",
    terminateReason,
    finalText,
    filesTouched: touched
  };
}
var currentCacheSafeParams, currentVersion, NO_TOOLS;
var init_forkedAgent = __esm({
  "packages/core/dist/src/utils/forkedAgent.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
    init_geminiChat();
    init_agents();
    currentCacheSafeParams = null;
    currentVersion = 0;
    __name(saveCacheSafeParams, "saveCacheSafeParams");
    __name(getCacheSafeParams, "getCacheSafeParams");
    __name(clearCacheSafeParams, "clearCacheSafeParams");
    NO_TOOLS = Object.freeze({ tools: [] });
    __name(createForkedChat, "createForkedChat");
    __name(extractQueryUsage, "extractQueryUsage");
    __name(createYoloConfig, "createYoloConfig");
    __name(extractFilePathsFromArgs, "extractFilePathsFromArgs");
    __name(runForkedAgent, "runForkedAgent");
  }
});

// packages/core/dist/src/utils/messageInspectors.js
function isFunctionResponse(content) {
  return content.role === "user" && !!content.parts && content.parts.every((part) => !!part.functionResponse);
}
var init_messageInspectors = __esm({
  "packages/core/dist/src/utils/messageInspectors.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isFunctionResponse, "isFunctionResponse");
  }
});

// packages/core/dist/src/utils/sideQuery.js
function buildDefaultPromptId(purpose) {
  return purpose ? `side-query:${purpose}` : "side-query";
}
async function runSideQuery(config2, options2) {
  const response = await config2.getBaseLlmClient().generateJson({
    contents: options2.contents,
    schema: options2.schema,
    abortSignal: options2.abortSignal,
    model: options2.model ?? config2.getModel() ?? DEFAULT_QWEN_MODEL,
    systemInstruction: options2.systemInstruction,
    promptId: options2.promptId ?? buildDefaultPromptId(options2.purpose),
    config: options2.config
  });
  const schemaError = SchemaValidator.validate(options2.schema, response);
  if (schemaError) {
    throw new Error(`Invalid side query response: ${schemaError}`);
  }
  const customError = options2.validate?.(response);
  if (customError) {
    throw new Error(customError);
  }
  return response;
}
var init_sideQuery = __esm({
  "packages/core/dist/src/utils/sideQuery.js"() {
    "use strict";
    init_esbuild_shims();
    init_models();
    init_schemaValidator();
    __name(buildDefaultPromptId, "buildDefaultPromptId");
    __name(runSideQuery, "runSideQuery");
  }
});

// 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 {
    return await runSideQuery(config2, {
      contents,
      schema: RESPONSE_SCHEMA,
      abortSignal,
      promptId,
      purpose: "next-speaker"
    });
  } catch (error40) {
    debugLogger46.warn("Failed to talk to Gemini endpoint when seeing if conversation should continue.", error40);
    return null;
  }
}
var debugLogger46, CHECK_PROMPT, RESPONSE_SCHEMA;
var init_nextSpeakerChecker = __esm({
  "packages/core/dist/src/utils/nextSpeakerChecker.js"() {
    "use strict";
    init_esbuild_shims();
    init_messageInspectors();
    init_debugLogger();
    init_sideQuery();
    debugLogger46 = 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/utils/promptIdContext.js
import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
var promptIdContext;
var init_promptIdContext = __esm({
  "packages/core/dist/src/utils/promptIdContext.js"() {
    "use strict";
    init_esbuild_shims();
    promptIdContext = new AsyncLocalStorage4();
  }
});

// packages/core/dist/src/core/client.js
var debugLogger47, MAX_TURNS, SendMessageType, EMPTY_RELEVANT_AUTO_MEMORY_RESULT, GeminiClient, TEST_ONLY;
var init_client4 = __esm({
  "packages/core/dist/src/core/client.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
    init_debugLogger();
    init_microcompact();
    init_geminiChat();
    init_prompts();
    init_turn();
    init_chatCompressionService();
    init_loopDetectionService();
    init_tool_names();
    init_telemetry();
    init_uiTelemetry();
    init_forkedAgent();
    init_environmentContext();
    init_sessionService();
    init_errorReporting();
    init_errors();
    init_nextSpeakerChecker();
    init_partUtils();
    init_promptIdContext();
    init_retry();
    init_types8();
    init_partUtils();
    init_types6();
    init_ideContext();
    init_types10();
    debugLogger47 = createDebugLogger("CLIENT");
    MAX_TURNS = 100;
    (function(SendMessageType2) {
      SendMessageType2["UserQuery"] = "userQuery";
      SendMessageType2["ToolResult"] = "toolResult";
      SendMessageType2["Retry"] = "retry";
      SendMessageType2["Hook"] = "hook";
      SendMessageType2["Cron"] = "cron";
      SendMessageType2["Notification"] = "notification";
    })(SendMessageType || (SendMessageType = {}));
    EMPTY_RELEVANT_AUTO_MEMORY_RESULT = {
      prompt: "",
      selectedDocs: [],
      strategy: "none"
    };
    GeminiClient = class {
      static {
        __name(this, "GeminiClient");
      }
      config;
      chat;
      sessionTurnCount = 0;
      surfacedRelevantAutoMemoryPaths = /* @__PURE__ */ new Set();
      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;
      /**
       * Promises for pending background memory tasks (dream / extract).
       * Each promise resolves with a count of memory files touched (0 = nothing written).
       * Consumed by the CLI via `consumePendingMemoryTaskPromises()`.
       */
      pendingMemoryTaskPromises = [];
      /**
       * Timestamp (epoch ms) of the last completed API call.
       * Used to detect idle periods for thinking block cleanup.
       * Starts as null — on the first query there is no prior thinking to clean,
       * so the idle check is skipped until the first API call completes.
       */
      lastApiCompletionTimestamp = null;
      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);
          await this.startChat(resumedHistory);
        } else {
          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(curated = false) {
        return this.getChat().getHistory(curated);
      }
      stripOrphanedUserEntriesFromHistory() {
        this.getChat().stripOrphanedUserEntriesFromHistory();
      }
      setHistory(history) {
        this.getChat().setHistory(history);
        this.forceFullIdeContext = true;
      }
      truncateHistory(keepCount) {
        this.getChat().truncateHistory(keepCount);
        this.forceFullIdeContext = true;
      }
      async setTools() {
        if (!this.isInitialized()) {
          return;
        }
        const toolRegistry = this.config.getToolRegistry();
        await toolRegistry.warmAll();
        const toolDeclarations = toolRegistry.getFunctionDeclarations();
        const tools = [{ functionDeclarations: toolDeclarations }];
        this.getChat().setTools(tools);
      }
      async resetChat() {
        this.surfacedRelevantAutoMemoryPaths.clear();
        this.lastApiCompletionTimestamp = null;
        await this.startChat();
      }
      getLoopDetectionService() {
        return this.loopDetector;
      }
      async addDirectoryContext() {
        if (!this.chat) {
          return;
        }
        this.getChat().addHistory({
          role: "user",
          parts: [{ text: await getDirectoryContextString(this.config) }]
        });
      }
      getMainSessionSystemInstruction() {
        const userMemory = this.config.getUserMemory();
        const overrideSystemPrompt = this.config.getSystemPrompt();
        const appendSystemPrompt = this.config.getAppendSystemPrompt();
        if (overrideSystemPrompt) {
          return getCustomSystemPrompt(overrideSystemPrompt, userMemory, appendSystemPrompt);
        }
        return getCoreSystemPrompt(userMemory, this.config.getModel(), appendSystemPrompt);
      }
      async startChat(extraHistory) {
        this.forceFullIdeContext = true;
        this.hasFailedCompressionAttempt = false;
        clearCacheSafeParams();
        const history = await getInitialChatHistory(this.config, extraHistory);
        try {
          const systemInstruction = this.getMainSessionSystemInstruction();
          this.chat = new GeminiChat(this.config, {
            systemInstruction
          }, history, this.config.getChatRecordingService(), uiTelemetryService);
          await this.setTools();
          return this.chat;
        } catch (error40) {
          await reportError2(error40, "Error initializing chat session.", history, "startChat");
          throw new Error(`Failed to initialize chat: ${getErrorMessage(error40)}`);
        }
      }
      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")
          ];
          debugLogger47.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 [path150] of currentFiles.entries()) {
            if (!lastFiles.has(path150)) {
              openedFiles.push(path150);
            }
          }
          if (openedFiles.length > 0) {
            changeLines.push("Files opened:");
            for (const filePath of openedFiles) {
              changeLines.push(`  - ${filePath}`);
            }
          }
          const closedFiles = [];
          for (const [path150] of lastFiles.entries()) {
            if (!currentFiles.has(path150)) {
              closedFiles.push(path150);
            }
          }
          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")
          ];
          debugLogger47.debug(contextParts.join("\n"));
          return {
            contextParts,
            newIdeContext: currentIdeContext
          };
        }
      }
      runManagedAutoMemoryBackgroundTasks(messageType) {
        if (messageType !== SendMessageType.UserQuery) {
          return;
        }
        if (!this.config.getManagedAutoMemoryEnabled()) {
          return;
        }
        const projectRoot = this.config.getProjectRoot();
        const sessionId = this.config.getSessionId();
        const history = this.getHistory();
        const mgr = this.config.getMemoryManager();
        const extractPromise = mgr.scheduleExtract({
          projectRoot,
          sessionId,
          history,
          config: this.config
        }).then((result) => result.touchedTopics.length).catch((error40) => {
          debugLogger47.warn("Failed to schedule managed auto-memory extraction.", error40);
          return 0;
        });
        this.pendingMemoryTaskPromises.push(extractPromise);
        const dreamPromise = mgr.scheduleDream({
          projectRoot,
          sessionId,
          config: this.config
        }).then((schedResult) => {
          if (schedResult.status === "scheduled" && schedResult.promise) {
            return schedResult.promise.then((state) => {
              const topics = state.metadata?.["touchedTopics"];
              return topics ? topics.length : 0;
            });
          }
          return 0;
        }).catch((error40) => {
          debugLogger47.warn("Failed to schedule managed auto-memory dream.", error40);
          return 0;
        });
        this.pendingMemoryTaskPromises.push(dreamPromise);
      }
      /**
       * Returns and clears the list of pending background memory task promises.
       * Each promise resolves with the number of memory files touched (0 = nothing
       * was written, caller should ignore).
       */
      consumePendingMemoryTaskPromises() {
        const promises9 = this.pendingMemoryTaskPromises;
        this.pendingMemoryTaskPromises = [];
        return promises9;
      }
      async *sendMessageStream(request4, signal, prompt_id, options2, turns = MAX_TURNS) {
        const messageType = options2?.type ?? SendMessageType.UserQuery;
        let relevantAutoMemoryPromise;
        if (messageType === SendMessageType.Retry) {
          this.stripOrphanedUserEntriesFromHistory();
        }
        const hooksEnabled = !this.config.getDisableAllHooks();
        const messageBus = this.config.getMessageBus();
        if (messageType !== SendMessageType.Retry && messageType !== SendMessageType.Cron && messageType !== SendMessageType.Notification && hooksEnabled && messageBus && this.config.hasHooksForEvent("UserPromptSubmit")) {
          const promptText = partToString(request4);
          const response = await messageBus.request({
            type: MessageBusType.HOOK_EXECUTION_REQUEST,
            eventName: "UserPromptSubmit",
            input: {
              prompt: promptText
            }
          }, MessageBusType.HOOK_EXECUTION_RESPONSE);
          const hookOutput = response.output ? createHookOutput("UserPromptSubmit", response.output) : void 0;
          if (hookOutput?.isBlockingDecision() || hookOutput?.shouldStopExecution()) {
            yield {
              type: GeminiEventType.UserPromptSubmitBlocked,
              value: {
                reason: hookOutput.getEffectiveReason(),
                originalPrompt: promptText
              }
            };
            return new Turn(this.getChat(), prompt_id);
          }
          const additionalContext = hookOutput?.getAdditionalContext();
          if (additionalContext) {
            const requestArray = Array.isArray(request4) ? request4 : [request4];
            request4 = [...requestArray, { text: additionalContext }];
          }
        }
        if (messageType === SendMessageType.Notification) {
          this.config.getChatRecordingService()?.recordNotification(request4, options2?.notificationDisplayText);
        }
        if (messageType === SendMessageType.UserQuery || messageType === SendMessageType.Cron || messageType === SendMessageType.Notification) {
          this.loopDetector.reset(prompt_id);
          this.lastPromptId = prompt_id;
        }
        if (messageType === SendMessageType.UserQuery || messageType === SendMessageType.Cron) {
          if (this.config.getManagedAutoMemoryEnabled()) {
            relevantAutoMemoryPromise = this.config.getMemoryManager().recall(this.config.getProjectRoot(), partToString(request4), {
              config: this.config,
              excludedFilePaths: this.surfacedRelevantAutoMemoryPaths
            }).catch((error40) => {
              debugLogger47.warn("Managed auto-memory recall prefetch failed.", error40);
              return EMPTY_RELEVANT_AUTO_MEMORY_RESULT;
            });
          }
          if (messageType === SendMessageType.Cron) {
            this.config.getChatRecordingService()?.recordCronPrompt(request4, options2?.notificationDisplayText);
          } else {
            this.config.getChatRecordingService()?.recordUserMessage(request4);
          }
          const mcResult = microcompactHistory(this.getChat().getHistory(), this.lastApiCompletionTimestamp, this.config.getClearContextOnIdle());
          if (mcResult.meta) {
            this.getChat().setHistory(mcResult.history);
            const m3 = mcResult.meta;
            debugLogger47.debug(`[TIME-BASED MC] gap ${m3.gapMinutes}min > ${m3.thresholdMinutes}min, cleared ${m3.toolsCleared} tool results (~${m3.tokensSaved} tokens), kept last ${m3.toolsKept}`);
          }
        }
        if (messageType !== SendMessageType.Retry) {
          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, signal);
        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 arenaAgentClient = this.config.getArenaAgentClient();
        if (arenaAgentClient) {
          const controlSignal = await arenaAgentClient.checkControlSignal();
          if (controlSignal) {
            debugLogger47.info(`Arena control signal received: ${controlSignal.type} - ${controlSignal.reason}`);
            await arenaAgentClient.reportCancelled();
            return new Turn(this.getChat(), prompt_id);
          }
        }
        const turn = new Turn(this.getChat(), prompt_id);
        const model = options2?.modelOverride ?? this.config.getModel();
        let requestToSent = await flatMapTextParts(request4, async (text) => [text]);
        if (messageType === SendMessageType.UserQuery || messageType === SendMessageType.Cron) {
          const systemReminders = [];
          const relevantAutoMemory = relevantAutoMemoryPromise ? await relevantAutoMemoryPromise : EMPTY_RELEVANT_AUTO_MEMORY_RESULT;
          const relevantAutoMemoryPrompt = relevantAutoMemory.prompt;
          if (relevantAutoMemoryPrompt) {
            systemReminders.push(relevantAutoMemoryPrompt);
            for (const doc of relevantAutoMemory.selectedDocs) {
              this.surfacedRelevantAutoMemoryPaths.add(doc.filePath);
            }
          }
          const hasAgentTool = await this.config.getToolRegistry().ensureTool(ToolNames.AGENT);
          const subagents = (await this.config.getSubagentManager().listSubagents()).filter((subagent) => subagent.level !== "builtin").map((subagent) => subagent.name);
          if (hasAgentTool && subagents.length > 0) {
            systemReminders.push(getSubagentSystemReminder(subagents));
          }
          if (this.config.getApprovalMode() === ApprovalMode.PLAN) {
            systemReminders.push(getPlanModeSystemReminder(this.config.getSdkMode()));
          }
          const arenaManager = this.config.getArenaManager();
          if (arenaManager) {
            try {
              const sessionDir = arenaManager.getArenaSessionDir();
              const configPath = `${sessionDir}/config.json`;
              systemReminders.push(getArenaSystemReminder(configPath));
            } catch {
            }
          }
          requestToSent = [...systemReminders, ...requestToSent];
        }
        const resultStream = turn.run(model, requestToSent, signal);
        for await (const event of resultStream) {
          if (!this.config.getSkipLoopDetection()) {
            if (this.loopDetector.addAndCheck(event)) {
              const loopType = this.loopDetector.getLastLoopType();
              yield {
                type: GeminiEventType.LoopDetected,
                ...loopType && { value: { loopType } }
              };
              if (arenaAgentClient) {
                await arenaAgentClient.reportError("Loop detected");
              }
              this.lastApiCompletionTimestamp = Date.now();
              return turn;
            }
          }
          if (arenaAgentClient && event.type === GeminiEventType.Finished) {
            await arenaAgentClient.updateStatus();
          }
          yield event;
          if (event.type === GeminiEventType.Error) {
            if (arenaAgentClient) {
              const errorMsg = event.value instanceof Error ? event.value.message : "Unknown error";
              await arenaAgentClient.reportError(errorMsg);
            }
            this.lastApiCompletionTimestamp = Date.now();
            return turn;
          }
        }
        this.lastApiCompletionTimestamp = Date.now();
        if (hooksEnabled && messageBus && !turn.pendingToolCalls.length && signal && !signal.aborted && this.config.hasHooksForEvent("Stop")) {
          const history2 = this.getHistory();
          const lastModelMessage = history2.filter((msg) => msg.role === "model").pop();
          const responseText = lastModelMessage?.parts?.filter((p2) => "text" in p2).map((p2) => p2.text).join("") || "[no response text]";
          const response = await messageBus.request({
            type: MessageBusType.HOOK_EXECUTION_REQUEST,
            eventName: "Stop",
            input: {
              stop_hook_active: true,
              last_assistant_message: responseText
            },
            signal
          }, MessageBusType.HOOK_EXECUTION_RESPONSE);
          if (signal.aborted) {
            return turn;
          }
          const hookOutput = response.output ? createHookOutput("Stop", response.output) : void 0;
          const stopOutput = hookOutput;
          if (stopOutput?.systemMessage) {
            yield {
              type: GeminiEventType.HookSystemMessage,
              value: stopOutput.systemMessage
            };
          }
          if (stopOutput?.isBlockingDecision() || stopOutput?.shouldStopExecution()) {
            if (signal.aborted) {
              return turn;
            }
            const continueReason = stopOutput.getEffectiveReason();
            const currentIterationCount = (options2?.stopHookState?.iterationCount ?? 0) + 1;
            const currentReasons = [
              ...options2?.stopHookState?.reasons ?? [],
              continueReason
            ];
            if (currentIterationCount > 1) {
              yield {
                type: GeminiEventType.StopHookLoop,
                value: {
                  iterationCount: currentIterationCount,
                  reasons: currentReasons,
                  stopHookCount: response.stopHookCount ?? 1
                }
              };
            }
            const continueRequest = [{ text: continueReason }];
            return yield* this.sendMessageStream(continueRequest, signal, prompt_id, {
              type: SendMessageType.Hook,
              modelOverride: options2?.modelOverride,
              stopHookState: {
                iterationCount: currentIterationCount,
                reasons: currentReasons
              }
            }, boundedTurns - 1);
          }
        }
        if (!turn.pendingToolCalls.length && signal && !signal.aborted) {
          try {
            const chat = this.getChat();
            const fullHistory = chat.getHistory(true);
            const maxHistoryForCache = 40;
            const cachedHistory = fullHistory.length > maxHistoryForCache ? fullHistory.slice(-maxHistoryForCache) : fullHistory;
            saveCacheSafeParams(chat.getGenerationConfig(), cachedHistory, this.config.getModel());
          } catch {
          }
          if (this.config.getSkipNextSpeakerCheck()) {
            this.runManagedAutoMemoryBackgroundTasks(messageType);
            if (arenaAgentClient) {
              await arenaAgentClient.reportCompleted();
            }
            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." }];
            return yield* this.sendMessageStream(nextRequest, signal, prompt_id, options2, boundedTurns - 1);
          }
          this.runManagedAutoMemoryBackgroundTasks(messageType);
          if (arenaAgentClient) {
            await arenaAgentClient.reportCompleted();
          }
        }
        if (signal?.aborted && arenaAgentClient) {
          await arenaAgentClient.reportCancelled();
        }
        return turn;
      }
      async generateContent(contents, generationConfig, abortSignal, model, promptIdOverride) {
        let currentAttemptModel = model;
        const promptId = promptIdOverride ?? promptIdContext.getStore() ?? this.lastPromptId;
        try {
          const userMemory = this.config.getUserMemory();
          const finalSystemInstruction = generationConfig.systemInstruction ? getCustomSystemPrompt(generationConfig.systemInstruction, userMemory) : this.getMainSessionSystemInstruction();
          const requestConfig = {
            abortSignal,
            ...generationConfig,
            systemInstruction: finalSystemInstruction
          };
          const apiCall = /* @__PURE__ */ __name(() => {
            currentAttemptModel = model;
            return this.getContentGeneratorOrFail().generateContent({
              model,
              config: requestConfig,
              contents
            }, promptId);
          }, "apiCall");
          const result = await retryWithBackoff(apiCall, {
            authType: this.config.getContentGeneratorConfig()?.authType,
            persistentMode: isUnattendedMode(),
            signal: abortSignal,
            heartbeatFn: /* @__PURE__ */ __name((info2) => {
              process.stderr.write(`[qwen-code] Waiting for API capacity... attempt ${info2.attempt}, retry in ${Math.ceil(info2.remainingMs / 1e3)}s
`);
            }, "heartbeatFn")
          });
          return result;
        } catch (error40) {
          if (abortSignal.aborted) {
            throw error40;
          }
          await reportError2(error40, `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(error40)}`);
        }
      }
      async tryCompressChat(prompt_id, force = false, signal) {
        const compressionService = new ChatCompressionService();
        const { newHistory, info: info2 } = await compressionService.compress(this.getChat(), prompt_id, force, this.config.getModel(), this.config, this.hasFailedCompressionAttempt, signal);
        if (info2.compressionStatus === CompressionStatus.COMPRESSED) {
          if (newHistory) {
            const chatRecordingService = this.config.getChatRecordingService();
            chatRecordingService?.recordChatCompression({
              info: info2,
              compressedHistory: newHistory
            });
            await this.startChat(newHistory);
            uiTelemetryService.setLastPromptTokenCount(info2.newTokenCount);
            this.forceFullIdeContext = true;
          }
        } else if (info2.compressionStatus === CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT || info2.compressionStatus === CompressionStatus.COMPRESSION_FAILED_EMPTY_SUMMARY) {
          if (!force) {
            this.hasFailedCompressionAttempt = true;
          }
        }
        return info2;
      }
    };
    TEST_ONLY = {
      COMPRESSION_PRESERVE_THRESHOLD,
      COMPRESSION_TOKEN_THRESHOLD
    };
  }
});

// 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 i4 = ai;
      if (ai >= 0 && bi > 0) {
        if (a2 === b2) {
          return [ai, bi];
        }
        begs = [];
        left3 = str2.length;
        while (i4 >= 0 && !result) {
          if (i4 == ai) {
            begs.push(i4);
            ai = str2.indexOf(a2, i4 + 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, i4 + 1);
          }
          i4 = 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 parts2 = [];
      var m3 = balanced("{", "}", str2);
      if (!m3)
        return str2.split(",");
      var pre = m3.pre;
      var body2 = m3.body;
      var post2 = m3.post;
      var p2 = pre.split(",");
      p2[p2.length - 1] += "{" + body2 + "}";
      var postParts = parseCommaParts(post2);
      if (post2.length) {
        p2[p2.length - 1] += postParts.shift();
        p2.push.apply(p2, postParts);
      }
      parts2.push.apply(parts2, p2);
      return parts2;
    }
    __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(i4, y2) {
      return i4 <= y2;
    }
    __name(lte, "lte");
    function gte(i4, y2) {
      return i4 >= y2;
    }
    __name(gte, "gte");
    function expand2(str2, isTop) {
      var expansions = [];
      var m3 = balanced("{", "}", str2);
      if (!m3) return [str2];
      var pre = m3.pre;
      var post2 = m3.post.length ? expand2(m3.post, false) : [""];
      if (/\$$/.test(m3.pre)) {
        for (var k2 = 0; k2 < post2.length; k2++) {
          var expansion = pre + "{" + m3.body + "}" + post2[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 post2.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 test2 = lte;
          var reverse = y2 < x3;
          if (reverse) {
            incr *= -1;
            test2 = gte;
          }
          var pad2 = n3.some(isPadded);
          N2 = [];
          for (var i4 = x3; test2(i4, y2); i4 += incr) {
            var c4;
            if (isAlphaSequence) {
              c4 = String.fromCharCode(i4);
              if (c4 === "\\")
                c4 = "";
            } else {
              c4 = String(i4);
              if (pad2) {
                var need = width - c4.length;
                if (need > 0) {
                  var z2 = new Array(need + 1).join("0");
                  if (i4 < 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 < post2.length; k2++) {
            var expansion = pre + N2[j2] + post2[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 i4 = pos2 + 1;
      let sawStart = false;
      let uflag = false;
      let escaping = false;
      let negate = false;
      let endPos = pos2;
      let rangeStart = "";
      WHILE: while (i4 < glob2.length) {
        const c4 = glob2.charAt(i4);
        if ((c4 === "!" || c4 === "^") && i4 === pos2 + 1) {
          negate = true;
          i4++;
          continue;
        }
        if (c4 === "]" && sawStart && !escaping) {
          endPos = i4 + 1;
          break;
        }
        sawStart = true;
        if (c4 === "\\") {
          if (!escaping) {
            escaping = true;
            i4++;
            continue;
          }
        }
        if (c4 === "[" && !escaping) {
          for (const [cls, [unip, u2, neg]] of Object.entries(posixClasses)) {
            if (glob2.startsWith(cls, i4)) {
              if (rangeStart) {
                return ["$.", false, glob2.length - pos2, true];
              }
              i4 += 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 = "";
          i4++;
          continue;
        }
        if (glob2.startsWith("-]", i4 + 1)) {
          ranges2.push(braceEscape(c4 + "-"));
          i4 += 2;
          continue;
        }
        if (glob2.startsWith("-", i4 + 1)) {
          rangeStart = c4;
          i4 += 2;
          continue;
        }
        ranges2.push(braceEscape(c4));
        i4++;
      }
      if (endPos < i4) {
        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 types4, 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();
    types4 = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
    isExtglobType = /* @__PURE__ */ __name((c4) => types4.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 i4 = p2.#parentIndex + 1; !pp.type && i4 < pp.#parts.length; i4++) {
              for (const part of n3.#parts) {
                if (typeof part === "string") {
                  throw new Error("string part in extglob AST??");
                }
                part.copyIn(pp.#parts[i4]);
              }
            }
            p2 = pp;
            pp = p2.#parent;
          }
        }
        return this;
      }
      push(...parts2) {
        for (const p2 of parts2) {
          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 i4 = 0; i4 < this.#parentIndex; i4++) {
          const pp = p2.#parts[i4];
          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 i5 = pos2;
          let acc2 = "";
          while (i5 < str2.length) {
            const c4 = str2.charAt(i5++);
            if (escaping || c4 === "\\") {
              escaping = !escaping;
              acc2 += c4;
              continue;
            }
            if (inBrace) {
              if (i5 === braceStart + 1) {
                if (c4 === "^" || c4 === "!") {
                  braceNeg = true;
                }
              } else if (c4 === "]" && !(i5 === braceStart + 2 && braceNeg)) {
                inBrace = false;
              }
              acc2 += c4;
              continue;
            } else if (c4 === "[") {
              inBrace = true;
              braceStart = i5;
              braceNeg = false;
              acc2 += c4;
              continue;
            }
            if (!opt.noext && isExtglobType(c4) && str2.charAt(i5) === "(") {
              ast.push(acc2);
              acc2 = "";
              const ext2 = new _AST(c4, ast);
              i5 = _AST.#parseAST(str2, ext2, i5, opt);
              ast.push(ext2);
              continue;
            }
            acc2 += c4;
          }
          ast.push(acc2);
          return i5;
        }
        let i4 = pos2 + 1;
        let part = new _AST(null, ast);
        const parts2 = [];
        let acc = "";
        while (i4 < str2.length) {
          const c4 = str2.charAt(i4++);
          if (escaping || c4 === "\\") {
            escaping = !escaping;
            acc += c4;
            continue;
          }
          if (inBrace) {
            if (i4 === braceStart + 1) {
              if (c4 === "^" || c4 === "!") {
                braceNeg = true;
              }
            } else if (c4 === "]" && !(i4 === braceStart + 2 && braceNeg)) {
              inBrace = false;
            }
            acc += c4;
            continue;
          } else if (c4 === "[") {
            inBrace = true;
            braceStart = i4;
            braceNeg = false;
            acc += c4;
            continue;
          }
          if (isExtglobType(c4) && str2.charAt(i4) === "(") {
            part.push(acc);
            acc = "";
            const ext2 = new _AST(c4, part);
            part.push(ext2);
            i4 = _AST.#parseAST(str2, ext2, i4, opt);
            continue;
          }
          if (c4 === "|") {
            part.push(acc);
            acc = "";
            parts2.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(...parts2, part);
            return i4;
          }
          acc += c4;
        }
        ast.type = null;
        ast.#hasMagic = void 0;
        ast.#parts = [str2.substring(pos2 - 1)];
        return i4;
      }
      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, body2, hasMagic2, uflag] = this.toRegExpSource();
        const anyMagic = hasMagic2 || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob2.toUpperCase() !== glob2.toLowerCase();
        if (!anyMagic) {
          return body2;
        }
        const flags2 = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");
        return Object.assign(new RegExp(`^${re3}$`, flags2), {
          _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 start3 = "";
          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));
                start3 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
              }
            }
          }
          let end = "";
          if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") {
            end = "(?:$|\\/)";
          }
          const final2 = start3 + src + end;
          return [
            final2,
            unescape2(src),
            this.#hasMagic = !!this.#hasMagic,
            this.#uflag
          ];
        }
        const repeated = this.type === "*" || this.type === "+";
        const start2 = this.type === "!" ? "(?:(?!(?:" : "(?:";
        let body2 = this.#partsToRegExp(dot);
        if (this.isStart() && this.isEnd() && !body2 && 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 === body2) {
          bodyDotAllowed = "";
        }
        if (bodyDotAllowed) {
          body2 = `(?:${body2})(?:${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 = start2 + body2 + close;
        }
        return [
          final,
          unescape2(body2),
          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 i4 = 0; i4 < glob2.length; i4++) {
          const c4 = glob2.charAt(i4);
          if (escaping) {
            escaping = false;
            re3 += (reSpecials.has(c4) ? "\\" : "") + c4;
            continue;
          }
          if (c4 === "\\") {
            if (i4 === glob2.length - 1) {
              re3 += "\\\\";
            } else {
              escaping = true;
            }
            continue;
          }
          if (c4 === "[") {
            const [src, needUflag, consumed, magic] = parseClass(glob2, i4);
            if (consumed) {
              re3 += src;
              uflag = uflag || needUflag;
              i4 += 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, path42, sep4, GLOBSTAR, qmark2, star2, twoStarDot, twoStarNoDot, filter, ext, defaults2, braceExpand, makeRe, match, globMagic, regExpEscape2, Minimatch;
var init_esm9 = __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";
    path42 = {
      win32: { sep: "\\" },
      posix: { sep: "/" }
    };
    sep4 = defaultPlatform === "win32" ? path42.win32.sep : path42.posix.sep;
    minimatch.sep = sep4;
    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 = (...args2) => console.error(...args2);
        }
        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 set2 = 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, set2);
        this.set = set2.filter((s5) => s5.indexOf(false) === -1);
        if (this.isWindows) {
          for (let i4 = 0; i4 < this.set.length; i4++) {
            const p2 = this.set[i4];
            if (p2[0] === "" && p2[1] === "" && this.globParts[i4][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 i4 = 0; i4 < globParts.length; i4++) {
            for (let j2 = 0; j2 < globParts[i4].length; j2++) {
              if (globParts[i4][j2] === "**") {
                globParts[i4][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((parts2) => {
          let gs = -1;
          while (-1 !== (gs = parts2.indexOf("**", gs + 1))) {
            let i4 = gs;
            while (parts2[i4 + 1] === "**") {
              i4++;
            }
            if (i4 !== gs) {
              parts2.splice(gs, i4 - gs);
            }
          }
          return parts2;
        });
      }
      // get rid of adjascent ** and resolve .. portions
      levelOneOptimize(globParts) {
        return globParts.map((parts2) => {
          parts2 = parts2.reduce((set2, part) => {
            const prev = set2[set2.length - 1];
            if (part === "**" && prev === "**") {
              return set2;
            }
            if (part === "..") {
              if (prev && prev !== ".." && prev !== "." && prev !== "**") {
                set2.pop();
                return set2;
              }
            }
            set2.push(part);
            return set2;
          }, []);
          return parts2.length === 0 ? [""] : parts2;
        });
      }
      levelTwoFileOptimize(parts2) {
        if (!Array.isArray(parts2)) {
          parts2 = this.slashSplit(parts2);
        }
        let didSomething = false;
        do {
          didSomething = false;
          if (!this.preserveMultipleSlashes) {
            for (let i4 = 1; i4 < parts2.length - 1; i4++) {
              const p2 = parts2[i4];
              if (i4 === 1 && p2 === "" && parts2[0] === "")
                continue;
              if (p2 === "." || p2 === "") {
                didSomething = true;
                parts2.splice(i4, 1);
                i4--;
              }
            }
            if (parts2[0] === "." && parts2.length === 2 && (parts2[1] === "." || parts2[1] === "")) {
              didSomething = true;
              parts2.pop();
            }
          }
          let dd = 0;
          while (-1 !== (dd = parts2.indexOf("..", dd + 1))) {
            const p2 = parts2[dd - 1];
            if (p2 && p2 !== "." && p2 !== ".." && p2 !== "**") {
              didSomething = true;
              parts2.splice(dd - 1, 2);
              dd -= 2;
            }
          }
        } while (didSomething);
        return parts2.length === 0 ? [""] : parts2;
      }
      // 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 parts2 of globParts) {
            let gs = -1;
            while (-1 !== (gs = parts2.indexOf("**", gs + 1))) {
              let gss = gs;
              while (parts2[gss + 1] === "**") {
                gss++;
              }
              if (gss > gs) {
                parts2.splice(gs + 1, gss - gs);
              }
              let next = parts2[gs + 1];
              const p2 = parts2[gs + 2];
              const p22 = parts2[gs + 3];
              if (next !== "..")
                continue;
              if (!p2 || p2 === "." || p2 === ".." || !p22 || p22 === "." || p22 === "..") {
                continue;
              }
              didSomething = true;
              parts2.splice(gs, 1);
              const other2 = parts2.slice(0);
              other2[gs] = "**";
              globParts.push(other2);
              gs--;
            }
            if (!this.preserveMultipleSlashes) {
              for (let i4 = 1; i4 < parts2.length - 1; i4++) {
                const p2 = parts2[i4];
                if (i4 === 1 && p2 === "" && parts2[0] === "")
                  continue;
                if (p2 === "." || p2 === "") {
                  didSomething = true;
                  parts2.splice(i4, 1);
                  i4--;
                }
              }
              if (parts2[0] === "." && parts2.length === 2 && (parts2[1] === "." || parts2[1] === "")) {
                didSomething = true;
                parts2.pop();
              }
            }
            let dd = 0;
            while (-1 !== (dd = parts2.indexOf("..", dd + 1))) {
              const p2 = parts2[dd - 1];
              if (p2 && p2 !== "." && p2 !== ".." && p2 !== "**") {
                didSomething = true;
                const needDot = dd === 1 && parts2[dd + 1] === "**";
                const splin = needDot ? ["."] : [];
                parts2.splice(dd - 1, 2, ...splin);
                if (parts2.length === 0)
                  parts2.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 i4 = 0; i4 < globParts.length - 1; i4++) {
          for (let j2 = i4 + 1; j2 < globParts.length; j2++) {
            const matched = this.partsMatch(globParts[i4], globParts[j2], !this.preserveMultipleSlashes);
            if (matched) {
              globParts[i4] = [];
              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 i4 = 0; i4 < pattern.length && pattern.charAt(i4) === "!"; i4++) {
          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(file2, pattern, partial2 = false) {
        const options2 = this.options;
        if (this.isWindows) {
          const fileDrive = typeof file2[0] === "string" && /^[a-z]:$/i.test(file2[0]);
          const fileUNC = !fileDrive && file2[0] === "" && file2[1] === "" && file2[2] === "?" && /^[a-z]:$/i.test(file2[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] = [file2[fdi], pattern[pdi]];
            if (fd.toLowerCase() === pd.toLowerCase()) {
              pattern[pdi] = fd;
              if (pdi > fdi) {
                pattern = pattern.slice(pdi);
              } else if (fdi > pdi) {
                file2 = file2.slice(fdi);
              }
            }
          }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
          file2 = this.levelTwoFileOptimize(file2);
        }
        this.debug("matchOne", this, { file: file2, pattern });
        this.debug("matchOne", file2.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file2.length, pl2 = pattern.length; fi < fl && pi < pl2; fi++, pi++) {
          this.debug("matchOne loop");
          var p2 = pattern[pi];
          var f5 = file2[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 (file2[fi] === "." || file2[fi] === ".." || !options2.dot && file2[fi].charAt(0) === ".")
                  return false;
              }
              return true;
            }
            while (fr2 < fl) {
              var swallowee = file2[fr2];
              this.debug("\nglobstar while", file2, fr2, pattern, pr2, swallowee);
              if (this.matchOne(file2.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!", file2, fr2, pattern, pr2);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr2++;
              }
            }
            if (partial2) {
              this.debug("\n>>> no match, partial?", file2, 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 && file2[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 set2 = this.set;
        if (!set2.length) {
          this.regexp = false;
          return this.regexp;
        }
        const options2 = this.options;
        const twoStar = options2.noglobstar ? star2 : options2.dot ? twoStarDot : twoStarNoDot;
        const flags2 = new Set(options2.nocase ? ["i"] : []);
        let re3 = set2.map((pattern) => {
          const pp = pattern.map((p2) => {
            if (p2 instanceof RegExp) {
              for (const f5 of p2.flags.split(""))
                flags2.add(f5);
            }
            return typeof p2 === "string" ? regExpEscape2(p2) : p2 === GLOBSTAR ? GLOBSTAR : p2._src;
          });
          pp.forEach((p2, i4) => {
            const next = pp[i4 + 1];
            const prev = pp[i4 - 1];
            if (p2 !== GLOBSTAR || prev === GLOBSTAR) {
              return;
            }
            if (prev === void 0) {
              if (next !== void 0 && next !== GLOBSTAR) {
                pp[i4 + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
              } else {
                pp[i4] = twoStar;
              }
            } else if (next === void 0) {
              pp[i4 - 1] = prev + "(?:\\/|" + twoStar + ")?";
            } else if (next !== GLOBSTAR) {
              pp[i4 - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
              pp[i4 + 1] = GLOBSTAR;
            }
          });
          return pp.filter((p2) => p2 !== GLOBSTAR).join("/");
        }).join("|");
        const [open4, close] = set2.length > 1 ? ["(?:", ")"] : ["", ""];
        re3 = "^" + open4 + re3 + close + "$";
        if (this.negate)
          re3 = "^(?!" + re3 + ").+$";
        try {
          this.regexp = new RegExp(re3, [...flags2].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 set2 = this.set;
        this.debug(this.pattern, "set", set2);
        let filename = ff[ff.length - 1];
        if (!filename) {
          for (let i4 = ff.length - 2; !filename && i4 >= 0; i4--) {
            filename = ff[i4];
          }
        }
        for (let i4 = 0; i4 < set2.length; i4++) {
          const pattern = set2[i4];
          let file2 = ff;
          if (options2.matchBase && pattern.length === 1) {
            file2 = [filename];
          }
          const hit = this.matchOne(file2, 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_esm10 = __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, start2 = perf.now()) => {
          starts[index] = ttl !== 0 ? start2 : 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 start2 = starts[index];
            if (!ttl || !start2)
              return;
            status.ttl = ttl;
            status.start = start2;
            status.now = cachedNow || getNow();
            const age = status.now - start2;
            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 start2 = starts[index];
          if (!ttl || !start2) {
            return Infinity;
          }
          const age = (cachedNow || getNow()) - start2;
          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 i4 = this.#tail; true; ) {
            if (!this.#isValidIndex(i4)) {
              break;
            }
            if (allowStale || !this.#isStale(i4)) {
              yield i4;
            }
            if (i4 === this.#head) {
              break;
            } else {
              i4 = this.#prev[i4];
            }
          }
        }
      }
      *#rindexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
          for (let i4 = this.#head; true; ) {
            if (!this.#isValidIndex(i4)) {
              break;
            }
            if (allowStale || !this.#isStale(i4)) {
              yield i4;
            }
            if (i4 === this.#tail) {
              break;
            } else {
              i4 = this.#next[i4];
            }
          }
        }
      }
      #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 i4 of this.#indexes()) {
          if (this.#valList[i4] !== void 0 && this.#keyList[i4] !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            yield [this.#keyList[i4], this.#valList[i4]];
          }
        }
      }
      /**
       * 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 i4 of this.#rindexes()) {
          if (this.#valList[i4] !== void 0 && this.#keyList[i4] !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            yield [this.#keyList[i4], this.#valList[i4]];
          }
        }
      }
      /**
       * Return a generator yielding the keys in the cache,
       * in order from most recently used to least recently used.
       */
      *keys() {
        for (const i4 of this.#indexes()) {
          const k2 = this.#keyList[i4];
          if (k2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            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 i4 of this.#rindexes()) {
          const k2 = this.#keyList[i4];
          if (k2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            yield k2;
          }
        }
      }
      /**
       * Return a generator yielding the values in the cache,
       * in order from most recently used to least recently used.
       */
      *values() {
        for (const i4 of this.#indexes()) {
          const v2 = this.#valList[i4];
          if (v2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            yield this.#valList[i4];
          }
        }
      }
      /**
       * 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 i4 of this.#rindexes()) {
          const v2 = this.#valList[i4];
          if (v2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            yield this.#valList[i4];
          }
        }
      }
      /**
       * 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 i4 of this.#indexes()) {
          const v2 = this.#valList[i4];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          if (fn(value, this.#keyList[i4], this)) {
            return this.get(this.#keyList[i4], 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 i4 of this.#indexes()) {
          const v2 = this.#valList[i4];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i4], 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 i4 of this.#rindexes()) {
          const v2 = this.#valList[i4];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i4], this);
        }
      }
      /**
       * Delete any stale entries. Returns true if anything was removed,
       * false otherwise.
       */
      purgeStale() {
        let deleted = false;
        for (const i4 of this.#rindexes({ allowStale: true })) {
          if (this.#isStale(i4)) {
            this.#delete(this.#keyList[i4], "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 i4 = this.#keyMap.get(key);
        if (i4 === void 0)
          return void 0;
        const v2 = this.#valList[i4];
        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[i4];
          const start2 = this.#starts[i4];
          if (ttl && start2) {
            const remain = ttl - (perf.now() - start2);
            entry.ttl = remain;
            entry.start = Date.now();
          }
        }
        if (this.#sizes) {
          entry.size = this.#sizes[i4];
        }
        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 i4 of this.#indexes({ allowStale: true })) {
          const key = this.#keyList[i4];
          const v2 = this.#valList[i4];
          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[i4];
            const age = perf.now() - this.#starts[i4];
            entry.start = Math.floor(Date.now() - age);
          }
          if (this.#sizes) {
            entry.size = this.#sizes[i4];
          }
          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: start2, 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, start2);
          }
          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 EventEmitter6 } 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, ABORT2, ABORTED, SIGNAL, DATALISTENERS, DISCARDED, defer, nodefer, isEndish, isArrayBufferLike, isArrayBufferView, Pipe, PipeProxyErrors, isObjectModeOptions, isEncodingOptions, Minipass;
var init_esm11 = __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 EventEmitter6 && 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 EventEmitter6 && 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");
    ABORT2 = 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 EventEmitter6 {
      static {
        __name(this, "Minipass");
      }
      [FLOWING] = false;
      [PAUSED] = false;
      [PIPES] = [];
      [BUFFER] = [];
      [OBJECTMODE];
      [ENCODING];
      [ASYNC];
      [DECODER];
      [EOF] = false;
      [EMITTED_END] = false;
      [EMITTING_END] = false;
      [CLOSED] = false;
      [EMITTED_ERROR] = null;
      [BUFFERLENGTH] = 0;
      [DESTROYED] = false;
      [SIGNAL];
      [ABORTED] = false;
      [DATALISTENERS] = 0;
      [DISCARDED] = false;
      /**
       * true if the stream can be written
       */
      writable = true;
      /**
       * true if the stream can be read
       */
      readable = true;
      /**
       * If `RType` is Buffer, then options do not need to be provided.
       * Otherwise, an options object must be provided to specify either
       * {@link Minipass.SharedOptions.objectMode} or
       * {@link Minipass.SharedOptions.encoding}, as appropriate.
       */
      constructor(...args2) {
        const options2 = args2[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[ABORT2]();
          } else {
            signal.addEventListener("abort", () => this[ABORT2]());
          }
        }
      }
      /**
       * 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
      [ABORT2]() {
        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, ...args2) {
        const data = args2[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, ...args2);
        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((resolve42, reject) => {
          this.on(DESTROYED, () => reject(new Error("stream destroyed")));
          this.on("error", (er2) => reject(er2));
          this.on("end", () => resolve42());
        });
      }
      /**
       * Asynchronous `for await of` iteration.
       *
       * This will continue emitting all chunks until the stream terminates.
       */
      [Symbol.asyncIterator]() {
        this[DISCARDED] = false;
        let stopped = false;
        const stop3 = /* @__PURE__ */ __name(async () => {
          this.pause();
          stopped = true;
          return { value: void 0, done: true };
        }, "stop");
        const next = /* @__PURE__ */ __name(() => {
          if (stopped)
            return stop3();
          const res = this.read();
          if (res !== null)
            return Promise.resolve({ done: false, value: res });
          if (this[EOF])
            return stop3();
          let resolve42;
          let reject;
          const onerr = /* @__PURE__ */ __name((er2) => {
            this.off("data", ondata);
            this.off("end", onend);
            this.off(DESTROYED, ondestroy);
            stop3();
            reject(er2);
          }, "onerr");
          const ondata = /* @__PURE__ */ __name((value) => {
            this.off("error", onerr);
            this.off("end", onend);
            this.off(DESTROYED, ondestroy);
            this.pause();
            resolve42({ value, done: !!this[EOF] });
          }, "ondata");
          const onend = /* @__PURE__ */ __name(() => {
            this.off("error", onerr);
            this.off("data", ondata);
            this.off(DESTROYED, ondestroy);
            stop3();
            resolve42({ done: true, value: void 0 });
          }, "onend");
          const ondestroy = /* @__PURE__ */ __name(() => onerr(new Error("stream destroyed")), "ondestroy");
          return new Promise((res2, rej) => {
            reject = rej;
            resolve42 = res2;
            this.once(DESTROYED, ondestroy);
            this.once("error", onerr);
            this.once("end", onend);
            this.once("data", ondata);
          });
        }, "next");
        return {
          next,
          throw: stop3,
          return: stop3,
          [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 stop3 = /* @__PURE__ */ __name(() => {
          this.pause();
          this.off(ERROR, stop3);
          this.off(DESTROYED, stop3);
          this.off("end", stop3);
          stopped = true;
          return { done: true, value: void 0 };
        }, "stop");
        const next = /* @__PURE__ */ __name(() => {
          if (stopped)
            return stop3();
          const value = this.read();
          return value === null ? stop3() : { done: false, value };
        }, "next");
        this.once("end", stop3);
        this.once(ERROR, stop3);
        this.once(DESTROYED, stop3);
        return {
          next,
          throw: stop3,
          return: stop3,
          [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 fileURLToPath4 } from "node:url";
import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync as readlinkSync2, realpathSync as rps } from "fs";
import * as actualFS from "node:fs";
import { lstat, readdir as readdir3, readlink, realpath } from "node:fs/promises";
var realpathSync4, 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, normalize4, normalizeNocaseCache, normalizeNocase, ResolveCache, ChildrenCache, setAsCwd, PathBase, PathWin32, PathPosix, PathScurryBase, PathScurryWin32, PathScurryPosix, PathScurryDarwin, Path, PathScurry;
var init_esm12 = __esm({
  "node_modules/path-scurry/dist/esm/index.js"() {
    init_esbuild_shims();
    init_esm10();
    init_esm11();
    realpathSync4 = rps.native;
    defaultFS = {
      lstatSync,
      readdir: readdirCB,
      readdirSync,
      readlinkSync: readlinkSync2,
      realpathSync: realpathSync4,
      promises: {
        lstat,
        readdir: readdir3,
        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();
    normalize4 = /* @__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 = normalize4(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(name4, type = UNKNOWN, root, roots, nocase, children, opts) {
        this.name = name4;
        this.#matchName = nocase ? normalizeNocase(name4) : normalize4(name4);
        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(path150) {
        if (!path150) {
          return this;
        }
        const rootPath = this.getRootString(path150);
        const dir = path150.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 name4 = this.nocase ? normalizeNocase(pathPart) : normalize4(pathPart);
        for (const p2 of children) {
          if (p2.#matchName === name4) {
            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 name4 = this.name;
        const p2 = this.parent;
        if (!p2) {
          return this.#relative = this.name;
        }
        const pv = p2.relative();
        return pv + (!pv || !p2.parent ? "" : this.sep) + name4;
      }
      /**
       * 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 name4 = this.name;
        const p2 = this.parent;
        if (!p2) {
          return this.#relativePosix = this.fullpathPosix();
        }
        const pv = p2.relativePosix();
        return pv + (!pv || !p2.parent ? "" : "/") + name4;
      }
      /**
       * The fully resolved path string for this Path entry
       */
      fullpath() {
        if (this.#fullpath !== void 0) {
          return this.#fullpath;
        }
        const name4 = this.name;
        const p2 = this.parent;
        if (!p2) {
          return this.#fullpath = this.name;
        }
        const pv = p2.fullpath();
        const fp = pv + (!p2.parent ? "" : this.sep) + name4;
        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 === normalize4(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 name4 = this.nocase ? normalizeNocase(e4.name) : normalize4(e4.name);
          if (name4 !== 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 resolve42 = /* @__PURE__ */ __name(() => {
          }, "resolve");
          this.#asyncReaddirInFlight = new Promise((res) => resolve42 = 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;
          resolve42();
        }
        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(name4, type = UNKNOWN, root, roots, nocase, children, opts) {
        super(name4, type, root, roots, nocase, children, opts);
      }
      /**
       * @internal
       */
      newChild(name4, type = UNKNOWN, opts = {}) {
        return new _PathWin32(name4, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
      }
      /**
       * @internal
       */
      getRootString(path150) {
        return win32.parse(path150).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(name4, type = UNKNOWN, root, roots, nocase, children, opts) {
        super(name4, type, root, roots, nocase, children, opts);
      }
      /**
       * @internal
       */
      getRootString(path150) {
        return path150.startsWith("/") ? "/" : "";
      }
      /**
       * @internal
       */
      getRoot(_rootPath) {
        return this.root;
      }
      /**
       * @internal
       */
      newChild(name4, type = UNKNOWN, opts = {}) {
        return new _PathPosix(name4, 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(cwd6 = process.cwd(), pathImpl, sep13, { nocase, childrenCacheSize = 16 * 1024, fs: fs142 = defaultFS } = {}) {
        this.#fs = fsFromOption(fs142);
        if (cwd6 instanceof URL || cwd6.startsWith("file://")) {
          cwd6 = fileURLToPath4(cwd6);
        }
        const cwdPath = pathImpl.resolve(cwd6);
        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(sep13);
        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(path150 = this.cwd) {
        if (typeof path150 === "string") {
          path150 = this.cwd.resolve(path150);
        }
        return path150.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 i4 = paths.length - 1; i4 >= 0; i4--) {
          const p2 = paths[i4];
          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 i4 = paths.length - 1; i4 >= 0; i4--) {
          const p2 = paths[i4];
          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: filter5, walkFilter } = opts;
        const results = [];
        if (!filter5 || filter5(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 (!filter5 || filter5(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 start2 = entry;
        return new Promise((res, rej) => {
          walk(start2, (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: filter5, walkFilter } = opts;
        const results = [];
        if (!filter5 || filter5(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 (!filter5 || filter5(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: filter5, walkFilter } = opts;
        if (!filter5 || filter5(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 (!filter5 || filter5(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: filter5, walkFilter } = opts;
        const results = new Minipass({ objectMode: true });
        if (!filter5 || filter5(entry)) {
          results.write(withFileTypes ? entry : entry.fullpath());
        }
        const dirs = /* @__PURE__ */ new Set();
        const queue = [entry];
        let processing = 0;
        const process51 = /* @__PURE__ */ __name(() => {
          let paused = false;
          while (!paused) {
            const dir = queue.shift();
            if (!dir) {
              if (processing === 0)
                results.end();
              return;
            }
            processing++;
            dirs.add(dir);
            const onReaddir = /* @__PURE__ */ __name((er2, entries, didRealpaths = false) => {
              if (er2)
                return results.emit("error", er2);
              if (follow && !didRealpaths) {
                const promises9 = [];
                for (const e4 of entries) {
                  if (e4.isSymbolicLink()) {
                    promises9.push(e4.realpath().then((r5) => r5?.isUnknown() ? r5.lstat() : r5));
                  }
                }
                if (promises9.length) {
                  Promise.all(promises9).then(() => onReaddir(null, entries, true));
                  return;
                }
              }
              for (const e4 of entries) {
                if (e4 && (!filter5 || filter5(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", process51);
              } else if (!sync2) {
                process51();
              }
            }, "onReaddir");
            let sync2 = true;
            dir.readdirCB(onReaddir, true);
            sync2 = false;
          }
        }, "process");
        process51();
        return results;
      }
      streamSync(entry = this.cwd, opts = {}) {
        if (typeof entry === "string") {
          entry = this.cwd.resolve(entry);
        } else if (!(entry instanceof PathBase)) {
          opts = entry;
          entry = this.cwd;
        }
        const { withFileTypes = true, follow = false, filter: filter5, walkFilter } = opts;
        const results = new Minipass({ objectMode: true });
        const dirs = /* @__PURE__ */ new Set();
        if (!filter5 || filter5(entry)) {
          results.write(withFileTypes ? entry : entry.fullpath());
        }
        const queue = [entry];
        let processing = 0;
        const process51 = /* @__PURE__ */ __name(() => {
          let paused = false;
          while (!paused) {
            const dir = queue.shift();
            if (!dir) {
              if (processing === 0)
                results.end();
              return;
            }
            processing++;
            dirs.add(dir);
            const entries = dir.readdirSync();
            for (const e4 of entries) {
              if (!filter5 || filter5(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", process51);
        }, "process");
        process51();
        return results;
      }
      chdir(path150 = this.cwd) {
        const oldCwd = this.cwd;
        this.cwd = typeof path150 === "string" ? this.cwd.resolve(path150) : path150;
        this.cwd[setAsCwd](oldCwd);
      }
    };
    PathScurryWin32 = class extends PathScurryBase {
      static {
        __name(this, "PathScurryWin32");
      }
      /**
       * separator for generating path strings
       */
      sep = "\\";
      constructor(cwd6 = process.cwd(), opts = {}) {
        const { nocase = true } = opts;
        super(cwd6, 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(fs142) {
        return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs142 });
      }
      /**
       * 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(cwd6 = process.cwd(), opts = {}) {
        const { nocase = false } = opts;
        super(cwd6, posix, "/", { ...opts, nocase });
        this.nocase = nocase;
      }
      /**
       * @internal
       */
      parseRootPath(_dir) {
        return "/";
      }
      /**
       * @internal
       */
      newRoot(fs142) {
        return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs142 });
      }
      /**
       * 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(cwd6 = process.cwd(), opts = {}) {
        const { nocase = true } = opts;
        super(cwd6, { ...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_esm9();
    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, platform15) {
        if (!isPatternList(patternList)) {
          throw new TypeError("empty pattern list");
        }
        if (!isGlobList(globList)) {
          throw new TypeError("empty glob list");
        }
        if (globList.length !== patternList.length) {
          throw new TypeError("mismatched pattern list and glob list lengths");
        }
        this.length = patternList.length;
        if (index < 0 || index >= this.length) {
          throw new TypeError("index out of range");
        }
        this.#patternList = patternList;
        this.#globList = globList;
        this.#index = index;
        this.#platform = platform15;
        if (this.#index === 0) {
          if (this.isUNC()) {
            const [p0, p1, p2, p3, ...prest] = this.#patternList;
            const [g0, g1, g2, g3, ...grest] = this.#globList;
            if (prest[0] === "") {
              prest.shift();
              grest.shift();
            }
            const 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_esm9();
    init_pattern();
    defaultPlatform2 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
    Ignore = class {
      static {
        __name(this, "Ignore");
      }
      relative;
      relativeChildren;
      absolute;
      absoluteChildren;
      platform;
      mmopts;
      constructor(ignored, { nobrace, nocase, noext, noglobstar, platform: platform15 = defaultPlatform2 }) {
        this.relative = [];
        this.absolute = [];
        this.relativeChildren = [];
        this.absoluteChildren = [];
        this.platform = platform15;
        this.mmopts = {
          dot: true,
          nobrace,
          nocase,
          noext,
          noglobstar,
          optimizationLevel: 2,
          platform: platform15,
          nocomment: true,
          nonegate: true
        };
        for (const ign of ignored)
          this.add(ign);
      }
      add(ign) {
        const mm = new Minimatch(ign, this.mmopts);
        for (let i4 = 0; i4 < mm.set.length; i4++) {
          const parsed = mm.set[i4];
          const globParts = mm.globParts[i4];
          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 relative14 = p2.relative() || ".";
        const relatives = `${relative14}/`;
        for (const m3 of this.relative) {
          if (m3.match(relative14) || 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 relative14 = (p2.relative() || ".") + "/";
        for (const m3 of this.relativeChildren) {
          if (m3.match(relative14))
            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_esm9();
    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(([path150, n3]) => [
          path150,
          !!(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_esm11();
    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, path150, opts) {
        this.patterns = patterns;
        this.path = path150;
        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(path150) {
        return this.seen.has(path150) || !!this.#ignore?.ignored?.(path150);
      }
      #childrenIgnored(path150) {
        return !!this.#ignore?.childrenIgnored?.(path150);
      }
      // 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, path150, opts) {
        super(patterns, path150, 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, path150, opts) {
        super(patterns, path150, 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 fileURLToPath5 } from "node:url";
var defaultPlatform3, Glob;
var init_glob = __esm({
  "node_modules/glob/dist/esm/glob.js"() {
    init_esbuild_shims();
    init_esm9();
    init_esm12();
    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 = fileURLToPath5(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((set2, m3) => {
          set2[0].push(...m3.set);
          set2[1].push(...m3.globParts);
          return set2;
        }, [[], []]);
        this.patterns = matchSet.map((set2, i4) => {
          const g2 = globParts[i4];
          if (!g2)
            throw new Error("invalid pattern object");
          return new Pattern(set2, 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_esm9();
    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_esm13 = __esm({
  "node_modules/glob/dist/esm/index.js"() {
    init_esbuild_shims();
    init_esm9();
    init_glob();
    init_has_magic();
    init_esm9();
    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 fs45 from "node:fs/promises";
import os21 from "node:os";
import * as path43 from "node:path";
function needsUtf8Bom(filePath) {
  const ext2 = path43.extname(filePath).toLowerCase();
  if (!UTF8_BOM_EXTENSIONS.has(ext2)) {
    return false;
  }
  if (cachedIsNonUtf8Windows === void 0) {
    if (os21.platform() !== "win32") {
      cachedIsNonUtf8Windows = false;
    } else {
      const sysEnc = getSystemEncoding();
      cachedIsNonUtf8Windows = sysEnc !== "utf-8";
    }
  }
  return cachedIsNonUtf8Windows;
}
function resetUtf8BomCache() {
  cachedIsNonUtf8Windows = void 0;
}
function needsCrlfLineEndings(filePath) {
  if (os21.platform() !== "win32") {
    return false;
  }
  const ext2 = path43.extname(filePath).toLowerCase();
  return CRLF_EXTENSIONS.has(ext2);
}
function ensureCrlfLineEndings(content) {
  return content.split("\r\n").join("\n").split("\n").join("\r\n");
}
function detectLineEnding(content) {
  return content.includes("\r\n") ? "crlf" : "lf";
}
function getBOMBytesForEncoding(encoding) {
  const lower3 = encoding.toLowerCase().replace(/[^a-z0-9]/g, "");
  switch (lower3) {
    case "utf8":
      return Buffer.from([239, 187, 191]);
    case "utf16le":
    case "utf16":
      return Buffer.from([255, 254]);
    case "utf16be":
      return Buffer.from([254, 255]);
    case "utf32le":
    case "utf32":
      return Buffer.from([255, 254, 0, 0]);
    case "utf32be":
      return Buffer.from([0, 0, 254, 255]);
    default:
      return null;
  }
}
var FileEncoding, CRLF_EXTENSIONS, UTF8_BOM_EXTENSIONS, cachedIsNonUtf8Windows, StandardFileSystemService;
var init_fileSystemService = __esm({
  "packages/core/dist/src/services/fileSystemService.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm13();
    init_fileUtils();
    init_iconvHelper();
    init_systemEncoding();
    FileEncoding = {
      UTF8: "utf-8",
      UTF8_BOM: "utf-8-bom"
    };
    CRLF_EXTENSIONS = /* @__PURE__ */ new Set([".bat", ".cmd"]);
    UTF8_BOM_EXTENSIONS = /* @__PURE__ */ new Set([".ps1"]);
    __name(needsUtf8Bom, "needsUtf8Bom");
    __name(resetUtf8BomCache, "resetUtf8BomCache");
    __name(needsCrlfLineEndings, "needsCrlfLineEndings");
    __name(ensureCrlfLineEndings, "ensureCrlfLineEndings");
    __name(detectLineEnding, "detectLineEnding");
    __name(getBOMBytesForEncoding, "getBOMBytesForEncoding");
    StandardFileSystemService = class {
      static {
        __name(this, "StandardFileSystemService");
      }
      async readTextFile(params) {
        const { path: path150, limit: limit2, line } = params;
        const { content, bom, encoding, originalLineCount } = await readFileWithLineAndLimit({
          path: path150,
          limit: limit2 ?? Number.POSITIVE_INFINITY,
          line: line || 0
        });
        const lineEnding = detectLineEnding(content);
        return { content, _meta: { bom, encoding, originalLineCount, lineEnding } };
      }
      async writeTextFile(params) {
        const { path: filePath, _meta } = params;
        const lineEnding = _meta?.["lineEnding"];
        const shouldUseCrlf = needsCrlfLineEndings(filePath) || lineEnding === "crlf";
        const content = shouldUseCrlf ? ensureCrlfLineEndings(params.content) : params.content;
        const bom = _meta?.["bom"] ?? false;
        const encoding = _meta?.["encoding"];
        const isNonUtf8Encoding = encoding && !isUtf8CompatibleEncoding(encoding) && iconvEncodingExists(encoding);
        if (isNonUtf8Encoding) {
          const encoded = iconvEncode(content, encoding);
          if (bom) {
            const bomBytes = getBOMBytesForEncoding(encoding);
            await fs45.writeFile(filePath, bomBytes ? Buffer.concat([bomBytes, encoded]) : encoded);
          } else {
            await fs45.writeFile(filePath, encoded);
          }
        } else 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 fs45.writeFile(filePath, Buffer.concat([bomBuffer, contentBuffer]));
        } else {
          await fs45.writeFile(filePath, content, "utf-8");
        }
        return { _meta };
      }
      findFiles(fileName, searchPaths) {
        return searchPaths.flatMap((searchPath) => {
          const pattern = path43.posix.join(searchPath, "**", fileName);
          return globSync(pattern, {
            nodir: true,
            absolute: true
          });
        });
      }
    };
  }
});

// packages/core/dist/src/services/gitService.js
import * as fs46 from "node:fs/promises";
import * as path44 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_esm8();
    init_errors();
    init_gitInit();
    GitService = class {
      static {
        __name(this, "GitService");
      }
      projectRoot;
      storage;
      constructor(projectRoot, storage) {
        this.projectRoot = path44.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 (error40) {
          throw new Error(`Failed to initialize checkpointing: ${error40 instanceof Error ? error40.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 = path44.join(repoDir, ".gitconfig");
        await fs46.mkdir(repoDir, { recursive: true });
        const gitConfigContent = "[user]\n  name = Qwen Code\n  email = qwen-code@qwen.ai\n[commit]\n  gpgsign = false\n";
        await fs46.writeFile(gitConfigPath, gitConfigContent);
        const repo = simpleGit(repoDir).env({
          // Prevent git from using the user's global git config.
          HOME: repoDir,
          XDG_CONFIG_HOME: repoDir
        });
        let isRepoDefined = false;
        try {
          isRepoDefined = await repo.checkIsRepo(CheckRepoActions.IS_REPO_ROOT);
        } catch {
          isRepoDefined = false;
        }
        if (!isRepoDefined) {
          await initRepositoryWithMainBranch(repo);
          await repo.commit("Initial commit", { "--allow-empty": null });
        }
        const userGitIgnorePath = path44.join(this.projectRoot, ".gitignore");
        const shadowGitIgnorePath = path44.join(repoDir, ".gitignore");
        let userGitIgnoreContent = "";
        try {
          userGitIgnoreContent = await fs46.readFile(userGitIgnorePath, "utf-8");
        } catch (error40) {
          if (isNodeError(error40) && error40.code !== "ENOENT") {
            throw error40;
          }
        }
        await fs46.writeFile(shadowGitIgnorePath, userGitIgnoreContent);
      }
      get shadowGitRepository() {
        const repoDir = this.getHistoryDir();
        return simpleGit(this.projectRoot).env({
          GIT_DIR: path44.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 (error40) {
          throw new Error(`Failed to create checkpoint snapshot: ${error40 instanceof Error ? error40.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/dist/src/utils/cronParser.js
function parseField(field, min, max) {
  const values = /* @__PURE__ */ new Set();
  for (const part of field.split(",")) {
    const trimmed2 = part.trim();
    if (!trimmed2) {
      throw new Error(`Empty field segment in "${field}"`);
    }
    const stepParts = trimmed2.split("/");
    if (stepParts.length > 2) {
      throw new Error(`Invalid step expression: "${trimmed2}"`);
    }
    let rangeStart;
    let rangeEnd;
    const base = stepParts[0];
    if (base === "*") {
      rangeStart = min;
      rangeEnd = max;
    } else if (base.includes("-")) {
      const [startStr, endStr] = base.split("-");
      rangeStart = parseInt(startStr, 10);
      rangeEnd = parseInt(endStr, 10);
      if (isNaN(rangeStart) || isNaN(rangeEnd)) {
        throw new Error(`Invalid range: "${base}"`);
      }
      if (rangeStart < min || rangeEnd > max || rangeStart > rangeEnd) {
        throw new Error(`Range ${base} out of bounds [${min}-${max}]`);
      }
    } else {
      const val = parseInt(base, 10);
      if (isNaN(val) || val < min || val > max) {
        throw new Error(`Value "${base}" out of bounds [${min}-${max}]`);
      }
      rangeStart = val;
      rangeEnd = val;
    }
    const step = stepParts.length === 2 ? parseInt(stepParts[1], 10) : 1;
    if (isNaN(step) || step <= 0) {
      throw new Error(`Invalid step: "${stepParts[1]}"`);
    }
    for (let i4 = rangeStart; i4 <= rangeEnd; i4 += step) {
      values.add(i4);
    }
  }
  return values;
}
function parseCron(cronExpr) {
  const parts2 = cronExpr.trim().split(/\s+/);
  if (parts2.length !== 5) {
    throw new Error(`Cron expression must have exactly 5 fields, got ${parts2.length}: "${cronExpr}"`);
  }
  const dayOfWeek = parseField(parts2[4], FIELD_RANGES[4][0], FIELD_RANGES[4][1]);
  if (dayOfWeek.has(7)) {
    dayOfWeek.delete(7);
    dayOfWeek.add(0);
  }
  return {
    minute: parseField(parts2[0], FIELD_RANGES[0][0], FIELD_RANGES[0][1]),
    hour: parseField(parts2[1], FIELD_RANGES[1][0], FIELD_RANGES[1][1]),
    dayOfMonth: parseField(parts2[2], FIELD_RANGES[2][0], FIELD_RANGES[2][1]),
    month: parseField(parts2[3], FIELD_RANGES[3][0], FIELD_RANGES[3][1]),
    dayOfWeek,
    domIsWild: parts2[2].trim() === "*",
    dowIsWild: parts2[4].trim() === "*"
  };
}
function matches(cronExpr, date5) {
  const fields = parseCron(cronExpr);
  if (!fields.minute.has(date5.getMinutes()) || !fields.hour.has(date5.getHours()) || !fields.month.has(date5.getMonth() + 1)) {
    return false;
  }
  const domMatch = fields.dayOfMonth.has(date5.getDate());
  const dowMatch = fields.dayOfWeek.has(date5.getDay());
  if (!fields.domIsWild && !fields.dowIsWild) {
    return domMatch || dowMatch;
  }
  return domMatch && dowMatch;
}
function nextFireTime(cronExpr, after) {
  const fields = parseCron(cronExpr);
  const candidate = new Date(after.getTime());
  candidate.setSeconds(0, 0);
  candidate.setMinutes(candidate.getMinutes() + 1);
  const maxIterations = 4 * 366 * 24 * 60;
  for (let i4 = 0; i4 < maxIterations; i4++) {
    const minuteOk = fields.minute.has(candidate.getMinutes());
    const hourOk = fields.hour.has(candidate.getHours());
    const monthOk = fields.month.has(candidate.getMonth() + 1);
    const domOk = fields.dayOfMonth.has(candidate.getDate());
    const dowOk = fields.dayOfWeek.has(candidate.getDay());
    const dayOk = !fields.domIsWild && !fields.dowIsWild ? domOk || dowOk : domOk && dowOk;
    if (minuteOk && hourOk && monthOk && dayOk) {
      return candidate;
    }
    candidate.setMinutes(candidate.getMinutes() + 1);
  }
  throw new Error(`No matching fire time found within 4 years for: "${cronExpr}"`);
}
var FIELD_RANGES;
var init_cronParser = __esm({
  "packages/core/dist/src/utils/cronParser.js"() {
    "use strict";
    init_esbuild_shims();
    FIELD_RANGES = [
      [0, 59],
      // minute
      [0, 23],
      // hour
      [1, 31],
      // day of month
      [1, 12],
      // month
      [0, 7]
      // day of week (0 and 7 both mean Sunday)
    ];
    __name(parseField, "parseField");
    __name(parseCron, "parseCron");
    __name(matches, "matches");
    __name(nextFireTime, "nextFireTime");
  }
});

// packages/core/dist/src/utils/cronDisplay.js
function humanReadableCron(cronExpr) {
  const parts2 = cronExpr.trim().split(/\s+/);
  if (parts2.length !== 5)
    return cronExpr;
  const [min, hour, dom, mon, dow] = parts2;
  if (min.startsWith("*/") && hour === "*" && dom === "*" && mon === "*" && dow === "*") {
    const n3 = parseInt(min.slice(2), 10);
    if (!isNaN(n3)) {
      return n3 === 1 ? "Every minute" : `Every ${n3} minutes`;
    }
  }
  if (/^\d+$/.test(min) && hour.startsWith("*/") && dom === "*" && mon === "*" && dow === "*") {
    const n3 = parseInt(hour.slice(2), 10);
    if (!isNaN(n3)) {
      return n3 === 1 ? "Every hour" : `Every ${n3} hours`;
    }
  }
  if (/^\d+$/.test(min) && /^\d+$/.test(hour) && dom.startsWith("*/") && mon === "*" && dow === "*") {
    const n3 = parseInt(dom.slice(2), 10);
    if (!isNaN(n3)) {
      return n3 === 1 ? "Every day" : `Every ${n3} days`;
    }
  }
  return cronExpr;
}
var init_cronDisplay = __esm({
  "packages/core/dist/src/utils/cronDisplay.js"() {
    "use strict";
    init_esbuild_shims();
    __name(humanReadableCron, "humanReadableCron");
  }
});

// packages/core/dist/src/services/cronScheduler.js
function hashId(id) {
  let hash = 0;
  for (let i4 = 0; i4 < id.length; i4++) {
    hash = hash * 31 + id.charCodeAt(i4) | 0;
  }
  return Math.abs(hash);
}
function computeJitter(id, cronExpr, recurring) {
  const hash = hashId(id);
  if (recurring) {
    const now = /* @__PURE__ */ new Date();
    try {
      const first2 = nextFireTime(cronExpr, now);
      const second = nextFireTime(cronExpr, first2);
      const periodMs = second.getTime() - first2.getTime();
      const tenPercent = periodMs * 0.1;
      const maxJitter = Math.min(tenPercent, MAX_RECURRING_JITTER_MS);
      return hash % Math.max(1, Math.floor(maxJitter));
    } catch {
      return 0;
    }
  }
  try {
    const fields = cronExpr.trim().split(/\s+/);
    const minuteField = fields[0] ?? "";
    const minuteVal = parseInt(minuteField, 10);
    if (!isNaN(minuteVal) && (minuteVal === 0 || minuteVal === 30)) {
      return -(hash % MAX_ONESHOT_JITTER_MS);
    }
  } catch {
  }
  return 0;
}
function generateId() {
  const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  let id = "";
  for (let i4 = 0; i4 < 8; i4++) {
    id += chars[Math.floor(Math.random() * chars.length)];
  }
  return id;
}
var MAX_JOBS, THREE_DAYS_MS, MAX_RECURRING_JITTER_MS, MAX_ONESHOT_JITTER_MS, CronScheduler;
var init_cronScheduler = __esm({
  "packages/core/dist/src/services/cronScheduler.js"() {
    "use strict";
    init_esbuild_shims();
    init_cronParser();
    init_cronDisplay();
    MAX_JOBS = 50;
    THREE_DAYS_MS = 3 * 24 * 60 * 60 * 1e3;
    MAX_RECURRING_JITTER_MS = 15 * 60 * 1e3;
    MAX_ONESHOT_JITTER_MS = 90 * 1e3;
    __name(hashId, "hashId");
    __name(computeJitter, "computeJitter");
    __name(generateId, "generateId");
    CronScheduler = class {
      static {
        __name(this, "CronScheduler");
      }
      jobs = /* @__PURE__ */ new Map();
      timer = null;
      onFire = null;
      /**
       * Creates a new cron job. Returns the created job.
       * Throws if the max job limit is reached.
       */
      create(cronExpr, prompt, recurring) {
        if (this.jobs.size >= MAX_JOBS) {
          throw new Error(`Maximum number of cron jobs (${MAX_JOBS}) reached. Delete some jobs first.`);
        }
        const id = generateId();
        const now = Date.now();
        const jitterMs = computeJitter(id, cronExpr, recurring);
        const job = {
          id,
          cronExpr,
          prompt,
          recurring,
          createdAt: now,
          expiresAt: recurring ? now + THREE_DAYS_MS : Infinity,
          jitterMs
        };
        this.jobs.set(id, job);
        return job;
      }
      /**
       * Deletes a job by ID. Returns true if the job existed.
       */
      delete(id) {
        return this.jobs.delete(id);
      }
      /**
       * Returns all active jobs.
       */
      list() {
        return [...this.jobs.values()];
      }
      /**
       * Returns the number of active jobs.
       */
      get size() {
        return this.jobs.size;
      }
      /**
       * Starts the scheduler tick. Calls `onFire` when a job is due.
       * Only fires when called — does not auto-fire missed intervals.
       */
      start(onFire) {
        this.onFire = onFire;
        if (this.timer)
          return;
        this.timer = setInterval(() => {
          this.tick();
        }, 1e3);
      }
      /**
       * Stops the scheduler. Does not clear jobs — they remain queryable.
       */
      stop() {
        if (this.timer) {
          clearInterval(this.timer);
          this.timer = null;
        }
        this.onFire = null;
      }
      /**
       * Returns true if the scheduler is running.
       */
      get running() {
        return this.timer !== null;
      }
      /**
       * Manual tick — checks all jobs against the current time and fires those
       * that are due. Exported for testing.
       */
      tick(now) {
        const currentDate = now ?? /* @__PURE__ */ new Date();
        const currentMs = currentDate.getTime();
        for (const job of this.jobs.values()) {
          if (currentMs >= job.expiresAt) {
            this.jobs.delete(job.id);
            continue;
          }
          const absJitter = Math.abs(job.jitterMs);
          const windowMinutes = Math.ceil(absJitter / 6e4);
          const nowMinuteStart = new Date(currentDate);
          nowMinuteStart.setSeconds(0, 0);
          const nowMinuteMs = nowMinuteStart.getTime();
          let matchedMinuteMs = null;
          for (let offset = -windowMinutes; offset <= windowMinutes; offset++) {
            const candidateMs = nowMinuteMs + offset * 6e4;
            const candidateDate = new Date(candidateMs);
            if (!matches(job.cronExpr, candidateDate))
              continue;
            const fireTimeMs = candidateMs + job.jitterMs;
            if (currentMs >= fireTimeMs) {
              if (matchedMinuteMs === null || candidateMs > matchedMinuteMs) {
                matchedMinuteMs = candidateMs;
              }
            }
          }
          if (matchedMinuteMs === null) {
            continue;
          }
          if (job.lastFiredAt !== void 0 && job.lastFiredAt === matchedMinuteMs) {
            continue;
          }
          job.lastFiredAt = matchedMinuteMs;
          if (!job.recurring) {
            this.jobs.delete(job.id);
          }
          if (this.onFire) {
            this.onFire(job);
          }
        }
      }
      /**
       * Returns a human-readable summary of active jobs for display on session
       * exit. Returns null if there are no active jobs.
       */
      getExitSummary() {
        if (this.jobs.size === 0)
          return null;
        const count = this.jobs.size;
        const lines = [
          `Session ending. ${count} active loop${count === 1 ? "" : "s"} cancelled:`
        ];
        for (const job of this.jobs.values()) {
          const schedule = humanReadableCron(job.cronExpr);
          const prompt = job.prompt.length > 60 ? job.prompt.slice(0, 57) + "..." : job.prompt;
          lines.push(`  - [${job.id}] ${schedule}: ${prompt}`);
        }
        return lines.join("\n");
      }
      /**
       * Clears all jobs and stops the scheduler.
       */
      destroy() {
        this.stop();
        this.jobs.clear();
      }
    };
  }
});

// packages/core/dist/src/utils/ripgrepUtils.js
import path45 from "node:path";
import { fileURLToPath as fileURLToPath6 } from "node:url";
import { execFile as execFile9 } from "node:child_process";
function wslTimeout() {
  return process.platform === "linux" && process.env["WSL_INTEROP"] ? RIPGREP_WSL_TIMEOUT_MS : RIPGREP_RUN_TIMEOUT_MS;
}
function getPlatformString(platform15) {
  switch (platform15) {
    case "darwin":
    case "linux":
    case "win32":
      return platform15;
    default:
      return void 0;
  }
}
function getArchitectureString(arch3) {
  switch (arch3) {
    case "x64":
    case "arm64":
      return arch3;
    default:
      return void 0;
  }
}
function getBuiltinRipgrep() {
  const platform15 = getPlatformString(process.platform);
  const arch3 = getArchitectureString(process.arch);
  if (!platform15 || !arch3) {
    return null;
  }
  const binaryName = platform15 === "win32" ? "rg.exe" : "rg";
  const inSrcUtils = __filename2.includes(path45.join("src", "utils"));
  const levelsUp = !inSrcUtils ? 0 : __filename2.endsWith(".ts") ? 2 : 3;
  return path45.join(__dirname3, ...Array(levelsUp).fill(".."), "vendor", "ripgrep", `${arch3}-${platform15}`, 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: error40 } = isCommandAvailable(RIPGREP_COMMAND);
  if (available) {
    cachedSelection = { mode: "system", command: RIPGREP_COMMAND };
    return cachedSelection;
  }
  if (error40) {
    throw error40;
  }
  return null;
}
async function ensureRipgrepHealthy(selection) {
  if (cachedHealth && cachedHealth.selection.command === selection.command && cachedHealth.working)
    return;
  try {
    const { stdout: stdout2, code: code2 } = await execCommand2(selection.command, ["--version"], {
      timeout: RIPGREP_TEST_TIMEOUT_MS
    });
    const working = code2 === 0 && stdout2.startsWith("ripgrep");
    cachedHealth = { working, lastTested: Date.now(), selection };
  } catch (error40) {
    cachedHealth = { working: false, lastTested: Date.now(), selection };
    throw error40;
  }
}
async function ensureMacBinarySigned(selection) {
  if (process.platform !== "darwin")
    return;
  if (macSigningAttempted)
    return;
  macSigningAttempted = true;
  if (selection.mode !== "builtin")
    return;
  const binaryPath = selection.command;
  const inspect3 = await execCommand2("codesign", ["-vv", "-d", binaryPath], {
    preserveOutputOnError: false
  });
  const alreadySigned = inspect3.stdout?.split("\n").some((line) => line.includes("linker-signed")) ?? false;
  if (!alreadySigned)
    return;
  await execCommand2("codesign", [
    "--sign",
    "-",
    "--force",
    "--preserve-metadata=entitlements,requirements,flags,runtime",
    binaryPath
  ]);
  await execCommand2("xattr", ["-d", "com.apple.quarantine", binaryPath]);
}
async function canUseRipgrep(useBuiltin = true) {
  const selection = await resolveRipgrep(useBuiltin);
  if (!selection) {
    return false;
  }
  await ensureRipgrepHealthy(selection);
  return true;
}
async function runRipgrep(args2, signal) {
  const selection = await resolveRipgrep();
  if (!selection) {
    throw new Error("ripgrep not found.");
  }
  await ensureRipgrepHealthy(selection);
  return new Promise((resolve42) => {
    const child = execFile9(selection.command, args2, {
      maxBuffer: RIPGREP_BUFFER_LIMIT,
      timeout: wslTimeout(),
      signal
    }, (error40, stdout2 = "", stderr = "") => {
      if (!error40) {
        resolve42({
          stdout: stdout2,
          truncated: false
        });
        return;
      }
      const errorCode = error40.code;
      if (errorCode === 1) {
        resolve42({ stdout: "", truncated: false });
        return;
      }
      const wasKilled = error40.signal === "SIGTERM" || error40.name === "AbortError";
      const overflow = errorCode === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
      const syntaxError2 = errorCode === 2;
      const truncated = wasKilled || overflow;
      let partialOutput = stdout2;
      if (truncated && partialOutput.length > 0) {
        const lines = partialOutput.split("\n");
        if (lines.length > 0) {
          lines.pop();
          partialOutput = lines.join("\n");
        }
      }
      if (!syntaxError2 && truncated) {
        debugLogger48.warn(`ripgrep exited abnormally (signal=${error40.signal} code=${error40.code}) with stderr:
${stderr.trim() || "(empty)"}`);
      }
      resolve42({
        stdout: partialOutput,
        truncated,
        error: error40 instanceof Error ? error40 : void 0
      });
    });
    child.on("error", (err2) => resolve42({ stdout: "", truncated: false, error: err2 }));
  });
}
var debugLogger48, RIPGREP_COMMAND, RIPGREP_BUFFER_LIMIT, RIPGREP_TEST_TIMEOUT_MS, RIPGREP_RUN_TIMEOUT_MS, RIPGREP_WSL_TIMEOUT_MS, cachedSelection, cachedHealth, macSigningAttempted, __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();
    debugLogger48 = 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;
    macSigningAttempted = false;
    __name(wslTimeout, "wslTimeout");
    __filename2 = fileURLToPath6(import.meta.url);
    __dirname3 = path45.dirname(__filename2);
    __name(getPlatformString, "getPlatformString");
    __name(getArchitectureString, "getArchitectureString");
    __name(getBuiltinRipgrep, "getBuiltinRipgrep");
    __name(resolveRipgrep, "resolveRipgrep");
    __name(ensureRipgrepHealthy, "ensureRipgrepHealthy");
    __name(ensureMacBinarySigned, "ensureMacBinarySigned");
    __name(canUseRipgrep, "canUseRipgrep");
    __name(runRipgrep, "runRipgrep");
  }
});

// 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(err2) {
  return err2 instanceof Error ? "errors" in err2 && Array.isArray(err2.errors) ? err2.errors.map(flattenError2).join(", ") : "cause" in err2 && err2.cause instanceof Error ? `${err2}: ${flattenError2(err2.cause)}` : err2.message : `${err2}`;
}
function inspectableError(err2) {
  return {
    type: err2.type,
    message: err2.message,
    code: err2.code,
    defaultPrevented: err2.defaultPrevented,
    cancelable: err2.cancelable,
    timeStamp: err2.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(url3, 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: body2, 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 body2 != "object" || !body2 || !("getReader" in body2)) {
            __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
            return;
          }
          const decoder = new TextDecoder(), reader = body2.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, (err2) => {
          __privateSet(this, _controller, void 0), !(err2.name === "AbortError" || err2.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError2(err2));
        }), __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 (url3 instanceof URL)
            __privateSet(this, _url2, url3);
          else if (typeof url3 == "string")
            __privateSet(this, _url2, new URL(url3, 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 init2 = {
        // [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 && (init2.credentials = this.withCredentials ? "include" : "same-origin"), init2;
    }, "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_types11();
    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(url3, opts) {
        this._url = url3;
        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 (error40) {
          this.onerror?.(error40);
          throw error40;
        }
        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((resolve42, reject) => {
          this._eventSource = new EventSource(this._url.href, {
            ...this._eventSourceInit,
            fetch: /* @__PURE__ */ __name(async (url3, init2) => {
              const headers = await this._commonHeaders();
              headers.set("Accept", "text/event-stream");
              const response = await fetchImpl(url3, {
                ...init2,
                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(resolve42, reject);
              return;
            }
            const error40 = new SseError(event.code, event.message, event);
            reject(error40);
            this.onerror?.(error40);
          };
          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 (error40) {
              reject(error40);
              this.onerror?.(error40);
              void this.close();
              return;
            }
            resolve42();
          });
          this._eventSource.onmessage = (event) => {
            const messageEvent = event;
            let message;
            try {
              message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
            } catch (error40) {
              this.onerror?.(error40);
              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 init2 = {
            ...this._requestInit,
            method: "POST",
            headers,
            body: JSON.stringify(message),
            signal: this._abortController?.signal
          };
          const response = await (this._fetch ?? fetch)(this._endpoint, init2);
          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 (error40) {
          this.onerror?.(error40);
          throw error40;
        }
      }
      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, debugLogger49, 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();
    debugLogger49 = 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 url3 = this.config?.url || this.config?.httpUrl;
        if (!url3) {
          throw new Error("URL must be provided in the config for Google Credentials provider");
        }
        const hostname4 = new URL(url3).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) {
          debugLogger49.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, debugLogger50, 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();
    debugLogger50 = 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 url3 = createIamApiUrl(this.targetServiceAccount);
        let idToken;
        try {
          const res = await client.request({
            url: url3,
            method: "POST",
            data: {
              audience: this.targetAudience,
              includeEmail: true
            }
          });
          idToken = res.data.token;
          if (!idToken || idToken.length === 0) {
            debugLogger50.error("Failed to get ID token from Google");
            return void 0;
          }
        } catch (e4) {
          debugLogger50.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) {
          debugLogger50.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 debugLogger51, 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();
    debugLogger51 = 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;
        debugLogger51.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.`);
        }
        debugLogger51.debug(`Sending message to '${this.serverName}': ${JSON.stringify(message)}`);
        try {
          const response = await this.sendMcpMessage(this.serverName, message);
          debugLogger51.debug(`Received response from '${this.serverName}': ${JSON.stringify(response)}`);
          if (this.onmessage) {
            this.onmessage(response);
          }
        } catch (error40) {
          debugLogger51.error(`Error sending to '${this.serverName}': ${error40}`);
          if (this.onerror) {
            this.onerror(error40 instanceof Error ? error40 : new Error(String(error40)));
          }
          throw error40;
        }
      }
      /**
       * Close the transport
       */
      async close() {
        if (!this.started) {
          return;
        }
        this.started = false;
        debugLogger51.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 execFile10 } from "node:child_process";
import { promisify as promisify8 } from "node:util";
import { platform as platform4 } from "node:os";
import { URL as URL3 } from "node:url";
function validateUrl(url3) {
  let parsedUrl;
  try {
    parsedUrl = new URL3(url3);
  } catch (_error) {
    throw new Error(`Invalid URL: ${url3}`);
  }
  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(url3)) {
    throw new Error("URL contains invalid characters");
  }
}
async function openBrowserSecurely(url3) {
  validateUrl(url3);
  const platformName = platform4();
  let command2;
  let args2;
  switch (platformName) {
    case "darwin":
      command2 = "open";
      args2 = [url3];
      break;
    case "win32":
      command2 = "powershell.exe";
      args2 = [
        "-NoProfile",
        "-NonInteractive",
        "-WindowStyle",
        "Hidden",
        "-Command",
        `Start-Process '${url3.replace(/'/g, "''")}'`
      ];
      break;
    case "linux":
    case "freebsd":
    case "openbsd":
      command2 = "xdg-open";
      args2 = [url3];
      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, args2, options2);
  } catch (_error) {
    if ((platformName === "linux" || platformName === "freebsd" || platformName === "openbsd") && command2 === "xdg-open") {
      const fallbackCommands = [
        "gnome-open",
        "kde-open",
        "firefox",
        "chromium",
        "google-chrome",
        "microsoft-edge"
      ];
      for (const fallbackCommand of fallbackCommands) {
        try {
          await execFileAsync6(fallbackCommand, [url3], options2);
          return;
        } catch {
          continue;
        }
      }
    }
    console.warn(`Failed to open browser automatically. Please open this URL manually: ${url3}`);
    return;
  }
}
var execFileAsync6;
var init_secure_browser_launcher = __esm({
  "packages/core/dist/src/utils/secure-browser-launcher.js"() {
    "use strict";
    init_esbuild_shims();
    execFileAsync6 = promisify8(execFile10);
    __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 fs47 } from "node:fs";
import * as path46 from "node:path";
import * as os22 from "node:os";
import * as crypto10 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 = path46.join(os22.homedir(), ".qwen");
        this.tokenFilePath = path46.join(configDir, "mcp-oauth-tokens-v2.json");
        this.encryptionKey = this.deriveEncryptionKey();
      }
      deriveEncryptionKey() {
        const salt = `${os22.hostname()}-${os22.userInfo().username}-qwen-code`;
        return crypto10.scryptSync("qwen-code-oauth", salt, 32);
      }
      encrypt(text) {
        const iv = crypto10.randomBytes(16);
        const cipher = crypto10.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 parts2 = encryptedData.split(":");
        if (parts2.length !== 3) {
          throw new Error("Invalid encrypted data format");
        }
        const iv = Buffer.from(parts2[0], "hex");
        const authTag = Buffer.from(parts2[1], "hex");
        const encrypted = parts2[2];
        const decipher = crypto10.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 = path46.dirname(this.tokenFilePath);
        await fs47.mkdir(dir, { recursive: true, mode: 448 });
      }
      async loadTokens() {
        try {
          const data = await fs47.readFile(this.tokenFilePath, "utf-8");
          const decrypted = this.decrypt(data);
          const tokens = JSON.parse(decrypted);
          return new Map(Object.entries(tokens));
        } catch (error40) {
          const err2 = error40;
          if (err2.code === "ENOENT") {
            throw new Error("Token file does not exist");
          }
          if (err2.message?.includes("Invalid encrypted data format") || err2.message?.includes("Unsupported state or unable to authenticate data")) {
            throw new Error("Token file corrupted");
          }
          throw error40;
        }
      }
      async saveTokens(tokens) {
        await this.ensureDirectoryExists();
        const data = Object.fromEntries(tokens);
        const json3 = JSON.stringify(data, null, 2);
        const encrypted = this.encrypt(json3);
        await fs47.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 fs47.unlink(this.tokenFilePath);
          } catch (error40) {
            const err2 = error40;
            if (err2.code !== "ENOENT") {
              throw error40;
            }
          }
        } 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 fs47.unlink(this.tokenFilePath);
        } catch (error40) {
          const err2 = error40;
          if (err2.code !== "ENOENT") {
            throw error40;
          }
        }
      }
    };
  }
});

// packages/core/dist/src/mcp/token-storage/types.js
var TokenStorageType;
var init_types12 = __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 crypto11 from "node:crypto";
var debugLogger52, 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();
    debugLogger52 = 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 (error40) {
          debugLogger52.error(`Failed to load keytar module: ${error40}`);
        }
        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 (error40) {
          if (error40 instanceof SyntaxError) {
            throw new Error(`Failed to parse stored credentials for ${serverName}`);
          }
          throw error40;
        }
      }
      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 (error40) {
          debugLogger52.error(`Failed to list servers from keychain: ${error40}`);
          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 (error40) {
              debugLogger52.error(`Failed to parse credentials for ${cred.account}: ${error40}`);
            }
          }
        } catch (error40) {
          debugLogger52.error(`Failed to get all credentials from keychain: ${error40}`);
        }
        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((error40) => {
          throw new Error(`Failed to list servers for clearing: ${error40.message}`);
        }) : [];
        const errors = [];
        for (const server of servers) {
          try {
            await this.deleteCredentials(server);
          } catch (error40) {
            errors.push(error40);
          }
        }
        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}${crypto11.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 success2 = deleted && retrieved === testPassword;
          this.keychainAvailable = success2;
          return success2;
        } 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 (error40) {
          debugLogger52.error(`Failed to list secrets from keychain: ${error40}`);
          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_types12();
    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_types12();
    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 fs48 } from "node:fs";
import * as path47 from "node:path";
var debugLogger53, 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();
    debugLogger53 = 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 = path47.dirname(this.getTokenFilePath());
        await fs48.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 fs48.readFile(tokenFile, "utf-8");
          const tokens = JSON.parse(data);
          for (const credential of tokens) {
            tokenMap.set(credential.serverName, credential);
          }
        } catch (error40) {
          if (error40.code !== "ENOENT") {
            debugLogger53.error(`Failed to load MCP OAuth tokens: ${getErrorMessage(error40)}`);
          }
        }
        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 fs48.writeFile(tokenFile, JSON.stringify(tokenArray, null, 2), { mode: 384 });
        } catch (error40) {
          debugLogger53.error(`Failed to save MCP OAuth token: ${getErrorMessage(error40)}`);
          throw error40;
        }
      }
      /**
       * 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 fs48.unlink(tokenFile);
            } else {
              await fs48.writeFile(tokenFile, JSON.stringify(tokenArray, null, 2), {
                mode: 384
              });
            }
          } catch (error40) {
            debugLogger53.error(`Failed to remove MCP OAuth token: ${getErrorMessage(error40)}`);
          }
        }
      }
      /**
       * 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 fs48.unlink(tokenFile);
        } catch (error40) {
          if (error40.code !== "ENOENT") {
            debugLogger53.error(`Failed to clear MCP OAuth tokens: ${getErrorMessage(error40)}`);
          }
        }
      }
    };
  }
});

// packages/core/dist/src/mcp/oauth-utils.js
var debugLogger54, OAuthUtils;
var init_oauth_utils = __esm({
  "packages/core/dist/src/mcp/oauth-utils.js"() {
    "use strict";
    init_esbuild_shims();
    init_errors();
    init_debugLogger();
    debugLogger54 = 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 (error40) {
          debugLogger54.debug(`Failed to fetch protected resource metadata from ${resourceMetadataUrl}: ${getErrorMessage(error40)}`);
          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 (error40) {
          debugLogger54.debug(`Failed to fetch authorization server metadata from ${authServerMetadataUrl}: ${getErrorMessage(error40)}`);
          return null;
        }
      }
      /**
       * Convert authorization server metadata to OAuth configuration.
       *
       * @param metadata The authorization server metadata
       * @returns The OAuth configuration
       */
      static metadataToOAuthConfig(metadata2) {
        return {
          authorizationUrl: metadata2.authorization_endpoint,
          tokenUrl: metadata2.token_endpoint,
          scopes: metadata2.scopes_supported || [],
          registrationUrl: metadata2.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;
          }
        }
        debugLogger54.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 url3 = new URL(serverUrl);
            if (url3.pathname && url3.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 (resourceMetadata.scopes_supported?.length) {
                config2.scopes = resourceMetadata.scopes_supported;
              }
              if (authServerMetadata2.registration_endpoint) {
                debugLogger54.debug(`Dynamic client registration is supported at: ${authServerMetadata2.registration_endpoint}`);
              }
              return config2;
            }
          }
          debugLogger54.debug(`Trying OAuth discovery fallback at ${serverUrl}`);
          const authServerMetadata = await this.discoverAuthorizationServerMetadata(serverUrl);
          if (authServerMetadata) {
            const config2 = this.metadataToOAuthConfig(authServerMetadata);
            if (authServerMetadata.registration_endpoint) {
              debugLogger54.debug(`Dynamic client registration is supported at: ${authServerMetadata.registration_endpoint}`);
            }
            return config2;
          }
          return null;
        } catch (error40) {
          debugLogger54.debug(`Failed to discover OAuth configuration: ${getErrorMessage(error40)}`);
          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) {
          const config2 = this.metadataToOAuthConfig(authServerMetadata);
          if (resourceMetadata.scopes_supported?.length) {
            config2.scopes = resourceMetadata.scopes_supported;
          }
          return config2;
        }
        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(url3) {
        return url3.includes("/sse") || !url3.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 url3 = new URL(endpointUrl);
        const path150 = url3.pathname === "/" ? "" : url3.pathname;
        let canonical = `${url3.protocol}//${url3.host}${path150}`;
        if (canonical.endsWith("/") && path150 !== "") {
          canonical = canonical.slice(0, -1);
        }
        return canonical;
      }
    };
  }
});

// packages/core/dist/src/mcp/oauth-provider.js
import * as http4 from "node:http";
import * as crypto12 from "node:crypto";
import { URL as URL4 } from "node:url";
var OAUTH_DISPLAY_MESSAGE_EVENT, OAUTH_AUTH_URL_EVENT, debugLogger55, activeCallbackServer, activeCallbackTimeout, 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";
    OAUTH_AUTH_URL_EVENT = "oauth-auth-url";
    debugLogger55 = createDebugLogger("MCP_OAUTH");
    activeCallbackServer = null;
    activeCallbackTimeout = null;
    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 = crypto12.randomBytes(32).toString("base64url");
        const codeChallenge = crypto12.createHash("sha256").update(codeVerifier).digest("base64url");
        const state = crypto12.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) {
        if (activeCallbackServer) {
          try {
            activeCallbackServer.close();
          } catch {
          }
          activeCallbackServer = null;
        }
        if (activeCallbackTimeout) {
          clearTimeout(activeCallbackTimeout);
          activeCallbackTimeout = null;
        }
        return new Promise((resolve42, reject) => {
          const server = http4.createServer(async (req, res) => {
            try {
              const url3 = new URL4(req.url, `http://localhost:${OAUTH_REDIRECT_PORT}`);
              if (url3.pathname !== OAUTH_REDIRECT_PATH) {
                res.writeHead(404);
                res.end("Not found");
                return;
              }
              const code2 = url3.searchParams.get("code");
              const state = url3.searchParams.get("state");
              const error40 = url3.searchParams.get("error");
              if (error40) {
                res.writeHead(HTTP_OK, { "Content-Type": "text/html" });
                res.end(`
              <html>
                <body>
                  <h1>Authentication Failed</h1>
                  <p>Error: ${error40.replace(/</g, "&lt;").replace(/>/g, "&gt;")}</p>
                  <p>${(url3.searchParams.get("error_description") || "").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</p>
                  <p>You can close this window.</p>
                </body>
              </html>
            `);
                activeCallbackServer = null;
                if (activeCallbackTimeout) {
                  clearTimeout(activeCallbackTimeout);
                  activeCallbackTimeout = null;
                }
                server.close();
                reject(new Error(`OAuth error: ${error40}`));
                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");
                activeCallbackServer = null;
                if (activeCallbackTimeout) {
                  clearTimeout(activeCallbackTimeout);
                  activeCallbackTimeout = null;
                }
                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>
          `);
              activeCallbackServer = null;
              if (activeCallbackTimeout) {
                clearTimeout(activeCallbackTimeout);
                activeCallbackTimeout = null;
              }
              server.close();
              resolve42({ code: code2, state });
            } catch (error40) {
              activeCallbackServer = null;
              if (activeCallbackTimeout) {
                clearTimeout(activeCallbackTimeout);
                activeCallbackTimeout = null;
              }
              server.close();
              reject(error40);
            }
          });
          server.on("error", reject);
          server.listen(OAUTH_REDIRECT_PORT, () => {
            debugLogger55.debug(`OAuth callback server listening on port ${OAUTH_REDIRECT_PORT}`);
          });
          activeCallbackServer = server;
          activeCallbackTimeout = setTimeout(() => {
            activeCallbackServer = null;
            activeCallbackTimeout = null;
            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 (error40) {
            debugLogger55.warn(`Could not add resource parameter: ${getErrorMessage(error40)}`);
          }
        }
        const url3 = new URL4(config2.authorizationUrl);
        params.forEach((value, key) => {
          url3.searchParams.append(key, value);
        });
        return url3.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 (error40) {
            debugLogger55.warn(`Could not add resource parameter: ${getErrorMessage(error40)}`);
          }
        }
        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 error40 = errorParams.get("error");
            const errorDescription = errorParams.get("error_description");
            if (error40) {
              errorMessage = `Token exchange failed: ${error40} - ${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")) {
          debugLogger55.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 error40 = tokenParams.get("error");
            const errorDescription = tokenParams.get("error_description");
            throw new Error(`Token exchange failed: ${error40 || "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 (error40) {
            debugLogger55.warn(`Could not add resource parameter: ${getErrorMessage(error40)}`);
          }
        }
        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 error40 = errorParams.get("error");
            const errorDescription = errorParams.get("error_description");
            if (error40) {
              errorMessage = `Token refresh failed: ${error40} - ${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")) {
          debugLogger55.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 error40 = tokenParams.get("error");
            const errorDescription = tokenParams.get("error_description");
            throw new Error(`Token refresh failed: ${error40 || "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 {
            if (typeof message === "string") {
              debugLogger55.info(message);
            } else {
              debugLogger55.info(`[${message.key}]${message.params ? ` ${JSON.stringify(message.params)}` : ""}`);
            }
          }
        }, "displayMessage");
        if (!config2.authorizationUrl && mcpServerUrl) {
          debugLogger55.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 (error40) {
            debugLogger55.debug(`Failed to check endpoint for authentication requirements: ${getErrorMessage(error40)}`);
          }
          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}`;
            debugLogger55.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;
            }
            debugLogger55.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({
          key: "If the browser does not open, copy and paste this URL into your browser:"
        });
        displayMessage({
          key: "Make sure to copy the COMPLETE URL - it may wrap across multiple lines."
        });
        if (events) {
          events.emit(OAUTH_AUTH_URL_EVENT, authUrl.toString());
        } else {
          displayMessage(`
${authUrl.toString()}
`);
        }
        const callbackPromise = this.startCallbackServer(pkceParams.state);
        try {
          await openBrowserSecurely(authUrl);
        } catch (error40) {
          debugLogger55.warn(`Failed to open browser automatically: ${getErrorMessage(error40)}`);
        }
        const { code: code2 } = await callbackPromise;
        debugLogger55.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);
          debugLogger55.debug("\u2713 Authentication successful! Token saved.");
          const savedToken = await this.tokenStorage.getCredentials(serverName);
          if (savedToken && savedToken.token && savedToken.token.accessToken) {
            const tokenFingerprint = crypto12.createHash("sha256").update(savedToken.token.accessToken).digest("hex").slice(0, 8);
            debugLogger55.debug(`\u2713 Token verification successful (fingerprint: ${tokenFingerprint})`);
          } else {
            debugLogger55.error("Token verification failed: token not found or invalid after save");
          }
        } catch (saveError) {
          debugLogger55.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) {
        debugLogger55.debug(`Getting valid token for server: ${serverName}`);
        const credentials = await this.tokenStorage.getCredentials(serverName);
        if (!credentials) {
          debugLogger55.debug(`No credentials found for server: ${serverName}`);
          return null;
        }
        const { token: token2 } = credentials;
        debugLogger55.debug(`Found token for server: ${serverName}, expired: ${this.tokenStorage.isTokenExpired(token2)}`);
        if (!this.tokenStorage.isTokenExpired(token2)) {
          debugLogger55.debug(`Returning valid token for server: ${serverName}`);
          return token2.accessToken;
        }
        if (token2.refreshToken && config2.clientId && credentials.tokenUrl) {
          try {
            debugLogger55.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 (error40) {
            debugLogger55.error(`Failed to refresh token: ${getErrorMessage(error40)}`);
            await this.tokenStorage.deleteCredentials(serverName);
          }
        }
        return null;
      }
    };
  }
});

// packages/core/dist/src/tools/mcp-client.js
import { existsSync as existsSync8 } from "node:fs";
import { basename as basename9 } from "node:path";
import { pathToFileURL } from "node:url";
function addMCPStatusChangeListener(listener) {
  statusChangeListeners.push(listener);
}
function removeMCPStatusChangeListener(listener) {
  const index = statusChangeListeners.indexOf(listener);
  if (index !== -1) {
    statusChangeListeners.splice(index, 1);
  }
}
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 getAllMCPServerStatuses() {
  return new Map(serverStatuses);
}
function getMCPDiscoveryState() {
  return mcpDiscoveryState;
}
function extractWWWAuthenticateHeader(errorString) {
  const patterns = [
    /www-authenticate:\s*([^\n\r]+)/i,
    /WWW-Authenticate:\s*([^\n\r]+)/i,
    /"www-authenticate":\s*"([^"]+)"/i,
    /'www-authenticate':\s*'([^']+)'/i
  ];
  for (const pattern of patterns) {
    const match2 = errorString.match(pattern);
    if (match2) {
      return match2[1].trim();
    }
  }
  return null;
}
async function handleAutomaticOAuth(mcpServerName, mcpServerConfig, wwwAuthenticate) {
  try {
    debugLogger56.info(`'${mcpServerName}' requires OAuth authentication`);
    let oauthConfig;
    const resourceMetadataUri = OAuthUtils.parseWWWAuthenticateHeader(wwwAuthenticate);
    if (resourceMetadataUri) {
      oauthConfig = await OAuthUtils.discoverOAuthConfig(resourceMetadataUri);
    } else if (hasNetworkTransport(mcpServerConfig)) {
      const serverUrl2 = new URL(mcpServerConfig.httpUrl || mcpServerConfig.url);
      const baseUrl = `${serverUrl2.protocol}//${serverUrl2.host}`;
      oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
    }
    if (!oauthConfig) {
      debugLogger56.error(`Could not configure OAuth for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
      return false;
    }
    const oauthAuthConfig = {
      enabled: true,
      authorizationUrl: oauthConfig.authorizationUrl,
      tokenUrl: oauthConfig.tokenUrl,
      scopes: oauthConfig.scopes || []
    };
    const serverUrl = mcpServerConfig.httpUrl || mcpServerConfig.url;
    debugLogger56.info(`Starting OAuth authentication for server '${mcpServerName}'...`);
    const authProvider = new MCPOAuthProvider(new MCPOAuthTokenStorage());
    await authProvider.authenticate(mcpServerName, oauthAuthConfig, serverUrl);
    debugLogger56.info(`OAuth authentication successful for server '${mcpServerName}'`);
    return true;
  } catch (error40) {
    debugLogger56.error(`Failed to handle automatic OAuth for server '${mcpServerName}': ${getErrorMessage(error40)}`);
    return false;
  }
}
async function createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken) {
  try {
    if (mcpServerConfig.httpUrl) {
      const oauthTransportOptions = {
        requestInit: {
          headers: {
            ...mcpServerConfig.headers,
            Authorization: `Bearer ${accessToken}`
          }
        }
      };
      return new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), oauthTransportOptions);
    } else if (mcpServerConfig.url) {
      return new SSEClientTransport(new URL(mcpServerConfig.url), {
        requestInit: {
          headers: {
            ...mcpServerConfig.headers,
            Authorization: `Bearer ${accessToken}`
          }
        }
      });
    }
    return null;
  } catch (error40) {
    debugLogger56.error(`Failed to create OAuth transport for server '${mcpServerName}': ${getErrorMessage(error40)}`);
    return null;
  }
}
async function discoverMcpTools(mcpServers, mcpServerCommand, toolRegistry, promptRegistry, debugMode, workspaceContext, cliConfig) {
  mcpDiscoveryState = MCPDiscoveryState.IN_PROGRESS;
  try {
    mcpServers = populateMcpServerCommand(mcpServers, mcpServerCommand);
    const discoveryPromises = Object.entries(mcpServers).map(([mcpServerName, mcpServerConfig]) => connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry, promptRegistry, debugMode, workspaceContext, cliConfig));
    await Promise.all(discoveryPromises);
  } finally {
    mcpDiscoveryState = MCPDiscoveryState.COMPLETED;
  }
}
function populateMcpServerCommand(mcpServers, mcpServerCommand) {
  if (mcpServerCommand) {
    const cmd = mcpServerCommand;
    const args2 = (0, import_shell_quote4.parse)(cmd, process.env);
    if (args2.some((arg) => typeof arg !== "string")) {
      throw new Error("failed to parse mcpServerCommand: " + cmd);
    }
    mcpServers["mcp"] = {
      command: args2[0],
      args: args2.slice(1)
    };
  }
  return mcpServers;
}
async function connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry, promptRegistry, debugMode, workspaceContext, cliConfig, sendSdkMcpMessage) {
  updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTING);
  let mcpClient;
  try {
    mcpClient = await connectToMcpServer(mcpServerName, mcpServerConfig, debugMode, workspaceContext, sendSdkMcpMessage);
    mcpClient.onerror = (error40) => {
      debugLogger56.error(`MCP ERROR (${mcpServerName}):`, error40.toString());
      updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
    };
    const prompts3 = await discoverPrompts(mcpServerName, mcpClient, promptRegistry);
    const tools = await discoverTools(mcpServerName, mcpServerConfig, mcpClient, cliConfig);
    if (prompts3.length === 0 && tools.length === 0) {
      throw new Error("No prompts or tools found on the server.");
    }
    updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTED);
    for (const tool of tools) {
      toolRegistry.registerTool(tool);
    }
  } catch (error40) {
    if (mcpClient) {
      mcpClient.close();
    }
    debugLogger56.error(`Error connecting to MCP server '${mcpServerName}': ${getErrorMessage(error40)}`);
    updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
  }
}
async function discoverTools(mcpServerName, mcpServerConfig, mcpClient, cliConfig) {
  try {
    const mcpCallableTool = mcpToTool(mcpClient, {
      timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC
    });
    const tool = await mcpCallableTool.tool();
    if (!Array.isArray(tool.functionDeclarations)) {
      return [];
    }
    const 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 {
      debugLogger56.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 (error40) {
        debugLogger56.error(`Error discovering tool: '${funcDecl.name}' from MCP server '${mcpServerName}': ${error40.message}`);
      }
    }
    return discoveredTools;
  } catch (error40) {
    if (error40 instanceof Error && !error40.message?.includes("Method not found")) {
      debugLogger56.error(`Error discovering tools from ${mcpServerName}: ${getErrorMessage(error40)}`);
    }
    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 (error40) {
    if (error40 instanceof Error && !error40.message?.includes("Method not found")) {
      debugLogger56.error(`Error discovering prompts from ${mcpServerName}: ${getErrorMessage(error40)}`);
    }
    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 (error40) {
    if (error40 instanceof Error && !error40.message?.includes("Method not found")) {
      debugLogger56.error(`Error invoking prompt '${promptName}' from ${mcpServerName} ${promptParams}: ${getErrorMessage(error40)}`);
    }
    throw error40;
  }
}
function hasNetworkTransport(config2) {
  return !!(config2.url || config2.httpUrl);
}
async function connectToMcpServer(mcpServerName, mcpServerConfig, debugMode, workspaceContext, sendSdkMcpMessage) {
  const mcpClient = new Client({
    name: "qwen-code-mcp-client",
    version: "0.0.1"
  });
  mcpClient.registerCapabilities({
    roots: {
      listChanged: true
    }
  });
  mcpClient.setRequestHandler(ListRootsRequestSchema, async () => {
    const roots = [];
    for (const dir of workspaceContext.getDirectories()) {
      roots.push({
        uri: pathToFileURL(dir).toString(),
        name: basename9(dir)
      });
    }
    return {
      roots
    };
  });
  let unlistenDirectories = workspaceContext.onDirectoriesChanged(async () => {
    try {
      await mcpClient.notification({
        method: "notifications/roots/list_changed"
      });
    } catch (_2) {
      unlistenDirectories?.();
      unlistenDirectories = void 0;
    }
  });
  const oldOnClose = mcpClient.onclose;
  mcpClient.onclose = () => {
    oldOnClose?.();
    unlistenDirectories?.();
    unlistenDirectories = void 0;
  };
  try {
    const transport = await createTransport(mcpServerName, mcpServerConfig, debugMode, sendSdkMcpMessage);
    try {
      await mcpClient.connect(transport, {
        timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC
      });
      return mcpClient;
    } catch (error40) {
      unlistenDirectories?.();
      unlistenDirectories = void 0;
      await transport.close();
      throw error40;
    }
  } catch (error40) {
    unlistenDirectories?.();
    unlistenDirectories = void 0;
    const errorString = String(error40);
    if (errorString.includes("401") && hasNetworkTransport(mcpServerConfig)) {
      mcpServerRequiresOAuth.set(mcpServerName, true);
      const shouldTriggerOAuth = mcpServerConfig.httpUrl || mcpServerConfig.oauth?.enabled;
      if (!shouldTriggerOAuth) {
        const tokenStorage = new MCPOAuthTokenStorage();
        const credentials = await tokenStorage.getCredentials(mcpServerName);
        if (credentials) {
          const authProvider = new MCPOAuthProvider(tokenStorage);
          const hasStoredTokens = await authProvider.getValidToken(mcpServerName, {
            // Pass client ID if available
            clientId: credentials.clientId
          });
          if (hasStoredTokens) {
            debugLogger56.warn(`Stored OAuth token for SSE server '${mcpServerName}' was rejected. Please re-authenticate using: /mcp auth ${mcpServerName}`);
          } else {
            debugLogger56.warn(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. Please authenticate using: /mcp auth ${mcpServerName}`);
          }
        }
        throw new Error(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. Please authenticate using: /mcp auth ${mcpServerName}`);
      }
      let wwwAuthenticate = extractWWWAuthenticateHeader(errorString);
      if (!wwwAuthenticate && hasNetworkTransport(mcpServerConfig)) {
        debugLogger56.debug(`No www-authenticate header in error, trying to fetch it from server...`);
        try {
          const urlToFetch = mcpServerConfig.httpUrl || mcpServerConfig.url;
          const response = await fetch(urlToFetch, {
            method: "HEAD",
            headers: {
              Accept: mcpServerConfig.httpUrl ? "application/json" : "text/event-stream"
            },
            signal: AbortSignal.timeout(5e3)
          });
          if (response.status === 401) {
            wwwAuthenticate = response.headers.get("www-authenticate");
            if (wwwAuthenticate) {
              debugLogger56.debug(`Found www-authenticate header from server: ${wwwAuthenticate}`);
            }
          }
        } catch (fetchError) {
          debugLogger56.debug(`Failed to fetch www-authenticate header: ${getErrorMessage(fetchError)}`);
        }
      }
      if (wwwAuthenticate) {
        debugLogger56.debug(`Received 401 with www-authenticate header: ${wwwAuthenticate}`);
        const oauthSuccess = await handleAutomaticOAuth(mcpServerName, mcpServerConfig, wwwAuthenticate);
        if (oauthSuccess) {
          debugLogger56.info(`Retrying connection to '${mcpServerName}' with OAuth token...`);
          const tokenStorage = new MCPOAuthTokenStorage();
          const credentials = await tokenStorage.getCredentials(mcpServerName);
          if (credentials) {
            const authProvider = new MCPOAuthProvider(tokenStorage);
            const accessToken = await authProvider.getValidToken(mcpServerName, {
              // Pass client ID if available
              clientId: credentials.clientId
            });
            if (accessToken) {
              const oauthTransport = await createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken);
              if (oauthTransport) {
                try {
                  await mcpClient.connect(oauthTransport, {
                    timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC
                  });
                  return mcpClient;
                } catch (retryError) {
                  debugLogger56.error(`Failed to connect with OAuth token: ${getErrorMessage(retryError)}`);
                  throw retryError;
                }
              } else {
                debugLogger56.error(`Failed to create OAuth transport for server '${mcpServerName}'`);
                throw new Error(`Failed to create OAuth transport for server '${mcpServerName}'`);
              }
            } else {
              debugLogger56.error(`Failed to get OAuth token for server '${mcpServerName}'`);
              throw new Error(`Failed to get OAuth token for server '${mcpServerName}'`);
            }
          } else {
            debugLogger56.error(`Failed to get credentials for server '${mcpServerName}' after successful OAuth authentication`);
            throw new Error(`Failed to get credentials for server '${mcpServerName}' after successful OAuth authentication`);
          }
        } else {
          debugLogger56.error(`Failed to handle automatic OAuth for server '${mcpServerName}'`);
          throw new Error(`Failed to handle automatic OAuth for server '${mcpServerName}'`);
        }
      } else {
        const shouldTryDiscovery = mcpServerConfig.httpUrl || mcpServerConfig.oauth?.enabled;
        if (!shouldTryDiscovery) {
          const tokenStorage = new MCPOAuthTokenStorage();
          const credentials = await tokenStorage.getCredentials(mcpServerName);
          if (credentials) {
            const authProvider = new MCPOAuthProvider(tokenStorage);
            const hasStoredTokens = await authProvider.getValidToken(mcpServerName, {
              // Pass client ID if available
              clientId: credentials.clientId
            });
            if (hasStoredTokens) {
              debugLogger56.warn(`Stored OAuth token for SSE server '${mcpServerName}' was rejected. Please re-authenticate using: /mcp auth ${mcpServerName}`);
            } else {
              debugLogger56.warn(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. Please authenticate using: /mcp auth ${mcpServerName}`);
            }
          }
          throw new Error(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. Please authenticate using: /mcp auth ${mcpServerName}`);
        }
        debugLogger56.info(`Attempting OAuth discovery for '${mcpServerName}'...`);
        if (hasNetworkTransport(mcpServerConfig)) {
          const serverUrl = new URL(mcpServerConfig.httpUrl || mcpServerConfig.url);
          const baseUrl = `${serverUrl.protocol}//${serverUrl.host}`;
          try {
            const oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
            if (oauthConfig) {
              debugLogger56.info(`Discovered OAuth configuration from base URL for server '${mcpServerName}'`);
              const oauthAuthConfig = {
                enabled: true,
                authorizationUrl: oauthConfig.authorizationUrl,
                tokenUrl: oauthConfig.tokenUrl,
                scopes: oauthConfig.scopes || []
              };
              const authServerUrl = mcpServerConfig.httpUrl || mcpServerConfig.url;
              debugLogger56.info(`Starting OAuth authentication for server '${mcpServerName}'...`);
              const authProvider = new MCPOAuthProvider(new MCPOAuthTokenStorage());
              await authProvider.authenticate(mcpServerName, oauthAuthConfig, authServerUrl);
              const tokenStorage = new MCPOAuthTokenStorage();
              const credentials = await tokenStorage.getCredentials(mcpServerName);
              if (credentials) {
                const authProvider2 = new MCPOAuthProvider(tokenStorage);
                const accessToken = await authProvider2.getValidToken(mcpServerName, {
                  // Pass client ID if available
                  clientId: credentials.clientId
                });
                if (accessToken) {
                  const oauthTransport = await createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken);
                  if (oauthTransport) {
                    try {
                      await mcpClient.connect(oauthTransport, {
                        timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC
                      });
                      return mcpClient;
                    } catch (retryError) {
                      debugLogger56.error(`Failed to connect with OAuth token: ${getErrorMessage(retryError)}`);
                      throw retryError;
                    }
                  } else {
                    debugLogger56.error(`Failed to create OAuth transport for server '${mcpServerName}'`);
                    throw new Error(`Failed to create OAuth transport for server '${mcpServerName}'`);
                  }
                } else {
                  debugLogger56.error(`Failed to get OAuth token for server '${mcpServerName}'`);
                  throw new Error(`Failed to get OAuth token for server '${mcpServerName}'`);
                }
              } else {
                debugLogger56.error(`Failed to get stored credentials for server '${mcpServerName}'`);
                throw new Error(`Failed to get stored credentials for server '${mcpServerName}'`);
              }
            } else {
              debugLogger56.error(`Could not configure OAuth for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
              throw new Error(`OAuth configuration failed for '${mcpServerName}'. Please authenticate manually with /mcp auth ${mcpServerName}`);
            }
          } catch (discoveryError) {
            debugLogger56.error(`OAuth discovery failed for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
            throw discoveryError;
          }
        } else {
          debugLogger56.error(`'${mcpServerName}' requires authentication but no OAuth configuration found`);
          throw new Error(`MCP server '${mcpServerName}' requires authentication. Please configure OAuth or check server settings.`);
        }
      }
    } else {
      const errorMessage = error40.message || String(error40);
      const isNetworkError = errorMessage.includes("ENOTFOUND") || errorMessage.includes("ECONNREFUSED");
      let conciseError;
      if (isNetworkError) {
        conciseError = `Cannot connect to '${mcpServerName}' - server may be down or URL incorrect`;
      } else {
        conciseError = `Connection failed for '${mcpServerName}': ${errorMessage}`;
      }
      if (process.env["SANDBOX"]) {
        conciseError += ` (check sandbox availability)`;
      }
      throw new Error(conciseError);
    }
  }
}
async function createTransport(mcpServerName, mcpServerConfig, debugMode, 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) {
      debugLogger56.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;
        debugLogger56.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) {
    if (mcpServerConfig.cwd && !existsSync8(mcpServerConfig.cwd)) {
      throw new Error(`MCP server '${mcpServerName}': configured cwd does not exist: ${mcpServerConfig.cwd}`);
    }
    const env6 = {
      ...normalizePathEnvForWindows({ ...process.env }),
      ...mcpServerConfig.env || {}
    };
    const transport = new StdioClientTransport({
      command: mcpServerConfig.command,
      args: mcpServerConfig.args || [],
      env: env6,
      cwd: mcpServerConfig.cwd,
      stderr: "pipe"
    });
    if (debugMode) {
      transport.stderr.on("data", (data) => {
        const stderrStr = data.toString().trim();
        debugLogger56.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) {
    debugLogger56.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_quote4, MCP_DEFAULT_TIMEOUT_MSEC, debugLogger56, MCPServerStatus, MCPDiscoveryState, McpClient, serverStatuses, mcpDiscoveryState, mcpServerRequiresOAuth, statusChangeListeners;
var init_mcp_client = __esm({
  "packages/core/dist/src/tools/mcp-client.js"() {
    "use strict";
    init_esbuild_shims();
    init_client3();
    init_sse();
    init_stdio2();
    init_streamableHttp();
    init_types11();
    import_shell_quote4 = __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();
    init_windowsPath();
    MCP_DEFAULT_TIMEOUT_MSEC = 10 * 60 * 1e3;
    debugLogger56 = 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 = (error40) => {
            if (this.isDisconnecting) {
              return;
            }
            debugLogger56.error(`MCP ERROR (${this.serverName}):`, error40.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 (error40) {
          this.updateStatus(MCPServerStatus.DISCONNECTED);
          throw error40;
        }
      }
      /**
       * 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;
    mcpServerRequiresOAuth = /* @__PURE__ */ new Map();
    statusChangeListeners = [];
    __name(addMCPStatusChangeListener, "addMCPStatusChangeListener");
    __name(removeMCPStatusChangeListener, "removeMCPStatusChangeListener");
    __name(updateMCPServerStatus, "updateMCPServerStatus");
    __name(getMCPServerStatus, "getMCPServerStatus");
    __name(getAllMCPServerStatuses, "getAllMCPServerStatuses");
    __name(getMCPDiscoveryState, "getMCPDiscoveryState");
    __name(extractWWWAuthenticateHeader, "extractWWWAuthenticateHeader");
    __name(handleAutomaticOAuth, "handleAutomaticOAuth");
    __name(createTransportWithOAuth, "createTransportWithOAuth");
    __name(discoverMcpTools, "discoverMcpTools");
    __name(populateMcpServerCommand, "populateMcpServerCommand");
    __name(connectAndDiscover, "connectAndDiscover");
    __name(discoverTools, "discoverTools");
    __name(discoverPrompts, "discoverPrompts");
    __name(invokeMcpPrompt, "invokeMcpPrompt");
    __name(hasNetworkTransport, "hasNetworkTransport");
    __name(connectToMcpServer, "connectToMcpServer");
    __name(createTransport, "createTransport");
    __name(isEnabled, "isEnabled");
  }
});

// packages/core/dist/src/tools/mcp-client-manager.js
var debugLogger57, DEFAULT_HEALTH_CONFIG, 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();
    debugLogger57 = createDebugLogger("MCP");
    DEFAULT_HEALTH_CONFIG = {
      checkIntervalMs: 3e4,
      // 30 seconds
      maxConsecutiveFailures: 3,
      autoReconnect: true,
      reconnectDelayMs: 5e3
      // 5 seconds
    };
    McpClientManager = class {
      static {
        __name(this, "McpClientManager");
      }
      clients = /* @__PURE__ */ new Map();
      toolRegistry;
      cliConfig;
      discoveryState = MCPDiscoveryState.NOT_STARTED;
      eventEmitter;
      sendSdkMcpMessage;
      healthConfig;
      healthCheckTimers = /* @__PURE__ */ new Map();
      consecutiveFailures = /* @__PURE__ */ new Map();
      isReconnecting = /* @__PURE__ */ new Map();
      constructor(config2, toolRegistry, eventEmitter, sendSdkMcpMessage, healthConfig) {
        this.cliConfig = config2;
        this.toolRegistry = toolRegistry;
        this.eventEmitter = eventEmitter;
        this.sendSdkMcpMessage = sendSdkMcpMessage;
        this.healthConfig = { ...DEFAULT_HEALTH_CONFIG, ...healthConfig };
      }
      /**
       * 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 ([name4, config2]) => {
          if (cliConfig.isMcpServerDisabled(name4)) {
            debugLogger57.debug(`Skipping disabled MCP server: ${name4}`);
            return;
          }
          const sdkCallback = isSdkMcpServerConfig(config2) ? this.sendSdkMcpMessage : void 0;
          const client = new McpClient(name4, config2, this.toolRegistry, this.cliConfig.getPromptRegistry(), this.cliConfig.getWorkspaceContext(), this.cliConfig.getDebugMode(), sdkCallback);
          this.clients.set(name4, 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 (error40) {
            this.eventEmitter?.emit("mcp-client-update", this.clients);
            debugLogger57.error(`Error during discovery for server '${name4}': ${getErrorMessage(error40)}`);
          }
        });
        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 (error40) {
            debugLogger57.error(`Error stopping client '${serverName}': ${getErrorMessage(error40)}`);
          } 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);
          this.startHealthCheck(serverName);
        } catch (error40) {
          debugLogger57.error(`Error during discovery for server '${serverName}': ${getErrorMessage(error40)}`);
        } 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() {
        this.stopAllHealthChecks();
        const disconnectionPromises = Array.from(this.clients.entries()).map(async ([name4, client]) => {
          try {
            await client.disconnect();
          } catch (error40) {
            debugLogger57.error(`Error stopping client '${name4}': ${getErrorMessage(error40)}`);
          }
        });
        await Promise.all(disconnectionPromises);
        this.clients.clear();
        this.consecutiveFailures.clear();
        this.isReconnecting.clear();
      }
      /**
       * Disconnects a specific MCP server.
       * @param serverName The name of the server to disconnect.
       */
      async disconnectServer(serverName) {
        this.stopHealthCheck(serverName);
        const client = this.clients.get(serverName);
        if (client) {
          try {
            await client.disconnect();
          } catch (error40) {
            debugLogger57.error(`Error disconnecting client '${serverName}': ${getErrorMessage(error40)}`);
          } finally {
            this.clients.delete(serverName);
            this.consecutiveFailures.delete(serverName);
            this.isReconnecting.delete(serverName);
            this.eventEmitter?.emit("mcp-client-update", this.clients);
          }
        }
      }
      getDiscoveryState() {
        return this.discoveryState;
      }
      /**
       * Gets the health monitoring configuration
       */
      getHealthConfig() {
        return { ...this.healthConfig };
      }
      /**
       * Updates the health monitoring configuration
       */
      updateHealthConfig(config2) {
        this.healthConfig = { ...this.healthConfig, ...config2 };
        this.stopAllHealthChecks();
        if (this.healthConfig.autoReconnect) {
          this.startAllHealthChecks();
        }
      }
      /**
       * Starts health monitoring for a specific server
       */
      startHealthCheck(serverName) {
        if (!this.healthConfig.autoReconnect) {
          return;
        }
        this.stopHealthCheck(serverName);
        const timer = setInterval(async () => {
          await this.performHealthCheck(serverName);
        }, this.healthConfig.checkIntervalMs);
        this.healthCheckTimers.set(serverName, timer);
      }
      /**
       * Stops health monitoring for a specific server
       */
      stopHealthCheck(serverName) {
        const timer = this.healthCheckTimers.get(serverName);
        if (timer) {
          clearInterval(timer);
          this.healthCheckTimers.delete(serverName);
        }
      }
      /**
       * Stops all health checks
       */
      stopAllHealthChecks() {
        for (const [, timer] of this.healthCheckTimers.entries()) {
          clearInterval(timer);
        }
        this.healthCheckTimers.clear();
      }
      /**
       * Starts health checks for all connected servers
       */
      startAllHealthChecks() {
        for (const serverName of this.clients.keys()) {
          this.startHealthCheck(serverName);
        }
      }
      /**
       * Performs a health check on a specific server
       */
      async performHealthCheck(serverName) {
        const client = this.clients.get(serverName);
        if (!client) {
          return;
        }
        if (this.isReconnecting.get(serverName)) {
          return;
        }
        try {
          const status = client.getStatus();
          if (status !== MCPServerStatus.CONNECTED) {
            const failures = (this.consecutiveFailures.get(serverName) || 0) + 1;
            this.consecutiveFailures.set(serverName, failures);
            debugLogger57.warn(`Health check failed for server '${serverName}' (${failures}/${this.healthConfig.maxConsecutiveFailures})`);
            if (failures >= this.healthConfig.maxConsecutiveFailures) {
              await this.reconnectServer(serverName);
            }
          } else {
            this.consecutiveFailures.set(serverName, 0);
          }
        } catch (error40) {
          debugLogger57.error(`Error during health check for server '${serverName}': ${getErrorMessage(error40)}`);
        }
      }
      /**
       * Reconnects a specific server
       */
      async reconnectServer(serverName) {
        if (this.isReconnecting.get(serverName)) {
          return;
        }
        this.isReconnecting.set(serverName, true);
        debugLogger57.info(`Attempting to reconnect to server '${serverName}'...`);
        try {
          await new Promise((resolve42) => setTimeout(resolve42, this.healthConfig.reconnectDelayMs));
          await this.discoverMcpToolsForServer(serverName, this.cliConfig);
          this.consecutiveFailures.set(serverName, 0);
          debugLogger57.info(`Successfully reconnected to server '${serverName}'`);
        } catch (error40) {
          debugLogger57.error(`Failed to reconnect to server '${serverName}': ${getErrorMessage(error40)}`);
        } finally {
          this.isReconnecting.set(serverName, false);
        }
      }
      /**
       * Discovers tools incrementally for all configured servers.
       * Only updates servers that have changed or are new.
       */
      async discoverAllMcpToolsIncremental(cliConfig) {
        if (!cliConfig.isTrustedFolder()) {
          return;
        }
        const servers = populateMcpServerCommand(this.cliConfig.getMcpServers() || {}, this.cliConfig.getMcpServerCommand());
        this.discoveryState = MCPDiscoveryState.IN_PROGRESS;
        const serversToUpdate = [];
        const currentServerNames = new Set(this.clients.keys());
        const newServerNames = new Set(Object.keys(servers));
        for (const [name4] of Object.entries(servers)) {
          const existingClient = this.clients.get(name4);
          if (!existingClient) {
            serversToUpdate.push(name4);
          } else if (existingClient.getStatus() === MCPServerStatus.DISCONNECTED) {
            serversToUpdate.push(name4);
          }
        }
        for (const name4 of currentServerNames) {
          if (!newServerNames.has(name4)) {
            await this.removeServer(name4);
          }
        }
        const discoveryPromises = serversToUpdate.map(async (name4) => {
          try {
            await this.discoverMcpToolsForServer(name4, cliConfig);
          } catch (error40) {
            debugLogger57.error(`Error during incremental discovery for server '${name4}': ${getErrorMessage(error40)}`);
          }
        });
        await Promise.all(discoveryPromises);
        if (this.healthConfig.autoReconnect) {
          this.startAllHealthChecks();
        }
        this.discoveryState = MCPDiscoveryState.COMPLETED;
      }
      /**
       * Removes a server and its tools
       */
      async removeServer(serverName) {
        const client = this.clients.get(serverName);
        if (client) {
          try {
            await client.disconnect();
          } catch (error40) {
            debugLogger57.error(`Error disconnecting removed server '${serverName}': ${getErrorMessage(error40)}`);
          }
          this.clients.delete(serverName);
          this.stopHealthCheck(serverName);
          this.consecutiveFailures.delete(serverName);
        }
        this.toolRegistry.removeMcpToolsByServer(serverName);
        this.eventEmitter?.emit("mcp-client-update", this.clients);
      }
      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 spawn4 } from "node:child_process";
import { StringDecoder as StringDecoder2 } from "node:string_decoder";
var import_shell_quote5, debugLogger58, 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_quote5 = __toESM(require_shell_quote(), 1);
    init_tool_error();
    init_safeJsonStringify();
    init_debugLogger();
    debugLogger58 = 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 = spawn4(callCommand, [this.toolName]);
        child.stdin.write(JSON.stringify(this.params));
        child.stdin.end();
        let stdout2 = "";
        let stderr = "";
        let error40 = null;
        let code2 = null;
        let signal = null;
        await new Promise((resolve42) => {
          const onStdout = /* @__PURE__ */ __name((data) => {
            stdout2 += data?.toString();
          }, "onStdout");
          const onStderr = /* @__PURE__ */ __name((data) => {
            stderr += data?.toString();
          }, "onStderr");
          const onError2 = /* @__PURE__ */ __name((err2) => {
            error40 = err2;
          }, "onError");
          const onClose = /* @__PURE__ */ __name((_code, _signal2) => {
            code2 = _code;
            signal = _signal2;
            cleanup();
            resolve42();
          }, "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 (error40 || code2 !== 0 || signal || stderr) {
          const llmContent = [
            `Stdout: ${stdout2 || "(empty)"}`,
            `Stderr: ${stderr || "(empty)"}`,
            `Error: ${error40 ?? "(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: stdout2,
          returnDisplay: stdout2
        };
      }
    };
    DiscoveredTool = class extends BaseDeclarativeTool {
      static {
        __name(this, "DiscoveredTool");
      }
      config;
      description;
      parameterSchema;
      constructor(config2, name4, 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} ${name4}\` 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(
          name4,
          name4,
          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();
      // Lazy tool factories keyed by tool name — resolved on first use.
      factories = /* @__PURE__ */ new Map();
      // In-flight factory promises — ensures concurrent ensureTool() calls for the
      // same name share one promise instead of running the factory multiple times.
      inflight = /* @__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 {
            debugLogger58.warn(`Tool with name "${tool.name}" is already registered. Overwriting.`);
          }
        }
        this.tools.set(tool.name, tool);
      }
      /**
       * Registers a lazy tool factory. The tool module is not imported and the tool
       * is not instantiated until {@link ensureTool} or {@link warmAll} is called.
       */
      registerFactory(name4, factory2) {
        this.factories.set(name4, factory2);
      }
      /**
       * Ensures a specific tool is loaded. Returns the cached instance if already
       * loaded, otherwise invokes the factory, caches the result, and returns it.
       * Concurrent calls for the same name share a single in-flight promise so the
       * factory is never executed more than once.
       */
      async ensureTool(name4) {
        const cached2 = this.tools.get(name4);
        if (cached2) {
          this.factories.delete(name4);
          return cached2;
        }
        const existing = this.inflight.get(name4);
        if (existing)
          return existing;
        const factory2 = this.factories.get(name4);
        if (!factory2)
          return void 0;
        const load = factory2().then((tool) => {
          this.tools.set(name4, tool);
          this.factories.delete(name4);
          this.inflight.delete(name4);
          return tool;
        }).catch((err2) => {
          this.inflight.delete(name4);
          throw err2;
        });
        this.inflight.set(name4, load);
        return load;
      }
      /**
       * Loads all pending tool factories in parallel. Safe to call multiple times
       * (no-op when all factories have been resolved). Call this before any bulk
       * access such as {@link getAllTools} or {@link getFunctionDeclarations}.
       *
       * @param options.strict - When `true`, re-throws the first factory failure
       *   instead of swallowing it. Use this during startup (e.g. in
       *   `Config.initialize`) so a broken built-in tool surfaces immediately
       *   rather than leaving the session partially initialised.
       */
      async warmAll(options2) {
        const pending = Array.from(this.factories.keys());
        if (pending.length === 0)
          return;
        const results = await Promise.allSettled(pending.map((name4) => this.ensureTool(name4)));
        for (const result of results) {
          if (result.status === "rejected") {
            if (options2?.strict)
              throw result.reason;
            debugLogger58.warn("Failed to warm tool factory:", result.reason);
          }
        }
      }
      /**
       * Copies discovered (non-core) tools from another registry into this one.
       * Used to share MCP/command-discovered tools with per-agent registries
       * that were built with skipDiscovery.
       */
      copyDiscoveredToolsFrom(source2) {
        for (const tool of source2.tools.values()) {
          if ((tool instanceof DiscoveredTool || tool instanceof DiscoveredMCPTool) && !this.tools.has(tool.name)) {
            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 [name4, tool] of this.tools.entries()) {
          if (tool instanceof DiscoveredMCPTool && tool.serverName === serverName) {
            this.tools.delete(name4);
          }
        }
      }
      /**
       * Disconnects an MCP server by removing its tools, prompts, and disconnecting the client.
       * Unlike disableMcpServer, this does NOT add the server to the exclusion list.
       * @param serverName The name of the server to disconnect.
       */
      async disconnectServer(serverName) {
        this.removeMcpToolsByServer(serverName);
        this.config.getPromptRegistry().removePromptsByServer(serverName);
        await this.mcpClientManager.disconnectServer(serverName);
      }
      /**
       * Disables an MCP server by removing its tools, prompts, and disconnecting the client.
       * Also updates the config's exclusion list.
       * @param serverName The name of the server to disable.
       */
      async disableMcpServer(serverName) {
        this.removeMcpToolsByServer(serverName);
        this.config.getPromptRegistry().removePromptsByServer(serverName);
        await this.mcpClientManager.disconnectServer(serverName);
        const currentExcluded = this.config.getExcludedMcpServers() || [];
        if (!currentExcluded.includes(serverName)) {
          this.config.setExcludedMcpServers([...currentExcluded, serverName]);
        }
      }
      /**
       * 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 [name4, tool] of this.tools.entries()) {
          if (tool instanceof DiscoveredMCPTool && tool.serverName === serverName) {
            this.tools.delete(name4);
          }
        }
        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_quote5.parse)(discoveryCmd);
          if (cmdParts.length === 0) {
            throw new Error("Tool discovery command is empty or contains only whitespace.");
          }
          const proc2 = spawn4(cmdParts[0], cmdParts.slice(1));
          let stdout2 = "";
          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;
            stdout2 += 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((resolve42, reject) => {
            proc2.on("error", reject);
            proc2.on("close", (code2) => {
              stdout2 += 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) {
                debugLogger58.error(`Tool discovery command failed with code ${code2}`);
                debugLogger58.error(stderr);
                return reject(new Error(`Tool discovery command failed with exit code ${code2}`));
              }
              resolve42();
            });
          });
          const functions = [];
          const discoveredItems = JSON.parse(stdout2.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 func2 of functions) {
            if (!func2.name) {
              debugLogger58.warn("Discovered a tool with no name. Skipping.");
              continue;
            }
            const parameters = func2.parametersJsonSchema && typeof func2.parametersJsonSchema === "object" && !Array.isArray(func2.parametersJsonSchema) ? func2.parametersJsonSchema : {};
            this.registerTool(new DiscoveredTool(this.config, func2.name, func2.description ?? "", parameters));
          }
        } catch (e4) {
          debugLogger58.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.
       * @remarks Requires all tool factories to be resolved first. Call
       * {@link warmAll} before invoking this method, otherwise factory-registered
       * tools that have not yet been loaded will be silently omitted.
       */
      getFunctionDeclarationsFiltered(toolNames) {
        if (this.factories.size > 0) {
          debugLogger58.warn(`getFunctionDeclarationsFiltered() called with ${this.factories.size} unloaded tool factories. Call warmAll() first to avoid incomplete results.`);
        }
        const declarations = [];
        for (const name4 of toolNames) {
          const tool = this.tools.get(name4);
          if (tool) {
            declarations.push(tool.schema);
          }
        }
        return declarations;
      }
      /**
       * Returns an array of all registered and discovered tool names,
       * including tools that are registered via factory but not yet loaded.
       */
      getAllToolNames() {
        const names = /* @__PURE__ */ new Set([...this.tools.keys(), ...this.factories.keys()]);
        return Array.from(names);
      }
      /**
       * Returns an array of all registered and discovered tool instances.
       * @remarks Requires all tool factories to be resolved first. Call
       * {@link warmAll} before invoking this method, otherwise factory-registered
       * tools that have not yet been loaded will be absent from the result.
       */
      getAllTools() {
        if (this.factories.size > 0) {
          debugLogger58.warn(`getAllTools() called with ${this.factories.size} unloaded tool factories. Call warmAll() first to avoid incomplete results.`);
        }
        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(name4) {
        return this.tools.get(name4);
      }
      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, disposes tools, and cleans up resources.
       * This method is idempotent and safe to call multiple times.
       */
      async stop() {
        if (this.inflight.size > 0) {
          await Promise.allSettled(this.inflight.values());
        }
        for (const tool of this.tools.values()) {
          if ("dispose" in tool && typeof tool.dispose === "function") {
            try {
              tool.dispose();
            } catch (error40) {
              debugLogger58.error(`Error disposing tool ${tool.name}:`, error40);
            }
          }
        }
        try {
          await this.mcpClientManager.stop();
        } catch (error40) {
          debugLogger58.error("Error stopping MCP clients:", error40);
        }
      }
    };
  }
});

// packages/core/dist/src/output/types.js
var InputFormat, OutputFormat;
var init_types13 = __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 debugLogger59, PromptRegistry;
var init_prompt_registry = __esm({
  "packages/core/dist/src/prompts/prompt-registry.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger59 = 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}`;
          debugLogger59.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(name4) {
        return this.prompts.get(name4);
      }
      /**
       * 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 [name4, prompt] of this.prompts.entries()) {
          if (prompt.serverName === serverName) {
            this.prompts.delete(name4);
          }
        }
      }
    };
  }
});

// node_modules/readdirp/esm/index.js
import { stat as stat4, 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_esm14 = __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((error40) => NORMAL_FLOW_ERRORS.has(error40.code), "isNormalFlowError");
    wantBigintFsStats = process.platform === "win32";
    emptyFn = /* @__PURE__ */ __name((_entryInfo) => true, "emptyFn");
    normalizeFilter = /* @__PURE__ */ __name((filter5) => {
      if (filter5 === void 0)
        return emptyFn;
      if (typeof filter5 === "function")
        return filter5;
      if (typeof filter5 === "string") {
        const fl = filter5.trim();
        return (entry) => entry.basename === fl;
      }
      if (Array.isArray(filter5)) {
        const trItems = filter5.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 : stat4;
        if (wantBigintFsStats) {
          this._stat = (path150) => statMethod(path150, { 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: path150, depth } = par;
              const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path150));
              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 (error40) {
          this.destroy(error40);
        } finally {
          this.reading = false;
        }
      }
      async _exploreDir(path150, depth) {
        let files;
        try {
          files = await readdir4(path150, this._rdOptions);
        } catch (error40) {
          this._onError(error40);
        }
        return { files, depth, path: path150 };
      }
      async _formatEntry(dirent, path150) {
        let entry;
        const basename34 = this._isDirent ? dirent.name : dirent;
        try {
          const fullPath = presolve(pjoin(path150, basename34));
          entry = { path: prelative(this._root, fullPath), fullPath, basename: basename34 };
          entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
        } catch (err2) {
          this._onError(err2);
          return;
        }
        return entry;
      }
      _onError(err2) {
        if (isNormalFlowError(err2) && !this.destroyed) {
          this.emit("warn", err2);
        } else {
          this.destroy(err2);
        }
      }
      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 (error40) {
            this._onError(error40);
            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 stat5, lstat as lstat3, realpath as fsrealpath } from "fs/promises";
import * as sysPath from "path";
import { type as osType } from "os";
function createFsWatchInstance(path150, options2, listener, errHandler, emitRaw) {
  const handleEvent = /* @__PURE__ */ __name((rawEvent, evPath) => {
    listener(path150);
    emitRaw(rawEvent, evPath, { watchedPath: path150 });
    if (evPath && path150 !== evPath) {
      fsWatchBroadcast(sysPath.resolve(path150, evPath), KEY_LISTENERS, sysPath.join(path150, evPath));
    }
  }, "handleEvent");
  try {
    return fs_watch(path150, {
      persistent: options2.persistent
    }, handleEvent);
  } catch (error40) {
    errHandler(error40);
    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: stat5 };
    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 set2 = cont[key];
      if (set2 instanceof Set) {
        set2.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((path150, fullPath, options2, handlers) => {
      const { listener, errHandler, rawEmitter } = handlers;
      let cont = FsWatchInstances.get(fullPath);
      let watcher;
      if (!options2.persistent) {
        watcher = createFsWatchInstance(path150, 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(
          path150,
          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 (error40) => {
          const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
          if (cont)
            cont.watcherUnusable = true;
          if (isWindows2 && error40.code === "EPERM") {
            try {
              const fd = await open3(path150, "r");
              await fd.close();
              broadcastErr(error40);
            } catch (err2) {
            }
          } else {
            broadcastErr(error40);
          }
        });
        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((path150, 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(path150, 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 = (error40) => fsW._handleError(error40);
      }
      /**
       * 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(path150, listener) {
        const opts = this.fsw.options;
        const directory = sysPath.dirname(path150);
        const basename34 = sysPath.basename(path150);
        const parent = this.fsw._getWatchedDir(directory);
        parent.add(basename34);
        const absolutePath = sysPath.resolve(path150);
        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(basename34) ? opts.binaryInterval : opts.interval;
          closer = setFsWatchFileListener(path150, absolutePath, options2, {
            listener,
            rawEmitter: this.fsw._emitRaw
          });
        } else {
          closer = setFsWatchListener(path150, 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(file2, stats, initialAdd) {
        if (this.fsw.closed) {
          return;
        }
        const dirname37 = sysPath.dirname(file2);
        const basename34 = sysPath.basename(file2);
        const parent = this.fsw._getWatchedDir(dirname37);
        let prevStats = stats;
        if (parent.has(basename34))
          return;
        const listener = /* @__PURE__ */ __name(async (path150, newStats) => {
          if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
            return;
          if (!newStats || newStats.mtimeMs === 0) {
            try {
              const newStats2 = await stat5(file2);
              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, file2, newStats2);
              }
              if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
                this.fsw._closeFile(path150);
                prevStats = newStats2;
                const closer2 = this._watchWithNodeFs(file2, listener);
                if (closer2)
                  this.fsw._addPathCloser(path150, closer2);
              } else {
                prevStats = newStats2;
              }
            } catch (error40) {
              this.fsw._remove(dirname37, basename34);
            }
          } else if (parent.has(basename34)) {
            const at2 = newStats.atimeMs;
            const mt2 = newStats.mtimeMs;
            if (!at2 || at2 <= mt2 || mt2 !== prevStats.mtimeMs) {
              this.fsw._emit(EV.CHANGE, file2, newStats);
            }
            prevStats = newStats;
          }
        }, "listener");
        const closer = this._watchWithNodeFs(file2, listener);
        if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) {
          if (!this.fsw._throttle(EV.ADD, file2, 0))
            return;
          this.fsw._emit(EV.ADD, file2, 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, path150, 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(path150);
          } 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, path150, entry.stats);
            }
          } else {
            dir.add(item);
            this.fsw._symlinkPaths.set(full, linkPath);
            this.fsw._emit(EV.ADD, path150, 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 stream5 = this.fsw._readdirp(directory, {
          fileFilter: /* @__PURE__ */ __name((entry) => wh.filterPath(entry), "fileFilter"),
          directoryFilter: /* @__PURE__ */ __name((entry) => wh.filterDir(entry), "directoryFilter")
        });
        if (!stream5)
          return;
        stream5.on(STR_DATA, async (entry) => {
          if (this.fsw.closed) {
            stream5 = void 0;
            return;
          }
          const item = entry.path;
          let path150 = sysPath.join(directory, item);
          current.add(item);
          if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path150, item)) {
            return;
          }
          if (this.fsw.closed) {
            stream5 = void 0;
            return;
          }
          if (item === target || !target && !previous.has(item)) {
            this.fsw._incrReadyCount();
            path150 = sysPath.join(dir, sysPath.relative(dir, path150));
            this._addToNodeFs(path150, initialAdd, wh, depth + 1);
          }
        }).on(EV.ERROR, this._boundHandleError);
        return new Promise((resolve42, reject) => {
          if (!stream5)
            return reject();
          stream5.once(STR_END, () => {
            if (this.fsw.closed) {
              stream5 = void 0;
              return;
            }
            const wasThrottled = throttler ? throttler.clear() : false;
            resolve42(void 0);
            previous.getChildren().filter((item) => {
              return item !== directory && !current.has(item);
            }).forEach((item) => {
              this.fsw._remove(directory, item);
            });
            stream5 = 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(path150, initialAdd, priorWh, depth, target) {
        const ready = this.fsw._emitReady;
        if (this.fsw._isIgnored(path150) || this.fsw.closed) {
          ready();
          return false;
        }
        const wh = this.fsw._getWatchHelpers(path150);
        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(path150);
            const targetPath = follow ? await fsrealpath(path150) : path150;
            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(path150) : path150;
            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, path150, wh, targetPath);
            if (this.fsw.closed)
              return;
            if (targetPath !== void 0) {
              this.fsw._symlinkPaths.set(sysPath.resolve(path150), targetPath);
            }
          } else {
            closer = this._handleFile(wh.watchPath, stats, initialAdd);
          }
          ready();
          if (closer)
            this.fsw._addPathCloser(path150, closer);
          return false;
        } catch (error40) {
          if (this.fsw._handleError(error40)) {
            ready();
            return path150;
          }
        }
      }
    };
  }
});

// node_modules/chokidar/esm/index.js
import { stat as statcb } from "fs";
import { stat as stat6, readdir as readdir5 } from "fs/promises";
import { EventEmitter as EventEmitter7 } 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 relative14 = sysPath2.relative(matcher.path, string4);
        if (!relative14) {
          return false;
        }
        return !relative14.startsWith("..") && !sysPath2.isAbsolute(relative14);
      }
      return false;
    };
  }
  return () => false;
}
function normalizePath(path150) {
  if (typeof path150 !== "string")
    throw new Error("string expected");
  path150 = sysPath2.normalize(path150);
  path150 = path150.replace(/\\/g, "/");
  let prepend = false;
  if (path150.startsWith("//"))
    prepend = true;
  const DOUBLE_SLASH_RE2 = /\/\//;
  while (path150.match(DOUBLE_SLASH_RE2))
    path150 = path150.replace(DOUBLE_SLASH_RE2, "/");
  if (prepend)
    path150 = "/" + path150;
  return path150;
}
function matchPatterns(patterns, testString, stats) {
  const path150 = normalizePath(testString);
  for (let index = 0; index < patterns.length; index++) {
    const pattern = patterns[index];
    if (pattern(path150, 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_esm15 = __esm({
  "node_modules/chokidar/esm/index.js"() {
    init_esbuild_shims();
    init_esm14();
    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((path150) => toUnix(sysPath2.normalize(toUnix(path150))), "normalizePathToUnix");
    normalizeIgnored = /* @__PURE__ */ __name((cwd6 = "") => (path150) => {
      if (typeof path150 === "string") {
        return normalizePathToUnix(sysPath2.isAbsolute(path150) ? path150 : sysPath2.join(cwd6, path150));
      } else {
        return path150;
      }
    }, "normalizeIgnored");
    getAbsolutePath = /* @__PURE__ */ __name((path150, cwd6) => {
      if (sysPath2.isAbsolute(path150)) {
        return path150;
      }
      return sysPath2.join(cwd6, path150);
    }, "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 (err2) {
          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(path150, follow, fsw) {
        this.fsw = fsw;
        const watchPath = path150;
        this.path = path150 = path150.replace(REPLACER_RE, "");
        this.watchPath = watchPath;
        this.fullWatchPath = sysPath2.resolve(watchPath);
        this.dirParts = [];
        this.dirParts.forEach((parts2) => {
          if (parts2.length > 1)
            parts2.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 EventEmitter7 {
      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 = (...args2) => this.emit(EVENTS.RAW, ...args2);
        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: cwd6 } = this.options;
        this.closed = false;
        this._closePromise = void 0;
        let paths = unifyPaths(paths_);
        if (cwd6) {
          paths = paths.map((path150) => {
            const absPath = getAbsolutePath(path150, cwd6);
            return absPath;
          });
        }
        paths.forEach((path150) => {
          this._removeIgnoredPath(path150);
        });
        this._userIgnored = void 0;
        if (!this._readyCount)
          this._readyCount = 0;
        this._readyCount += paths.length;
        Promise.all(paths.map(async (path150) => {
          const res = await this._nodeFsHandler._addToNodeFs(path150, !_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: cwd6 } = this.options;
        paths.forEach((path150) => {
          if (!sysPath2.isAbsolute(path150) && !this._closers.has(path150)) {
            if (cwd6)
              path150 = sysPath2.join(cwd6, path150);
            path150 = sysPath2.resolve(path150);
          }
          this._closePath(path150);
          this._addIgnoredPath(path150);
          if (this._watched.has(path150)) {
            this._addIgnoredPath({
              path: path150,
              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 promise2 = closer();
          if (promise2 instanceof Promise)
            closers.push(promise2);
        }));
        this._streams.forEach((stream5) => stream5.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, args2) {
        this.emit(event, ...args2);
        if (event !== EVENTS.ERROR)
          this.emit(EVENTS.ALL, event, ...args2);
      }
      // 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, path150, stats) {
        if (this.closed)
          return;
        const opts = this.options;
        if (isWindows2)
          path150 = sysPath2.normalize(path150);
        if (opts.cwd)
          path150 = sysPath2.relative(opts.cwd, path150);
        const args2 = [path150];
        if (stats != null)
          args2.push(stats);
        const awf = opts.awaitWriteFinish;
        let pw;
        if (awf && (pw = this._pendingWrites.get(path150))) {
          pw.lastChange = /* @__PURE__ */ new Date();
          return this;
        }
        if (opts.atomic) {
          if (event === EVENTS.UNLINK) {
            this._pendingUnlinks.set(path150, [event, ...args2]);
            setTimeout(() => {
              this._pendingUnlinks.forEach((entry, path151) => {
                this.emit(...entry);
                this.emit(EVENTS.ALL, ...entry);
                this._pendingUnlinks.delete(path151);
              });
            }, typeof opts.atomic === "number" ? opts.atomic : 100);
            return this;
          }
          if (event === EVENTS.ADD && this._pendingUnlinks.has(path150)) {
            event = EVENTS.CHANGE;
            this._pendingUnlinks.delete(path150);
          }
        }
        if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
          const awfEmit = /* @__PURE__ */ __name((err2, stats2) => {
            if (err2) {
              event = EVENTS.ERROR;
              args2[0] = err2;
              this.emitWithAll(event, args2);
            } else if (stats2) {
              if (args2.length > 1) {
                args2[1] = stats2;
              } else {
                args2.push(stats2);
              }
              this.emitWithAll(event, args2);
            }
          }, "awfEmit");
          this._awaitWriteFinish(path150, awf.stabilityThreshold, event, awfEmit);
          return this;
        }
        if (event === EVENTS.CHANGE) {
          const isThrottled = !this._throttle(EVENTS.CHANGE, path150, 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, path150) : path150;
          let stats2;
          try {
            stats2 = await stat6(fullPath);
          } catch (err2) {
          }
          if (!stats2 || this.closed)
            return;
          args2.push(stats2);
        }
        this.emitWithAll(event, args2);
        return this;
      }
      /**
       * Common handler for errors
       * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
       */
      _handleError(error40) {
        const code2 = error40 && error40.code;
        if (error40 && code2 !== "ENOENT" && code2 !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code2 !== "EPERM" && code2 !== "EACCES")) {
          this.emit(EVENTS.ERROR, error40);
        }
        return error40 || 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, path150, 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(path150);
        if (actionPath) {
          actionPath.count++;
          return false;
        }
        let timeoutObject;
        const clear = /* @__PURE__ */ __name(() => {
          const item = action.get(path150);
          const count = item ? item.count : 0;
          action.delete(path150);
          clearTimeout(timeoutObject);
          if (item)
            clearTimeout(item.timeoutObject);
          return count;
        }, "clear");
        timeoutObject = setTimeout(clear, timeout2);
        const thr = { timeoutObject, clear, count: 0 };
        action.set(path150, 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(path150, threshold, event, awfEmit) {
        const awf = this.options.awaitWriteFinish;
        if (typeof awf !== "object")
          return;
        const pollInterval = awf.pollInterval;
        let timeoutHandler;
        let fullPath = path150;
        if (this.options.cwd && !sysPath2.isAbsolute(path150)) {
          fullPath = sysPath2.join(this.options.cwd, path150);
        }
        const now = /* @__PURE__ */ new Date();
        const writes = this._pendingWrites;
        function awaitWriteFinishFn(prevStat) {
          statcb(fullPath, (err2, curStat) => {
            if (err2 || !writes.has(path150)) {
              if (err2 && err2.code !== "ENOENT")
                awfEmit(err2);
              return;
            }
            const now2 = Number(/* @__PURE__ */ new Date());
            if (prevStat && curStat.size !== prevStat.size) {
              writes.get(path150).lastChange = now2;
            }
            const pw = writes.get(path150);
            const df = now2 - pw.lastChange;
            if (df >= threshold) {
              writes.delete(path150);
              awfEmit(void 0, curStat);
            } else {
              timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
            }
          });
        }
        __name(awaitWriteFinishFn, "awaitWriteFinishFn");
        if (!writes.has(path150)) {
          writes.set(path150, {
            lastChange: now,
            cancelWait: /* @__PURE__ */ __name(() => {
              writes.delete(path150);
              clearTimeout(timeoutHandler);
              return event;
            }, "cancelWait")
          });
          timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
        }
      }
      /**
       * Determines whether user has asked to ignore this path.
       */
      _isIgnored(path150, stats) {
        if (this.options.atomic && DOT_RE.test(path150))
          return true;
        if (!this._userIgnored) {
          const { cwd: cwd6 } = this.options;
          const ign = this.options.ignored;
          const ignored = (ign || []).map(normalizeIgnored(cwd6));
          const ignoredPaths = [...this._ignoredPaths];
          const list3 = [...ignoredPaths.map(normalizeIgnored(cwd6)), ...ignored];
          this._userIgnored = anymatch(list3, void 0);
        }
        return this._userIgnored(path150, stats);
      }
      _isntIgnored(path150, stat14) {
        return !this._isIgnored(path150, stat14);
      }
      /**
       * Provides a set of common helpers and properties relating to symlink handling.
       * @param path file or directory pattern being watched
       */
      _getWatchHelpers(path150) {
        return new WatchHelper(path150, 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 path150 = sysPath2.join(directory, item);
        const fullPath = sysPath2.resolve(path150);
        isDirectory = isDirectory != null ? isDirectory : this._watched.has(path150) || this._watched.has(fullPath);
        if (!this._throttle("remove", path150, 100))
          return;
        if (!isDirectory && this._watched.size === 1) {
          this.add(directory, item, true);
        }
        const wp = this._getWatchedDir(path150);
        const nestedDirectoryChildren = wp.getChildren();
        nestedDirectoryChildren.forEach((nested) => this._remove(path150, 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 = path150;
        if (this.options.cwd)
          relPath = sysPath2.relative(this.options.cwd, path150);
        if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
          const event = this._pendingWrites.get(relPath).cancelWait();
          if (event === EVENTS.ADD)
            return;
        }
        this._watched.delete(path150);
        this._watched.delete(fullPath);
        const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
        if (wasTracked && !this._isIgnored(path150))
          this._emit(eventName, path150);
        this._closePath(path150);
      }
      /**
       * Closes all watchers for a path
       */
      _closePath(path150) {
        this._closeFile(path150);
        const dir = sysPath2.dirname(path150);
        this._getWatchedDir(dir).remove(sysPath2.basename(path150));
      }
      /**
       * Closes only file-specific watchers
       */
      _closeFile(path150) {
        const closers = this._closers.get(path150);
        if (!closers)
          return;
        closers.forEach((closer) => closer());
        this._closers.delete(path150);
      }
      _addPathCloser(path150, closer) {
        if (!closer)
          return;
        let list3 = this._closers.get(path150);
        if (!list3) {
          list3 = [];
          this._closers.set(path150, list3);
        }
        list3.push(closer);
      }
      _readdirp(root, opts) {
        if (this.closed)
          return;
        const options2 = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
        let stream5 = readdirp(root, options2);
        this._streams.add(stream5);
        stream5.once(STR_CLOSE, () => {
          stream5 = void 0;
        });
        stream5.once(STR_END, () => {
          if (stream5) {
            this._streams.delete(stream5);
            stream5 = void 0;
          }
        });
        return stream5;
      }
    };
    __name(watch, "watch");
  }
});

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

// node_modules/yaml/dist/nodes/identity.js
var require_identity = __commonJS({
  "node_modules/yaml/dist/nodes/identity.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var ALIAS = Symbol.for("yaml.alias");
    var DOC = Symbol.for("yaml.document");
    var MAP = Symbol.for("yaml.map");
    var PAIR = Symbol.for("yaml.pair");
    var SCALAR = Symbol.for("yaml.scalar");
    var SEQ = Symbol.for("yaml.seq");
    var NODE_TYPE = Symbol.for("yaml.node.type");
    var isAlias = /* @__PURE__ */ __name((node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS, "isAlias");
    var isDocument2 = /* @__PURE__ */ __name((node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC, "isDocument");
    var isMap = /* @__PURE__ */ __name((node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP, "isMap");
    var isPair = /* @__PURE__ */ __name((node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR, "isPair");
    var isScalar = /* @__PURE__ */ __name((node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR, "isScalar");
    var isSeq = /* @__PURE__ */ __name((node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ, "isSeq");
    function isCollection(node) {
      if (node && typeof node === "object")
        switch (node[NODE_TYPE]) {
          case MAP:
          case SEQ:
            return true;
        }
      return false;
    }
    __name(isCollection, "isCollection");
    function isNode3(node) {
      if (node && typeof node === "object")
        switch (node[NODE_TYPE]) {
          case ALIAS:
          case MAP:
          case SCALAR:
          case SEQ:
            return true;
        }
      return false;
    }
    __name(isNode3, "isNode");
    var hasAnchor = /* @__PURE__ */ __name((node) => (isScalar(node) || isCollection(node)) && !!node.anchor, "hasAnchor");
    exports2.ALIAS = ALIAS;
    exports2.DOC = DOC;
    exports2.MAP = MAP;
    exports2.NODE_TYPE = NODE_TYPE;
    exports2.PAIR = PAIR;
    exports2.SCALAR = SCALAR;
    exports2.SEQ = SEQ;
    exports2.hasAnchor = hasAnchor;
    exports2.isAlias = isAlias;
    exports2.isCollection = isCollection;
    exports2.isDocument = isDocument2;
    exports2.isMap = isMap;
    exports2.isNode = isNode3;
    exports2.isPair = isPair;
    exports2.isScalar = isScalar;
    exports2.isSeq = isSeq;
  }
});

// node_modules/yaml/dist/visit.js
var require_visit = __commonJS({
  "node_modules/yaml/dist/visit.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var BREAK = Symbol("break visit");
    var SKIP2 = Symbol("skip children");
    var REMOVE = Symbol("remove node");
    function visit(node, visitor) {
      const visitor_ = initVisitor(visitor);
      if (identity.isDocument(node)) {
        const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
        if (cd === REMOVE)
          node.contents = null;
      } else
        visit_(null, node, visitor_, Object.freeze([]));
    }
    __name(visit, "visit");
    visit.BREAK = BREAK;
    visit.SKIP = SKIP2;
    visit.REMOVE = REMOVE;
    function visit_(key, node, visitor, path150) {
      const ctrl = callVisitor(key, node, visitor, path150);
      if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
        replaceNode(key, path150, ctrl);
        return visit_(key, ctrl, visitor, path150);
      }
      if (typeof ctrl !== "symbol") {
        if (identity.isCollection(node)) {
          path150 = Object.freeze(path150.concat(node));
          for (let i4 = 0; i4 < node.items.length; ++i4) {
            const ci = visit_(i4, node.items[i4], visitor, path150);
            if (typeof ci === "number")
              i4 = ci - 1;
            else if (ci === BREAK)
              return BREAK;
            else if (ci === REMOVE) {
              node.items.splice(i4, 1);
              i4 -= 1;
            }
          }
        } else if (identity.isPair(node)) {
          path150 = Object.freeze(path150.concat(node));
          const ck = visit_("key", node.key, visitor, path150);
          if (ck === BREAK)
            return BREAK;
          else if (ck === REMOVE)
            node.key = null;
          const cv = visit_("value", node.value, visitor, path150);
          if (cv === BREAK)
            return BREAK;
          else if (cv === REMOVE)
            node.value = null;
        }
      }
      return ctrl;
    }
    __name(visit_, "visit_");
    async function visitAsync(node, visitor) {
      const visitor_ = initVisitor(visitor);
      if (identity.isDocument(node)) {
        const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
        if (cd === REMOVE)
          node.contents = null;
      } else
        await visitAsync_(null, node, visitor_, Object.freeze([]));
    }
    __name(visitAsync, "visitAsync");
    visitAsync.BREAK = BREAK;
    visitAsync.SKIP = SKIP2;
    visitAsync.REMOVE = REMOVE;
    async function visitAsync_(key, node, visitor, path150) {
      const ctrl = await callVisitor(key, node, visitor, path150);
      if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
        replaceNode(key, path150, ctrl);
        return visitAsync_(key, ctrl, visitor, path150);
      }
      if (typeof ctrl !== "symbol") {
        if (identity.isCollection(node)) {
          path150 = Object.freeze(path150.concat(node));
          for (let i4 = 0; i4 < node.items.length; ++i4) {
            const ci = await visitAsync_(i4, node.items[i4], visitor, path150);
            if (typeof ci === "number")
              i4 = ci - 1;
            else if (ci === BREAK)
              return BREAK;
            else if (ci === REMOVE) {
              node.items.splice(i4, 1);
              i4 -= 1;
            }
          }
        } else if (identity.isPair(node)) {
          path150 = Object.freeze(path150.concat(node));
          const ck = await visitAsync_("key", node.key, visitor, path150);
          if (ck === BREAK)
            return BREAK;
          else if (ck === REMOVE)
            node.key = null;
          const cv = await visitAsync_("value", node.value, visitor, path150);
          if (cv === BREAK)
            return BREAK;
          else if (cv === REMOVE)
            node.value = null;
        }
      }
      return ctrl;
    }
    __name(visitAsync_, "visitAsync_");
    function initVisitor(visitor) {
      if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
        return Object.assign({
          Alias: visitor.Node,
          Map: visitor.Node,
          Scalar: visitor.Node,
          Seq: visitor.Node
        }, visitor.Value && {
          Map: visitor.Value,
          Scalar: visitor.Value,
          Seq: visitor.Value
        }, visitor.Collection && {
          Map: visitor.Collection,
          Seq: visitor.Collection
        }, visitor);
      }
      return visitor;
    }
    __name(initVisitor, "initVisitor");
    function callVisitor(key, node, visitor, path150) {
      if (typeof visitor === "function")
        return visitor(key, node, path150);
      if (identity.isMap(node))
        return visitor.Map?.(key, node, path150);
      if (identity.isSeq(node))
        return visitor.Seq?.(key, node, path150);
      if (identity.isPair(node))
        return visitor.Pair?.(key, node, path150);
      if (identity.isScalar(node))
        return visitor.Scalar?.(key, node, path150);
      if (identity.isAlias(node))
        return visitor.Alias?.(key, node, path150);
      return void 0;
    }
    __name(callVisitor, "callVisitor");
    function replaceNode(key, path150, node) {
      const parent = path150[path150.length - 1];
      if (identity.isCollection(parent)) {
        parent.items[key] = node;
      } else if (identity.isPair(parent)) {
        if (key === "key")
          parent.key = node;
        else
          parent.value = node;
      } else if (identity.isDocument(parent)) {
        parent.contents = node;
      } else {
        const pt2 = identity.isAlias(parent) ? "alias" : "scalar";
        throw new Error(`Cannot replace node with ${pt2} parent`);
      }
    }
    __name(replaceNode, "replaceNode");
    exports2.visit = visit;
    exports2.visitAsync = visitAsync;
  }
});

// node_modules/yaml/dist/doc/directives.js
var require_directives = __commonJS({
  "node_modules/yaml/dist/doc/directives.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var visit = require_visit();
    var escapeChars = {
      "!": "%21",
      ",": "%2C",
      "[": "%5B",
      "]": "%5D",
      "{": "%7B",
      "}": "%7D"
    };
    var escapeTagName = /* @__PURE__ */ __name((tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]), "escapeTagName");
    var Directives = class _Directives {
      static {
        __name(this, "Directives");
      }
      constructor(yaml3, tags) {
        this.docStart = null;
        this.docEnd = false;
        this.yaml = Object.assign({}, _Directives.defaultYaml, yaml3);
        this.tags = Object.assign({}, _Directives.defaultTags, tags);
      }
      clone() {
        const copy = new _Directives(this.yaml, this.tags);
        copy.docStart = this.docStart;
        return copy;
      }
      /**
       * During parsing, get a Directives instance for the current document and
       * update the stream state according to the current version's spec.
       */
      atDocument() {
        const res = new _Directives(this.yaml, this.tags);
        switch (this.yaml.version) {
          case "1.1":
            this.atNextDocument = true;
            break;
          case "1.2":
            this.atNextDocument = false;
            this.yaml = {
              explicit: _Directives.defaultYaml.explicit,
              version: "1.2"
            };
            this.tags = Object.assign({}, _Directives.defaultTags);
            break;
        }
        return res;
      }
      /**
       * @param onError - May be called even if the action was successful
       * @returns `true` on success
       */
      add(line, onError2) {
        if (this.atNextDocument) {
          this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" };
          this.tags = Object.assign({}, _Directives.defaultTags);
          this.atNextDocument = false;
        }
        const parts2 = line.trim().split(/[ \t]+/);
        const name4 = parts2.shift();
        switch (name4) {
          case "%TAG": {
            if (parts2.length !== 2) {
              onError2(0, "%TAG directive should contain exactly two parts");
              if (parts2.length < 2)
                return false;
            }
            const [handle2, prefix] = parts2;
            this.tags[handle2] = prefix;
            return true;
          }
          case "%YAML": {
            this.yaml.explicit = true;
            if (parts2.length !== 1) {
              onError2(0, "%YAML directive should contain exactly one part");
              return false;
            }
            const [version2] = parts2;
            if (version2 === "1.1" || version2 === "1.2") {
              this.yaml.version = version2;
              return true;
            } else {
              const isValid2 = /^\d+\.\d+$/.test(version2);
              onError2(6, `Unsupported YAML version ${version2}`, isValid2);
              return false;
            }
          }
          default:
            onError2(0, `Unknown directive ${name4}`, true);
            return false;
        }
      }
      /**
       * Resolves a tag, matching handles to those defined in %TAG directives.
       *
       * @returns Resolved tag, which may also be the non-specific tag `'!'` or a
       *   `'!local'` tag, or `null` if unresolvable.
       */
      tagName(source2, onError2) {
        if (source2 === "!")
          return "!";
        if (source2[0] !== "!") {
          onError2(`Not a valid tag: ${source2}`);
          return null;
        }
        if (source2[1] === "<") {
          const verbatim = source2.slice(2, -1);
          if (verbatim === "!" || verbatim === "!!") {
            onError2(`Verbatim tags aren't resolved, so ${source2} is invalid.`);
            return null;
          }
          if (source2[source2.length - 1] !== ">")
            onError2("Verbatim tags must end with a >");
          return verbatim;
        }
        const [, handle2, suffix] = source2.match(/^(.*!)([^!]*)$/s);
        if (!suffix)
          onError2(`The ${source2} tag has no suffix`);
        const prefix = this.tags[handle2];
        if (prefix) {
          try {
            return prefix + decodeURIComponent(suffix);
          } catch (error40) {
            onError2(String(error40));
            return null;
          }
        }
        if (handle2 === "!")
          return source2;
        onError2(`Could not resolve tag: ${source2}`);
        return null;
      }
      /**
       * Given a fully resolved tag, returns its printable string form,
       * taking into account current tag prefixes and defaults.
       */
      tagString(tag2) {
        for (const [handle2, prefix] of Object.entries(this.tags)) {
          if (tag2.startsWith(prefix))
            return handle2 + escapeTagName(tag2.substring(prefix.length));
        }
        return tag2[0] === "!" ? tag2 : `!<${tag2}>`;
      }
      toString(doc) {
        const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
        const tagEntries = Object.entries(this.tags);
        let tagNames;
        if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {
          const tags = {};
          visit.visit(doc.contents, (_key, node) => {
            if (identity.isNode(node) && node.tag)
              tags[node.tag] = true;
          });
          tagNames = Object.keys(tags);
        } else
          tagNames = [];
        for (const [handle2, prefix] of tagEntries) {
          if (handle2 === "!!" && prefix === "tag:yaml.org,2002:")
            continue;
          if (!doc || tagNames.some((tn) => tn.startsWith(prefix)))
            lines.push(`%TAG ${handle2} ${prefix}`);
        }
        return lines.join("\n");
      }
    };
    Directives.defaultYaml = { explicit: false, version: "1.2" };
    Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
    exports2.Directives = Directives;
  }
});

// node_modules/yaml/dist/doc/anchors.js
var require_anchors = __commonJS({
  "node_modules/yaml/dist/doc/anchors.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var visit = require_visit();
    function anchorIsValid(anchor) {
      if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
        const sa = JSON.stringify(anchor);
        const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
        throw new Error(msg);
      }
      return true;
    }
    __name(anchorIsValid, "anchorIsValid");
    function anchorNames(root) {
      const anchors = /* @__PURE__ */ new Set();
      visit.visit(root, {
        Value(_key, node) {
          if (node.anchor)
            anchors.add(node.anchor);
        }
      });
      return anchors;
    }
    __name(anchorNames, "anchorNames");
    function findNewAnchor(prefix, exclude) {
      for (let i4 = 1; true; ++i4) {
        const name4 = `${prefix}${i4}`;
        if (!exclude.has(name4))
          return name4;
      }
    }
    __name(findNewAnchor, "findNewAnchor");
    function createNodeAnchors(doc, prefix) {
      const aliasObjects = [];
      const sourceObjects = /* @__PURE__ */ new Map();
      let prevAnchors = null;
      return {
        onAnchor: /* @__PURE__ */ __name((source2) => {
          aliasObjects.push(source2);
          prevAnchors ?? (prevAnchors = anchorNames(doc));
          const anchor = findNewAnchor(prefix, prevAnchors);
          prevAnchors.add(anchor);
          return anchor;
        }, "onAnchor"),
        /**
         * With circular references, the source node is only resolved after all
         * of its child nodes are. This is why anchors are set only after all of
         * the nodes have been created.
         */
        setAnchors: /* @__PURE__ */ __name(() => {
          for (const source2 of aliasObjects) {
            const ref = sourceObjects.get(source2);
            if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {
              ref.node.anchor = ref.anchor;
            } else {
              const error40 = new Error("Failed to resolve repeated object (this should not happen)");
              error40.source = source2;
              throw error40;
            }
          }
        }, "setAnchors"),
        sourceObjects
      };
    }
    __name(createNodeAnchors, "createNodeAnchors");
    exports2.anchorIsValid = anchorIsValid;
    exports2.anchorNames = anchorNames;
    exports2.createNodeAnchors = createNodeAnchors;
    exports2.findNewAnchor = findNewAnchor;
  }
});

// node_modules/yaml/dist/doc/applyReviver.js
var require_applyReviver = __commonJS({
  "node_modules/yaml/dist/doc/applyReviver.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    function applyReviver(reviver, obj, key, val) {
      if (val && typeof val === "object") {
        if (Array.isArray(val)) {
          for (let i4 = 0, len = val.length; i4 < len; ++i4) {
            const v0 = val[i4];
            const v1 = applyReviver(reviver, val, String(i4), v0);
            if (v1 === void 0)
              delete val[i4];
            else if (v1 !== v0)
              val[i4] = v1;
          }
        } else if (val instanceof Map) {
          for (const k2 of Array.from(val.keys())) {
            const v0 = val.get(k2);
            const v1 = applyReviver(reviver, val, k2, v0);
            if (v1 === void 0)
              val.delete(k2);
            else if (v1 !== v0)
              val.set(k2, v1);
          }
        } else if (val instanceof Set) {
          for (const v0 of Array.from(val)) {
            const v1 = applyReviver(reviver, val, v0, v0);
            if (v1 === void 0)
              val.delete(v0);
            else if (v1 !== v0) {
              val.delete(v0);
              val.add(v1);
            }
          }
        } else {
          for (const [k2, v0] of Object.entries(val)) {
            const v1 = applyReviver(reviver, val, k2, v0);
            if (v1 === void 0)
              delete val[k2];
            else if (v1 !== v0)
              val[k2] = v1;
          }
        }
      }
      return reviver.call(obj, key, val);
    }
    __name(applyReviver, "applyReviver");
    exports2.applyReviver = applyReviver;
  }
});

// node_modules/yaml/dist/nodes/toJS.js
var require_toJS = __commonJS({
  "node_modules/yaml/dist/nodes/toJS.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    function toJS(value, arg, ctx) {
      if (Array.isArray(value))
        return value.map((v2, i4) => toJS(v2, String(i4), ctx));
      if (value && typeof value.toJSON === "function") {
        if (!ctx || !identity.hasAnchor(value))
          return value.toJSON(arg, ctx);
        const data = { aliasCount: 0, count: 1, res: void 0 };
        ctx.anchors.set(value, data);
        ctx.onCreate = (res2) => {
          data.res = res2;
          delete ctx.onCreate;
        };
        const res = value.toJSON(arg, ctx);
        if (ctx.onCreate)
          ctx.onCreate(res);
        return res;
      }
      if (typeof value === "bigint" && !ctx?.keep)
        return Number(value);
      return value;
    }
    __name(toJS, "toJS");
    exports2.toJS = toJS;
  }
});

// node_modules/yaml/dist/nodes/Node.js
var require_Node = __commonJS({
  "node_modules/yaml/dist/nodes/Node.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var applyReviver = require_applyReviver();
    var identity = require_identity();
    var toJS = require_toJS();
    var NodeBase = class {
      static {
        __name(this, "NodeBase");
      }
      constructor(type) {
        Object.defineProperty(this, identity.NODE_TYPE, { value: type });
      }
      /** Create a copy of this node.  */
      clone() {
        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
        if (this.range)
          copy.range = this.range.slice();
        return copy;
      }
      /** A plain JavaScript representation of this node. */
      toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
        if (!identity.isDocument(doc))
          throw new TypeError("A document argument is required");
        const ctx = {
          anchors: /* @__PURE__ */ new Map(),
          doc,
          keep: true,
          mapAsMap: mapAsMap === true,
          mapKeyWarned: false,
          maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
        };
        const res = toJS.toJS(this, "", ctx);
        if (typeof onAnchor === "function")
          for (const { count, res: res2 } of ctx.anchors.values())
            onAnchor(res2, count);
        return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
      }
    };
    exports2.NodeBase = NodeBase;
  }
});

// node_modules/yaml/dist/nodes/Alias.js
var require_Alias = __commonJS({
  "node_modules/yaml/dist/nodes/Alias.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var anchors = require_anchors();
    var visit = require_visit();
    var identity = require_identity();
    var Node5 = require_Node();
    var toJS = require_toJS();
    var Alias = class extends Node5.NodeBase {
      static {
        __name(this, "Alias");
      }
      constructor(source2) {
        super(identity.ALIAS);
        this.source = source2;
        Object.defineProperty(this, "tag", {
          set() {
            throw new Error("Alias nodes cannot have tags");
          }
        });
      }
      /**
       * Resolve the value of this alias within `doc`, finding the last
       * instance of the `source` anchor before this node.
       */
      resolve(doc, ctx) {
        let nodes;
        if (ctx?.aliasResolveCache) {
          nodes = ctx.aliasResolveCache;
        } else {
          nodes = [];
          visit.visit(doc, {
            Node: /* @__PURE__ */ __name((_key, node) => {
              if (identity.isAlias(node) || identity.hasAnchor(node))
                nodes.push(node);
            }, "Node")
          });
          if (ctx)
            ctx.aliasResolveCache = nodes;
        }
        let found = void 0;
        for (const node of nodes) {
          if (node === this)
            break;
          if (node.anchor === this.source)
            found = node;
        }
        return found;
      }
      toJSON(_arg, ctx) {
        if (!ctx)
          return { source: this.source };
        const { anchors: anchors2, doc, maxAliasCount } = ctx;
        const source2 = this.resolve(doc, ctx);
        if (!source2) {
          const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
          throw new ReferenceError(msg);
        }
        let data = anchors2.get(source2);
        if (!data) {
          toJS.toJS(source2, null, ctx);
          data = anchors2.get(source2);
        }
        if (!data || data.res === void 0) {
          const msg = "This should not happen: Alias anchor was not resolved?";
          throw new ReferenceError(msg);
        }
        if (maxAliasCount >= 0) {
          data.count += 1;
          if (data.aliasCount === 0)
            data.aliasCount = getAliasCount(doc, source2, anchors2);
          if (data.count * data.aliasCount > maxAliasCount) {
            const msg = "Excessive alias count indicates a resource exhaustion attack";
            throw new ReferenceError(msg);
          }
        }
        return data.res;
      }
      toString(ctx, _onComment, _onChompKeep) {
        const src = `*${this.source}`;
        if (ctx) {
          anchors.anchorIsValid(this.source);
          if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
            const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
            throw new Error(msg);
          }
          if (ctx.implicitKey)
            return `${src} `;
        }
        return src;
      }
    };
    function getAliasCount(doc, node, anchors2) {
      if (identity.isAlias(node)) {
        const source2 = node.resolve(doc);
        const anchor = anchors2 && source2 && anchors2.get(source2);
        return anchor ? anchor.count * anchor.aliasCount : 0;
      } else if (identity.isCollection(node)) {
        let count = 0;
        for (const item of node.items) {
          const c4 = getAliasCount(doc, item, anchors2);
          if (c4 > count)
            count = c4;
        }
        return count;
      } else if (identity.isPair(node)) {
        const kc = getAliasCount(doc, node.key, anchors2);
        const vc = getAliasCount(doc, node.value, anchors2);
        return Math.max(kc, vc);
      }
      return 1;
    }
    __name(getAliasCount, "getAliasCount");
    exports2.Alias = Alias;
  }
});

// node_modules/yaml/dist/nodes/Scalar.js
var require_Scalar = __commonJS({
  "node_modules/yaml/dist/nodes/Scalar.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var Node5 = require_Node();
    var toJS = require_toJS();
    var isScalarValue = /* @__PURE__ */ __name((value) => !value || typeof value !== "function" && typeof value !== "object", "isScalarValue");
    var Scalar = class extends Node5.NodeBase {
      static {
        __name(this, "Scalar");
      }
      constructor(value) {
        super(identity.SCALAR);
        this.value = value;
      }
      toJSON(arg, ctx) {
        return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
      }
      toString() {
        return String(this.value);
      }
    };
    Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
    Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
    Scalar.PLAIN = "PLAIN";
    Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
    Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
    exports2.Scalar = Scalar;
    exports2.isScalarValue = isScalarValue;
  }
});

// node_modules/yaml/dist/doc/createNode.js
var require_createNode = __commonJS({
  "node_modules/yaml/dist/doc/createNode.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Alias = require_Alias();
    var identity = require_identity();
    var Scalar = require_Scalar();
    var defaultTagPrefix = "tag:yaml.org,2002:";
    function findTagObject(value, tagName, tags) {
      if (tagName) {
        const match2 = tags.filter((t5) => t5.tag === tagName);
        const tagObj = match2.find((t5) => !t5.format) ?? match2[0];
        if (!tagObj)
          throw new Error(`Tag ${tagName} not found`);
        return tagObj;
      }
      return tags.find((t5) => t5.identify?.(value) && !t5.format);
    }
    __name(findTagObject, "findTagObject");
    function createNode2(value, tagName, ctx) {
      if (identity.isDocument(value))
        value = value.contents;
      if (identity.isNode(value))
        return value;
      if (identity.isPair(value)) {
        const map3 = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);
        map3.items.push(value);
        return map3;
      }
      if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) {
        value = value.valueOf();
      }
      const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
      let ref = void 0;
      if (aliasDuplicateObjects && value && typeof value === "object") {
        ref = sourceObjects.get(value);
        if (ref) {
          ref.anchor ?? (ref.anchor = onAnchor(value));
          return new Alias.Alias(ref.anchor);
        } else {
          ref = { anchor: null, node: null };
          sourceObjects.set(value, ref);
        }
      }
      if (tagName?.startsWith("!!"))
        tagName = defaultTagPrefix + tagName.slice(2);
      let tagObj = findTagObject(value, tagName, schema.tags);
      if (!tagObj) {
        if (value && typeof value.toJSON === "function") {
          value = value.toJSON();
        }
        if (!value || typeof value !== "object") {
          const node2 = new Scalar.Scalar(value);
          if (ref)
            ref.node = node2;
          return node2;
        }
        tagObj = value instanceof Map ? schema[identity.MAP] : Symbol.iterator in Object(value) ? schema[identity.SEQ] : schema[identity.MAP];
      }
      if (onTagObj) {
        onTagObj(tagObj);
        delete ctx.onTagObj;
      }
      const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value);
      if (tagName)
        node.tag = tagName;
      else if (!tagObj.default)
        node.tag = tagObj.tag;
      if (ref)
        ref.node = node;
      return node;
    }
    __name(createNode2, "createNode");
    exports2.createNode = createNode2;
  }
});

// node_modules/yaml/dist/nodes/Collection.js
var require_Collection = __commonJS({
  "node_modules/yaml/dist/nodes/Collection.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var createNode2 = require_createNode();
    var identity = require_identity();
    var Node5 = require_Node();
    function collectionFromPath(schema, path150, value) {
      let v2 = value;
      for (let i4 = path150.length - 1; i4 >= 0; --i4) {
        const k2 = path150[i4];
        if (typeof k2 === "number" && Number.isInteger(k2) && k2 >= 0) {
          const a2 = [];
          a2[k2] = v2;
          v2 = a2;
        } else {
          v2 = /* @__PURE__ */ new Map([[k2, v2]]);
        }
      }
      return createNode2.createNode(v2, void 0, {
        aliasDuplicateObjects: false,
        keepUndefined: false,
        onAnchor: /* @__PURE__ */ __name(() => {
          throw new Error("This should not happen, please report a bug.");
        }, "onAnchor"),
        schema,
        sourceObjects: /* @__PURE__ */ new Map()
      });
    }
    __name(collectionFromPath, "collectionFromPath");
    var isEmptyPath = /* @__PURE__ */ __name((path150) => path150 == null || typeof path150 === "object" && !!path150[Symbol.iterator]().next().done, "isEmptyPath");
    var Collection = class extends Node5.NodeBase {
      static {
        __name(this, "Collection");
      }
      constructor(type, schema) {
        super(type);
        Object.defineProperty(this, "schema", {
          value: schema,
          configurable: true,
          enumerable: false,
          writable: true
        });
      }
      /**
       * Create a copy of this collection.
       *
       * @param schema - If defined, overwrites the original's schema
       */
      clone(schema) {
        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
        if (schema)
          copy.schema = schema;
        copy.items = copy.items.map((it3) => identity.isNode(it3) || identity.isPair(it3) ? it3.clone(schema) : it3);
        if (this.range)
          copy.range = this.range.slice();
        return copy;
      }
      /**
       * Adds a value to the collection. For `!!map` and `!!omap` the value must
       * be a Pair instance or a `{ key, value }` object, which may not have a key
       * that already exists in the map.
       */
      addIn(path150, value) {
        if (isEmptyPath(path150))
          this.add(value);
        else {
          const [key, ...rest] = path150;
          const node = this.get(key, true);
          if (identity.isCollection(node))
            node.addIn(rest, value);
          else if (node === void 0 && this.schema)
            this.set(key, collectionFromPath(this.schema, rest, value));
          else
            throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
        }
      }
      /**
       * Removes a value from the collection.
       * @returns `true` if the item was found and removed.
       */
      deleteIn(path150) {
        const [key, ...rest] = path150;
        if (rest.length === 0)
          return this.delete(key);
        const node = this.get(key, true);
        if (identity.isCollection(node))
          return node.deleteIn(rest);
        else
          throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
      }
      /**
       * Returns item at `key`, or `undefined` if not found. By default unwraps
       * scalar values from their surrounding node; to disable set `keepScalar` to
       * `true` (collections are always returned intact).
       */
      getIn(path150, keepScalar) {
        const [key, ...rest] = path150;
        const node = this.get(key, true);
        if (rest.length === 0)
          return !keepScalar && identity.isScalar(node) ? node.value : node;
        else
          return identity.isCollection(node) ? node.getIn(rest, keepScalar) : void 0;
      }
      hasAllNullValues(allowScalar) {
        return this.items.every((node) => {
          if (!identity.isPair(node))
            return false;
          const n3 = node.value;
          return n3 == null || allowScalar && identity.isScalar(n3) && n3.value == null && !n3.commentBefore && !n3.comment && !n3.tag;
        });
      }
      /**
       * Checks if the collection includes a value with the key `key`.
       */
      hasIn(path150) {
        const [key, ...rest] = path150;
        if (rest.length === 0)
          return this.has(key);
        const node = this.get(key, true);
        return identity.isCollection(node) ? node.hasIn(rest) : false;
      }
      /**
       * Sets a value in this collection. For `!!set`, `value` needs to be a
       * boolean to add/remove the item from the set.
       */
      setIn(path150, value) {
        const [key, ...rest] = path150;
        if (rest.length === 0) {
          this.set(key, value);
        } else {
          const node = this.get(key, true);
          if (identity.isCollection(node))
            node.setIn(rest, value);
          else if (node === void 0 && this.schema)
            this.set(key, collectionFromPath(this.schema, rest, value));
          else
            throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
        }
      }
    };
    exports2.Collection = Collection;
    exports2.collectionFromPath = collectionFromPath;
    exports2.isEmptyPath = isEmptyPath;
  }
});

// node_modules/yaml/dist/stringify/stringifyComment.js
var require_stringifyComment = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyComment.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var stringifyComment = /* @__PURE__ */ __name((str2) => str2.replace(/^(?!$)(?: $)?/gm, "#"), "stringifyComment");
    function indentComment(comment, indent) {
      if (/^\n+$/.test(comment))
        return comment.substring(1);
      return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
    }
    __name(indentComment, "indentComment");
    var lineComment = /* @__PURE__ */ __name((str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment, "lineComment");
    exports2.indentComment = indentComment;
    exports2.lineComment = lineComment;
    exports2.stringifyComment = stringifyComment;
  }
});

// node_modules/yaml/dist/stringify/foldFlowLines.js
var require_foldFlowLines = __commonJS({
  "node_modules/yaml/dist/stringify/foldFlowLines.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var FOLD_FLOW = "flow";
    var FOLD_BLOCK = "block";
    var FOLD_QUOTED = "quoted";
    function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
      if (!lineWidth || lineWidth < 0)
        return text;
      if (lineWidth < minContentWidth)
        minContentWidth = 0;
      const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
      if (text.length <= endStep)
        return text;
      const folds = [];
      const escapedFolds = {};
      let end = lineWidth - indent.length;
      if (typeof indentAtStart === "number") {
        if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
          folds.push(0);
        else
          end = lineWidth - indentAtStart;
      }
      let split = void 0;
      let prev = void 0;
      let overflow = false;
      let i4 = -1;
      let escStart = -1;
      let escEnd = -1;
      if (mode === FOLD_BLOCK) {
        i4 = consumeMoreIndentedLines(text, i4, indent.length);
        if (i4 !== -1)
          end = i4 + endStep;
      }
      for (let ch; ch = text[i4 += 1]; ) {
        if (mode === FOLD_QUOTED && ch === "\\") {
          escStart = i4;
          switch (text[i4 + 1]) {
            case "x":
              i4 += 3;
              break;
            case "u":
              i4 += 5;
              break;
            case "U":
              i4 += 9;
              break;
            default:
              i4 += 1;
          }
          escEnd = i4;
        }
        if (ch === "\n") {
          if (mode === FOLD_BLOCK)
            i4 = consumeMoreIndentedLines(text, i4, indent.length);
          end = i4 + indent.length + endStep;
          split = void 0;
        } else {
          if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== "	") {
            const next = text[i4 + 1];
            if (next && next !== " " && next !== "\n" && next !== "	")
              split = i4;
          }
          if (i4 >= end) {
            if (split) {
              folds.push(split);
              end = split + endStep;
              split = void 0;
            } else if (mode === FOLD_QUOTED) {
              while (prev === " " || prev === "	") {
                prev = ch;
                ch = text[i4 += 1];
                overflow = true;
              }
              const j2 = i4 > escEnd + 1 ? i4 - 2 : escStart - 1;
              if (escapedFolds[j2])
                return text;
              folds.push(j2);
              escapedFolds[j2] = true;
              end = j2 + endStep;
              split = void 0;
            } else {
              overflow = true;
            }
          }
        }
        prev = ch;
      }
      if (overflow && onOverflow)
        onOverflow();
      if (folds.length === 0)
        return text;
      if (onFold)
        onFold();
      let res = text.slice(0, folds[0]);
      for (let i5 = 0; i5 < folds.length; ++i5) {
        const fold = folds[i5];
        const end2 = folds[i5 + 1] || text.length;
        if (fold === 0)
          res = `
${indent}${text.slice(0, end2)}`;
        else {
          if (mode === FOLD_QUOTED && escapedFolds[fold])
            res += `${text[fold]}\\`;
          res += `
${indent}${text.slice(fold + 1, end2)}`;
        }
      }
      return res;
    }
    __name(foldFlowLines, "foldFlowLines");
    function consumeMoreIndentedLines(text, i4, indent) {
      let end = i4;
      let start2 = i4 + 1;
      let ch = text[start2];
      while (ch === " " || ch === "	") {
        if (i4 < start2 + indent) {
          ch = text[++i4];
        } else {
          do {
            ch = text[++i4];
          } while (ch && ch !== "\n");
          end = i4;
          start2 = i4 + 1;
          ch = text[start2];
        }
      }
      return end;
    }
    __name(consumeMoreIndentedLines, "consumeMoreIndentedLines");
    exports2.FOLD_BLOCK = FOLD_BLOCK;
    exports2.FOLD_FLOW = FOLD_FLOW;
    exports2.FOLD_QUOTED = FOLD_QUOTED;
    exports2.foldFlowLines = foldFlowLines;
  }
});

// node_modules/yaml/dist/stringify/stringifyString.js
var require_stringifyString = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyString.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Scalar = require_Scalar();
    var foldFlowLines = require_foldFlowLines();
    var getFoldOptions = /* @__PURE__ */ __name((ctx, isBlock) => ({
      indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
      lineWidth: ctx.options.lineWidth,
      minContentWidth: ctx.options.minContentWidth
    }), "getFoldOptions");
    var containsDocumentMarker = /* @__PURE__ */ __name((str2) => /^(%|---|\.\.\.)/m.test(str2), "containsDocumentMarker");
    function lineLengthOverLimit(str2, lineWidth, indentLength) {
      if (!lineWidth || lineWidth < 0)
        return false;
      const limit2 = lineWidth - indentLength;
      const strLen = str2.length;
      if (strLen <= limit2)
        return false;
      for (let i4 = 0, start2 = 0; i4 < strLen; ++i4) {
        if (str2[i4] === "\n") {
          if (i4 - start2 > limit2)
            return true;
          start2 = i4 + 1;
          if (strLen - start2 <= limit2)
            return false;
        }
      }
      return true;
    }
    __name(lineLengthOverLimit, "lineLengthOverLimit");
    function doubleQuotedString(value, ctx) {
      const json3 = JSON.stringify(value);
      if (ctx.options.doubleQuotedAsJSON)
        return json3;
      const { implicitKey } = ctx;
      const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
      const indent = ctx.indent || (containsDocumentMarker(value) ? "  " : "");
      let str2 = "";
      let start2 = 0;
      for (let i4 = 0, ch = json3[i4]; ch; ch = json3[++i4]) {
        if (ch === " " && json3[i4 + 1] === "\\" && json3[i4 + 2] === "n") {
          str2 += json3.slice(start2, i4) + "\\ ";
          i4 += 1;
          start2 = i4;
          ch = "\\";
        }
        if (ch === "\\")
          switch (json3[i4 + 1]) {
            case "u":
              {
                str2 += json3.slice(start2, i4);
                const code2 = json3.substr(i4 + 2, 4);
                switch (code2) {
                  case "0000":
                    str2 += "\\0";
                    break;
                  case "0007":
                    str2 += "\\a";
                    break;
                  case "000b":
                    str2 += "\\v";
                    break;
                  case "001b":
                    str2 += "\\e";
                    break;
                  case "0085":
                    str2 += "\\N";
                    break;
                  case "00a0":
                    str2 += "\\_";
                    break;
                  case "2028":
                    str2 += "\\L";
                    break;
                  case "2029":
                    str2 += "\\P";
                    break;
                  default:
                    if (code2.substr(0, 2) === "00")
                      str2 += "\\x" + code2.substr(2);
                    else
                      str2 += json3.substr(i4, 6);
                }
                i4 += 5;
                start2 = i4 + 1;
              }
              break;
            case "n":
              if (implicitKey || json3[i4 + 2] === '"' || json3.length < minMultiLineLength) {
                i4 += 1;
              } else {
                str2 += json3.slice(start2, i4) + "\n\n";
                while (json3[i4 + 2] === "\\" && json3[i4 + 3] === "n" && json3[i4 + 4] !== '"') {
                  str2 += "\n";
                  i4 += 2;
                }
                str2 += indent;
                if (json3[i4 + 2] === " ")
                  str2 += "\\";
                i4 += 1;
                start2 = i4 + 1;
              }
              break;
            default:
              i4 += 1;
          }
      }
      str2 = start2 ? str2 + json3.slice(start2) : json3;
      return implicitKey ? str2 : foldFlowLines.foldFlowLines(str2, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
    }
    __name(doubleQuotedString, "doubleQuotedString");
    function singleQuotedString(value, ctx) {
      if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value))
        return doubleQuotedString(value, ctx);
      const indent = ctx.indent || (containsDocumentMarker(value) ? "  " : "");
      const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
      return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
    }
    __name(singleQuotedString, "singleQuotedString");
    function quotedString(value, ctx) {
      const { singleQuote } = ctx.options;
      let qs;
      if (singleQuote === false)
        qs = doubleQuotedString;
      else {
        const hasDouble = value.includes('"');
        const hasSingle = value.includes("'");
        if (hasDouble && !hasSingle)
          qs = singleQuotedString;
        else if (hasSingle && !hasDouble)
          qs = doubleQuotedString;
        else
          qs = singleQuote ? singleQuotedString : doubleQuotedString;
      }
      return qs(value, ctx);
    }
    __name(quotedString, "quotedString");
    var blockEndNewlines;
    try {
      blockEndNewlines = new RegExp("(^|(?<!\n))\n+(?!\n|$)", "g");
    } catch {
      blockEndNewlines = /\n+(?!\n|$)/g;
    }
    function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
      const { blockQuote, commentString, lineWidth } = ctx.options;
      if (!blockQuote || /\n[\t ]+$/.test(value)) {
        return quotedString(value, ctx);
      }
      const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? "  " : "");
      const literal3 = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.Scalar.BLOCK_FOLDED ? false : type === Scalar.Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
      if (!value)
        return literal3 ? "|\n" : ">\n";
      let chomp;
      let endStart;
      for (endStart = value.length; endStart > 0; --endStart) {
        const ch = value[endStart - 1];
        if (ch !== "\n" && ch !== "	" && ch !== " ")
          break;
      }
      let end = value.substring(endStart);
      const endNlPos = end.indexOf("\n");
      if (endNlPos === -1) {
        chomp = "-";
      } else if (value === end || endNlPos !== end.length - 1) {
        chomp = "+";
        if (onChompKeep)
          onChompKeep();
      } else {
        chomp = "";
      }
      if (end) {
        value = value.slice(0, -end.length);
        if (end[end.length - 1] === "\n")
          end = end.slice(0, -1);
        end = end.replace(blockEndNewlines, `$&${indent}`);
      }
      let startWithSpace = false;
      let startEnd;
      let startNlPos = -1;
      for (startEnd = 0; startEnd < value.length; ++startEnd) {
        const ch = value[startEnd];
        if (ch === " ")
          startWithSpace = true;
        else if (ch === "\n")
          startNlPos = startEnd;
        else
          break;
      }
      let start2 = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
      if (start2) {
        value = value.substring(start2.length);
        start2 = start2.replace(/\n+/g, `$&${indent}`);
      }
      const indentSize = indent ? "2" : "1";
      let header = (startWithSpace ? indentSize : "") + chomp;
      if (comment) {
        header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
        if (onComment)
          onComment();
      }
      if (!literal3) {
        const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
        let literalFallback = false;
        const foldOptions = getFoldOptions(ctx, true);
        if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) {
          foldOptions.onOverflow = () => {
            literalFallback = true;
          };
        }
        const body2 = foldFlowLines.foldFlowLines(`${start2}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);
        if (!literalFallback)
          return `>${header}
${indent}${body2}`;
      }
      value = value.replace(/\n+/g, `$&${indent}`);
      return `|${header}
${indent}${start2}${value}${end}`;
    }
    __name(blockString, "blockString");
    function plainString(item, ctx, onComment, onChompKeep) {
      const { type, value } = item;
      const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
      if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) {
        return quotedString(value, ctx);
      }
      if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
        return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
      }
      if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes("\n")) {
        return blockString(item, ctx, onComment, onChompKeep);
      }
      if (containsDocumentMarker(value)) {
        if (indent === "") {
          ctx.forceBlockIndent = true;
          return blockString(item, ctx, onComment, onChompKeep);
        } else if (implicitKey && indent === indentStep) {
          return quotedString(value, ctx);
        }
      }
      const str2 = value.replace(/\n+/g, `$&
${indent}`);
      if (actualString) {
        const test2 = /* @__PURE__ */ __name((tag2) => tag2.default && tag2.tag !== "tag:yaml.org,2002:str" && tag2.test?.test(str2), "test");
        const { compat, tags } = ctx.doc.schema;
        if (tags.some(test2) || compat?.some(test2))
          return quotedString(value, ctx);
      }
      return implicitKey ? str2 : foldFlowLines.foldFlowLines(str2, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
    }
    __name(plainString, "plainString");
    function stringifyString(item, ctx, onComment, onChompKeep) {
      const { implicitKey, inFlow } = ctx;
      const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
      let { type } = item;
      if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
        if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
          type = Scalar.Scalar.QUOTE_DOUBLE;
      }
      const _stringify = /* @__PURE__ */ __name((_type2) => {
        switch (_type2) {
          case Scalar.Scalar.BLOCK_FOLDED:
          case Scalar.Scalar.BLOCK_LITERAL:
            return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
          case Scalar.Scalar.QUOTE_DOUBLE:
            return doubleQuotedString(ss.value, ctx);
          case Scalar.Scalar.QUOTE_SINGLE:
            return singleQuotedString(ss.value, ctx);
          case Scalar.Scalar.PLAIN:
            return plainString(ss, ctx, onComment, onChompKeep);
          default:
            return null;
        }
      }, "_stringify");
      let res = _stringify(type);
      if (res === null) {
        const { defaultKeyType, defaultStringType } = ctx.options;
        const t5 = implicitKey && defaultKeyType || defaultStringType;
        res = _stringify(t5);
        if (res === null)
          throw new Error(`Unsupported default string type ${t5}`);
      }
      return res;
    }
    __name(stringifyString, "stringifyString");
    exports2.stringifyString = stringifyString;
  }
});

// node_modules/yaml/dist/stringify/stringify.js
var require_stringify2 = __commonJS({
  "node_modules/yaml/dist/stringify/stringify.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var anchors = require_anchors();
    var identity = require_identity();
    var stringifyComment = require_stringifyComment();
    var stringifyString = require_stringifyString();
    function createStringifyContext(doc, options2) {
      const opt = Object.assign({
        blockQuote: true,
        commentString: stringifyComment.stringifyComment,
        defaultKeyType: null,
        defaultStringType: "PLAIN",
        directives: null,
        doubleQuotedAsJSON: false,
        doubleQuotedMinMultiLineLength: 40,
        falseStr: "false",
        flowCollectionPadding: true,
        indentSeq: true,
        lineWidth: 80,
        minContentWidth: 20,
        nullStr: "null",
        simpleKeys: false,
        singleQuote: null,
        trueStr: "true",
        verifyAliasOrder: true
      }, doc.schema.toStringOptions, options2);
      let inFlow;
      switch (opt.collectionStyle) {
        case "block":
          inFlow = false;
          break;
        case "flow":
          inFlow = true;
          break;
        default:
          inFlow = null;
      }
      return {
        anchors: /* @__PURE__ */ new Set(),
        doc,
        flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
        indent: "",
        indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : "  ",
        inFlow,
        options: opt
      };
    }
    __name(createStringifyContext, "createStringifyContext");
    function getTagObject(tags, item) {
      if (item.tag) {
        const match2 = tags.filter((t5) => t5.tag === item.tag);
        if (match2.length > 0)
          return match2.find((t5) => t5.format === item.format) ?? match2[0];
      }
      let tagObj = void 0;
      let obj;
      if (identity.isScalar(item)) {
        obj = item.value;
        let match2 = tags.filter((t5) => t5.identify?.(obj));
        if (match2.length > 1) {
          const testMatch = match2.filter((t5) => t5.test);
          if (testMatch.length > 0)
            match2 = testMatch;
        }
        tagObj = match2.find((t5) => t5.format === item.format) ?? match2.find((t5) => !t5.format);
      } else {
        obj = item;
        tagObj = tags.find((t5) => t5.nodeClass && obj instanceof t5.nodeClass);
      }
      if (!tagObj) {
        const name4 = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj);
        throw new Error(`Tag not resolved for ${name4} value`);
      }
      return tagObj;
    }
    __name(getTagObject, "getTagObject");
    function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
      if (!doc.directives)
        return "";
      const props = [];
      const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;
      if (anchor && anchors.anchorIsValid(anchor)) {
        anchors$1.add(anchor);
        props.push(`&${anchor}`);
      }
      const tag2 = node.tag ?? (tagObj.default ? null : tagObj.tag);
      if (tag2)
        props.push(doc.directives.tagString(tag2));
      return props.join(" ");
    }
    __name(stringifyProps, "stringifyProps");
    function stringify4(item, ctx, onComment, onChompKeep) {
      if (identity.isPair(item))
        return item.toString(ctx, onComment, onChompKeep);
      if (identity.isAlias(item)) {
        if (ctx.doc.directives)
          return item.toString(ctx);
        if (ctx.resolvedAliases?.has(item)) {
          throw new TypeError(`Cannot stringify circular structure without alias nodes`);
        } else {
          if (ctx.resolvedAliases)
            ctx.resolvedAliases.add(item);
          else
            ctx.resolvedAliases = /* @__PURE__ */ new Set([item]);
          item = item.resolve(ctx.doc);
        }
      }
      let tagObj = void 0;
      const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: /* @__PURE__ */ __name((o3) => tagObj = o3, "onTagObj") });
      tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
      const props = stringifyProps(node, tagObj, ctx);
      if (props.length > 0)
        ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
      const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
      if (!props)
        return str2;
      return identity.isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props}
${ctx.indent}${str2}`;
    }
    __name(stringify4, "stringify");
    exports2.createStringifyContext = createStringifyContext;
    exports2.stringify = stringify4;
  }
});

// node_modules/yaml/dist/stringify/stringifyPair.js
var require_stringifyPair = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyPair.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var Scalar = require_Scalar();
    var stringify4 = require_stringify2();
    var stringifyComment = require_stringifyComment();
    function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
      const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
      let keyComment = identity.isNode(key) && key.comment || null;
      if (simpleKeys) {
        if (keyComment) {
          throw new Error("With simple keys, key nodes cannot have comments");
        }
        if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") {
          const msg = "With simple keys, collection cannot be used as a key value";
          throw new Error(msg);
        }
      }
      let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object"));
      ctx = Object.assign({}, ctx, {
        allNullValues: false,
        implicitKey: !explicitKey && (simpleKeys || !allNullValues),
        indent: indent + indentStep
      });
      let keyCommentDone = false;
      let chompKeep = false;
      let str2 = stringify4.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
      if (!explicitKey && !ctx.inFlow && str2.length > 1024) {
        if (simpleKeys)
          throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
        explicitKey = true;
      }
      if (ctx.inFlow) {
        if (allNullValues || value == null) {
          if (keyCommentDone && onComment)
            onComment();
          return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2;
        }
      } else if (allNullValues && !simpleKeys || value == null && explicitKey) {
        str2 = `? ${str2}`;
        if (keyComment && !keyCommentDone) {
          str2 += stringifyComment.lineComment(str2, ctx.indent, commentString(keyComment));
        } else if (chompKeep && onChompKeep)
          onChompKeep();
        return str2;
      }
      if (keyCommentDone)
        keyComment = null;
      if (explicitKey) {
        if (keyComment)
          str2 += stringifyComment.lineComment(str2, ctx.indent, commentString(keyComment));
        str2 = `? ${str2}
${indent}:`;
      } else {
        str2 = `${str2}:`;
        if (keyComment)
          str2 += stringifyComment.lineComment(str2, ctx.indent, commentString(keyComment));
      }
      let vsb, vcb, valueComment;
      if (identity.isNode(value)) {
        vsb = !!value.spaceBefore;
        vcb = value.commentBefore;
        valueComment = value.comment;
      } else {
        vsb = false;
        vcb = null;
        valueComment = null;
        if (value && typeof value === "object")
          value = doc.createNode(value);
      }
      ctx.implicitKey = false;
      if (!explicitKey && !keyComment && identity.isScalar(value))
        ctx.indentAtStart = str2.length + 1;
      chompKeep = false;
      if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) {
        ctx.indent = ctx.indent.substring(2);
      }
      let valueCommentDone = false;
      const valueStr = stringify4.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true);
      let ws2 = " ";
      if (keyComment || vsb || vcb) {
        ws2 = vsb ? "\n" : "";
        if (vcb) {
          const cs = commentString(vcb);
          ws2 += `
${stringifyComment.indentComment(cs, ctx.indent)}`;
        }
        if (valueStr === "" && !ctx.inFlow) {
          if (ws2 === "\n")
            ws2 = "\n\n";
        } else {
          ws2 += `
${ctx.indent}`;
        }
      } else if (!explicitKey && identity.isCollection(value)) {
        const vs0 = valueStr[0];
        const nl0 = valueStr.indexOf("\n");
        const hasNewline = nl0 !== -1;
        const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
        if (hasNewline || !flow) {
          let hasPropsLine = false;
          if (hasNewline && (vs0 === "&" || vs0 === "!")) {
            let sp0 = valueStr.indexOf(" ");
            if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
              sp0 = valueStr.indexOf(" ", sp0 + 1);
            }
            if (sp0 === -1 || nl0 < sp0)
              hasPropsLine = true;
          }
          if (!hasPropsLine)
            ws2 = `
${ctx.indent}`;
        }
      } else if (valueStr === "" || valueStr[0] === "\n") {
        ws2 = "";
      }
      str2 += ws2 + valueStr;
      if (ctx.inFlow) {
        if (valueCommentDone && onComment)
          onComment();
      } else if (valueComment && !valueCommentDone) {
        str2 += stringifyComment.lineComment(str2, ctx.indent, commentString(valueComment));
      } else if (chompKeep && onChompKeep) {
        onChompKeep();
      }
      return str2;
    }
    __name(stringifyPair, "stringifyPair");
    exports2.stringifyPair = stringifyPair;
  }
});

// node_modules/yaml/dist/log.js
var require_log = __commonJS({
  "node_modules/yaml/dist/log.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var node_process = __require("process");
    function debug3(logLevel, ...messages) {
      if (logLevel === "debug")
        console.log(...messages);
    }
    __name(debug3, "debug");
    function warn(logLevel, warning) {
      if (logLevel === "debug" || logLevel === "warn") {
        if (typeof node_process.emitWarning === "function")
          node_process.emitWarning(warning);
        else
          console.warn(warning);
      }
    }
    __name(warn, "warn");
    exports2.debug = debug3;
    exports2.warn = warn;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/merge.js
var require_merge2 = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/merge.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var Scalar = require_Scalar();
    var MERGE_KEY = "<<";
    var merge5 = {
      identify: /* @__PURE__ */ __name((value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, "identify"),
      default: "key",
      tag: "tag:yaml.org,2002:merge",
      test: /^<<$/,
      resolve: /* @__PURE__ */ __name(() => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {
        addToJSMap: addMergeToJSMap
      }), "resolve"),
      stringify: /* @__PURE__ */ __name(() => MERGE_KEY, "stringify")
    };
    var isMergeKey = /* @__PURE__ */ __name((ctx, key) => (merge5.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge5.identify(key.value)) && ctx?.doc.schema.tags.some((tag2) => tag2.tag === merge5.tag && tag2.default), "isMergeKey");
    function addMergeToJSMap(ctx, map3, value) {
      value = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;
      if (identity.isSeq(value))
        for (const it3 of value.items)
          mergeValue(ctx, map3, it3);
      else if (Array.isArray(value))
        for (const it3 of value)
          mergeValue(ctx, map3, it3);
      else
        mergeValue(ctx, map3, value);
    }
    __name(addMergeToJSMap, "addMergeToJSMap");
    function mergeValue(ctx, map3, value) {
      const source2 = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value;
      if (!identity.isMap(source2))
        throw new Error("Merge sources must be maps or map aliases");
      const srcMap = source2.toJSON(null, ctx, Map);
      for (const [key, value2] of srcMap) {
        if (map3 instanceof Map) {
          if (!map3.has(key))
            map3.set(key, value2);
        } else if (map3 instanceof Set) {
          map3.add(key);
        } else if (!Object.prototype.hasOwnProperty.call(map3, key)) {
          Object.defineProperty(map3, key, {
            value: value2,
            writable: true,
            enumerable: true,
            configurable: true
          });
        }
      }
      return map3;
    }
    __name(mergeValue, "mergeValue");
    exports2.addMergeToJSMap = addMergeToJSMap;
    exports2.isMergeKey = isMergeKey;
    exports2.merge = merge5;
  }
});

// node_modules/yaml/dist/nodes/addPairToJSMap.js
var require_addPairToJSMap = __commonJS({
  "node_modules/yaml/dist/nodes/addPairToJSMap.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var log = require_log();
    var merge5 = require_merge2();
    var stringify4 = require_stringify2();
    var identity = require_identity();
    var toJS = require_toJS();
    function addPairToJSMap(ctx, map3, { key, value }) {
      if (identity.isNode(key) && key.addToJSMap)
        key.addToJSMap(ctx, map3, value);
      else if (merge5.isMergeKey(ctx, key))
        merge5.addMergeToJSMap(ctx, map3, value);
      else {
        const jsKey = toJS.toJS(key, "", ctx);
        if (map3 instanceof Map) {
          map3.set(jsKey, toJS.toJS(value, jsKey, ctx));
        } else if (map3 instanceof Set) {
          map3.add(jsKey);
        } else {
          const stringKey = stringifyKey(key, jsKey, ctx);
          const jsValue = toJS.toJS(value, stringKey, ctx);
          if (stringKey in map3)
            Object.defineProperty(map3, stringKey, {
              value: jsValue,
              writable: true,
              enumerable: true,
              configurable: true
            });
          else
            map3[stringKey] = jsValue;
        }
      }
      return map3;
    }
    __name(addPairToJSMap, "addPairToJSMap");
    function stringifyKey(key, jsKey, ctx) {
      if (jsKey === null)
        return "";
      if (typeof jsKey !== "object")
        return String(jsKey);
      if (identity.isNode(key) && ctx?.doc) {
        const strCtx = stringify4.createStringifyContext(ctx.doc, {});
        strCtx.anchors = /* @__PURE__ */ new Set();
        for (const node of ctx.anchors.keys())
          strCtx.anchors.add(node.anchor);
        strCtx.inFlow = true;
        strCtx.inStringifyKey = true;
        const strKey = key.toString(strCtx);
        if (!ctx.mapKeyWarned) {
          let jsonStr = JSON.stringify(strKey);
          if (jsonStr.length > 40)
            jsonStr = jsonStr.substring(0, 36) + '..."';
          log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
          ctx.mapKeyWarned = true;
        }
        return strKey;
      }
      return JSON.stringify(jsKey);
    }
    __name(stringifyKey, "stringifyKey");
    exports2.addPairToJSMap = addPairToJSMap;
  }
});

// node_modules/yaml/dist/nodes/Pair.js
var require_Pair = __commonJS({
  "node_modules/yaml/dist/nodes/Pair.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var createNode2 = require_createNode();
    var stringifyPair = require_stringifyPair();
    var addPairToJSMap = require_addPairToJSMap();
    var identity = require_identity();
    function createPair(key, value, ctx) {
      const k2 = createNode2.createNode(key, void 0, ctx);
      const v2 = createNode2.createNode(value, void 0, ctx);
      return new Pair(k2, v2);
    }
    __name(createPair, "createPair");
    var Pair = class _Pair {
      static {
        __name(this, "Pair");
      }
      constructor(key, value = null) {
        Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });
        this.key = key;
        this.value = value;
      }
      clone(schema) {
        let { key, value } = this;
        if (identity.isNode(key))
          key = key.clone(schema);
        if (identity.isNode(value))
          value = value.clone(schema);
        return new _Pair(key, value);
      }
      toJSON(_2, ctx) {
        const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
        return addPairToJSMap.addPairToJSMap(ctx, pair, this);
      }
      toString(ctx, onComment, onChompKeep) {
        return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
      }
    };
    exports2.Pair = Pair;
    exports2.createPair = createPair;
  }
});

// node_modules/yaml/dist/stringify/stringifyCollection.js
var require_stringifyCollection = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyCollection.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var stringify4 = require_stringify2();
    var stringifyComment = require_stringifyComment();
    function stringifyCollection(collection, ctx, options2) {
      const flow = ctx.inFlow ?? collection.flow;
      const stringify5 = flow ? stringifyFlowCollection : stringifyBlockCollection;
      return stringify5(collection, ctx, options2);
    }
    __name(stringifyCollection, "stringifyCollection");
    function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
      const { indent, options: { commentString } } = ctx;
      const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
      let chompKeep = false;
      const lines = [];
      for (let i4 = 0; i4 < items.length; ++i4) {
        const item = items[i4];
        let comment2 = null;
        if (identity.isNode(item)) {
          if (!chompKeep && item.spaceBefore)
            lines.push("");
          addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
          if (item.comment)
            comment2 = item.comment;
        } else if (identity.isPair(item)) {
          const ik = identity.isNode(item.key) ? item.key : null;
          if (ik) {
            if (!chompKeep && ik.spaceBefore)
              lines.push("");
            addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
          }
        }
        chompKeep = false;
        let str3 = stringify4.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
        if (comment2)
          str3 += stringifyComment.lineComment(str3, itemIndent, commentString(comment2));
        if (chompKeep && comment2)
          chompKeep = false;
        lines.push(blockItemPrefix + str3);
      }
      let str2;
      if (lines.length === 0) {
        str2 = flowChars.start + flowChars.end;
      } else {
        str2 = lines[0];
        for (let i4 = 1; i4 < lines.length; ++i4) {
          const line = lines[i4];
          str2 += line ? `
${indent}${line}` : "\n";
        }
      }
      if (comment) {
        str2 += "\n" + stringifyComment.indentComment(commentString(comment), indent);
        if (onComment)
          onComment();
      } else if (chompKeep && onChompKeep)
        onChompKeep();
      return str2;
    }
    __name(stringifyBlockCollection, "stringifyBlockCollection");
    function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
      const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
      itemIndent += indentStep;
      const itemCtx = Object.assign({}, ctx, {
        indent: itemIndent,
        inFlow: true,
        type: null
      });
      let reqNewline = false;
      let linesAtValue = 0;
      const lines = [];
      for (let i4 = 0; i4 < items.length; ++i4) {
        const item = items[i4];
        let comment = null;
        if (identity.isNode(item)) {
          if (item.spaceBefore)
            lines.push("");
          addCommentBefore(ctx, lines, item.commentBefore, false);
          if (item.comment)
            comment = item.comment;
        } else if (identity.isPair(item)) {
          const ik = identity.isNode(item.key) ? item.key : null;
          if (ik) {
            if (ik.spaceBefore)
              lines.push("");
            addCommentBefore(ctx, lines, ik.commentBefore, false);
            if (ik.comment)
              reqNewline = true;
          }
          const iv = identity.isNode(item.value) ? item.value : null;
          if (iv) {
            if (iv.comment)
              comment = iv.comment;
            if (iv.commentBefore)
              reqNewline = true;
          } else if (item.value == null && ik?.comment) {
            comment = ik.comment;
          }
        }
        if (comment)
          reqNewline = true;
        let str2 = stringify4.stringify(item, itemCtx, () => comment = null);
        if (i4 < items.length - 1)
          str2 += ",";
        if (comment)
          str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment));
        if (!reqNewline && (lines.length > linesAtValue || str2.includes("\n")))
          reqNewline = true;
        lines.push(str2);
        linesAtValue = lines.length;
      }
      const { start: start2, end } = flowChars;
      if (lines.length === 0) {
        return start2 + end;
      } else {
        if (!reqNewline) {
          const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
          reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
        }
        if (reqNewline) {
          let str2 = start2;
          for (const line of lines)
            str2 += line ? `
${indentStep}${indent}${line}` : "\n";
          return `${str2}
${indent}${end}`;
        } else {
          return `${start2}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
        }
      }
    }
    __name(stringifyFlowCollection, "stringifyFlowCollection");
    function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
      if (comment && chompKeep)
        comment = comment.replace(/^\n+/, "");
      if (comment) {
        const ic = stringifyComment.indentComment(commentString(comment), indent);
        lines.push(ic.trimStart());
      }
    }
    __name(addCommentBefore, "addCommentBefore");
    exports2.stringifyCollection = stringifyCollection;
  }
});

// node_modules/yaml/dist/nodes/YAMLMap.js
var require_YAMLMap = __commonJS({
  "node_modules/yaml/dist/nodes/YAMLMap.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var stringifyCollection = require_stringifyCollection();
    var addPairToJSMap = require_addPairToJSMap();
    var Collection = require_Collection();
    var identity = require_identity();
    var Pair = require_Pair();
    var Scalar = require_Scalar();
    function findPair(items, key) {
      const k2 = identity.isScalar(key) ? key.value : key;
      for (const it3 of items) {
        if (identity.isPair(it3)) {
          if (it3.key === key || it3.key === k2)
            return it3;
          if (identity.isScalar(it3.key) && it3.key.value === k2)
            return it3;
        }
      }
      return void 0;
    }
    __name(findPair, "findPair");
    var YAMLMap = class extends Collection.Collection {
      static {
        __name(this, "YAMLMap");
      }
      static get tagName() {
        return "tag:yaml.org,2002:map";
      }
      constructor(schema) {
        super(identity.MAP, schema);
        this.items = [];
      }
      /**
       * A generic collection parsing method that can be extended
       * to other node classes that inherit from YAMLMap
       */
      static from(schema, obj, ctx) {
        const { keepUndefined, replacer } = ctx;
        const map3 = new this(schema);
        const add = /* @__PURE__ */ __name((key, value) => {
          if (typeof replacer === "function")
            value = replacer.call(obj, key, value);
          else if (Array.isArray(replacer) && !replacer.includes(key))
            return;
          if (value !== void 0 || keepUndefined)
            map3.items.push(Pair.createPair(key, value, ctx));
        }, "add");
        if (obj instanceof Map) {
          for (const [key, value] of obj)
            add(key, value);
        } else if (obj && typeof obj === "object") {
          for (const key of Object.keys(obj))
            add(key, obj[key]);
        }
        if (typeof schema.sortMapEntries === "function") {
          map3.items.sort(schema.sortMapEntries);
        }
        return map3;
      }
      /**
       * Adds a value to the collection.
       *
       * @param overwrite - If not set `true`, using a key that is already in the
       *   collection will throw. Otherwise, overwrites the previous value.
       */
      add(pair, overwrite) {
        let _pair;
        if (identity.isPair(pair))
          _pair = pair;
        else if (!pair || typeof pair !== "object" || !("key" in pair)) {
          _pair = new Pair.Pair(pair, pair?.value);
        } else
          _pair = new Pair.Pair(pair.key, pair.value);
        const prev = findPair(this.items, _pair.key);
        const sortEntries = this.schema?.sortMapEntries;
        if (prev) {
          if (!overwrite)
            throw new Error(`Key ${_pair.key} already set`);
          if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
            prev.value.value = _pair.value;
          else
            prev.value = _pair.value;
        } else if (sortEntries) {
          const i4 = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
          if (i4 === -1)
            this.items.push(_pair);
          else
            this.items.splice(i4, 0, _pair);
        } else {
          this.items.push(_pair);
        }
      }
      delete(key) {
        const it3 = findPair(this.items, key);
        if (!it3)
          return false;
        const del = this.items.splice(this.items.indexOf(it3), 1);
        return del.length > 0;
      }
      get(key, keepScalar) {
        const it3 = findPair(this.items, key);
        const node = it3?.value;
        return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? void 0;
      }
      has(key) {
        return !!findPair(this.items, key);
      }
      set(key, value) {
        this.add(new Pair.Pair(key, value), true);
      }
      /**
       * @param ctx - Conversion context, originally set in Document#toJS()
       * @param {Class} Type - If set, forces the returned collection type
       * @returns Instance of Type, Map, or Object
       */
      toJSON(_2, ctx, Type3) {
        const map3 = Type3 ? new Type3() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
        if (ctx?.onCreate)
          ctx.onCreate(map3);
        for (const item of this.items)
          addPairToJSMap.addPairToJSMap(ctx, map3, item);
        return map3;
      }
      toString(ctx, onComment, onChompKeep) {
        if (!ctx)
          return JSON.stringify(this);
        for (const item of this.items) {
          if (!identity.isPair(item))
            throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
        }
        if (!ctx.allNullValues && this.hasAllNullValues(false))
          ctx = Object.assign({}, ctx, { allNullValues: true });
        return stringifyCollection.stringifyCollection(this, ctx, {
          blockItemPrefix: "",
          flowChars: { start: "{", end: "}" },
          itemIndent: ctx.indent || "",
          onChompKeep,
          onComment
        });
      }
    };
    exports2.YAMLMap = YAMLMap;
    exports2.findPair = findPair;
  }
});

// node_modules/yaml/dist/schema/common/map.js
var require_map = __commonJS({
  "node_modules/yaml/dist/schema/common/map.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var YAMLMap = require_YAMLMap();
    var map3 = {
      collection: "map",
      default: true,
      nodeClass: YAMLMap.YAMLMap,
      tag: "tag:yaml.org,2002:map",
      resolve(map4, onError2) {
        if (!identity.isMap(map4))
          onError2("Expected a mapping for this tag");
        return map4;
      },
      createNode: /* @__PURE__ */ __name((schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx), "createNode")
    };
    exports2.map = map3;
  }
});

// node_modules/yaml/dist/nodes/YAMLSeq.js
var require_YAMLSeq = __commonJS({
  "node_modules/yaml/dist/nodes/YAMLSeq.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var createNode2 = require_createNode();
    var stringifyCollection = require_stringifyCollection();
    var Collection = require_Collection();
    var identity = require_identity();
    var Scalar = require_Scalar();
    var toJS = require_toJS();
    var YAMLSeq = class extends Collection.Collection {
      static {
        __name(this, "YAMLSeq");
      }
      static get tagName() {
        return "tag:yaml.org,2002:seq";
      }
      constructor(schema) {
        super(identity.SEQ, schema);
        this.items = [];
      }
      add(value) {
        this.items.push(value);
      }
      /**
       * Removes a value from the collection.
       *
       * `key` must contain a representation of an integer for this to succeed.
       * It may be wrapped in a `Scalar`.
       *
       * @returns `true` if the item was found and removed.
       */
      delete(key) {
        const idx = asItemIndex(key);
        if (typeof idx !== "number")
          return false;
        const del = this.items.splice(idx, 1);
        return del.length > 0;
      }
      get(key, keepScalar) {
        const idx = asItemIndex(key);
        if (typeof idx !== "number")
          return void 0;
        const it3 = this.items[idx];
        return !keepScalar && identity.isScalar(it3) ? it3.value : it3;
      }
      /**
       * Checks if the collection includes a value with the key `key`.
       *
       * `key` must contain a representation of an integer for this to succeed.
       * It may be wrapped in a `Scalar`.
       */
      has(key) {
        const idx = asItemIndex(key);
        return typeof idx === "number" && idx < this.items.length;
      }
      /**
       * Sets a value in this collection. For `!!set`, `value` needs to be a
       * boolean to add/remove the item from the set.
       *
       * If `key` does not contain a representation of an integer, this will throw.
       * It may be wrapped in a `Scalar`.
       */
      set(key, value) {
        const idx = asItemIndex(key);
        if (typeof idx !== "number")
          throw new Error(`Expected a valid index, not ${key}.`);
        const prev = this.items[idx];
        if (identity.isScalar(prev) && Scalar.isScalarValue(value))
          prev.value = value;
        else
          this.items[idx] = value;
      }
      toJSON(_2, ctx) {
        const seq = [];
        if (ctx?.onCreate)
          ctx.onCreate(seq);
        let i4 = 0;
        for (const item of this.items)
          seq.push(toJS.toJS(item, String(i4++), ctx));
        return seq;
      }
      toString(ctx, onComment, onChompKeep) {
        if (!ctx)
          return JSON.stringify(this);
        return stringifyCollection.stringifyCollection(this, ctx, {
          blockItemPrefix: "- ",
          flowChars: { start: "[", end: "]" },
          itemIndent: (ctx.indent || "") + "  ",
          onChompKeep,
          onComment
        });
      }
      static from(schema, obj, ctx) {
        const { replacer } = ctx;
        const seq = new this(schema);
        if (obj && Symbol.iterator in Object(obj)) {
          let i4 = 0;
          for (let it3 of obj) {
            if (typeof replacer === "function") {
              const key = obj instanceof Set ? it3 : String(i4++);
              it3 = replacer.call(obj, key, it3);
            }
            seq.items.push(createNode2.createNode(it3, void 0, ctx));
          }
        }
        return seq;
      }
    };
    function asItemIndex(key) {
      let idx = identity.isScalar(key) ? key.value : key;
      if (idx && typeof idx === "string")
        idx = Number(idx);
      return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
    }
    __name(asItemIndex, "asItemIndex");
    exports2.YAMLSeq = YAMLSeq;
  }
});

// node_modules/yaml/dist/schema/common/seq.js
var require_seq = __commonJS({
  "node_modules/yaml/dist/schema/common/seq.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var YAMLSeq = require_YAMLSeq();
    var seq = {
      collection: "seq",
      default: true,
      nodeClass: YAMLSeq.YAMLSeq,
      tag: "tag:yaml.org,2002:seq",
      resolve(seq2, onError2) {
        if (!identity.isSeq(seq2))
          onError2("Expected a sequence for this tag");
        return seq2;
      },
      createNode: /* @__PURE__ */ __name((schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx), "createNode")
    };
    exports2.seq = seq;
  }
});

// node_modules/yaml/dist/schema/common/string.js
var require_string = __commonJS({
  "node_modules/yaml/dist/schema/common/string.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var stringifyString = require_stringifyString();
    var string4 = {
      identify: /* @__PURE__ */ __name((value) => typeof value === "string", "identify"),
      default: true,
      tag: "tag:yaml.org,2002:str",
      resolve: /* @__PURE__ */ __name((str2) => str2, "resolve"),
      stringify(item, ctx, onComment, onChompKeep) {
        ctx = Object.assign({ actualString: true }, ctx);
        return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
      }
    };
    exports2.string = string4;
  }
});

// node_modules/yaml/dist/schema/common/null.js
var require_null = __commonJS({
  "node_modules/yaml/dist/schema/common/null.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Scalar = require_Scalar();
    var nullTag = {
      identify: /* @__PURE__ */ __name((value) => value == null, "identify"),
      createNode: /* @__PURE__ */ __name(() => new Scalar.Scalar(null), "createNode"),
      default: true,
      tag: "tag:yaml.org,2002:null",
      test: /^(?:~|[Nn]ull|NULL)?$/,
      resolve: /* @__PURE__ */ __name(() => new Scalar.Scalar(null), "resolve"),
      stringify: /* @__PURE__ */ __name(({ source: source2 }, ctx) => typeof source2 === "string" && nullTag.test.test(source2) ? source2 : ctx.options.nullStr, "stringify")
    };
    exports2.nullTag = nullTag;
  }
});

// node_modules/yaml/dist/schema/core/bool.js
var require_bool = __commonJS({
  "node_modules/yaml/dist/schema/core/bool.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Scalar = require_Scalar();
    var boolTag = {
      identify: /* @__PURE__ */ __name((value) => typeof value === "boolean", "identify"),
      default: true,
      tag: "tag:yaml.org,2002:bool",
      test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
      resolve: /* @__PURE__ */ __name((str2) => new Scalar.Scalar(str2[0] === "t" || str2[0] === "T"), "resolve"),
      stringify({ source: source2, value }, ctx) {
        if (source2 && boolTag.test.test(source2)) {
          const sv = source2[0] === "t" || source2[0] === "T";
          if (value === sv)
            return source2;
        }
        return value ? ctx.options.trueStr : ctx.options.falseStr;
      }
    };
    exports2.boolTag = boolTag;
  }
});

// node_modules/yaml/dist/stringify/stringifyNumber.js
var require_stringifyNumber = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyNumber.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    function stringifyNumber({ format: format4, minFractionDigits, tag: tag2, value }) {
      if (typeof value === "bigint")
        return String(value);
      const num = typeof value === "number" ? value : Number(value);
      if (!isFinite(num))
        return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
      let n3 = JSON.stringify(value);
      if (!format4 && minFractionDigits && (!tag2 || tag2 === "tag:yaml.org,2002:float") && /^\d/.test(n3)) {
        let i4 = n3.indexOf(".");
        if (i4 < 0) {
          i4 = n3.length;
          n3 += ".";
        }
        let d2 = minFractionDigits - (n3.length - i4 - 1);
        while (d2-- > 0)
          n3 += "0";
      }
      return n3;
    }
    __name(stringifyNumber, "stringifyNumber");
    exports2.stringifyNumber = stringifyNumber;
  }
});

// node_modules/yaml/dist/schema/core/float.js
var require_float2 = __commonJS({
  "node_modules/yaml/dist/schema/core/float.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Scalar = require_Scalar();
    var stringifyNumber = require_stringifyNumber();
    var floatNaN = {
      identify: /* @__PURE__ */ __name((value) => typeof value === "number", "identify"),
      default: true,
      tag: "tag:yaml.org,2002:float",
      test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
      resolve: /* @__PURE__ */ __name((str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, "resolve"),
      stringify: stringifyNumber.stringifyNumber
    };
    var floatExp = {
      identify: /* @__PURE__ */ __name((value) => typeof value === "number", "identify"),
      default: true,
      tag: "tag:yaml.org,2002:float",
      format: "EXP",
      test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
      resolve: /* @__PURE__ */ __name((str2) => parseFloat(str2), "resolve"),
      stringify(node) {
        const num = Number(node.value);
        return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
      }
    };
    var float = {
      identify: /* @__PURE__ */ __name((value) => typeof value === "number", "identify"),
      default: true,
      tag: "tag:yaml.org,2002:float",
      test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
      resolve(str2) {
        const node = new Scalar.Scalar(parseFloat(str2));
        const dot = str2.indexOf(".");
        if (dot !== -1 && str2[str2.length - 1] === "0")
          node.minFractionDigits = str2.length - dot - 1;
        return node;
      },
      stringify: stringifyNumber.stringifyNumber
    };
    exports2.float = float;
    exports2.floatExp = floatExp;
    exports2.floatNaN = floatNaN;
  }
});

// node_modules/yaml/dist/schema/core/int.js
var require_int = __commonJS({
  "node_modules/yaml/dist/schema/core/int.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var stringifyNumber = require_stringifyNumber();
    var intIdentify = /* @__PURE__ */ __name((value) => typeof value === "bigint" || Number.isInteger(value), "intIdentify");
    var intResolve = /* @__PURE__ */ __name((str2, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2.substring(offset), radix), "intResolve");
    function intStringify(node, radix, prefix) {
      const { value } = node;
      if (intIdentify(value) && value >= 0)
        return prefix + value.toString(radix);
      return stringifyNumber.stringifyNumber(node);
    }
    __name(intStringify, "intStringify");
    var intOct = {
      identify: /* @__PURE__ */ __name((value) => intIdentify(value) && value >= 0, "identify"),
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "OCT",
      test: /^0o[0-7]+$/,
      resolve: /* @__PURE__ */ __name((str2, _onError2, opt) => intResolve(str2, 2, 8, opt), "resolve"),
      stringify: /* @__PURE__ */ __name((node) => intStringify(node, 8, "0o"), "stringify")
    };
    var int2 = {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      test: /^[-+]?[0-9]+$/,
      resolve: /* @__PURE__ */ __name((str2, _onError2, opt) => intResolve(str2, 0, 10, opt), "resolve"),
      stringify: stringifyNumber.stringifyNumber
    };
    var intHex = {
      identify: /* @__PURE__ */ __name((value) => intIdentify(value) && value >= 0, "identify"),
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "HEX",
      test: /^0x[0-9a-fA-F]+$/,
      resolve: /* @__PURE__ */ __name((str2, _onError2, opt) => intResolve(str2, 2, 16, opt), "resolve"),
      stringify: /* @__PURE__ */ __name((node) => intStringify(node, 16, "0x"), "stringify")
    };
    exports2.int = int2;
    exports2.intHex = intHex;
    exports2.intOct = intOct;
  }
});

// node_modules/yaml/dist/schema/core/schema.js
var require_schema2 = __commonJS({
  "node_modules/yaml/dist/schema/core/schema.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var map3 = require_map();
    var _null4 = require_null();
    var seq = require_seq();
    var string4 = require_string();
    var bool = require_bool();
    var float = require_float2();
    var int2 = require_int();
    var schema = [
      map3.map,
      seq.seq,
      string4.string,
      _null4.nullTag,
      bool.boolTag,
      int2.intOct,
      int2.int,
      int2.intHex,
      float.floatNaN,
      float.floatExp,
      float.float
    ];
    exports2.schema = schema;
  }
});

// node_modules/yaml/dist/schema/json/schema.js
var require_schema3 = __commonJS({
  "node_modules/yaml/dist/schema/json/schema.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Scalar = require_Scalar();
    var map3 = require_map();
    var seq = require_seq();
    function intIdentify(value) {
      return typeof value === "bigint" || Number.isInteger(value);
    }
    __name(intIdentify, "intIdentify");
    var stringifyJSON = /* @__PURE__ */ __name(({ value }) => JSON.stringify(value), "stringifyJSON");
    var jsonScalars = [
      {
        identify: /* @__PURE__ */ __name((value) => typeof value === "string", "identify"),
        default: true,
        tag: "tag:yaml.org,2002:str",
        resolve: /* @__PURE__ */ __name((str2) => str2, "resolve"),
        stringify: stringifyJSON
      },
      {
        identify: /* @__PURE__ */ __name((value) => value == null, "identify"),
        createNode: /* @__PURE__ */ __name(() => new Scalar.Scalar(null), "createNode"),
        default: true,
        tag: "tag:yaml.org,2002:null",
        test: /^null$/,
        resolve: /* @__PURE__ */ __name(() => null, "resolve"),
        stringify: stringifyJSON
      },
      {
        identify: /* @__PURE__ */ __name((value) => typeof value === "boolean", "identify"),
        default: true,
        tag: "tag:yaml.org,2002:bool",
        test: /^true$|^false$/,
        resolve: /* @__PURE__ */ __name((str2) => str2 === "true", "resolve"),
        stringify: stringifyJSON
      },
      {
        identify: intIdentify,
        default: true,
        tag: "tag:yaml.org,2002:int",
        test: /^-?(?:0|[1-9][0-9]*)$/,
        resolve: /* @__PURE__ */ __name((str2, _onError2, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10), "resolve"),
        stringify: /* @__PURE__ */ __name(({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value), "stringify")
      },
      {
        identify: /* @__PURE__ */ __name((value) => typeof value === "number", "identify"),
        default: true,
        tag: "tag:yaml.org,2002:float",
        test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
        resolve: /* @__PURE__ */ __name((str2) => parseFloat(str2), "resolve"),
        stringify: stringifyJSON
      }
    ];
    var jsonError = {
      default: true,
      tag: "",
      test: /^/,
      resolve(str2, onError2) {
        onError2(`Unresolved plain scalar ${JSON.stringify(str2)}`);
        return str2;
      }
    };
    var schema = [map3.map, seq.seq].concat(jsonScalars, jsonError);
    exports2.schema = schema;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/binary.js
var require_binary = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/binary.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var node_buffer = __require("buffer");
    var Scalar = require_Scalar();
    var stringifyString = require_stringifyString();
    var binary2 = {
      identify: /* @__PURE__ */ __name((value) => value instanceof Uint8Array, "identify"),
      // Buffer inherits from Uint8Array
      default: false,
      tag: "tag:yaml.org,2002:binary",
      /**
       * Returns a Buffer in node and an Uint8Array in browsers
       *
       * To use the resulting buffer as an image, you'll want to do something like:
       *
       *   const blob = new Blob([buffer], { type: 'image/jpeg' })
       *   document.querySelector('#photo').src = URL.createObjectURL(blob)
       */
      resolve(src, onError2) {
        if (typeof node_buffer.Buffer === "function") {
          return node_buffer.Buffer.from(src, "base64");
        } else if (typeof atob === "function") {
          const str2 = atob(src.replace(/[\n\r]/g, ""));
          const buffer = new Uint8Array(str2.length);
          for (let i4 = 0; i4 < str2.length; ++i4)
            buffer[i4] = str2.charCodeAt(i4);
          return buffer;
        } else {
          onError2("This environment does not support reading binary tags; either Buffer or atob is required");
          return src;
        }
      },
      stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
        if (!value)
          return "";
        const buf = value;
        let str2;
        if (typeof node_buffer.Buffer === "function") {
          str2 = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64");
        } else if (typeof btoa === "function") {
          let s5 = "";
          for (let i4 = 0; i4 < buf.length; ++i4)
            s5 += String.fromCharCode(buf[i4]);
          str2 = btoa(s5);
        } else {
          throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
        }
        type ?? (type = Scalar.Scalar.BLOCK_LITERAL);
        if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
          const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
          const n3 = Math.ceil(str2.length / lineWidth);
          const lines = new Array(n3);
          for (let i4 = 0, o3 = 0; i4 < n3; ++i4, o3 += lineWidth) {
            lines[i4] = str2.substr(o3, lineWidth);
          }
          str2 = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? "\n" : " ");
        }
        return stringifyString.stringifyString({ comment, type, value: str2 }, ctx, onComment, onChompKeep);
      }
    };
    exports2.binary = binary2;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/pairs.js
var require_pairs = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/pairs.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var Pair = require_Pair();
    var Scalar = require_Scalar();
    var YAMLSeq = require_YAMLSeq();
    function resolvePairs(seq, onError2) {
      if (identity.isSeq(seq)) {
        for (let i4 = 0; i4 < seq.items.length; ++i4) {
          let item = seq.items[i4];
          if (identity.isPair(item))
            continue;
          else if (identity.isMap(item)) {
            if (item.items.length > 1)
              onError2("Each pair must have its own sequence indicator");
            const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
            if (item.commentBefore)
              pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
${pair.key.commentBefore}` : item.commentBefore;
            if (item.comment) {
              const cn = pair.value ?? pair.key;
              cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
            }
            item = pair;
          }
          seq.items[i4] = identity.isPair(item) ? item : new Pair.Pair(item);
        }
      } else
        onError2("Expected a sequence for this tag");
      return seq;
    }
    __name(resolvePairs, "resolvePairs");
    function createPairs(schema, iterable, ctx) {
      const { replacer } = ctx;
      const pairs2 = new YAMLSeq.YAMLSeq(schema);
      pairs2.tag = "tag:yaml.org,2002:pairs";
      let i4 = 0;
      if (iterable && Symbol.iterator in Object(iterable))
        for (let it3 of iterable) {
          if (typeof replacer === "function")
            it3 = replacer.call(iterable, String(i4++), it3);
          let key, value;
          if (Array.isArray(it3)) {
            if (it3.length === 2) {
              key = it3[0];
              value = it3[1];
            } else
              throw new TypeError(`Expected [key, value] tuple: ${it3}`);
          } else if (it3 && it3 instanceof Object) {
            const keys = Object.keys(it3);
            if (keys.length === 1) {
              key = keys[0];
              value = it3[key];
            } else {
              throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
            }
          } else {
            key = it3;
          }
          pairs2.items.push(Pair.createPair(key, value, ctx));
        }
      return pairs2;
    }
    __name(createPairs, "createPairs");
    var pairs = {
      collection: "seq",
      default: false,
      tag: "tag:yaml.org,2002:pairs",
      resolve: resolvePairs,
      createNode: createPairs
    };
    exports2.createPairs = createPairs;
    exports2.pairs = pairs;
    exports2.resolvePairs = resolvePairs;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/omap.js
var require_omap = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/omap.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var toJS = require_toJS();
    var YAMLMap = require_YAMLMap();
    var YAMLSeq = require_YAMLSeq();
    var pairs = require_pairs();
    var YAMLOMap = class _YAMLOMap extends YAMLSeq.YAMLSeq {
      static {
        __name(this, "YAMLOMap");
      }
      constructor() {
        super();
        this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
        this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
        this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
        this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
        this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
        this.tag = _YAMLOMap.tag;
      }
      /**
       * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
       * but TypeScript won't allow widening the signature of a child method.
       */
      toJSON(_2, ctx) {
        if (!ctx)
          return super.toJSON(_2);
        const map3 = /* @__PURE__ */ new Map();
        if (ctx?.onCreate)
          ctx.onCreate(map3);
        for (const pair of this.items) {
          let key, value;
          if (identity.isPair(pair)) {
            key = toJS.toJS(pair.key, "", ctx);
            value = toJS.toJS(pair.value, key, ctx);
          } else {
            key = toJS.toJS(pair, "", ctx);
          }
          if (map3.has(key))
            throw new Error("Ordered maps must not include duplicate keys");
          map3.set(key, value);
        }
        return map3;
      }
      static from(schema, iterable, ctx) {
        const pairs$1 = pairs.createPairs(schema, iterable, ctx);
        const omap2 = new this();
        omap2.items = pairs$1.items;
        return omap2;
      }
    };
    YAMLOMap.tag = "tag:yaml.org,2002:omap";
    var omap = {
      collection: "seq",
      identify: /* @__PURE__ */ __name((value) => value instanceof Map, "identify"),
      nodeClass: YAMLOMap,
      default: false,
      tag: "tag:yaml.org,2002:omap",
      resolve(seq, onError2) {
        const pairs$1 = pairs.resolvePairs(seq, onError2);
        const seenKeys = [];
        for (const { key } of pairs$1.items) {
          if (identity.isScalar(key)) {
            if (seenKeys.includes(key.value)) {
              onError2(`Ordered maps must not include duplicate keys: ${key.value}`);
            } else {
              seenKeys.push(key.value);
            }
          }
        }
        return Object.assign(new YAMLOMap(), pairs$1);
      },
      createNode: /* @__PURE__ */ __name((schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx), "createNode")
    };
    exports2.YAMLOMap = YAMLOMap;
    exports2.omap = omap;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/bool.js
var require_bool2 = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/bool.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Scalar = require_Scalar();
    function boolStringify({ value, source: source2 }, ctx) {
      const boolObj = value ? trueTag : falseTag;
      if (source2 && boolObj.test.test(source2))
        return source2;
      return value ? ctx.options.trueStr : ctx.options.falseStr;
    }
    __name(boolStringify, "boolStringify");
    var trueTag = {
      identify: /* @__PURE__ */ __name((value) => value === true, "identify"),
      default: true,
      tag: "tag:yaml.org,2002:bool",
      test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
      resolve: /* @__PURE__ */ __name(() => new Scalar.Scalar(true), "resolve"),
      stringify: boolStringify
    };
    var falseTag = {
      identify: /* @__PURE__ */ __name((value) => value === false, "identify"),
      default: true,
      tag: "tag:yaml.org,2002:bool",
      test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
      resolve: /* @__PURE__ */ __name(() => new Scalar.Scalar(false), "resolve"),
      stringify: boolStringify
    };
    exports2.falseTag = falseTag;
    exports2.trueTag = trueTag;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/float.js
var require_float3 = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/float.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Scalar = require_Scalar();
    var stringifyNumber = require_stringifyNumber();
    var floatNaN = {
      identify: /* @__PURE__ */ __name((value) => typeof value === "number", "identify"),
      default: true,
      tag: "tag:yaml.org,2002:float",
      test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
      resolve: /* @__PURE__ */ __name((str2) => str2.slice(-3).toLowerCase() === "nan" ? NaN : str2[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, "resolve"),
      stringify: stringifyNumber.stringifyNumber
    };
    var floatExp = {
      identify: /* @__PURE__ */ __name((value) => typeof value === "number", "identify"),
      default: true,
      tag: "tag:yaml.org,2002:float",
      format: "EXP",
      test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
      resolve: /* @__PURE__ */ __name((str2) => parseFloat(str2.replace(/_/g, "")), "resolve"),
      stringify(node) {
        const num = Number(node.value);
        return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
      }
    };
    var float = {
      identify: /* @__PURE__ */ __name((value) => typeof value === "number", "identify"),
      default: true,
      tag: "tag:yaml.org,2002:float",
      test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
      resolve(str2) {
        const node = new Scalar.Scalar(parseFloat(str2.replace(/_/g, "")));
        const dot = str2.indexOf(".");
        if (dot !== -1) {
          const f5 = str2.substring(dot + 1).replace(/_/g, "");
          if (f5[f5.length - 1] === "0")
            node.minFractionDigits = f5.length;
        }
        return node;
      },
      stringify: stringifyNumber.stringifyNumber
    };
    exports2.float = float;
    exports2.floatExp = floatExp;
    exports2.floatNaN = floatNaN;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/int.js
var require_int2 = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/int.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var stringifyNumber = require_stringifyNumber();
    var intIdentify = /* @__PURE__ */ __name((value) => typeof value === "bigint" || Number.isInteger(value), "intIdentify");
    function intResolve(str2, offset, radix, { intAsBigInt }) {
      const sign = str2[0];
      if (sign === "-" || sign === "+")
        offset += 1;
      str2 = str2.substring(offset).replace(/_/g, "");
      if (intAsBigInt) {
        switch (radix) {
          case 2:
            str2 = `0b${str2}`;
            break;
          case 8:
            str2 = `0o${str2}`;
            break;
          case 16:
            str2 = `0x${str2}`;
            break;
        }
        const n4 = BigInt(str2);
        return sign === "-" ? BigInt(-1) * n4 : n4;
      }
      const n3 = parseInt(str2, radix);
      return sign === "-" ? -1 * n3 : n3;
    }
    __name(intResolve, "intResolve");
    function intStringify(node, radix, prefix) {
      const { value } = node;
      if (intIdentify(value)) {
        const str2 = value.toString(radix);
        return value < 0 ? "-" + prefix + str2.substr(1) : prefix + str2;
      }
      return stringifyNumber.stringifyNumber(node);
    }
    __name(intStringify, "intStringify");
    var intBin = {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "BIN",
      test: /^[-+]?0b[0-1_]+$/,
      resolve: /* @__PURE__ */ __name((str2, _onError2, opt) => intResolve(str2, 2, 2, opt), "resolve"),
      stringify: /* @__PURE__ */ __name((node) => intStringify(node, 2, "0b"), "stringify")
    };
    var intOct = {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "OCT",
      test: /^[-+]?0[0-7_]+$/,
      resolve: /* @__PURE__ */ __name((str2, _onError2, opt) => intResolve(str2, 1, 8, opt), "resolve"),
      stringify: /* @__PURE__ */ __name((node) => intStringify(node, 8, "0"), "stringify")
    };
    var int2 = {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      test: /^[-+]?[0-9][0-9_]*$/,
      resolve: /* @__PURE__ */ __name((str2, _onError2, opt) => intResolve(str2, 0, 10, opt), "resolve"),
      stringify: stringifyNumber.stringifyNumber
    };
    var intHex = {
      identify: intIdentify,
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "HEX",
      test: /^[-+]?0x[0-9a-fA-F_]+$/,
      resolve: /* @__PURE__ */ __name((str2, _onError2, opt) => intResolve(str2, 2, 16, opt), "resolve"),
      stringify: /* @__PURE__ */ __name((node) => intStringify(node, 16, "0x"), "stringify")
    };
    exports2.int = int2;
    exports2.intBin = intBin;
    exports2.intHex = intHex;
    exports2.intOct = intOct;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/set.js
var require_set = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/set.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var Pair = require_Pair();
    var YAMLMap = require_YAMLMap();
    var YAMLSet = class _YAMLSet extends YAMLMap.YAMLMap {
      static {
        __name(this, "YAMLSet");
      }
      constructor(schema) {
        super(schema);
        this.tag = _YAMLSet.tag;
      }
      add(key) {
        let pair;
        if (identity.isPair(key))
          pair = key;
        else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
          pair = new Pair.Pair(key.key, null);
        else
          pair = new Pair.Pair(key, null);
        const prev = YAMLMap.findPair(this.items, pair.key);
        if (!prev)
          this.items.push(pair);
      }
      /**
       * If `keepPair` is `true`, returns the Pair matching `key`.
       * Otherwise, returns the value of that Pair's key.
       */
      get(key, keepPair) {
        const pair = YAMLMap.findPair(this.items, key);
        return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair;
      }
      set(key, value) {
        if (typeof value !== "boolean")
          throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
        const prev = YAMLMap.findPair(this.items, key);
        if (prev && !value) {
          this.items.splice(this.items.indexOf(prev), 1);
        } else if (!prev && value) {
          this.items.push(new Pair.Pair(key));
        }
      }
      toJSON(_2, ctx) {
        return super.toJSON(_2, ctx, Set);
      }
      toString(ctx, onComment, onChompKeep) {
        if (!ctx)
          return JSON.stringify(this);
        if (this.hasAllNullValues(true))
          return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
        else
          throw new Error("Set items must all have null values");
      }
      static from(schema, iterable, ctx) {
        const { replacer } = ctx;
        const set3 = new this(schema);
        if (iterable && Symbol.iterator in Object(iterable))
          for (let value of iterable) {
            if (typeof replacer === "function")
              value = replacer.call(iterable, value, value);
            set3.items.push(Pair.createPair(value, null, ctx));
          }
        return set3;
      }
    };
    YAMLSet.tag = "tag:yaml.org,2002:set";
    var set2 = {
      collection: "map",
      identify: /* @__PURE__ */ __name((value) => value instanceof Set, "identify"),
      nodeClass: YAMLSet,
      default: false,
      tag: "tag:yaml.org,2002:set",
      createNode: /* @__PURE__ */ __name((schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), "createNode"),
      resolve(map3, onError2) {
        if (identity.isMap(map3)) {
          if (map3.hasAllNullValues(true))
            return Object.assign(new YAMLSet(), map3);
          else
            onError2("Set items must all have null values");
        } else
          onError2("Expected a mapping for this tag");
        return map3;
      }
    };
    exports2.YAMLSet = YAMLSet;
    exports2.set = set2;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/timestamp.js
var require_timestamp = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/timestamp.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var stringifyNumber = require_stringifyNumber();
    function parseSexagesimal(str2, asBigInt) {
      const sign = str2[0];
      const parts2 = sign === "-" || sign === "+" ? str2.substring(1) : str2;
      const num = /* @__PURE__ */ __name((n3) => asBigInt ? BigInt(n3) : Number(n3), "num");
      const res = parts2.replace(/_/g, "").split(":").reduce((res2, p2) => res2 * num(60) + num(p2), num(0));
      return sign === "-" ? num(-1) * res : res;
    }
    __name(parseSexagesimal, "parseSexagesimal");
    function stringifySexagesimal(node) {
      let { value } = node;
      let num = /* @__PURE__ */ __name((n3) => n3, "num");
      if (typeof value === "bigint")
        num = /* @__PURE__ */ __name((n3) => BigInt(n3), "num");
      else if (isNaN(value) || !isFinite(value))
        return stringifyNumber.stringifyNumber(node);
      let sign = "";
      if (value < 0) {
        sign = "-";
        value *= num(-1);
      }
      const _60 = num(60);
      const parts2 = [value % _60];
      if (value < 60) {
        parts2.unshift(0);
      } else {
        value = (value - parts2[0]) / _60;
        parts2.unshift(value % _60);
        if (value >= 60) {
          value = (value - parts2[0]) / _60;
          parts2.unshift(value);
        }
      }
      return sign + parts2.map((n3) => String(n3).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
    }
    __name(stringifySexagesimal, "stringifySexagesimal");
    var intTime = {
      identify: /* @__PURE__ */ __name((value) => typeof value === "bigint" || Number.isInteger(value), "identify"),
      default: true,
      tag: "tag:yaml.org,2002:int",
      format: "TIME",
      test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
      resolve: /* @__PURE__ */ __name((str2, _onError2, { intAsBigInt }) => parseSexagesimal(str2, intAsBigInt), "resolve"),
      stringify: stringifySexagesimal
    };
    var floatTime = {
      identify: /* @__PURE__ */ __name((value) => typeof value === "number", "identify"),
      default: true,
      tag: "tag:yaml.org,2002:float",
      format: "TIME",
      test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
      resolve: /* @__PURE__ */ __name((str2) => parseSexagesimal(str2, false), "resolve"),
      stringify: stringifySexagesimal
    };
    var timestamp = {
      identify: /* @__PURE__ */ __name((value) => value instanceof Date, "identify"),
      default: true,
      tag: "tag:yaml.org,2002:timestamp",
      // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
      // may be omitted altogether, resulting in a date format. In such a case, the time part is
      // assumed to be 00:00:00Z (start of day, UTC).
      test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),
      resolve(str2) {
        const match2 = str2.match(timestamp.test);
        if (!match2)
          throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
        const [, year, month, day, hour, minute, second] = match2.map(Number);
        const millisec = match2[7] ? Number((match2[7] + "00").substr(1, 3)) : 0;
        let date5 = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
        const tz = match2[8];
        if (tz && tz !== "Z") {
          let d2 = parseSexagesimal(tz, false);
          if (Math.abs(d2) < 30)
            d2 *= 60;
          date5 -= 6e4 * d2;
        }
        return new Date(date5);
      },
      stringify: /* @__PURE__ */ __name(({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "", "stringify")
    };
    exports2.floatTime = floatTime;
    exports2.intTime = intTime;
    exports2.timestamp = timestamp;
  }
});

// node_modules/yaml/dist/schema/yaml-1.1/schema.js
var require_schema4 = __commonJS({
  "node_modules/yaml/dist/schema/yaml-1.1/schema.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var map3 = require_map();
    var _null4 = require_null();
    var seq = require_seq();
    var string4 = require_string();
    var binary2 = require_binary();
    var bool = require_bool2();
    var float = require_float3();
    var int2 = require_int2();
    var merge5 = require_merge2();
    var omap = require_omap();
    var pairs = require_pairs();
    var set2 = require_set();
    var timestamp = require_timestamp();
    var schema = [
      map3.map,
      seq.seq,
      string4.string,
      _null4.nullTag,
      bool.trueTag,
      bool.falseTag,
      int2.intBin,
      int2.intOct,
      int2.int,
      int2.intHex,
      float.floatNaN,
      float.floatExp,
      float.float,
      binary2.binary,
      merge5.merge,
      omap.omap,
      pairs.pairs,
      set2.set,
      timestamp.intTime,
      timestamp.floatTime,
      timestamp.timestamp
    ];
    exports2.schema = schema;
  }
});

// node_modules/yaml/dist/schema/tags.js
var require_tags = __commonJS({
  "node_modules/yaml/dist/schema/tags.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var map3 = require_map();
    var _null4 = require_null();
    var seq = require_seq();
    var string4 = require_string();
    var bool = require_bool();
    var float = require_float2();
    var int2 = require_int();
    var schema = require_schema2();
    var schema$1 = require_schema3();
    var binary2 = require_binary();
    var merge5 = require_merge2();
    var omap = require_omap();
    var pairs = require_pairs();
    var schema$2 = require_schema4();
    var set2 = require_set();
    var timestamp = require_timestamp();
    var schemas = /* @__PURE__ */ new Map([
      ["core", schema.schema],
      ["failsafe", [map3.map, seq.seq, string4.string]],
      ["json", schema$1.schema],
      ["yaml11", schema$2.schema],
      ["yaml-1.1", schema$2.schema]
    ]);
    var tagsByName = {
      binary: binary2.binary,
      bool: bool.boolTag,
      float: float.float,
      floatExp: float.floatExp,
      floatNaN: float.floatNaN,
      floatTime: timestamp.floatTime,
      int: int2.int,
      intHex: int2.intHex,
      intOct: int2.intOct,
      intTime: timestamp.intTime,
      map: map3.map,
      merge: merge5.merge,
      null: _null4.nullTag,
      omap: omap.omap,
      pairs: pairs.pairs,
      seq: seq.seq,
      set: set2.set,
      timestamp: timestamp.timestamp
    };
    var coreKnownTags = {
      "tag:yaml.org,2002:binary": binary2.binary,
      "tag:yaml.org,2002:merge": merge5.merge,
      "tag:yaml.org,2002:omap": omap.omap,
      "tag:yaml.org,2002:pairs": pairs.pairs,
      "tag:yaml.org,2002:set": set2.set,
      "tag:yaml.org,2002:timestamp": timestamp.timestamp
    };
    function getTags(customTags, schemaName, addMergeTag) {
      const schemaTags = schemas.get(schemaName);
      if (schemaTags && !customTags) {
        return addMergeTag && !schemaTags.includes(merge5.merge) ? schemaTags.concat(merge5.merge) : schemaTags.slice();
      }
      let tags = schemaTags;
      if (!tags) {
        if (Array.isArray(customTags))
          tags = [];
        else {
          const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", ");
          throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
        }
      }
      if (Array.isArray(customTags)) {
        for (const tag2 of customTags)
          tags = tags.concat(tag2);
      } else if (typeof customTags === "function") {
        tags = customTags(tags.slice());
      }
      if (addMergeTag)
        tags = tags.concat(merge5.merge);
      return tags.reduce((tags2, tag2) => {
        const tagObj = typeof tag2 === "string" ? tagsByName[tag2] : tag2;
        if (!tagObj) {
          const tagName = JSON.stringify(tag2);
          const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
          throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);
        }
        if (!tags2.includes(tagObj))
          tags2.push(tagObj);
        return tags2;
      }, []);
    }
    __name(getTags, "getTags");
    exports2.coreKnownTags = coreKnownTags;
    exports2.getTags = getTags;
  }
});

// node_modules/yaml/dist/schema/Schema.js
var require_Schema = __commonJS({
  "node_modules/yaml/dist/schema/Schema.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var map3 = require_map();
    var seq = require_seq();
    var string4 = require_string();
    var tags = require_tags();
    var sortMapEntriesByKey = /* @__PURE__ */ __name((a2, b2) => a2.key < b2.key ? -1 : a2.key > b2.key ? 1 : 0, "sortMapEntriesByKey");
    var Schema = class _Schema {
      static {
        __name(this, "Schema");
      }
      constructor({ compat, customTags, merge: merge5, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
        this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null;
        this.name = typeof schema === "string" && schema || "core";
        this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
        this.tags = tags.getTags(customTags, this.name, merge5);
        this.toStringOptions = toStringDefaults ?? null;
        Object.defineProperty(this, identity.MAP, { value: map3.map });
        Object.defineProperty(this, identity.SCALAR, { value: string4.string });
        Object.defineProperty(this, identity.SEQ, { value: seq.seq });
        this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
      }
      clone() {
        const copy = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this));
        copy.tags = this.tags.slice();
        return copy;
      }
    };
    exports2.Schema = Schema;
  }
});

// node_modules/yaml/dist/stringify/stringifyDocument.js
var require_stringifyDocument = __commonJS({
  "node_modules/yaml/dist/stringify/stringifyDocument.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var stringify4 = require_stringify2();
    var stringifyComment = require_stringifyComment();
    function stringifyDocument(doc, options2) {
      const lines = [];
      let hasDirectives = options2.directives === true;
      if (options2.directives !== false && doc.directives) {
        const dir = doc.directives.toString(doc);
        if (dir) {
          lines.push(dir);
          hasDirectives = true;
        } else if (doc.directives.docStart)
          hasDirectives = true;
      }
      if (hasDirectives)
        lines.push("---");
      const ctx = stringify4.createStringifyContext(doc, options2);
      const { commentString } = ctx.options;
      if (doc.commentBefore) {
        if (lines.length !== 1)
          lines.unshift("");
        const cs = commentString(doc.commentBefore);
        lines.unshift(stringifyComment.indentComment(cs, ""));
      }
      let chompKeep = false;
      let contentComment = null;
      if (doc.contents) {
        if (identity.isNode(doc.contents)) {
          if (doc.contents.spaceBefore && hasDirectives)
            lines.push("");
          if (doc.contents.commentBefore) {
            const cs = commentString(doc.contents.commentBefore);
            lines.push(stringifyComment.indentComment(cs, ""));
          }
          ctx.forceBlockIndent = !!doc.comment;
          contentComment = doc.contents.comment;
        }
        const onChompKeep = contentComment ? void 0 : () => chompKeep = true;
        let body2 = stringify4.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
        if (contentComment)
          body2 += stringifyComment.lineComment(body2, "", commentString(contentComment));
        if ((body2[0] === "|" || body2[0] === ">") && lines[lines.length - 1] === "---") {
          lines[lines.length - 1] = `--- ${body2}`;
        } else
          lines.push(body2);
      } else {
        lines.push(stringify4.stringify(doc.contents, ctx));
      }
      if (doc.directives?.docEnd) {
        if (doc.comment) {
          const cs = commentString(doc.comment);
          if (cs.includes("\n")) {
            lines.push("...");
            lines.push(stringifyComment.indentComment(cs, ""));
          } else {
            lines.push(`... ${cs}`);
          }
        } else {
          lines.push("...");
        }
      } else {
        let dc = doc.comment;
        if (dc && chompKeep)
          dc = dc.replace(/^\n+/, "");
        if (dc) {
          if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
            lines.push("");
          lines.push(stringifyComment.indentComment(commentString(dc), ""));
        }
      }
      return lines.join("\n") + "\n";
    }
    __name(stringifyDocument, "stringifyDocument");
    exports2.stringifyDocument = stringifyDocument;
  }
});

// node_modules/yaml/dist/doc/Document.js
var require_Document = __commonJS({
  "node_modules/yaml/dist/doc/Document.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Alias = require_Alias();
    var Collection = require_Collection();
    var identity = require_identity();
    var Pair = require_Pair();
    var toJS = require_toJS();
    var Schema = require_Schema();
    var stringifyDocument = require_stringifyDocument();
    var anchors = require_anchors();
    var applyReviver = require_applyReviver();
    var createNode2 = require_createNode();
    var directives = require_directives();
    var Document2 = class _Document {
      static {
        __name(this, "Document");
      }
      constructor(value, replacer, options2) {
        this.commentBefore = null;
        this.comment = null;
        this.errors = [];
        this.warnings = [];
        Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });
        let _replacer = null;
        if (typeof replacer === "function" || Array.isArray(replacer)) {
          _replacer = replacer;
        } else if (options2 === void 0 && replacer) {
          options2 = replacer;
          replacer = void 0;
        }
        const opt = Object.assign({
          intAsBigInt: false,
          keepSourceTokens: false,
          logLevel: "warn",
          prettyErrors: true,
          strict: true,
          stringKeys: false,
          uniqueKeys: true,
          version: "1.2"
        }, options2);
        this.options = opt;
        let { version: version2 } = opt;
        if (options2?._directives) {
          this.directives = options2._directives.atDocument();
          if (this.directives.yaml.explicit)
            version2 = this.directives.yaml.version;
        } else
          this.directives = new directives.Directives({ version: version2 });
        this.setSchema(version2, options2);
        this.contents = value === void 0 ? null : this.createNode(value, _replacer, options2);
      }
      /**
       * Create a deep copy of this Document and its contents.
       *
       * Custom Node values that inherit from `Object` still refer to their original instances.
       */
      clone() {
        const copy = Object.create(_Document.prototype, {
          [identity.NODE_TYPE]: { value: identity.DOC }
        });
        copy.commentBefore = this.commentBefore;
        copy.comment = this.comment;
        copy.errors = this.errors.slice();
        copy.warnings = this.warnings.slice();
        copy.options = Object.assign({}, this.options);
        if (this.directives)
          copy.directives = this.directives.clone();
        copy.schema = this.schema.clone();
        copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents;
        if (this.range)
          copy.range = this.range.slice();
        return copy;
      }
      /** Adds a value to the document. */
      add(value) {
        if (assertCollection(this.contents))
          this.contents.add(value);
      }
      /** Adds a value to the document. */
      addIn(path150, value) {
        if (assertCollection(this.contents))
          this.contents.addIn(path150, value);
      }
      /**
       * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
       *
       * If `node` already has an anchor, `name` is ignored.
       * Otherwise, the `node.anchor` value will be set to `name`,
       * or if an anchor with that name is already present in the document,
       * `name` will be used as a prefix for a new unique anchor.
       * If `name` is undefined, the generated anchor will use 'a' as a prefix.
       */
      createAlias(node, name4) {
        if (!node.anchor) {
          const prev = anchors.anchorNames(this);
          node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
          !name4 || prev.has(name4) ? anchors.findNewAnchor(name4 || "a", prev) : name4;
        }
        return new Alias.Alias(node.anchor);
      }
      createNode(value, replacer, options2) {
        let _replacer = void 0;
        if (typeof replacer === "function") {
          value = replacer.call({ "": value }, "", value);
          _replacer = replacer;
        } else if (Array.isArray(replacer)) {
          const keyToStr = /* @__PURE__ */ __name((v2) => typeof v2 === "number" || v2 instanceof String || v2 instanceof Number, "keyToStr");
          const asStr = replacer.filter(keyToStr).map(String);
          if (asStr.length > 0)
            replacer = replacer.concat(asStr);
          _replacer = replacer;
        } else if (options2 === void 0 && replacer) {
          options2 = replacer;
          replacer = void 0;
        }
        const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag: tag2 } = options2 ?? {};
        const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(
          this,
          // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
          anchorPrefix || "a"
        );
        const ctx = {
          aliasDuplicateObjects: aliasDuplicateObjects ?? true,
          keepUndefined: keepUndefined ?? false,
          onAnchor,
          onTagObj,
          replacer: _replacer,
          schema: this.schema,
          sourceObjects
        };
        const node = createNode2.createNode(value, tag2, ctx);
        if (flow && identity.isCollection(node))
          node.flow = true;
        setAnchors();
        return node;
      }
      /**
       * Convert a key and a value into a `Pair` using the current schema,
       * recursively wrapping all values as `Scalar` or `Collection` nodes.
       */
      createPair(key, value, options2 = {}) {
        const k2 = this.createNode(key, null, options2);
        const v2 = this.createNode(value, null, options2);
        return new Pair.Pair(k2, v2);
      }
      /**
       * Removes a value from the document.
       * @returns `true` if the item was found and removed.
       */
      delete(key) {
        return assertCollection(this.contents) ? this.contents.delete(key) : false;
      }
      /**
       * Removes a value from the document.
       * @returns `true` if the item was found and removed.
       */
      deleteIn(path150) {
        if (Collection.isEmptyPath(path150)) {
          if (this.contents == null)
            return false;
          this.contents = null;
          return true;
        }
        return assertCollection(this.contents) ? this.contents.deleteIn(path150) : false;
      }
      /**
       * Returns item at `key`, or `undefined` if not found. By default unwraps
       * scalar values from their surrounding node; to disable set `keepScalar` to
       * `true` (collections are always returned intact).
       */
      get(key, keepScalar) {
        return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0;
      }
      /**
       * Returns item at `path`, or `undefined` if not found. By default unwraps
       * scalar values from their surrounding node; to disable set `keepScalar` to
       * `true` (collections are always returned intact).
       */
      getIn(path150, keepScalar) {
        if (Collection.isEmptyPath(path150))
          return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
        return identity.isCollection(this.contents) ? this.contents.getIn(path150, keepScalar) : void 0;
      }
      /**
       * Checks if the document includes a value with the key `key`.
       */
      has(key) {
        return identity.isCollection(this.contents) ? this.contents.has(key) : false;
      }
      /**
       * Checks if the document includes a value at `path`.
       */
      hasIn(path150) {
        if (Collection.isEmptyPath(path150))
          return this.contents !== void 0;
        return identity.isCollection(this.contents) ? this.contents.hasIn(path150) : false;
      }
      /**
       * Sets a value in this document. For `!!set`, `value` needs to be a
       * boolean to add/remove the item from the set.
       */
      set(key, value) {
        if (this.contents == null) {
          this.contents = Collection.collectionFromPath(this.schema, [key], value);
        } else if (assertCollection(this.contents)) {
          this.contents.set(key, value);
        }
      }
      /**
       * Sets a value in this document. For `!!set`, `value` needs to be a
       * boolean to add/remove the item from the set.
       */
      setIn(path150, value) {
        if (Collection.isEmptyPath(path150)) {
          this.contents = value;
        } else if (this.contents == null) {
          this.contents = Collection.collectionFromPath(this.schema, Array.from(path150), value);
        } else if (assertCollection(this.contents)) {
          this.contents.setIn(path150, value);
        }
      }
      /**
       * Change the YAML version and schema used by the document.
       * A `null` version disables support for directives, explicit tags, anchors, and aliases.
       * It also requires the `schema` option to be given as a `Schema` instance value.
       *
       * Overrides all previously set schema options.
       */
      setSchema(version2, options2 = {}) {
        if (typeof version2 === "number")
          version2 = String(version2);
        let opt;
        switch (version2) {
          case "1.1":
            if (this.directives)
              this.directives.yaml.version = "1.1";
            else
              this.directives = new directives.Directives({ version: "1.1" });
            opt = { resolveKnownTags: false, schema: "yaml-1.1" };
            break;
          case "1.2":
          case "next":
            if (this.directives)
              this.directives.yaml.version = version2;
            else
              this.directives = new directives.Directives({ version: version2 });
            opt = { resolveKnownTags: true, schema: "core" };
            break;
          case null:
            if (this.directives)
              delete this.directives;
            opt = null;
            break;
          default: {
            const sv = JSON.stringify(version2);
            throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
          }
        }
        if (options2.schema instanceof Object)
          this.schema = options2.schema;
        else if (opt)
          this.schema = new Schema.Schema(Object.assign(opt, options2));
        else
          throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
      }
      // json & jsonArg are only used from toJSON()
      toJS({ json: json3, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
        const ctx = {
          anchors: /* @__PURE__ */ new Map(),
          doc: this,
          keep: !json3,
          mapAsMap: mapAsMap === true,
          mapKeyWarned: false,
          maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
        };
        const res = toJS.toJS(this.contents, jsonArg ?? "", ctx);
        if (typeof onAnchor === "function")
          for (const { count, res: res2 } of ctx.anchors.values())
            onAnchor(res2, count);
        return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
      }
      /**
       * A JSON representation of the document `contents`.
       *
       * @param jsonArg Used by `JSON.stringify` to indicate the array index or
       *   property name.
       */
      toJSON(jsonArg, onAnchor) {
        return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
      }
      /** A YAML representation of the document. */
      toString(options2 = {}) {
        if (this.errors.length > 0)
          throw new Error("Document with errors cannot be stringified");
        if ("indent" in options2 && (!Number.isInteger(options2.indent) || Number(options2.indent) <= 0)) {
          const s5 = JSON.stringify(options2.indent);
          throw new Error(`"indent" option must be a positive integer, not ${s5}`);
        }
        return stringifyDocument.stringifyDocument(this, options2);
      }
    };
    function assertCollection(contents) {
      if (identity.isCollection(contents))
        return true;
      throw new Error("Expected a YAML collection as document contents");
    }
    __name(assertCollection, "assertCollection");
    exports2.Document = Document2;
  }
});

// node_modules/yaml/dist/errors.js
var require_errors4 = __commonJS({
  "node_modules/yaml/dist/errors.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var YAMLError = class extends Error {
      static {
        __name(this, "YAMLError");
      }
      constructor(name4, pos2, code2, message) {
        super();
        this.name = name4;
        this.code = code2;
        this.message = message;
        this.pos = pos2;
      }
    };
    var YAMLParseError = class extends YAMLError {
      static {
        __name(this, "YAMLParseError");
      }
      constructor(pos2, code2, message) {
        super("YAMLParseError", pos2, code2, message);
      }
    };
    var YAMLWarning = class extends YAMLError {
      static {
        __name(this, "YAMLWarning");
      }
      constructor(pos2, code2, message) {
        super("YAMLWarning", pos2, code2, message);
      }
    };
    var prettifyError2 = /* @__PURE__ */ __name((src, lc) => (error40) => {
      if (error40.pos[0] === -1)
        return;
      error40.linePos = error40.pos.map((pos2) => lc.linePos(pos2));
      const { line, col } = error40.linePos[0];
      error40.message += ` at line ${line}, column ${col}`;
      let ci = col - 1;
      let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
      if (ci >= 60 && lineStr.length > 80) {
        const trimStart = Math.min(ci - 39, lineStr.length - 79);
        lineStr = "\u2026" + lineStr.substring(trimStart);
        ci -= trimStart - 1;
      }
      if (lineStr.length > 80)
        lineStr = lineStr.substring(0, 79) + "\u2026";
      if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
        let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
        if (prev.length > 80)
          prev = prev.substring(0, 79) + "\u2026\n";
        lineStr = prev + lineStr;
      }
      if (/[^ ]/.test(lineStr)) {
        let count = 1;
        const end = error40.linePos[1];
        if (end && end.line === line && end.col > col) {
          count = Math.max(1, Math.min(end.col - col, 80 - ci));
        }
        const pointer = " ".repeat(ci) + "^".repeat(count);
        error40.message += `:

${lineStr}
${pointer}
`;
      }
    }, "prettifyError");
    exports2.YAMLError = YAMLError;
    exports2.YAMLParseError = YAMLParseError;
    exports2.YAMLWarning = YAMLWarning;
    exports2.prettifyError = prettifyError2;
  }
});

// node_modules/yaml/dist/compose/resolve-props.js
var require_resolve_props = __commonJS({
  "node_modules/yaml/dist/compose/resolve-props.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    function resolveProps(tokens, { flow, indicator, next, offset, onError: onError2, parentIndent, startOnNewline }) {
      let spaceBefore = false;
      let atNewline = startOnNewline;
      let hasSpace = startOnNewline;
      let comment = "";
      let commentSep = "";
      let hasNewline = false;
      let reqSpace = false;
      let tab2 = null;
      let anchor = null;
      let tag2 = null;
      let newlineAfterProp = null;
      let comma = null;
      let found = null;
      let start2 = null;
      for (const token2 of tokens) {
        if (reqSpace) {
          if (token2.type !== "space" && token2.type !== "newline" && token2.type !== "comma")
            onError2(token2.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
          reqSpace = false;
        }
        if (tab2) {
          if (atNewline && token2.type !== "comment" && token2.type !== "newline") {
            onError2(tab2, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
          }
          tab2 = null;
        }
        switch (token2.type) {
          case "space":
            if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token2.source.includes("	")) {
              tab2 = token2;
            }
            hasSpace = true;
            break;
          case "comment": {
            if (!hasSpace)
              onError2(token2, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
            const cb = token2.source.substring(1) || " ";
            if (!comment)
              comment = cb;
            else
              comment += commentSep + cb;
            commentSep = "";
            atNewline = false;
            break;
          }
          case "newline":
            if (atNewline) {
              if (comment)
                comment += token2.source;
              else if (!found || indicator !== "seq-item-ind")
                spaceBefore = true;
            } else
              commentSep += token2.source;
            atNewline = true;
            hasNewline = true;
            if (anchor || tag2)
              newlineAfterProp = token2;
            hasSpace = true;
            break;
          case "anchor":
            if (anchor)
              onError2(token2, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
            if (token2.source.endsWith(":"))
              onError2(token2.offset + token2.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
            anchor = token2;
            start2 ?? (start2 = token2.offset);
            atNewline = false;
            hasSpace = false;
            reqSpace = true;
            break;
          case "tag": {
            if (tag2)
              onError2(token2, "MULTIPLE_TAGS", "A node can have at most one tag");
            tag2 = token2;
            start2 ?? (start2 = token2.offset);
            atNewline = false;
            hasSpace = false;
            reqSpace = true;
            break;
          }
          case indicator:
            if (anchor || tag2)
              onError2(token2, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token2.source} indicator`);
            if (found)
              onError2(token2, "UNEXPECTED_TOKEN", `Unexpected ${token2.source} in ${flow ?? "collection"}`);
            found = token2;
            atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
            hasSpace = false;
            break;
          case "comma":
            if (flow) {
              if (comma)
                onError2(token2, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
              comma = token2;
              atNewline = false;
              hasSpace = false;
              break;
            }
          // else fallthrough
          default:
            onError2(token2, "UNEXPECTED_TOKEN", `Unexpected ${token2.type} token`);
            atNewline = false;
            hasSpace = false;
        }
      }
      const last2 = tokens[tokens.length - 1];
      const end = last2 ? last2.offset + last2.source.length : offset;
      if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) {
        onError2(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
      }
      if (tab2 && (atNewline && tab2.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq"))
        onError2(tab2, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
      return {
        comma,
        found,
        spaceBefore,
        comment,
        hasNewline,
        anchor,
        tag: tag2,
        newlineAfterProp,
        end,
        start: start2 ?? end
      };
    }
    __name(resolveProps, "resolveProps");
    exports2.resolveProps = resolveProps;
  }
});

// node_modules/yaml/dist/compose/util-contains-newline.js
var require_util_contains_newline = __commonJS({
  "node_modules/yaml/dist/compose/util-contains-newline.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    function containsNewline(key) {
      if (!key)
        return null;
      switch (key.type) {
        case "alias":
        case "scalar":
        case "double-quoted-scalar":
        case "single-quoted-scalar":
          if (key.source.includes("\n"))
            return true;
          if (key.end) {
            for (const st2 of key.end)
              if (st2.type === "newline")
                return true;
          }
          return false;
        case "flow-collection":
          for (const it3 of key.items) {
            for (const st2 of it3.start)
              if (st2.type === "newline")
                return true;
            if (it3.sep) {
              for (const st2 of it3.sep)
                if (st2.type === "newline")
                  return true;
            }
            if (containsNewline(it3.key) || containsNewline(it3.value))
              return true;
          }
          return false;
        default:
          return true;
      }
    }
    __name(containsNewline, "containsNewline");
    exports2.containsNewline = containsNewline;
  }
});

// node_modules/yaml/dist/compose/util-flow-indent-check.js
var require_util_flow_indent_check = __commonJS({
  "node_modules/yaml/dist/compose/util-flow-indent-check.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var utilContainsNewline = require_util_contains_newline();
    function flowIndentCheck(indent, fc, onError2) {
      if (fc?.type === "flow-collection") {
        const end = fc.end[0];
        if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) {
          const msg = "Flow end indicator should be more indented than parent";
          onError2(end, "BAD_INDENT", msg, true);
        }
      }
    }
    __name(flowIndentCheck, "flowIndentCheck");
    exports2.flowIndentCheck = flowIndentCheck;
  }
});

// node_modules/yaml/dist/compose/util-map-includes.js
var require_util_map_includes = __commonJS({
  "node_modules/yaml/dist/compose/util-map-includes.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    function mapIncludes(ctx, items, search) {
      const { uniqueKeys } = ctx.options;
      if (uniqueKeys === false)
        return false;
      const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a2, b2) => a2 === b2 || identity.isScalar(a2) && identity.isScalar(b2) && a2.value === b2.value;
      return items.some((pair) => isEqual(pair.key, search));
    }
    __name(mapIncludes, "mapIncludes");
    exports2.mapIncludes = mapIncludes;
  }
});

// node_modules/yaml/dist/compose/resolve-block-map.js
var require_resolve_block_map = __commonJS({
  "node_modules/yaml/dist/compose/resolve-block-map.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Pair = require_Pair();
    var YAMLMap = require_YAMLMap();
    var resolveProps = require_resolve_props();
    var utilContainsNewline = require_util_contains_newline();
    var utilFlowIndentCheck = require_util_flow_indent_check();
    var utilMapIncludes = require_util_map_includes();
    var startColMsg = "All mapping items must start at the same column";
    function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError2, tag2) {
      const NodeClass = tag2?.nodeClass ?? YAMLMap.YAMLMap;
      const map3 = new NodeClass(ctx.schema);
      if (ctx.atRoot)
        ctx.atRoot = false;
      let offset = bm.offset;
      let commentEnd = null;
      for (const collItem of bm.items) {
        const { start: start2, key, sep: sep13, value } = collItem;
        const keyProps = resolveProps.resolveProps(start2, {
          indicator: "explicit-key-ind",
          next: key ?? sep13?.[0],
          offset,
          onError: onError2,
          parentIndent: bm.indent,
          startOnNewline: true
        });
        const implicitKey = !keyProps.found;
        if (implicitKey) {
          if (key) {
            if (key.type === "block-seq")
              onError2(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
            else if ("indent" in key && key.indent !== bm.indent)
              onError2(offset, "BAD_INDENT", startColMsg);
          }
          if (!keyProps.anchor && !keyProps.tag && !sep13) {
            commentEnd = keyProps.end;
            if (keyProps.comment) {
              if (map3.comment)
                map3.comment += "\n" + keyProps.comment;
              else
                map3.comment = keyProps.comment;
            }
            continue;
          }
          if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {
            onError2(key ?? start2[start2.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
          }
        } else if (keyProps.found?.indent !== bm.indent) {
          onError2(offset, "BAD_INDENT", startColMsg);
        }
        ctx.atKey = true;
        const keyStart = keyProps.end;
        const keyNode = key ? composeNode(ctx, key, keyProps, onError2) : composeEmptyNode(ctx, keyStart, start2, null, keyProps, onError2);
        if (ctx.schema.compat)
          utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError2);
        ctx.atKey = false;
        if (utilMapIncludes.mapIncludes(ctx, map3.items, keyNode))
          onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
        const valueProps = resolveProps.resolveProps(sep13 ?? [], {
          indicator: "map-value-ind",
          next: value,
          offset: keyNode.range[2],
          onError: onError2,
          parentIndent: bm.indent,
          startOnNewline: !key || key.type === "block-scalar"
        });
        offset = valueProps.end;
        if (valueProps.found) {
          if (implicitKey) {
            if (value?.type === "block-map" && !valueProps.hasNewline)
              onError2(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
            if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
              onError2(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
          }
          const valueNode = value ? composeNode(ctx, value, valueProps, onError2) : composeEmptyNode(ctx, offset, sep13, null, valueProps, onError2);
          if (ctx.schema.compat)
            utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError2);
          offset = valueNode.range[2];
          const pair = new Pair.Pair(keyNode, valueNode);
          if (ctx.options.keepSourceTokens)
            pair.srcToken = collItem;
          map3.items.push(pair);
        } else {
          if (implicitKey)
            onError2(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
          if (valueProps.comment) {
            if (keyNode.comment)
              keyNode.comment += "\n" + valueProps.comment;
            else
              keyNode.comment = valueProps.comment;
          }
          const pair = new Pair.Pair(keyNode);
          if (ctx.options.keepSourceTokens)
            pair.srcToken = collItem;
          map3.items.push(pair);
        }
      }
      if (commentEnd && commentEnd < offset)
        onError2(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
      map3.range = [bm.offset, offset, commentEnd ?? offset];
      return map3;
    }
    __name(resolveBlockMap, "resolveBlockMap");
    exports2.resolveBlockMap = resolveBlockMap;
  }
});

// node_modules/yaml/dist/compose/resolve-block-seq.js
var require_resolve_block_seq = __commonJS({
  "node_modules/yaml/dist/compose/resolve-block-seq.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var YAMLSeq = require_YAMLSeq();
    var resolveProps = require_resolve_props();
    var utilFlowIndentCheck = require_util_flow_indent_check();
    function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError2, tag2) {
      const NodeClass = tag2?.nodeClass ?? YAMLSeq.YAMLSeq;
      const seq = new NodeClass(ctx.schema);
      if (ctx.atRoot)
        ctx.atRoot = false;
      if (ctx.atKey)
        ctx.atKey = false;
      let offset = bs.offset;
      let commentEnd = null;
      for (const { start: start2, value } of bs.items) {
        const props = resolveProps.resolveProps(start2, {
          indicator: "seq-item-ind",
          next: value,
          offset,
          onError: onError2,
          parentIndent: bs.indent,
          startOnNewline: true
        });
        if (!props.found) {
          if (props.anchor || props.tag || value) {
            if (value && value.type === "block-seq")
              onError2(props.end, "BAD_INDENT", "All sequence items must start at the same column");
            else
              onError2(offset, "MISSING_CHAR", "Sequence item without - indicator");
          } else {
            commentEnd = props.end;
            if (props.comment)
              seq.comment = props.comment;
            continue;
          }
        }
        const node = value ? composeNode(ctx, value, props, onError2) : composeEmptyNode(ctx, props.end, start2, null, props, onError2);
        if (ctx.schema.compat)
          utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError2);
        offset = node.range[2];
        seq.items.push(node);
      }
      seq.range = [bs.offset, offset, commentEnd ?? offset];
      return seq;
    }
    __name(resolveBlockSeq, "resolveBlockSeq");
    exports2.resolveBlockSeq = resolveBlockSeq;
  }
});

// node_modules/yaml/dist/compose/resolve-end.js
var require_resolve_end = __commonJS({
  "node_modules/yaml/dist/compose/resolve-end.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    function resolveEnd(end, offset, reqSpace, onError2) {
      let comment = "";
      if (end) {
        let hasSpace = false;
        let sep13 = "";
        for (const token2 of end) {
          const { source: source2, type } = token2;
          switch (type) {
            case "space":
              hasSpace = true;
              break;
            case "comment": {
              if (reqSpace && !hasSpace)
                onError2(token2, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
              const cb = source2.substring(1) || " ";
              if (!comment)
                comment = cb;
              else
                comment += sep13 + cb;
              sep13 = "";
              break;
            }
            case "newline":
              if (comment)
                sep13 += source2;
              hasSpace = true;
              break;
            default:
              onError2(token2, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
          }
          offset += source2.length;
        }
      }
      return { comment, offset };
    }
    __name(resolveEnd, "resolveEnd");
    exports2.resolveEnd = resolveEnd;
  }
});

// node_modules/yaml/dist/compose/resolve-flow-collection.js
var require_resolve_flow_collection = __commonJS({
  "node_modules/yaml/dist/compose/resolve-flow-collection.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var Pair = require_Pair();
    var YAMLMap = require_YAMLMap();
    var YAMLSeq = require_YAMLSeq();
    var resolveEnd = require_resolve_end();
    var resolveProps = require_resolve_props();
    var utilContainsNewline = require_util_contains_newline();
    var utilMapIncludes = require_util_map_includes();
    var blockMsg = "Block collections are not allowed within flow collections";
    var isBlock = /* @__PURE__ */ __name((token2) => token2 && (token2.type === "block-map" || token2.type === "block-seq"), "isBlock");
    function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError2, tag2) {
      const isMap = fc.start.source === "{";
      const fcName = isMap ? "flow map" : "flow sequence";
      const NodeClass = tag2?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
      const coll = new NodeClass(ctx.schema);
      coll.flow = true;
      const atRoot = ctx.atRoot;
      if (atRoot)
        ctx.atRoot = false;
      if (ctx.atKey)
        ctx.atKey = false;
      let offset = fc.offset + fc.start.source.length;
      for (let i4 = 0; i4 < fc.items.length; ++i4) {
        const collItem = fc.items[i4];
        const { start: start2, key, sep: sep13, value } = collItem;
        const props = resolveProps.resolveProps(start2, {
          flow: fcName,
          indicator: "explicit-key-ind",
          next: key ?? sep13?.[0],
          offset,
          onError: onError2,
          parentIndent: fc.indent,
          startOnNewline: false
        });
        if (!props.found) {
          if (!props.anchor && !props.tag && !sep13 && !value) {
            if (i4 === 0 && props.comma)
              onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
            else if (i4 < fc.items.length - 1)
              onError2(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
            if (props.comment) {
              if (coll.comment)
                coll.comment += "\n" + props.comment;
              else
                coll.comment = props.comment;
            }
            offset = props.end;
            continue;
          }
          if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))
            onError2(
              key,
              // checked by containsNewline()
              "MULTILINE_IMPLICIT_KEY",
              "Implicit keys of flow sequence pairs need to be on a single line"
            );
        }
        if (i4 === 0) {
          if (props.comma)
            onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
        } else {
          if (!props.comma)
            onError2(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
          if (props.comment) {
            let prevItemComment = "";
            loop: for (const st2 of start2) {
              switch (st2.type) {
                case "comma":
                case "space":
                  break;
                case "comment":
                  prevItemComment = st2.source.substring(1);
                  break loop;
                default:
                  break loop;
              }
            }
            if (prevItemComment) {
              let prev = coll.items[coll.items.length - 1];
              if (identity.isPair(prev))
                prev = prev.value ?? prev.key;
              if (prev.comment)
                prev.comment += "\n" + prevItemComment;
              else
                prev.comment = prevItemComment;
              props.comment = props.comment.substring(prevItemComment.length + 1);
            }
          }
        }
        if (!isMap && !sep13 && !props.found) {
          const valueNode = value ? composeNode(ctx, value, props, onError2) : composeEmptyNode(ctx, props.end, sep13, null, props, onError2);
          coll.items.push(valueNode);
          offset = valueNode.range[2];
          if (isBlock(value))
            onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
        } else {
          ctx.atKey = true;
          const keyStart = props.end;
          const keyNode = key ? composeNode(ctx, key, props, onError2) : composeEmptyNode(ctx, keyStart, start2, null, props, onError2);
          if (isBlock(key))
            onError2(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
          ctx.atKey = false;
          const valueProps = resolveProps.resolveProps(sep13 ?? [], {
            flow: fcName,
            indicator: "map-value-ind",
            next: value,
            offset: keyNode.range[2],
            onError: onError2,
            parentIndent: fc.indent,
            startOnNewline: false
          });
          if (valueProps.found) {
            if (!isMap && !props.found && ctx.options.strict) {
              if (sep13)
                for (const st2 of sep13) {
                  if (st2 === valueProps.found)
                    break;
                  if (st2.type === "newline") {
                    onError2(st2, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
                    break;
                  }
                }
              if (props.start < valueProps.found.offset - 1024)
                onError2(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
            }
          } else if (value) {
            if ("source" in value && value.source && value.source[0] === ":")
              onError2(value, "MISSING_CHAR", `Missing space after : in ${fcName}`);
            else
              onError2(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
          }
          const valueNode = value ? composeNode(ctx, value, valueProps, onError2) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep13, null, valueProps, onError2) : null;
          if (valueNode) {
            if (isBlock(value))
              onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
          } else if (valueProps.comment) {
            if (keyNode.comment)
              keyNode.comment += "\n" + valueProps.comment;
            else
              keyNode.comment = valueProps.comment;
          }
          const pair = new Pair.Pair(keyNode, valueNode);
          if (ctx.options.keepSourceTokens)
            pair.srcToken = collItem;
          if (isMap) {
            const map3 = coll;
            if (utilMapIncludes.mapIncludes(ctx, map3.items, keyNode))
              onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
            map3.items.push(pair);
          } else {
            const map3 = new YAMLMap.YAMLMap(ctx.schema);
            map3.flow = true;
            map3.items.push(pair);
            const endRange = (valueNode ?? keyNode).range;
            map3.range = [keyNode.range[0], endRange[1], endRange[2]];
            coll.items.push(map3);
          }
          offset = valueNode ? valueNode.range[2] : valueProps.end;
        }
      }
      const expectedEnd = isMap ? "}" : "]";
      const [ce2, ...ee2] = fc.end;
      let cePos = offset;
      if (ce2 && ce2.source === expectedEnd)
        cePos = ce2.offset + ce2.source.length;
      else {
        const name4 = fcName[0].toUpperCase() + fcName.substring(1);
        const msg = atRoot ? `${name4} must end with a ${expectedEnd}` : `${name4} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
        onError2(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
        if (ce2 && ce2.source.length !== 1)
          ee2.unshift(ce2);
      }
      if (ee2.length > 0) {
        const end = resolveEnd.resolveEnd(ee2, cePos, ctx.options.strict, onError2);
        if (end.comment) {
          if (coll.comment)
            coll.comment += "\n" + end.comment;
          else
            coll.comment = end.comment;
        }
        coll.range = [fc.offset, cePos, end.offset];
      } else {
        coll.range = [fc.offset, cePos, cePos];
      }
      return coll;
    }
    __name(resolveFlowCollection, "resolveFlowCollection");
    exports2.resolveFlowCollection = resolveFlowCollection;
  }
});

// node_modules/yaml/dist/compose/compose-collection.js
var require_compose_collection = __commonJS({
  "node_modules/yaml/dist/compose/compose-collection.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var Scalar = require_Scalar();
    var YAMLMap = require_YAMLMap();
    var YAMLSeq = require_YAMLSeq();
    var resolveBlockMap = require_resolve_block_map();
    var resolveBlockSeq = require_resolve_block_seq();
    var resolveFlowCollection = require_resolve_flow_collection();
    function resolveCollection(CN, ctx, token2, onError2, tagName, tag2) {
      const coll = token2.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token2, onError2, tag2) : token2.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token2, onError2, tag2) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token2, onError2, tag2);
      const Coll = coll.constructor;
      if (tagName === "!" || tagName === Coll.tagName) {
        coll.tag = Coll.tagName;
        return coll;
      }
      if (tagName)
        coll.tag = tagName;
      return coll;
    }
    __name(resolveCollection, "resolveCollection");
    function composeCollection(CN, ctx, token2, props, onError2) {
      const tagToken = props.tag;
      const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg));
      if (token2.type === "block-seq") {
        const { anchor, newlineAfterProp: nl2 } = props;
        const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
        if (lastProp && (!nl2 || nl2.offset < lastProp.offset)) {
          const message = "Missing newline after block sequence props";
          onError2(lastProp, "MISSING_CHAR", message);
        }
      }
      const expType = token2.type === "block-map" ? "map" : token2.type === "block-seq" ? "seq" : token2.start.source === "{" ? "map" : "seq";
      if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") {
        return resolveCollection(CN, ctx, token2, onError2, tagName);
      }
      let tag2 = ctx.schema.tags.find((t5) => t5.tag === tagName && t5.collection === expType);
      if (!tag2) {
        const kt2 = ctx.schema.knownTags[tagName];
        if (kt2 && kt2.collection === expType) {
          ctx.schema.tags.push(Object.assign({}, kt2, { default: false }));
          tag2 = kt2;
        } else {
          if (kt2) {
            onError2(tagToken, "BAD_COLLECTION_TYPE", `${kt2.tag} used for ${expType} collection, but expects ${kt2.collection ?? "scalar"}`, true);
          } else {
            onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
          }
          return resolveCollection(CN, ctx, token2, onError2, tagName);
        }
      }
      const coll = resolveCollection(CN, ctx, token2, onError2, tagName, tag2);
      const res = tag2.resolve?.(coll, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll;
      const node = identity.isNode(res) ? res : new Scalar.Scalar(res);
      node.range = coll.range;
      node.tag = tagName;
      if (tag2?.format)
        node.format = tag2.format;
      return node;
    }
    __name(composeCollection, "composeCollection");
    exports2.composeCollection = composeCollection;
  }
});

// node_modules/yaml/dist/compose/resolve-block-scalar.js
var require_resolve_block_scalar = __commonJS({
  "node_modules/yaml/dist/compose/resolve-block-scalar.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Scalar = require_Scalar();
    function resolveBlockScalar(ctx, scalar, onError2) {
      const start2 = scalar.offset;
      const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError2);
      if (!header)
        return { value: "", type: null, comment: "", range: [start2, start2, start2] };
      const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
      const lines = scalar.source ? splitLines3(scalar.source) : [];
      let chompStart = lines.length;
      for (let i4 = lines.length - 1; i4 >= 0; --i4) {
        const content = lines[i4][1];
        if (content === "" || content === "\r")
          chompStart = i4;
        else
          break;
      }
      if (chompStart === 0) {
        const value2 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : "";
        let end2 = start2 + header.length;
        if (scalar.source)
          end2 += scalar.source.length;
        return { value: value2, type, comment: header.comment, range: [start2, end2, end2] };
      }
      let trimIndent = scalar.indent + header.indent;
      let offset = scalar.offset + header.length;
      let contentStart = 0;
      for (let i4 = 0; i4 < chompStart; ++i4) {
        const [indent, content] = lines[i4];
        if (content === "" || content === "\r") {
          if (header.indent === 0 && indent.length > trimIndent)
            trimIndent = indent.length;
        } else {
          if (indent.length < trimIndent) {
            const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
            onError2(offset + indent.length, "MISSING_CHAR", message);
          }
          if (header.indent === 0)
            trimIndent = indent.length;
          contentStart = i4;
          if (trimIndent === 0 && !ctx.atRoot) {
            const message = "Block scalar values in collections must be indented";
            onError2(offset, "BAD_INDENT", message);
          }
          break;
        }
        offset += indent.length + content.length + 1;
      }
      for (let i4 = lines.length - 1; i4 >= chompStart; --i4) {
        if (lines[i4][0].length > trimIndent)
          chompStart = i4 + 1;
      }
      let value = "";
      let sep13 = "";
      let prevMoreIndented = false;
      for (let i4 = 0; i4 < contentStart; ++i4)
        value += lines[i4][0].slice(trimIndent) + "\n";
      for (let i4 = contentStart; i4 < chompStart; ++i4) {
        let [indent, content] = lines[i4];
        offset += indent.length + content.length + 1;
        const crlf = content[content.length - 1] === "\r";
        if (crlf)
          content = content.slice(0, -1);
        if (content && indent.length < trimIndent) {
          const src = header.indent ? "explicit indentation indicator" : "first line";
          const message = `Block scalar lines must not be less indented than their ${src}`;
          onError2(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
          indent = "";
        }
        if (type === Scalar.Scalar.BLOCK_LITERAL) {
          value += sep13 + indent.slice(trimIndent) + content;
          sep13 = "\n";
        } else if (indent.length > trimIndent || content[0] === "	") {
          if (sep13 === " ")
            sep13 = "\n";
          else if (!prevMoreIndented && sep13 === "\n")
            sep13 = "\n\n";
          value += sep13 + indent.slice(trimIndent) + content;
          sep13 = "\n";
          prevMoreIndented = true;
        } else if (content === "") {
          if (sep13 === "\n")
            value += "\n";
          else
            sep13 = "\n";
        } else {
          value += sep13 + content;
          sep13 = " ";
          prevMoreIndented = false;
        }
      }
      switch (header.chomp) {
        case "-":
          break;
        case "+":
          for (let i4 = chompStart; i4 < lines.length; ++i4)
            value += "\n" + lines[i4][0].slice(trimIndent);
          if (value[value.length - 1] !== "\n")
            value += "\n";
          break;
        default:
          value += "\n";
      }
      const end = start2 + header.length + scalar.source.length;
      return { value, type, comment: header.comment, range: [start2, end, end] };
    }
    __name(resolveBlockScalar, "resolveBlockScalar");
    function parseBlockScalarHeader({ offset, props }, strict, onError2) {
      if (props[0].type !== "block-scalar-header") {
        onError2(props[0], "IMPOSSIBLE", "Block scalar header not found");
        return null;
      }
      const { source: source2 } = props[0];
      const mode = source2[0];
      let indent = 0;
      let chomp = "";
      let error40 = -1;
      for (let i4 = 1; i4 < source2.length; ++i4) {
        const ch = source2[i4];
        if (!chomp && (ch === "-" || ch === "+"))
          chomp = ch;
        else {
          const n3 = Number(ch);
          if (!indent && n3)
            indent = n3;
          else if (error40 === -1)
            error40 = offset + i4;
        }
      }
      if (error40 !== -1)
        onError2(error40, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source2}`);
      let hasSpace = false;
      let comment = "";
      let length = source2.length;
      for (let i4 = 1; i4 < props.length; ++i4) {
        const token2 = props[i4];
        switch (token2.type) {
          case "space":
            hasSpace = true;
          // fallthrough
          case "newline":
            length += token2.source.length;
            break;
          case "comment":
            if (strict && !hasSpace) {
              const message = "Comments must be separated from other tokens by white space characters";
              onError2(token2, "MISSING_CHAR", message);
            }
            length += token2.source.length;
            comment = token2.source.substring(1);
            break;
          case "error":
            onError2(token2, "UNEXPECTED_TOKEN", token2.message);
            length += token2.source.length;
            break;
          /* istanbul ignore next should not happen */
          default: {
            const message = `Unexpected token in block scalar header: ${token2.type}`;
            onError2(token2, "UNEXPECTED_TOKEN", message);
            const ts = token2.source;
            if (ts && typeof ts === "string")
              length += ts.length;
          }
        }
      }
      return { mode, indent, chomp, comment, length };
    }
    __name(parseBlockScalarHeader, "parseBlockScalarHeader");
    function splitLines3(source2) {
      const split = source2.split(/\n( *)/);
      const first2 = split[0];
      const m3 = first2.match(/^( *)/);
      const line0 = m3?.[1] ? [m3[1], first2.slice(m3[1].length)] : ["", first2];
      const lines = [line0];
      for (let i4 = 1; i4 < split.length; i4 += 2)
        lines.push([split[i4], split[i4 + 1]]);
      return lines;
    }
    __name(splitLines3, "splitLines");
    exports2.resolveBlockScalar = resolveBlockScalar;
  }
});

// node_modules/yaml/dist/compose/resolve-flow-scalar.js
var require_resolve_flow_scalar = __commonJS({
  "node_modules/yaml/dist/compose/resolve-flow-scalar.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Scalar = require_Scalar();
    var resolveEnd = require_resolve_end();
    function resolveFlowScalar(scalar, strict, onError2) {
      const { offset, type, source: source2, end } = scalar;
      let _type2;
      let value;
      const _onError2 = /* @__PURE__ */ __name((rel, code2, msg) => onError2(offset + rel, code2, msg), "_onError");
      switch (type) {
        case "scalar":
          _type2 = Scalar.Scalar.PLAIN;
          value = plainValue(source2, _onError2);
          break;
        case "single-quoted-scalar":
          _type2 = Scalar.Scalar.QUOTE_SINGLE;
          value = singleQuotedValue(source2, _onError2);
          break;
        case "double-quoted-scalar":
          _type2 = Scalar.Scalar.QUOTE_DOUBLE;
          value = doubleQuotedValue(source2, _onError2);
          break;
        /* istanbul ignore next should not happen */
        default:
          onError2(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
          return {
            value: "",
            type: null,
            comment: "",
            range: [offset, offset + source2.length, offset + source2.length]
          };
      }
      const valueEnd = offset + source2.length;
      const re3 = resolveEnd.resolveEnd(end, valueEnd, strict, onError2);
      return {
        value,
        type: _type2,
        comment: re3.comment,
        range: [offset, valueEnd, re3.offset]
      };
    }
    __name(resolveFlowScalar, "resolveFlowScalar");
    function plainValue(source2, onError2) {
      let badChar = "";
      switch (source2[0]) {
        /* istanbul ignore next should not happen */
        case "	":
          badChar = "a tab character";
          break;
        case ",":
          badChar = "flow indicator character ,";
          break;
        case "%":
          badChar = "directive indicator character %";
          break;
        case "|":
        case ">": {
          badChar = `block scalar indicator ${source2[0]}`;
          break;
        }
        case "@":
        case "`": {
          badChar = `reserved character ${source2[0]}`;
          break;
        }
      }
      if (badChar)
        onError2(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
      return foldLines(source2);
    }
    __name(plainValue, "plainValue");
    function singleQuotedValue(source2, onError2) {
      if (source2[source2.length - 1] !== "'" || source2.length === 1)
        onError2(source2.length, "MISSING_CHAR", "Missing closing 'quote");
      return foldLines(source2.slice(1, -1)).replace(/''/g, "'");
    }
    __name(singleQuotedValue, "singleQuotedValue");
    function foldLines(source2) {
      let first2, line;
      try {
        first2 = new RegExp("(.*?)(?<![ 	])[ 	]*\r?\n", "sy");
        line = new RegExp("[ 	]*(.*?)(?:(?<![ 	])[ 	]*)?\r?\n", "sy");
      } catch {
        first2 = /(.*?)[ \t]*\r?\n/sy;
        line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
      }
      let match2 = first2.exec(source2);
      if (!match2)
        return source2;
      let res = match2[1];
      let sep13 = " ";
      let pos2 = first2.lastIndex;
      line.lastIndex = pos2;
      while (match2 = line.exec(source2)) {
        if (match2[1] === "") {
          if (sep13 === "\n")
            res += sep13;
          else
            sep13 = "\n";
        } else {
          res += sep13 + match2[1];
          sep13 = " ";
        }
        pos2 = line.lastIndex;
      }
      const last2 = /[ \t]*(.*)/sy;
      last2.lastIndex = pos2;
      match2 = last2.exec(source2);
      return res + sep13 + (match2?.[1] ?? "");
    }
    __name(foldLines, "foldLines");
    function doubleQuotedValue(source2, onError2) {
      let res = "";
      for (let i4 = 1; i4 < source2.length - 1; ++i4) {
        const ch = source2[i4];
        if (ch === "\r" && source2[i4 + 1] === "\n")
          continue;
        if (ch === "\n") {
          const { fold, offset } = foldNewline(source2, i4);
          res += fold;
          i4 = offset;
        } else if (ch === "\\") {
          let next = source2[++i4];
          const cc = escapeCodes[next];
          if (cc)
            res += cc;
          else if (next === "\n") {
            next = source2[i4 + 1];
            while (next === " " || next === "	")
              next = source2[++i4 + 1];
          } else if (next === "\r" && source2[i4 + 1] === "\n") {
            next = source2[++i4 + 1];
            while (next === " " || next === "	")
              next = source2[++i4 + 1];
          } else if (next === "x" || next === "u" || next === "U") {
            const length = { x: 2, u: 4, U: 8 }[next];
            res += parseCharCode(source2, i4 + 1, length, onError2);
            i4 += length;
          } else {
            const raw2 = source2.substr(i4 - 1, 2);
            onError2(i4 - 1, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw2}`);
            res += raw2;
          }
        } else if (ch === " " || ch === "	") {
          const wsStart = i4;
          let next = source2[i4 + 1];
          while (next === " " || next === "	")
            next = source2[++i4 + 1];
          if (next !== "\n" && !(next === "\r" && source2[i4 + 2] === "\n"))
            res += i4 > wsStart ? source2.slice(wsStart, i4 + 1) : ch;
        } else {
          res += ch;
        }
      }
      if (source2[source2.length - 1] !== '"' || source2.length === 1)
        onError2(source2.length, "MISSING_CHAR", 'Missing closing "quote');
      return res;
    }
    __name(doubleQuotedValue, "doubleQuotedValue");
    function foldNewline(source2, offset) {
      let fold = "";
      let ch = source2[offset + 1];
      while (ch === " " || ch === "	" || ch === "\n" || ch === "\r") {
        if (ch === "\r" && source2[offset + 2] !== "\n")
          break;
        if (ch === "\n")
          fold += "\n";
        offset += 1;
        ch = source2[offset + 1];
      }
      if (!fold)
        fold = " ";
      return { fold, offset };
    }
    __name(foldNewline, "foldNewline");
    var escapeCodes = {
      "0": "\0",
      // null character
      a: "\x07",
      // bell character
      b: "\b",
      // backspace
      e: "\x1B",
      // escape character
      f: "\f",
      // form feed
      n: "\n",
      // line feed
      r: "\r",
      // carriage return
      t: "	",
      // horizontal tab
      v: "\v",
      // vertical tab
      N: "\x85",
      // Unicode next line
      _: "\xA0",
      // Unicode non-breaking space
      L: "\u2028",
      // Unicode line separator
      P: "\u2029",
      // Unicode paragraph separator
      " ": " ",
      '"': '"',
      "/": "/",
      "\\": "\\",
      "	": "	"
    };
    function parseCharCode(source2, offset, length, onError2) {
      const cc = source2.substr(offset, length);
      const ok2 = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
      const code2 = ok2 ? parseInt(cc, 16) : NaN;
      if (isNaN(code2)) {
        const raw2 = source2.substr(offset - 2, length + 2);
        onError2(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw2}`);
        return raw2;
      }
      return String.fromCodePoint(code2);
    }
    __name(parseCharCode, "parseCharCode");
    exports2.resolveFlowScalar = resolveFlowScalar;
  }
});

// node_modules/yaml/dist/compose/compose-scalar.js
var require_compose_scalar = __commonJS({
  "node_modules/yaml/dist/compose/compose-scalar.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var identity = require_identity();
    var Scalar = require_Scalar();
    var resolveBlockScalar = require_resolve_block_scalar();
    var resolveFlowScalar = require_resolve_flow_scalar();
    function composeScalar(ctx, token2, tagToken, onError2) {
      const { value, type, comment, range } = token2.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token2, onError2) : resolveFlowScalar.resolveFlowScalar(token2, ctx.options.strict, onError2);
      const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
      let tag2;
      if (ctx.options.stringKeys && ctx.atKey) {
        tag2 = ctx.schema[identity.SCALAR];
      } else if (tagName)
        tag2 = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError2);
      else if (token2.type === "scalar")
        tag2 = findScalarTagByTest(ctx, value, token2, onError2);
      else
        tag2 = ctx.schema[identity.SCALAR];
      let scalar;
      try {
        const res = tag2.resolve(value, (msg) => onError2(tagToken ?? token2, "TAG_RESOLVE_FAILED", msg), ctx.options);
        scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);
      } catch (error40) {
        const msg = error40 instanceof Error ? error40.message : String(error40);
        onError2(tagToken ?? token2, "TAG_RESOLVE_FAILED", msg);
        scalar = new Scalar.Scalar(value);
      }
      scalar.range = range;
      scalar.source = value;
      if (type)
        scalar.type = type;
      if (tagName)
        scalar.tag = tagName;
      if (tag2.format)
        scalar.format = tag2.format;
      if (comment)
        scalar.comment = comment;
      return scalar;
    }
    __name(composeScalar, "composeScalar");
    function findScalarTagByName(schema, value, tagName, tagToken, onError2) {
      if (tagName === "!")
        return schema[identity.SCALAR];
      const matchWithTest = [];
      for (const tag2 of schema.tags) {
        if (!tag2.collection && tag2.tag === tagName) {
          if (tag2.default && tag2.test)
            matchWithTest.push(tag2);
          else
            return tag2;
        }
      }
      for (const tag2 of matchWithTest)
        if (tag2.test?.test(value))
          return tag2;
      const kt2 = schema.knownTags[tagName];
      if (kt2 && !kt2.collection) {
        schema.tags.push(Object.assign({}, kt2, { default: false, test: void 0 }));
        return kt2;
      }
      onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
      return schema[identity.SCALAR];
    }
    __name(findScalarTagByName, "findScalarTagByName");
    function findScalarTagByTest({ atKey, directives, schema }, value, token2, onError2) {
      const tag2 = schema.tags.find((tag3) => (tag3.default === true || atKey && tag3.default === "key") && tag3.test?.test(value)) || schema[identity.SCALAR];
      if (schema.compat) {
        const compat = schema.compat.find((tag3) => tag3.default && tag3.test?.test(value)) ?? schema[identity.SCALAR];
        if (tag2.tag !== compat.tag) {
          const ts = directives.tagString(tag2.tag);
          const cs = directives.tagString(compat.tag);
          const msg = `Value may be parsed as either ${ts} or ${cs}`;
          onError2(token2, "TAG_RESOLVE_FAILED", msg, true);
        }
      }
      return tag2;
    }
    __name(findScalarTagByTest, "findScalarTagByTest");
    exports2.composeScalar = composeScalar;
  }
});

// node_modules/yaml/dist/compose/util-empty-scalar-position.js
var require_util_empty_scalar_position = __commonJS({
  "node_modules/yaml/dist/compose/util-empty-scalar-position.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    function emptyScalarPosition(offset, before, pos2) {
      if (before) {
        pos2 ?? (pos2 = before.length);
        for (let i4 = pos2 - 1; i4 >= 0; --i4) {
          let st2 = before[i4];
          switch (st2.type) {
            case "space":
            case "comment":
            case "newline":
              offset -= st2.source.length;
              continue;
          }
          st2 = before[++i4];
          while (st2?.type === "space") {
            offset += st2.source.length;
            st2 = before[++i4];
          }
          break;
        }
      }
      return offset;
    }
    __name(emptyScalarPosition, "emptyScalarPosition");
    exports2.emptyScalarPosition = emptyScalarPosition;
  }
});

// node_modules/yaml/dist/compose/compose-node.js
var require_compose_node = __commonJS({
  "node_modules/yaml/dist/compose/compose-node.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Alias = require_Alias();
    var identity = require_identity();
    var composeCollection = require_compose_collection();
    var composeScalar = require_compose_scalar();
    var resolveEnd = require_resolve_end();
    var utilEmptyScalarPosition = require_util_empty_scalar_position();
    var CN = { composeNode, composeEmptyNode };
    function composeNode(ctx, token2, props, onError2) {
      const atKey = ctx.atKey;
      const { spaceBefore, comment, anchor, tag: tag2 } = props;
      let node;
      let isSrcToken = true;
      switch (token2.type) {
        case "alias":
          node = composeAlias(ctx, token2, onError2);
          if (anchor || tag2)
            onError2(token2, "ALIAS_PROPS", "An alias node must not specify any properties");
          break;
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar":
        case "block-scalar":
          node = composeScalar.composeScalar(ctx, token2, tag2, onError2);
          if (anchor)
            node.anchor = anchor.source.substring(1);
          break;
        case "block-map":
        case "block-seq":
        case "flow-collection":
          node = composeCollection.composeCollection(CN, ctx, token2, props, onError2);
          if (anchor)
            node.anchor = anchor.source.substring(1);
          break;
        default: {
          const message = token2.type === "error" ? token2.message : `Unsupported token (type: ${token2.type})`;
          onError2(token2, "UNEXPECTED_TOKEN", message);
          node = composeEmptyNode(ctx, token2.offset, void 0, null, props, onError2);
          isSrcToken = false;
        }
      }
      if (anchor && node.anchor === "")
        onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
      if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) {
        const msg = "With stringKeys, all keys must be strings";
        onError2(tag2 ?? token2, "NON_STRING_KEY", msg);
      }
      if (spaceBefore)
        node.spaceBefore = true;
      if (comment) {
        if (token2.type === "scalar" && token2.source === "")
          node.comment = comment;
        else
          node.commentBefore = comment;
      }
      if (ctx.options.keepSourceTokens && isSrcToken)
        node.srcToken = token2;
      return node;
    }
    __name(composeNode, "composeNode");
    function composeEmptyNode(ctx, offset, before, pos2, { spaceBefore, comment, anchor, tag: tag2, end }, onError2) {
      const token2 = {
        type: "scalar",
        offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos2),
        indent: -1,
        source: ""
      };
      const node = composeScalar.composeScalar(ctx, token2, tag2, onError2);
      if (anchor) {
        node.anchor = anchor.source.substring(1);
        if (node.anchor === "")
          onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
      }
      if (spaceBefore)
        node.spaceBefore = true;
      if (comment) {
        node.comment = comment;
        node.range[2] = end;
      }
      return node;
    }
    __name(composeEmptyNode, "composeEmptyNode");
    function composeAlias({ options: options2 }, { offset, source: source2, end }, onError2) {
      const alias = new Alias.Alias(source2.substring(1));
      if (alias.source === "")
        onError2(offset, "BAD_ALIAS", "Alias cannot be an empty string");
      if (alias.source.endsWith(":"))
        onError2(offset + source2.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
      const valueEnd = offset + source2.length;
      const re3 = resolveEnd.resolveEnd(end, valueEnd, options2.strict, onError2);
      alias.range = [offset, valueEnd, re3.offset];
      if (re3.comment)
        alias.comment = re3.comment;
      return alias;
    }
    __name(composeAlias, "composeAlias");
    exports2.composeEmptyNode = composeEmptyNode;
    exports2.composeNode = composeNode;
  }
});

// node_modules/yaml/dist/compose/compose-doc.js
var require_compose_doc = __commonJS({
  "node_modules/yaml/dist/compose/compose-doc.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var Document2 = require_Document();
    var composeNode = require_compose_node();
    var resolveEnd = require_resolve_end();
    var resolveProps = require_resolve_props();
    function composeDoc(options2, directives, { offset, start: start2, value, end }, onError2) {
      const opts = Object.assign({ _directives: directives }, options2);
      const doc = new Document2.Document(void 0, opts);
      const ctx = {
        atKey: false,
        atRoot: true,
        directives: doc.directives,
        options: doc.options,
        schema: doc.schema
      };
      const props = resolveProps.resolveProps(start2, {
        indicator: "doc-start",
        next: value ?? end?.[0],
        offset,
        onError: onError2,
        parentIndent: 0,
        startOnNewline: true
      });
      if (props.found) {
        doc.directives.docStart = true;
        if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline)
          onError2(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
      }
      doc.contents = value ? composeNode.composeNode(ctx, value, props, onError2) : composeNode.composeEmptyNode(ctx, props.end, start2, null, props, onError2);
      const contentEnd = doc.contents.range[2];
      const re3 = resolveEnd.resolveEnd(end, contentEnd, false, onError2);
      if (re3.comment)
        doc.comment = re3.comment;
      doc.range = [offset, contentEnd, re3.offset];
      return doc;
    }
    __name(composeDoc, "composeDoc");
    exports2.composeDoc = composeDoc;
  }
});

// node_modules/yaml/dist/compose/composer.js
var require_composer = __commonJS({
  "node_modules/yaml/dist/compose/composer.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var node_process = __require("process");
    var directives = require_directives();
    var Document2 = require_Document();
    var errors = require_errors4();
    var identity = require_identity();
    var composeDoc = require_compose_doc();
    var resolveEnd = require_resolve_end();
    function getErrorPos(src) {
      if (typeof src === "number")
        return [src, src + 1];
      if (Array.isArray(src))
        return src.length === 2 ? src : [src[0], src[1]];
      const { offset, source: source2 } = src;
      return [offset, offset + (typeof source2 === "string" ? source2.length : 1)];
    }
    __name(getErrorPos, "getErrorPos");
    function parsePrelude(prelude) {
      let comment = "";
      let atComment = false;
      let afterEmptyLine = false;
      for (let i4 = 0; i4 < prelude.length; ++i4) {
        const source2 = prelude[i4];
        switch (source2[0]) {
          case "#":
            comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source2.substring(1) || " ");
            atComment = true;
            afterEmptyLine = false;
            break;
          case "%":
            if (prelude[i4 + 1]?.[0] !== "#")
              i4 += 1;
            atComment = false;
            break;
          default:
            if (!atComment)
              afterEmptyLine = true;
            atComment = false;
        }
      }
      return { comment, afterEmptyLine };
    }
    __name(parsePrelude, "parsePrelude");
    var Composer2 = class {
      static {
        __name(this, "Composer");
      }
      constructor(options2 = {}) {
        this.doc = null;
        this.atDirectives = false;
        this.prelude = [];
        this.errors = [];
        this.warnings = [];
        this.onError = (source2, code2, message, warning) => {
          const pos2 = getErrorPos(source2);
          if (warning)
            this.warnings.push(new errors.YAMLWarning(pos2, code2, message));
          else
            this.errors.push(new errors.YAMLParseError(pos2, code2, message));
        };
        this.directives = new directives.Directives({ version: options2.version || "1.2" });
        this.options = options2;
      }
      decorate(doc, afterDoc) {
        const { comment, afterEmptyLine } = parsePrelude(this.prelude);
        if (comment) {
          const dc = doc.contents;
          if (afterDoc) {
            doc.comment = doc.comment ? `${doc.comment}
${comment}` : comment;
          } else if (afterEmptyLine || doc.directives.docStart || !dc) {
            doc.commentBefore = comment;
          } else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {
            let it3 = dc.items[0];
            if (identity.isPair(it3))
              it3 = it3.key;
            const cb = it3.commentBefore;
            it3.commentBefore = cb ? `${comment}
${cb}` : comment;
          } else {
            const cb = dc.commentBefore;
            dc.commentBefore = cb ? `${comment}
${cb}` : comment;
          }
        }
        if (afterDoc) {
          Array.prototype.push.apply(doc.errors, this.errors);
          Array.prototype.push.apply(doc.warnings, this.warnings);
        } else {
          doc.errors = this.errors;
          doc.warnings = this.warnings;
        }
        this.prelude = [];
        this.errors = [];
        this.warnings = [];
      }
      /**
       * Current stream status information.
       *
       * Mostly useful at the end of input for an empty stream.
       */
      streamInfo() {
        return {
          comment: parsePrelude(this.prelude).comment,
          directives: this.directives,
          errors: this.errors,
          warnings: this.warnings
        };
      }
      /**
       * Compose tokens into documents.
       *
       * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
       * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
       */
      *compose(tokens, forceDoc = false, endOffset = -1) {
        for (const token2 of tokens)
          yield* this.next(token2);
        yield* this.end(forceDoc, endOffset);
      }
      /** Advance the composer by one CST token. */
      *next(token2) {
        if (node_process.env.LOG_STREAM)
          console.dir(token2, { depth: null });
        switch (token2.type) {
          case "directive":
            this.directives.add(token2.source, (offset, message, warning) => {
              const pos2 = getErrorPos(token2);
              pos2[0] += offset;
              this.onError(pos2, "BAD_DIRECTIVE", message, warning);
            });
            this.prelude.push(token2.source);
            this.atDirectives = true;
            break;
          case "document": {
            const doc = composeDoc.composeDoc(this.options, this.directives, token2, this.onError);
            if (this.atDirectives && !doc.directives.docStart)
              this.onError(token2, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
            this.decorate(doc, false);
            if (this.doc)
              yield this.doc;
            this.doc = doc;
            this.atDirectives = false;
            break;
          }
          case "byte-order-mark":
          case "space":
            break;
          case "comment":
          case "newline":
            this.prelude.push(token2.source);
            break;
          case "error": {
            const msg = token2.source ? `${token2.message}: ${JSON.stringify(token2.source)}` : token2.message;
            const error40 = new errors.YAMLParseError(getErrorPos(token2), "UNEXPECTED_TOKEN", msg);
            if (this.atDirectives || !this.doc)
              this.errors.push(error40);
            else
              this.doc.errors.push(error40);
            break;
          }
          case "doc-end": {
            if (!this.doc) {
              const msg = "Unexpected doc-end without preceding document";
              this.errors.push(new errors.YAMLParseError(getErrorPos(token2), "UNEXPECTED_TOKEN", msg));
              break;
            }
            this.doc.directives.docEnd = true;
            const end = resolveEnd.resolveEnd(token2.end, token2.offset + token2.source.length, this.doc.options.strict, this.onError);
            this.decorate(this.doc, true);
            if (end.comment) {
              const dc = this.doc.comment;
              this.doc.comment = dc ? `${dc}
${end.comment}` : end.comment;
            }
            this.doc.range[2] = end.offset;
            break;
          }
          default:
            this.errors.push(new errors.YAMLParseError(getErrorPos(token2), "UNEXPECTED_TOKEN", `Unsupported token ${token2.type}`));
        }
      }
      /**
       * Call at end of input to yield any remaining document.
       *
       * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
       * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
       */
      *end(forceDoc = false, endOffset = -1) {
        if (this.doc) {
          this.decorate(this.doc, true);
          yield this.doc;
          this.doc = null;
        } else if (forceDoc) {
          const opts = Object.assign({ _directives: this.directives }, this.options);
          const doc = new Document2.Document(void 0, opts);
          if (this.atDirectives)
            this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
          doc.range = [0, endOffset, endOffset];
          this.decorate(doc, false);
          yield doc;
        }
      }
    };
    exports2.Composer = Composer2;
  }
});

// node_modules/yaml/dist/parse/cst-scalar.js
var require_cst_scalar = __commonJS({
  "node_modules/yaml/dist/parse/cst-scalar.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var resolveBlockScalar = require_resolve_block_scalar();
    var resolveFlowScalar = require_resolve_flow_scalar();
    var errors = require_errors4();
    var stringifyString = require_stringifyString();
    function resolveAsScalar(token2, strict = true, onError2) {
      if (token2) {
        const _onError2 = /* @__PURE__ */ __name((pos2, code2, message) => {
          const offset = typeof pos2 === "number" ? pos2 : Array.isArray(pos2) ? pos2[0] : pos2.offset;
          if (onError2)
            onError2(offset, code2, message);
          else
            throw new errors.YAMLParseError([offset, offset + 1], code2, message);
        }, "_onError");
        switch (token2.type) {
          case "scalar":
          case "single-quoted-scalar":
          case "double-quoted-scalar":
            return resolveFlowScalar.resolveFlowScalar(token2, strict, _onError2);
          case "block-scalar":
            return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token2, _onError2);
        }
      }
      return null;
    }
    __name(resolveAsScalar, "resolveAsScalar");
    function createScalarToken(value, context2) {
      const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context2;
      const source2 = stringifyString.stringifyString({ type, value }, {
        implicitKey,
        indent: indent > 0 ? " ".repeat(indent) : "",
        inFlow,
        options: { blockQuote: true, lineWidth: -1 }
      });
      const end = context2.end ?? [
        { type: "newline", offset: -1, indent, source: "\n" }
      ];
      switch (source2[0]) {
        case "|":
        case ">": {
          const he2 = source2.indexOf("\n");
          const head = source2.substring(0, he2);
          const body2 = source2.substring(he2 + 1) + "\n";
          const props = [
            { type: "block-scalar-header", offset, indent, source: head }
          ];
          if (!addEndtoBlockProps(props, end))
            props.push({ type: "newline", offset: -1, indent, source: "\n" });
          return { type: "block-scalar", offset, indent, props, source: body2 };
        }
        case '"':
          return { type: "double-quoted-scalar", offset, indent, source: source2, end };
        case "'":
          return { type: "single-quoted-scalar", offset, indent, source: source2, end };
        default:
          return { type: "scalar", offset, indent, source: source2, end };
      }
    }
    __name(createScalarToken, "createScalarToken");
    function setScalarValue(token2, value, context2 = {}) {
      let { afterKey = false, implicitKey = false, inFlow = false, type } = context2;
      let indent = "indent" in token2 ? token2.indent : null;
      if (afterKey && typeof indent === "number")
        indent += 2;
      if (!type)
        switch (token2.type) {
          case "single-quoted-scalar":
            type = "QUOTE_SINGLE";
            break;
          case "double-quoted-scalar":
            type = "QUOTE_DOUBLE";
            break;
          case "block-scalar": {
            const header = token2.props[0];
            if (header.type !== "block-scalar-header")
              throw new Error("Invalid block scalar header");
            type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
            break;
          }
          default:
            type = "PLAIN";
        }
      const source2 = stringifyString.stringifyString({ type, value }, {
        implicitKey: implicitKey || indent === null,
        indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
        inFlow,
        options: { blockQuote: true, lineWidth: -1 }
      });
      switch (source2[0]) {
        case "|":
        case ">":
          setBlockScalarValue(token2, source2);
          break;
        case '"':
          setFlowScalarValue(token2, source2, "double-quoted-scalar");
          break;
        case "'":
          setFlowScalarValue(token2, source2, "single-quoted-scalar");
          break;
        default:
          setFlowScalarValue(token2, source2, "scalar");
      }
    }
    __name(setScalarValue, "setScalarValue");
    function setBlockScalarValue(token2, source2) {
      const he2 = source2.indexOf("\n");
      const head = source2.substring(0, he2);
      const body2 = source2.substring(he2 + 1) + "\n";
      if (token2.type === "block-scalar") {
        const header = token2.props[0];
        if (header.type !== "block-scalar-header")
          throw new Error("Invalid block scalar header");
        header.source = head;
        token2.source = body2;
      } else {
        const { offset } = token2;
        const indent = "indent" in token2 ? token2.indent : -1;
        const props = [
          { type: "block-scalar-header", offset, indent, source: head }
        ];
        if (!addEndtoBlockProps(props, "end" in token2 ? token2.end : void 0))
          props.push({ type: "newline", offset: -1, indent, source: "\n" });
        for (const key of Object.keys(token2))
          if (key !== "type" && key !== "offset")
            delete token2[key];
        Object.assign(token2, { type: "block-scalar", indent, props, source: body2 });
      }
    }
    __name(setBlockScalarValue, "setBlockScalarValue");
    function addEndtoBlockProps(props, end) {
      if (end)
        for (const st2 of end)
          switch (st2.type) {
            case "space":
            case "comment":
              props.push(st2);
              break;
            case "newline":
              props.push(st2);
              return true;
          }
      return false;
    }
    __name(addEndtoBlockProps, "addEndtoBlockProps");
    function setFlowScalarValue(token2, source2, type) {
      switch (token2.type) {
        case "scalar":
        case "double-quoted-scalar":
        case "single-quoted-scalar":
          token2.type = type;
          token2.source = source2;
          break;
        case "block-scalar": {
          const end = token2.props.slice(1);
          let oa = source2.length;
          if (token2.props[0].type === "block-scalar-header")
            oa -= token2.props[0].source.length;
          for (const tok of end)
            tok.offset += oa;
          delete token2.props;
          Object.assign(token2, { type, source: source2, end });
          break;
        }
        case "block-map":
        case "block-seq": {
          const offset = token2.offset + source2.length;
          const nl2 = { type: "newline", offset, indent: token2.indent, source: "\n" };
          delete token2.items;
          Object.assign(token2, { type, source: source2, end: [nl2] });
          break;
        }
        default: {
          const indent = "indent" in token2 ? token2.indent : -1;
          const end = "end" in token2 && Array.isArray(token2.end) ? token2.end.filter((st2) => st2.type === "space" || st2.type === "comment" || st2.type === "newline") : [];
          for (const key of Object.keys(token2))
            if (key !== "type" && key !== "offset")
              delete token2[key];
          Object.assign(token2, { type, indent, source: source2, end });
        }
      }
    }
    __name(setFlowScalarValue, "setFlowScalarValue");
    exports2.createScalarToken = createScalarToken;
    exports2.resolveAsScalar = resolveAsScalar;
    exports2.setScalarValue = setScalarValue;
  }
});

// node_modules/yaml/dist/parse/cst-stringify.js
var require_cst_stringify = __commonJS({
  "node_modules/yaml/dist/parse/cst-stringify.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var stringify4 = /* @__PURE__ */ __name((cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst), "stringify");
    function stringifyToken(token2) {
      switch (token2.type) {
        case "block-scalar": {
          let res = "";
          for (const tok of token2.props)
            res += stringifyToken(tok);
          return res + token2.source;
        }
        case "block-map":
        case "block-seq": {
          let res = "";
          for (const item of token2.items)
            res += stringifyItem(item);
          return res;
        }
        case "flow-collection": {
          let res = token2.start.source;
          for (const item of token2.items)
            res += stringifyItem(item);
          for (const st2 of token2.end)
            res += st2.source;
          return res;
        }
        case "document": {
          let res = stringifyItem(token2);
          if (token2.end)
            for (const st2 of token2.end)
              res += st2.source;
          return res;
        }
        default: {
          let res = token2.source;
          if ("end" in token2 && token2.end)
            for (const st2 of token2.end)
              res += st2.source;
          return res;
        }
      }
    }
    __name(stringifyToken, "stringifyToken");
    function stringifyItem({ start: start2, key, sep: sep13, value }) {
      let res = "";
      for (const st2 of start2)
        res += st2.source;
      if (key)
        res += stringifyToken(key);
      if (sep13)
        for (const st2 of sep13)
          res += st2.source;
      if (value)
        res += stringifyToken(value);
      return res;
    }
    __name(stringifyItem, "stringifyItem");
    exports2.stringify = stringify4;
  }
});

// node_modules/yaml/dist/parse/cst-visit.js
var require_cst_visit = __commonJS({
  "node_modules/yaml/dist/parse/cst-visit.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var BREAK = Symbol("break visit");
    var SKIP2 = Symbol("skip children");
    var REMOVE = Symbol("remove item");
    function visit(cst, visitor) {
      if ("type" in cst && cst.type === "document")
        cst = { start: cst.start, value: cst.value };
      _visit(Object.freeze([]), cst, visitor);
    }
    __name(visit, "visit");
    visit.BREAK = BREAK;
    visit.SKIP = SKIP2;
    visit.REMOVE = REMOVE;
    visit.itemAtPath = (cst, path150) => {
      let item = cst;
      for (const [field, index] of path150) {
        const tok = item?.[field];
        if (tok && "items" in tok) {
          item = tok.items[index];
        } else
          return void 0;
      }
      return item;
    };
    visit.parentCollection = (cst, path150) => {
      const parent = visit.itemAtPath(cst, path150.slice(0, -1));
      const field = path150[path150.length - 1][0];
      const coll = parent?.[field];
      if (coll && "items" in coll)
        return coll;
      throw new Error("Parent collection not found");
    };
    function _visit(path150, item, visitor) {
      let ctrl = visitor(item, path150);
      if (typeof ctrl === "symbol")
        return ctrl;
      for (const field of ["key", "value"]) {
        const token2 = item[field];
        if (token2 && "items" in token2) {
          for (let i4 = 0; i4 < token2.items.length; ++i4) {
            const ci = _visit(Object.freeze(path150.concat([[field, i4]])), token2.items[i4], visitor);
            if (typeof ci === "number")
              i4 = ci - 1;
            else if (ci === BREAK)
              return BREAK;
            else if (ci === REMOVE) {
              token2.items.splice(i4, 1);
              i4 -= 1;
            }
          }
          if (typeof ctrl === "function" && field === "key")
            ctrl = ctrl(item, path150);
        }
      }
      return typeof ctrl === "function" ? ctrl(item, path150) : ctrl;
    }
    __name(_visit, "_visit");
    exports2.visit = visit;
  }
});

// node_modules/yaml/dist/parse/cst.js
var require_cst = __commonJS({
  "node_modules/yaml/dist/parse/cst.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var cstScalar = require_cst_scalar();
    var cstStringify = require_cst_stringify();
    var cstVisit = require_cst_visit();
    var BOM = "\uFEFF";
    var DOCUMENT = "";
    var FLOW_END = "";
    var SCALAR = "";
    var isCollection = /* @__PURE__ */ __name((token2) => !!token2 && "items" in token2, "isCollection");
    var isScalar = /* @__PURE__ */ __name((token2) => !!token2 && (token2.type === "scalar" || token2.type === "single-quoted-scalar" || token2.type === "double-quoted-scalar" || token2.type === "block-scalar"), "isScalar");
    function prettyToken(token2) {
      switch (token2) {
        case BOM:
          return "<BOM>";
        case DOCUMENT:
          return "<DOC>";
        case FLOW_END:
          return "<FLOW_END>";
        case SCALAR:
          return "<SCALAR>";
        default:
          return JSON.stringify(token2);
      }
    }
    __name(prettyToken, "prettyToken");
    function tokenType(source2) {
      switch (source2) {
        case BOM:
          return "byte-order-mark";
        case DOCUMENT:
          return "doc-mode";
        case FLOW_END:
          return "flow-error-end";
        case SCALAR:
          return "scalar";
        case "---":
          return "doc-start";
        case "...":
          return "doc-end";
        case "":
        case "\n":
        case "\r\n":
          return "newline";
        case "-":
          return "seq-item-ind";
        case "?":
          return "explicit-key-ind";
        case ":":
          return "map-value-ind";
        case "{":
          return "flow-map-start";
        case "}":
          return "flow-map-end";
        case "[":
          return "flow-seq-start";
        case "]":
          return "flow-seq-end";
        case ",":
          return "comma";
      }
      switch (source2[0]) {
        case " ":
        case "	":
          return "space";
        case "#":
          return "comment";
        case "%":
          return "directive-line";
        case "*":
          return "alias";
        case "&":
          return "anchor";
        case "!":
          return "tag";
        case "'":
          return "single-quoted-scalar";
        case '"':
          return "double-quoted-scalar";
        case "|":
        case ">":
          return "block-scalar-header";
      }
      return null;
    }
    __name(tokenType, "tokenType");
    exports2.createScalarToken = cstScalar.createScalarToken;
    exports2.resolveAsScalar = cstScalar.resolveAsScalar;
    exports2.setScalarValue = cstScalar.setScalarValue;
    exports2.stringify = cstStringify.stringify;
    exports2.visit = cstVisit.visit;
    exports2.BOM = BOM;
    exports2.DOCUMENT = DOCUMENT;
    exports2.FLOW_END = FLOW_END;
    exports2.SCALAR = SCALAR;
    exports2.isCollection = isCollection;
    exports2.isScalar = isScalar;
    exports2.prettyToken = prettyToken;
    exports2.tokenType = tokenType;
  }
});

// node_modules/yaml/dist/parse/lexer.js
var require_lexer = __commonJS({
  "node_modules/yaml/dist/parse/lexer.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var cst = require_cst();
    function isEmpty(ch) {
      switch (ch) {
        case void 0:
        case " ":
        case "\n":
        case "\r":
        case "	":
          return true;
        default:
          return false;
      }
    }
    __name(isEmpty, "isEmpty");
    var hexDigits3 = new Set("0123456789ABCDEFabcdef");
    var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
    var flowIndicatorChars = new Set(",[]{}");
    var invalidAnchorChars = new Set(" ,[]{}\n\r	");
    var isNotAnchorChar = /* @__PURE__ */ __name((ch) => !ch || invalidAnchorChars.has(ch), "isNotAnchorChar");
    var Lexer = class {
      static {
        __name(this, "Lexer");
      }
      constructor() {
        this.atEnd = false;
        this.blockScalarIndent = -1;
        this.blockScalarKeep = false;
        this.buffer = "";
        this.flowKey = false;
        this.flowLevel = 0;
        this.indentNext = 0;
        this.indentValue = 0;
        this.lineEndPos = null;
        this.next = null;
        this.pos = 0;
      }
      /**
       * Generate YAML tokens from the `source` string. If `incomplete`,
       * a part of the last line may be left as a buffer for the next call.
       *
       * @returns A generator of lexical tokens
       */
      *lex(source2, incomplete = false) {
        if (source2) {
          if (typeof source2 !== "string")
            throw TypeError("source is not a string");
          this.buffer = this.buffer ? this.buffer + source2 : source2;
          this.lineEndPos = null;
        }
        this.atEnd = !incomplete;
        let next = this.next ?? "stream";
        while (next && (incomplete || this.hasChars(1)))
          next = yield* this.parseNext(next);
      }
      atLineEnd() {
        let i4 = this.pos;
        let ch = this.buffer[i4];
        while (ch === " " || ch === "	")
          ch = this.buffer[++i4];
        if (!ch || ch === "#" || ch === "\n")
          return true;
        if (ch === "\r")
          return this.buffer[i4 + 1] === "\n";
        return false;
      }
      charAt(n3) {
        return this.buffer[this.pos + n3];
      }
      continueScalar(offset) {
        let ch = this.buffer[offset];
        if (this.indentNext > 0) {
          let indent = 0;
          while (ch === " ")
            ch = this.buffer[++indent + offset];
          if (ch === "\r") {
            const next = this.buffer[indent + offset + 1];
            if (next === "\n" || !next && !this.atEnd)
              return offset + indent + 1;
          }
          return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1;
        }
        if (ch === "-" || ch === ".") {
          const dt2 = this.buffer.substr(offset, 3);
          if ((dt2 === "---" || dt2 === "...") && isEmpty(this.buffer[offset + 3]))
            return -1;
        }
        return offset;
      }
      getLine() {
        let end = this.lineEndPos;
        if (typeof end !== "number" || end !== -1 && end < this.pos) {
          end = this.buffer.indexOf("\n", this.pos);
          this.lineEndPos = end;
        }
        if (end === -1)
          return this.atEnd ? this.buffer.substring(this.pos) : null;
        if (this.buffer[end - 1] === "\r")
          end -= 1;
        return this.buffer.substring(this.pos, end);
      }
      hasChars(n3) {
        return this.pos + n3 <= this.buffer.length;
      }
      setNext(state) {
        this.buffer = this.buffer.substring(this.pos);
        this.pos = 0;
        this.lineEndPos = null;
        this.next = state;
        return null;
      }
      peek(n3) {
        return this.buffer.substr(this.pos, n3);
      }
      *parseNext(next) {
        switch (next) {
          case "stream":
            return yield* this.parseStream();
          case "line-start":
            return yield* this.parseLineStart();
          case "block-start":
            return yield* this.parseBlockStart();
          case "doc":
            return yield* this.parseDocument();
          case "flow":
            return yield* this.parseFlowCollection();
          case "quoted-scalar":
            return yield* this.parseQuotedScalar();
          case "block-scalar":
            return yield* this.parseBlockScalar();
          case "plain-scalar":
            return yield* this.parsePlainScalar();
        }
      }
      *parseStream() {
        let line = this.getLine();
        if (line === null)
          return this.setNext("stream");
        if (line[0] === cst.BOM) {
          yield* this.pushCount(1);
          line = line.substring(1);
        }
        if (line[0] === "%") {
          let dirEnd = line.length;
          let cs = line.indexOf("#");
          while (cs !== -1) {
            const ch = line[cs - 1];
            if (ch === " " || ch === "	") {
              dirEnd = cs - 1;
              break;
            } else {
              cs = line.indexOf("#", cs + 1);
            }
          }
          while (true) {
            const ch = line[dirEnd - 1];
            if (ch === " " || ch === "	")
              dirEnd -= 1;
            else
              break;
          }
          const n3 = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
          yield* this.pushCount(line.length - n3);
          this.pushNewline();
          return "stream";
        }
        if (this.atLineEnd()) {
          const sp = yield* this.pushSpaces(true);
          yield* this.pushCount(line.length - sp);
          yield* this.pushNewline();
          return "stream";
        }
        yield cst.DOCUMENT;
        return yield* this.parseLineStart();
      }
      *parseLineStart() {
        const ch = this.charAt(0);
        if (!ch && !this.atEnd)
          return this.setNext("line-start");
        if (ch === "-" || ch === ".") {
          if (!this.atEnd && !this.hasChars(4))
            return this.setNext("line-start");
          const s5 = this.peek(3);
          if ((s5 === "---" || s5 === "...") && isEmpty(this.charAt(3))) {
            yield* this.pushCount(3);
            this.indentValue = 0;
            this.indentNext = 0;
            return s5 === "---" ? "doc" : "stream";
          }
        }
        this.indentValue = yield* this.pushSpaces(false);
        if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
          this.indentNext = this.indentValue;
        return yield* this.parseBlockStart();
      }
      *parseBlockStart() {
        const [ch0, ch1] = this.peek(2);
        if (!ch1 && !this.atEnd)
          return this.setNext("block-start");
        if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) {
          const n3 = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
          this.indentNext = this.indentValue + 1;
          this.indentValue += n3;
          return yield* this.parseBlockStart();
        }
        return "doc";
      }
      *parseDocument() {
        yield* this.pushSpaces(true);
        const line = this.getLine();
        if (line === null)
          return this.setNext("doc");
        let n3 = yield* this.pushIndicators();
        switch (line[n3]) {
          case "#":
            yield* this.pushCount(line.length - n3);
          // fallthrough
          case void 0:
            yield* this.pushNewline();
            return yield* this.parseLineStart();
          case "{":
          case "[":
            yield* this.pushCount(1);
            this.flowKey = false;
            this.flowLevel = 1;
            return "flow";
          case "}":
          case "]":
            yield* this.pushCount(1);
            return "doc";
          case "*":
            yield* this.pushUntil(isNotAnchorChar);
            return "doc";
          case '"':
          case "'":
            return yield* this.parseQuotedScalar();
          case "|":
          case ">":
            n3 += yield* this.parseBlockScalarHeader();
            n3 += yield* this.pushSpaces(true);
            yield* this.pushCount(line.length - n3);
            yield* this.pushNewline();
            return yield* this.parseBlockScalar();
          default:
            return yield* this.parsePlainScalar();
        }
      }
      *parseFlowCollection() {
        let nl2, sp;
        let indent = -1;
        do {
          nl2 = yield* this.pushNewline();
          if (nl2 > 0) {
            sp = yield* this.pushSpaces(false);
            this.indentValue = indent = sp;
          } else {
            sp = 0;
          }
          sp += yield* this.pushSpaces(true);
        } while (nl2 + sp > 0);
        const line = this.getLine();
        if (line === null)
          return this.setNext("flow");
        if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) {
          const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
          if (!atFlowEndMarker) {
            this.flowLevel = 0;
            yield cst.FLOW_END;
            return yield* this.parseLineStart();
          }
        }
        let n3 = 0;
        while (line[n3] === ",") {
          n3 += yield* this.pushCount(1);
          n3 += yield* this.pushSpaces(true);
          this.flowKey = false;
        }
        n3 += yield* this.pushIndicators();
        switch (line[n3]) {
          case void 0:
            return "flow";
          case "#":
            yield* this.pushCount(line.length - n3);
            return "flow";
          case "{":
          case "[":
            yield* this.pushCount(1);
            this.flowKey = false;
            this.flowLevel += 1;
            return "flow";
          case "}":
          case "]":
            yield* this.pushCount(1);
            this.flowKey = true;
            this.flowLevel -= 1;
            return this.flowLevel ? "flow" : "doc";
          case "*":
            yield* this.pushUntil(isNotAnchorChar);
            return "flow";
          case '"':
          case "'":
            this.flowKey = true;
            return yield* this.parseQuotedScalar();
          case ":": {
            const next = this.charAt(1);
            if (this.flowKey || isEmpty(next) || next === ",") {
              this.flowKey = false;
              yield* this.pushCount(1);
              yield* this.pushSpaces(true);
              return "flow";
            }
          }
          // fallthrough
          default:
            this.flowKey = false;
            return yield* this.parsePlainScalar();
        }
      }
      *parseQuotedScalar() {
        const quote3 = this.charAt(0);
        let end = this.buffer.indexOf(quote3, this.pos + 1);
        if (quote3 === "'") {
          while (end !== -1 && this.buffer[end + 1] === "'")
            end = this.buffer.indexOf("'", end + 2);
        } else {
          while (end !== -1) {
            let n3 = 0;
            while (this.buffer[end - 1 - n3] === "\\")
              n3 += 1;
            if (n3 % 2 === 0)
              break;
            end = this.buffer.indexOf('"', end + 1);
          }
        }
        const qb = this.buffer.substring(0, end);
        let nl2 = qb.indexOf("\n", this.pos);
        if (nl2 !== -1) {
          while (nl2 !== -1) {
            const cs = this.continueScalar(nl2 + 1);
            if (cs === -1)
              break;
            nl2 = qb.indexOf("\n", cs);
          }
          if (nl2 !== -1) {
            end = nl2 - (qb[nl2 - 1] === "\r" ? 2 : 1);
          }
        }
        if (end === -1) {
          if (!this.atEnd)
            return this.setNext("quoted-scalar");
          end = this.buffer.length;
        }
        yield* this.pushToIndex(end + 1, false);
        return this.flowLevel ? "flow" : "doc";
      }
      *parseBlockScalarHeader() {
        this.blockScalarIndent = -1;
        this.blockScalarKeep = false;
        let i4 = this.pos;
        while (true) {
          const ch = this.buffer[++i4];
          if (ch === "+")
            this.blockScalarKeep = true;
          else if (ch > "0" && ch <= "9")
            this.blockScalarIndent = Number(ch) - 1;
          else if (ch !== "-")
            break;
        }
        return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#");
      }
      *parseBlockScalar() {
        let nl2 = this.pos - 1;
        let indent = 0;
        let ch;
        loop: for (let i5 = this.pos; ch = this.buffer[i5]; ++i5) {
          switch (ch) {
            case " ":
              indent += 1;
              break;
            case "\n":
              nl2 = i5;
              indent = 0;
              break;
            case "\r": {
              const next = this.buffer[i5 + 1];
              if (!next && !this.atEnd)
                return this.setNext("block-scalar");
              if (next === "\n")
                break;
            }
            // fallthrough
            default:
              break loop;
          }
        }
        if (!ch && !this.atEnd)
          return this.setNext("block-scalar");
        if (indent >= this.indentNext) {
          if (this.blockScalarIndent === -1)
            this.indentNext = indent;
          else {
            this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
          }
          do {
            const cs = this.continueScalar(nl2 + 1);
            if (cs === -1)
              break;
            nl2 = this.buffer.indexOf("\n", cs);
          } while (nl2 !== -1);
          if (nl2 === -1) {
            if (!this.atEnd)
              return this.setNext("block-scalar");
            nl2 = this.buffer.length;
          }
        }
        let i4 = nl2 + 1;
        ch = this.buffer[i4];
        while (ch === " ")
          ch = this.buffer[++i4];
        if (ch === "	") {
          while (ch === "	" || ch === " " || ch === "\r" || ch === "\n")
            ch = this.buffer[++i4];
          nl2 = i4 - 1;
        } else if (!this.blockScalarKeep) {
          do {
            let i5 = nl2 - 1;
            let ch2 = this.buffer[i5];
            if (ch2 === "\r")
              ch2 = this.buffer[--i5];
            const lastChar = i5;
            while (ch2 === " ")
              ch2 = this.buffer[--i5];
            if (ch2 === "\n" && i5 >= this.pos && i5 + 1 + indent > lastChar)
              nl2 = i5;
            else
              break;
          } while (true);
        }
        yield cst.SCALAR;
        yield* this.pushToIndex(nl2 + 1, true);
        return yield* this.parseLineStart();
      }
      *parsePlainScalar() {
        const inFlow = this.flowLevel > 0;
        let end = this.pos - 1;
        let i4 = this.pos - 1;
        let ch;
        while (ch = this.buffer[++i4]) {
          if (ch === ":") {
            const next = this.buffer[i4 + 1];
            if (isEmpty(next) || inFlow && flowIndicatorChars.has(next))
              break;
            end = i4;
          } else if (isEmpty(ch)) {
            let next = this.buffer[i4 + 1];
            if (ch === "\r") {
              if (next === "\n") {
                i4 += 1;
                ch = "\n";
                next = this.buffer[i4 + 1];
              } else
                end = i4;
            }
            if (next === "#" || inFlow && flowIndicatorChars.has(next))
              break;
            if (ch === "\n") {
              const cs = this.continueScalar(i4 + 1);
              if (cs === -1)
                break;
              i4 = Math.max(i4, cs - 2);
            }
          } else {
            if (inFlow && flowIndicatorChars.has(ch))
              break;
            end = i4;
          }
        }
        if (!ch && !this.atEnd)
          return this.setNext("plain-scalar");
        yield cst.SCALAR;
        yield* this.pushToIndex(end + 1, true);
        return inFlow ? "flow" : "doc";
      }
      *pushCount(n3) {
        if (n3 > 0) {
          yield this.buffer.substr(this.pos, n3);
          this.pos += n3;
          return n3;
        }
        return 0;
      }
      *pushToIndex(i4, allowEmpty) {
        const s5 = this.buffer.slice(this.pos, i4);
        if (s5) {
          yield s5;
          this.pos += s5.length;
          return s5.length;
        } else if (allowEmpty)
          yield "";
        return 0;
      }
      *pushIndicators() {
        switch (this.charAt(0)) {
          case "!":
            return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
          case "&":
            return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
          case "-":
          // this is an error
          case "?":
          // this is an error outside flow collections
          case ":": {
            const inFlow = this.flowLevel > 0;
            const ch1 = this.charAt(1);
            if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
              if (!inFlow)
                this.indentNext = this.indentValue + 1;
              else if (this.flowKey)
                this.flowKey = false;
              return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
            }
          }
        }
        return 0;
      }
      *pushTag() {
        if (this.charAt(1) === "<") {
          let i4 = this.pos + 2;
          let ch = this.buffer[i4];
          while (!isEmpty(ch) && ch !== ">")
            ch = this.buffer[++i4];
          return yield* this.pushToIndex(ch === ">" ? i4 + 1 : i4, false);
        } else {
          let i4 = this.pos + 1;
          let ch = this.buffer[i4];
          while (ch) {
            if (tagChars.has(ch))
              ch = this.buffer[++i4];
            else if (ch === "%" && hexDigits3.has(this.buffer[i4 + 1]) && hexDigits3.has(this.buffer[i4 + 2])) {
              ch = this.buffer[i4 += 3];
            } else
              break;
          }
          return yield* this.pushToIndex(i4, false);
        }
      }
      *pushNewline() {
        const ch = this.buffer[this.pos];
        if (ch === "\n")
          return yield* this.pushCount(1);
        else if (ch === "\r" && this.charAt(1) === "\n")
          return yield* this.pushCount(2);
        else
          return 0;
      }
      *pushSpaces(allowTabs) {
        let i4 = this.pos - 1;
        let ch;
        do {
          ch = this.buffer[++i4];
        } while (ch === " " || allowTabs && ch === "	");
        const n3 = i4 - this.pos;
        if (n3 > 0) {
          yield this.buffer.substr(this.pos, n3);
          this.pos = i4;
        }
        return n3;
      }
      *pushUntil(test2) {
        let i4 = this.pos;
        let ch = this.buffer[i4];
        while (!test2(ch))
          ch = this.buffer[++i4];
        return yield* this.pushToIndex(i4, false);
      }
    };
    exports2.Lexer = Lexer;
  }
});

// node_modules/yaml/dist/parse/line-counter.js
var require_line_counter = __commonJS({
  "node_modules/yaml/dist/parse/line-counter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var LineCounter = class {
      static {
        __name(this, "LineCounter");
      }
      constructor() {
        this.lineStarts = [];
        this.addNewLine = (offset) => this.lineStarts.push(offset);
        this.linePos = (offset) => {
          let low = 0;
          let high = this.lineStarts.length;
          while (low < high) {
            const mid = low + high >> 1;
            if (this.lineStarts[mid] < offset)
              low = mid + 1;
            else
              high = mid;
          }
          if (this.lineStarts[low] === offset)
            return { line: low + 1, col: 1 };
          if (low === 0)
            return { line: 0, col: offset };
          const start2 = this.lineStarts[low - 1];
          return { line: low, col: offset - start2 + 1 };
        };
      }
    };
    exports2.LineCounter = LineCounter;
  }
});

// node_modules/yaml/dist/parse/parser.js
var require_parser = __commonJS({
  "node_modules/yaml/dist/parse/parser.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var node_process = __require("process");
    var cst = require_cst();
    var lexer2 = require_lexer();
    function includesToken(list3, type) {
      for (let i4 = 0; i4 < list3.length; ++i4)
        if (list3[i4].type === type)
          return true;
      return false;
    }
    __name(includesToken, "includesToken");
    function findNonEmptyIndex(list3) {
      for (let i4 = 0; i4 < list3.length; ++i4) {
        switch (list3[i4].type) {
          case "space":
          case "comment":
          case "newline":
            break;
          default:
            return i4;
        }
      }
      return -1;
    }
    __name(findNonEmptyIndex, "findNonEmptyIndex");
    function isFlowToken(token2) {
      switch (token2?.type) {
        case "alias":
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar":
        case "flow-collection":
          return true;
        default:
          return false;
      }
    }
    __name(isFlowToken, "isFlowToken");
    function getPrevProps(parent) {
      switch (parent.type) {
        case "document":
          return parent.start;
        case "block-map": {
          const it3 = parent.items[parent.items.length - 1];
          return it3.sep ?? it3.start;
        }
        case "block-seq":
          return parent.items[parent.items.length - 1].start;
        /* istanbul ignore next should not happen */
        default:
          return [];
      }
    }
    __name(getPrevProps, "getPrevProps");
    function getFirstKeyStartProps(prev) {
      if (prev.length === 0)
        return [];
      let i4 = prev.length;
      loop: while (--i4 >= 0) {
        switch (prev[i4].type) {
          case "doc-start":
          case "explicit-key-ind":
          case "map-value-ind":
          case "seq-item-ind":
          case "newline":
            break loop;
        }
      }
      while (prev[++i4]?.type === "space") {
      }
      return prev.splice(i4, prev.length);
    }
    __name(getFirstKeyStartProps, "getFirstKeyStartProps");
    function fixFlowSeqItems(fc) {
      if (fc.start.type === "flow-seq-start") {
        for (const it3 of fc.items) {
          if (it3.sep && !it3.value && !includesToken(it3.start, "explicit-key-ind") && !includesToken(it3.sep, "map-value-ind")) {
            if (it3.key)
              it3.value = it3.key;
            delete it3.key;
            if (isFlowToken(it3.value)) {
              if (it3.value.end)
                Array.prototype.push.apply(it3.value.end, it3.sep);
              else
                it3.value.end = it3.sep;
            } else
              Array.prototype.push.apply(it3.start, it3.sep);
            delete it3.sep;
          }
        }
      }
    }
    __name(fixFlowSeqItems, "fixFlowSeqItems");
    var Parser6 = class {
      static {
        __name(this, "Parser");
      }
      /**
       * @param onNewLine - If defined, called separately with the start position of
       *   each new line (in `parse()`, including the start of input).
       */
      constructor(onNewLine) {
        this.atNewLine = true;
        this.atScalar = false;
        this.indent = 0;
        this.offset = 0;
        this.onKeyLine = false;
        this.stack = [];
        this.source = "";
        this.type = "";
        this.lexer = new lexer2.Lexer();
        this.onNewLine = onNewLine;
      }
      /**
       * Parse `source` as a YAML stream.
       * If `incomplete`, a part of the last line may be left as a buffer for the next call.
       *
       * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
       *
       * @returns A generator of tokens representing each directive, document, and other structure.
       */
      *parse(source2, incomplete = false) {
        if (this.onNewLine && this.offset === 0)
          this.onNewLine(0);
        for (const lexeme of this.lexer.lex(source2, incomplete))
          yield* this.next(lexeme);
        if (!incomplete)
          yield* this.end();
      }
      /**
       * Advance the parser by the `source` of one lexical token.
       */
      *next(source2) {
        this.source = source2;
        if (node_process.env.LOG_TOKENS)
          console.log("|", cst.prettyToken(source2));
        if (this.atScalar) {
          this.atScalar = false;
          yield* this.step();
          this.offset += source2.length;
          return;
        }
        const type = cst.tokenType(source2);
        if (!type) {
          const message = `Not a YAML token: ${source2}`;
          yield* this.pop({ type: "error", offset: this.offset, message, source: source2 });
          this.offset += source2.length;
        } else if (type === "scalar") {
          this.atNewLine = false;
          this.atScalar = true;
          this.type = "scalar";
        } else {
          this.type = type;
          yield* this.step();
          switch (type) {
            case "newline":
              this.atNewLine = true;
              this.indent = 0;
              if (this.onNewLine)
                this.onNewLine(this.offset + source2.length);
              break;
            case "space":
              if (this.atNewLine && source2[0] === " ")
                this.indent += source2.length;
              break;
            case "explicit-key-ind":
            case "map-value-ind":
            case "seq-item-ind":
              if (this.atNewLine)
                this.indent += source2.length;
              break;
            case "doc-mode":
            case "flow-error-end":
              return;
            default:
              this.atNewLine = false;
          }
          this.offset += source2.length;
        }
      }
      /** Call at end of input to push out any remaining constructions */
      *end() {
        while (this.stack.length > 0)
          yield* this.pop();
      }
      get sourceToken() {
        const st2 = {
          type: this.type,
          offset: this.offset,
          indent: this.indent,
          source: this.source
        };
        return st2;
      }
      *step() {
        const top2 = this.peek(1);
        if (this.type === "doc-end" && (!top2 || top2.type !== "doc-end")) {
          while (this.stack.length > 0)
            yield* this.pop();
          this.stack.push({
            type: "doc-end",
            offset: this.offset,
            source: this.source
          });
          return;
        }
        if (!top2)
          return yield* this.stream();
        switch (top2.type) {
          case "document":
            return yield* this.document(top2);
          case "alias":
          case "scalar":
          case "single-quoted-scalar":
          case "double-quoted-scalar":
            return yield* this.scalar(top2);
          case "block-scalar":
            return yield* this.blockScalar(top2);
          case "block-map":
            return yield* this.blockMap(top2);
          case "block-seq":
            return yield* this.blockSequence(top2);
          case "flow-collection":
            return yield* this.flowCollection(top2);
          case "doc-end":
            return yield* this.documentEnd(top2);
        }
        yield* this.pop();
      }
      peek(n3) {
        return this.stack[this.stack.length - n3];
      }
      *pop(error40) {
        const token2 = error40 ?? this.stack.pop();
        if (!token2) {
          const message = "Tried to pop an empty stack";
          yield { type: "error", offset: this.offset, source: "", message };
        } else if (this.stack.length === 0) {
          yield token2;
        } else {
          const top2 = this.peek(1);
          if (token2.type === "block-scalar") {
            token2.indent = "indent" in top2 ? top2.indent : 0;
          } else if (token2.type === "flow-collection" && top2.type === "document") {
            token2.indent = 0;
          }
          if (token2.type === "flow-collection")
            fixFlowSeqItems(token2);
          switch (top2.type) {
            case "document":
              top2.value = token2;
              break;
            case "block-scalar":
              top2.props.push(token2);
              break;
            case "block-map": {
              const it3 = top2.items[top2.items.length - 1];
              if (it3.value) {
                top2.items.push({ start: [], key: token2, sep: [] });
                this.onKeyLine = true;
                return;
              } else if (it3.sep) {
                it3.value = token2;
              } else {
                Object.assign(it3, { key: token2, sep: [] });
                this.onKeyLine = !it3.explicitKey;
                return;
              }
              break;
            }
            case "block-seq": {
              const it3 = top2.items[top2.items.length - 1];
              if (it3.value)
                top2.items.push({ start: [], value: token2 });
              else
                it3.value = token2;
              break;
            }
            case "flow-collection": {
              const it3 = top2.items[top2.items.length - 1];
              if (!it3 || it3.value)
                top2.items.push({ start: [], key: token2, sep: [] });
              else if (it3.sep)
                it3.value = token2;
              else
                Object.assign(it3, { key: token2, sep: [] });
              return;
            }
            /* istanbul ignore next should not happen */
            default:
              yield* this.pop();
              yield* this.pop(token2);
          }
          if ((top2.type === "document" || top2.type === "block-map" || top2.type === "block-seq") && (token2.type === "block-map" || token2.type === "block-seq")) {
            const last2 = token2.items[token2.items.length - 1];
            if (last2 && !last2.sep && !last2.value && last2.start.length > 0 && findNonEmptyIndex(last2.start) === -1 && (token2.indent === 0 || last2.start.every((st2) => st2.type !== "comment" || st2.indent < token2.indent))) {
              if (top2.type === "document")
                top2.end = last2.start;
              else
                top2.items.push({ start: last2.start });
              token2.items.splice(-1, 1);
            }
          }
        }
      }
      *stream() {
        switch (this.type) {
          case "directive-line":
            yield { type: "directive", offset: this.offset, source: this.source };
            return;
          case "byte-order-mark":
          case "space":
          case "comment":
          case "newline":
            yield this.sourceToken;
            return;
          case "doc-mode":
          case "doc-start": {
            const doc = {
              type: "document",
              offset: this.offset,
              start: []
            };
            if (this.type === "doc-start")
              doc.start.push(this.sourceToken);
            this.stack.push(doc);
            return;
          }
        }
        yield {
          type: "error",
          offset: this.offset,
          message: `Unexpected ${this.type} token in YAML stream`,
          source: this.source
        };
      }
      *document(doc) {
        if (doc.value)
          return yield* this.lineEnd(doc);
        switch (this.type) {
          case "doc-start": {
            if (findNonEmptyIndex(doc.start) !== -1) {
              yield* this.pop();
              yield* this.step();
            } else
              doc.start.push(this.sourceToken);
            return;
          }
          case "anchor":
          case "tag":
          case "space":
          case "comment":
          case "newline":
            doc.start.push(this.sourceToken);
            return;
        }
        const bv = this.startBlockValue(doc);
        if (bv)
          this.stack.push(bv);
        else {
          yield {
            type: "error",
            offset: this.offset,
            message: `Unexpected ${this.type} token in YAML document`,
            source: this.source
          };
        }
      }
      *scalar(scalar) {
        if (this.type === "map-value-ind") {
          const prev = getPrevProps(this.peek(2));
          const start2 = getFirstKeyStartProps(prev);
          let sep13;
          if (scalar.end) {
            sep13 = scalar.end;
            sep13.push(this.sourceToken);
            delete scalar.end;
          } else
            sep13 = [this.sourceToken];
          const map3 = {
            type: "block-map",
            offset: scalar.offset,
            indent: scalar.indent,
            items: [{ start: start2, key: scalar, sep: sep13 }]
          };
          this.onKeyLine = true;
          this.stack[this.stack.length - 1] = map3;
        } else
          yield* this.lineEnd(scalar);
      }
      *blockScalar(scalar) {
        switch (this.type) {
          case "space":
          case "comment":
          case "newline":
            scalar.props.push(this.sourceToken);
            return;
          case "scalar":
            scalar.source = this.source;
            this.atNewLine = true;
            this.indent = 0;
            if (this.onNewLine) {
              let nl2 = this.source.indexOf("\n") + 1;
              while (nl2 !== 0) {
                this.onNewLine(this.offset + nl2);
                nl2 = this.source.indexOf("\n", nl2) + 1;
              }
            }
            yield* this.pop();
            break;
          /* istanbul ignore next should not happen */
          default:
            yield* this.pop();
            yield* this.step();
        }
      }
      *blockMap(map3) {
        const it3 = map3.items[map3.items.length - 1];
        switch (this.type) {
          case "newline":
            this.onKeyLine = false;
            if (it3.value) {
              const end = "end" in it3.value ? it3.value.end : void 0;
              const last2 = Array.isArray(end) ? end[end.length - 1] : void 0;
              if (last2?.type === "comment")
                end?.push(this.sourceToken);
              else
                map3.items.push({ start: [this.sourceToken] });
            } else if (it3.sep) {
              it3.sep.push(this.sourceToken);
            } else {
              it3.start.push(this.sourceToken);
            }
            return;
          case "space":
          case "comment":
            if (it3.value) {
              map3.items.push({ start: [this.sourceToken] });
            } else if (it3.sep) {
              it3.sep.push(this.sourceToken);
            } else {
              if (this.atIndentedComment(it3.start, map3.indent)) {
                const prev = map3.items[map3.items.length - 2];
                const end = prev?.value?.end;
                if (Array.isArray(end)) {
                  Array.prototype.push.apply(end, it3.start);
                  end.push(this.sourceToken);
                  map3.items.pop();
                  return;
                }
              }
              it3.start.push(this.sourceToken);
            }
            return;
        }
        if (this.indent >= map3.indent) {
          const atMapIndent = !this.onKeyLine && this.indent === map3.indent;
          const atNextItem = atMapIndent && (it3.sep || it3.explicitKey) && this.type !== "seq-item-ind";
          let start2 = [];
          if (atNextItem && it3.sep && !it3.value) {
            const nl2 = [];
            for (let i4 = 0; i4 < it3.sep.length; ++i4) {
              const st2 = it3.sep[i4];
              switch (st2.type) {
                case "newline":
                  nl2.push(i4);
                  break;
                case "space":
                  break;
                case "comment":
                  if (st2.indent > map3.indent)
                    nl2.length = 0;
                  break;
                default:
                  nl2.length = 0;
              }
            }
            if (nl2.length >= 2)
              start2 = it3.sep.splice(nl2[1]);
          }
          switch (this.type) {
            case "anchor":
            case "tag":
              if (atNextItem || it3.value) {
                start2.push(this.sourceToken);
                map3.items.push({ start: start2 });
                this.onKeyLine = true;
              } else if (it3.sep) {
                it3.sep.push(this.sourceToken);
              } else {
                it3.start.push(this.sourceToken);
              }
              return;
            case "explicit-key-ind":
              if (!it3.sep && !it3.explicitKey) {
                it3.start.push(this.sourceToken);
                it3.explicitKey = true;
              } else if (atNextItem || it3.value) {
                start2.push(this.sourceToken);
                map3.items.push({ start: start2, explicitKey: true });
              } else {
                this.stack.push({
                  type: "block-map",
                  offset: this.offset,
                  indent: this.indent,
                  items: [{ start: [this.sourceToken], explicitKey: true }]
                });
              }
              this.onKeyLine = true;
              return;
            case "map-value-ind":
              if (it3.explicitKey) {
                if (!it3.sep) {
                  if (includesToken(it3.start, "newline")) {
                    Object.assign(it3, { key: null, sep: [this.sourceToken] });
                  } else {
                    const start3 = getFirstKeyStartProps(it3.start);
                    this.stack.push({
                      type: "block-map",
                      offset: this.offset,
                      indent: this.indent,
                      items: [{ start: start3, key: null, sep: [this.sourceToken] }]
                    });
                  }
                } else if (it3.value) {
                  map3.items.push({ start: [], key: null, sep: [this.sourceToken] });
                } else if (includesToken(it3.sep, "map-value-ind")) {
                  this.stack.push({
                    type: "block-map",
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start: start2, key: null, sep: [this.sourceToken] }]
                  });
                } else if (isFlowToken(it3.key) && !includesToken(it3.sep, "newline")) {
                  const start3 = getFirstKeyStartProps(it3.start);
                  const key = it3.key;
                  const sep13 = it3.sep;
                  sep13.push(this.sourceToken);
                  delete it3.key;
                  delete it3.sep;
                  this.stack.push({
                    type: "block-map",
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start: start3, key, sep: sep13 }]
                  });
                } else if (start2.length > 0) {
                  it3.sep = it3.sep.concat(start2, this.sourceToken);
                } else {
                  it3.sep.push(this.sourceToken);
                }
              } else {
                if (!it3.sep) {
                  Object.assign(it3, { key: null, sep: [this.sourceToken] });
                } else if (it3.value || atNextItem) {
                  map3.items.push({ start: start2, key: null, sep: [this.sourceToken] });
                } else if (includesToken(it3.sep, "map-value-ind")) {
                  this.stack.push({
                    type: "block-map",
                    offset: this.offset,
                    indent: this.indent,
                    items: [{ start: [], key: null, sep: [this.sourceToken] }]
                  });
                } else {
                  it3.sep.push(this.sourceToken);
                }
              }
              this.onKeyLine = true;
              return;
            case "alias":
            case "scalar":
            case "single-quoted-scalar":
            case "double-quoted-scalar": {
              const fs142 = this.flowScalar(this.type);
              if (atNextItem || it3.value) {
                map3.items.push({ start: start2, key: fs142, sep: [] });
                this.onKeyLine = true;
              } else if (it3.sep) {
                this.stack.push(fs142);
              } else {
                Object.assign(it3, { key: fs142, sep: [] });
                this.onKeyLine = true;
              }
              return;
            }
            default: {
              const bv = this.startBlockValue(map3);
              if (bv) {
                if (bv.type === "block-seq") {
                  if (!it3.explicitKey && it3.sep && !includesToken(it3.sep, "newline")) {
                    yield* this.pop({
                      type: "error",
                      offset: this.offset,
                      message: "Unexpected block-seq-ind on same line with key",
                      source: this.source
                    });
                    return;
                  }
                } else if (atMapIndent) {
                  map3.items.push({ start: start2 });
                }
                this.stack.push(bv);
                return;
              }
            }
          }
        }
        yield* this.pop();
        yield* this.step();
      }
      *blockSequence(seq) {
        const it3 = seq.items[seq.items.length - 1];
        switch (this.type) {
          case "newline":
            if (it3.value) {
              const end = "end" in it3.value ? it3.value.end : void 0;
              const last2 = Array.isArray(end) ? end[end.length - 1] : void 0;
              if (last2?.type === "comment")
                end?.push(this.sourceToken);
              else
                seq.items.push({ start: [this.sourceToken] });
            } else
              it3.start.push(this.sourceToken);
            return;
          case "space":
          case "comment":
            if (it3.value)
              seq.items.push({ start: [this.sourceToken] });
            else {
              if (this.atIndentedComment(it3.start, seq.indent)) {
                const prev = seq.items[seq.items.length - 2];
                const end = prev?.value?.end;
                if (Array.isArray(end)) {
                  Array.prototype.push.apply(end, it3.start);
                  end.push(this.sourceToken);
                  seq.items.pop();
                  return;
                }
              }
              it3.start.push(this.sourceToken);
            }
            return;
          case "anchor":
          case "tag":
            if (it3.value || this.indent <= seq.indent)
              break;
            it3.start.push(this.sourceToken);
            return;
          case "seq-item-ind":
            if (this.indent !== seq.indent)
              break;
            if (it3.value || includesToken(it3.start, "seq-item-ind"))
              seq.items.push({ start: [this.sourceToken] });
            else
              it3.start.push(this.sourceToken);
            return;
        }
        if (this.indent > seq.indent) {
          const bv = this.startBlockValue(seq);
          if (bv) {
            this.stack.push(bv);
            return;
          }
        }
        yield* this.pop();
        yield* this.step();
      }
      *flowCollection(fc) {
        const it3 = fc.items[fc.items.length - 1];
        if (this.type === "flow-error-end") {
          let top2;
          do {
            yield* this.pop();
            top2 = this.peek(1);
          } while (top2 && top2.type === "flow-collection");
        } else if (fc.end.length === 0) {
          switch (this.type) {
            case "comma":
            case "explicit-key-ind":
              if (!it3 || it3.sep)
                fc.items.push({ start: [this.sourceToken] });
              else
                it3.start.push(this.sourceToken);
              return;
            case "map-value-ind":
              if (!it3 || it3.value)
                fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
              else if (it3.sep)
                it3.sep.push(this.sourceToken);
              else
                Object.assign(it3, { key: null, sep: [this.sourceToken] });
              return;
            case "space":
            case "comment":
            case "newline":
            case "anchor":
            case "tag":
              if (!it3 || it3.value)
                fc.items.push({ start: [this.sourceToken] });
              else if (it3.sep)
                it3.sep.push(this.sourceToken);
              else
                it3.start.push(this.sourceToken);
              return;
            case "alias":
            case "scalar":
            case "single-quoted-scalar":
            case "double-quoted-scalar": {
              const fs142 = this.flowScalar(this.type);
              if (!it3 || it3.value)
                fc.items.push({ start: [], key: fs142, sep: [] });
              else if (it3.sep)
                this.stack.push(fs142);
              else
                Object.assign(it3, { key: fs142, sep: [] });
              return;
            }
            case "flow-map-end":
            case "flow-seq-end":
              fc.end.push(this.sourceToken);
              return;
          }
          const bv = this.startBlockValue(fc);
          if (bv)
            this.stack.push(bv);
          else {
            yield* this.pop();
            yield* this.step();
          }
        } else {
          const parent = this.peek(2);
          if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
            yield* this.pop();
            yield* this.step();
          } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
            const prev = getPrevProps(parent);
            const start2 = getFirstKeyStartProps(prev);
            fixFlowSeqItems(fc);
            const sep13 = fc.end.splice(1, fc.end.length);
            sep13.push(this.sourceToken);
            const map3 = {
              type: "block-map",
              offset: fc.offset,
              indent: fc.indent,
              items: [{ start: start2, key: fc, sep: sep13 }]
            };
            this.onKeyLine = true;
            this.stack[this.stack.length - 1] = map3;
          } else {
            yield* this.lineEnd(fc);
          }
        }
      }
      flowScalar(type) {
        if (this.onNewLine) {
          let nl2 = this.source.indexOf("\n") + 1;
          while (nl2 !== 0) {
            this.onNewLine(this.offset + nl2);
            nl2 = this.source.indexOf("\n", nl2) + 1;
          }
        }
        return {
          type,
          offset: this.offset,
          indent: this.indent,
          source: this.source
        };
      }
      startBlockValue(parent) {
        switch (this.type) {
          case "alias":
          case "scalar":
          case "single-quoted-scalar":
          case "double-quoted-scalar":
            return this.flowScalar(this.type);
          case "block-scalar-header":
            return {
              type: "block-scalar",
              offset: this.offset,
              indent: this.indent,
              props: [this.sourceToken],
              source: ""
            };
          case "flow-map-start":
          case "flow-seq-start":
            return {
              type: "flow-collection",
              offset: this.offset,
              indent: this.indent,
              start: this.sourceToken,
              items: [],
              end: []
            };
          case "seq-item-ind":
            return {
              type: "block-seq",
              offset: this.offset,
              indent: this.indent,
              items: [{ start: [this.sourceToken] }]
            };
          case "explicit-key-ind": {
            this.onKeyLine = true;
            const prev = getPrevProps(parent);
            const start2 = getFirstKeyStartProps(prev);
            start2.push(this.sourceToken);
            return {
              type: "block-map",
              offset: this.offset,
              indent: this.indent,
              items: [{ start: start2, explicitKey: true }]
            };
          }
          case "map-value-ind": {
            this.onKeyLine = true;
            const prev = getPrevProps(parent);
            const start2 = getFirstKeyStartProps(prev);
            return {
              type: "block-map",
              offset: this.offset,
              indent: this.indent,
              items: [{ start: start2, key: null, sep: [this.sourceToken] }]
            };
          }
        }
        return null;
      }
      atIndentedComment(start2, indent) {
        if (this.type !== "comment")
          return false;
        if (this.indent <= indent)
          return false;
        return start2.every((st2) => st2.type === "newline" || st2.type === "space");
      }
      *documentEnd(docEnd) {
        if (this.type !== "doc-mode") {
          if (docEnd.end)
            docEnd.end.push(this.sourceToken);
          else
            docEnd.end = [this.sourceToken];
          if (this.type === "newline")
            yield* this.pop();
        }
      }
      *lineEnd(token2) {
        switch (this.type) {
          case "comma":
          case "doc-start":
          case "doc-end":
          case "flow-seq-end":
          case "flow-map-end":
          case "map-value-ind":
            yield* this.pop();
            yield* this.step();
            break;
          case "newline":
            this.onKeyLine = false;
          // fallthrough
          case "space":
          case "comment":
          default:
            if (token2.end)
              token2.end.push(this.sourceToken);
            else
              token2.end = [this.sourceToken];
            if (this.type === "newline")
              yield* this.pop();
        }
      }
    };
    exports2.Parser = Parser6;
  }
});

// node_modules/yaml/dist/public-api.js
var require_public_api2 = __commonJS({
  "node_modules/yaml/dist/public-api.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var composer = require_composer();
    var Document2 = require_Document();
    var errors = require_errors4();
    var log = require_log();
    var identity = require_identity();
    var lineCounter = require_line_counter();
    var parser6 = require_parser();
    function parseOptions(options2) {
      const prettyErrors = options2.prettyErrors !== false;
      const lineCounter$1 = options2.lineCounter || prettyErrors && new lineCounter.LineCounter() || null;
      return { lineCounter: lineCounter$1, prettyErrors };
    }
    __name(parseOptions, "parseOptions");
    function parseAllDocuments(source2, options2 = {}) {
      const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options2);
      const parser$1 = new parser6.Parser(lineCounter2?.addNewLine);
      const composer$1 = new composer.Composer(options2);
      const docs = Array.from(composer$1.compose(parser$1.parse(source2)));
      if (prettyErrors && lineCounter2)
        for (const doc of docs) {
          doc.errors.forEach(errors.prettifyError(source2, lineCounter2));
          doc.warnings.forEach(errors.prettifyError(source2, lineCounter2));
        }
      if (docs.length > 0)
        return docs;
      return Object.assign([], { empty: true }, composer$1.streamInfo());
    }
    __name(parseAllDocuments, "parseAllDocuments");
    function parseDocument2(source2, options2 = {}) {
      const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options2);
      const parser$1 = new parser6.Parser(lineCounter2?.addNewLine);
      const composer$1 = new composer.Composer(options2);
      let doc = null;
      for (const _doc of composer$1.compose(parser$1.parse(source2), true, source2.length)) {
        if (!doc)
          doc = _doc;
        else if (doc.options.logLevel !== "silent") {
          doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
          break;
        }
      }
      if (prettyErrors && lineCounter2) {
        doc.errors.forEach(errors.prettifyError(source2, lineCounter2));
        doc.warnings.forEach(errors.prettifyError(source2, lineCounter2));
      }
      return doc;
    }
    __name(parseDocument2, "parseDocument");
    function parse17(src, reviver, options2) {
      let _reviver = void 0;
      if (typeof reviver === "function") {
        _reviver = reviver;
      } else if (options2 === void 0 && reviver && typeof reviver === "object") {
        options2 = reviver;
      }
      const doc = parseDocument2(src, options2);
      if (!doc)
        return null;
      doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning));
      if (doc.errors.length > 0) {
        if (doc.options.logLevel !== "silent")
          throw doc.errors[0];
        else
          doc.errors = [];
      }
      return doc.toJS(Object.assign({ reviver: _reviver }, options2));
    }
    __name(parse17, "parse");
    function stringify4(value, replacer, options2) {
      let _replacer = null;
      if (typeof replacer === "function" || Array.isArray(replacer)) {
        _replacer = replacer;
      } else if (options2 === void 0 && replacer) {
        options2 = replacer;
      }
      if (typeof options2 === "string")
        options2 = options2.length;
      if (typeof options2 === "number") {
        const indent = Math.round(options2);
        options2 = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent };
      }
      if (value === void 0) {
        const { keepUndefined } = options2 ?? replacer ?? {};
        if (!keepUndefined)
          return void 0;
      }
      if (identity.isDocument(value) && !_replacer)
        return value.toString(options2);
      return new Document2.Document(value, _replacer, options2).toString(options2);
    }
    __name(stringify4, "stringify");
    exports2.parse = parse17;
    exports2.parseAllDocuments = parseAllDocuments;
    exports2.parseDocument = parseDocument2;
    exports2.stringify = stringify4;
  }
});

// node_modules/yaml/dist/index.js
var require_dist6 = __commonJS({
  "node_modules/yaml/dist/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var composer = require_composer();
    var Document2 = require_Document();
    var Schema = require_Schema();
    var errors = require_errors4();
    var Alias = require_Alias();
    var identity = require_identity();
    var Pair = require_Pair();
    var Scalar = require_Scalar();
    var YAMLMap = require_YAMLMap();
    var YAMLSeq = require_YAMLSeq();
    var cst = require_cst();
    var lexer2 = require_lexer();
    var lineCounter = require_line_counter();
    var parser6 = require_parser();
    var publicApi = require_public_api2();
    var visit = require_visit();
    exports2.Composer = composer.Composer;
    exports2.Document = Document2.Document;
    exports2.Schema = Schema.Schema;
    exports2.YAMLError = errors.YAMLError;
    exports2.YAMLParseError = errors.YAMLParseError;
    exports2.YAMLWarning = errors.YAMLWarning;
    exports2.Alias = Alias.Alias;
    exports2.isAlias = identity.isAlias;
    exports2.isCollection = identity.isCollection;
    exports2.isDocument = identity.isDocument;
    exports2.isMap = identity.isMap;
    exports2.isNode = identity.isNode;
    exports2.isPair = identity.isPair;
    exports2.isScalar = identity.isScalar;
    exports2.isSeq = identity.isSeq;
    exports2.Pair = Pair.Pair;
    exports2.Scalar = Scalar.Scalar;
    exports2.YAMLMap = YAMLMap.YAMLMap;
    exports2.YAMLSeq = YAMLSeq.YAMLSeq;
    exports2.CST = cst;
    exports2.Lexer = lexer2.Lexer;
    exports2.LineCounter = lineCounter.LineCounter;
    exports2.Parser = parser6.Parser;
    exports2.parse = publicApi.parse;
    exports2.parseAllDocuments = publicApi.parseAllDocuments;
    exports2.parseDocument = publicApi.parseDocument;
    exports2.stringify = publicApi.stringify;
    exports2.visit = visit.visit;
    exports2.visitAsync = visit.visitAsync;
  }
});

// packages/core/dist/src/skills/types.js
function parseModelField(frontmatter) {
  const raw2 = frontmatter["model"];
  if (raw2 === void 0) {
    return void 0;
  }
  if (typeof raw2 !== "string") {
    throw new Error('"model" must be a string');
  }
  const trimmed2 = raw2.trim();
  if (trimmed2 === "" || trimmed2 === "inherit") {
    return void 0;
  }
  return trimmed2;
}
var SkillError, SkillErrorCode;
var init_types14 = __esm({
  "packages/core/dist/src/skills/types.js"() {
    "use strict";
    init_esbuild_shims();
    __name(parseModelField, "parseModelField");
    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 fs49 from "fs/promises";
import * as path48 from "path";
async function loadSkillsFromDir(baseDir) {
  debugLogger60.debug(`Loading skills from directory (skill-load): ${baseDir}`);
  try {
    const entries = await fs49.readdir(baseDir, { withFileTypes: true });
    const skills = [];
    debugLogger60.debug(`Found ${entries.length} entries in ${baseDir}`);
    for (const entry of entries) {
      if (!entry.isDirectory()) {
        debugLogger60.warn(`Skipping non-directory entry: ${entry.name}`);
        continue;
      }
      const skillDir = path48.join(baseDir, entry.name);
      const skillManifest = path48.join(skillDir, SKILL_MANIFEST_FILE);
      try {
        await fs49.access(skillManifest);
        const content = await fs49.readFile(skillManifest, "utf8");
        const config2 = parseSkillContent(content, skillManifest);
        skills.push(config2);
      } catch (error40) {
        const errorMessage = error40 instanceof Error ? error40.message : "Unknown error";
        debugLogger60.error(`Failed to parse skill at ${skillDir}: ${errorMessage}`);
        continue;
      }
    }
    return skills;
  } catch (error40) {
    const errorMessage = error40 instanceof Error ? error40.message : "Unknown error";
    debugLogger60.debug(`Cannot read skills directory ${baseDir}: ${errorMessage}`);
    return [];
  }
}
function parseSkillContent(content, filePath) {
  debugLogger60.debug(`Parsing skill content from: ${filePath}`);
  const normalizedContent = normalizeContent(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, body2] = match2;
  const frontmatter = parse8(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 name4 = 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 model = parseModelField(frontmatter);
  const argumentHint = typeof frontmatter["argument-hint"] === "string" ? frontmatter["argument-hint"] : void 0;
  const config2 = {
    name: name4,
    description,
    allowedTools,
    argumentHint,
    model,
    filePath,
    body: body2.trim(),
    level: "extension"
  };
  const validation2 = validateConfig(config2);
  if (!validation2.isValid) {
    throw new Error(`Validation failed: ${validation2.errors.join(", ")}`);
  }
  debugLogger60.debug(`Successfully parsed skill: ${name4} 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 debugLogger60, SKILL_MANIFEST_FILE;
var init_skill_load = __esm({
  "packages/core/dist/src/skills/skill-load.js"() {
    "use strict";
    init_esbuild_shims();
    init_types14();
    init_yaml_parser();
    init_debugLogger();
    init_textUtils();
    debugLogger60 = createDebugLogger("SKILL_LOAD");
    SKILL_MANIFEST_FILE = "SKILL.md";
    __name(loadSkillsFromDir, "loadSkillsFromDir");
    __name(parseSkillContent, "parseSkillContent");
    __name(validateConfig, "validateConfig");
  }
});

// packages/core/dist/src/skills/skill-manager.js
import * as fs50 from "fs/promises";
import * as fsSync from "fs";
import * as path49 from "path";
import * as os23 from "os";
import { fileURLToPath as fileURLToPath7 } from "url";
function watcherIgnored(filePath, stats) {
  if (stats && !stats.isFile() && !stats.isDirectory())
    return true;
  return filePath.split(path49.sep).includes(".git");
}
var yaml, debugLogger61, QWEN_CONFIG_DIR2, SKILLS_CONFIG_DIR, SKILL_MANIFEST_FILE2, WATCHER_MAX_DEPTH, SkillManager;
var init_skill_manager = __esm({
  "packages/core/dist/src/skills/skill-manager.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm15();
    init_yaml_parser();
    yaml = __toESM(require_dist6(), 1);
    init_types14();
    init_skill_load();
    init_debugLogger();
    init_textUtils();
    init_storage();
    init_types6();
    debugLogger61 = createDebugLogger("SKILL_MANAGER");
    QWEN_CONFIG_DIR2 = ".qwen";
    SKILLS_CONFIG_DIR = "skills";
    SKILL_MANIFEST_FILE2 = "SKILL.md";
    WATCHER_MAX_DEPTH = 2;
    __name(watcherIgnored, "watcherIgnored");
    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;
      bundledSkillsDir;
      constructor(config2) {
        this.config = config2;
        this.bundledSkillsDir = path49.join(path49.dirname(fileURLToPath7(import.meta.url)), "bundled");
      }
      /**
       * 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 (error40) {
            debugLogger61.warn("Skill change listener threw an error:", error40);
          }
        }
      }
      /**
       * 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 = {}) {
        debugLogger61.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", "bundled"];
        const shouldUseCache = !options2.force && this.skillsCache !== null;
        if (!shouldUseCache) {
          debugLogger61.debug("Cache miss or force refresh, reloading skills");
          await this.refreshCache();
        } else {
          debugLogger61.debug("Using cached skills");
        }
        for (const level of levelsToCheck) {
          const levelSkills = this.skillsCache?.get(level) || [];
          debugLogger61.debug(`Processing ${levelSkills.length} ${level} level skills`);
          for (const skill of levelSkills) {
            if (seenNames.has(skill.name)) {
              debugLogger61.debug(`Skipping duplicate skill: ${skill.name} (${level})`);
              continue;
            }
            skills.push(skill);
            seenNames.add(skill.name);
          }
        }
        skills.sort((a2, b2) => a2.name.localeCompare(b2.name));
        debugLogger61.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 in precedence order: project > user > extension > bundled.
       *
       * @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(name4, level) {
        debugLogger61.debug(`Loading skill: ${name4}${level ? ` at level: ${level}` : ""}`);
        if (level) {
          const skill = await this.findSkillByNameAtLevel(name4, level);
          if (skill) {
            debugLogger61.debug(`Found skill ${name4} at ${level} level`);
          } else {
            debugLogger61.debug(`Skill ${name4} not found at ${level} level`);
          }
          return skill;
        }
        const projectSkill = await this.findSkillByNameAtLevel(name4, "project");
        if (projectSkill) {
          debugLogger61.debug(`Found skill ${name4} at project level`);
          return projectSkill;
        }
        const userSkill = await this.findSkillByNameAtLevel(name4, "user");
        if (userSkill) {
          debugLogger61.debug(`Found skill ${name4} at user level`);
          return userSkill;
        }
        const extensionSkill = await this.findSkillByNameAtLevel(name4, "extension");
        if (extensionSkill) {
          debugLogger61.debug(`Found skill ${name4} at extension level`);
          return extensionSkill;
        }
        const bundledSkill = await this.findSkillByNameAtLevel(name4, "bundled");
        if (bundledSkill) {
          debugLogger61.debug(`Found skill ${name4} at bundled level`);
        } else {
          debugLogger61.debug(`Skill ${name4} not found at any level (checked: project, user, extension, bundled)`);
        }
        return bundledSkill;
      }
      /**
       * 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(name4, level) {
        debugLogger61.debug(`Loading skill for runtime: ${name4}${level ? ` at level: ${level}` : ""}`);
        const skill = await this.loadSkill(name4, level);
        if (!skill) {
          debugLogger61.debug(`Skill not found for runtime: ${name4}`);
          return null;
        }
        debugLogger61.info(`Skill loaded for runtime: ${name4} 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() {
        debugLogger61.info("Refreshing skills cache...");
        const skillsCache = /* @__PURE__ */ new Map();
        this.parseErrors.clear();
        const levels = ["project", "user", "extension", "bundled"];
        let totalSkills = 0;
        for (const level of levels) {
          const levelSkills = await this.listSkillsAtLevel(level);
          skillsCache.set(level, levelSkills);
          totalSkills += levelSkills.length;
          debugLogger61.debug(`Loaded ${levelSkills.length} ${level} level skills`);
        }
        this.skillsCache = skillsCache;
        debugLogger61.info(`Skills cache refreshed: ${totalSkills} total skills loaded`);
        this.notifyChangeListeners();
      }
      /**
       * Starts watching skill directories for changes.
       */
      async startWatching() {
        if (this.watchStarted) {
          debugLogger61.debug("Skill watching already started, skipping");
          return;
        }
        if (this.config.getBareMode()) {
          debugLogger61.info("Bare mode enabled; refreshing skill cache without starting watchers");
          await this.refreshCache();
          return;
        }
        debugLogger61.info("Starting skill directory watchers...");
        this.watchStarted = true;
        await this.ensureUserSkillsDir();
        await this.refreshCache();
        this.updateWatchersFromCache();
        debugLogger61.info("Skill directory watchers started");
      }
      /**
       * Stops watching skill directories for changes.
       */
      stopWatching() {
        debugLogger61.info("Stopping skill directory watchers...");
        for (const watcher of this.watchers.values()) {
          void watcher.close().catch((error40) => {
            debugLogger61.warn("Failed to close skills watcher:", error40);
          });
        }
        this.watchers.clear();
        this.watchStarted = false;
        if (this.refreshTimer) {
          clearTimeout(this.refreshTimer);
          this.refreshTimer = null;
        }
        debugLogger61.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 fs50.readFile(filePath, "utf8");
        } catch (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : "Unknown error";
          debugLogger61.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 = normalizeContent(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, body2] = match2;
          const frontmatter = parse8(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 name4 = 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');
            }
          }
          let hooks;
          if (frontmatterYaml.includes("hooks:")) {
            const fullFrontmatter = yaml.parse(frontmatterYaml);
            const hooksRaw = fullFrontmatter["hooks"];
            if (hooksRaw !== void 0) {
              hooks = this.parseHooksConfig(hooksRaw);
            }
          }
          const skillRoot = path49.dirname(filePath);
          const model = parseModelField(frontmatter);
          const argumentHint = typeof frontmatter["argument-hint"] === "string" ? frontmatter["argument-hint"] : void 0;
          const whenToUse = typeof frontmatter["when_to_use"] === "string" ? frontmatter["when_to_use"] : void 0;
          const disableModelInvocationRaw = frontmatter["disable-model-invocation"];
          const disableModelInvocation = disableModelInvocationRaw === true || disableModelInvocationRaw === "true" ? true : void 0;
          const config2 = {
            name: name4,
            description,
            allowedTools,
            hooks,
            skillRoot,
            argumentHint,
            model,
            level,
            filePath,
            body: body2.trim(),
            whenToUse,
            disableModelInvocation
          };
          const validation2 = this.validateConfig(config2);
          if (!validation2.isValid) {
            throw new Error(`Validation failed: ${validation2.errors.join(", ")}`);
          }
          debugLogger61.debug(`Successfully parsed skill: ${name4} (${level}) from ${filePath}`);
          return config2;
        } catch (error40) {
          const skillError = new SkillError(`Failed to parse skill file: ${error40 instanceof Error ? error40.message : "Unknown error"}`, SkillErrorCode.PARSE_ERROR);
          this.parseErrors.set(filePath, skillError);
          throw skillError;
        }
      }
      /**
       * Parses hooks configuration from frontmatter.
       *
       * @param hooksRaw - Raw hooks object from frontmatter
       * @returns Parsed SkillHooksSettings
       */
      parseHooksConfig(hooksRaw) {
        const hooks = {};
        const validEvents = Object.values(HookEventName);
        for (const [eventName, matchersRaw] of Object.entries(hooksRaw)) {
          if (!validEvents.includes(eventName)) {
            debugLogger61.warn(`Unknown hook event: ${eventName}, skipping`);
            continue;
          }
          if (!Array.isArray(matchersRaw)) {
            debugLogger61.warn(`Hooks for ${eventName} must be an array, skipping`);
            continue;
          }
          const matchers = [];
          for (const matcherRaw of matchersRaw) {
            if (typeof matcherRaw !== "object" || matcherRaw === null) {
              debugLogger61.warn(`Invalid matcher in ${eventName}, skipping`);
              continue;
            }
            const matcher = matcherRaw;
            const hookDef = this.parseHookMatcher(matcher);
            if (hookDef) {
              matchers.push(hookDef);
            }
          }
          if (matchers.length > 0) {
            hooks[eventName] = matchers;
          }
        }
        return hooks;
      }
      /**
       * Parses a single hook matcher configuration.
       *
       * @param matcher - Raw matcher object
       * @returns HookDefinition or null if invalid
       */
      parseHookMatcher(matcher) {
        const matcherPattern = matcher["matcher"];
        const hooksRaw = matcher["hooks"];
        if (!hooksRaw || !Array.isArray(hooksRaw)) {
          debugLogger61.warn("Matcher missing hooks array, skipping");
          return null;
        }
        const hooks = [];
        for (const hookRaw of hooksRaw) {
          if (typeof hookRaw !== "object" || hookRaw === null) {
            continue;
          }
          const hook = hookRaw;
          const hookType = hook["type"];
          if (hookType === "command") {
            const commandHook = {
              type: HookType.Command,
              command: hook["command"],
              timeout: hook["timeout"],
              statusMessage: hook["statusMessage"],
              shell: hook["shell"]
            };
            hooks.push(commandHook);
          } else if (hookType === "http") {
            const httpHook = {
              type: HookType.Http,
              url: hook["url"],
              headers: hook["headers"],
              allowedEnvVars: hook["allowedEnvVars"],
              timeout: hook["timeout"],
              statusMessage: hook["statusMessage"]
            };
            hooks.push(httpHook);
          } else {
            debugLogger61.warn(`Unknown hook type: ${hookType}, skipping`);
          }
        }
        if (hooks.length === 0) {
          return null;
        }
        return {
          matcher: matcherPattern,
          hooks
        };
      }
      /**
       * Gets the base directory for skills at a specific level.
       *
       * @param level - Storage level
       * @returns Absolute directory paths
       */
      getSkillsBaseDirs(level) {
        switch (level) {
          case "project":
            return SKILL_PROVIDER_CONFIG_DIRS.map((v2) => path49.join(this.config.getProjectRoot(), v2, SKILLS_CONFIG_DIR));
          case "user":
            return SKILL_PROVIDER_CONFIG_DIRS.map((v2) => path49.join(os23.homedir(), v2, SKILLS_CONFIG_DIR));
          case "bundled":
            return [this.bundledSkillsDir];
          case "extension":
            throw new Error("Extension skills do not have a base directory; they are loaded from active extensions.");
          default:
            throw new Error(`Unknown skill level: ${level}`);
        }
      }
      /**
       * Lists skills at a specific level.
       *
       * @param level - Storage level to scan
       * @returns Array of skill configurations
       */
      async listSkillsAtLevel(level) {
        if (this.config.getBareMode()) {
          debugLogger61.debug(`Skipping ${level} level skills in bare mode`);
          return [];
        }
        const projectRoot = this.config.getProjectRoot();
        const homeDir = os23.homedir();
        const isHomeDirectory = path49.resolve(projectRoot) === path49.resolve(homeDir);
        if (level === "project" && isHomeDirectory) {
          debugLogger61.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, extensionName: extension.name });
            });
          }
          debugLogger61.debug(`Loaded ${skills2.length} extension-level skills from ${extensions.length} extensions`);
          return skills2;
        }
        if (level === "bundled") {
          const bundledDir = this.bundledSkillsDir;
          if (!fsSync.existsSync(bundledDir)) {
            debugLogger61.warn(`Bundled skills directory not found: ${bundledDir}. This may indicate an incomplete installation.`);
            return [];
          }
          debugLogger61.debug(`Loading bundled skills from: ${bundledDir}`);
          const skills2 = await this.loadSkillsFromDir(bundledDir, "bundled");
          debugLogger61.debug(`Loaded ${skills2.length} bundled skills`);
          return skills2;
        }
        const baseDirs = this.getSkillsBaseDirs(level);
        const skills = [];
        const seenNames = /* @__PURE__ */ new Set();
        for (const baseDir of baseDirs) {
          debugLogger61.debug(`Loading ${level} level skills from: ${baseDir}`);
          const skillsFromDir = await this.loadSkillsFromDir(baseDir, level);
          for (const skill of skillsFromDir) {
            if (seenNames.has(skill.name)) {
              debugLogger61.debug(`Skipping duplicate skill at ${level} level: ${skill.name} from ${baseDir}`);
              continue;
            }
            seenNames.add(skill.name);
            skills.push(skill);
          }
        }
        debugLogger61.debug(`Loaded ${skills.length} ${level} level skills`);
        return skills;
      }
      async loadSkillsFromDir(baseDir, level) {
        debugLogger61.debug(`Loading skills from directory: ${baseDir}`);
        try {
          const entries = await fs50.readdir(baseDir, { withFileTypes: true });
          const skills = [];
          debugLogger61.debug(`Found ${entries.length} entries in ${baseDir}`);
          for (const entry of entries) {
            const isDirectory = entry.isDirectory();
            const isSymlink = entry.isSymbolicLink();
            if (!isDirectory && !isSymlink) {
              debugLogger61.warn(`Skipping non-directory entry: ${entry.name}`);
              continue;
            }
            const skillDir = path49.join(baseDir, entry.name);
            if (isSymlink) {
              try {
                const targetStat = await fs50.stat(skillDir);
                if (!targetStat.isDirectory()) {
                  debugLogger61.warn(`Skipping symlink ${entry.name} that does not point to a directory`);
                  continue;
                }
              } catch (error40) {
                debugLogger61.warn(`Skipping invalid symlink ${entry.name}: ${error40 instanceof Error ? error40.message : "Unknown error"}`);
                continue;
              }
            }
            const skillManifest = path49.join(skillDir, SKILL_MANIFEST_FILE2);
            try {
              await fs50.access(skillManifest);
              const config2 = await this.parseSkillFileInternal(skillManifest, level);
              skills.push(config2);
            } catch (error40) {
              if (error40 instanceof SkillError) {
                debugLogger61.error(`Failed to parse skill at ${skillDir}: ${error40.message}`);
              } else {
                debugLogger61.debug(`No valid SKILL.md found in ${skillDir}, skipping`);
              }
              continue;
            }
          }
          return skills;
        } catch (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : "Unknown error";
          debugLogger61.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(name4, level) {
        await this.ensureLevelCache(level);
        const levelSkills = this.skillsCache?.get(level) || [];
        return levelSkills.find((skill) => skill.name === name4) || 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);
        }
      }
      // Only watch project and user skill directories for changes.
      // Bundled skills are immutable (shipped with the package) and extension
      // skills are managed by the extension system, so neither needs watching.
      updateWatchersFromCache() {
        if (this.config.getBareMode()) {
          return;
        }
        const watchTargets = new Set(["project", "user"].map((level) => this.getSkillsBaseDirs(level)).reduce((acc, baseDirs) => acc.concat(baseDirs), []).filter((baseDir) => fsSync.existsSync(baseDir)));
        for (const existingPath of this.watchers.keys()) {
          if (!watchTargets.has(existingPath)) {
            void this.watchers.get(existingPath)?.close().catch((error40) => {
              debugLogger61.warn(`Failed to close skills watcher for ${existingPath}:`, error40);
            });
            this.watchers.delete(existingPath);
          }
        }
        for (const watchPath of watchTargets) {
          if (this.watchers.has(watchPath)) {
            continue;
          }
          try {
            const watcher = watch(watchPath, {
              ignoreInitial: true,
              ignored: watcherIgnored,
              depth: WATCHER_MAX_DEPTH
            }).on("all", () => {
              this.scheduleRefresh();
            }).on("error", (error40) => {
              debugLogger61.warn(`Skills watcher error for ${watchPath}:`, error40);
            });
            this.watchers.set(watchPath, watcher);
          } catch (error40) {
            debugLogger61.warn(`Failed to watch skills directory at ${watchPath}:`, error40);
          }
        }
      }
      scheduleRefresh() {
        if (this.refreshTimer) {
          clearTimeout(this.refreshTimer);
        }
        this.refreshTimer = setTimeout(() => {
          this.refreshTimer = null;
          void this.refreshCache().then(() => this.updateWatchersFromCache());
        }, 150);
      }
      async ensureUserSkillsDir() {
        const baseDir = path49.join(os23.homedir(), QWEN_CONFIG_DIR2, SKILLS_CONFIG_DIR);
        try {
          await fs50.mkdir(baseDir, { recursive: true });
        } catch (error40) {
          debugLogger61.warn(`Failed to create user skills directory at ${baseDir}:`, error40);
        }
      }
    };
  }
});

// packages/core/dist/src/permissions/shell-semantics.js
import nodePath2 from "node:path";
import os24 from "node:os";
function tokenize3(command2) {
  const tokens = [];
  let current = "";
  let inSingle = false;
  let inDouble = false;
  let escaped = false;
  for (let i4 = 0; i4 < command2.length; i4++) {
    const ch = command2[i4];
    if (escaped) {
      current += ch;
      escaped = false;
      continue;
    }
    if (ch === "\\" && !inSingle) {
      escaped = true;
      continue;
    }
    if (ch === "'" && !inDouble) {
      inSingle = !inSingle;
      continue;
    }
    if (ch === '"' && !inSingle) {
      inDouble = !inDouble;
      continue;
    }
    if (!inSingle && !inDouble && (ch === " " || ch === "	")) {
      if (current) {
        tokens.push(current);
        current = "";
      }
      continue;
    }
    current += ch;
  }
  if (current)
    tokens.push(current);
  return tokens;
}
function resolvePath2(p2, cwd6) {
  const normP = p2.replace(/\\/g, "/");
  const normCwd = cwd6.replace(/\\/g, "/");
  if (normP === "~" || normP.startsWith("~/")) {
    const homeDir = os24.homedir().replace(/\\/g, "/");
    const rest = normP.slice(1);
    return rest ? nodePath2.posix.join(homeDir, rest) : homeDir;
  }
  if (nodePath2.isAbsolute(normP) || normP.startsWith("/")) {
    return normP;
  }
  return nodePath2.posix.join(normCwd, normP);
}
function looksLikePath(s5) {
  if (!s5)
    return false;
  if (s5.startsWith("$"))
    return false;
  if (s5.startsWith("-"))
    return false;
  if (/^\d+$/.test(s5))
    return false;
  if (s5.includes("{") || s5.includes("}"))
    return false;
  if (s5.includes("://"))
    return false;
  return true;
}
function extractRedirects(tokens, cwd6) {
  const readFiles = [];
  const writeFiles = [];
  const toRemove = /* @__PURE__ */ new Set();
  for (let i4 = 0; i4 < tokens.length; i4++) {
    const tok = tokens[i4];
    if (tok === ">" || tok === "1>") {
      const target = tokens[i4 + 1];
      if (target && looksLikePath(target)) {
        writeFiles.push(resolvePath2(target, cwd6));
        toRemove.add(i4);
        toRemove.add(i4 + 1);
        i4++;
      }
    } else if (tok === ">>" || tok === "1>>") {
      const target = tokens[i4 + 1];
      if (target && looksLikePath(target)) {
        writeFiles.push(resolvePath2(target, cwd6));
        toRemove.add(i4);
        toRemove.add(i4 + 1);
        i4++;
      }
    } else if (tok === "<") {
      const target = tokens[i4 + 1];
      if (target && looksLikePath(target)) {
        readFiles.push(resolvePath2(target, cwd6));
        toRemove.add(i4);
        toRemove.add(i4 + 1);
        i4++;
      }
    } else if (tok === "2>" || tok === "2>>" || tok === "&>" || tok === "&>>") {
      const target = tokens[i4 + 1];
      if (target) {
        if (target !== "/dev/null" && looksLikePath(target)) {
          writeFiles.push(resolvePath2(target, cwd6));
        }
        toRemove.add(i4);
        toRemove.add(i4 + 1);
        i4++;
      }
    } else {
      const m3 = tok.match(/^(>>|>|2>>|2>|&>>|&>|<)(.+)$/);
      if (m3) {
        const op = m3[1];
        const target = m3[2];
        if (target !== "/dev/null" && looksLikePath(target)) {
          if (op === "<") {
            readFiles.push(resolvePath2(target, cwd6));
          } else {
            writeFiles.push(resolvePath2(target, cwd6));
          }
        }
        toRemove.add(i4);
      }
    }
  }
  const filtered = tokens.filter((_2, idx) => !toRemove.has(idx));
  tokens.length = 0;
  tokens.push(...filtered);
  return { readFiles, writeFiles };
}
function getPositionalArgs(args2, flagsWithValue = /* @__PURE__ */ new Set()) {
  const positional = [];
  let skipNext = false;
  for (const arg of args2) {
    if (skipNext) {
      skipNext = false;
      continue;
    }
    if (!arg.startsWith("-")) {
      positional.push(arg);
      continue;
    }
    if (flagsWithValue.has(arg)) {
      skipNext = true;
    }
  }
  return positional;
}
function readOps(args2, cwd6, flagsWithValue) {
  return getPositionalArgs(args2, flagsWithValue).filter(looksLikePath).map((p2) => ({
    virtualTool: "read_file",
    filePath: resolvePath2(p2, cwd6)
  }));
}
function listOps(args2, cwd6, flagsWithValue) {
  const dirs = getPositionalArgs(args2, flagsWithValue).filter(looksLikePath);
  if (dirs.length === 0)
    return [{ virtualTool: "list_directory", filePath: cwd6 }];
  return dirs.map((p2) => ({
    virtualTool: "list_directory",
    filePath: resolvePath2(p2, cwd6)
  }));
}
function webOp(url3) {
  try {
    const normalized2 = url3.includes("://") ? url3 : `https://${url3}`;
    const domain2 = new URL(normalized2).hostname;
    return domain2 ? { virtualTool: "web_fetch", domain: domain2 } : null;
  } catch {
    return null;
  }
}
function extractShellOperations(simpleCommand, cwd6) {
  if (!simpleCommand.trim())
    return [];
  const tokens = tokenize3(simpleCommand);
  if (tokens.length === 0)
    return [];
  const { readFiles: redirectReads, writeFiles: redirectWrites } = extractRedirects(tokens, cwd6);
  const cmdName = tokens[0];
  if (!cmdName) {
    return [
      ...redirectReads.map((p2) => ({
        virtualTool: "read_file",
        filePath: p2
      })),
      ...redirectWrites.map((p2) => ({
        virtualTool: "write_file",
        filePath: p2
      }))
    ];
  }
  if (cmdName.includes("="))
    return [];
  const ops = [];
  if (PREFIX_COMMANDS.has(cmdName)) {
    const flagsWithVal = PREFIX_COMMAND_FLAGS_WITH_VALUE.get(cmdName);
    let startIdx = 1;
    while (startIdx < tokens.length) {
      const t5 = tokens[startIdx];
      if (t5.startsWith("-")) {
        startIdx++;
        if (flagsWithVal?.has(t5) && startIdx < tokens.length && !tokens[startIdx].startsWith("-")) {
          startIdx++;
        }
      } else if (t5.includes("=")) {
        startIdx++;
      } else {
        break;
      }
    }
    if (cmdName === "timeout" && startIdx < tokens.length && /^\d/.test(tokens[startIdx])) {
      startIdx++;
    }
    if (startIdx < tokens.length) {
      const innerCommand = tokens.slice(startIdx).join(" ");
      ops.push(...extractShellOperations(innerCommand, cwd6));
    }
  } else {
    const handler = COMMANDS[cmdName];
    if (handler) {
      const args2 = tokens.slice(1);
      ops.push(...handler(args2, cwd6));
    }
  }
  ops.push(...redirectReads.map((p2) => ({
    virtualTool: "read_file",
    filePath: p2
  })), ...redirectWrites.map((p2) => ({
    virtualTool: "write_file",
    filePath: p2
  })));
  return ops;
}
var COMMANDS, PREFIX_COMMAND_FLAGS_WITH_VALUE, PREFIX_COMMANDS;
var init_shell_semantics = __esm({
  "packages/core/dist/src/permissions/shell-semantics.js"() {
    "use strict";
    init_esbuild_shims();
    __name(tokenize3, "tokenize");
    __name(resolvePath2, "resolvePath");
    __name(looksLikePath, "looksLikePath");
    __name(extractRedirects, "extractRedirects");
    __name(getPositionalArgs, "getPositionalArgs");
    __name(readOps, "readOps");
    __name(listOps, "listOps");
    __name(webOp, "webOp");
    COMMANDS = {
      // ── File-read commands ────────────────────────────────────────────────────
      cat: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "cat"),
      tac: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "tac"),
      nl: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "nl"),
      zcat: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "zcat"),
      bzcat: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "bzcat"),
      xzcat: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "xzcat"),
      gzcat: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "gzcat"),
      lzcat: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "lzcat"),
      head: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-n", "-c", "--lines", "--bytes"])), "head"),
      tail: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-n", "-c", "-s", "--lines", "--bytes", "--sleep-interval"])), "tail"),
      less: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-b", "-h", "-j", "-p", "-x", "-y", "-z", "--shift", "--tabs"])), "less"),
      more: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "more"),
      most: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "most"),
      wc: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "wc"),
      file: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-m",
        "-e",
        "-F",
        "-P",
        "--magic-file",
        "--exclude",
        "--extension",
        "--separator"
      ])), "file"),
      stat: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-c", "-f", "--format", "--printf", "--file-system"])), "stat"),
      readlink: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-e",
        "-f",
        "-m",
        "-q",
        "-s",
        "-v",
        "-z",
        "--canonicalize",
        "--canonicalize-existing",
        "--canonicalize-missing",
        "--no-newline",
        "--quiet",
        "--silent",
        "--verbose",
        "--zero"
      ])), "readlink"),
      realpath: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "--relative-to",
        "--relative-base",
        "-e",
        "-m",
        "-s",
        "-z",
        "--canonicalize-existing",
        "--canonicalize-missing",
        "--logical",
        "--physical",
        "--no-symlinks",
        "--quiet",
        "--strip",
        "--zero"
      ])), "realpath"),
      diff: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-u",
        "-U",
        "-c",
        "-C",
        "-I",
        "-x",
        "-X",
        "-W",
        "--label",
        "--to-file",
        "--from-file",
        "--width",
        "--horizon-lines",
        "--strip-trailing-cr",
        "--ignore-matching-lines",
        "--exclude",
        "--exclude-from"
      ])), "diff"),
      diff3: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-m",
        "-T",
        "-A",
        "-E",
        "-e",
        "-x",
        "-X",
        "-3",
        "-i",
        "--label"
      ])), "diff3"),
      sdiff: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-o", "-w", "-W", "-s", "-i", "-b", "-B", "-E", "-H"])), "sdiff"),
      cmp: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-i",
        "-l",
        "-n",
        "-s",
        "--ignore-initial",
        "--bytes",
        "--print-bytes",
        "--quiet",
        "--silent",
        "--verbose",
        "--zero"
      ])), "cmp"),
      md5sum: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "md5sum"),
      sha1sum: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "sha1sum"),
      sha256sum: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "sha256sum"),
      sha512sum: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "sha512sum"),
      sha224sum: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "sha224sum"),
      sha384sum: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "sha384sum"),
      cksum: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "cksum"),
      b2sum: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "b2sum"),
      sum: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "sum"),
      strings: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-n",
        "-t",
        "-e",
        "-o",
        "-a",
        "--min-len",
        "--radix",
        "--encoding",
        "--file",
        "--print-file-name",
        "--data",
        "--all"
      ])), "strings"),
      hexdump: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-n",
        "-s",
        "-l",
        "-C",
        "-b",
        "-c",
        "-d",
        "-o",
        "-x",
        "-e",
        "-f",
        "-v"
      ])), "hexdump"),
      xxd: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-l",
        "-s",
        "-c",
        "-g",
        "-o",
        "-n",
        "-b",
        "-e",
        "-i",
        "-p",
        "-r",
        "-u",
        "-E"
      ])), "xxd"),
      od: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-N",
        "-j",
        "-w",
        "-s",
        "-t",
        "-A",
        "-v",
        "--address-radix",
        "--endian",
        "--format",
        "--read-bytes",
        "--skip-bytes",
        "--strings",
        "--output-duplicates",
        "--width"
      ])), "od"),
      sort: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-k",
        "-t",
        "-T",
        "--output",
        "-o",
        "--field-separator",
        "--key",
        "--temporary-directory",
        "--compress-program",
        "--batch-size",
        "--parallel",
        "--random-source",
        "--sort"
      ])), "sort"),
      uniq: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-f",
        "-s",
        "-w",
        "-n",
        "--skip-fields",
        "--skip-chars",
        "--check-chars"
      ])), "uniq"),
      cut: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-b",
        "-c",
        "-d",
        "-f",
        "--delimiter",
        "--fields",
        "--bytes",
        "--characters",
        "--output-delimiter"
      ])), "cut"),
      paste: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-d", "-s", "--delimiters", "--serial"])), "paste"),
      join: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-t",
        "-1",
        "-2",
        "-j",
        "-o",
        "-a",
        "-e",
        "--field",
        "--header",
        "--check-order",
        "--nocheck-order",
        "--zero-terminated"
      ])), "join"),
      column: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set([
        "-t",
        "-s",
        "-n",
        "-c",
        "-o",
        "-x",
        "--table",
        "--separator",
        "--output-separator",
        "--fillrows"
      ])), "column"),
      fold: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-w", "-b", "-s", "--width", "--bytes", "--spaces"])), "fold"),
      expand: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-t", "--tabs", "--initial"])), "expand"),
      unexpand: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-t", "-a", "--tabs", "--all", "--first-only"])), "unexpand"),
      base64: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-d", "-i", "-w", "--decode", "--ignore-garbage", "--wrap"])), "base64"),
      base32: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2, /* @__PURE__ */ new Set(["-d", "-i", "-w", "--decode", "--ignore-garbage", "--wrap"])), "base32"),
      tr: /* @__PURE__ */ __name((a2, d2) => readOps(a2, d2), "tr"),
      // ── Grep / search commands ────────────────────────────────────────────────
      grep: /* @__PURE__ */ __name((args2, cwd6) => {
        const hasPatternFlag = args2.some((a2) => a2 === "-e" || a2 === "-f" || a2.startsWith("-e") || a2.startsWith("-f"));
        const isRecursive = args2.some((a2) => ["-r", "-R", "--recursive", "--dereference-recursive"].includes(a2));
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-e",
          "-f",
          "-m",
          "-A",
          "-B",
          "-C",
          "--context",
          "--include",
          "--exclude",
          "--exclude-dir",
          "--max-count",
          "--after-context",
          "--before-context",
          "-n",
          "--line-number",
          "--label",
          "-D",
          "--devices",
          "--max-depth",
          "-X",
          "--exclude-from"
        ]);
        const positional = getPositionalArgs(args2, flagsWithValue).filter(looksLikePath);
        const filePaths = hasPatternFlag ? positional : positional.slice(1);
        const tool = isRecursive ? "list_directory" : "read_file";
        return filePaths.map((p2) => ({
          virtualTool: tool,
          filePath: resolvePath2(p2, cwd6)
        }));
      }, "grep"),
      egrep: /* @__PURE__ */ __name((a2, d2) => COMMANDS["grep"](a2, d2), "egrep"),
      fgrep: /* @__PURE__ */ __name((a2, d2) => COMMANDS["grep"](a2, d2), "fgrep"),
      zgrep: /* @__PURE__ */ __name((a2, d2) => COMMANDS["grep"](a2, d2), "zgrep"),
      bzgrep: /* @__PURE__ */ __name((a2, d2) => COMMANDS["grep"](a2, d2), "bzgrep"),
      rg: /* @__PURE__ */ __name((args2, cwd6) => {
        const hasPatternFlag = args2.some((a2) => a2 === "-e" || a2 === "-f");
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-e",
          "-f",
          "-m",
          "-A",
          "-B",
          "-C",
          "-t",
          "-T",
          "-g",
          "--iglob",
          "--glob",
          "--type",
          "--type-not",
          "--max-count",
          "--max-depth",
          "--context",
          "--after-context",
          "--before-context",
          "-M",
          "--max-columns",
          "--field-match-separator"
        ]);
        const positional = getPositionalArgs(args2, flagsWithValue).filter(looksLikePath);
        const filePaths = hasPatternFlag ? positional : positional.slice(1);
        return filePaths.map((p2) => ({
          virtualTool: "list_directory",
          filePath: resolvePath2(p2, cwd6)
        }));
      }, "rg"),
      ag: /* @__PURE__ */ __name((args2, cwd6) => {
        const hasPatternFlag = args2.some((a2) => a2 === "-e");
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-e",
          "-m",
          "-A",
          "-B",
          "-C",
          "--depth",
          "--file-search-regex",
          "--file-search-regex-i",
          "--ignore",
          "--ignore-dir",
          "-n"
        ]);
        const positional = getPositionalArgs(args2, flagsWithValue).filter(looksLikePath);
        const filePaths = hasPatternFlag ? positional : positional.slice(1);
        return filePaths.map((p2) => ({
          virtualTool: "list_directory",
          filePath: resolvePath2(p2, cwd6)
        }));
      }, "ag"),
      ack: /* @__PURE__ */ __name((args2, cwd6) => {
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-m",
          "-A",
          "-B",
          "-C",
          "--type",
          "--ignore-dir",
          "--ignore-file",
          "--ignore-directory",
          "-n"
        ]);
        const positional = getPositionalArgs(args2, flagsWithValue).filter(looksLikePath);
        return positional.slice(1).map((p2) => ({
          virtualTool: "list_directory",
          filePath: resolvePath2(p2, cwd6)
        }));
      }, "ack"),
      // ── Directory-listing commands ────────────────────────────────────────────
      ls: /* @__PURE__ */ __name((a2, d2) => listOps(a2, d2), "ls"),
      dir: /* @__PURE__ */ __name((a2, d2) => listOps(a2, d2), "dir"),
      vdir: /* @__PURE__ */ __name((a2, d2) => listOps(a2, d2), "vdir"),
      exa: /* @__PURE__ */ __name((a2, d2) => listOps(a2, d2, /* @__PURE__ */ new Set([
        "-L",
        "--level",
        "--sort",
        "--color",
        "--colour",
        "--group",
        "-I",
        "--ignore-glob"
      ])), "exa"),
      eza: /* @__PURE__ */ __name((a2, d2) => listOps(a2, d2, /* @__PURE__ */ new Set([
        "-L",
        "--level",
        "--sort",
        "--color",
        "--colour",
        "--group",
        "-I",
        "--ignore-glob"
      ])), "eza"),
      lsd: /* @__PURE__ */ __name((a2, d2) => listOps(a2, d2, /* @__PURE__ */ new Set([
        "--depth",
        "--color",
        "--icon",
        "--icon-theme",
        "--date",
        "--size",
        "--blocks",
        "--header",
        "--classic",
        "--no-symlink",
        "--ignore-glob",
        "-I"
      ])), "lsd"),
      find: /* @__PURE__ */ __name((args2, cwd6) => {
        const expressionKeywords = /* @__PURE__ */ new Set([
          "-name",
          "-iname",
          "-path",
          "-ipath",
          "-regex",
          "-iregex",
          "-type",
          "-maxdepth",
          "-mindepth",
          "-newer",
          "-mtime",
          "-atime",
          "-ctime",
          "-size",
          "-user",
          "-group",
          "-perm",
          "-links",
          "-inum",
          "-exec",
          "-execdir",
          "-ok",
          "-okdir",
          "-print",
          "-print0",
          "-ls",
          "-delete",
          "-prune",
          "-depth",
          "-empty",
          "-readable",
          "-writable",
          "-executable",
          "-follow",
          "-xdev",
          "-mount",
          "-true",
          "-false",
          "-not",
          "!",
          "-a",
          "-and",
          "-o",
          "-or"
        ]);
        const startingPoints = [];
        for (const arg of args2) {
          if (arg.startsWith("-") || arg === "(" || arg === ")" || expressionKeywords.has(arg))
            break;
          if (looksLikePath(arg))
            startingPoints.push(resolvePath2(arg, cwd6));
        }
        if (startingPoints.length === 0) {
          return [{ virtualTool: "list_directory", filePath: cwd6 }];
        }
        return startingPoints.map((p2) => ({
          virtualTool: "list_directory",
          filePath: p2
        }));
      }, "find"),
      tree: /* @__PURE__ */ __name((args2, cwd6) => listOps(args2, cwd6, /* @__PURE__ */ new Set([
        "-L",
        "-P",
        "-I",
        "-o",
        "-n",
        "-H",
        "-T",
        "--charset",
        "--filelimit",
        "--matchdirs",
        "--dirsfirst",
        "-J",
        "-X",
        "--du",
        "--si"
      ])), "tree"),
      du: /* @__PURE__ */ __name((args2, cwd6) => listOps(args2, cwd6, /* @__PURE__ */ new Set([
        "-d",
        "--max-depth",
        "--threshold",
        "-t",
        "--block-size",
        "-B",
        "--time-style",
        "--exclude",
        "-X",
        "--time",
        "--output"
      ])), "du"),
      // ── File-write commands (create or overwrite) ─────────────────────────────
      touch: /* @__PURE__ */ __name((args2, cwd6) => getPositionalArgs(args2, /* @__PURE__ */ new Set(["-t", "-r", "--reference", "--date", "-d", "--time"])).filter(looksLikePath).map((p2) => ({
        virtualTool: "write_file",
        filePath: resolvePath2(p2, cwd6)
      })), "touch"),
      mkdir: /* @__PURE__ */ __name((args2, cwd6) => getPositionalArgs(args2, /* @__PURE__ */ new Set(["-m", "--mode", "-Z", "--context"])).filter(looksLikePath).map((p2) => ({
        virtualTool: "write_file",
        filePath: resolvePath2(p2, cwd6)
      })), "mkdir"),
      mkfifo: /* @__PURE__ */ __name((args2, cwd6) => getPositionalArgs(args2, /* @__PURE__ */ new Set(["-m", "--mode", "-Z"])).filter(looksLikePath).map((p2) => ({
        virtualTool: "write_file",
        filePath: resolvePath2(p2, cwd6)
      })), "mkfifo"),
      tee: /* @__PURE__ */ __name((args2, cwd6) => getPositionalArgs(args2).filter(looksLikePath).map((p2) => ({
        virtualTool: "write_file",
        filePath: resolvePath2(p2, cwd6)
      })), "tee"),
      cp: /* @__PURE__ */ __name((args2, cwd6) => {
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-S",
          "--suffix",
          "-t",
          "--target-directory",
          "--backup",
          "--no-target-directory",
          "--sparse",
          "--reflink",
          "-Z",
          "--context",
          "--copy-contents"
        ]);
        const positional = getPositionalArgs(args2, flagsWithValue).filter(looksLikePath);
        if (positional.length === 0)
          return [];
        if (positional.length === 1) {
          return [
            {
              virtualTool: "read_file",
              filePath: resolvePath2(positional[0], cwd6)
            }
          ];
        }
        const srcs = positional.slice(0, -1);
        const dst = positional[positional.length - 1];
        return [
          ...srcs.map((p2) => ({
            virtualTool: "read_file",
            filePath: resolvePath2(p2, cwd6)
          })),
          { virtualTool: "write_file", filePath: resolvePath2(dst, cwd6) }
        ];
      }, "cp"),
      mv: /* @__PURE__ */ __name((args2, cwd6) => {
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-S",
          "--suffix",
          "-t",
          "--target-directory",
          "--backup",
          "-Z",
          "--context"
        ]);
        const positional = getPositionalArgs(args2, flagsWithValue).filter(looksLikePath);
        if (positional.length < 2)
          return [];
        const srcs = positional.slice(0, -1);
        const dst = positional[positional.length - 1];
        return [
          // The source files are edited (moved away — their original location changes)
          ...srcs.map((p2) => ({
            virtualTool: "edit",
            filePath: resolvePath2(p2, cwd6)
          })),
          { virtualTool: "write_file", filePath: resolvePath2(dst, cwd6) }
        ];
      }, "mv"),
      install: /* @__PURE__ */ __name((args2, cwd6) => {
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-m",
          "--mode",
          "-o",
          "--owner",
          "-g",
          "--group",
          "-S",
          "--suffix",
          "-t",
          "--target-directory",
          "-T",
          "--no-target-directory",
          "-Z",
          "--context",
          "-C",
          "--compare"
        ]);
        const positional = getPositionalArgs(args2, flagsWithValue).filter(looksLikePath);
        if (positional.length < 2)
          return [];
        const dst = positional[positional.length - 1];
        return [{ virtualTool: "write_file", filePath: resolvePath2(dst, cwd6) }];
      }, "install"),
      dd: /* @__PURE__ */ __name((args2, cwd6) => {
        const ops = [];
        for (const arg of args2) {
          if (arg.startsWith("if=")) {
            const p2 = arg.slice(3);
            if (looksLikePath(p2)) {
              ops.push({ virtualTool: "read_file", filePath: resolvePath2(p2, cwd6) });
            }
          } else if (arg.startsWith("of=")) {
            const p2 = arg.slice(3);
            if (looksLikePath(p2)) {
              ops.push({
                virtualTool: "write_file",
                filePath: resolvePath2(p2, cwd6)
              });
            }
          }
        }
        return ops;
      }, "dd"),
      ln: /* @__PURE__ */ __name((args2, cwd6) => {
        const positional = getPositionalArgs(args2, /* @__PURE__ */ new Set(["-S", "--suffix", "-t", "--target-directory", "-b", "--backup"])).filter(looksLikePath);
        if (positional.length < 2)
          return [];
        const linkname = positional[positional.length - 1];
        return [
          { virtualTool: "write_file", filePath: resolvePath2(linkname, cwd6) }
        ];
      }, "ln"),
      // ── File-edit commands (modify or delete existing content) ────────────────
      rm: /* @__PURE__ */ __name((args2, cwd6) => getPositionalArgs(args2, /* @__PURE__ */ new Set(["--interactive"])).filter(looksLikePath).map((p2) => ({
        virtualTool: "edit",
        filePath: resolvePath2(p2, cwd6)
      })), "rm"),
      rmdir: /* @__PURE__ */ __name((args2, cwd6) => getPositionalArgs(args2, /* @__PURE__ */ new Set(["--ignore-fail-on-non-empty", "-p", "--parents"])).filter(looksLikePath).map((p2) => ({
        virtualTool: "edit",
        filePath: resolvePath2(p2, cwd6)
      })), "rmdir"),
      unlink: /* @__PURE__ */ __name((args2, cwd6) => getPositionalArgs(args2).filter(looksLikePath).map((p2) => ({
        virtualTool: "edit",
        filePath: resolvePath2(p2, cwd6)
      })), "unlink"),
      shred: /* @__PURE__ */ __name((args2, cwd6) => getPositionalArgs(args2, /* @__PURE__ */ new Set(["-n", "--iterations", "-s", "--size", "--random-source"])).filter(looksLikePath).map((p2) => ({
        virtualTool: "edit",
        filePath: resolvePath2(p2, cwd6)
      })), "shred"),
      truncate: /* @__PURE__ */ __name((args2, cwd6) => getPositionalArgs(args2, /* @__PURE__ */ new Set([
        "-s",
        "--size",
        "-r",
        "--reference",
        "-o",
        "-I",
        "-c",
        "--io-blocks",
        "--no-create"
      ])).filter(looksLikePath).map((p2) => ({
        virtualTool: "edit",
        filePath: resolvePath2(p2, cwd6)
      })), "truncate"),
      chmod: /* @__PURE__ */ __name((args2, cwd6) => {
        const positional = getPositionalArgs(args2, /* @__PURE__ */ new Set(["-f", "--reference", "--from"]));
        return positional.slice(1).filter(looksLikePath).map((p2) => ({
          virtualTool: "edit",
          filePath: resolvePath2(p2, cwd6)
        }));
      }, "chmod"),
      chown: /* @__PURE__ */ __name((args2, cwd6) => {
        const positional = getPositionalArgs(args2, /* @__PURE__ */ new Set(["--from", "--reference"]));
        return positional.slice(1).filter(looksLikePath).map((p2) => ({
          virtualTool: "edit",
          filePath: resolvePath2(p2, cwd6)
        }));
      }, "chown"),
      chgrp: /* @__PURE__ */ __name((args2, cwd6) => {
        const positional = getPositionalArgs(args2, /* @__PURE__ */ new Set(["--reference"]));
        return positional.slice(1).filter(looksLikePath).map((p2) => ({
          virtualTool: "edit",
          filePath: resolvePath2(p2, cwd6)
        }));
      }, "chgrp"),
      rename: /* @__PURE__ */ __name((args2, cwd6) => {
        const positional = getPositionalArgs(args2).filter(looksLikePath);
        return positional.slice(2).map((p2) => ({
          virtualTool: "edit",
          filePath: resolvePath2(p2, cwd6)
        }));
      }, "rename"),
      sed: /* @__PURE__ */ __name((args2, cwd6) => {
        const hasInPlace = args2.some((a2) => a2 === "-i" || a2.startsWith("-i"));
        const hasExplicitScript = args2.some((a2) => a2 === "-e" || a2 === "-f" || a2.startsWith("-e"));
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-e",
          "-f",
          "--expression",
          "--file",
          // NOTE: -i is intentionally absent — it is an optional-suffix flag
          // (e.g. `-i`, `-i.bak`) and does NOT consume the next token as a value.
          "-l",
          "--line-length",
          "--sandbox",
          "-s",
          "--separate"
        ]);
        const positional = getPositionalArgs(args2, flagsWithValue).filter(looksLikePath);
        const filePaths = hasExplicitScript ? positional : positional.slice(1);
        const tool = hasInPlace ? "edit" : "read_file";
        return filePaths.map((p2) => ({
          virtualTool: tool,
          filePath: resolvePath2(p2, cwd6)
        }));
      }, "sed"),
      awk: /* @__PURE__ */ __name((args2, cwd6) => {
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-F",
          "-f",
          "-v",
          "-m",
          "-W",
          "-M",
          "--source",
          "--include",
          "--load",
          "-b",
          "--characters-as-bytes",
          "-c",
          "--traditional",
          "-d",
          "-D",
          "--debug",
          "-e",
          "--exec",
          "-h",
          "--help",
          "-i",
          "--lint",
          "-o",
          "-p",
          "-r",
          "-s",
          "-S",
          "-t",
          "-V"
        ]);
        return getPositionalArgs(args2, flagsWithValue).filter(looksLikePath).map((p2) => ({
          virtualTool: "read_file",
          filePath: resolvePath2(p2, cwd6)
        }));
      }, "awk"),
      // ── WebFetch commands ─────────────────────────────────────────────────────
      curl: /* @__PURE__ */ __name((args2) => {
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-o",
          "-O",
          "--output",
          "-u",
          "--user",
          "-A",
          "--user-agent",
          "-H",
          "--header",
          "-d",
          "--data",
          "--data-binary",
          "--data-raw",
          "--data-urlencode",
          "-X",
          "--request",
          "-F",
          "--form",
          "-e",
          "--referer",
          "-T",
          "--upload-file",
          "--cacert",
          "--capath",
          "--cert",
          "--key",
          "--pass",
          "-m",
          "--max-time",
          "--connect-timeout",
          "-r",
          "--range",
          "--limit-rate",
          "-b",
          "--cookie",
          "-c",
          "--cookie-jar",
          "--proxy",
          "-U",
          "--proxy-user",
          "-K",
          "--config",
          "--netrc-file",
          "--resolve",
          "--connect-to",
          "-w",
          "--write-out",
          "-x",
          "-Y",
          "--speed-limit",
          "--speed-time",
          "-y",
          "--max-filesize",
          "--proto",
          "--proto-redir",
          "-E",
          "--cert-type",
          "--key-type"
        ]);
        return getPositionalArgs(args2, flagsWithValue).filter((p2) => p2.includes("://") || /^https?:\/\//.test(p2) || /^ftp:\/\//.test(p2)).flatMap((url3) => {
          const op = webOp(url3);
          return op ? [op] : [];
        });
      }, "curl"),
      wget: /* @__PURE__ */ __name((args2) => {
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-O",
          "--output-document",
          "-P",
          "--directory-prefix",
          "-o",
          "--output-file",
          "-a",
          "--append-output",
          "-U",
          "--user-agent",
          "--header",
          "-e",
          "--execute",
          "--tries",
          "-t",
          "-T",
          "--timeout",
          "--wait",
          "-w",
          "--quota",
          "-Q",
          "--bind-address",
          "--limit-rate",
          "--user",
          "--password",
          "--proxy-user",
          "--proxy-password",
          "-i",
          "--input-file",
          "--base",
          "--config",
          "--referer",
          "-D",
          "--domains",
          "--exclude-domains",
          "-I",
          "--include-directories",
          "-X",
          "--exclude-directories",
          "--regex-type",
          "-A",
          "-R",
          "--accept",
          "--reject",
          "--no-check-certificate",
          "--ca-certificate",
          "--ca-directory",
          "--certificate",
          "--private-key"
        ]);
        return getPositionalArgs(args2, flagsWithValue).filter((p2) => p2.includes("://") || /^https?:\/\//.test(p2)).flatMap((url3) => {
          const op = webOp(url3);
          return op ? [op] : [];
        });
      }, "wget"),
      fetch: /* @__PURE__ */ __name((args2) => {
        const flagsWithValue = /* @__PURE__ */ new Set([
          "-o",
          "-q",
          "-v",
          "-a",
          "-T",
          "-S",
          "--no-verify-peer",
          "--no-verify-hostname",
          "--ca-cert"
        ]);
        return getPositionalArgs(args2, flagsWithValue).filter((p2) => p2.includes("://")).flatMap((url3) => {
          const op = webOp(url3);
          return op ? [op] : [];
        });
      }, "fetch")
    };
    PREFIX_COMMAND_FLAGS_WITH_VALUE = /* @__PURE__ */ new Map([
      [
        "sudo",
        /* @__PURE__ */ new Set([
          "-u",
          "--user",
          "-g",
          "--group",
          "-C",
          "--close-from",
          "-c",
          "--login-class",
          "-D",
          "--chdir",
          "-p",
          "--prompt",
          "-r",
          "--role",
          "-t",
          "--type",
          "-T",
          "--command-timeout",
          "-U",
          "--other-user"
        ])
      ],
      ["timeout", /* @__PURE__ */ new Set(["-s", "--signal", "-k", "--kill-after"])]
    ]);
    PREFIX_COMMANDS = /* @__PURE__ */ new Set([
      "sudo",
      "doas",
      // OpenBSD sudo alternative
      "env",
      "time",
      "nice",
      "ionice",
      "nohup",
      "timeout",
      "unbuffer",
      "stdbuf"
    ]);
    __name(extractShellOperations, "extractShellOperations");
  }
});

// packages/core/dist/src/permissions/permission-manager.js
var debugLogger62, DECISION_PRIORITY, PermissionManager;
var init_permission_manager = __esm({
  "packages/core/dist/src/permissions/permission-manager.js"() {
    "use strict";
    init_esbuild_shims();
    init_rule_parser();
    init_shell_semantics();
    init_shellAstParser();
    init_shell_utils();
    init_debugLogger();
    debugLogger62 = createDebugLogger("PERMISSIONS");
    DECISION_PRIORITY = {
      deny: 3,
      ask: 2,
      default: 1,
      allow: 0
    };
    PermissionManager = class _PermissionManager {
      static {
        __name(this, "PermissionManager");
      }
      config;
      /** Persistent rules loaded from settings (all scopes merged). */
      persistentRules = {
        allow: [],
        ask: [],
        deny: []
      };
      /** In-memory rules added for the current session only. */
      sessionRules = {
        allow: [],
        ask: [],
        deny: []
      };
      /**
       * Canonical tool names from the legacy `coreTools` allowlist.
       * When non-null, `isToolEnabled()` rejects any tool not in this set.
       * Populated during `initialize()` from `config.getCoreTools()`.
       */
      coreToolsAllowList = null;
      constructor(config2) {
        this.config = config2;
      }
      /**
       * Initialise from the config's permission parameters.
       * Must be called once before any rule lookups.
       *
       * The config getters already return fully-merged lists (settings + SDK params),
       * so we simply parse them into typed rules.
       */
      initialize() {
        this.persistentRules = {
          allow: parseRules(this.config.getPermissionsAllow() ?? []),
          ask: parseRules(this.config.getPermissionsAsk() ?? []),
          deny: parseRules(this.config.getPermissionsDeny() ?? [])
        };
        const rawCoreTools = this.config.getCoreTools?.();
        if (rawCoreTools && rawCoreTools.length > 0) {
          this.coreToolsAllowList = new Set(rawCoreTools.map((t5) => parseRule(t5).toolName));
        }
      }
      // ---------------------------------------------------------------------------
      // Core evaluation
      // ---------------------------------------------------------------------------
      /**
       * Evaluate the permission decision for a given tool invocation context.
       *
       * @param ctx - The context containing the tool name and optional command.
       * @returns A PermissionDecision indicating how to handle this tool call.
       */
      async evaluate(ctx) {
        const { command: command2, toolName } = ctx;
        if (command2 !== void 0) {
          const subCommands = splitCompoundCommand(command2);
          if (subCommands.length > 1) {
            return this.evaluateCompoundCommand(ctx, subCommands);
          }
        }
        const decision = this.evaluateSingle(ctx);
        if (decision === "default" && toolName === "run_shell_command" && command2 !== void 0) {
          return this.resolveDefaultPermission(command2);
        }
        return decision;
      }
      /**
       * Evaluate a single (non-compound) context against all rules.
       *
       * For shell commands (run_shell_command), the result is the most restrictive
       * of:
       *   1. The base decision from Bash / command-pattern rules.
       *   2. The decision derived from virtual file / network operations extracted
       *      via `extractShellOperations` — allows Read/Edit/Write/WebFetch rules
       *      to match equivalent shell commands (e.g. `cat` → Read, `curl` → WebFetch).
       */
      evaluateSingle(ctx) {
        const { toolName, command: command2, filePath, domain: domain2, specifier } = ctx;
        const pathCtx = this.config.getProjectRoot && this.config.getCwd ? {
          projectRoot: this.config.getProjectRoot(),
          cwd: this.config.getCwd()
        } : void 0;
        const matchArgs = [
          toolName,
          command2,
          filePath,
          domain2,
          pathCtx,
          specifier
        ];
        const baseDecision = (() => {
          for (const rule of [
            ...this.sessionRules.deny,
            ...this.persistentRules.deny
          ]) {
            if (matchesRule(rule, ...matchArgs))
              return "deny";
          }
          for (const rule of [
            ...this.sessionRules.ask,
            ...this.persistentRules.ask
          ]) {
            if (matchesRule(rule, ...matchArgs))
              return "ask";
          }
          for (const rule of [
            ...this.sessionRules.allow,
            ...this.persistentRules.allow
          ]) {
            if (matchesRule(rule, ...matchArgs))
              return "allow";
          }
          return "default";
        })();
        if (baseDecision === "deny")
          return "deny";
        if (toolName === "run_shell_command" && command2 !== void 0) {
          const cwd6 = pathCtx?.cwd ?? process.cwd();
          const virtualDecision = this.evaluateShellVirtualOps(extractShellOperations(command2, cwd6), pathCtx);
          if (virtualDecision !== "default" && DECISION_PRIORITY[virtualDecision] > DECISION_PRIORITY[baseDecision]) {
            return virtualDecision;
          }
        }
        return baseDecision;
      }
      /**
       * Evaluate a list of virtual operations (derived from shell command analysis)
       * against all current rules.  Returns the most restrictive matching decision,
       * or `'default'` if no rule matches any operation.
       *
       * Each operation is evaluated as if it were a direct invocation of its
       * `virtualTool` (e.g. `read_file`, `web_fetch`, `edit`), so Read/Edit/etc.
       * rules are applied naturally.
       */
      evaluateShellVirtualOps(ops, _pathCtx) {
        if (ops.length === 0)
          return "default";
        let worst = "default";
        for (const op of ops) {
          const opDecision = this.evaluateSingle({
            toolName: op.virtualTool,
            filePath: op.filePath,
            domain: op.domain
          });
          if (DECISION_PRIORITY[opDecision] > DECISION_PRIORITY[worst]) {
            worst = opDecision;
            if (worst === "deny")
              return "deny";
          }
        }
        return worst;
      }
      /**
       * Evaluate a compound command by splitting it into sub-commands,
       * evaluating each independently, and returning the most restrictive result.
       *
       * Restriction order: deny > ask > allow
       *
       * When a sub-command returns 'default' (no rule matches), it is resolved to
       * the actual default permission using AST analysis:
       *   - Command substitution detected → 'deny'
       *   - Read-only command (cd, ls, git status, etc.) → 'allow'
       *   - Otherwise → 'ask'
       *
       * Example: with rules `allow: [git checkout *]`
       *   - "cd /path && git checkout -b feature" → allow (cd) + allow (rule) → allow
       *   - "rm /path && git checkout -b feature" → ask (rm) + allow (rule) → ask
       *   - "evil-cmd && git checkout" (deny: [evil-cmd]) → deny + allow → deny
       */
      async evaluateCompoundCommand(ctx, subCommands) {
        const PRIORITY = {
          deny: 3,
          ask: 2,
          allow: 0
        };
        let mostRestrictive = "allow";
        for (const subCmd of subCommands) {
          const subCtx = {
            ...ctx,
            command: subCmd
          };
          const rawDecision = this.evaluateSingle(subCtx);
          const decision = rawDecision === "default" ? await this.resolveDefaultPermission(subCmd) : rawDecision;
          if (PRIORITY[decision] > PRIORITY[mostRestrictive]) {
            mostRestrictive = decision;
          }
          if (mostRestrictive === "deny") {
            return "deny";
          }
        }
        return mostRestrictive;
      }
      /**
       * Resolve 'default' permission to actual permission using AST analysis.
       * This mirrors the logic in ShellToolInvocation.getDefaultPermission().
       *
       * @param command - The shell command to analyze.
       * @returns 'deny' for command substitution, 'allow' for read-only, 'ask' otherwise.
       */
      async resolveDefaultPermission(command2) {
        if (detectCommandSubstitution(command2)) {
          return "deny";
        }
        try {
          const isReadOnly = await isShellCommandReadOnlyAST(command2);
          if (isReadOnly) {
            return "allow";
          }
        } catch {
        }
        return "ask";
      }
      // ---------------------------------------------------------------------------
      // Registry-level helper
      // ---------------------------------------------------------------------------
      /**
       * Core tools that are subject to the coreTools allowlist check.
       * Tools not in this set (MCP, Skill, Agent, etc.) bypass the check.
       */
      static CORE_TOOLS = /* @__PURE__ */ new Set([
        "read_file",
        "write_file",
        "edit",
        "glob",
        "grep_search",
        "run_shell_command",
        "list_directory",
        "web_fetch",
        "todo_write",
        "save_memory",
        "lsp",
        "cron_create",
        "cron_list",
        "cron_delete"
      ]);
      /**
       * Check if a tool is a core tool subject to the coreTools allowlist check.
       */
      isCoreTool(toolName) {
        return _PermissionManager.CORE_TOOLS.has(toolName);
      }
      /**
       * Determine whether a tool should be present in the tool registry.
       *
       * A tool is disabled (returns false) when a `deny` rule without a specifier
       * (i.e. a whole-tool deny) matches.  Specifier-based deny rules such as
       * `"Bash(rm -rf *)"` do NOT remove the tool from the registry – they only
       * deny specific invocations at runtime.
       *
       * Non-core tools (MCP, Skill, Agent, etc.) skip the coreTools allowlist
       * check because they are dynamically discovered or essential for system
       * operation.
       */
      async isToolEnabled(toolName) {
        const canonicalName = resolveToolName(toolName);
        if (!this.isCoreTool(canonicalName)) {
          const decision2 = await this.evaluate({ toolName: canonicalName });
          return decision2 !== "deny";
        }
        if (this.coreToolsAllowList !== null && this.coreToolsAllowList.size > 0) {
          if (!this.coreToolsAllowList.has(canonicalName)) {
            return false;
          }
        }
        const decision = await this.evaluate({ toolName: canonicalName });
        return decision !== "deny";
      }
      /**
       * Find the first deny rule that matches the given context.
       * Returns the raw rule string if found, or undefined if no deny rule matches.
       *
       * Useful for providing user-visible feedback about which rule caused a denial.
       */
      findMatchingDenyRule(ctx) {
        const { toolName, command: command2, filePath, domain: domain2, specifier } = ctx;
        const pathCtx = this.config.getProjectRoot && this.config.getCwd ? {
          projectRoot: this.config.getProjectRoot(),
          cwd: this.config.getCwd()
        } : void 0;
        const matchArgs = [
          toolName,
          command2,
          filePath,
          domain2,
          pathCtx,
          specifier
        ];
        for (const rule of [
          ...this.sessionRules.deny,
          ...this.persistentRules.deny
        ]) {
          if (matchesRule(rule, ...matchArgs)) {
            return rule.raw;
          }
        }
        return void 0;
      }
      // ---------------------------------------------------------------------------
      // Shell command helper
      // ---------------------------------------------------------------------------
      /**
       * Determine the permission decision for a specific shell command string.
       *
       * @param command - The shell command to evaluate.
       * @returns The PermissionDecision for this command.
       */
      async isCommandAllowed(command2) {
        return this.evaluate({
          toolName: "run_shell_command",
          command: command2
        });
      }
      // ---------------------------------------------------------------------------
      // Relevance check
      // ---------------------------------------------------------------------------
      /**
       * Check whether any rule (allow, ask, or deny) in the current rule set
       * matches the given invocation context.
       *
       * This allows the scheduler to skip the full `evaluate()` call when no
       * rules are relevant, preserving the tool's `getDefaultPermission()` result
       * as-is.
       *
       * "Relevant" means at least one rule's toolName matches AND, if the rule
       * has a specifier, it also matches the context's command/filePath/domain.
       *
       * Examples for Shell executing `git clone xxx`:
       *   - "Bash"               → matches (tool-level rule, no specifier)
       *   - "Bash(git *)"        → matches (git sub-command wildcard)
       *   - "Bash(git clone *)"  → matches (exact sub-command wildcard)
       *   - "Bash(git add *)"    → no match (different sub-command)
       *   - "Edit"               → no match (different tool)
       *
       * @param ctx - Permission check context.
       * @returns true if at least one rule matches.
       */
      hasRelevantRules(ctx) {
        const { toolName, command: command2, filePath, domain: domain2, specifier } = ctx;
        if (ctx.toolName === "run_shell_command" && command2 !== void 0) {
          const subCommands = splitCompoundCommand(command2);
          if (subCommands.length > 1) {
            return subCommands.some((subCmd) => this.hasRelevantRules({ ...ctx, command: subCmd }));
          }
        }
        const pathCtx = this.config.getProjectRoot && this.config.getCwd ? {
          projectRoot: this.config.getProjectRoot(),
          cwd: this.config.getCwd()
        } : void 0;
        const matchArgs = [
          toolName,
          command2,
          filePath,
          domain2,
          pathCtx,
          specifier
        ];
        const allRules = [
          ...this.sessionRules.allow,
          ...this.persistentRules.allow,
          ...this.sessionRules.ask,
          ...this.persistentRules.ask,
          ...this.sessionRules.deny,
          ...this.persistentRules.deny
        ];
        if (allRules.some((rule) => matchesRule(rule, ...matchArgs)))
          return true;
        if (ctx.toolName === "run_shell_command" && ctx.command !== void 0) {
          const cwd6 = pathCtx?.cwd ?? process.cwd();
          const ops = extractShellOperations(ctx.command, cwd6);
          if (ops.some((op) => {
            const opMatchArgs = [
              op.virtualTool,
              void 0,
              op.filePath,
              op.domain,
              pathCtx,
              void 0
            ];
            return allRules.some((rule) => matchesRule(rule, ...opMatchArgs));
          })) {
            return true;
          }
        }
        return false;
      }
      /**
       * Returns true when the invocation is matched by an explicit `ask` rule.
       *
       * This is intentionally narrower than `evaluate(ctx) === 'ask'`. Shell
       * commands can resolve to `ask` simply because they are non-read-only and no
       * explicit allow/deny rule matched. That fallback should still allow users to
       * create new allow rules, so callers must only hide "Always allow" when a
       * real ask rule matched.
       */
      hasMatchingAskRule(ctx) {
        const { toolName, command: command2, filePath, domain: domain2, specifier } = ctx;
        if (ctx.toolName === "run_shell_command" && command2 !== void 0) {
          const subCommands = splitCompoundCommand(command2);
          if (subCommands.length > 1) {
            return subCommands.some((subCmd) => this.hasMatchingAskRule({ ...ctx, command: subCmd }));
          }
        }
        const pathCtx = this.config.getProjectRoot && this.config.getCwd ? {
          projectRoot: this.config.getProjectRoot(),
          cwd: this.config.getCwd()
        } : void 0;
        const matchArgs = [
          toolName,
          command2,
          filePath,
          domain2,
          pathCtx,
          specifier
        ];
        const askRules = [...this.sessionRules.ask, ...this.persistentRules.ask];
        if (askRules.some((rule) => matchesRule(rule, ...matchArgs))) {
          return true;
        }
        if (ctx.toolName === "run_shell_command" && ctx.command !== void 0) {
          const cwd6 = pathCtx?.cwd ?? process.cwd();
          const ops = extractShellOperations(ctx.command, cwd6);
          return ops.some((op) => {
            const opMatchArgs = [
              op.virtualTool,
              void 0,
              op.filePath,
              op.domain,
              pathCtx,
              void 0
            ];
            return askRules.some((rule) => matchesRule(rule, ...opMatchArgs));
          });
        }
        return false;
      }
      // ---------------------------------------------------------------------------
      // Session rule management
      // ---------------------------------------------------------------------------
      /**
       * Add a session-level allow rule (in-memory, cleared when the session ends).
       * Used when the user clicks "Always allow for this session".
       *
       * @param raw - The raw rule string, e.g. "Bash(git status)".
       */
      addSessionAllowRule(raw2) {
        if (raw2 && raw2.trim()) {
          const rule = parseRule(raw2);
          if (rule.invalid) {
            debugLogger62.warn(`Ignoring malformed allow rule (unbalanced parentheses): ${rule.raw}`);
            return;
          }
          this.sessionRules.allow.push(rule);
        }
      }
      /**
       * Add a session-level deny rule (in-memory, cleared when the session ends).
       */
      addSessionDenyRule(raw2) {
        if (raw2 && raw2.trim()) {
          const rule = parseRule(raw2);
          if (rule.invalid) {
            debugLogger62.warn(`Ignoring malformed deny rule (unbalanced parentheses): ${rule.raw}`);
            return;
          }
          this.sessionRules.deny.push(rule);
        }
      }
      /**
       * Add a session-level ask rule (in-memory, cleared when the session ends).
       */
      addSessionAskRule(raw2) {
        if (raw2 && raw2.trim()) {
          const rule = parseRule(raw2);
          if (rule.invalid) {
            debugLogger62.warn(`Ignoring malformed ask rule (unbalanced parentheses): ${rule.raw}`);
            return;
          }
          this.sessionRules.ask.push(rule);
        }
      }
      // ---------------------------------------------------------------------------
      // Persistent rule management
      // ---------------------------------------------------------------------------
      /**
       * Add a single persistent rule to the specified type.
       * This modifies the in-memory rule set; the caller is responsible for
       * persisting the change to disk (e.g. by writing to settings.json).
       *
       * @param raw - The raw rule string, e.g. "Bash(git *)"
       * @param type - 'allow' | 'ask' | 'deny'
       * @returns The parsed rule that was added.
       */
      addPersistentRule(raw2, type) {
        const rule = parseRule(raw2);
        if (rule.invalid) {
          debugLogger62.warn(`Ignoring malformed ${type} rule (unbalanced parentheses): ${rule.raw}`);
          return rule;
        }
        const exists3 = this.persistentRules[type].some((r5) => r5.raw === rule.raw);
        if (!exists3) {
          this.persistentRules[type].push(rule);
        }
        return rule;
      }
      /**
       * Remove a persistent rule matching the given raw string from the
       * specified type.  Removes the first match only.
       *
       * @returns true if a rule was removed, false if no matching rule was found.
       */
      removePersistentRule(raw2, type) {
        const rules = this.persistentRules[type];
        const idx = rules.findIndex((r5) => r5.raw === raw2);
        if (idx !== -1) {
          rules.splice(idx, 1);
          return true;
        }
        return false;
      }
      // ---------------------------------------------------------------------------
      // Default mode
      // ---------------------------------------------------------------------------
      /**
       * Return the current default approval mode from config.
       * This is used by the UI layer when `evaluate()` returns 'default' to
       * determine the actual behavior (ask vs allow).
       */
      getDefaultMode() {
        return this.config.getApprovalMode?.() ?? "default";
      }
      /**
       * Update the persistent deny rules (called after migrating settings).
       * Replaces the persistent deny rule set entirely.
       */
      updatePersistentRules(ruleSet) {
        if (ruleSet.allow !== void 0) {
          this.persistentRules.allow = ruleSet.allow;
        }
        if (ruleSet.ask !== void 0) {
          this.persistentRules.ask = ruleSet.ask;
        }
        if (ruleSet.deny !== void 0) {
          this.persistentRules.deny = ruleSet.deny;
        }
      }
      // ---------------------------------------------------------------------------
      // Listing rules (for /permissions UI)
      // ---------------------------------------------------------------------------
      /**
       * Return all active rules with their types and scopes, suitable for
       * display in the /permissions dialog.
       */
      listRules() {
        const result = [];
        const addRules = /* @__PURE__ */ __name((rules, type, scope) => {
          for (const rule of rules) {
            if (!rule.invalid) {
              result.push({ rule, type, scope });
            }
          }
        }, "addRules");
        addRules(this.sessionRules.deny, "deny", "session");
        addRules(this.persistentRules.deny, "deny", "user");
        addRules(this.sessionRules.ask, "ask", "session");
        addRules(this.persistentRules.ask, "ask", "user");
        addRules(this.sessionRules.allow, "allow", "session");
        addRules(this.persistentRules.allow, "allow", "user");
        return result;
      }
      /**
       * Return a summary of active allow rules (raw strings), including
       * both session and persistent rules.  Used for telemetry.
       */
      getAllowRawStrings() {
        return [
          ...this.sessionRules.allow.map((r5) => r5.raw),
          ...this.persistentRules.allow.map((r5) => r5.raw)
        ];
      }
    };
  }
});

// packages/core/dist/src/subagents/types.js
var SubagentError, SubagentErrorCode;
var init_types15 = __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"
    };
  }
});

// packages/core/dist/src/subagents/model-selection.js
function parseSubagentModelSelection(model) {
  const trimmed2 = model?.trim();
  if (!trimmed2 || trimmed2 === "inherit") {
    return { inherits: true };
  }
  const colonIndex = trimmed2.indexOf(":");
  if (colonIndex === -1) {
    return { modelId: trimmed2, inherits: false };
  }
  const maybeAuthType = trimmed2.slice(0, colonIndex).trim();
  const modelId = trimmed2.slice(colonIndex + 1).trim();
  if (!AUTH_TYPES.has(maybeAuthType)) {
    return { modelId: trimmed2, inherits: false };
  }
  if (!modelId) {
    throw new Error("Model selector must include a model ID after the authType");
  }
  return {
    authType: maybeAuthType,
    modelId,
    inherits: false
  };
}
var AUTH_TYPES;
var init_model_selection = __esm({
  "packages/core/dist/src/subagents/model-selection.js"() {
    "use strict";
    init_esbuild_shims();
    init_contentGenerator();
    AUTH_TYPES = new Set(Object.values(AuthType2));
    __name(parseSubagentModelSelection, "parseSubagentModelSelection");
  }
});

// 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_types15();
    init_model_selection();
    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 > 1e3) {
          warnings.push("Description is quite long (>1,000 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.disallowedTools && config2.disallowedTools.length > 0) {
          const disallowedValidation = this.validateTools(config2.disallowedTools);
          if (!disallowedValidation.isValid) {
            errors.push(...disallowedValidation.errors);
          }
          warnings.push(...disallowedValidation.warnings);
        }
        if (config2.model) {
          const modelValidation = this.validateModel(config2.model);
          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(name4) {
        const errors = [];
        const warnings = [];
        if (!name4 || name4.trim().length === 0) {
          errors.push("Name is required and cannot be empty");
          return { isValid: false, errors, warnings };
        }
        const trimmedName = name4.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 = /^[\p{L}\p{N}_-]+$/u;
        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",
          "main"
        ];
        if (reservedNames.includes(trimmedName.toLowerCase())) {
          errors.push(`"${trimmedName}" is a reserved name and cannot be used`);
        }
        if (trimmedName !== trimmedName.toLowerCase() && /[a-zA-Z]/.test(trimmedName)) {
          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) {
          warnings.push("System prompt is quite long (>10,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 a subagent model selector.
       *
       * @param model - Model selector to validate
       * @returns ValidationResult
       */
      validateModel(model) {
        const errors = [];
        const warnings = [];
        if (typeof model !== "string" || model.trim().length === 0) {
          errors.push("Model must be a non-empty string");
          return {
            isValid: false,
            errors,
            warnings
          };
        }
        try {
          parseSubagentModelSelection(model);
        } catch (error40) {
          errors.push(error40 instanceof Error ? error40.message : "Invalid model");
        }
        if (model.trim() === "inherit") {
          warnings.push('Explicit "inherit" is optional because omitting the model uses the main conversation model');
        }
        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();
    init_tool_names();
    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 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, respond with a concise report covering what was done and any key findings \u2014 the caller will relay this to the user, so it only needs the essentials.

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: search broadly when you don't know where something lives. Use ${ToolNames.READ_FILE} 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, share file paths (always absolute, never relative) that are relevant to the task. Include code snippets only when the exact text is load-bearing \u2014 do not recap code you merely read.
- For clear communication, avoid using emojis.

Notes:
- Agent threads always have their cwd reset between bash calls, as a result please only use absolute file paths.
- In your final response, share file paths (always absolute, never relative) that are relevant to the task. Include code snippets only when the exact text is load-bearing (e.g., a bug you found, a function signature the caller asked for) \u2014 do not recap code you merely read.
- For clear communication with the user the assistant MUST avoid using emojis.`
        },
        {
          name: "Explore",
          description: 'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',
          systemPrompt: `You are a file search specialist agent. You excel at thoroughly navigating and exploring codebases.

=== CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
This is a READ-ONLY exploration task. You are STRICTLY PROHIBITED from:
- Creating new files (no ${ToolDisplayNames.WRITE_FILE}, touch, or file creation of any kind)
- Modifying existing files (no ${ToolDisplayNames.EDIT} operations)
- Deleting files (no rm or deletion)
- Moving or copying files (no mv or cp)
- Creating temporary files anywhere, including /tmp
- Using redirect operators (>, >>, |) or heredocs to write to files
- Running ANY commands that change system state

Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools - attempting to edit files will fail.

Your strengths:
- Rapidly finding files using glob patterns
- Searching code and text with powerful regex patterns
- Reading and analyzing file contents

Guidelines:
- Use ${ToolDisplayNames.GLOB} for broad file pattern matching
- Use ${ToolDisplayNames.GREP} for searching file contents with regex
- Use ${ToolDisplayNames.READ_FILE} when you know the specific file path you need to read
- Use ${ToolDisplayNames.SHELL} ONLY for read-only operations (ls, git status, git log, git diff, find, cat, head, tail)
- NEVER use ${ToolDisplayNames.SHELL} for: mkdir, touch, rm, cp, mv, git add, git commit, npm install, pip install, or any file creation/modification
- Adapt your search approach based on the thoroughness level specified by the caller
- Return file paths as absolute paths in your final response
- For clear communication, avoid using emojis
- Communicate your final report directly as a regular message - do NOT attempt to create files

NOTE: You are meant to be a fast agent that returns output as quickly as possible. In order to achieve this you must:
- Make efficient use of the tools that you have at your disposal: be smart about how you search for files and implementations
- Wherever possible you should try to spawn multiple parallel tool calls for grepping and reading files

Complete the user's search request efficiently and report your findings clearly.

Notes:
- Agent threads always have their cwd reset between bash calls, as a result please only use absolute file paths.
- In your final response, share file paths (always absolute, never relative) that are relevant to the task. Include code snippets only when the exact text is load-bearing (e.g., a bug you found, a function signature the caller asked for) \u2014 do not recap code you merely read.
- For clear communication with the user the assistant MUST avoid using emojis.`,
          tools: [
            ToolNames.READ_FILE,
            ToolNames.GREP,
            ToolNames.GLOB,
            ToolNames.SHELL,
            ToolNames.LS,
            ToolNames.WEB_FETCH,
            ToolNames.TODO_WRITE,
            ToolNames.MEMORY,
            ToolNames.SKILL,
            ToolNames.LSP,
            ToolNames.ASK_USER_QUESTION
          ]
        },
        {
          name: "statusline-setup",
          description: "Use this agent to configure the user's Qwen Code status line setting.",
          tools: [
            ToolNames.READ_FILE,
            ToolNames.WRITE_FILE,
            ToolNames.EDIT,
            ToolNames.ASK_USER_QUESTION
          ],
          color: "orange",
          systemPrompt: `You are a status line setup agent for Qwen Code. Your job is to create or update the statusLine command in the user's Qwen Code settings.

CRITICAL \u2014 JSON SAFETY RULES:
The statusLine command is stored as a JSON string value in settings.json.
Shell commands with complex quoting (especially single-quote escaping like '\\'' or nested quotes)
WILL corrupt settings.json and prevent Qwen Code from starting.

You MUST follow these rules:
1. For ANY command that uses jq, pipes, single-quote escaping, or nested quotes:
   ALWAYS save it as a script file (~/.qwen/statusline-command.sh) and set
   the command to "bash ~/.qwen/statusline-command.sh".
2. Only use inline commands for VERY simple cases (e.g., "echo hello").
3. NEVER use shell single-quote escape sequences like '\\'' in the command value.
4. After writing settings.json, ALWAYS read it back and verify it is valid JSON.
   If it is not valid, fix it immediately.

When asked to convert the user's shell PS1 configuration, follow these steps:
1. Read the user's shell configuration files in this order of preference:
   - ~/.zshrc
   - ~/.bashrc
   - ~/.bash_profile
   - ~/.profile

2. Look for PS1 assignments. PS1 may be quoted or unquoted, e.g.:
   - PS1="\\u@\\h:\\w\\$ "
   - PS1='\\u@\\h:\\w\\$ '
   - PS1=\\u@\\h:\\w\\$
   - export PS1="..."
   If there are multiple PS1 assignments, use the last one (it takes effect).

3. Convert PS1 escape sequences to shell commands:
   - \\u \u2192 $(whoami)
   - \\h \u2192 $(hostname -s)
   - \\H \u2192 $(hostname)
   - \\w \u2192 $(pwd)
   - \\W \u2192 $(basename "$(pwd)")
   - \\$ \u2192 $
   - \\n \u2192 (remove or replace with a space \u2014 the status line only displays one line)
   - \\t \u2192 $(date +%H:%M:%S)
   - \\d \u2192 $(date "+%a %b %d")
   - \\@ \u2192 $(date +%I:%M%p)
   - \\# \u2192 #
   - \\! \u2192 !
   - \\[ and \\] \u2192 (remove \u2014 these are readline non-printing markers, not needed in the status line)
   - \\e or \\033 \u2192 (ANSI escape \u2014 strip the entire color sequence including \\e[...m)

4. Strip ANSI color/escape sequences from the PS1 output. The status line already renders in dimmed color, so PS1 colors are not useful and can produce garbled output.

5. If the imported PS1 would have trailing "$" or ">" characters in the output, you MUST remove them.

6. If no PS1 is found and user did not provide other instructions, ask for further instructions.

How to use the statusLine command:
1. The statusLine command will receive the following JSON input via stdin:
   {
     "session_id": "string",
     "version": "string",
     "model": {
       "display_name": "string"
     },
     "context_window": {
       "context_window_size": number,
       "used_percentage": number,
       "remaining_percentage": number,
       "current_usage": number,
       "total_input_tokens": number,
       "total_output_tokens": number
     },
     "workspace": {
       "current_dir": "string"
     },
     "git": {                     // Optional, only present when inside a git repo
       "branch": "string"
     },
     "metrics": {
       "models": {
         "<model_id>": {
           "api": { "total_requests": number, "total_errors": number, "total_latency_ms": number },
           "tokens": { "prompt": number, "completion": number, "total": number, "cached": number, "thoughts": number }
         }
       },
       "files": {
         "total_lines_added": number, "total_lines_removed": number
       }
     },
     "vim": {                     // Optional, only present when vim mode is enabled
       "mode": "INSERT" | "NORMAL"
     }
   }

   IMPORTANT: stdin can only be consumed once. Always read it into a variable first.

   IMPORTANT: The examples below are meant for use INSIDE a script file
   (e.g. ~/.qwen/statusline-command.sh), NOT as inline command values in settings.json.
   Putting these directly in the "command" field will corrupt settings.json.

   Example script content (save to ~/.qwen/statusline-command.sh):
   #!/bin/bash
   input=$(cat)
   echo "$(echo "$input" | jq -r '.model.display_name') in $(echo "$input" | jq -r '.workspace.current_dir')"

   Example displaying context usage (save to ~/.qwen/statusline-command.sh):
   #!/bin/bash
   input=$(cat)
   pct=$(echo "$input" | jq -r '.context_window.used_percentage')
   echo "Context: $pct% used"

   Example displaying git branch (save to ~/.qwen/statusline-command.sh):
   #!/bin/bash
   input=$(cat)
   branch=$(echo "$input" | jq -r '.git.branch // empty')
   echo "\${branch:-no branch}"

2. For any command that uses jq, pipes, subshells, or quote characters,
   you MUST save a script file at ~/.qwen/statusline-command.sh and use
   "bash ~/.qwen/statusline-command.sh" as the command value in settings (no chmod needed).
   This is REQUIRED to avoid JSON escaping issues that corrupt settings.json.

3. Update the user's ~/.qwen/settings.json. The statusLine setting is nested under the "ui" key:
   {
     "ui": {
       "statusLine": {
         "type": "command",
         "command": "your_command_here"
       }
     }
   }
   Make sure to preserve any existing "ui" settings (theme, etc.) when updating.

4. Optionally add a "refreshInterval" field (number of seconds, minimum 1) to re-run
   the command on a timer. Use this when the statusLine shows data that can change
   WITHOUT an Agent event \u2014 examples:
     - A clock / uptime / elapsed timer \u2192 refreshInterval: 1
     - Rate-limit or quota counters that tick down \u2192 refreshInterval: 5\u201310
     - CI / build status polled from a local cache file \u2192 refreshInterval: 10\u201330
   Do NOT set refreshInterval for commands that only show Agent-driven data
   (model name, token usage, git branch) \u2014 those already refresh on state changes.

Guidelines:
- The status line supports multi-line output (up to 2 lines) \u2014 each line of stdout is rendered as a separate row in the footer
- Preserve existing settings when updating
- Return a summary of what was configured, including the name of the script file if used
- If the script includes git commands, prefix them with GIT_OPTIONAL_LOCKS=0 to avoid index.lock contention (e.g. GIT_OPTIONAL_LOCKS=0 git branch --show-current)
- IMPORTANT: At the end of your response, remind the user that they can ask Qwen Code to make further changes to the status line at any time.
`
        }
      ];
      /**
       * 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(name4) {
        const lowerName = name4.toLowerCase();
        const agent = this.BUILTIN_AGENTS.find((a2) => a2.name.toLowerCase() === lowerName);
        if (!agent) {
          return null;
        }
        return {
          ...agent,
          level: "builtin",
          filePath: `<builtin:${agent.name}>`,
          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(name4) {
        const lowerName = name4.toLowerCase();
        return this.BUILTIN_AGENTS.some((agent) => agent.name.toLowerCase() === lowerName);
      }
      /**
       * 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 fs51 from "fs/promises";
import * as path50 from "path";
import * as os25 from "os";
async function loadSubagentFromDir(baseDir) {
  try {
    const files = await fs51.readdir(baseDir);
    const subagents = [];
    for (const file2 of files) {
      if (!file2.endsWith(".md"))
        continue;
      const filePath = path50.join(baseDir, file2);
      try {
        const content = await fs51.readFile(filePath, "utf8");
        const config2 = parseSubagentContent(content, filePath, "extension", new SubagentValidator());
        subagents.push(config2);
      } catch (error40) {
        warnInvalidSubagentFile(filePath, error40);
        continue;
      }
    }
    return subagents;
  } catch (_error) {
    return [];
  }
}
function parseSubagentContent(content, filePath, level, validator) {
  try {
    const normalizedContent = normalizeContent(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, systemPrompt] = match2;
    const frontmatter = parse8(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 name4 = String(nameRaw);
    const description = String(descriptionRaw);
    const tools = frontmatter["tools"];
    const disallowedToolsRaw = frontmatter["disallowedTools"];
    const disallowedTools = Array.isArray(disallowedToolsRaw) ? disallowedToolsRaw.filter((item) => typeof item === "string") : typeof disallowedToolsRaw === "string" ? [disallowedToolsRaw] : void 0;
    const modelRaw = frontmatter["model"];
    const legacyModelConfig = frontmatter["modelConfig"];
    const runConfig = frontmatter["runConfig"];
    const color = frontmatter["color"];
    const approvalModeRaw = frontmatter["approvalMode"];
    if (approvalModeRaw !== void 0 && approvalModeRaw !== null && typeof approvalModeRaw !== "string") {
      throw new Error(`Invalid "approvalMode" value: expected a string, got ${typeof approvalModeRaw}. Valid values: ${APPROVAL_MODES.join(", ")}`);
    }
    const approvalMode = typeof approvalModeRaw === "string" && approvalModeRaw !== "" ? approvalModeRaw : void 0;
    if (approvalMode !== void 0 && !APPROVAL_MODES.includes(approvalMode)) {
      throw new Error(`Invalid "approvalMode" value "${approvalMode}". Valid values: ${APPROVAL_MODES.join(", ")}`);
    }
    const model = modelRaw != null && modelRaw !== "" ? String(modelRaw) : typeof legacyModelConfig?.["model"] === "string" ? legacyModelConfig["model"] : void 0;
    const backgroundRaw = frontmatter["background"];
    if (backgroundRaw !== void 0 && backgroundRaw !== "true" && backgroundRaw !== "false" && backgroundRaw !== true && backgroundRaw !== false) {
      debugLogger63.warn(`Agent file ${filePath} has invalid background value '${backgroundRaw}'. Must be 'true', 'false', or omitted.`);
    }
    const background = backgroundRaw === "true" || backgroundRaw === true ? true : void 0;
    const config2 = {
      name: name4,
      description,
      tools,
      disallowedTools,
      approvalMode,
      systemPrompt: systemPrompt.trim(),
      filePath,
      model,
      runConfig,
      color,
      level,
      ...background ? { background } : {}
    };
    const validation2 = validator.validateConfig(config2);
    if (!validation2.isValid) {
      throw new Error(`Validation failed: ${validation2.errors.join(", ")}`);
    }
    return config2;
  } catch (error40) {
    throw new SubagentError(`Failed to parse subagent file: ${error40 instanceof Error ? error40.message : "Unknown error"}`, SubagentErrorCode.INVALID_CONFIG);
  }
}
function warnInvalidSubagentFile(filePath, error40) {
  const message = error40 instanceof Error ? error40.message : String(error40);
  debugLogger63.debug(`Skipped invalid file ${filePath}: ${message}`);
}
var debugLogger63, 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_types15();
    init_validation();
    init_agent_headless();
    init_config3();
    init_contentGenerator();
    init_content_generator_config();
    init_debugLogger();
    init_textUtils();
    init_model_selection();
    init_builtin_agents();
    init_tool_names();
    debugLogger63 = 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 (error40) {
            debugLogger63.warn("Subagent change listener threw an error:", error40);
          }
        }
      }
      /**
       * 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 fs51.access(filePath);
            throw new SubagentError(`Subagent "${config2.name}" already exists at ${filePath}`, SubagentErrorCode.ALREADY_EXISTS, config2.name);
          } catch (error40) {
            if (error40 instanceof SubagentError)
              throw error40;
          }
        }
        const dir = path50.dirname(filePath);
        await fs51.mkdir(dir, { recursive: true });
        const finalConfig = {
          ...config2,
          level: options2.level,
          filePath
        };
        const content = this.serializeSubagent(finalConfig);
        try {
          await fs51.writeFile(filePath, content, "utf8");
          await this.refreshCache();
        } catch (error40) {
          throw new SubagentError(`Failed to write subagent file: ${error40 instanceof Error ? error40.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(name4, level) {
        const lowerName = name4.toLowerCase();
        if (level) {
          if (level === "builtin") {
            return BuiltinAgentRegistry.getBuiltinAgent(name4);
          }
          if (level === "session") {
            const sessionSubagents2 = this.subagentsCache?.get("session") || [];
            return sessionSubagents2.find((agent) => agent.name.toLowerCase() === lowerName) || null;
          }
          return this.findSubagentByNameAtLevel(name4, level);
        }
        const sessionSubagents = this.subagentsCache?.get("session") || [];
        const sessionConfig = sessionSubagents.find((agent) => agent.name.toLowerCase() === lowerName);
        if (sessionConfig) {
          return sessionConfig;
        }
        const projectConfig = await this.findSubagentByNameAtLevel(name4, "project");
        if (projectConfig) {
          return projectConfig;
        }
        const userConfig = await this.findSubagentByNameAtLevel(name4, "user");
        if (userConfig) {
          return userConfig;
        }
        const extensionConfig = await this.findSubagentByNameAtLevel(name4, "extension");
        if (extensionConfig) {
          return extensionConfig;
        }
        return BuiltinAgentRegistry.getBuiltinAgent(name4);
      }
      /**
       * 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(name4, updates, level) {
        const existing = await this.loadSubagent(name4, level);
        if (!existing) {
          throw new SubagentError(`Subagent "${name4}" not found`, SubagentErrorCode.NOT_FOUND, name4);
        }
        if (existing.isBuiltin) {
          throw new SubagentError(`Cannot update built-in subagent "${name4}"`, SubagentErrorCode.INVALID_CONFIG, name4);
        }
        if (existing.level === "session") {
          throw new SubagentError(`Cannot update session-level subagent "${name4}"`, SubagentErrorCode.INVALID_CONFIG, name4);
        }
        const updatedConfig = this.mergeConfigurations(existing, updates);
        this.validator.validateOrThrow(updatedConfig);
        if (!existing.filePath) {
          throw new SubagentError(`Cannot update subagent "${name4}": no file path available`, SubagentErrorCode.FILE_ERROR, name4);
        }
        const content = this.serializeSubagent(updatedConfig);
        try {
          await fs51.writeFile(existing.filePath, content, "utf8");
          await this.refreshCache();
        } catch (error40) {
          throw new SubagentError(`Failed to update subagent file: ${error40 instanceof Error ? error40.message : "Unknown error"}`, SubagentErrorCode.FILE_ERROR, name4);
        }
      }
      /**
       * 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(name4, level, extensionName) {
        if (BuiltinAgentRegistry.isBuiltinAgent(name4)) {
          throw new SubagentError(`Cannot delete built-in subagent "${name4}"`, SubagentErrorCode.INVALID_CONFIG, name4);
        }
        if (level === "extension") {
          throw new SubagentError(`Cannot delete subagent "${name4}" in extension "${extensionName}", If needed, you can directly uninstall extension.`, SubagentErrorCode.INVALID_CONFIG, name4);
        }
        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(name4, currentLevel);
          if (config2 && config2.filePath) {
            try {
              await fs51.unlink(config2.filePath);
              deleted = true;
            } catch (_error) {
            }
          }
        }
        if (!deleted) {
          throw new SubagentError(`Subagent "${name4}" not found`, SubagentErrorCode.NOT_FOUND, name4);
        }
        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);
        }
        const sessionSubagents = this.subagentsCache?.get("session");
        if (sessionSubagents) {
          subagentsCache.set("session", sessionSubagents);
        }
        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(name4, level) {
        const config2 = await this.loadSubagent(name4, 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 fs51.readFile(filePath, "utf8");
        } catch (error40) {
          throw new SubagentError(`Failed to read subagent file: ${error40 instanceof Error ? error40.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.disallowedTools && config2.disallowedTools.length > 0) {
          frontmatter["disallowedTools"] = config2.disallowedTools;
        }
        if (config2.model && config2.model !== "inherit") {
          frontmatter["model"] = config2.model;
        }
        if (config2.runConfig) {
          frontmatter["runConfig"] = config2.runConfig;
        }
        if (config2.color && config2.color !== "auto") {
          frontmatter["color"] = config2.color;
        }
        if (config2.approvalMode && APPROVAL_MODES.includes(config2.approvalMode)) {
          frontmatter["approvalMode"] = config2.approvalMode;
        }
        if (config2.background) {
          frontmatter["background"] = true;
        }
        const yamlContent = stringify2(frontmatter, {
          lineWidth: 0,
          // Disable line wrapping
          minContentWidth: 0
        }).trim();
        return `---
${yamlContent}
---

${config2.systemPrompt}
`;
      }
      /**
       * Creates an AgentHeadless from a subagent configuration.
       *
       * @param config - Subagent configuration
       * @param runtimeContext - Runtime context
       * @returns Promise resolving to AgentHeadless
       */
      async createAgentHeadless(config2, runtimeContext, options2) {
        try {
          const runtimeConfig = await this.convertToRuntimeConfig(config2);
          const agentContext = await this.maybeOverrideContentGenerator(config2, runtimeContext);
          return await AgentHeadless.create(config2.name, agentContext, runtimeConfig.promptConfig, runtimeConfig.modelConfig, runtimeConfig.runConfig, runtimeConfig.toolConfig, options2?.eventEmitter, options2?.hooks);
        } catch (error40) {
          if (error40 instanceof Error) {
            throw new SubagentError(`Failed to create AgentHeadless: ${error40.message}`, SubagentErrorCode.INVALID_CONFIG, config2.name);
          }
          throw error40;
        }
      }
      /**
       * When a subagent's model selector specifies a model (bare ID or
       * authType-prefixed), build a Config override with a dedicated
       * ContentGenerator so the model actually reaches the API.
       * Returns the original context unchanged for inherit selectors.
       */
      async maybeOverrideContentGenerator(config2, base) {
        const selection = parseSubagentModelSelection(config2.model);
        if (selection.inherits) {
          return base;
        }
        const authType = selection.authType ?? base.getContentGeneratorConfig().authType;
        const authOverrides = {
          authType
        };
        const agentGeneratorConfig = buildAgentContentGeneratorConfig(base, selection.modelId, authOverrides);
        const agentGenerator = await createContentGenerator(agentGeneratorConfig, base);
        const override = Object.create(base);
        override.getContentGenerator = () => agentGenerator;
        override.getContentGeneratorConfig = () => agentGeneratorConfig;
        override.getAuthType = () => agentGeneratorConfig.authType;
        override.getModel = () => agentGeneratorConfig.model;
        debugLogger63.info(`Created per-agent ContentGenerator for subagent "${config2.name}": authType=${authType}, model=${agentGeneratorConfig.model}`);
        return override;
      }
      /**
       * Converts a file-based SubagentConfig to runtime configuration
       * compatible with AgentHeadless.create().
       *
       * @param config - File-based subagent configuration
       * @returns Runtime configuration for AgentHeadless
       */
      async convertToRuntimeConfig(config2) {
        const promptConfig = {
          systemPrompt: config2.systemPrompt
        };
        const selection = parseSubagentModelSelection(config2.model);
        const modelConfig = {
          ...selection.modelId ? { model: selection.modelId } : {}
        };
        const runConfig = {
          ...config2.runConfig
        };
        let toolConfig;
        if (config2.tools && config2.tools.length > 0 || config2.disallowedTools && config2.disallowedTools.length > 0) {
          const toolNames = config2.tools ? await this.transformToToolNames(config2.tools) : ["*"];
          toolConfig = {
            tools: toolNames,
            ...config2.disallowedTools && config2.disallowedTools.length > 0 ? {
              disallowedTools: await this.transformToToolNames(config2.disallowedTools)
            } : {}
          };
        }
        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
       */
      async transformToToolNames(tools) {
        const toolRegistry = this.config.getToolRegistry();
        if (!toolRegistry) {
          return tools;
        }
        await toolRegistry.warmAll();
        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);
          debugLogger63.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,
          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(name4, level) {
        if (level === "builtin") {
          return `<builtin:${name4}>`;
        }
        if (level === "session") {
          return `<session:${name4}>`;
        }
        const baseDir = level === "project" ? path50.join(this.config.getProjectRoot(), QWEN_CONFIG_DIR3, AGENT_CONFIG_DIR) : path50.join(os25.homedir(), QWEN_CONFIG_DIR3, AGENT_CONFIG_DIR);
        return path50.join(baseDir, `${name4}.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 = os25.homedir();
        const isHomeDirectory = path50.resolve(projectRoot) === path50.resolve(homeDir);
        if (level === "project" && isHomeDirectory) {
          return [];
        }
        let baseDir = level === "project" ? projectRoot : homeDir;
        baseDir = path50.join(baseDir, QWEN_CONFIG_DIR3, AGENT_CONFIG_DIR);
        try {
          const files = await fs51.readdir(baseDir);
          const subagents = [];
          for (const file2 of files) {
            if (!file2.endsWith(".md"))
              continue;
            const filePath = path50.join(baseDir, file2);
            try {
              const config2 = await this.parseSubagentFile(filePath, level);
              subagents.push(config2);
            } catch (error40) {
              warnInvalidSubagentFile(filePath, error40);
              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(name4, level) {
        const allSubagents = await this.listSubagentsAtLevel(level);
        const lowerName = name4.toLowerCase();
        for (const subagent of allSubagents) {
          if (subagent.name.toLowerCase() === lowerName) {
            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(name4, level) {
        const existing = await this.loadSubagent(name4, level);
        if (!existing) {
          return true;
        }
        if (level && existing.level !== level) {
          return true;
        }
        return false;
      }
    };
    __name(loadSubagentFromDir, "loadSubagentFromDir");
    __name(parseSubagentContent, "parseSubagentContent");
    __name(warnInvalidSubagentFile, "warnInvalidSubagentFile");
  }
});

// packages/core/dist/src/services/backgroundShellRegistry.js
var debugLogger64, BackgroundShellRegistry;
var init_backgroundShellRegistry = __esm({
  "packages/core/dist/src/services/backgroundShellRegistry.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger64 = createDebugLogger("BACKGROUND_SHELLS");
    BackgroundShellRegistry = class {
      static {
        __name(this, "BackgroundShellRegistry");
      }
      // Entries persist for the session lifetime — no automatic eviction of
      // terminal entries. For typical interactive sessions (tens of background
      // shells over an hour) this is fine, but long-running sessions that spawn
      // many short-lived background commands will see the map and the on-disk
      // output files grow without bound. Eviction policy (LRU? age-based? cap?)
      // is left as a follow-up alongside output-file rotation.
      entries = /* @__PURE__ */ new Map();
      registerCallback;
      statusChangeCallback;
      /**
       * Subscribe to new-entry events. Called synchronously inside `register()`.
       * Setting `undefined` clears the existing subscriber. Single-subscriber on
       * purpose — the UI hook is the only consumer in the codebase, and a list
       * would invite drift in error-handling.
       */
      setRegisterCallback(cb) {
        this.registerCallback = cb;
      }
      /**
       * Subscribe to status transitions (running → terminal). Called
       * synchronously inside `complete()` / `fail()` / `cancel()` after the
       * entry has been mutated. Same single-subscriber rationale as
       * `setRegisterCallback`.
       */
      setStatusChangeCallback(cb) {
        this.statusChangeCallback = cb;
      }
      register(entry) {
        this.entries.set(entry.shellId, entry);
        this.fireRegister(entry);
        this.fireStatusChange(entry);
      }
      get(shellId) {
        return this.entries.get(shellId);
      }
      getAll() {
        return [...this.entries.values()];
      }
      complete(shellId, exitCode, endTime) {
        const entry = this.entries.get(shellId);
        if (!entry || entry.status !== "running")
          return;
        entry.status = "completed";
        entry.exitCode = exitCode;
        entry.endTime = endTime;
        this.fireStatusChange(entry);
      }
      fail(shellId, error40, endTime) {
        const entry = this.entries.get(shellId);
        if (!entry || entry.status !== "running")
          return;
        entry.status = "failed";
        entry.error = error40;
        entry.endTime = endTime;
        this.fireStatusChange(entry);
      }
      cancel(shellId, endTime) {
        const entry = this.entries.get(shellId);
        if (!entry || entry.status !== "running")
          return;
        entry.status = "cancelled";
        entry.endTime = endTime;
        entry.abortController.abort();
        this.fireStatusChange(entry);
      }
      fireRegister(entry) {
        if (!this.registerCallback)
          return;
        try {
          this.registerCallback(entry);
        } catch (error40) {
          debugLogger64.error("register callback failed:", error40);
        }
      }
      fireStatusChange(entry) {
        if (!this.statusChangeCallback)
          return;
        try {
          this.statusChangeCallback(entry);
        } catch (error40) {
          debugLogger64.error("statusChange callback failed:", error40);
        }
      }
      /**
       * Request cancellation without marking the entry terminal.
       *
       * Triggers the entry's AbortController so the spawn handler can tear the
       * process down, but leaves `status='running'` until the settle path
       * observes the abort and records the real exit moment + outcome via
       * `complete()` / `fail()` / `cancel()`. This keeps the registry honest:
       * a cancelled shell only shows its terminal `endTime` once the process
       * has actually drained, and a cancel-vs-exit race can't permanently hide
       * a real completed/failed result.
       *
       * Used by the `task_stop` tool path; the immediate-mark `cancel()` above
       * is reserved for `abortAll()` / shutdown, where the CLI process is
       * tearing down anyway and there is no settle handler to wait for.
       *
       * Idempotent: no-op on entries that aren't `running`.
       */
      requestCancel(shellId) {
        const entry = this.entries.get(shellId);
        if (!entry || entry.status !== "running")
          return;
        entry.abortController.abort();
      }
      /**
       * Cancel every still-running entry. Called on session/Config shutdown so
       * background shells don't outlive the CLI process and leak orphaned
       * children. Symmetric with `BackgroundTaskRegistry.abortAll()` for the
       * subagent path.
       */
      abortAll() {
        const endTime = Date.now();
        for (const entry of Array.from(this.entries.values())) {
          if (entry.status === "running") {
            this.cancel(entry.shellId, endTime);
          }
        }
      }
    };
  }
});

// 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 path51 from "node:path";
import * as fs52 from "node:fs";
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;
}
function substituteHookVariables(hooks, basePath) {
  if (!hooks)
    return hooks;
  const clonedHooks = JSON.parse(JSON.stringify(hooks));
  for (const eventName in clonedHooks) {
    const eventHooks = clonedHooks[eventName];
    if (eventHooks && Array.isArray(eventHooks)) {
      for (const hookDef of eventHooks) {
        if (hookDef.hooks && Array.isArray(hookDef.hooks)) {
          for (const hook of hookDef.hooks) {
            if (hook.type === "command" && hook.command) {
              hook.command = hook.command.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, basePath);
            }
          }
        }
      }
    }
  }
  return clonedHooks;
}
function performVariableReplacement(extensionPath) {
  const mdGlobPattern = "**/*.md";
  const mdGlobOptions = {
    cwd: extensionPath,
    nodir: true
  };
  try {
    const mdFiles = glob.sync(mdGlobPattern, mdGlobOptions);
    for (const file2 of mdFiles) {
      const filePath = path51.join(extensionPath, file2);
      try {
        const content = fs52.readFileSync(filePath, "utf8");
        const updatedContent = content.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, extensionPath);
        const syntaxUpdatedContent = updatedContent.replace(/```!(?:\s*\n)?([\s\S]*?)\n*```/g, "!{$1}");
        const updatedMdContent = syntaxUpdatedContent.replace(/(\$\{?HOME\}?\/|~\/)?\.claude(\/|$)/g, "$1.qwen$2");
        if (updatedMdContent !== content) {
          fs52.writeFileSync(filePath, updatedMdContent, "utf8");
          debugLogger65.debug(`Updated variables, syntax, and .claude paths in file: ${filePath}`);
        }
      } catch (error40) {
        debugLogger65.warn(`Failed to process file ${filePath}: ${error40 instanceof Error ? error40.message : String(error40)}`);
      }
    }
  } catch (error40) {
    debugLogger65.warn(`Failed to scan markdown files in extension directory ${extensionPath}: ${error40 instanceof Error ? error40.message : String(error40)}`);
  }
  const scriptGlobPattern = "**/*.sh";
  const scriptGlobOptions = {
    cwd: extensionPath,
    nodir: true
  };
  try {
    const scriptFiles = glob.sync(scriptGlobPattern, scriptGlobOptions);
    for (const file2 of scriptFiles) {
      const filePath = path51.join(extensionPath, file2);
      try {
        const content = fs52.readFileSync(filePath, "utf8");
        const updatedScriptContent = content.replace(/"role":"assistant"/g, '"type":"assistant"');
        const adaptedScriptContent = updatedScriptContent.replace(/\.message\.content\s*\|\s*map\(select\(\.type\s*==\s*"text"\)\)/g, '.message.parts | map(select(has("text")))');
        const finalScriptContent = adaptedScriptContent.replace(/(\$\{?HOME\}?\/|~\/)?\.claude(\/|$)/g, "$1.qwen$2");
        if (finalScriptContent !== content) {
          fs52.writeFileSync(filePath, finalScriptContent, "utf8");
          debugLogger65.debug(`Updated transcript format and replaced .claude with .qwen in shell script: ${filePath}`);
        }
      } catch (error40) {
        debugLogger65.warn(`Failed to process shell script file ${filePath}: ${error40 instanceof Error ? error40.message : String(error40)}`);
      }
    }
  } catch (error40) {
    debugLogger65.warn(`Failed to scan shell script files in extension directory ${extensionPath}: ${error40 instanceof Error ? error40.message : String(error40)}`);
  }
}
var debugLogger65, 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();
    init_esm13();
    init_debugLogger();
    debugLogger65 = createDebugLogger("Extension:variables");
    EXTENSIONS_DIRECTORY_NAME = path51.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");
    __name(substituteHookVariables, "substituteHookVariables");
    __name(performVariableReplacement, "performVariableReplacement");
  }
});

// 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 fs53 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_esm16 = __esm({
  "node_modules/@isaacs/fs-minipass/dist/esm/index.js"() {
    init_esbuild_shims();
    init_esm11();
    writev = fs53.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(path150, opt) {
        opt = opt || {};
        super(opt);
        this.readable = true;
        this.writable = false;
        if (typeof path150 !== "string") {
          throw new TypeError("path must be a string");
        }
        this[_errored] = false;
        this[_fd] = typeof opt.fd === "number" ? opt.fd : void 0;
        this[_path] = path150;
        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]() {
        fs53.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));
          }
          fs53.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;
          fs53.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, ...args2) {
        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, ...args2);
          default:
            return super.emit(ev, ...args2);
        }
      }
    };
    ReadStreamSync = class extends ReadStream {
      static {
        __name(this, "ReadStreamSync");
      }
      [_open]() {
        let threw = true;
        try {
          this[_onopen](null, fs53.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 : fs53.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;
          fs53.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(path150, opt) {
        opt = opt || {};
        super(opt);
        this[_path] = path150;
        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, ...args2) {
        if (ev === "error") {
          if (this[_errored]) {
            return false;
          }
          this[_errored] = true;
        }
        return super.emit(ev, ...args2);
      }
      get fd() {
        return this[_fd];
      }
      get path() {
        return this[_path];
      }
      [_onerror](er2) {
        this[_close]();
        this[_writing] = true;
        this.emit("error", er2);
      }
      [_open]() {
        fs53.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) {
        fs53.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;
          fs53.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 = fs53.openSync(this[_path], this[_flags], this[_mode]);
          } catch (er2) {
            if (er2?.code === "ENOENT") {
              this[_flags] = "w";
              return this[_open]();
            } else {
              throw er2;
            }
          }
        } else {
          fd = fs53.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;
          fs53.closeSync(fd);
          this.emit("close");
        }
      }
      [_write](buf) {
        let threw = true;
        try {
          this[_onwrite](null, fs53.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_esm17 = __esm({
  "node_modules/minizlib/dist/esm/index.js"() {
    init_esbuild_shims();
    init_esm11();
    init_constants7();
    init_constants7();
    OriginalBufferConcat = Buffer6.concat;
    desc = Object.getOwnPropertyDescriptor(Buffer6, "concat");
    noop4 = /* @__PURE__ */ __name((args2) => args2, "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(err2, origin2) {
        super("zlib: " + err2.message, { cause: err2 });
        this.code = err2.code;
        this.errno = err2.errno;
        if (!this.code)
          this.code = "ZLIB_ERROR";
        this.message = "zlib: " + err2.message;
        Error.captureStackTrace(this, origin2 ?? 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 = (err2) => {
          if (this.#sawError)
            return;
          this.#sawError = true;
          this.close();
          this.emit("error", err2);
        };
        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 (err2) {
          passthroughBufferConcat(false);
          this.#onError(new ZlibError(err2, 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 i4 = 1; i4 < result.length; i4++) {
              writeReturn = this[_superWrite](result[i4]);
            }
          } 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, parse10, 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 i4 = buf.length; i4 > 1; i4--) {
        buf[i4 - 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 i4 = buf.length; i4 > 1; i4--) {
        var byte = num & 255;
        num = Math.floor(num / 256);
        if (flipped) {
          buf[i4 - 1] = onesComp(byte);
        } else if (byte === 0) {
          buf[i4 - 1] = 0;
        } else {
          flipped = true;
          buf[i4 - 1] = twosComp(byte);
        }
      }
    }, "encodeNegative");
    parse10 = /* @__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 i4 = len - 1; i4 > -1; i4--) {
        var byte = Number(buf[i4]);
        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 - i4 - 1);
        }
      }
      return sum;
    }, "twos");
    pos = /* @__PURE__ */ __name((buf) => {
      var len = buf.length;
      var sum = 0;
      for (var i4 = len - 1; i4 > -1; i4--) {
        var byte = Number(buf[i4]);
        if (byte !== 0) {
          sum += byte * Math.pow(256, len - i4 - 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_types16 = __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_types16();
    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 i4 = off; i4 < off + 148; i4++) {
          sum += buf[i4];
        }
        for (let i4 = off + 156; i4 < off + 512; i4++) {
          sum += buf[i4];
        }
        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 path150 = split[0];
        const prefix = split[1];
        this.needPax = !!split[2];
        this.needPax = encString(buf, off, 100, path150) || 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 i4 = off; i4 < off + 148; i4++) {
          sum += buf[i4];
        }
        for (let i4 = off + 156; i4 < off + 512; i4++) {
          sum += buf[i4];
        }
        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 ? parse10(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, date5) => date5 === void 0 ? false : encNumber(buf, off, size, date5.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, merge2, 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 body2 = this.encodeBody();
        if (body2 === "") {
          return Buffer.allocUnsafe(0);
        }
        const bodyLen = Buffer.byteLength(body2);
        const bufLen = 512 * Math.ceil(1 + bodyLen / 512);
        const buf = Buffer.allocUnsafe(bufLen);
        for (let i4 = 0; i4 < 512; i4++) {
          buf[i4] = 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(body2, 512, bodyLen, "utf8");
        for (let i4 = bodyLen + 512; i4 < buf.length; i4++) {
          buf[i4] = 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(merge2(parseKV(str2), ex), g2);
      }
    };
    merge2 = /* @__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((set2, line) => {
      const n3 = parseInt(line, 10);
      if (n3 !== Buffer.byteLength(line) + 1) {
        return set2;
      }
      line = line.slice((n3 + " ").length);
      const kv = line.split("=");
      const r5 = kv.shift();
      if (!r5) {
        return set2;
      }
      const k2 = r5.replace(/^SCHILY\.(dev|ino|nlink)/, "$1");
      const v2 = kv.join("=");
      set2[k2] = /^([A-Z]+\.)?([mac]|birth|creation)time$/.test(k2) ? new Date(Number(v2) * 1e3) : /^[0-9]+$/.test(v2) ? +v2 : v2;
      return set2;
    }, "parseKVLine");
  }
});

// node_modules/tar/dist/esm/normalize-windows-path.js
var platform5, normalizeWindowsPath;
var init_normalize_windows_path = __esm({
  "node_modules/tar/dist/esm/normalize-windows-path.js"() {
    init_esbuild_shims();
    platform5 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
    normalizeWindowsPath = platform5 !== "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_esm11();
    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, Parser3;
var init_parse5 = __esm({
  "node_modules/tar/dist/esm/parse.js"() {
    init_esbuild_shims();
    init_esm17();
    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");
    Parser3 = 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, ...args2] = entry;
          this.emit(ev, ...args2);
        } 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(error40) {
        this[ABORTED2] = true;
        this.emit("abort", error40);
        this.warn("TAR_ABORT", error40, { 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 i4 = 0; this[UNZIP] === void 0 && i4 < gzipHeader.length; i4++) {
            if (chunk[i4] !== gzipHeader[i4]) {
              this[UNZIP] = false;
            }
          }
          let isZstd = false;
          if (this[UNZIP] === false && this.zstd !== false) {
            isZstd = true;
            for (let i4 = 0; i4 < zstdHeader.length; i4++) {
              if (chunk[i4] !== zstdHeader[i4]) {
                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 i4 = str2.length - 1;
      let slashesStart = -1;
      while (i4 > -1 && str2.charAt(i4) === "/") {
        slashesStart = i4;
        i4--;
      }
      return slashesStart === -1 ? str2 : str2.slice(0, slashesStart);
    }, "stripTrailingSlashes");
  }
});

// node_modules/tar/dist/esm/list.js
import fs54 from "node:fs";
import { dirname as dirname14, parse as parse11 } from "path";
var onReadEntryFunction, filesFilter, listFileSync, listFile, list;
var init_list = __esm({
  "node_modules/tar/dist/esm/list.js"() {
    init_esbuild_shims();
    init_esm16();
    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 map3 = new Map(files.map((f5) => [stripTrailingSlashes(f5), true]));
      const filter5 = opt.filter;
      const mapHas = /* @__PURE__ */ __name((file2, r5 = "") => {
        const root = r5 || parse11(file2).root || ".";
        let ret;
        if (file2 === root)
          ret = false;
        else {
          const m3 = map3.get(file2);
          if (m3 !== void 0) {
            ret = m3;
          } else {
            ret = mapHas(dirname14(file2), root);
          }
        }
        map3.set(file2, ret);
        return ret;
      }, "mapHas");
      opt.filter = filter5 ? (file2, entry) => filter5(file2, entry) && mapHas(stripTrailingSlashes(file2)) : (file2) => mapHas(stripTrailingSlashes(file2));
    }, "filesFilter");
    listFileSync = /* @__PURE__ */ __name((opt) => {
      const p2 = new Parser3(opt);
      const file2 = opt.file;
      let fd;
      try {
        fd = fs54.openSync(file2, "r");
        const stat14 = fs54.fstatSync(fd);
        const readSize = opt.maxReadSize || 16 * 1024 * 1024;
        if (stat14.size < readSize) {
          const buf = Buffer.allocUnsafe(stat14.size);
          const read3 = fs54.readSync(fd, buf, 0, stat14.size, 0);
          p2.end(read3 === buf.byteLength ? buf : buf.subarray(0, read3));
        } else {
          let pos2 = 0;
          const buf = Buffer.allocUnsafe(readSize);
          while (pos2 < stat14.size) {
            const bytesRead = fs54.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 {
            fs54.closeSync(fd);
          } catch (er2) {
          }
        }
      }
    }, "listFileSync");
    listFile = /* @__PURE__ */ __name((opt, _files) => {
      const parse17 = new Parser3(opt);
      const readSize = opt.maxReadSize || 16 * 1024 * 1024;
      const file2 = opt.file;
      const p2 = new Promise((resolve42, reject) => {
        parse17.on("error", reject);
        parse17.on("end", resolve42);
        fs54.stat(file2, (er2, stat14) => {
          if (er2) {
            reject(er2);
          } else {
            const stream5 = new ReadStream(file2, {
              readSize,
              size: stat14.size
            });
            stream5.on("error", reject);
            stream5.pipe(parse17);
          }
        });
      });
      return p2;
    }, "listFile");
    list = makeCommand(listFileSync, listFile, (opt) => new Parser3(opt), (opt) => new Parser3(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 isAbsolute7, parse12, stripAbsolutePath;
var init_strip_absolute_path = __esm({
  "node_modules/tar/dist/esm/strip-absolute-path.js"() {
    init_esbuild_shims();
    ({ isAbsolute: isAbsolute7, parse: parse12 } = win322);
    stripAbsolutePath = /* @__PURE__ */ __name((path150) => {
      let r5 = "";
      let parsed = parse12(path150);
      while (isAbsolute7(path150) || parsed.root) {
        const root = path150.charAt(0) === "/" && path150.slice(0, 4) !== "//?/" ? "/" : parsed.root;
        path150 = path150.slice(root.length);
        r5 += root;
        parsed = parse12(path150);
      }
      return [r5, path150];
    }, "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, i4) => [char, win[i4]]));
    toRaw = new Map(win.map((char, i4) => [char, raw[i4]]));
    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 fs55 from "fs";
import path52 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_esm11();
    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((path150, prefix) => {
      if (!prefix) {
        return normalizeWindowsPath(path150);
      }
      path150 = normalizeWindowsPath(path150).replace(/^\.(\/|$)/, "");
      return stripTrailingSlashes(prefix) + "/" + path150;
    }, "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 || path52.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]() {
        fs55.lstat(this.absolute, (er2, stat14) => {
          if (er2) {
            return this.emit("error", er2);
          }
          this[ONLSTAT](stat14);
        });
      }
      [ONLSTAT](stat14) {
        this.statCache.set(this.absolute, stat14);
        this.stat = stat14;
        if (!stat14.isFile()) {
          stat14.size = 0;
        }
        this.type = getType3(stat14);
        this.emit("stat", stat14);
        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](path150) {
        return prefixPath(path150, 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]() {
        fs55.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(path52.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]() {
        fs55.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");
        }
        fs55.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)
          fs55.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 i4 = bytesRead; i4 < this.length && bytesRead < this.blockRemain; i4++) {
            this.buf[i4 + 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](fs55.lstatSync(this.absolute));
      }
      [SYMLINK]() {
        this[ONREADLINK](fs55.readlinkSync(this.absolute));
      }
      [OPENFILE]() {
        this[ONOPENFILE](fs55.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 = fs55.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)
          fs55.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](path150) {
        return prefixPath(path150, 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((stat14) => stat14.isFile() ? "File" : stat14.isDirectory() ? "Directory" : stat14.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 Node2(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 Node2(item, self2.tail, void 0, self2);
  if (!self2.head) {
    self2.head = self2.tail;
  }
  self2.length++;
}
function unshift(self2, item) {
  self2.head = new Node2(item, void 0, self2.head, self2);
  if (!self2.tail) {
    self2.tail = self2.head;
  }
  self2.length++;
}
var Yallist, Node2;
var init_esm18 = __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(...args2) {
        for (let i4 = 0, l3 = args2.length; i4 < l3; i4++) {
          push(this, args2[i4]);
        }
        return this.length;
      }
      unshift(...args2) {
        for (var i4 = 0, l3 = args2.length; i4 < l3; i4++) {
          unshift(this, args2[i4]);
        }
        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, i4 = 0; !!walker; i4++) {
          fn.call(thisp, walker.value, i4, this);
          walker = walker.next;
        }
      }
      forEachReverse(fn, thisp) {
        thisp = thisp || this;
        for (let walker = this.tail, i4 = this.length - 1; !!walker; i4--) {
          fn.call(thisp, walker.value, i4, this);
          walker = walker.prev;
        }
      }
      get(n3) {
        let i4 = 0;
        let walker = this.head;
        for (; !!walker && i4 < n3; i4++) {
          walker = walker.next;
        }
        if (i4 === n3 && !!walker) {
          return walker.value;
        }
      }
      getReverse(n3) {
        let i4 = 0;
        let walker = this.tail;
        for (; !!walker && i4 < n3; i4++) {
          walker = walker.prev;
        }
        if (i4 === 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 i4 = 0; !!walker; i4++) {
          acc = fn(acc, walker.value, i4);
          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 i4 = this.length - 1; !!walker; i4--) {
          acc = fn(acc, walker.value, i4);
          walker = walker.prev;
        }
        return acc;
      }
      toArray() {
        const arr = new Array(this.length);
        for (let i4 = 0, walker = this.head; !!walker; i4++) {
          arr[i4] = walker.value;
          walker = walker.next;
        }
        return arr;
      }
      toArrayReverse() {
        const arr = new Array(this.length);
        for (let i4 = 0, walker = this.tail; !!walker; i4++) {
          arr[i4] = 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 i4 = 0;
        for (i4 = 0; !!walker && i4 < from; i4++) {
          walker = walker.next;
        }
        for (; !!walker && i4 < to; i4++, 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 i4 = this.length;
        let walker = this.tail;
        for (; !!walker && i4 > to; i4--) {
          walker = walker.prev;
        }
        for (; !!walker && i4 > from; i4--, walker = walker.prev) {
          ret.push(walker.value);
        }
        return ret;
      }
      splice(start2, deleteCount = 0, ...nodes) {
        if (start2 > this.length) {
          start2 = this.length - 1;
        }
        if (start2 < 0) {
          start2 = this.length + start2;
        }
        let walker = this.head;
        for (let i4 = 0; !!walker && i4 < start2; i4++) {
          walker = walker.next;
        }
        const ret = [];
        for (let i4 = 0; !!walker && i4 < deleteCount; i4++) {
          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");
    Node2 = 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 fs56 from "fs";
import path53 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_esm11();
    init_esm17();
    init_esm18();
    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(path150, absolute) {
        this.path = path150 || "./";
        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(path150) {
        this.write(path150);
        return this;
      }
      end(path150, encoding, cb) {
        if (typeof path150 === "function") {
          cb = path150;
          path150 = void 0;
        }
        if (typeof encoding === "function") {
          cb = encoding;
          encoding = void 0;
        }
        if (path150) {
          this.add(path150);
        }
        this[ENDED2] = true;
        this[PROCESS3]();
        if (cb)
          cb();
        return this;
      }
      write(path150) {
        if (this[ENDED2]) {
          throw new Error("write after end");
        }
        if (path150 instanceof ReadEntry) {
          this[ADDTARENTRY](path150);
        } else {
          this[ADDFSENTRY](path150);
        }
        return this.flowing;
      }
      [ADDTARENTRY](p2) {
        const absolute = normalizeWindowsPath(path53.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(path53.resolve(this.cwd, p2));
        this[QUEUE2].push(new PackJob(p2, absolute));
        this[PROCESS3]();
      }
      [STAT](job) {
        job.pending = true;
        this[JOBS] += 1;
        const stat14 = this.follow ? "stat" : "lstat";
        fs56[stat14](job.absolute, (er2, stat15) => {
          job.pending = false;
          this[JOBS] -= 1;
          if (er2) {
            this.emit("error", er2);
          } else {
            this[ONSTAT](job, stat15);
          }
        });
      }
      [ONSTAT](job, stat14) {
        this.statCache.set(job.absolute, stat14);
        job.stat = stat14;
        if (!this.filter(job.path, stat14)) {
          job.ignore = true;
        }
        this[PROCESS3]();
      }
      [READDIR](job) {
        job.pending = true;
        this[JOBS] += 1;
        fs56.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 stat14 = this.follow ? "statSync" : "lstatSync";
        this[ONSTAT](job, fs56[stat14](job.absolute));
      }
      [READDIR](job) {
        this[ONREADDIR](job, fs56.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 path54 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_esm16();
    init_list();
    init_make_command();
    init_pack();
    createFileSync = /* @__PURE__ */ __name((opt, files) => {
      const p2 = new PackSync(opt);
      const stream5 = new WriteStreamSync(opt.file, {
        mode: opt.mode || 438
      });
      p2.pipe(stream5);
      addFilesSync(p2, files);
    }, "createFileSync");
    createFile = /* @__PURE__ */ __name((opt, files) => {
      const p2 = new Pack(opt);
      const stream5 = new WriteStream(opt.file, {
        mode: opt.mode || 438
      });
      p2.pipe(stream5);
      const promise2 = new Promise((res, rej) => {
        stream5.on("error", rej);
        stream5.on("close", res);
        p2.on("error", rej);
      });
      addFilesAsync(p2, files);
      return promise2;
    }, "createFile");
    addFilesSync = /* @__PURE__ */ __name((p2, files) => {
      files.forEach((file2) => {
        if (file2.charAt(0) === "@") {
          list({
            file: path54.resolve(p2.cwd, file2.slice(1)),
            sync: true,
            noResume: true,
            onReadEntry: /* @__PURE__ */ __name((entry) => p2.add(entry), "onReadEntry")
          });
        } else {
          p2.add(file2);
        }
      });
      p2.end();
    }, "addFilesSync");
    addFilesAsync = /* @__PURE__ */ __name(async (p2, files) => {
      for (let i4 = 0; i4 < files.length; i4++) {
        const file2 = String(files[i4]);
        if (file2.charAt(0) === "@") {
          await list({
            file: path54.resolve(String(p2.cwd), file2.slice(1)),
            noResume: true,
            onReadEntry: /* @__PURE__ */ __name((entry) => {
              p2.add(entry);
            }, "onReadEntry")
          });
        } else {
          p2.add(file2);
        }
      }
      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 fs57 from "fs";
var platform6, 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();
    platform6 = process.env.__FAKE_PLATFORM__ || process.platform;
    isWindows3 = platform6 === "win32";
    ({ O_CREAT, O_TRUNC, O_WRONLY } = fs57.constants);
    UV_FS_O_FILEMAP = Number(process.env.__FAKE_FS_O_FILENAME__) || fs57.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 fs58 from "node:fs";
import path55 from "node:path";
var lchownSync, chown, chownrKid, chownr, chownrKidSync, chownrSync;
var init_esm19 = __esm({
  "node_modules/chownr/dist/esm/index.js"() {
    init_esbuild_shims();
    lchownSync = /* @__PURE__ */ __name((path150, uid, gid) => {
      try {
        return fs58.lchownSync(path150, uid, gid);
      } catch (er2) {
        if (er2?.code !== "ENOENT")
          throw er2;
      }
    }, "lchownSync");
    chown = /* @__PURE__ */ __name((cpath, uid, gid, cb) => {
      fs58.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(path55.resolve(p2, child.name), uid, gid, (er2) => {
          if (er2)
            return cb(er2);
          const cpath = path55.resolve(p2, child.name);
          chown(cpath, uid, gid, cb);
        });
      } else {
        const cpath = path55.resolve(p2, child.name);
        chown(cpath, uid, gid, cb);
      }
    }, "chownrKid");
    chownr = /* @__PURE__ */ __name((p2, uid, gid, cb) => {
      fs58.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(path55.resolve(p2, child.name), uid, gid);
      lchownSync(path55.resolve(p2, child.name), uid, gid);
    }, "chownrKidSync");
    chownrSync = /* @__PURE__ */ __name((p2, uid, gid) => {
      let children;
      try {
        children = fs58.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(path150, code2) {
        super(`${code2}: Cannot cd into '${path150}'`);
        this.path = path150;
        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, path150) {
        super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link");
        this.symlink = symlink;
        this.path = path150;
      }
      get name() {
        return "SymlinkError";
      }
    };
  }
});

// node_modules/tar/dist/esm/mkdir.js
import fs59 from "node:fs";
import fsp from "node:fs/promises";
import path56 from "node:path";
var checkCwd, mkdir8, mkdir_, onmkdir, checkCwdSync, mkdirSync4;
var init_mkdir = __esm({
  "node_modules/tar/dist/esm/mkdir.js"() {
    init_esbuild_shims();
    init_esm19();
    init_cwd_error();
    init_normalize_windows_path();
    init_symlink_error();
    checkCwd = /* @__PURE__ */ __name((dir, cb) => {
      fs59.stat(dir, (er2, st2) => {
        if (er2 || !st2.isDirectory()) {
          er2 = new CwdError(dir, er2?.code || "ENOTDIR");
        }
        cb(er2);
      });
    }, "checkCwd");
    mkdir8 = /* @__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 unlink6 = opt.unlink;
      const cwd6 = 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) {
            fs59.chmod(dir, mode, cb);
          } else {
            cb();
          }
        }
      }, "done");
      if (dir === cwd6) {
        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(path56.relative(cwd6, dir));
      const parts2 = sub.split("/");
      mkdir_(cwd6, parts2, mode, unlink6, cwd6, void 0, done);
    }, "mkdir");
    mkdir_ = /* @__PURE__ */ __name((base, parts2, mode, unlink6, cwd6, created, cb) => {
      if (!parts2.length) {
        return cb(null, created);
      }
      const p2 = parts2.shift();
      const part = normalizeWindowsPath(path56.resolve(base + "/" + p2));
      fs59.mkdir(part, mode, onmkdir(part, parts2, mode, unlink6, cwd6, created, cb));
    }, "mkdir_");
    onmkdir = /* @__PURE__ */ __name((part, parts2, mode, unlink6, cwd6, created, cb) => (er2) => {
      if (er2) {
        fs59.lstat(part, (statEr, st2) => {
          if (statEr) {
            statEr.path = statEr.path && normalizeWindowsPath(statEr.path);
            cb(statEr);
          } else if (st2.isDirectory()) {
            mkdir_(part, parts2, mode, unlink6, cwd6, created, cb);
          } else if (unlink6) {
            fs59.unlink(part, (er3) => {
              if (er3) {
                return cb(er3);
              }
              fs59.mkdir(part, mode, onmkdir(part, parts2, mode, unlink6, cwd6, created, cb));
            });
          } else if (st2.isSymbolicLink()) {
            return cb(new SymlinkError(part, part + "/" + parts2.join("/")));
          } else {
            cb(er2);
          }
        });
      } else {
        created = created || part;
        mkdir_(part, parts2, mode, unlink6, cwd6, created, cb);
      }
    }, "onmkdir");
    checkCwdSync = /* @__PURE__ */ __name((dir) => {
      let ok2 = false;
      let code2 = void 0;
      try {
        ok2 = fs59.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 unlink6 = opt.unlink;
      const cwd6 = normalizeWindowsPath(opt.cwd);
      const done = /* @__PURE__ */ __name((created2) => {
        if (created2 && doChown) {
          chownrSync(created2, uid, gid);
        }
        if (needChmod) {
          fs59.chmodSync(dir, mode);
        }
      }, "done");
      if (dir === cwd6) {
        checkCwdSync(cwd6);
        return done();
      }
      if (preserve) {
        return done(fs59.mkdirSync(dir, { mode, recursive: true }) ?? void 0);
      }
      const sub = normalizeWindowsPath(path56.relative(cwd6, dir));
      const parts2 = sub.split("/");
      let created = void 0;
      for (let p2 = parts2.shift(), part = cwd6; p2 && (part += "/" + p2); p2 = parts2.shift()) {
        part = normalizeWindowsPath(path56.resolve(part));
        try {
          fs59.mkdirSync(part, mode);
          created = created || part;
        } catch (er2) {
          const st2 = fs59.lstatSync(part);
          if (st2.isDirectory()) {
            continue;
          } else if (unlink6) {
            fs59.unlinkSync(part);
            fs59.mkdirSync(part, mode);
            created = created || part;
            continue;
          } else if (st2.isSymbolicLink()) {
            return new SymlinkError(part, part + "/" + parts2.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 i4 = cache2.size - MAX;
      if (i4 > MAX / 10) {
        for (const s6 of cache2) {
          cache2.delete(s6);
          delete normalizeCache2[s6];
          if (--i4 <= 0)
            break;
        }
      }
      return ret;
    }, "normalizeUnicode");
  }
});

// node_modules/tar/dist/esm/path-reservations.js
import { join as join24 } from "node:path";
var platform7, 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();
    platform7 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
    isWindows4 = platform7 === "win32";
    getDirs = /* @__PURE__ */ __name((path150) => {
      const dirs = path150.split("/").slice(0, -1).reduce((set2, path151) => {
        const s5 = set2[set2.length - 1];
        if (s5 !== void 0) {
          path151 = join24(s5, path151);
        }
        set2.push(path151 || "/");
        return set2;
      }, []);
      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(join24(normalizeUnicode(p2))).toLowerCase();
        });
        const dirs = new Set(paths.map((path150) => getDirs(path150)).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((path150) => this.#queues.get(path150)),
          dirs: [...res.dirs].map((path150) => this.#queues.get(path150))
        };
      }
      // 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 path150 of paths) {
          const q2 = this.#queues.get(path150);
          if (!q2 || q2?.[0] !== fn) {
            continue;
          }
          const q0 = q2[1];
          if (!q0) {
            this.#queues.delete(path150);
            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 randomBytes6 } from "node:crypto";
import fs60 from "node:fs";
import path57 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, platform8, isWindows5, DEFAULT_MAX_DEPTH, unlinkFile, unlinkFileSync, uint322, Unpack, callSync, UnpackSync;
var init_unpack = __esm({
  "node_modules/tar/dist/esm/unpack.js"() {
    init_esbuild_shims();
    init_esm16();
    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");
    platform8 = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
    isWindows5 = platform8 === "win32";
    DEFAULT_MAX_DEPTH = 1024;
    unlinkFile = /* @__PURE__ */ __name((path150, cb) => {
      if (!isWindows5) {
        return fs60.unlink(path150, cb);
      }
      const name4 = path150 + ".DELETE." + randomBytes6(16).toString("hex");
      fs60.rename(path150, name4, (er2) => {
        if (er2) {
          return cb(er2);
        }
        fs60.unlink(name4, cb);
      });
    }, "unlinkFile");
    unlinkFileSync = /* @__PURE__ */ __name((path150) => {
      if (!isWindows5) {
        return fs60.unlinkSync(path150);
      }
      const name4 = path150 + ".DELETE." + randomBytes6(16).toString("hex");
      fs60.renameSync(path150, name4);
      fs60.unlinkSync(name4);
    }, "unlinkFileSync");
    uint322 = /* @__PURE__ */ __name((a2, b2, c4) => a2 !== void 0 && a2 === a2 >>> 0 ? a2 : b2 !== void 0 && b2 === b2 >>> 0 ? b2 : c4, "uint32");
    Unpack = class extends Parser3 {
      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(path57.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 parts2 = p2.split("/");
        if (this.strip) {
          if (parts2.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;
            }
          }
          parts2.splice(0, this.strip);
          entry.path = parts2.join("/");
        }
        if (isFinite(this.maxDepth) && parts2.length > this.maxDepth) {
          this.warn("TAR_ENTRY_ERROR", "path excessively deep", {
            entry,
            path: p2,
            depth: parts2.length,
            maxDepth: this.maxDepth
          });
          return false;
        }
        if (!this.preservePaths) {
          if (parts2.includes("..") || /* c8 ignore next */
          isWindows5 && /^[a-z]:\.\.$/i.test(parts2[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 (path57.isAbsolute(entry.path)) {
          entry.absolute = normalizeWindowsPath(path57.resolve(entry.path));
        } else {
          entry.absolute = normalizeWindowsPath(path57.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 } = path57.win32.parse(String(entry.absolute));
          entry.absolute = aRoot + encode3(String(entry.absolute).slice(aRoot.length));
          const { root: pRoot } = path57.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) {
        mkdir8(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 uint322(this.uid, entry.uid, this.processUid);
      }
      [GID](entry) {
        return uint322(this.gid, entry.gid, this.processGid);
      }
      [FILE2](entry, fullyDone) {
        const mode = typeof entry.mode === "number" ? entry.mode & 4095 : this.fmode;
        const stream5 = new WriteStream(String(entry.absolute), {
          // slight lie, but it can be numeric flags
          flags: getWriteFlag(entry.size),
          mode,
          autoClose: false
        });
        stream5.on("error", (er2) => {
          if (stream5.fd) {
            fs60.close(stream5.fd, () => {
            });
          }
          stream5.write = () => true;
          this[ONERROR](er2, entry);
          fullyDone();
        });
        let actions = 1;
        const done = /* @__PURE__ */ __name((er2) => {
          if (er2) {
            if (stream5.fd) {
              fs60.close(stream5.fd, () => {
              });
            }
            this[ONERROR](er2, entry);
            fullyDone();
            return;
          }
          if (--actions === 0) {
            if (stream5.fd !== void 0) {
              fs60.close(stream5.fd, (er3) => {
                if (er3) {
                  this[ONERROR](er3, entry);
                } else {
                  this[UNPEND]();
                }
                fullyDone();
              });
            }
          }
        }, "done");
        stream5.on("finish", () => {
          const abs = String(entry.absolute);
          const fd = stream5.fd;
          if (typeof fd === "number" && entry.mtime && !this.noMtime) {
            actions++;
            const atime = entry.atime || /* @__PURE__ */ new Date();
            const mtime = entry.mtime;
            fs60.futimes(fd, atime, mtime, (er2) => er2 ? fs60.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") {
              fs60.fchown(fd, uid, gid, (er2) => er2 ? fs60.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(stream5);
      }
      [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++;
            fs60.utimes(String(entry.absolute), entry.atime || /* @__PURE__ */ new Date(), entry.mtime, done);
          }
          if (this[DOCHOWN](entry)) {
            actions++;
            fs60.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(path57.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;
            start2();
          });
        }, "checkCwd");
        const start2 = /* @__PURE__ */ __name(() => {
          if (entry.absolute !== this.cwd) {
            const parent = normalizeWindowsPath(path57.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(() => {
          fs60.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 fs60.chmod(String(entry.absolute), Number(entry.mode), afterChmod);
              }
              if (entry.absolute !== this.cwd) {
                return fs60.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]) {
          start2();
        } 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) {
        fs60[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(path57.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(() => fs60.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(() => {
              fs60.chmodSync(String(entry.absolute), Number(entry.mode));
            }) : [];
            return this[MAKEFS](er4, entry);
          }
          const [er3] = callSync(() => fs60.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 {
            fs60.closeSync(fd);
          } catch (e4) {
            closeError = e4;
          }
          if (er2 || closeError) {
            this[ONERROR](er2 || closeError, entry);
          }
          done();
        }, "oner");
        let fd;
        try {
          fd = fs60.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 {
            fs60.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 {
              fs60.futimesSync(fd, atime, mtime);
            } catch (futimeser) {
              try {
                fs60.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 {
              fs60.fchownSync(fd, Number(uid), Number(gid));
            } catch (fchowner) {
              try {
                fs60.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 {
            fs60.utimesSync(String(entry.absolute), entry.atime || /* @__PURE__ */ new Date(), entry.mtime);
          } catch (er3) {
          }
        }
        if (this[DOCHOWN](entry)) {
          try {
            fs60.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 {
          fs60[ls](linkpath, String(entry.absolute));
          done();
          entry.resume();
        } catch (er2) {
          return this[ONERROR](er2, entry);
        }
      }
    };
  }
});

// node_modules/tar/dist/esm/extract.js
import fs61 from "node:fs";
var extractFileSync, extractFile, extract;
var init_extract = __esm({
  "node_modules/tar/dist/esm/extract.js"() {
    init_esbuild_shims();
    init_esm16();
    init_list();
    init_make_command();
    init_unpack();
    extractFileSync = /* @__PURE__ */ __name((opt) => {
      const u2 = new UnpackSync(opt);
      const file2 = opt.file;
      const stat14 = fs61.statSync(file2);
      const readSize = opt.maxReadSize || 16 * 1024 * 1024;
      const stream5 = new ReadStreamSync(file2, {
        readSize,
        size: stat14.size
      });
      stream5.pipe(u2);
    }, "extractFileSync");
    extractFile = /* @__PURE__ */ __name((opt, _2) => {
      const u2 = new Unpack(opt);
      const readSize = opt.maxReadSize || 16 * 1024 * 1024;
      const file2 = opt.file;
      const p2 = new Promise((resolve42, reject) => {
        u2.on("error", reject);
        u2.on("close", resolve42);
        fs61.stat(file2, (er2, stat14) => {
          if (er2) {
            reject(er2);
          } else {
            const stream5 = new ReadStream(file2, {
              readSize,
              size: stat14.size
            });
            stream5.on("error", reject);
            stream5.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 fs62 from "node:fs";
import path58 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_esm16();
    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 = fs62.openSync(opt.file, "r+");
        } catch (er2) {
          if (er2?.code === "ENOENT") {
            fd = fs62.openSync(opt.file, "w+");
          } else {
            throw er2;
          }
        }
        const st2 = fs62.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 = fs62.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 {
            fs62.closeSync(fd);
          } catch (er2) {
          }
        }
      }
    }, "replaceSync");
    streamSync2 = /* @__PURE__ */ __name((opt, p2, position, fd, files) => {
      const stream5 = new WriteStreamSync(opt.file, {
        fd,
        start: position
      });
      p2.pipe(stream5);
      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) {
            fs62.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 fs62.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;
          fs62.read(fd, headBuf, 0, 512, position, onread);
        }, "onread");
        fs62.read(fd, headBuf, 0, 512, position, onread);
      }, "getPos");
      const promise2 = new Promise((resolve42, reject) => {
        p2.on("error", reject);
        let flag = "r+";
        const onopen = /* @__PURE__ */ __name((er2, fd) => {
          if (er2 && er2.code === "ENOENT" && flag === "r+") {
            flag = "w+";
            return fs62.open(opt.file, flag, onopen);
          }
          if (er2 || !fd) {
            return reject(er2);
          }
          fs62.fstat(fd, (er3, st2) => {
            if (er3) {
              return fs62.close(fd, () => reject(er3));
            }
            getPos(fd, st2.size, (er4, position) => {
              if (er4) {
                return reject(er4);
              }
              const stream5 = new WriteStream(opt.file, {
                fd,
                start: position
              });
              p2.pipe(stream5);
              stream5.on("error", reject);
              stream5.on("close", resolve42);
              addFilesAsync2(p2, files);
            });
          });
        }, "onopen");
        fs62.open(opt.file, flag, onopen);
      });
      return promise2;
    }, "replaceAsync");
    addFilesSync2 = /* @__PURE__ */ __name((p2, files) => {
      files.forEach((file2) => {
        if (file2.charAt(0) === "@") {
          list({
            file: path58.resolve(p2.cwd, file2.slice(1)),
            sync: true,
            noResume: true,
            onReadEntry: /* @__PURE__ */ __name((entry) => p2.add(entry), "onReadEntry")
          });
        } else {
          p2.add(file2);
        }
      });
      p2.end();
    }, "addFilesSync");
    addFilesAsync2 = /* @__PURE__ */ __name(async (p2, files) => {
      for (let i4 = 0; i4 < files.length; i4++) {
        const file2 = String(files[i4]);
        if (file2.charAt(0) === "@") {
          await list({
            file: path58.resolve(String(p2.cwd), file2.slice(1)),
            noResume: true,
            onReadEntry: /* @__PURE__ */ __name((entry) => p2.add(entry), "onReadEntry")
          });
        } else {
          p2.add(file2);
        }
      }
      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 filter5 = opt.filter;
      if (!opt.mtimeCache) {
        opt.mtimeCache = /* @__PURE__ */ new Map();
      }
      opt.filter = filter5 ? (path150, stat14) => filter5(path150, stat14) && !/* c8 ignore start */
      ((opt.mtimeCache?.get(path150) ?? stat14.mtime ?? 0) > (stat14.mtime ?? 0)) : (path150, stat14) => !/* c8 ignore start */
      ((opt.mtimeCache?.get(path150) ?? stat14.mtime ?? 0) > (stat14.mtime ?? 0));
    }, "mtimeFilter");
  }
});

// node_modules/tar/dist/esm/index.js
var init_esm20 = __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_types16();
    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 args2 = new Array(arguments.length);
        for (var i4 = 0; i4 < args2.length; i4++) {
          args2[i4] = arguments[i4];
        }
        var ret = fn.apply(this, args2);
        var cb2 = args2[args2.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 name4 = fn.name || "Function wrapped with `once`";
      f5.onceError = name4 + " 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 noop11 = /* @__PURE__ */ __name(function() {
    }, "noop");
    var qnt = globalThis.Bare ? queueMicrotask : process.nextTick.bind(process);
    var isRequest4 = /* @__PURE__ */ __name(function(stream5) {
      return stream5.setHeader && typeof stream5.abort === "function";
    }, "isRequest");
    var isChildProcess = /* @__PURE__ */ __name(function(stream5) {
      return stream5.stdio && Array.isArray(stream5.stdio) && stream5.stdio.length === 3;
    }, "isChildProcess");
    var eos = /* @__PURE__ */ __name(function(stream5, opts, callback) {
      if (typeof opts === "function") return eos(stream5, null, opts);
      if (!opts) opts = {};
      callback = once(callback || noop11);
      var ws2 = stream5._writableState;
      var rs = stream5._readableState;
      var readable = opts.readable || opts.readable !== false && stream5.readable;
      var writable = opts.writable || opts.writable !== false && stream5.writable;
      var cancelled = false;
      var onlegacyfinish = /* @__PURE__ */ __name(function() {
        if (!stream5.writable) onfinish();
      }, "onlegacyfinish");
      var onfinish = /* @__PURE__ */ __name(function() {
        writable = false;
        if (!readable) callback.call(stream5);
      }, "onfinish");
      var onend = /* @__PURE__ */ __name(function() {
        readable = false;
        if (!writable) callback.call(stream5);
      }, "onend");
      var onexit = /* @__PURE__ */ __name(function(exitCode) {
        callback.call(stream5, exitCode ? new Error("exited with error code: " + exitCode) : null);
      }, "onexit");
      var onerror = /* @__PURE__ */ __name(function(err2) {
        callback.call(stream5, err2);
      }, "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(stream5, new Error("premature close"));
        if (writable && !(ws2 && (ws2.ended && !ws2.destroyed))) return callback.call(stream5, new Error("premature close"));
      }, "onclosenexttick");
      var onrequest = /* @__PURE__ */ __name(function() {
        stream5.req.on("finish", onfinish);
      }, "onrequest");
      if (isRequest4(stream5)) {
        stream5.on("complete", onfinish);
        stream5.on("abort", onclose);
        if (stream5.req) onrequest();
        else stream5.on("request", onrequest);
      } else if (writable && !ws2) {
        stream5.on("end", onlegacyfinish);
        stream5.on("close", onlegacyfinish);
      }
      if (isChildProcess(stream5)) stream5.on("exit", onexit);
      stream5.on("end", onend);
      stream5.on("finish", onfinish);
      if (opts.error !== false) stream5.on("error", onerror);
      stream5.on("close", onclose);
      return function() {
        cancelled = true;
        stream5.removeListener("complete", onfinish);
        stream5.removeListener("abort", onclose);
        stream5.removeListener("request", onrequest);
        if (stream5.req) stream5.req.removeListener("finish", onfinish);
        stream5.removeListener("end", onlegacyfinish);
        stream5.removeListener("close", onlegacyfinish);
        stream5.removeListener("finish", onfinish);
        stream5.removeListener("exit", onexit);
        stream5.removeListener("end", onend);
        stream5.removeListener("error", onerror);
        stream5.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 fs142;
    try {
      fs142 = __require("fs");
    } catch (e4) {
    }
    var noop11 = /* @__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(stream5) {
      if (!ancient) return false;
      if (!fs142) return false;
      return (stream5 instanceof (fs142.ReadStream || noop11) || stream5 instanceof (fs142.WriteStream || noop11)) && isFn(stream5.close);
    }, "isFS");
    var isRequest4 = /* @__PURE__ */ __name(function(stream5) {
      return stream5.setHeader && isFn(stream5.abort);
    }, "isRequest");
    var destroyer = /* @__PURE__ */ __name(function(stream5, reading, writing, callback) {
      callback = once(callback);
      var closed = false;
      stream5.on("close", function() {
        closed = true;
      });
      eos(stream5, { readable: reading, writable: writing }, function(err2) {
        if (err2) return callback(err2);
        closed = true;
        callback();
      });
      var destroyed = false;
      return function(err2) {
        if (closed) return;
        if (destroyed) return;
        destroyed = true;
        if (isFS(stream5)) return stream5.close(noop11);
        if (isRequest4(stream5)) return stream5.abort();
        if (isFn(stream5.destroy)) return stream5.destroy();
        callback(err2 || 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] || noop11) && streams.pop() || noop11;
      if (Array.isArray(streams[0])) streams = streams[0];
      if (streams.length < 2) throw new Error("pump requires two streams per minimum");
      var error40;
      var destroys = streams.map(function(stream5, i4) {
        var reading = i4 < streams.length - 1;
        var writing = i4 > 0;
        return destroyer(stream5, reading, writing, function(err2) {
          if (!error40) error40 = err2;
          if (err2) destroys.forEach(call);
          if (reading) return;
          destroys.forEach(call);
          callback(error40);
        });
      });
      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 isBuffer2 = encoding === "buffer";
      let objectMode = false;
      if (array2) {
        objectMode = !(encoding || isBuffer2);
      } else {
        encoding = encoding || "utf8";
      }
      if (isBuffer2) {
        encoding = null;
      }
      const stream5 = new PassThroughStream({ objectMode });
      if (encoding) {
        stream5.setEncoding(encoding);
      }
      let length = 0;
      const chunks = [];
      stream5.on("data", (chunk) => {
        chunks.push(chunk);
        if (objectMode) {
          length = chunks.length;
        } else {
          length += chunk.length;
        }
      });
      stream5.getBufferedValue = () => {
        if (array2) {
          return chunks;
        }
        return isBuffer2 ? Buffer.concat(chunks, length) : chunks.join("");
      };
      stream5.getBufferedLength = () => length;
      return stream5;
    };
  }
});

// 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 stream5;
      await new Promise((resolve42, reject) => {
        const rejectPromise = /* @__PURE__ */ __name((error40) => {
          if (error40 && stream5.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
            error40.bufferedData = stream5.getBufferedValue();
          }
          reject(error40);
        }, "rejectPromise");
        stream5 = pump3(inputStream, bufferStream(options2), (error40) => {
          if (error40) {
            rejectPromise(error40);
            return;
          }
          resolve42();
        });
        stream5.on("data", () => {
          if (stream5.getBufferedLength() > maxBuffer) {
            rejectPromise(new MaxBufferError());
          }
        });
      });
      return stream5.getBufferedValue();
    }
    __name(getStream, "getStream");
    module2.exports = getStream;
    module2.exports.default = getStream;
    module2.exports.buffer = (stream5, options2) => getStream(stream5, { ...options2, encoding: "buffer" });
    module2.exports.array = (stream5, options2) => getStream(stream5, { ...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(err2) {
        if (called) throw new Error("callback called twice");
        called = true;
        self2.error = self2.error || err2;
        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 fs142 = __require("fs");
    var util5 = __require("util");
    var stream5 = __require("stream");
    var Readable8 = stream5.Readable;
    var Writable4 = stream5.Writable;
    var PassThrough8 = stream5.PassThrough;
    var Pend = require_pend();
    var EventEmitter16 = __require("events").EventEmitter;
    exports2.createFromBuffer = createFromBuffer;
    exports2.createFromFd = createFromFd;
    exports2.BufferSlicer = BufferSlicer;
    exports2.FdSlicer = FdSlicer;
    util5.inherits(FdSlicer, EventEmitter16);
    function FdSlicer(fd, options2) {
      options2 = options2 || {};
      EventEmitter16.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) {
        fs142.read(self2.fd, buffer, offset, length, position, function(err2, bytesRead, buffer2) {
          cb();
          callback(err2, bytesRead, buffer2);
        });
      });
    };
    FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
      var self2 = this;
      self2.pend.go(function(cb) {
        fs142.write(self2.fd, buffer, offset, length, position, function(err2, written, buffer2) {
          cb();
          callback(err2, 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) {
        fs142.close(self2.fd, onCloseDone);
      }
      function onCloseDone(err2) {
        if (err2) {
          self2.emit("error", err2);
        } else {
          self2.emit("close");
        }
      }
      __name(onCloseDone, "onCloseDone");
    };
    util5.inherits(ReadStream2, Readable8);
    function ReadStream2(context2, options2) {
      options2 = options2 || {};
      Readable8.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);
        fs142.read(self2.context.fd, buffer, 0, toRead, self2.pos, function(err2, bytesRead) {
          if (err2) {
            self2.destroy(err2);
          } 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(err2) {
      if (this.destroyed) return;
      err2 = err2 || new Error("stream destroyed");
      this.destroyed = true;
      this.emit("error", err2);
      this.context.unref();
    };
    util5.inherits(WriteStream2, Writable4);
    function WriteStream2(context2, options2) {
      options2 = options2 || {};
      Writable4.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 err2 = new Error("maximum file length exceeded");
        err2.code = "ETOOBIG";
        self2.destroy();
        callback(err2);
        return;
      }
      self2.context.pend.go(function(cb) {
        if (self2.destroyed) return cb();
        fs142.write(self2.context.fd, buffer, 0, buffer.length, self2.pos, function(err3, bytes) {
          if (err3) {
            self2.destroy();
            cb();
            callback(err3);
          } 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();
    };
    util5.inherits(BufferSlicer, EventEmitter16);
    function BufferSlicer(buffer, options2) {
      EventEmitter16.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 readStream2 = new PassThrough8(options2);
      readStream2.destroyed = false;
      readStream2.start = options2.start || 0;
      readStream2.endOffset = options2.end;
      readStream2.pos = readStream2.endOffset || this.buffer.length;
      var entireSlice = this.buffer.slice(readStream2.start, readStream2.pos);
      var offset = 0;
      while (true) {
        var nextOffset = offset + this.maxChunkSize;
        if (nextOffset >= entireSlice.length) {
          if (offset < entireSlice.length) {
            readStream2.write(entireSlice.slice(offset, entireSlice.length));
          }
          break;
        }
        readStream2.write(entireSlice.slice(offset, nextOffset));
        offset = nextOffset;
      }
      readStream2.end();
      readStream2.destroy = function() {
        readStream2.destroyed = true;
      };
      return readStream2;
    };
    BufferSlicer.prototype.createWriteStream = function(options2) {
      var bufferSlicer = this;
      options2 = options2 || {};
      var writeStream = new Writable4(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 err2 = new Error("maximum file length exceeded");
          err2.code = "ETOOBIG";
          writeStream.destroyed = true;
          callback(err2);
          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 fs142 = __require("fs");
    var zlib5 = __require("zlib");
    var fd_slicer = require_fd_slicer();
    var crc32 = require_buffer_crc32();
    var util5 = __require("util");
    var EventEmitter16 = __require("events").EventEmitter;
    var Transform2 = __require("stream").Transform;
    var PassThrough8 = __require("stream").PassThrough;
    var Writable4 = __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(path150, 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;
      fs142.open(path150, "r", function(err2, fd) {
        if (err2) return callback(err2);
        fromFd(fd, options2, function(err3, zipfile) {
          if (err3) fs142.close(fd, defaultCallback);
          callback(err3, 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;
      fs142.fstat(fd, function(err2, stats) {
        if (err2) return callback(err2);
        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(err2) {
        if (err2) return callback(err2);
        for (var i4 = bufferSize - eocdrWithoutCommentSize; i4 >= 0; i4 -= 1) {
          if (buffer.readUInt32LE(i4) !== 101010256) continue;
          var eocdrBuffer = buffer.slice(i4);
          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 + i4 - zip64EocdlBuffer.length;
          readAndAssertNoEof(reader, zip64EocdlBuffer, 0, zip64EocdlBuffer.length, zip64EocdlOffset, function(err3) {
            if (err3) return callback(err3);
            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(err4) {
              if (err4) return callback(err4);
              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");
    util5.inherits(ZipFile, EventEmitter16);
    function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
      var self2 = this;
      EventEmitter16.call(self2);
      self2.reader = reader;
      self2.reader.on("error", function(err2) {
        emitError(self2, err2);
      });
      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, err2) {
      if (self2.autoClose) self2.close();
      emitError(self2, err2);
    }
    __name(emitErrorAndAutoClose, "emitErrorAndAutoClose");
    function emitError(self2, err2) {
      if (self2.emittedError) return;
      self2.emittedError = true;
      self2.emit("error", err2);
    }
    __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(err2) {
        if (err2) return emitErrorAndAutoClose(self2, err2);
        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(err3) {
          if (err3) return emitErrorAndAutoClose(self2, err3);
          if (self2.emittedError) return;
          var isUtf82 = (entry.generalPurposeBitFlag & 2048) !== 0;
          entry.fileName = self2.decodeStrings ? decodeBuffer(buffer, 0, entry.fileNameLength, isUtf82) : buffer.slice(0, entry.fileNameLength);
          var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
          var extraFieldBuffer = buffer.slice(entry.fileNameLength, fileCommentStart);
          entry.extraFields = [];
          var i4 = 0;
          while (i4 < extraFieldBuffer.length - 3) {
            var headerId = extraFieldBuffer.readUInt16LE(i4 + 0);
            var dataSize = extraFieldBuffer.readUInt16LE(i4 + 2);
            var dataStart = i4 + 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
            });
            i4 = dataEnd;
          }
          entry.fileComment = self2.decodeStrings ? decodeBuffer(buffer, fileCommentStart, fileCommentStart + entry.fileCommentLength, isUtf82) : 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 i4 = 0; i4 < entry.extraFields.length; i4++) {
              var extraField = entry.extraFields[i4];
              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 i4 = 0; i4 < entry.extraFields.length; i4++) {
              var extraField = entry.extraFields[i4];
              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(err2) {
        try {
          if (err2) return callback(err2);
          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 readStream2 = self2.reader.createReadStream({
            start: fileDataStart + relativeStart,
            end: fileDataStart + relativeEnd
          });
          var endpointStream = readStream2;
          if (decompress) {
            var destroyed = false;
            var inflateFilter = zlib5.createInflateRaw();
            readStream2.on("error", function(err3) {
              setImmediate(function() {
                if (!destroyed) inflateFilter.emit("error", err3);
              });
            });
            readStream2.pipe(inflateFilter);
            if (self2.validateEntrySizes) {
              endpointStream = new AssertByteCountStream(entry.uncompressedSize);
              inflateFilter.on("error", function(err3) {
                setImmediate(function() {
                  if (!destroyed) endpointStream.emit("error", err3);
                });
              });
              inflateFilter.pipe(endpointStream);
            } else {
              endpointStream = inflateFilter;
            }
            endpointStream.destroy = function() {
              destroyed = true;
              if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
              readStream2.unpipe(inflateFilter);
              readStream2.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(date5, time3) {
      var day = date5 & 31;
      var month = (date5 >> 5 & 15) - 1;
      var year = (date5 >> 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(err2, bytesRead) {
        if (err2) return callback(err2);
        if (bytesRead < length) {
          return callback(new Error("unexpected EOF"));
        }
        callback();
      });
    }
    __name(readAndAssertNoEof, "readAndAssertNoEof");
    util5.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();
    };
    util5.inherits(RandomAccessReader, EventEmitter16);
    function RandomAccessReader() {
      EventEmitter16.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(err2) {
        if (err2) return self2.emit("error", err2);
        self2.emit("close");
      }
      __name(onCloseDone, "onCloseDone");
    };
    RandomAccessReader.prototype.createReadStream = function(options2) {
      var start2 = options2.start;
      var end = options2.end;
      if (start2 === end) {
        var emptyStream = new PassThrough8();
        setImmediate(function() {
          emptyStream.end();
        });
        return emptyStream;
      }
      var stream5 = this._readStreamForRange(start2, end);
      var destroyed = false;
      var refUnrefFilter = new RefUnrefFilter(this);
      stream5.on("error", function(err2) {
        setImmediate(function() {
          if (!destroyed) refUnrefFilter.emit("error", err2);
        });
      });
      refUnrefFilter.destroy = function() {
        stream5.unpipe(refUnrefFilter);
        refUnrefFilter.unref();
        stream5.destroy();
      };
      var byteCounter = new AssertByteCountStream(end - start2);
      refUnrefFilter.on("error", function(err2) {
        setImmediate(function() {
          if (!destroyed) byteCounter.emit("error", err2);
        });
      });
      byteCounter.destroy = function() {
        destroyed = true;
        refUnrefFilter.unpipe(byteCounter);
        refUnrefFilter.destroy();
      };
      return stream5.pipe(refUnrefFilter).pipe(byteCounter);
    };
    RandomAccessReader.prototype._readStreamForRange = function(start2, end) {
      throw new Error("not implemented");
    };
    RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
      var readStream2 = this.createReadStream({ start: position, end: position + length });
      var writeStream = new Writable4();
      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);
      readStream2.on("error", function(error40) {
        callback(error40);
      });
      readStream2.pipe(writeStream);
    };
    RandomAccessReader.prototype.close = function(callback) {
      setImmediate(callback);
    };
    util5.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, start2, end, isUtf82) {
      if (isUtf82) {
        return buffer.toString("utf8", start2, end);
      } else {
        var result = "";
        for (var i4 = start2; i4 < end; i4++) {
          result += cp437[buffer[i4]];
        }
        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(err2) {
      if (err2) throw err2;
    }
    __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: createWriteStream7, promises: fs142 } = __require("fs");
    var getStream = require_get_stream();
    var path150 = __require("path");
    var { promisify: promisify13 } = __require("util");
    var stream5 = __require("stream");
    var yauzl = require_yauzl();
    var openZip = promisify13(yauzl.open);
    var pipeline3 = promisify13(stream5.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((resolve42, reject) => {
          this.zipfile.on("error", (err2) => {
            this.canceled = true;
            reject(err2);
          });
          this.zipfile.readEntry();
          this.zipfile.on("close", () => {
            if (!this.canceled) {
              debug3("zip extraction complete");
              resolve42();
            }
          });
          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 = path150.dirname(path150.join(this.opts.dir, entry.fileName));
            try {
              await fs142.mkdir(destDir, { recursive: true });
              const canonicalDestDir = await fs142.realpath(destDir);
              const relativeDestDir = path150.relative(this.opts.dir, canonicalDestDir);
              if (relativeDestDir.split(path150.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 (err2) {
              this.canceled = true;
              this.zipfile.close();
              reject(err2);
            }
          });
        });
      }
      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 = path150.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 : path150.dirname(dest);
        const mkdirOptions2 = { recursive: true };
        if (isDir) {
          mkdirOptions2.mode = procMode;
        }
        debug3("mkdir", { dir: destDir, ...mkdirOptions2 });
        await fs142.mkdir(destDir, mkdirOptions2);
        if (isDir) return;
        debug3("opening read stream", dest);
        const readStream2 = await promisify13(this.zipfile.openReadStream.bind(this.zipfile))(entry);
        if (symlink) {
          const link3 = await getStream(readStream2);
          debug3("creating symlink", link3, dest);
          await fs142.symlink(link3, dest);
        } else {
          await pipeline3(readStream2, createWriteStream7(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 (!path150.isAbsolute(opts.dir)) {
        throw new Error("Target directory is expected to be absolute");
      }
      await fs142.mkdir(opts.dir, { recursive: true });
      opts.dir = await fs142.realpath(opts.dir);
      return new Extractor(zipPath, opts).extract();
    };
  }
});

// packages/core/dist/src/extension/npm.js
import * as fs63 from "node:fs";
import * as path59 from "node:path";
import * as os26 from "node:os";
import * as https4 from "node:https";
import * as http5 from "node:http";
function parseNpmPackageSource(source2) {
  const match2 = source2.match(/^(@[^/]+\/[^@]+)(?:@(.+))?$/);
  if (!match2) {
    throw new Error(`Invalid scoped npm package source: ${source2}`);
  }
  return {
    name: match2[1],
    version: match2[2]
  };
}
function isScopedNpmPackage(source2) {
  return /^@[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+(@.+)?$/.test(source2);
}
function resolveNpmRegistry(scope, registryOverride) {
  if (registryOverride) {
    return registryOverride.replace(/\/$/, "");
  }
  const npmrcPaths = [
    path59.join(process.cwd(), ".npmrc"),
    path59.join(os26.homedir(), ".npmrc")
  ];
  let scopedRegistry;
  let defaultRegistry;
  for (const npmrcPath of npmrcPaths) {
    try {
      const content = fs63.readFileSync(npmrcPath, "utf-8");
      const lines = content.split("\n");
      for (const line of lines) {
        const trimmed2 = line.trim();
        const scopeMatch = trimmed2.match(new RegExp(`^${scope.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}:registry\\s*=\\s*(.+)`));
        if (scopeMatch && !scopedRegistry) {
          scopedRegistry = scopeMatch[1].trim().replace(/\/$/, "");
        }
        const defaultMatch = trimmed2.match(/^registry\s*=\s*(.+)/);
        if (defaultMatch && !defaultRegistry) {
          defaultRegistry = defaultMatch[1].trim().replace(/\/$/, "");
        }
      }
    } catch {
    }
  }
  return scopedRegistry || defaultRegistry || "https://registry.npmjs.org";
}
function getNpmAuthToken(registryUrl2) {
  const envToken = process.env["NPM_TOKEN"];
  if (envToken) {
    return envToken;
  }
  const npmrcPaths = [
    path59.join(process.cwd(), ".npmrc"),
    path59.join(os26.homedir(), ".npmrc")
  ];
  const parsed = new URL(registryUrl2);
  const registryPrefixes = [];
  const pathSegments = parsed.pathname.replace(/\/$/, "").split("/").filter(Boolean);
  for (let i4 = pathSegments.length; i4 >= 0; i4--) {
    const prefix = pathSegments.slice(0, i4).join("/");
    registryPrefixes.push(`${parsed.host}${prefix ? `/${prefix}` : ""}`);
  }
  for (const npmrcPath of npmrcPaths) {
    try {
      const content = fs63.readFileSync(npmrcPath, "utf-8");
      const lines = content.split("\n");
      for (const line of lines) {
        const trimmed2 = line.trim();
        const match2 = trimmed2.match(/^\/\/(.+?)\/:_authToken\s*=\s*(.+)/);
        if (match2) {
          const entryPrefix = match2[1].replace(/\/$/, "");
          if (registryPrefixes.includes(entryPrefix)) {
            return match2[2].trim();
          }
        }
      }
    } catch {
    }
  }
  return void 0;
}
function fetchNpmJson(url3, authToken) {
  const headers = {
    Accept: "application/json"
  };
  if (authToken) {
    headers["Authorization"] = `Bearer ${authToken}`;
  }
  const client = url3.startsWith("https://") ? https4 : http5;
  return new Promise((resolve42, reject) => {
    client.get(url3, { headers }, (res) => {
      if (res.statusCode === 301 || res.statusCode === 302) {
        if (res.headers.location) {
          const originalHost = new URL(url3).host;
          const redirectHost = new URL(res.headers.location).host;
          const redirectToken = redirectHost === originalHost ? authToken : void 0;
          fetchNpmJson(res.headers.location, redirectToken).then(resolve42).catch(reject);
          return;
        }
      }
      if (res.statusCode !== 200) {
        return reject(new Error(`npm registry request failed with status ${res.statusCode}: ${url3}`));
      }
      const chunks = [];
      res.on("data", (chunk) => chunks.push(chunk));
      res.on("end", () => {
        try {
          resolve42(JSON.parse(Buffer.concat(chunks).toString()));
        } catch (e4) {
          reject(new Error(`Failed to parse npm registry response: ${e4}`));
        }
      });
    }).on("error", reject);
  });
}
function downloadNpmFile(url3, dest, authToken) {
  const headers = {};
  if (authToken) {
    headers["Authorization"] = `Bearer ${authToken}`;
  }
  const client = url3.startsWith("https://") ? https4 : http5;
  return new Promise((resolve42, reject) => {
    client.get(url3, { headers }, (res) => {
      if (res.statusCode === 301 || res.statusCode === 302) {
        if (res.headers.location) {
          const originalHost = new URL(url3).host;
          const redirectHost = new URL(res.headers.location).host;
          const redirectToken = redirectHost === originalHost ? authToken : void 0;
          downloadNpmFile(res.headers.location, dest, redirectToken).then(resolve42).catch(reject);
          return;
        }
      }
      if (res.statusCode !== 200) {
        return reject(new Error(`Failed to download npm tarball: status ${res.statusCode}`));
      }
      const file2 = fs63.createWriteStream(dest);
      res.pipe(file2);
      file2.on("finish", () => file2.close(resolve42));
    }).on("error", reject);
  });
}
async function downloadFromNpmRegistry(installMetadata, destination) {
  const { name: name4, version: requestedVersion } = parseNpmPackageSource(installMetadata.source);
  const scope = name4.split("/")[0];
  const registryUrl2 = installMetadata.registryUrl || resolveNpmRegistry(scope, void 0);
  installMetadata.registryUrl = registryUrl2;
  const authToken = getNpmAuthToken(registryUrl2);
  const encodedName = name4.replaceAll("/", "%2f");
  const metadataUrl = `${registryUrl2}/${encodedName}`;
  debugLogger66.debug(`Fetching npm package metadata from ${metadataUrl}`);
  const metadata2 = await fetchNpmJson(metadataUrl, authToken);
  let resolvedVersion;
  if (requestedVersion && requestedVersion !== "latest") {
    if (metadata2.versions[requestedVersion]) {
      resolvedVersion = requestedVersion;
    } else if (metadata2["dist-tags"][requestedVersion]) {
      resolvedVersion = metadata2["dist-tags"][requestedVersion];
    } else {
      throw new Error(`Version "${requestedVersion}" not found for package ${name4}`);
    }
  } else {
    resolvedVersion = metadata2["dist-tags"]["latest"];
    if (!resolvedVersion) {
      throw new Error(`No "latest" dist-tag found for package ${name4}`);
    }
  }
  const versionData = metadata2.versions[resolvedVersion];
  if (!versionData) {
    throw new Error(`Version data for "${resolvedVersion}" not found for package ${name4}`);
  }
  const tarballUrl = versionData.dist.tarball;
  debugLogger66.debug(`Downloading ${name4}@${resolvedVersion} from ${tarballUrl}`);
  const registryHost = new URL(registryUrl2).host;
  const tarballHost = new URL(tarballUrl).host;
  const tarballAuthToken = tarballHost === registryHost ? authToken : void 0;
  const tarballPath = path59.join(destination, "package.tgz");
  await downloadNpmFile(tarballUrl, tarballPath, tarballAuthToken);
  await extract({
    file: tarballPath,
    cwd: destination
  });
  const packageDir = path59.join(destination, "package");
  if (fs63.existsSync(packageDir)) {
    const entries = await fs63.promises.readdir(packageDir);
    for (const entry of entries) {
      await fs63.promises.rename(path59.join(packageDir, entry), path59.join(destination, entry));
    }
    await fs63.promises.rmdir(packageDir);
  }
  await fs63.promises.unlink(tarballPath);
  debugLogger66.debug(`Successfully extracted ${name4}@${resolvedVersion} to ${destination}`);
  return {
    version: resolvedVersion,
    type: "npm"
  };
}
async function checkNpmUpdate(installMetadata) {
  try {
    const { name: name4 } = parseNpmPackageSource(installMetadata.source);
    const scope = name4.split("/")[0];
    const registryUrl2 = installMetadata.registryUrl || resolveNpmRegistry(scope, void 0);
    const authToken = getNpmAuthToken(registryUrl2);
    const encodedName = name4.replaceAll("/", "%2f");
    const metadataUrl = `${registryUrl2}/${encodedName}`;
    const metadata2 = await fetchNpmJson(metadataUrl, authToken);
    const { version: requestedVersion } = parseNpmPackageSource(installMetadata.source);
    if (requestedVersion && requestedVersion !== "latest" && !metadata2["dist-tags"][requestedVersion]) {
      return ExtensionUpdateState.UP_TO_DATE;
    }
    const targetTag = requestedVersion && metadata2["dist-tags"][requestedVersion] ? requestedVersion : "latest";
    const targetVersion = metadata2["dist-tags"][targetTag];
    if (!targetVersion) {
      debugLogger66.error(`No "${targetTag}" dist-tag found for package ${name4}`);
      return ExtensionUpdateState.ERROR;
    }
    if (targetVersion !== installMetadata.releaseTag) {
      return ExtensionUpdateState.UPDATE_AVAILABLE;
    }
    return ExtensionUpdateState.UP_TO_DATE;
  } catch (error40) {
    debugLogger66.error(`Failed to check npm update for "${installMetadata.source}": ${error40}`);
    return ExtensionUpdateState.ERROR;
  }
}
var debugLogger66;
var init_npm = __esm({
  "packages/core/dist/src/extension/npm.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm20();
    init_extensionManager();
    init_debugLogger();
    debugLogger66 = createDebugLogger("EXT_NPM");
    __name(parseNpmPackageSource, "parseNpmPackageSource");
    __name(isScopedNpmPackage, "isScopedNpmPackage");
    __name(resolveNpmRegistry, "resolveNpmRegistry");
    __name(getNpmAuthToken, "getNpmAuthToken");
    __name(fetchNpmJson, "fetchNpmJson");
    __name(downloadNpmFile, "downloadNpmFile");
    __name(downloadFromNpmRegistry, "downloadFromNpmRegistry");
    __name(checkNpmUpdate, "checkNpmUpdate");
  }
});

// packages/core/dist/src/extension/github.js
import * as os27 from "node:os";
import * as https5 from "node:https";
import * as fs64 from "node:fs";
import * as path60 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 {
      }
    }
    const symlinkValue = os27.platform() === "win32" ? "false" : "true";
    await git.clone(sourceUrl, "./", [
      "-c",
      `core.symlinks=${symlinkValue}`,
      "--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 (error40) {
    throw new Error(`Failed to clone Git repository from ${installMetadata.source} ${getErrorMessage(error40)}`, {
      cause: error40
    });
  }
}
function parseGitHubRepoForReleases(source2) {
  const parsedUrl = URL.parse(source2, "https://github.com");
  const parts2 = parsedUrl?.pathname.substring(1).split("/");
  if (parts2?.length !== 2 || parsedUrl?.host !== "github.com") {
    throw new Error(`Invalid GitHub repository source: ${source2}. Expected "owner/repo" or a github repo uri.`);
  }
  const owner = parts2[0];
  const repo = parts2[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 url3 = `https://api.github.com/repos/${owner}/${repo}/${endpoint}`;
  return await fetchJson(url3);
}
async function checkForExtensionUpdate(extension, extensionManager) {
  const installMetadata = extension.installMetadata;
  if (installMetadata?.type === "local") {
    let latestConfig;
    try {
      latestConfig = extensionManager.loadExtensionConfig({
        extensionDir: installMetadata.source
      });
    } catch (e4) {
      debugLogger67.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) {
      debugLogger67.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?.type === "npm") {
    return checkNpmUpdate(installMetadata);
  }
  if (!installMetadata || installMetadata.originSource === "Claude" || 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) {
        debugLogger67.error("No git remotes found.");
        return ExtensionUpdateState.ERROR;
      }
      const remoteUrl = remotes[0].refs.fetch;
      if (!remoteUrl) {
        debugLogger67.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() === "") {
        debugLogger67.error(`Git ref ${refToCheck} not found.`);
        return ExtensionUpdateState.ERROR;
      }
      const remoteHash = lsRemoteOutput.split("	")[0];
      const localHash = await git.revparse(["HEAD"]);
      if (!remoteHash) {
        debugLogger67.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) {
        debugLogger67.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 (error40) {
    debugLogger67.error(`Failed to check for updates for extension "${installMetadata.source}": ${getErrorMessage(error40)}`);
    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 = path60.join(destination, path60.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 fs64.promises.readdir(destination, {
      withFileTypes: true
    });
    if (entries.length === 2) {
      const lonelyDir = entries.find((entry) => entry.isDirectory());
      if (lonelyDir) {
        const hasQwenConfig = fs64.existsSync(path60.join(destination, lonelyDir.name, EXTENSIONS_CONFIG_FILENAME));
        const hasGeminiConfig = fs64.existsSync(path60.join(destination, lonelyDir.name, "gemini-extension.json"));
        const hasMarketplaceConfig = fs64.existsSync(path60.join(destination, lonelyDir.name, ".claude-plugin/marketplace.json"));
        const hasClaudePluginConfig = fs64.existsSync(path60.join(destination, lonelyDir.name, ".claude-plugin/plugin.json"));
        if (hasQwenConfig || hasGeminiConfig || hasMarketplaceConfig || hasClaudePluginConfig) {
          const dirPathToExtract = path60.join(destination, lonelyDir.name);
          const extractedDirFiles = await fs64.promises.readdir(dirPathToExtract);
          for (const file2 of extractedDirFiles) {
            await fs64.promises.rename(path60.join(dirPathToExtract, file2), path60.join(destination, file2));
          }
          await fs64.promises.rmdir(dirPathToExtract);
        }
      }
    }
    await fs64.promises.unlink(downloadedAssetPath);
    return {
      tagName: releaseData.tag_name,
      type: "github-release"
    };
  } catch (error40) {
    throw new Error(`Failed to download release from ${installMetadata.source}: ${getErrorMessage(error40)}`);
  }
}
function findReleaseAsset(assets) {
  const platform15 = os27.platform();
  const arch3 = os27.arch();
  const platformArchPrefix = `${platform15}.${arch3}.`;
  const platformPrefix = `${platform15}.`;
  const platformArchAsset = assets.find((asset) => asset.name.toLowerCase().startsWith(platformArchPrefix));
  if (platformArchAsset) {
    return platformArchAsset;
  }
  const platformAsset = assets.find((asset) => asset.name.toLowerCase().startsWith(platformPrefix));
  if (platformAsset) {
    return platformAsset;
  }
  const genericAsset = assets.find((asset) => !asset.name.toLowerCase().includes("darwin") && !asset.name.toLowerCase().includes("linux") && !asset.name.toLowerCase().includes("win32"));
  if (assets.length === 1) {
    return genericAsset;
  }
  return void 0;
}
async function fetchJson(url3) {
  const headers = {
    "User-Agent": "gemini-cli"
  };
  const token2 = getGitHubToken();
  if (token2) {
    headers.Authorization = `token ${token2}`;
  }
  return new Promise((resolve42, reject) => {
    https5.get(url3, { 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();
        resolve42(JSON.parse(data));
      });
    }).on("error", reject);
  });
}
async function downloadFile2(url3, dest) {
  const headers = {
    "User-agent": "gemini-cli"
  };
  const token2 = getGitHubToken();
  if (token2) {
    headers.Authorization = `token ${token2}`;
  }
  return new Promise((resolve42, reject) => {
    https5.get(url3, { headers }, (res) => {
      if (res.statusCode === 302 || res.statusCode === 301) {
        downloadFile2(res.headers.location, dest).then(resolve42).catch(reject);
        return;
      }
      if (res.statusCode !== 200) {
        return reject(new Error(`Request failed with status code ${res.statusCode}`));
      }
      const file2 = fs64.createWriteStream(dest);
      res.pipe(file2);
      file2.on("finish", () => file2.close(resolve42));
    }).on("error", reject);
  });
}
async function extractFile2(file2, dest) {
  if (file2.endsWith(".tar.gz")) {
    await extract({
      file: file2,
      cwd: dest
    });
  } else if (file2.endsWith(".zip")) {
    await (0, import_extract_zip.default)(file2, { dir: dest });
  } else {
    throw new Error(`Unsupported file extension for extraction: ${file2}`);
  }
}
var import_extract_zip, debugLogger67;
var init_github = __esm({
  "packages/core/dist/src/extension/github.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm8();
    init_errors();
    init_variables();
    init_esm20();
    import_extract_zip = __toESM(require_extract_zip(), 1);
    init_debugLogger();
    init_extensionManager();
    init_npm();
    debugLogger67 = 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(path150) {
        return this.asRegex().test(path150);
      }
    };
    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 path61 from "node:path";
import * as os28 from "node:os";
import * as fs65 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 path61.join(_ExtensionStorage.getUserExtensionsDir(), this.extensionName);
      }
      getConfigPath() {
        return path61.join(this.getExtensionDir(), EXTENSIONS_CONFIG_FILENAME);
      }
      getEnvFilePath() {
        return path61.join(this.getExtensionDir(), EXTENSION_SETTINGS_FILENAME);
      }
      static getUserExtensionsDir() {
        const homeDir = os28.homedir();
        if (!homeDir) {
          const tmpDir = os28.tmpdir();
          if (!tmpDir) {
            return "/tmp/.qwen/extensions";
          }
          return path61.join(tmpDir, ".qwen", "extensions");
        }
        const storage = new Storage(homeDir);
        return storage.getExtensionsDir();
      }
      static async createTmpDir() {
        return await fs65.promises.mkdtemp(path61.join(os28.tmpdir(), "qwen-extension"));
      }
    };
  }
});

// node_modules/@iarna/toml/lib/parser.js
var require_parser2 = __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 Parser6 = 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(err2) {
        err2.line = this.line;
        err2.col = this.col;
        err2.pos = this.pos;
        return err2;
      }
      /* istanbul ignore next */
      parseStart() {
        throw new ParserError("Must declare a parseStart method");
      }
    };
    Parser6.END = ParserEND;
    Parser6.Error = ParserError;
    module2.exports = Parser6;
  }
});

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

// 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 date5 = `${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 `${date5}T${time3}`;
      }
    };
    module2.exports = (value) => {
      const date5 = new FloatingDateTime(value);
      if (isNaN(date5)) {
        throw new TypeError("Invalid Datetime");
      } else {
        return date5;
      }
    };
  }
});

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

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

// 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_parser2());
    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 = (err2) => {
      const terr = new TomlError(err2.message);
      terr.code = err2.code;
      terr.wrapped = err2;
      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(Parser6) {
      class TOMLParser extends Parser6 {
        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 === Parser6.END || this.char === CTRL_J || this.char === CTRL_M;
        }
        parseStart() {
          if (this.char === Parser6.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 === Parser6.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 === Parser6.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 === Parser6.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 === Parser6.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 === Parser6.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 === Parser6.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 (err2) {
            throw this.error(TomlError.wrap(err2));
          }
        }
        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 === Parser6.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 === Parser6.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 === Parser6.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(err2, buf) {
      if (err2.pos == null || err2.line == null) return err2;
      let msg = err2.message;
      msg += ` at row ${err2.line + 1}, col ${err2.col + 1}, pos ${err2.pos}:
`;
      if (buf && buf.split) {
        const lines = buf.split(/\n/);
        const lineNumWidth = String(Math.min(lines.length, err2.line + 3)).length;
        let linePadding = " ";
        while (linePadding.length < lineNumWidth) linePadding += " ";
        for (let ii = Math.max(0, err2.line - 1); ii < Math.min(lines.length, err2.line + 2); ++ii) {
          let lineNum = String(ii + 1);
          if (lineNum.length < lineNumWidth) lineNum = " " + lineNum;
          if (err2.line === ii) {
            msg += lineNum + "> " + lines[ii] + "\n";
            msg += linePadding + "  ";
            for (let hh = 0; hh < err2.col; ++hh) {
              msg += " ";
            }
            msg += "^\n";
          } else {
            msg += lineNum + ": " + lines[ii] + "\n";
          }
        }
      }
      err2.message = msg + "\n";
      return err2;
    }
    __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 (err2) {
        throw prettyError(err2, 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((resolve42, reject) => {
        setImmediate(parseAsyncNext, index, blocksize, resolve42, reject);
      });
      function parseAsyncNext(index2, blocksize2, resolve42, reject) {
        if (index2 >= str2.length) {
          try {
            return resolve42(parser6.finish());
          } catch (err2) {
            return reject(prettyError(err2, str2));
          }
        }
        try {
          parser6.parse(str2.slice(index2, index2 + blocksize2));
          setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve42, reject);
        } catch (err2) {
          reject(prettyError(err2, 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 stream5 = __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((resolve42, reject) => {
        let readable;
        let ended = false;
        let errored = false;
        function finish() {
          ended = true;
          if (readable) return;
          try {
            resolve42(parser6.finish());
          } catch (err2) {
            reject(err2);
          }
        }
        __name(finish, "finish");
        function error40(err2) {
          errored = true;
          reject(err2);
        }
        __name(error40, "error");
        stm.once("end", finish);
        stm.once("error", error40);
        readNext();
        function readNext() {
          readable = true;
          let data;
          while ((data = stm.read()) !== null) {
            try {
              parser6.parse(data);
            } catch (err2) {
              return error40(err2);
            }
          }
          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 stream5.Transform({
        objectMode: true,
        transform(chunk, encoding, cb) {
          try {
            parser6.parse(chunk.toString(encoding));
          } catch (err2) {
            this.emit("error", err2);
          }
          cb();
        },
        flush(cb) {
          try {
            this.push(parser6.finish());
          } catch (err2) {
            this.emit("error", err2);
          }
          cb();
        }
      });
    }
    __name(parseTransform, "parseTransform");
  }
});

// node_modules/@iarna/toml/parse.js
var require_parse7 = __commonJS({
  "node_modules/@iarna/toml/parse.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = require_parse_string();
    module2.exports.async = require_parse_async();
    module2.exports.stream = require_parse_stream();
    module2.exports.prettyError = require_parse_pretty_error();
  }
});

// node_modules/@iarna/toml/stringify.js
var require_stringify3 = __commonJS({
  "node_modules/@iarna/toml/stringify.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = 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 isNumber4(type) {
      return type === "float" || type === "integer";
    }
    __name(isNumber4, "isNumber");
    function arrayType2(values) {
      var contentType = tomlType2(values[0]);
      if (values.every((_2) => tomlType2(_2) === contentType)) return contentType;
      if (values.every((_2) => isNumber4(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_parse7();
    exports2.stringify = require_stringify3();
  }
});

// packages/core/dist/src/utils/toml-to-markdown-converter.js
function convertTomlToMarkdown(tomlContent) {
  let parsed;
  try {
    parsed = import_toml.default.parse(tomlContent);
  } catch (error40) {
    throw new Error(`Failed to parse TOML: ${error40 instanceof Error ? error40.message : String(error40)}`);
  }
  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}
`;
  }
}
function isTomlFormat(content) {
  try {
    import_toml.default.parse(content);
    return true;
  } catch {
    return false;
  }
}
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");
    __name(isTomlFormat, "isTomlFormat");
  }
});

// packages/core/dist/src/extension/gemini-converter.js
import * as fs66 from "node:fs";
import * as path62 from "node:path";
function convertGeminiToQwenConfig(extensionDir) {
  const configFilePath2 = path62.join(extensionDir, "gemini-extension.json");
  const configContent = fs66.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 = path62.join(tmpDir, "commands");
    if (fs66.existsSync(commandsDir)) {
      await convertCommandsDirectory(commandsDir);
    }
    const qwenConfigPath = path62.join(tmpDir, "qwen-extension.json");
    fs66.writeFileSync(qwenConfigPath, JSON.stringify(geminiConfig, null, 2), "utf-8");
    return {
      config: geminiConfig,
      convertedDir: tmpDir
    };
  } catch (error40) {
    try {
      fs66.rmSync(tmpDir, { recursive: true, force: true });
    } catch {
    }
    throw error40;
  }
}
async function copyDirectory(source2, destination) {
  if (!fs66.existsSync(destination)) {
    fs66.mkdirSync(destination, { recursive: true });
  }
  const entries = fs66.readdirSync(source2, { withFileTypes: true });
  for (const entry of entries) {
    const sourcePath = path62.join(source2, entry.name);
    const destPath = path62.join(destination, entry.name);
    if (entry.isDirectory()) {
      await copyDirectory(sourcePath, destPath);
    } else if (entry.isSymbolicLink()) {
      try {
        const realPath = fs66.realpathSync(sourcePath);
        const targetStat = fs66.statSync(realPath);
        if (targetStat.isDirectory()) {
          await copyDirectory(realPath, destPath);
        } else if (targetStat.isFile()) {
          fs66.copyFileSync(realPath, destPath);
        }
      } catch {
      }
    } else if (entry.isFile()) {
      fs66.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 = path62.join(commandsDir, relativeFile);
    try {
      const tomlContent = fs66.readFileSync(tomlPath, "utf-8");
      const markdownContent = convertTomlToMarkdown(tomlContent);
      const markdownPath = tomlPath.replace(/\.toml$/, ".md");
      fs66.writeFileSync(markdownPath, markdownContent, "utf-8");
      fs66.unlinkSync(tomlPath);
    } catch (error40) {
      debugLogger68.warn(`Warning: Failed to convert command file ${relativeFile}: ${error40 instanceof Error ? error40.message : String(error40)}`);
    }
  }
}
function isGeminiExtensionConfig(extensionDir) {
  const configFilePath2 = path62.join(extensionDir, "gemini-extension.json");
  if (!fs66.existsSync(configFilePath2)) {
    return false;
  }
  const configContent = fs66.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 debugLogger68;
var init_gemini_converter = __esm({
  "packages/core/dist/src/extension/gemini-converter.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm13();
    init_storage2();
    init_toml_to_markdown_converter();
    init_debugLogger();
    debugLogger68 = 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 fs67 from "node:fs";
import * as path63 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["model"] = claudeAgent.model;
  }
  if (claudeAgent.permissionMode) {
    const claudeToQwenMode = {
      default: "default",
      plan: "plan",
      acceptEdits: "auto-edit",
      dontAsk: "default",
      bypassPermissions: "yolo",
      auto: "auto-edit"
    };
    const mapped = claudeToQwenMode[claudeAgent.permissionMode] ?? claudeAgent.permissionMode;
    qwenAgent["approvalMode"] = mapped;
  }
  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 (!fs67.existsSync(agentsDir)) {
    return;
  }
  const files = await fs67.promises.readdir(agentsDir);
  for (const file2 of files) {
    if (!file2.endsWith(".md"))
      continue;
    const filePath = path63.join(agentsDir, file2);
    try {
      const content = await fs67.promises.readFile(filePath, "utf-8");
      const normalizedContent = normalizeContent(content);
      const frontmatterRegex = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/;
      const match2 = normalizedContent.match(frontmatterRegex);
      if (!match2) {
        continue;
      }
      const [, frontmatterYaml, body2] = match2;
      const frontmatter = parse8(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: body2.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"] || body2.trim();
      const newContent = `---
${newYaml}
---

${systemPrompt}
`;
      await fs67.promises.writeFile(filePath, newContent, "utf-8");
    } catch (error40) {
      debugLogger69.warn(`[Claude Converter] Failed to convert agent file ${filePath}: ${error40 instanceof Error ? error40.message : String(error40)}`);
    }
  }
}
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") {
      debugLogger69.warn(`[Claude Converter] MCP servers path not yet supported: ${claudeConfig.mcpServers}`);
    } else {
      mcpServers = claudeConfig.mcpServers;
    }
  }
  let hooks;
  if (claudeConfig.hooks) {
    if (typeof claudeConfig.hooks === "string") {
    } else {
      hooks = claudeConfig.hooks;
    }
  } else {
    hooks = void 0;
  }
  if (claudeConfig.outputStyles) {
    debugLogger69.warn(`[Claude Converter] Output styles are not yet supported in ${claudeConfig.name}`);
  }
  return {
    name: claudeConfig.name,
    version: claudeConfig.version,
    mcpServers,
    lspServers: claudeConfig.lspServers,
    hooks
    // Assign the properly typed hooks variable
  };
}
async function convertClaudePluginPackage(extensionDir, pluginName) {
  const marketplaceJsonPath = path63.join(extensionDir, ".claude-plugin", "marketplace.json");
  if (!fs67.existsSync(marketplaceJsonPath)) {
    throw new Error(`Marketplace configuration not found at ${marketplaceJsonPath}`);
  }
  const marketplaceContent = fs67.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 = path63.join(extensionDir, `plugin${createHash4("sha256").update(`${extensionDir}/${pluginName}`).digest("hex")}`);
  await fs67.promises.mkdir(pluginDir, { recursive: true });
  const pluginSource = await resolvePluginSource(marketplacePlugin, extensionDir, pluginDir);
  if (!fs67.existsSync(pluginSource)) {
    throw new Error(`Plugin source directory not found: ${pluginSource}`);
  }
  const strict = marketplacePlugin.strict ?? false;
  let mergedConfig;
  const pluginJsonPath = path63.join(pluginSource, ".claude-plugin", "plugin.json");
  if (strict && !fs67.existsSync(pluginJsonPath)) {
    throw new Error(`Strict mode requires plugin.json at ${pluginJsonPath}`);
  }
  if (fs67.existsSync(pluginJsonPath)) {
    const pluginContent = fs67.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 = path63.isAbsolute(mergedConfig.mcpServers) ? mergedConfig.mcpServers : path63.join(pluginSource, mergedConfig.mcpServers);
    if (fs67.existsSync(mcpServersPath)) {
      try {
        const mcpContent = fs67.readFileSync(mcpServersPath, "utf-8");
        mergedConfig.mcpServers = JSON.parse(mcpContent);
      } catch (error40) {
        debugLogger69.warn(`Failed to parse MCP servers file ${mcpServersPath}: ${error40 instanceof Error ? error40.message : String(error40)}`);
      }
    }
  }
  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: name4, config: config2 } of resourceConfigs) {
      const folderPath = path63.join(tmpDir, name4);
      const sourceFolderPath = path63.join(pluginSource, name4);
      if (config2) {
        if (fs67.existsSync(folderPath)) {
          fs67.rmSync(folderPath, { recursive: true, force: true });
        }
        await collectResources(config2, pluginSource, folderPath);
      } else if (!fs67.existsSync(sourceFolderPath) && fs67.existsSync(folderPath)) {
        fs67.rmSync(folderPath, { recursive: true, force: true });
      }
    }
    if (mergedConfig.hooks && typeof mergedConfig.hooks === "string") {
      const hooksPath = path63.isAbsolute(mergedConfig.hooks) ? mergedConfig.hooks : path63.join(pluginSource, mergedConfig.hooks);
      if (fs67.existsSync(hooksPath)) {
        try {
          const hooksContent = fs67.readFileSync(hooksPath, "utf-8");
          const parsedHooks = JSON.parse(hooksContent);
          let hooksData;
          if (parsedHooks.hooks && typeof parsedHooks.hooks === "object") {
            hooksData = parsedHooks.hooks;
          } else {
            hooksData = parsedHooks;
          }
          mergedConfig.hooks = substituteHookVariables(hooksData, pluginSource);
        } catch (error40) {
          debugLogger69.warn(`Failed to parse hooks file ${hooksPath}: ${error40 instanceof Error ? error40.message : String(error40)}`);
        }
      }
    }
    const agentsDestDir = path63.join(tmpDir, "agents");
    await convertAgentFiles(agentsDestDir);
    const qwenConfig = convertClaudeToQwenConfig(mergedConfig);
    const qwenConfigPath = path63.join(tmpDir, "qwen-extension.json");
    fs67.writeFileSync(qwenConfigPath, JSON.stringify(qwenConfig, null, 2), "utf-8");
    return {
      config: qwenConfig,
      convertedDir: tmpDir
    };
  } catch (error40) {
    try {
      fs67.rmSync(tmpDir, { recursive: true, force: true });
    } catch {
    }
    throw error40;
  }
}
async function collectResources(resourcePaths, pluginRoot, destDir) {
  const paths = Array.isArray(resourcePaths) ? resourcePaths : [resourcePaths];
  if (!fs67.existsSync(destDir)) {
    fs67.mkdirSync(destDir, { recursive: true });
  }
  const destFolderName = path63.basename(destDir);
  for (const resourcePath of paths) {
    const resolvedPath = path63.isAbsolute(resourcePath) ? resourcePath : path63.join(pluginRoot, resourcePath);
    if (!fs67.existsSync(resolvedPath)) {
      debugLogger69.warn(`Resource path not found: ${resolvedPath}`);
      continue;
    }
    const stat14 = fs67.statSync(resolvedPath);
    if (stat14.isDirectory()) {
      const dirName = path63.basename(resolvedPath);
      const parentDir = path63.dirname(resolvedPath);
      if (dirName === destFolderName && parentDir === pluginRoot) {
        debugLogger69.debug(`Skipping ${resolvedPath} as it's already in the correct location`);
        continue;
      }
      const finalDestDir = path63.join(destDir, dirName);
      const files = await glob("**/*", {
        cwd: resolvedPath,
        nodir: true,
        dot: false
      });
      for (const file2 of files) {
        const srcFile = path63.join(resolvedPath, file2);
        const destFile = path63.join(finalDestDir, file2);
        try {
          const fileStat = fs67.statSync(srcFile);
          if (!fileStat.isFile()) {
            debugLogger69.debug(`Skipping non-regular file: ${srcFile}`);
            continue;
          }
        } catch {
          debugLogger69.debug(`Failed to stat file, skipping: ${srcFile}`);
          continue;
        }
        const destFileDir = path63.dirname(destFile);
        if (!fs67.existsSync(destFileDir)) {
          fs67.mkdirSync(destFileDir, { recursive: true });
        }
        fs67.copyFileSync(srcFile, destFile);
      }
    } else {
      const relativePath = path63.relative(pluginRoot, resolvedPath);
      const segments = relativePath.split(path63.sep);
      if (segments.length > 0 && segments[0] === destFolderName) {
        debugLogger69.debug(`Skipping ${resolvedPath} as it's already in ${destFolderName}/`);
        continue;
      }
      const fileName = path63.basename(resolvedPath);
      const destFile = path63.join(destDir, fileName);
      fs67.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;
}
function isClaudePluginConfig(extensionDir, marketplace) {
  const marketplaceConfigFilePath = path63.join(extensionDir, ".claude-plugin/marketplace.json");
  if (!fs67.existsSync(marketplaceConfigFilePath)) {
    return false;
  }
  const marketplaceConfigContent = fs67.readFileSync(marketplaceConfigFilePath, "utf-8");
  const marketplaceConfig = JSON.parse(marketplaceConfigContent);
  if (typeof marketplaceConfig !== "object" || marketplaceConfig === null) {
    return false;
  }
  const marketplaceConfigObj = marketplaceConfig;
  if (typeof marketplaceConfigObj["name"] !== "string" || typeof marketplaceConfigObj["owner"] !== "object") {
    return false;
  }
  if (!Array.isArray(marketplaceConfigObj["plugins"])) {
    return false;
  }
  const marketplacePluginObj = marketplaceConfigObj["plugins"].find((plugin4) => plugin4.name === marketplace.pluginName);
  if (!marketplacePluginObj)
    return false;
  return true;
}
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 = path63.join(pluginRoot, source2);
    if (!fs67.existsSync(sourcePath)) {
      throw new Error(`Plugin source not found at ${sourcePath}`);
    }
    if (path63.resolve(sourcePath) === path63.resolve(marketplaceDir)) {
      return marketplaceDir;
    }
    await fs67.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 debugLogger69, CLAUDE_TOOLS_MAPPING, claudeBuildInToolsTransform;
var init_claude_converter = __esm({
  "packages/core/dist/src/extension/claude-converter.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm13();
    init_storage2();
    init_github();
    init_gemini_converter();
    init_yaml_parser();
    init_debugLogger();
    init_textUtils();
    init_variables();
    debugLogger69 = createDebugLogger("CLAUDE_CONVERTER");
    CLAUDE_TOOLS_MAPPING = {
      AskUserQuestion: "AskUserQuestion",
      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: "None",
      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(isClaudePluginConfig, "isClaudePluginConfig");
    __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 fs142 = __require("fs");
    var path150 = __require("path");
    var os59 = __require("os");
    var crypto18 = __require("crypto");
    var packageJson4 = require_package5();
    var version2 = packageJson4.version;
    var TIPS = [
      "\u{1F510} encrypt with dotenvx: https://dotenvx.com",
      "\u{1F510} prevent committing .env to code: https://dotenvx.com/precommit",
      "\u{1F510} prevent building .env in docker: https://dotenvx.com/prebuild",
      "\u{1F6E0}\uFE0F  run anywhere with `dotenvx run -- yourcommand`",
      "\u2699\uFE0F  specify custom .env file path with { path: '/custom/path/.env' }",
      "\u2699\uFE0F  enable debug logging with { debug: true }",
      "\u2699\uFE0F  override existing env vars with { override: true }",
      "\u2699\uFE0F  suppress all logs with { quiet: true }",
      "\u2699\uFE0F  write to custom object with { processEnv: myObject }",
      "\u2699\uFE0F  load multiple .env files with { path: ['.env.local', '.env'] }"
    ];
    function _getRandomTip() {
      return TIPS[Math.floor(Math.random() * TIPS.length)];
    }
    __name(_getRandomTip, "_getRandomTip");
    function supportsAnsi() {
      return process.stdout.isTTY;
    }
    __name(supportsAnsi, "supportsAnsi");
    function dim(text) {
      return supportsAnsi() ? `\x1B[2m${text}\x1B[0m` : text;
    }
    __name(dim, "dim");
    var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
    function parse17(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(parse17, "parse");
    function _parseVault(options2) {
      options2 = options2 || {};
      const vaultPath = _vaultPath(options2);
      options2.path = vaultPath;
      const result = DotenvModule.configDotenv(options2);
      if (!result.parsed) {
        const err2 = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
        err2.code = "MISSING_DATA";
        throw err2;
      }
      const keys = _dotenvKey(options2).split(",");
      const length = keys.length;
      let decrypted;
      for (let i4 = 0; i4 < length; i4++) {
        try {
          const key = keys[i4].trim();
          const attrs = _instructions(result, key);
          decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
          break;
        } catch (error40) {
          if (i4 + 1 >= length) {
            throw error40;
          }
        }
      }
      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 (error40) {
        if (error40.code === "ERR_INVALID_URL") {
          const err2 = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
          err2.code = "INVALID_DOTENV_KEY";
          throw err2;
        }
        throw error40;
      }
      const key = uri.password;
      if (!key) {
        const err2 = new Error("INVALID_DOTENV_KEY: Missing key part");
        err2.code = "INVALID_DOTENV_KEY";
        throw err2;
      }
      const environment = uri.searchParams.get("environment");
      if (!environment) {
        const err2 = new Error("INVALID_DOTENV_KEY: Missing environment part");
        err2.code = "INVALID_DOTENV_KEY";
        throw err2;
      }
      const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
      const ciphertext = result.parsed[environmentKey];
      if (!ciphertext) {
        const err2 = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
        err2.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
        throw err2;
      }
      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 (fs142.existsSync(filepath)) {
              possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
            }
          }
        } else {
          possibleVaultPath = options2.path.endsWith(".vault") ? options2.path : `${options2.path}.vault`;
        }
      } else {
        possibleVaultPath = path150.resolve(process.cwd(), ".env.vault");
      }
      if (fs142.existsSync(possibleVaultPath)) {
        return possibleVaultPath;
      }
      return null;
    }
    __name(_vaultPath, "_vaultPath");
    function _resolveHome(envPath) {
      return envPath[0] === "~" ? path150.join(os59.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 = path150.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 path151 of optionPaths) {
        try {
          const parsed = DotenvModule.parse(fs142.readFileSync(path151, { encoding }));
          DotenvModule.populate(parsedAll, parsed, options2);
        } catch (e4) {
          if (debug3) {
            _debug(`Failed to load ${path151} ${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 relative14 = path150.relative(process.cwd(), filePath);
            shortPaths.push(relative14);
          } 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 = crypto18.createDecipheriv("aes-256-gcm", key, nonce);
        aesgcm.setAuthTag(authTag);
        return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
      } catch (error40) {
        const isRange = error40 instanceof RangeError;
        const invalidKeyLength = error40.message === "Invalid key length";
        const decryptionFailed = error40.message === "Unsupported state or unable to authenticate data";
        if (isRange || invalidKeyLength) {
          const err2 = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
          err2.code = "INVALID_DOTENV_KEY";
          throw err2;
        } else if (decryptionFailed) {
          const err2 = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
          err2.code = "DECRYPTION_FAILED";
          throw err2;
        } else {
          throw error40;
        }
      }
    }
    __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 err2 = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
        err2.code = "OBJECT_REQUIRED";
        throw err2;
      }
      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: parse17,
      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: init2(0, 0),
      bold: init2(1, 22),
      dim: init2(2, 22),
      italic: init2(3, 23),
      underline: init2(4, 24),
      inverse: init2(7, 27),
      hidden: init2(8, 28),
      strikethrough: init2(9, 29),
      // colors
      black: init2(30, 39),
      red: init2(31, 39),
      green: init2(32, 39),
      yellow: init2(33, 39),
      blue: init2(34, 39),
      magenta: init2(35, 39),
      cyan: init2(36, 39),
      white: init2(37, 39),
      gray: init2(90, 39),
      grey: init2(90, 39),
      // background colors
      bgBlack: init2(40, 49),
      bgRed: init2(41, 49),
      bgGreen: init2(42, 49),
      bgYellow: init2(43, 49),
      bgBlue: init2(44, 49),
      bgMagenta: init2(45, 49),
      bgCyan: init2(46, 49),
      bgWhite: init2(47, 49)
    };
    function run2(arr, str2) {
      let i4 = 0, tmp, beg = "", end = "";
      for (; i4 < arr.length; i4++) {
        tmp = arr[i4];
        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(run2, "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 init2(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 ? run2(this.keys, txt + "") : txt + "";
        }
        return txt === void 0 ? chain2([open4], [blk]) : $2.enabled ? run2([blk], txt + "") : txt + "";
      };
    }
    __name(init2, "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 ESC6 = "\x1B";
    var CSI = `${ESC6}[`;
    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: `${ESC6}7`,
      restore: `${ESC6}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 i4 = 0; i4 < count; i4++)
          clear += this.line + (i4 < 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 it3 = typeof Symbol !== "undefined" && o3[Symbol.iterator] || o3["@@iterator"];
      if (!it3) {
        if (Array.isArray(o3) || (it3 = _unsupportedIterableToArray2(o3)) || allowArrayLike && o3 && typeof o3.length === "number") {
          if (it3) o3 = it3;
          var i4 = 0;
          var F4 = /* @__PURE__ */ __name(function F5() {
          }, "F");
          return { s: F4, n: /* @__PURE__ */ __name(function n3() {
            if (i4 >= o3.length) return { done: true };
            return { done: false, value: o3[i4++] };
          }, "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, err2;
      return { s: /* @__PURE__ */ __name(function s5() {
        it3 = it3.call(o3);
      }, "s"), n: /* @__PURE__ */ __name(function n3() {
        var step = it3.next();
        normalCompletion = step.done;
        return step;
      }, "n"), e: /* @__PURE__ */ __name(function e4(_e2) {
        didErr = true;
        err2 = _e2;
      }, "e"), f: /* @__PURE__ */ __name(function f5() {
        try {
          if (!normalCompletion && it3.return != null) it3.return();
        } finally {
          if (didErr) throw err2;
        }
      }, "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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) arr2[i4] = arr[i4];
      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 (err2) {
        _iterator.e(err2);
      } 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 symbol2 = /* @__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: symbol2,
      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 EventEmitter16 = __require("events");
    var _require22 = require_src37();
    var beep2 = _require22.beep;
    var cursor = _require22.cursor;
    var color = require_kleur();
    var Prompt = class extends EventEmitter16 {
      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, resolve42, reject, _next, _throw, key, arg) {
      try {
        var info2 = gen[key](arg);
        var value = info2.value;
      } catch (error40) {
        reject(error40);
        return;
      }
      if (info2.done) {
        resolve42(value);
      } else {
        Promise.resolve(value).then(_next, _throw);
      }
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(fn) {
      return function() {
        var self2 = this, args2 = arguments;
        return new Promise(function(resolve42, reject) {
          var gen = fn.apply(self2, args2);
          function _next(value) {
            asyncGeneratorStep(gen, resolve42, reject, _next, _throw, "next", value);
          }
          __name(_next, "_next");
          function _throw(err2) {
            asyncGeneratorStep(gen, resolve42, reject, _next, _throw, "throw", err2);
          }
          __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, i4) => a2 + `
${i4 ? " " : 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 i4 = startIndex; i4 < endIndex; i4++) {
            let title, prefix, desc2 = "", v2 = this.choices[i4];
            if (i4 === startIndex && startIndex > 0) {
              prefix = figures.arrowUp;
            } else if (i4 === endIndex - 1 && endIndex < this.choices.length) {
              prefix = figures.arrowDown;
            } else {
              prefix = " ";
            }
            if (v2.disabled) {
              title = this.cursor === i4 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
              prefix = (this.cursor === i4 ? color.bold().gray(figures.pointer) + " " : "  ") + prefix;
            } else {
              title = this.cursor === i4 ? color.cyan().underline(v2.title) : v2.title;
              prefix = (this.cursor === i4 ? color.cyan(figures.pointer) + " " : "  ") + prefix;
              if (v2.description && this.cursor === i4) {
                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: date5,
        parts: parts2,
        locales
      }) {
        this.token = token2;
        this.date = date5 || /* @__PURE__ */ new Date();
        this.parts = parts2 || [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 parts2 = [].concat(this.parts).reverse();
        const currentIdx = parts2.indexOf(this);
        return parts2.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 date5 = this.date.getDate();
        let day = this.date.getDay();
        return this.token === "DD" ? String(date5).padStart(2, "0") : this.token === "Do" ? date5 + pos2(date5) : this.token === "d" ? day + 1 : this.token === "ddd" ? this.locales.weekdaysShort[day] : this.token === "dddd" ? this.locales.weekdays[day] : date5;
      }
    };
    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, resolve42, reject, _next, _throw, key, arg) {
      try {
        var info2 = gen[key](arg);
        var value = info2.value;
      } catch (error40) {
        reject(error40);
        return;
      }
      if (info2.done) {
        resolve42(value);
      } else {
        Promise.resolve(value).then(_next, _throw);
      }
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(fn) {
      return function() {
        var self2 = this, args2 = arguments;
        return new Promise(function(resolve42, reject) {
          var gen = fn.apply(self2, args2);
          function _next(value) {
            asyncGeneratorStep(gen, resolve42, reject, _next, _throw, "next", value);
          }
          __name(_next, "_next");
          function _throw(err2) {
            asyncGeneratorStep(gen, resolve42, reject, _next, _throw, "throw", err2);
          }
          __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(date5) {
        if (date5) this._date.setTime(date5.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 parts2 = this.parts.reduce((arr, i4) => {
          if (typeof i4 === "string" && typeof arr[arr.length - 1] === "string") arr[arr.length - 1] += i4;
          else arr.push(i4);
          return arr;
        }, []);
        this.parts.splice(0);
        this.parts.push(...parts2);
        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, i4) => a2 + `
${i4 ? ` ` : 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, resolve42, reject, _next, _throw, key, arg) {
      try {
        var info2 = gen[key](arg);
        var value = info2.value;
      } catch (error40) {
        reject(error40);
        return;
      }
      if (info2.done) {
        resolve42(value);
      } else {
        Promise.resolve(value).then(_next, _throw);
      }
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(fn) {
      return function() {
        var self2 = this, args2 = arguments;
        return new Promise(function(resolve42, reject) {
          var gen = fn.apply(self2, args2);
          function _next(value) {
            asyncGeneratorStep(gen, resolve42, reject, _next, _throw, "next", value);
          }
          __name(_next, "_next");
          function _throw(err2) {
            asyncGeneratorStep(gen, resolve42, reject, _next, _throw, "throw", err2);
          }
          __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 isNumber4 = /[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 || isNumber4.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, i4) => a2 + `
${i4 ? ` ` : 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, i4, arrowIndicator) {
        const prefix = (v2.selected ? color.green(figures.radioOn) : figures.radioOff) + " " + arrowIndicator + " ";
        let title, desc2;
        if (v2.disabled) {
          title = cursor2 === i4 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
        } else {
          title = cursor2 === i4 ? color.cyan().underline(v2.title) : v2.title;
          if (cursor2 === i4 && 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 i4 = startIndex; i4 < endIndex; i4++) {
          if (i4 === startIndex && startIndex > 0) {
            prefix = figures.arrowUp;
          } else if (i4 === endIndex - 1 && endIndex < options2.length) {
            prefix = figures.arrowDown;
          } else {
            prefix = " ";
          }
          styledOptions.push(this.renderOption(this.cursor, options2[i4], i4, 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, resolve42, reject, _next, _throw, key, arg) {
      try {
        var info2 = gen[key](arg);
        var value = info2.value;
      } catch (error40) {
        reject(error40);
        return;
      }
      if (info2.done) {
        resolve42(value);
      } else {
        Promise.resolve(value).then(_next, _throw);
      }
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(fn) {
      return function() {
        var self2 = this, args2 = arguments;
        return new Promise(function(resolve42, reject) {
          var gen = fn.apply(self2, args2);
          function _next(value) {
            asyncGeneratorStep(gen, resolve42, reject, _next, _throw, "next", value);
          }
          __name(_next, "_next");
          function _throw(err2) {
            asyncGeneratorStep(gen, resolve42, reject, _next, _throw, "throw", err2);
          }
          __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, i4) => arr[i4] && (arr[i4].value || arr[i4].title || arr[i4]), "getVal");
    var getTitle = /* @__PURE__ */ __name((arr, i4) => arr[i4] && (arr[i4].title || arr[i4].value || arr[i4]), "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(i4) {
        this.select = i4;
        if (this.suggestions.length > 0) this.value = getVal(this.suggestions, i4);
        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, i4, arr) => ({
            title: getTitle(arr, i4),
            value: getVal(arr, i4),
            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, i4) => this.renderOption(item, this.select === i4 + startIndex, i4 === 0 && startIndex > 0, i4 + 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, i4) {
        let title;
        if (v2.disabled) title = cursor2 === i4 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
        else title = cursor2 === i4 ? 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 noop11 = /* @__PURE__ */ __name((v2) => v2, "noop");
    function toPrompt(type, args2, opts = {}) {
      return new Promise((res, rej) => {
        const p2 = new el[type](args2);
        const onAbort = opts.onAbort || noop11;
        const onSubmit = opts.onSubmit || noop11;
        const onExit = opts.onExit || noop11;
        p2.on("state", args2.onState || noop11);
        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 = (args2) => toPrompt("TextPrompt", args2);
    $2.password = (args2) => {
      args2.style = "password";
      return $2.text(args2);
    };
    $2.invisible = (args2) => {
      args2.style = "invisible";
      return $2.text(args2);
    };
    $2.number = (args2) => toPrompt("NumberPrompt", args2);
    $2.date = (args2) => toPrompt("DatePrompt", args2);
    $2.confirm = (args2) => toPrompt("ConfirmPrompt", args2);
    $2.list = (args2) => {
      const sep13 = args2.separator || ",";
      return toPrompt("TextPrompt", args2, {
        onSubmit: /* @__PURE__ */ __name((str2) => str2.split(sep13).map((s5) => s5.trim()), "onSubmit")
      });
    };
    $2.toggle = (args2) => toPrompt("TogglePrompt", args2);
    $2.select = (args2) => toPrompt("SelectPrompt", args2);
    $2.multiselect = (args2) => {
      args2.choices = [].concat(args2.choices || []);
      const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
      return toPrompt("MultiselectPrompt", args2, {
        onAbort: toSelected,
        onSubmit: toSelected
      });
    };
    $2.autocompleteMultiselect = (args2) => {
      args2.choices = [].concat(args2.choices || []);
      const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
      return toPrompt("AutocompleteMultiselectPrompt", args2, {
        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 = (args2) => {
      args2.suggest = args2.suggest || byTitle;
      args2.choices = [].concat(args2.choices || []);
      return toPrompt("AutocompletePrompt", args2);
    };
  }
});

// node_modules/prompts/dist/index.js
var require_dist7 = __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 i4 = 1; i4 < arguments.length; i4++) {
        var source2 = arguments[i4] != null ? arguments[i4] : {};
        if (i4 % 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 it3 = typeof Symbol !== "undefined" && o3[Symbol.iterator] || o3["@@iterator"];
      if (!it3) {
        if (Array.isArray(o3) || (it3 = _unsupportedIterableToArray2(o3)) || allowArrayLike && o3 && typeof o3.length === "number") {
          if (it3) o3 = it3;
          var i4 = 0;
          var F4 = /* @__PURE__ */ __name(function F5() {
          }, "F");
          return { s: F4, n: /* @__PURE__ */ __name(function n3() {
            if (i4 >= o3.length) return { done: true };
            return { done: false, value: o3[i4++] };
          }, "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, err2;
      return { s: /* @__PURE__ */ __name(function s5() {
        it3 = it3.call(o3);
      }, "s"), n: /* @__PURE__ */ __name(function n3() {
        var step = it3.next();
        normalCompletion = step.done;
        return step;
      }, "n"), e: /* @__PURE__ */ __name(function e4(_e2) {
        didErr = true;
        err2 = _e2;
      }, "e"), f: /* @__PURE__ */ __name(function f5() {
        try {
          if (!normalCompletion && it3.return != null) it3.return();
        } finally {
          if (didErr) throw err2;
        }
      }, "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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) arr2[i4] = arr[i4];
      return arr2;
    }
    __name(_arrayLikeToArray2, "_arrayLikeToArray");
    function asyncGeneratorStep(gen, resolve42, reject, _next, _throw, key, arg) {
      try {
        var info2 = gen[key](arg);
        var value = info2.value;
      } catch (error40) {
        reject(error40);
        return;
      }
      if (info2.done) {
        resolve42(value);
      } else {
        Promise.resolve(value).then(_next, _throw);
      }
    }
    __name(asyncGeneratorStep, "asyncGeneratorStep");
    function _asyncToGenerator(fn) {
      return function() {
        var self2 = this, args2 = arguments;
        return new Promise(function(resolve42, reject) {
          var gen = fn.apply(self2, args2);
          function _next(value) {
            asyncGeneratorStep(gen, resolve42, reject, _next, _throw, "next", value);
          }
          __name(_next, "_next");
          function _throw(err2) {
            asyncGeneratorStep(gen, resolve42, reject, _next, _throw, "throw", err2);
          }
          __name(_throw, "_throw");
          _next(void 0);
        });
      };
    }
    __name(_asyncToGenerator, "_asyncToGenerator");
    var prompts3 = require_prompts();
    var passOn = ["suggest", "format", "onState", "validate", "onRender", "type"];
    var noop11 = /* @__PURE__ */ __name(() => {
    }, "noop");
    function prompt() {
      return _prompt.apply(this, arguments);
    }
    __name(prompt, "prompt");
    function _prompt() {
      _prompt = _asyncToGenerator(function* (questions = [], {
        onSubmit = noop11,
        onCancel = noop11
      } = {}) {
        const answers = {};
        const override2 = prompt._override || {};
        questions = [].concat(questions);
        let answer, question, quit, name4, 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;
            name4 = _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;
            name4 = _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[name4] = answer;
                continue;
              }
            }
            try {
              answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : yield prompts3[type](question);
              answers[name4] = answer = yield getFormattedAnswer(question, answer, true);
              quit = yield onSubmit(question, answer, answers);
            } catch (err2) {
              quit = !(yield onCancel(question, answers));
            }
            if (quit) return answers;
          }
        } catch (err2) {
          _iterator.e(err2);
        } 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 symbol2 = /* @__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: symbol2,
      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 EventEmitter16 = __require("events");
    var { beep: beep2, cursor } = require_src37();
    var color = require_kleur();
    var Prompt = class extends EventEmitter16 {
      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, i4) => a2 + `
${i4 ? " " : 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 i4 = startIndex; i4 < endIndex; i4++) {
            let title, prefix, desc2 = "", v2 = this.choices[i4];
            if (i4 === startIndex && startIndex > 0) {
              prefix = figures.arrowUp;
            } else if (i4 === endIndex - 1 && endIndex < this.choices.length) {
              prefix = figures.arrowDown;
            } else {
              prefix = " ";
            }
            if (v2.disabled) {
              title = this.cursor === i4 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
              prefix = (this.cursor === i4 ? color.bold().gray(figures.pointer) + " " : "  ") + prefix;
            } else {
              title = this.cursor === i4 ? color.cyan().underline(v2.title) : v2.title;
              prefix = (this.cursor === i4 ? color.cyan(figures.pointer) + " " : "  ") + prefix;
              if (v2.description && this.cursor === i4) {
                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: date5, parts: parts2, locales }) {
        this.token = token2;
        this.date = date5 || /* @__PURE__ */ new Date();
        this.parts = parts2 || [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 parts2 = [].concat(this.parts).reverse();
        const currentIdx = parts2.indexOf(this);
        return parts2.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 date5 = this.date.getDate();
        let day = this.date.getDay();
        return this.token === "DD" ? String(date5).padStart(2, "0") : this.token === "Do" ? date5 + pos2(date5) : this.token === "d" ? day + 1 : this.token === "ddd" ? this.locales.weekdaysShort[day] : this.token === "dddd" ? this.locales.weekdays[day] : date5;
      }
    };
    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(date5) {
        if (date5) this._date.setTime(date5.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 parts2 = this.parts.reduce((arr, i4) => {
          if (typeof i4 === "string" && typeof arr[arr.length - 1] === "string")
            arr[arr.length - 1] += i4;
          else arr.push(i4);
          return arr;
        }, []);
        this.parts.splice(0);
        this.parts.push(...parts2);
        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, i4) => a2 + `
${i4 ? ` ` : 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 isNumber4 = /[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 || isNumber4.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, i4) => a2 + `
${i4 ? ` ` : 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, i4, arrowIndicator) {
        const prefix = (v2.selected ? color.green(figures.radioOn) : figures.radioOff) + " " + arrowIndicator + " ";
        let title, desc2;
        if (v2.disabled) {
          title = cursor2 === i4 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
        } else {
          title = cursor2 === i4 ? color.cyan().underline(v2.title) : v2.title;
          if (cursor2 === i4 && 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 i4 = startIndex; i4 < endIndex; i4++) {
          if (i4 === startIndex && startIndex > 0) {
            prefix = figures.arrowUp;
          } else if (i4 === endIndex - 1 && endIndex < options2.length) {
            prefix = figures.arrowDown;
          } else {
            prefix = " ";
          }
          styledOptions.push(this.renderOption(this.cursor, options2[i4], i4, 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, i4) => arr[i4] && (arr[i4].value || arr[i4].title || arr[i4]), "getVal");
    var getTitle = /* @__PURE__ */ __name((arr, i4) => arr[i4] && (arr[i4].title || arr[i4].value || arr[i4]), "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(i4) {
        this.select = i4;
        if (this.suggestions.length > 0)
          this.value = getVal(this.suggestions, i4);
        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, i4, arr) => ({ title: getTitle(arr, i4), value: getVal(arr, i4), 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, i4) => this.renderOption(
            item,
            this.select === i4 + startIndex,
            i4 === 0 && startIndex > 0,
            i4 + 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, i4) {
        let title;
        if (v2.disabled) title = cursor2 === i4 ? color.gray().underline(v2.title) : color.strikethrough().gray(v2.title);
        else title = cursor2 === i4 ? 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 noop11 = /* @__PURE__ */ __name((v2) => v2, "noop");
    function toPrompt(type, args2, opts = {}) {
      return new Promise((res, rej) => {
        const p2 = new el[type](args2);
        const onAbort = opts.onAbort || noop11;
        const onSubmit = opts.onSubmit || noop11;
        const onExit = opts.onExit || noop11;
        p2.on("state", args2.onState || noop11);
        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 = (args2) => toPrompt("TextPrompt", args2);
    $2.password = (args2) => {
      args2.style = "password";
      return $2.text(args2);
    };
    $2.invisible = (args2) => {
      args2.style = "invisible";
      return $2.text(args2);
    };
    $2.number = (args2) => toPrompt("NumberPrompt", args2);
    $2.date = (args2) => toPrompt("DatePrompt", args2);
    $2.confirm = (args2) => toPrompt("ConfirmPrompt", args2);
    $2.list = (args2) => {
      const sep13 = args2.separator || ",";
      return toPrompt("TextPrompt", args2, {
        onSubmit: /* @__PURE__ */ __name((str2) => str2.split(sep13).map((s5) => s5.trim()), "onSubmit")
      });
    };
    $2.toggle = (args2) => toPrompt("TogglePrompt", args2);
    $2.select = (args2) => toPrompt("SelectPrompt", args2);
    $2.multiselect = (args2) => {
      args2.choices = [].concat(args2.choices || []);
      const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
      return toPrompt("MultiselectPrompt", args2, {
        onAbort: toSelected,
        onSubmit: toSelected
      });
    };
    $2.autocompleteMultiselect = (args2) => {
      args2.choices = [].concat(args2.choices || []);
      const toSelected = /* @__PURE__ */ __name((items) => items.filter((item) => item.selected).map((item) => item.value), "toSelected");
      return toPrompt("AutocompleteMultiselectPrompt", args2, {
        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 = (args2) => {
      args2.suggest = args2.suggest || byTitle;
      args2.choices = [].concat(args2.choices || []);
      return toPrompt("AutocompletePrompt", args2);
    };
  }
});

// node_modules/prompts/lib/index.js
var require_lib5 = __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 noop11 = /* @__PURE__ */ __name(() => {
    }, "noop");
    async function prompt(questions = [], { onSubmit = noop11, onCancel = noop11 } = {}) {
      const answers = {};
      const override2 = prompt._override || {};
      questions = [].concat(questions);
      let answer, question, quit, name4, 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: name4, 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: name4, 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[name4] = answer;
            continue;
          }
        }
        try {
          answer = prompt._injected ? getInjectedAnswer(prompt._injected, question.initial) : await prompts3[type](question);
          answers[name4] = answer = await getFormattedAnswer(question, answer, true);
          quit = await onSubmit(question, answer, answers);
        } catch (err2) {
          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 i4 = 0, src = process.versions.node.split(".").map(Number);
      for (; i4 < tar.length; i4++) {
        if (src[i4] > tar[i4]) return false;
        if (tar[i4] > src[i4]) return true;
      }
      return false;
    }
    __name(isNodeLT, "isNodeLT");
    module2.exports = isNodeLT("8.6.0") ? require_dist7() : require_lib5();
  }
});

// packages/core/dist/src/extension/extensionSettings.js
import * as fs68 from "node:fs/promises";
import * as fsSync2 from "node:fs";
import * as path64 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 fs68.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_prompts5.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 (fsSync2.existsSync(envFilePath)) {
    const envFile = fsSync2.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) {
    debugLogger70.debug(`updateSetting: Extension "${extensionName}" has no settings`);
    return;
  }
  const settingToUpdate = settings.find((s5) => s5.name === settingKey || s5.envVar === settingKey);
  if (!settingToUpdate) {
    debugLogger70.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 (fsSync2.existsSync(envFilePath)) {
    envContent = await fs68.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 fs68.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 (fsSync2.existsSync(envFilePath)) {
    await fs68.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_prompts5, debugLogger70, 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_prompts5 = __toESM(require_prompts3(), 1);
    init_variables();
    init_keychain_token_storage();
    init_debugLogger();
    debugLogger70 = 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 path64.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 fs69 from "node:fs";
import * as path65 from "node:path";
import * as os29 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(cwd6, telemetrySettings) {
  const config2 = new Config({
    telemetry: telemetrySettings,
    interactive: false,
    targetDir: cwd6,
    cwd: cwd6,
    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((file2) => {
      const relativePathWithExt = path65.relative(dir, path65.join(dir, file2));
      const relativePath = relativePathWithExt.substring(0, relativePathWithExt.length - 3);
      const commandName = relativePath.split(path65.sep).map((segment) => segment.replaceAll(":", "_")).join(":");
      return commandName;
    });
    return commandNames;
  } catch (error40) {
    const isEnoent = error40.code === "ENOENT";
    const isAbortError3 = error40 instanceof Error && error40.name === "AbortError";
    if (!isEnoent && !isAbortError3) {
      debugLogger71.error(`Error loading commands from ${dir}:`, error40);
    }
    return [];
  }
}
async function convertGeminiOrClaudeExtension(extensionDir, pluginName) {
  let newExtensionDir = extensionDir;
  let originSource = "QwenCode";
  const configFilePath2 = path65.join(extensionDir, EXTENSIONS_CONFIG_FILENAME);
  if (fs69.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 fs69.promises.cp(source2, destination, {
    recursive: true,
    dereference: true,
    filter: /* @__PURE__ */ __name(async (src) => {
      try {
        const stats = await fs69.promises.stat(src);
        return stats.isFile() || stats.isDirectory();
      } catch {
        return false;
      }
    }, "filter")
  });
}
function getExtensionId(config2, installMetadata) {
  let idValue = config2.name;
  let githubUrlParts = null;
  if (installMetadata && (installMetadata.type === "git" || installMetadata.type === "github-release")) {
    try {
      githubUrlParts = parseGitHubRepoForReleases(installMetadata.source);
    } catch {
    }
  }
  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(name4) {
  if (!/^[a-zA-Z0-9-_.]+$/.test(name4)) {
    throw new Error(`Invalid extension name: "${name4}". Only letters (a-z, A-Z), numbers (0-9), underscores (_), dots (.), and dashes (-) are allowed.`);
  }
}
var debugLogger71, 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_npm();
    init_override();
    init_gemini_converter();
    init_claude_converter();
    init_esm13();
    init_storage2();
    init_extensionSettings();
    init_loggers();
    init_types4();
    init_skill_load();
    init_subagent_manager();
    init_debugLogger();
    debugLogger71 = 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((name4) => name4.toLowerCase()) ?? [];
        this.configDir = ExtensionStorage.getUserExtensionsDir();
        this.configFilePath = path65.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 name4 of this.enabledExtensionNamesOverride) {
          if (name4 === "none")
            continue;
          if (!extensions.some((ext2) => ext2.config.name.toLowerCase() === name4.toLowerCase())) {
            debugLogger71.error(`Extension not found: ${name4}`);
          }
        }
      }
      /**
       * 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 enabled2 = true;
        const allOverrides = extensionConfig?.overrides ?? [];
        for (const rule of allOverrides) {
          const override = Override.fromFileRule(rule);
          if (override.matchesPath(ensureLeadingAndTrailingSlash2(checkPath))) {
            enabled2 = !override.isDisable;
          }
        }
        return enabled2;
      }
      /**
       * Enables an extension at the specified scope.
       */
      async enableExtension(name4, scope, cwd6) {
        const currentDir = cwd6 ?? 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 === name4);
        if (!extension) {
          throw new Error(`Extension with name ${name4} does not exist.`);
        }
        const scopePath = scope === SettingScope.Workspace ? currentDir : os29.homedir();
        this.enableByPath(name4, true, scopePath);
        const config2 = getTelemetryConfig(currentDir, this.telemetrySettings);
        logExtensionEnable(config2, new ExtensionEnableEvent(name4, scope));
        extension.isActive = true;
        await this.refreshTools();
      }
      /**
       * Disables an extension at the specified scope.
       */
      async disableExtension(name4, scope, cwd6) {
        const currentDir = cwd6 ?? 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 === name4);
        if (!extension) {
          throw new Error(`Extension with name ${name4} does not exist.`);
        }
        const scopePath = scope === SettingScope.Workspace ? currentDir : os29.homedir();
        this.disableByPath(name4, true, scopePath);
        logExtensionDisable(config2, new ExtensionDisableEvent(name4, 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 = fs69.readFileSync(this.configFilePath, "utf-8");
          return JSON.parse(content);
        } catch (error40) {
          if (error40 instanceof Error && "code" in error40 && error40.code === "ENOENT") {
            return {};
          }
          debugLogger71.error("Error reading extension enablement config:", error40);
          return {};
        }
      }
      writeEnablementConfig(config2) {
        fs69.mkdirSync(this.configDir, { recursive: true });
        fs69.writeFileSync(this.configFilePath, JSON.stringify(config2, null, 2));
      }
      /**
       * Refreshes the extension cache from disk.
       */
      async refreshCache(options2) {
        this.extensionCache = /* @__PURE__ */ new Map();
        const requestedNames = options2?.names?.filter(Boolean) ?? [];
        const extensions = requestedNames.length > 0 ? (await Promise.all(requestedNames.map((name4) => this.loadExtensionByName(name4)))).filter((extension) => extension !== null) : await this.loadExtensionsFromDir(os29.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(name4, workspaceDir) {
        const cwd6 = workspaceDir ?? this.workspaceDir;
        const userExtensionsDir = ExtensionStorage.getUserExtensionsDir();
        if (!fs69.existsSync(userExtensionsDir)) {
          return null;
        }
        for (const subdir of fs69.readdirSync(userExtensionsDir)) {
          const extensionDir = path65.join(userExtensionsDir, subdir);
          if (!fs69.statSync(extensionDir).isDirectory()) {
            continue;
          }
          const extension = await this.loadExtension({
            extensionDir,
            workspaceDir: cwd6
          });
          if (extension && extension.config.name.toLowerCase() === name4.toLowerCase()) {
            return extension;
          }
        }
        return null;
      }
      async loadExtensionsFromDir(dir) {
        const storage = new Storage(dir);
        const extensionsDir = storage.getExtensionsDir();
        let subdirs;
        try {
          subdirs = fs69.readdirSync(extensionsDir);
        } catch {
          return [];
        }
        const extensions = [];
        for (const subdir of subdirs) {
          const extensionDir = path65.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 (!fs69.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 || installMetadata?.marketplaceConfig?.metadata?.version || "1.0.0",
            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)
            ]));
          }
          if (config2.channels) {
            extension.channels = config2.channels;
          }
          extension.commands = await loadCommandsFromDir(`${effectiveExtensionPath}/commands`);
          extension.contextFiles = getContextFileNames(config2).map((contextFileName) => path65.join(effectiveExtensionPath, contextFileName)).filter((contextFilePath) => fs69.existsSync(contextFilePath));
          extension.skills = await loadSkillsFromDir(`${effectiveExtensionPath}/skills`);
          extension.agents = await loadSubagentFromDir(`${effectiveExtensionPath}/agents`);
          if (config2.hooks && typeof config2.hooks !== "string") {
            extension.hooks = this.substituteHookVariables(config2.hooks, effectiveExtensionPath);
          }
          if (!extension.hooks) {
            const hooksDir = path65.join(effectiveExtensionPath, "hooks");
            const hooksJsonPath = path65.join(hooksDir, "hooks.json");
            const configHooksPath = typeof config2.hooks === "string" ? path65.isAbsolute(config2.hooks) ? config2.hooks : path65.join(effectiveExtensionPath, config2.hooks) : null;
            if (fs69.existsSync(hooksJsonPath) || configHooksPath && fs69.existsSync(configHooksPath)) {
              const hooksFilePath = configHooksPath && fs69.existsSync(configHooksPath) ? configHooksPath : hooksJsonPath;
              try {
                const hooksContent = fs69.readFileSync(hooksFilePath, "utf-8");
                const parsedHooks = JSON.parse(hooksContent);
                let hooksData;
                if (parsedHooks.hooks && typeof parsedHooks.hooks === "object") {
                  hooksData = parsedHooks.hooks;
                } else {
                  hooksData = parsedHooks;
                }
                extension.hooks = this.substituteHookVariables(hooksData, effectiveExtensionPath);
              } catch (error40) {
                debugLogger71.warn(`Failed to parse hooks file ${hooksJsonPath}: ${error40 instanceof Error ? error40.message : String(error40)}`);
              }
            }
          }
          return extension;
        } catch (e4) {
          debugLogger71.warn(`Warning: Skipping extension in ${effectiveExtensionPath}: ${getErrorMessage(e4)}`);
          return null;
        }
      }
      /**
       * Substitute variables in hook configurations, particularly ${CLAUDE_PLUGIN_ROOT}
       */
      substituteHookVariables(hooks, extensionPath) {
        return substituteHookVariables(hooks, extensionPath);
      }
      loadInstallMetadata(extensionDir) {
        const metadataFilePath = path65.join(extensionDir, INSTALL_METADATA_FILENAME);
        try {
          const configContent = fs69.readFileSync(metadataFilePath, "utf-8");
          const metadata2 = JSON.parse(configContent);
          return metadata2;
        } catch (_e2) {
          return void 0;
        }
      }
      loadExtensionConfig(context2) {
        const { extensionDir, workspaceDir = this.workspaceDir } = context2;
        const configFilePath2 = path65.join(extensionDir, EXTENSIONS_CONFIG_FILENAME);
        if (!fs69.existsSync(configFilePath2)) {
          throw new Error(`Configuration file not found at ${configFilePath2}`);
        }
        try {
          const configContent = fs69.readFileSync(configFilePath2, "utf-8");
          const config2 = recursivelyHydrateStrings(JSON.parse(configContent), {
            extensionPath: extensionDir,
            CLAUDE_PLUGIN_ROOT: extensionDir,
            workspacePath: workspaceDir,
            "/": path65.sep,
            pathSeparator: path65.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, cwd6, previousExtensionConfig) {
        const currentDir = cwd6 ?? 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 fs69.promises.mkdir(extensionsDir, { recursive: true });
          if (!path65.isAbsolute(installMetadata.source) && (installMetadata.type === "local" || installMetadata.type === "link")) {
            installMetadata.source = path65.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 === "npm") {
            tempDir = await ExtensionStorage.createTmpDir();
            const result = await downloadFromNpmRegistry(installMetadata, tempDir);
            installMetadata.releaseTag = result.version;
            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((installed2) => installed2.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 fs69.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 hooksDir = path65.join(destinationPath, "hooks");
            const configHooksPath = typeof newExtensionConfig.hooks === "string" ? path65.isAbsolute(newExtensionConfig.hooks) ? newExtensionConfig.hooks : path65.join(destinationPath, newExtensionConfig.hooks) : null;
            if (originSource === "Claude" && fs69.existsSync(hooksDir) || originSource === "Claude" && configHooksPath && fs69.existsSync(configHooksPath)) {
              try {
                await performVariableReplacement(destinationPath);
              } catch (error40) {
                debugLogger71.error("Variable replacement failed", error40);
              }
            }
            const metadataString = JSON.stringify(installMetadata, null, 2);
            const metadataPath = path65.join(destinationPath, INSTALL_METADATA_FILENAME);
            await fs69.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"));
              await this.refreshTools();
            } else {
              logExtensionInstallEvent(telemetryConfig, new ExtensionInstallEvent(newExtensionConfig.name, newExtensionConfig.version, installMetadata.source, "success"));
              this.enableExtension(newExtensionConfig.name, SettingScope.User);
            }
          } finally {
            if (tempDir) {
              await fs69.promises.rm(tempDir, { recursive: true, force: true });
            }
            if (localSourcePath !== tempDir && installMetadata.type !== "link" && installMetadata.type !== "local") {
              await fs69.promises.rm(localSourcePath, {
                recursive: true,
                force: true
              });
            }
          }
          return extension;
        } catch (error40) {
          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 error40;
        }
      }
      /**
       * Uninstalls an extension.
       */
      async uninstallExtension(extensionIdentifier, isUpdate, cwd6) {
        const currentDir = cwd6 ?? this.workspaceDir;
        const telemetryConfig = getTelemetryConfig(currentDir, this.telemetrySettings);
        const installedExtensions = this.getLoadedExtensions();
        const extension = installedExtensions.find((installed2) => installed2.config.name.toLowerCase() === extensionIdentifier.toLowerCase() || installed2.installMetadata?.source.toLowerCase() === extensionIdentifier.toLowerCase());
        if (!extension) {
          throw new Error(`Extension not found.`);
        }
        const storage = new ExtensionStorage(extension.installMetadata?.type === "link" ? extension.name : path65.basename(extension.path));
        await fs69.promises.rm(storage.getExtensionDir(), {
          recursive: true,
          force: true
        });
        if (this.extensionCache) {
          this.extensionCache.delete(extension.name);
        }
        if (isUpdate)
          return;
        this.removeEnablementConfig(extension.name);
        await 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 promises9 = [];
        for (const extension of extensions) {
          if (!extension.installMetadata) {
            callback(extension.name, ExtensionUpdateState.NOT_UPDATABLE);
            continue;
          }
          callback(extension.name, ExtensionUpdateState.CHECKING_FOR_UPDATES);
          promises9.push(checkForExtensionUpdate(extension, this).then((state) => callback(extension.name, state)).catch(() => callback(extension.name, ExtensionUpdateState.ERROR)));
        }
        await Promise.all(promises9);
      }
      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) {
          debugLogger71.error(`Error updating extension, rolling back. ${getErrorMessage(e4)}`);
          callback(extension.name, ExtensionUpdateState.ERROR);
          await copyExtension(tempDir, extension.path);
          throw e4;
        } finally {
          await fs69.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;
        await this.config.getToolRegistry().restartMcpServers();
        this.config.getSkillManager()?.refreshCache();
        this.config.getSubagentManager().refreshCache();
        this.config.refreshHierarchicalMemory();
      }
      async refreshTools() {
        if (!this.config)
          return;
        await this.refreshMemory();
      }
    };
    __name(copyExtension, "copyExtension");
    __name(getExtensionId, "getExtensionId");
    __name(hashValue, "hashValue");
    __name(validateName, "validateName");
  }
});

// packages/core/dist/src/hooks/hookRegistry.js
var debugLogger72, HookRegistry;
var init_hookRegistry = __esm({
  "packages/core/dist/src/hooks/hookRegistry.js"() {
    "use strict";
    init_esbuild_shims();
    init_types6();
    init_debugLogger();
    debugLogger72 = createDebugLogger("HOOK_REGISTRY");
    HookRegistry = class {
      static {
        __name(this, "HookRegistry");
      }
      config;
      feedbackEmitter;
      entries = [];
      constructor(config2, feedbackEmitter) {
        this.config = config2;
        this.feedbackEmitter = feedbackEmitter;
      }
      /**
       * Initialize the registry by processing hooks from config
       */
      async initialize() {
        this.entries = [];
        this.processHooksFromConfig();
        debugLogger72.debug(`Hook registry initialized with ${this.entries.length} hook entries`);
      }
      /**
       * Get all hook entries for a specific event
       */
      getHooksForEvent(eventName) {
        return this.entries.filter((entry) => entry.eventName === eventName && entry.enabled).sort((a2, b2) => this.getSourcePriority(a2.source) - this.getSourcePriority(b2.source));
      }
      /**
       * Get all registered hooks
       */
      getAllHooks() {
        return [...this.entries];
      }
      /**
       * Enable or disable a specific hook
       */
      setHookEnabled(hookName, enabled2) {
        const updated = this.entries.filter((entry) => {
          const name4 = this.getHookName(entry);
          if (name4 === hookName) {
            entry.enabled = enabled2;
            return true;
          }
          return false;
        });
        if (updated.length > 0) {
          debugLogger72.info(`${enabled2 ? "Enabled" : "Disabled"} ${updated.length} hook(s) matching "${hookName}"`);
        } else {
          debugLogger72.warn(`No hooks found matching "${hookName}"`);
        }
      }
      /**
       * Get hook name for identification and display purposes
       */
      getHookName(entry) {
        const config2 = entry.config;
        if (config2.name)
          return config2.name;
        if (config2.type === "command")
          return config2.command || "unknown-command";
        if (config2.type === "http")
          return config2.url || "unknown-url";
        if (config2.type === "function")
          return config2.id || "unknown-function";
        return "unknown-hook";
      }
      /**
       * Process hooks from the config that was already loaded by the CLI
       */
      processHooksFromConfig() {
        const userHooks = this.config.getUserHooks();
        if (userHooks) {
          this.processHooksConfiguration(userHooks, HooksConfigSource.User);
        }
        const projectHooks = this.config.getProjectHooks();
        if (projectHooks) {
          this.processHooksConfiguration(projectHooks, HooksConfigSource.Project);
        }
        const extensions = this.config.getExtensions() || [];
        for (const extension of extensions) {
          if (extension.isActive && extension.hooks) {
            this.processHooksConfiguration(extension.hooks, HooksConfigSource.Extensions);
          }
        }
      }
      /**
       * Process hooks configuration and add entries
       */
      processHooksConfiguration(hooksConfig, source2) {
        for (const [eventName, definitions] of Object.entries(hooksConfig)) {
          if (HOOKS_CONFIG_FIELDS.includes(eventName)) {
            continue;
          }
          if (!this.isValidEventName(eventName)) {
            this.feedbackEmitter?.emitFeedback("warning", `Invalid hook event name: "${eventName}" from ${source2} config. Skipping.`);
            continue;
          }
          const typedEventName = eventName;
          if (!Array.isArray(definitions)) {
            debugLogger72.warn(`Hook definitions for event "${eventName}" from source "${source2}" is not an array. Skipping.`);
            continue;
          }
          for (const definition of definitions) {
            this.processHookDefinition(definition, typedEventName, source2);
          }
        }
      }
      /**
       * Process a single hook definition
       */
      processHookDefinition(definition, eventName, source2) {
        if (!definition || typeof definition !== "object" || !Array.isArray(definition.hooks)) {
          debugLogger72.warn(`Discarding invalid hook definition for ${eventName} from ${source2}:`, definition);
          return;
        }
        for (const hookConfig of definition.hooks) {
          if (hookConfig && typeof hookConfig === "object" && this.validateHookConfig(hookConfig, eventName, source2)) {
            const hookName = this.getHookName({ config: hookConfig });
            const isDuplicate = this.entries.some((existing) => existing.eventName === eventName && existing.source === source2 && this.getHookName(existing) === hookName && existing.matcher === definition.matcher && existing.sequential === definition.sequential);
            if (isDuplicate) {
              debugLogger72.debug(`Skipping duplicate hook "${hookName}" for ${eventName} from ${source2}`);
              continue;
            }
            if (hookConfig.type !== "function") {
              hookConfig.source = source2;
            }
            this.entries.push({
              config: hookConfig,
              source: source2,
              eventName,
              matcher: definition.matcher,
              sequential: definition.sequential,
              enabled: true
            });
          } else {
            debugLogger72.warn(`Discarding invalid hook configuration for ${eventName} from ${source2}:`, hookConfig);
          }
        }
      }
      /**
       * Validate a hook configuration
       */
      validateHookConfig(config2, eventName, source2) {
        if (!config2.type || !["command", "http", "function"].includes(config2.type)) {
          debugLogger72.warn(`Invalid hook ${eventName} from ${source2} type: ${config2.type}`);
          return false;
        }
        if (config2.type === "command" && !config2.command) {
          debugLogger72.warn(`Command hook ${eventName} from ${source2} missing command field`);
          return false;
        }
        if (config2.type === "http" && !config2.url) {
          debugLogger72.warn(`HTTP hook ${eventName} from ${source2} missing url field`);
          return false;
        }
        if (config2.type === "function" && typeof config2.callback !== "function") {
          debugLogger72.warn(`Function hook ${eventName} from ${source2} missing or invalid callback`);
          return false;
        }
        return true;
      }
      /**
       * Check if an event name is valid
       */
      isValidEventName(eventName) {
        const validEventNames = Object.values(HookEventName);
        return validEventNames.includes(eventName);
      }
      /**
       * Get source priority (lower number = higher priority)
       */
      getSourcePriority(source2) {
        switch (source2) {
          case HooksConfigSource.Project:
            return 1;
          case HooksConfigSource.User:
            return 2;
          case HooksConfigSource.System:
            return 3;
          case HooksConfigSource.Extensions:
            return 4;
          default:
            return 999;
        }
      }
    };
  }
});

// packages/core/dist/src/hooks/envInterpolator.js
function sanitizeHeaderValue(value) {
  return value.replace(/[\r\n\x00]/g, "");
}
function isSafeVarName(varName) {
  return !DANGEROUS_VAR_NAMES.includes(varName);
}
function interpolateEnvVars(value, allowedVars) {
  const interpolated = value.replace(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g, (match2, varName) => {
    if (!isSafeVarName(varName)) {
      return "";
    }
    if (allowedVars.includes(varName)) {
      return process.env[varName] || "";
    }
    return "";
  });
  return sanitizeHeaderValue(interpolated);
}
function interpolateHeaders(headers, allowedVars) {
  const result = {};
  for (const [key, value] of Object.entries(headers)) {
    result[key] = interpolateEnvVars(value, allowedVars);
  }
  return result;
}
function interpolateUrl(url3, allowedVars) {
  return interpolateEnvVars(url3, allowedVars);
}
var DANGEROUS_VAR_NAMES;
var init_envInterpolator = __esm({
  "packages/core/dist/src/hooks/envInterpolator.js"() {
    "use strict";
    init_esbuild_shims();
    __name(sanitizeHeaderValue, "sanitizeHeaderValue");
    DANGEROUS_VAR_NAMES = [
      "__proto__",
      "constructor",
      "prototype",
      "__defineGetter__",
      "__defineSetter__",
      "__lookupGetter__",
      "__lookupSetter__"
    ];
    __name(isSafeVarName, "isSafeVarName");
    __name(interpolateEnvVars, "interpolateEnvVars");
    __name(interpolateHeaders, "interpolateHeaders");
    __name(interpolateUrl, "interpolateUrl");
  }
});

// packages/core/dist/src/hooks/ssrfGuard.js
import { isIP as isIP2 } from "net";
function isBlockedAddress(address) {
  const v2 = isIP2(address);
  if (v2 === 4) {
    return isBlockedV4(address);
  }
  if (v2 === 6) {
    return isBlockedV6(address);
  }
  return false;
}
function isBlockedV4(address) {
  const parts2 = address.split(".").map(Number);
  const [a2, b2] = parts2;
  if (parts2.length !== 4 || a2 === void 0 || b2 === void 0 || parts2.some((n3) => Number.isNaN(n3))) {
    return false;
  }
  if (a2 === 127)
    return false;
  if (a2 === 0)
    return true;
  if (a2 === 10)
    return true;
  if (a2 === 169 && b2 === 254)
    return true;
  if (a2 === 172 && b2 >= 16 && b2 <= 31)
    return true;
  if (a2 === 100 && b2 >= 64 && b2 <= 127)
    return true;
  if (a2 === 192 && b2 === 168)
    return true;
  return false;
}
function isBlockedV6(address) {
  const lower3 = address.toLowerCase();
  if (lower3 === "::1")
    return false;
  if (lower3 === "::")
    return true;
  const mappedV4 = extractMappedIPv4(lower3);
  if (mappedV4 !== null) {
    return isBlockedV4(mappedV4);
  }
  if (lower3.startsWith("fc") || lower3.startsWith("fd")) {
    return true;
  }
  const firstHextet = lower3.split(":")[0];
  if (firstHextet && firstHextet.length >= 3 && firstHextet >= "fe80" && firstHextet <= "febf") {
    return true;
  }
  return false;
}
function expandIPv6Groups(addr2) {
  let tailHextets = [];
  if (addr2.includes(".")) {
    const lastColon = addr2.lastIndexOf(":");
    const v42 = addr2.slice(lastColon + 1);
    addr2 = addr2.slice(0, lastColon);
    const octets = v42.split(".").map(Number);
    if (octets.length !== 4 || octets.some((n3) => !Number.isInteger(n3) || n3 < 0 || n3 > 255)) {
      return null;
    }
    tailHextets = [
      octets[0] << 8 | octets[1],
      octets[2] << 8 | octets[3]
    ];
  }
  const dbl = addr2.indexOf("::");
  let head;
  let tail;
  if (dbl === -1) {
    head = addr2.split(":");
    tail = [];
  } else {
    const headStr = addr2.slice(0, dbl);
    const tailStr = addr2.slice(dbl + 2);
    head = headStr === "" ? [] : headStr.split(":");
    tail = tailStr === "" ? [] : tailStr.split(":");
  }
  const target = 8 - tailHextets.length;
  const fill = target - head.length - tail.length;
  if (fill < 0)
    return null;
  const hex = [...head, ...new Array(fill).fill("0"), ...tail];
  const nums = hex.map((h3) => parseInt(h3, 16));
  if (nums.some((n3) => Number.isNaN(n3) || n3 < 0 || n3 > 65535)) {
    return null;
  }
  nums.push(...tailHextets);
  return nums.length === 8 ? nums : null;
}
function extractMappedIPv4(addr2) {
  const g2 = expandIPv6Groups(addr2);
  if (!g2)
    return null;
  if (g2[0] === 0 && g2[1] === 0 && g2[2] === 0 && g2[3] === 0 && g2[4] === 0 && g2[5] === 65535) {
    const hi = g2[6];
    const lo = g2[7];
    return `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
  }
  return null;
}
var init_ssrfGuard = __esm({
  "packages/core/dist/src/hooks/ssrfGuard.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isBlockedAddress, "isBlockedAddress");
    __name(isBlockedV4, "isBlockedV4");
    __name(isBlockedV6, "isBlockedV6");
    __name(expandIPv6Groups, "expandIPv6Groups");
    __name(extractMappedIPv4, "extractMappedIPv4");
  }
});

// packages/core/dist/src/hooks/urlValidator.js
import { isIPv4, isIPv6 } from "net";
var debugLogger73, BLOCKED_HOSTS, UrlValidator;
var init_urlValidator = __esm({
  "packages/core/dist/src/hooks/urlValidator.js"() {
    "use strict";
    init_esbuild_shims();
    init_ssrfGuard();
    init_debugLogger();
    debugLogger73 = createDebugLogger("URL_VALIDATOR");
    BLOCKED_HOSTS = [
      "localhost.localdomain",
      "ip6-localhost",
      "ip6-loopback",
      "metadata.google.internal",
      // GCP metadata
      "169.254.169.254",
      // Cloud metadata (AWS, GCP, Azure)
      "metadata.azure.internal"
      // Azure metadata
    ];
    UrlValidator = class {
      static {
        __name(this, "UrlValidator");
      }
      allowedPatterns;
      compiledPatterns;
      /**
       * Create a new URL validator
       * @param allowedPatterns - Array of allowed URL patterns (supports * wildcard)
       */
      constructor(allowedPatterns = []) {
        this.allowedPatterns = allowedPatterns;
        this.compiledPatterns = allowedPatterns.map((pattern) => this.compilePattern(pattern));
      }
      /**
       * Compile a URL pattern with wildcards into a RegExp.
       * Supports both pre-escaped patterns (e.g., 'https://api\\.example\\.com/*')
       * and unescaped patterns (e.g., 'https://api.example.com/*').
       */
      compilePattern(pattern) {
        const isPreEscaped = pattern.includes("\\.");
        let escaped;
        if (isPreEscaped) {
          escaped = pattern.replace(/\*/g, ".*");
        } else {
          escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
        }
        return new RegExp(`^${escaped}$`, "i");
      }
      /**
       * Check if a URL is allowed by the whitelist
       * @param url - The URL to check
       * @returns True if the URL matches any allowed pattern
       */
      isAllowed(url3) {
        if (this.allowedPatterns.length === 0) {
          return true;
        }
        return this.compiledPatterns.some((pattern) => pattern.test(url3));
      }
      /**
       * Check if a URL should be blocked for security reasons (SSRF protection).
       * Uses ssrfGuard.ts for IP address blocking (authoritative implementation).
       * @param url - The URL to check
       * @returns True if the URL should be blocked
       */
      isBlocked(url3) {
        try {
          const parsed = new URL(url3);
          const hostname4 = parsed.hostname.toLowerCase();
          if (BLOCKED_HOSTS.includes(hostname4)) {
            debugLogger73.debug(`URL blocked: hostname ${hostname4} is in blocklist`);
            return true;
          }
          if (this.isIpAddress(hostname4)) {
            const cleanHostname = hostname4.replace(/^\[|\]$/g, "");
            if (isBlockedAddress(cleanHostname)) {
              debugLogger73.debug(`URL blocked: IP ${hostname4} is blocked`);
              return true;
            }
          }
          return false;
        } catch {
          debugLogger73.debug(`URL blocked: invalid URL format`);
          return true;
        }
      }
      /**
       * Validate a URL for use in HTTP hooks
       * @param url - The URL to validate
       * @returns Validation result with allowed status and reason
       */
      validate(url3) {
        if (this.isBlocked(url3)) {
          return {
            allowed: false,
            reason: "URL is blocked for security reasons (SSRF protection)"
          };
        }
        if (!this.isAllowed(url3)) {
          return {
            allowed: false,
            reason: `URL does not match any allowed pattern. Allowed patterns: ${this.allowedPatterns.join(", ")}`
          };
        }
        return { allowed: true };
      }
      /**
       * Check if a string is an IP address (IPv4 or IPv6)
       * Uses Node.js net module for accurate validation of all IP formats
       * including ::1, ::ffff:192.168.1.1, 2001:db8::1, etc.
       */
      isIpAddress(hostname4) {
        const cleanHostname = hostname4.replace(/^\[|\]$/g, "");
        return isIPv4(cleanHostname) || isIPv6(cleanHostname);
      }
    };
  }
});

// packages/core/dist/src/hooks/combinedAbortSignal.js
function createCombinedAbortSignal(externalSignal, options2) {
  const controller = new AbortController();
  const timeoutMs = options2?.timeoutMs;
  let timeoutId;
  if (timeoutMs !== void 0 && timeoutMs > 0) {
    timeoutId = setTimeout(() => {
      controller.abort();
    }, timeoutMs);
  }
  let abortHandler;
  if (externalSignal) {
    if (externalSignal.aborted) {
      controller.abort();
    } else {
      abortHandler = /* @__PURE__ */ __name(() => {
        controller.abort();
      }, "abortHandler");
      externalSignal.addEventListener("abort", abortHandler, { once: true });
    }
  }
  const cleanup = /* @__PURE__ */ __name(() => {
    if (timeoutId !== void 0) {
      clearTimeout(timeoutId);
      timeoutId = void 0;
    }
    if (externalSignal && abortHandler) {
      externalSignal.removeEventListener("abort", abortHandler);
      abortHandler = void 0;
    }
  }, "cleanup");
  return { signal: controller.signal, cleanup };
}
var init_combinedAbortSignal = __esm({
  "packages/core/dist/src/hooks/combinedAbortSignal.js"() {
    "use strict";
    init_esbuild_shims();
    __name(createCombinedAbortSignal, "createCombinedAbortSignal");
  }
});

// packages/core/dist/src/hooks/httpHookRunner.js
import { lookup as dnsLookup } from "dns";
async function validateResolvedHost(hostname4) {
  return new Promise((resolve42) => {
    if (isBlockedAddress(hostname4)) {
      resolve42({
        ok: false,
        error: `HTTP hook blocked: ${hostname4} is in a private/link-local range`
      });
      return;
    }
    dnsLookup(hostname4, { all: true }, (err2, addresses) => {
      if (err2) {
        resolve42({ ok: true });
        return;
      }
      for (const addr2 of addresses) {
        if (isBlockedAddress(addr2.address)) {
          resolve42({
            ok: false,
            error: `HTTP hook blocked: ${hostname4} resolves to ${addr2.address} (private/link-local). Loopback (127.0.0.1, ::1) is allowed.`
          });
          return;
        }
      }
      resolve42({ ok: true });
    });
  });
}
var debugLogger74, DEFAULT_HTTP_TIMEOUT, MAX_OUTPUT_LENGTH, HttpHookRunner;
var init_httpHookRunner = __esm({
  "packages/core/dist/src/hooks/httpHookRunner.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_envInterpolator();
    init_urlValidator();
    init_combinedAbortSignal();
    init_ssrfGuard();
    debugLogger74 = createDebugLogger("HTTP_HOOK_RUNNER");
    DEFAULT_HTTP_TIMEOUT = 10 * 60 * 1e3;
    MAX_OUTPUT_LENGTH = 1e4;
    __name(validateResolvedHost, "validateResolvedHost");
    HttpHookRunner = class {
      static {
        __name(this, "HttpHookRunner");
      }
      urlValidator;
      executedOnceHooks = /* @__PURE__ */ new Set();
      statusMessageCallback;
      constructor(allowedUrls) {
        this.urlValidator = new UrlValidator(allowedUrls);
      }
      /**
       * Set callback for displaying status messages
       */
      setStatusMessageCallback(callback) {
        this.statusMessageCallback = callback;
      }
      /**
       * Execute an HTTP hook
       * @param hookConfig HTTP hook configuration
       * @param eventName Event name
       * @param input Hook input
       * @param signal Optional AbortSignal to cancel hook execution
       */
      async execute(hookConfig, eventName, input, signal) {
        const startTime = Date.now();
        const hookId = hookConfig.name || hookConfig.url;
        if (signal?.aborted) {
          return {
            hookConfig,
            eventName,
            success: false,
            error: new Error(`HTTP hook execution cancelled (aborted): ${hookId}`),
            duration: 0
          };
        }
        if (hookConfig.once) {
          const onceKey = `${hookConfig.url}:${eventName}`;
          if (this.executedOnceHooks.has(onceKey)) {
            debugLogger74.debug(`Skipping once hook ${hookId} - already executed for ${eventName}`);
            return {
              hookConfig,
              eventName,
              success: true,
              duration: 0,
              output: { continue: true }
            };
          }
          this.executedOnceHooks.add(onceKey);
        }
        if (hookConfig.statusMessage && this.statusMessageCallback) {
          this.statusMessageCallback(hookConfig.statusMessage);
        }
        try {
          const url3 = interpolateUrl(hookConfig.url, hookConfig.allowedEnvVars || []);
          const validation2 = this.urlValidator.validate(url3);
          if (!validation2.allowed) {
            return {
              hookConfig,
              eventName,
              success: false,
              error: new Error(`URL validation failed: ${validation2.reason}`),
              duration: Date.now() - startTime
            };
          }
          const parsed = new URL(url3);
          const hostValidation = await validateResolvedHost(parsed.hostname);
          if (!hostValidation.ok) {
            return {
              hookConfig,
              eventName,
              success: false,
              error: new Error(hostValidation.error),
              duration: Date.now() - startTime
            };
          }
          const headers = hookConfig.headers ? interpolateHeaders(hookConfig.headers, hookConfig.allowedEnvVars || []) : {};
          const body2 = JSON.stringify({
            ...input,
            hook_event_name: eventName
          });
          const timeout2 = hookConfig.timeout ? hookConfig.timeout * 1e3 : DEFAULT_HTTP_TIMEOUT;
          const { signal: combinedSignal, cleanup } = createCombinedAbortSignal(signal, { timeoutMs: timeout2 });
          try {
            debugLogger74.debug(`Executing HTTP hook: ${hookId} -> ${url3}`);
            const response = await fetch(url3, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                ...headers
              },
              body: body2,
              signal: combinedSignal
            });
            cleanup();
            const duration3 = Date.now() - startTime;
            if (!response.ok) {
              debugLogger74.warn(`HTTP hook ${hookId} returned non-2xx status ${response.status} (non-blocking)`);
              return {
                hookConfig,
                eventName,
                success: true,
                output: { continue: true },
                duration: duration3
              };
            }
            const output = await this.parseResponse(response, eventName);
            debugLogger74.debug(`HTTP hook ${hookId} completed successfully in ${duration3}ms`);
            return {
              hookConfig,
              eventName,
              success: true,
              output,
              duration: duration3
            };
          } catch (fetchError) {
            cleanup();
            const duration3 = Date.now() - startTime;
            if (fetchError instanceof Error && (fetchError.name === "AbortError" || combinedSignal.aborted)) {
              debugLogger74.warn(`HTTP hook ${hookId} timed out or was aborted after ${timeout2}ms (non-blocking)`);
              return {
                hookConfig,
                eventName,
                success: true,
                output: { continue: true },
                duration: duration3
              };
            }
            debugLogger74.warn(`HTTP hook ${hookId} connection failed (non-blocking): ${fetchError instanceof Error ? fetchError.message : String(fetchError)}`);
            return {
              hookConfig,
              eventName,
              success: true,
              output: { continue: true },
              duration: duration3
            };
          }
        } catch (error40) {
          const duration3 = Date.now() - startTime;
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          debugLogger74.warn(`HTTP hook ${hookId} failed: ${errorMessage}`);
          return {
            hookConfig,
            eventName,
            success: false,
            error: error40 instanceof Error ? error40 : new Error(errorMessage),
            duration: duration3
          };
        }
      }
      /**
       * Parse HTTP response into HookOutput
       */
      async parseResponse(response, eventName) {
        const contentType = response.headers.get("content-type") || "";
        if (contentType.includes("application/json")) {
          try {
            const json3 = await response.json();
            return this.normalizeOutput(json3, eventName);
          } catch {
            debugLogger74.warn("Failed to parse JSON response, using empty output");
            return { continue: true };
          }
        }
        const text = await response.text();
        if (text.trim()) {
          return {
            continue: true,
            systemMessage: this.truncateOutput(text.trim())
          };
        }
        return { continue: true };
      }
      /**
       * Truncate output to MAX_OUTPUT_LENGTH characters
       * Per Qwen Code spec: output is capped at 10,000 characters
       */
      truncateOutput(output) {
        if (output.length <= MAX_OUTPUT_LENGTH) {
          return output;
        }
        const truncated = output.substring(0, MAX_OUTPUT_LENGTH);
        debugLogger74.debug(`Output truncated from ${output.length} to ${MAX_OUTPUT_LENGTH} characters`);
        return `${truncated}
... [truncated, ${output.length - MAX_OUTPUT_LENGTH} more characters]`;
      }
      /**
       * Normalize response JSON into HookOutput format
       */
      normalizeOutput(json3, eventName) {
        const output = {};
        if ("continue" in json3 && typeof json3["continue"] === "boolean") {
          output.continue = json3["continue"];
        }
        if ("stopReason" in json3 && typeof json3["stopReason"] === "string") {
          output.stopReason = this.truncateOutput(json3["stopReason"]);
        }
        if ("suppressOutput" in json3 && typeof json3["suppressOutput"] === "boolean") {
          output.suppressOutput = json3["suppressOutput"];
        }
        if ("systemMessage" in json3 && typeof json3["systemMessage"] === "string") {
          output.systemMessage = this.truncateOutput(json3["systemMessage"]);
        }
        if ("decision" in json3 && typeof json3["decision"] === "string") {
          output.decision = json3["decision"];
        }
        if ("reason" in json3 && typeof json3["reason"] === "string") {
          output.reason = this.truncateOutput(json3["reason"]);
        }
        if ("hookSpecificOutput" in json3 && typeof json3["hookSpecificOutput"] === "object" && json3["hookSpecificOutput"] !== null) {
          const hookOutput = json3["hookSpecificOutput"];
          if ("additionalContext" in hookOutput && typeof hookOutput["additionalContext"] === "string") {
            hookOutput["additionalContext"] = this.truncateOutput(hookOutput["additionalContext"]);
          }
          output.hookSpecificOutput = hookOutput;
          if (!("hookEventName" in output.hookSpecificOutput)) {
            output.hookSpecificOutput["hookEventName"] = eventName;
          }
        }
        return output;
      }
      /**
       * Reset once hooks tracking (useful for testing)
       */
      resetOnceHooks() {
        this.executedOnceHooks.clear();
      }
      /**
       * Update allowed URLs
       */
      updateAllowedUrls(allowedUrls) {
        this.urlValidator = new UrlValidator(allowedUrls);
      }
    };
  }
});

// packages/core/dist/src/hooks/functionHookRunner.js
var debugLogger75, DEFAULT_FUNCTION_TIMEOUT, FunctionHookRunner;
var init_functionHookRunner = __esm({
  "packages/core/dist/src/hooks/functionHookRunner.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger75 = createDebugLogger("FUNCTION_HOOK_RUNNER");
    DEFAULT_FUNCTION_TIMEOUT = 5e3;
    FunctionHookRunner = class {
      static {
        __name(this, "FunctionHookRunner");
      }
      /**
       * Execute a function hook
       * @param hookConfig Function hook configuration
       * @param eventName Event name
       * @param input Hook input
       * @param context Optional context (messages, toolUseID, signal)
       */
      async execute(hookConfig, eventName, input, context2) {
        const startTime = Date.now();
        const hookId = hookConfig.id || hookConfig.name || "anonymous-function";
        const signal = context2?.signal;
        if (signal?.aborted) {
          return {
            hookConfig,
            eventName,
            success: false,
            outcome: "cancelled",
            error: new Error(`Function hook execution cancelled (aborted): ${hookId}`),
            duration: 0
          };
        }
        try {
          const timeout2 = hookConfig.timeout ?? DEFAULT_FUNCTION_TIMEOUT;
          const result = await this.executeWithTimeout(hookConfig.callback, input, context2, timeout2, signal);
          const duration3 = Date.now() - startTime;
          debugLogger75.debug(`Function hook ${hookId} completed successfully in ${duration3}ms`);
          const executionResult = this.processHookResult(hookConfig, eventName, result, duration3);
          if (executionResult.success && hookConfig.onHookSuccess) {
            try {
              hookConfig.onHookSuccess(executionResult);
            } catch (error40) {
              debugLogger75.warn(`onHookSuccess callback failed for ${hookId}: ${error40 instanceof Error ? error40.message : String(error40)}`);
            }
          }
          return executionResult;
        } catch (error40) {
          const duration3 = Date.now() - startTime;
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          debugLogger75.warn(`Function hook ${hookId} failed: ${errorMessage}`);
          const displayError = hookConfig.errorMessage ? new Error(`${hookConfig.errorMessage}: ${errorMessage}`) : error40 instanceof Error ? error40 : new Error(errorMessage);
          return {
            hookConfig,
            eventName,
            success: false,
            outcome: "non_blocking_error",
            error: displayError,
            duration: duration3
          };
        }
      }
      /**
       * Process hook result and convert to execution result
       */
      processHookResult(hookConfig, eventName, result, duration3) {
        if (typeof result === "boolean") {
          if (result) {
            return {
              hookConfig,
              eventName,
              success: true,
              outcome: "success",
              output: { continue: true },
              duration: duration3
            };
          } else {
            return {
              hookConfig,
              eventName,
              success: false,
              outcome: "blocking",
              output: {
                continue: false,
                stopReason: hookConfig.errorMessage || "Blocked by function hook",
                decision: "block",
                reason: hookConfig.errorMessage || "Blocked by function hook"
              },
              duration: duration3
            };
          }
        }
        const output = result || { continue: true };
        const outcome = this.determineOutcome(output);
        return {
          hookConfig,
          eventName,
          success: outcome === "success",
          outcome,
          output,
          duration: duration3
        };
      }
      /**
       * Determine outcome from HookOutput
       */
      determineOutcome(output) {
        if (output.decision === "block" || output.decision === "deny") {
          return "blocking";
        }
        if (output.continue === false) {
          return "blocking";
        }
        return "success";
      }
      /**
       * Execute callback with timeout support using Promise.race for proper race condition handling
       */
      async executeWithTimeout(callback, input, context2, timeout2, signal) {
        if (typeof callback !== "function") {
          throw new Error("Invalid callback: expected a function");
        }
        let timeoutId;
        let abortHandler;
        const cleanup = /* @__PURE__ */ __name(() => {
          if (timeoutId) {
            clearTimeout(timeoutId);
            timeoutId = void 0;
          }
          if (signal && abortHandler) {
            signal.removeEventListener("abort", abortHandler);
            abortHandler = void 0;
          }
        }, "cleanup");
        try {
          const timeoutPromise = new Promise((_2, reject) => {
            timeoutId = setTimeout(() => {
              reject(new Error(`Function hook timed out after ${timeout2}ms`));
            }, timeout2);
          });
          const abortPromise = new Promise((_2, reject) => {
            if (signal) {
              if (signal.aborted) {
                reject(new Error("Function hook execution aborted"));
                return;
              }
              abortHandler = /* @__PURE__ */ __name(() => {
                reject(new Error("Function hook execution aborted"));
              }, "abortHandler");
              signal.addEventListener("abort", abortHandler);
            }
          });
          const promises9 = [callback(input, context2), timeoutPromise];
          if (signal) {
            promises9.push(abortPromise);
          }
          const result = await Promise.race(promises9);
          cleanup();
          return result;
        } catch (error40) {
          cleanup();
          throw error40;
        }
      }
    };
  }
});

// packages/core/dist/src/hooks/asyncHookRegistry.js
function generateHookId() {
  return `hook_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
}
var debugLogger76, DEFAULT_MAX_CONCURRENT_HOOKS, DEFAULT_TIMEOUT_CHECK_INTERVAL, AsyncHookRegistry;
var init_asyncHookRegistry = __esm({
  "packages/core/dist/src/hooks/asyncHookRegistry.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger76 = createDebugLogger("ASYNC_HOOK_REGISTRY");
    DEFAULT_MAX_CONCURRENT_HOOKS = 10;
    DEFAULT_TIMEOUT_CHECK_INTERVAL = 5e3;
    __name(generateHookId, "generateHookId");
    AsyncHookRegistry = class {
      static {
        __name(this, "AsyncHookRegistry");
      }
      pendingHooks = /* @__PURE__ */ new Map();
      completedOutputs = [];
      completedContexts = [];
      maxConcurrentHooks;
      timeoutCheckTimer;
      constructor(options2 = {}) {
        this.maxConcurrentHooks = options2.maxConcurrentHooks ?? DEFAULT_MAX_CONCURRENT_HOOKS;
        if (options2.enableAutoTimeoutCheck) {
          const interval = options2.timeoutCheckInterval ?? DEFAULT_TIMEOUT_CHECK_INTERVAL;
          this.startTimeoutChecker(interval);
        }
      }
      /**
       * Start automatic timeout checking
       */
      startTimeoutChecker(interval) {
        if (this.timeoutCheckTimer) {
          clearInterval(this.timeoutCheckTimer);
        }
        this.timeoutCheckTimer = setInterval(() => {
          this.checkTimeouts();
        }, interval);
      }
      /**
       * Stop automatic timeout checking
       */
      stopTimeoutChecker() {
        if (this.timeoutCheckTimer) {
          clearInterval(this.timeoutCheckTimer);
          this.timeoutCheckTimer = void 0;
        }
      }
      /**
       * Get current number of running hooks
       */
      getRunningCount() {
        return Array.from(this.pendingHooks.values()).filter((hook) => hook.status === "running").length;
      }
      /**
       * Check if we can accept more async hooks
       */
      canAcceptMore() {
        return this.getRunningCount() < this.maxConcurrentHooks;
      }
      /**
       * Register a new async hook execution
       * @returns hookId if registered, null if rejected due to concurrency limit
       */
      register(hook) {
        if (!this.canAcceptMore()) {
          debugLogger76.warn(`Async hook registration rejected: concurrency limit reached (${this.maxConcurrentHooks})`);
          return null;
        }
        const hookId = hook.hookId;
        const pendingHook = {
          ...hook,
          status: "running"
        };
        this.pendingHooks.set(hookId, pendingHook);
        debugLogger76.debug(`Registered async hook: ${hookId} (${hook.hookName}) for event ${hook.hookEvent} [${this.getRunningCount()}/${this.maxConcurrentHooks}]`);
        return hookId;
      }
      /**
       * Update hook output (stdout/stderr)
       */
      updateOutput(hookId, stdout2, stderr) {
        const hook = this.pendingHooks.get(hookId);
        if (hook) {
          if (stdout2 !== void 0) {
            hook.stdout += stdout2;
          }
          if (stderr !== void 0) {
            hook.stderr += stderr;
          }
        }
      }
      /**
       * Mark a hook as completed with output
       */
      complete(hookId, output) {
        const hook = this.pendingHooks.get(hookId);
        if (!hook) {
          debugLogger76.warn(`Attempted to complete unknown hook: ${hookId}`);
          return;
        }
        hook.status = "completed";
        hook.output = output;
        this.processCompletedOutput(hook);
        this.pendingHooks.delete(hookId);
        debugLogger76.debug(`Async hook completed: ${hookId} (${hook.hookName})`);
      }
      /**
       * Mark a hook as failed
       */
      fail(hookId, error40) {
        const hook = this.pendingHooks.get(hookId);
        if (!hook) {
          debugLogger76.warn(`Attempted to fail unknown hook: ${hookId}`);
          return;
        }
        hook.status = "failed";
        hook.error = error40;
        this.completedOutputs.push({
          type: "error",
          message: `Async hook ${hook.hookName} failed: ${error40.message}`,
          hookName: hook.hookName,
          hookId,
          timestamp: Date.now()
        });
        this.pendingHooks.delete(hookId);
        debugLogger76.debug(`Async hook failed: ${hookId} (${hook.hookName})`);
      }
      /**
       * Mark a hook as timed out and terminate the process if running
       */
      timeout(hookId) {
        const hook = this.pendingHooks.get(hookId);
        if (!hook) {
          debugLogger76.warn(`Attempted to timeout unknown hook: ${hookId}`);
          return;
        }
        if (hook.process && !hook.process.killed) {
          debugLogger76.debug(`Terminating process for timed out hook: ${hookId}`);
          hook.process.kill("SIGTERM");
          const forceKillTimeout = setTimeout(() => {
            if (hook.process && !hook.process.killed) {
              debugLogger76.debug(`Force killing process for hook: ${hookId}`);
              hook.process.kill("SIGKILL");
            }
          }, 2e3);
          hook.process.once("exit", () => {
            clearTimeout(forceKillTimeout);
          });
        }
        hook.status = "timeout";
        hook.error = new Error(`Hook timed out after ${hook.timeout}ms`);
        this.completedOutputs.push({
          type: "warning",
          message: `Async hook ${hook.hookName} timed out after ${hook.timeout}ms`,
          hookName: hook.hookName,
          hookId,
          timestamp: Date.now()
        });
        this.pendingHooks.delete(hookId);
        debugLogger76.debug(`Async hook timed out: ${hookId} (${hook.hookName})`);
      }
      /**
       * Get all pending hooks
       */
      getPendingHooks() {
        return Array.from(this.pendingHooks.values());
      }
      /**
       * Get pending hooks for a specific session
       */
      getPendingHooksForSession(sessionId) {
        return Array.from(this.pendingHooks.values()).filter((hook) => hook.sessionId === sessionId);
      }
      /**
       * Get and clear pending output for delivery to the next turn
       */
      getPendingOutput() {
        const output = {
          messages: [...this.completedOutputs],
          contexts: [...this.completedContexts]
        };
        this.completedOutputs.length = 0;
        this.completedContexts.length = 0;
        return output;
      }
      /**
       * Check if there are any pending outputs
       */
      hasPendingOutput() {
        return this.completedOutputs.length > 0 || this.completedContexts.length > 0;
      }
      /**
       * Check if there are any running hooks
       */
      hasRunningHooks() {
        return this.pendingHooks.size > 0;
      }
      /**
       * Check for timed out hooks and mark them
       */
      checkTimeouts() {
        const now = Date.now();
        for (const [hookId, hook] of this.pendingHooks.entries()) {
          if (hook.status === "running" && now - hook.startTime > hook.timeout) {
            this.timeout(hookId);
          }
        }
      }
      /**
       * Clear all pending hooks for a session (e.g., on session end)
       */
      clearSession(sessionId) {
        for (const [hookId, hook] of this.pendingHooks.entries()) {
          if (hook.sessionId === sessionId) {
            this.pendingHooks.delete(hookId);
            debugLogger76.debug(`Cleared async hook on session end: ${hookId} (${hook.hookName})`);
          }
        }
      }
      /**
       * Process completed hook output for delivery
       */
      processCompletedOutput(hook) {
        if (hook.stdout) {
          try {
            const parsed = JSON.parse(hook.stdout.trim());
            if (parsed.systemMessage && typeof parsed.systemMessage === "string") {
              this.completedOutputs.push({
                type: "system",
                message: parsed.systemMessage,
                hookName: hook.hookName,
                hookId: hook.hookId,
                timestamp: Date.now()
              });
            }
            if (parsed.hookSpecificOutput?.additionalContext && typeof parsed.hookSpecificOutput.additionalContext === "string") {
              this.completedContexts.push(parsed.hookSpecificOutput.additionalContext);
            }
          } catch {
            const trimmed2 = hook.stdout.trim();
            if (trimmed2) {
              this.completedOutputs.push({
                type: "info",
                message: trimmed2,
                hookName: hook.hookName,
                hookId: hook.hookId,
                timestamp: Date.now()
              });
            }
          }
        }
        if (hook.stderr && hook.stderr.trim()) {
          this.completedOutputs.push({
            type: "warning",
            message: hook.stderr.trim(),
            hookName: hook.hookName,
            hookId: hook.hookId,
            timestamp: Date.now()
          });
        }
      }
    };
  }
});

// packages/core/dist/src/hooks/hookRunner.js
import { spawn as spawn5 } from "node:child_process";
var debugLogger77, DEFAULT_HOOK_TIMEOUT, MAX_OUTPUT_LENGTH2, EXIT_CODE_SUCCESS, EXIT_CODE_NON_BLOCKING_ERROR, HookRunner;
var init_hookRunner = __esm({
  "packages/core/dist/src/hooks/hookRunner.js"() {
    "use strict";
    init_esbuild_shims();
    init_types6();
    init_debugLogger();
    init_shell_utils();
    init_httpHookRunner();
    init_functionHookRunner();
    init_asyncHookRegistry();
    debugLogger77 = createDebugLogger("TRUSTED_HOOKS");
    DEFAULT_HOOK_TIMEOUT = 6e4;
    MAX_OUTPUT_LENGTH2 = 1024 * 1024;
    EXIT_CODE_SUCCESS = 0;
    EXIT_CODE_NON_BLOCKING_ERROR = 1;
    HookRunner = class {
      static {
        __name(this, "HookRunner");
      }
      httpRunner;
      functionRunner;
      asyncRegistry;
      constructor(allowedHttpUrls) {
        this.httpRunner = new HttpHookRunner(allowedHttpUrls);
        this.functionRunner = new FunctionHookRunner();
        this.asyncRegistry = new AsyncHookRegistry();
      }
      /**
       * Get the async hook registry
       */
      getAsyncRegistry() {
        return this.asyncRegistry;
      }
      /**
       * Update allowed HTTP URLs
       */
      updateAllowedHttpUrls(allowedUrls) {
        this.httpRunner.updateAllowedUrls(allowedUrls);
      }
      /**
       * Execute a single hook
       * @param hookConfig Hook configuration
       * @param eventName Event name
       * @param input Hook input
       * @param contextOrSignal Optional context (for function hooks) or AbortSignal
       */
      async executeHook(hookConfig, eventName, input, contextOrSignal) {
        const startTime = Date.now();
        const signal = contextOrSignal && "aborted" in contextOrSignal ? contextOrSignal : contextOrSignal?.signal;
        if (signal?.aborted) {
          const hookId = this.getHookId(hookConfig);
          return {
            hookConfig,
            eventName,
            success: false,
            outcome: "cancelled",
            error: new Error(`Hook execution cancelled (aborted): ${hookId}`),
            duration: 0
          };
        }
        try {
          if (this.isAsyncHook(hookConfig)) {
            return this.executeAsyncHook(hookConfig, eventName, input, signal);
          }
          switch (hookConfig.type) {
            case HookType.Command:
              return await this.executeCommandHook(hookConfig, eventName, input, startTime, signal);
            case HookType.Http:
              return await this.httpRunner.execute(hookConfig, eventName, input, signal);
            case HookType.Function: {
              const functionContext = contextOrSignal && !("aborted" in contextOrSignal) ? contextOrSignal : { signal };
              return await this.functionRunner.execute(hookConfig, eventName, input, functionContext);
            }
            default:
              throw new Error(`Unknown hook type: ${hookConfig.type}`);
          }
        } catch (error40) {
          const duration3 = Date.now() - startTime;
          const hookId = this.getHookId(hookConfig);
          const errorMessage = `Hook execution failed for event '${eventName}' (hook: ${hookId}): ${error40}`;
          debugLogger77.warn(`Hook execution error (non-fatal): ${errorMessage}`);
          return {
            hookConfig,
            eventName,
            success: false,
            error: error40 instanceof Error ? error40 : new Error(errorMessage),
            duration: duration3
          };
        }
      }
      /**
       * Check if a hook should be executed asynchronously
       */
      isAsyncHook(hookConfig) {
        return hookConfig.type === HookType.Command && hookConfig.async === true;
      }
      /**
       * Get a unique identifier for a hook
       */
      getHookId(hookConfig) {
        if (hookConfig.name) {
          return hookConfig.name;
        }
        switch (hookConfig.type) {
          case HookType.Command:
            return hookConfig.command || "unknown-command";
          case HookType.Http:
            return hookConfig.url || "unknown-url";
          case HookType.Function:
            return hookConfig.id || "unknown-function";
          default:
            return "unknown";
        }
      }
      /**
       * Get shell configuration for a hook, respecting hookConfig.shell override
       */
      getShellConfigForHook(hookConfig) {
        const globalConfig2 = getShellConfiguration();
        if (hookConfig.shell) {
          const shellType = hookConfig.shell === "powershell" ? "powershell" : "bash";
          if (shellType === "powershell") {
            return {
              shell: "powershell",
              executable: "powershell",
              argsPrefix: ["-Command"]
            };
          }
          return {
            shell: "bash",
            executable: globalConfig2.shell === "bash" ? globalConfig2.executable : "bash",
            argsPrefix: ["-c"]
          };
        }
        return globalConfig2;
      }
      /**
       * Execute a command hook asynchronously (non-blocking)
       */
      async executeAsyncHook(hookConfig, eventName, input, signal) {
        const hookId = generateHookId();
        const hookName = hookConfig.name || hookConfig.command || "async-hook";
        if (!this.asyncRegistry.canAcceptMore()) {
          debugLogger77.warn(`Async hook rejected due to concurrency limit: ${hookName}`);
          return {
            hookConfig,
            eventName,
            success: false,
            duration: 0,
            isAsync: true,
            error: new Error("Async hook rejected: too many concurrent async hooks running"),
            output: { continue: true }
            // Non-blocking, continue execution
          };
        }
        const registeredId = this.asyncRegistry.register({
          hookId,
          hookName,
          hookEvent: eventName,
          sessionId: input.session_id,
          startTime: Date.now(),
          timeout: hookConfig.timeout || DEFAULT_HOOK_TIMEOUT,
          stdout: "",
          stderr: ""
        });
        if (!registeredId) {
          debugLogger77.warn(`Async hook registration failed due to concurrency limit: ${hookName}`);
          return {
            hookConfig,
            eventName,
            success: false,
            duration: 0,
            isAsync: true,
            error: new Error("Async hook rejected: too many concurrent async hooks running"),
            output: { continue: true }
          };
        }
        this.executeCommandHookInBackground(hookConfig, eventName, input, hookId, signal).catch((error40) => {
          debugLogger77.error(`Unexpected error in async hook background execution: ${hookId} (${hookName}): ${error40 instanceof Error ? error40.message : String(error40)}`);
          try {
            this.asyncRegistry.fail(hookId, error40 instanceof Error ? error40 : new Error(`Unexpected error: ${String(error40)}`));
          } catch (registryError) {
            debugLogger77.error(`Failed to update async registry for hook ${hookId}: ${registryError}`);
          }
        });
        debugLogger77.debug(`Started async hook: ${hookId} (${hookName})`);
        return {
          hookConfig,
          eventName,
          success: true,
          duration: 0,
          isAsync: true,
          output: { continue: true }
        };
      }
      /**
       * Execute a command hook in the background
       */
      async executeCommandHookInBackground(hookConfig, eventName, input, hookId, signal) {
        const hookName = hookConfig.name || hookConfig.command || "async-hook";
        try {
          debugLogger77.debug(`Executing async hook in background: ${hookId}`);
          const result = await this.executeCommandHook(hookConfig, eventName, input, Date.now(), signal);
          if (result.success) {
            this.asyncRegistry.updateOutput(hookId, result.stdout, result.stderr);
            this.asyncRegistry.complete(hookId, result.output);
            debugLogger77.debug(`Async hook completed successfully: ${hookId} (${hookName})`);
          } else {
            const error40 = result.error || new Error("Unknown error");
            this.asyncRegistry.fail(hookId, error40);
            debugLogger77.warn(`Async hook failed: ${hookId} (${hookName}): ${error40.message}`);
          }
        } catch (error40) {
          const errorObj = error40 instanceof Error ? error40 : new Error(String(error40));
          this.asyncRegistry.fail(hookId, errorObj);
          debugLogger77.error(`Async hook threw exception: ${hookId} (${hookName}): ${errorObj.message}`);
          throw error40;
        }
      }
      /**
       * Execute multiple hooks in parallel
       * @param context Optional function hook context (messages, toolUseID)
       */
      async executeHooksParallel(hookConfigs, eventName, input, onHookStart, onHookEnd, signal, context2) {
        const promises9 = hookConfigs.map(async (config2, index) => {
          onHookStart?.(config2, index);
          const result = await this.executeHook(config2, eventName, input, {
            ...context2,
            signal
          });
          onHookEnd?.(config2, result);
          return result;
        });
        return Promise.all(promises9);
      }
      /**
       * Execute multiple hooks sequentially
       * @param context Optional function hook context (messages, toolUseID)
       */
      async executeHooksSequential(hookConfigs, eventName, input, onHookStart, onHookEnd, signal, context2) {
        const results = [];
        let currentInput = input;
        for (let i4 = 0; i4 < hookConfigs.length; i4++) {
          if (signal?.aborted) {
            break;
          }
          const config2 = hookConfigs[i4];
          onHookStart?.(config2, i4);
          const result = await this.executeHook(config2, eventName, currentInput, {
            ...context2,
            signal
          });
          onHookEnd?.(config2, result);
          results.push(result);
          if (result.success && result.output) {
            currentInput = this.applyHookOutputToInput(currentInput, result.output, eventName);
          }
        }
        return results;
      }
      /**
       * Apply hook output to modify input for the next hook in sequential execution
       */
      applyHookOutputToInput(originalInput, hookOutput, eventName) {
        const modifiedInput = { ...originalInput };
        if (hookOutput.hookSpecificOutput) {
          switch (eventName) {
            case HookEventName.UserPromptSubmit:
              if ("additionalContext" in hookOutput.hookSpecificOutput) {
                const additionalContext = hookOutput.hookSpecificOutput["additionalContext"];
                if (typeof additionalContext === "string" && "prompt" in modifiedInput) {
                  modifiedInput.prompt += "\n\n" + additionalContext;
                }
              }
              break;
            case HookEventName.PreToolUse:
              if ("tool_input" in hookOutput.hookSpecificOutput) {
                const newToolInput = hookOutput.hookSpecificOutput["tool_input"];
                if (newToolInput && "tool_input" in modifiedInput) {
                  modifiedInput.tool_input = {
                    ...modifiedInput.tool_input,
                    ...newToolInput
                  };
                }
              }
              break;
            default:
              break;
          }
        }
        return modifiedInput;
      }
      /**
       * Execute a command hook
       * @param hookConfig Hook configuration
       * @param eventName Event name
       * @param input Hook input
       * @param startTime Start time for duration calculation
       * @param signal Optional AbortSignal to cancel hook execution
       */
      async executeCommandHook(hookConfig, eventName, input, startTime, signal) {
        const timeout2 = hookConfig.timeout ?? DEFAULT_HOOK_TIMEOUT;
        return new Promise((resolve42) => {
          if (!hookConfig.command) {
            const errorMessage = "Command hook missing command";
            debugLogger77.warn(`Hook configuration error (non-fatal): ${errorMessage}`);
            resolve42({
              hookConfig,
              eventName,
              success: false,
              error: new Error(errorMessage),
              duration: Date.now() - startTime
            });
            return;
          }
          let stdout2 = "";
          let stderr = "";
          let timedOut = false;
          let aborted2 = false;
          const shellConfig = this.getShellConfigForHook(hookConfig);
          const command2 = this.expandCommand(hookConfig.command, input, shellConfig.shell);
          const env6 = {
            ...process.env,
            GEMINI_PROJECT_DIR: input.cwd,
            CLAUDE_PROJECT_DIR: input.cwd,
            // For compatibility
            QWEN_PROJECT_DIR: input.cwd,
            // For Qwen Code compatibility
            ...hookConfig.env
          };
          const child = spawn5(shellConfig.executable, [...shellConfig.argsPrefix, command2], {
            env: env6,
            cwd: input.cwd,
            stdio: ["pipe", "pipe", "pipe"],
            shell: false
          });
          const killChild = /* @__PURE__ */ __name(() => {
            if (!child.killed) {
              child.kill("SIGTERM");
              setTimeout(() => {
                if (!child.killed) {
                  child.kill("SIGKILL");
                }
              }, 2e3);
            }
          }, "killChild");
          const timeoutHandle = setTimeout(() => {
            timedOut = true;
            killChild();
          }, timeout2);
          const abortHandler = /* @__PURE__ */ __name(() => {
            aborted2 = true;
            clearTimeout(timeoutHandle);
            killChild();
          }, "abortHandler");
          if (signal) {
            signal.addEventListener("abort", abortHandler);
          }
          if (child.stdin) {
            child.stdin.on("error", (err2) => {
              if (err2.code !== "EPIPE") {
                debugLogger77.debug(`Hook stdin error: ${err2}`);
              }
            });
            try {
              child.stdin.write(JSON.stringify(input));
              child.stdin.end();
            } catch (err2) {
              if (err2 instanceof Error && "code" in err2 && err2.code !== "EPIPE") {
                debugLogger77.debug(`Hook stdin write error: ${err2}`);
              }
            }
          }
          child.stdout?.on("data", (data) => {
            if (stdout2.length < MAX_OUTPUT_LENGTH2) {
              const remaining = MAX_OUTPUT_LENGTH2 - stdout2.length;
              stdout2 += data.slice(0, remaining).toString();
              if (data.length > remaining) {
                debugLogger77.warn(`Hook stdout exceeded max length (${MAX_OUTPUT_LENGTH2} bytes), truncating`);
              }
            }
          });
          child.stderr?.on("data", (data) => {
            if (stderr.length < MAX_OUTPUT_LENGTH2) {
              const remaining = MAX_OUTPUT_LENGTH2 - stderr.length;
              stderr += data.slice(0, remaining).toString();
              if (data.length > remaining) {
                debugLogger77.warn(`Hook stderr exceeded max length (${MAX_OUTPUT_LENGTH2} bytes), truncating`);
              }
            }
          });
          child.on("close", (exitCode) => {
            clearTimeout(timeoutHandle);
            if (signal) {
              signal.removeEventListener("abort", abortHandler);
            }
            const duration3 = Date.now() - startTime;
            if (aborted2) {
              resolve42({
                hookConfig,
                eventName,
                success: false,
                error: new Error("Hook execution cancelled (aborted)"),
                stdout: stdout2,
                stderr,
                duration: duration3
              });
              return;
            }
            if (timedOut) {
              resolve42({
                hookConfig,
                eventName,
                success: false,
                error: new Error(`Hook timed out after ${timeout2}ms`),
                stdout: stdout2,
                stderr,
                duration: duration3
              });
              return;
            }
            let output;
            const isBlockingError = exitCode === 2;
            const textToParse = isBlockingError ? stderr.trim() : stdout2.trim() || stderr.trim();
            if (textToParse) {
              try {
                let parsed = JSON.parse(textToParse);
                if (typeof parsed === "string") {
                  parsed = JSON.parse(parsed);
                }
                if (parsed && typeof parsed === "object") {
                  output = parsed;
                }
              } catch {
                output = this.convertPlainTextToHookOutput(textToParse, isBlockingError ? exitCode : exitCode || EXIT_CODE_SUCCESS);
              }
            }
            const killedBySignal = exitCode === null;
            resolve42({
              hookConfig,
              eventName,
              success: exitCode === EXIT_CODE_SUCCESS,
              output,
              stdout: stdout2,
              stderr,
              exitCode: exitCode ?? -1,
              duration: duration3,
              ...killedBySignal && {
                error: new Error("Hook killed by signal")
              }
            });
          });
          child.on("error", (error40) => {
            clearTimeout(timeoutHandle);
            if (signal) {
              signal.removeEventListener("abort", abortHandler);
            }
            const duration3 = Date.now() - startTime;
            resolve42({
              hookConfig,
              eventName,
              success: false,
              error: error40,
              stdout: stdout2,
              stderr,
              duration: duration3
            });
          });
        });
      }
      /**
       * Expand command with environment variables and input context
       */
      expandCommand(command2, input, shellType) {
        debugLogger77.debug(`Expanding hook command: ${command2} (cwd: ${input.cwd})`);
        const escapedCwd = escapeShellArg(input.cwd, shellType);
        return command2.replace(/\$GEMINI_PROJECT_DIR/g, () => escapedCwd).replace(/\$CLAUDE_PROJECT_DIR/g, () => escapedCwd);
      }
      /**
       * Convert plain text output to structured HookOutput
       */
      convertPlainTextToHookOutput(text, exitCode) {
        if (exitCode === EXIT_CODE_SUCCESS) {
          return {
            decision: "allow",
            reason: "Hook executed successfully",
            systemMessage: text
          };
        } else if (exitCode === EXIT_CODE_NON_BLOCKING_ERROR) {
          return {
            decision: "allow",
            reason: `Non-blocking error: ${text}`,
            systemMessage: `Warning: ${text}`
          };
        } else {
          return {
            decision: "deny",
            reason: text
          };
        }
      }
    };
  }
});

// packages/core/dist/src/hooks/hookAggregator.js
var HookAggregator;
var init_hookAggregator = __esm({
  "packages/core/dist/src/hooks/hookAggregator.js"() {
    "use strict";
    init_esbuild_shims();
    init_types6();
    HookAggregator = class {
      static {
        __name(this, "HookAggregator");
      }
      /**
       * Aggregate results from multiple hook executions
       */
      aggregateResults(results, eventName) {
        if (eventName === HookEventName.StopFailure) {
          let totalDuration2 = 0;
          for (const result of results) {
            totalDuration2 += result.duration;
          }
          return {
            success: true,
            // Always return success
            allOutputs: [],
            errors: [],
            // Ignore errors
            totalDuration: totalDuration2,
            finalOutput: void 0
          };
        }
        const allOutputs = [];
        const errors = [];
        let totalDuration = 0;
        for (const result of results) {
          totalDuration += result.duration;
          if (!result.success && result.error) {
            errors.push(result.error);
          }
          if (result.output) {
            allOutputs.push(result.output);
          }
        }
        const success2 = errors.length === 0;
        const finalOutput = this.mergeOutputs(allOutputs, eventName);
        return {
          success: success2,
          allOutputs,
          errors,
          totalDuration,
          finalOutput
        };
      }
      /**
       * Merge multiple hook outputs based on event type
       */
      mergeOutputs(outputs, eventName) {
        if (outputs.length === 0) {
          return void 0;
        }
        if (outputs.length === 1) {
          return this.createSpecificHookOutput(outputs[0], eventName);
        }
        let merged;
        switch (eventName) {
          case HookEventName.PreToolUse:
          case HookEventName.PostToolUse:
          case HookEventName.PostToolUseFailure:
          case HookEventName.Stop:
          case HookEventName.UserPromptSubmit:
          case HookEventName.SubagentStop:
            merged = this.mergeWithOrLogic(outputs, eventName);
            break;
          case HookEventName.PermissionRequest:
            merged = this.mergePermissionRequestOutputs(outputs);
            break;
          default:
            merged = this.mergeSimple(outputs);
        }
        return this.createSpecificHookOutput(merged, eventName);
      }
      /**
       * Merge outputs using OR logic for decisions and concatenation for messages.
       *
       * Rules:
       * - Any "block" or "deny" decision results in blocking (most restrictive wins)
       * - Reasons are concatenated with newlines
       * - continue=false takes precedence over continue=true
       * - Additional context is concatenated
       * - For PostToolUse, decision and reason are required fields
       */
      mergeWithOrLogic(outputs, _eventName) {
        const merged = {};
        const reasons = [];
        const additionalContexts = [];
        let hasBlock = false;
        let hasContinueFalse = false;
        let stopReason;
        const otherHookSpecificFields = {};
        for (const output of outputs) {
          if (output.decision === "block" || output.decision === "deny") {
            hasBlock = true;
          }
          if (output.reason) {
            reasons.push(output.reason);
          }
          if (output.continue === false) {
            hasContinueFalse = true;
            if (output.stopReason) {
              stopReason = output.stopReason;
            }
          }
          this.extractAdditionalContext(output, additionalContexts);
          if (output.hookSpecificOutput) {
            for (const [key, value] of Object.entries(output.hookSpecificOutput)) {
              if (key !== "additionalContext") {
                otherHookSpecificFields[key] = value;
              }
            }
          }
          if (output.suppressOutput !== void 0) {
            merged.suppressOutput = output.suppressOutput;
          }
          if (output.systemMessage !== void 0) {
            merged.systemMessage = output.systemMessage;
          }
        }
        if (hasBlock) {
          merged.decision = "block";
        } else if (outputs.some((o3) => o3.decision === "allow")) {
          merged.decision = "allow";
        }
        if (reasons.length > 0) {
          merged.reason = reasons.join("\n");
        }
        if (hasContinueFalse) {
          merged.continue = false;
          if (stopReason) {
            merged.stopReason = stopReason;
          }
        }
        const hookSpecificOutput = {
          ...otherHookSpecificFields
        };
        if (additionalContexts.length > 0) {
          hookSpecificOutput["additionalContext"] = additionalContexts.join("\n");
        }
        if (Object.keys(hookSpecificOutput).length > 0) {
          merged.hookSpecificOutput = hookSpecificOutput;
        }
        return merged;
      }
      /**
       * Merge outputs for mergePermissionRequestOutputs events.
       *
       * Rules:
       * - behavior: deny wins over allow (security priority)
       * - message: concatenated with newlines
       * - updatedInput: later values win
       * - updatedPermissions: concatenated
       * - interrupt: true wins over false
       */
      mergePermissionRequestOutputs(outputs) {
        const merged = {};
        const messages = [];
        let hasDeny = false;
        let hasAllow = false;
        let interrupt = false;
        let updatedInput;
        const allUpdatedPermissions = [];
        for (const output of outputs) {
          const specific = output.hookSpecificOutput;
          if (!specific)
            continue;
          const decision = specific["decision"];
          if (!decision)
            continue;
          if (decision["behavior"] === "deny") {
            hasDeny = true;
          } else if (decision["behavior"] === "allow") {
            hasAllow = true;
          }
          if (decision["message"]) {
            messages.push(decision["message"]);
          }
          if (decision["interrupt"] === true) {
            interrupt = true;
          }
          if (decision["updatedInput"]) {
            updatedInput = decision["updatedInput"];
          }
          if (decision["updatedPermissions"]) {
            allUpdatedPermissions.push(...decision["updatedPermissions"]);
          }
          if (output.continue !== void 0) {
            merged.continue = output.continue;
          }
          if (output.reason !== void 0) {
            merged.reason = output.reason;
          }
        }
        const mergedDecision = {};
        if (hasDeny) {
          mergedDecision["behavior"] = "deny";
        } else if (hasAllow) {
          mergedDecision["behavior"] = "allow";
        }
        if (messages.length > 0) {
          mergedDecision["message"] = messages.join("\n");
        }
        if (interrupt) {
          mergedDecision["interrupt"] = true;
        }
        if (updatedInput) {
          mergedDecision["updatedInput"] = updatedInput;
        }
        if (allUpdatedPermissions.length > 0) {
          mergedDecision["updatedPermissions"] = allUpdatedPermissions;
        }
        merged.hookSpecificOutput = {
          ...merged.hookSpecificOutput,
          decision: mergedDecision
        };
        return merged;
      }
      /**
       * Simple merge for events without special logic
       */
      mergeSimple(outputs) {
        const additionalContexts = [];
        let merged = {};
        for (const output of outputs) {
          this.extractAdditionalContext(output, additionalContexts);
          merged = { ...merged, ...output };
        }
        if (additionalContexts.length > 0) {
          merged.hookSpecificOutput = {
            ...merged.hookSpecificOutput,
            additionalContext: additionalContexts.join("\n")
          };
        }
        return merged;
      }
      /**
       * Create the appropriate specific hook output class based on event type
       */
      createSpecificHookOutput(output, eventName) {
        switch (eventName) {
          case HookEventName.PreToolUse:
            return new PreToolUseHookOutput(output);
          case HookEventName.PostToolUse:
            return new PostToolUseHookOutput(output);
          case HookEventName.PostToolUseFailure:
            return new PostToolUseFailureHookOutput(output);
          case HookEventName.Stop:
          case HookEventName.SubagentStop:
            return new StopHookOutput(output);
          case HookEventName.PermissionRequest:
            return new PermissionRequestHookOutput(output);
          default:
            return new DefaultHookOutput(output);
        }
      }
      /**
       * Extract additional context from hook-specific outputs
       */
      extractAdditionalContext(output, contexts) {
        const specific = output.hookSpecificOutput;
        if (!specific) {
          return;
        }
        if ("additionalContext" in specific && typeof specific["additionalContext"] === "string") {
          contexts.push(specific["additionalContext"]);
        }
      }
    };
  }
});

// packages/core/dist/src/hooks/hookPlanner.js
var debugLogger78, HookPlanner;
var init_hookPlanner = __esm({
  "packages/core/dist/src/hooks/hookPlanner.js"() {
    "use strict";
    init_esbuild_shims();
    init_types6();
    init_debugLogger();
    debugLogger78 = createDebugLogger("TRUSTED_HOOKS");
    HookPlanner = class {
      static {
        __name(this, "HookPlanner");
      }
      hookRegistry;
      constructor(hookRegistry) {
        this.hookRegistry = hookRegistry;
      }
      /**
       * Create execution plan for a hook event
       */
      createExecutionPlan(eventName, context2) {
        const hookEntries = this.hookRegistry.getHooksForEvent(eventName);
        if (hookEntries.length === 0) {
          return null;
        }
        const matchingEntries = hookEntries.filter((entry) => this.matchesContext(entry, eventName, context2));
        if (matchingEntries.length === 0) {
          return null;
        }
        const deduplicatedEntries = this.deduplicateHooks(matchingEntries);
        const hookConfigs = deduplicatedEntries.map((entry) => entry.config);
        const sequential = deduplicatedEntries.some((entry) => entry.sequential === true);
        const plan = {
          eventName,
          hookConfigs,
          sequential
        };
        return plan;
      }
      /**
       * Check if a hook entry matches the given context.
       * Uses explicit event-based dispatch to avoid ambiguity between events
       * that share similar context fields (e.g., SessionStart and SubagentStart
       * both have agentType, but use different matcher semantics).
       */
      matchesContext(entry, eventName, context2) {
        if (!entry.matcher || !context2) {
          return true;
        }
        const matcher = entry.matcher.trim();
        if (matcher === "" || matcher === "*") {
          return true;
        }
        switch (eventName) {
          // Tool events: match against tool name
          case HookEventName.PreToolUse:
          case HookEventName.PostToolUse:
          case HookEventName.PostToolUseFailure:
          case HookEventName.PermissionRequest:
            return context2.toolName ? this.matchesToolName(matcher, context2.toolName) : true;
          // Subagent events: match against agent type
          case HookEventName.SubagentStart:
          case HookEventName.SubagentStop:
            return context2.agentType ? this.matchesAgentType(matcher, context2.agentType) : true;
          // PreCompact: match against trigger
          case HookEventName.PreCompact:
            return context2.trigger ? this.matchesTrigger(matcher, context2.trigger) : true;
          // PostCompact: match against trigger
          case HookEventName.PostCompact:
            return context2.trigger ? this.matchesTrigger(matcher, context2.trigger) : true;
          // StopFailure: match against error type (fieldToMatch: 'error')
          case HookEventName.StopFailure:
            return context2.error ? this.matchesTrigger(matcher, context2.error) : true;
          // Notification: match against notification type
          case HookEventName.Notification:
            return context2.notificationType ? this.matchesNotificationType(matcher, context2.notificationType) : true;
          // SessionStart/SessionEnd: match against source/reason
          case HookEventName.SessionStart:
            return context2.trigger ? this.matchesSessionTrigger(matcher, context2.trigger) : true;
          case HookEventName.SessionEnd:
            return context2.trigger ? this.matchesSessionTrigger(matcher, context2.trigger) : true;
          // Events that don't support matchers: always match
          case HookEventName.UserPromptSubmit:
          case HookEventName.Stop:
          default:
            return true;
        }
      }
      /**
       * Match notification type against matcher pattern
       */
      matchesNotificationType(matcher, notificationType) {
        return matcher === notificationType;
      }
      /**
       * Match session source or end reason against matcher pattern
       */
      matchesSessionTrigger(matcher, trigger) {
        try {
          const regex3 = new RegExp(matcher);
          return regex3.test(trigger);
        } catch (error40) {
          debugLogger78.warn(`Invalid regex in hook matcher "${matcher}" for session trigger "${trigger}", falling back to exact match: ${error40}`);
          return matcher === trigger;
        }
      }
      /**
       * Match tool name against matcher pattern
       */
      matchesToolName(matcher, toolName) {
        try {
          const regex3 = new RegExp(matcher);
          return regex3.test(toolName);
        } catch (error40) {
          debugLogger78.warn(`Invalid regex in hook matcher "${matcher}" for tool "${toolName}", falling back to exact match: ${error40}`);
          return matcher === toolName;
        }
      }
      /**
       * Match trigger/source against matcher pattern
       */
      matchesTrigger(matcher, trigger) {
        return matcher === trigger;
      }
      /**
       * Match agent type against matcher pattern.
       * Supports regex matching, same as tool name matching.
       */
      matchesAgentType(matcher, agentType) {
        try {
          const regex3 = new RegExp(matcher);
          return regex3.test(agentType);
        } catch (error40) {
          debugLogger78.warn(`Invalid regex in hook matcher "${matcher}" for agent type "${agentType}", falling back to exact match: ${error40}`);
          return matcher === agentType;
        }
      }
      /**
       * Deduplicate identical hook configurations
       */
      deduplicateHooks(entries) {
        const seen = /* @__PURE__ */ new Set();
        const deduplicated = [];
        for (const entry of entries) {
          const key = getHookKey(entry.config);
          if (!seen.has(key)) {
            seen.add(key);
            deduplicated.push(entry);
          }
        }
        return deduplicated;
      }
    };
  }
});

// packages/core/dist/src/hooks/hookEventHandler.js
var debugLogger79, HookEventHandler;
var init_hookEventHandler = __esm({
  "packages/core/dist/src/hooks/hookEventHandler.js"() {
    "use strict";
    init_esbuild_shims();
    init_types6();
    init_types6();
    init_debugLogger();
    init_loggers();
    init_types4();
    debugLogger79 = createDebugLogger("TRUSTED_HOOKS");
    HookEventHandler = class {
      static {
        __name(this, "HookEventHandler");
      }
      config;
      hookPlanner;
      hookRunner;
      hookAggregator;
      sessionHooksManager;
      /** Optional provider for conversation history */
      messagesProvider;
      constructor(config2, hookPlanner, hookRunner, hookAggregator, sessionHooksManager, messagesProvider) {
        this.config = config2;
        this.hookPlanner = hookPlanner;
        this.hookRunner = hookRunner;
        this.hookAggregator = hookAggregator;
        this.sessionHooksManager = sessionHooksManager;
        this.messagesProvider = messagesProvider;
      }
      /**
       * Set the messages provider for automatic conversation history passing
       */
      setMessagesProvider(provider) {
        this.messagesProvider = provider;
      }
      /**
       * Get the current messages provider
       */
      getMessagesProvider() {
        return this.messagesProvider;
      }
      /**
       * Fire a UserPromptSubmit event
       * Called by handleHookExecutionRequest - executes hooks directly
       */
      async fireUserPromptSubmitEvent(prompt, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.UserPromptSubmit),
          prompt
        };
        return this.executeHooks(HookEventName.UserPromptSubmit, input, void 0, signal);
      }
      /**
       * Fire a Stop event
       * Called by handleHookExecutionRequest - executes hooks directly
       */
      async fireStopEvent(stopHookActive = false, lastAssistantMessage = "", signal) {
        const input = {
          ...this.createBaseInput(HookEventName.Stop),
          stop_hook_active: stopHookActive,
          last_assistant_message: lastAssistantMessage
        };
        return this.executeHooks(HookEventName.Stop, input, void 0, signal);
      }
      /**
       * Fire a SessionStart event
       * Called when a new session starts or resumes
       */
      async fireSessionStartEvent(source2, model, permissionMode, agentType, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.SessionStart),
          permission_mode: permissionMode ?? PermissionMode.Default,
          source: source2,
          model,
          agent_type: agentType
        };
        return this.executeHooks(HookEventName.SessionStart, input, {
          trigger: source2
        }, signal);
      }
      /**
       * Fire a SessionEnd event
       * Called when a session ends
       */
      async fireSessionEndEvent(reason, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.SessionEnd),
          reason
        };
        return this.executeHooks(HookEventName.SessionEnd, input, {
          trigger: reason
        }, signal);
      }
      /**
       * Fire a PreToolUse event
       * Called before tool execution begins
       */
      async firePreToolUseEvent(toolName, toolInput, toolUseId, permissionMode, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.PreToolUse),
          permission_mode: permissionMode,
          tool_name: toolName,
          tool_input: toolInput,
          tool_use_id: toolUseId
        };
        return this.executeHooks(HookEventName.PreToolUse, input, {
          toolName
        }, signal);
      }
      /**
       * Fire a PostToolUse event
       * Called after successful tool execution
       */
      async firePostToolUseEvent(toolName, toolInput, toolResponse, toolUseId, permissionMode, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.PostToolUse),
          permission_mode: permissionMode,
          tool_name: toolName,
          tool_input: toolInput,
          tool_response: toolResponse,
          tool_use_id: toolUseId
        };
        return this.executeHooks(HookEventName.PostToolUse, input, {
          toolName
        }, signal);
      }
      /**
       * Fire a PostToolUseFailure event
       * Called when tool execution fails
       */
      async firePostToolUseFailureEvent(toolUseId, toolName, toolInput, errorMessage, isInterrupt, permissionMode, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.PostToolUseFailure),
          permission_mode: permissionMode ?? PermissionMode.Default,
          tool_use_id: toolUseId,
          tool_name: toolName,
          tool_input: toolInput,
          error: errorMessage,
          is_interrupt: isInterrupt
        };
        return this.executeHooks(HookEventName.PostToolUseFailure, input, {
          toolName
        }, signal);
      }
      /**
       * Fire a PreCompact event
       * Called before conversation compaction begins
       */
      async firePreCompactEvent(trigger, customInstructions = "", signal) {
        const input = {
          ...this.createBaseInput(HookEventName.PreCompact),
          trigger,
          custom_instructions: customInstructions
        };
        return this.executeHooks(HookEventName.PreCompact, input, {
          trigger
        }, signal);
      }
      /**
       * Fire a Notification event
       */
      async fireNotificationEvent(message, notificationType, title, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.Notification),
          message,
          notification_type: notificationType,
          title
        };
        return this.executeHooks(HookEventName.Notification, input, {
          notificationType
        }, signal);
      }
      /**
       * Fire a PermissionRequest event
       * Called when a permission dialog is about to be shown to the user
       */
      async firePermissionRequestEvent(toolName, toolInput, permissionMode, permissionSuggestions, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.PermissionRequest),
          permission_mode: permissionMode,
          tool_name: toolName,
          tool_input: toolInput,
          permission_suggestions: permissionSuggestions
        };
        return this.executeHooks(HookEventName.PermissionRequest, input, {
          toolName
        }, signal);
      }
      /**
       * Fire a SubagentStart event
       * Called when a subagent is spawned via the Agent tool
       */
      async fireSubagentStartEvent(agentId, agentType, permissionMode, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.SubagentStart),
          permission_mode: permissionMode,
          agent_id: agentId,
          agent_type: agentType
        };
        return this.executeHooks(HookEventName.SubagentStart, input, {
          agentType: String(agentType)
        }, signal);
      }
      /**
       * Fire a SubagentStop event
       * Called when a subagent has finished responding
       */
      async fireSubagentStopEvent(agentId, agentType, agentTranscriptPath, lastAssistantMessage, stopHookActive, permissionMode, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.SubagentStop),
          permission_mode: permissionMode,
          stop_hook_active: stopHookActive,
          agent_id: agentId,
          agent_type: agentType,
          agent_transcript_path: agentTranscriptPath,
          last_assistant_message: lastAssistantMessage
        };
        return this.executeHooks(HookEventName.SubagentStop, input, {
          agentType: String(agentType)
        }, signal);
      }
      /**
       * Fire a StopFailure event
       * Called when an API error ends the turn (instead of Stop)
       * Fire-and-forget: output and exit codes are ignored
       */
      async fireStopFailureEvent(error40, errorDetails, lastAssistantMessage, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.StopFailure),
          error: error40,
          error_details: errorDetails,
          last_assistant_message: lastAssistantMessage
        };
        return this.executeHooks(HookEventName.StopFailure, input, { error: error40 }, signal);
      }
      /**
       * Fire a PostCompact event
       * Called after conversation compaction completes
       */
      async firePostCompactEvent(trigger, compactSummary, signal) {
        const input = {
          ...this.createBaseInput(HookEventName.PostCompact),
          trigger,
          compact_summary: compactSummary
        };
        return this.executeHooks(HookEventName.PostCompact, input, { trigger }, signal);
      }
      /**
       * Execute hooks for a specific event (direct execution without MessageBus)
       * Used as fallback when MessageBus is not available
       */
      async executeHooks(eventName, input, context2, signal) {
        try {
          const plan = this.hookPlanner.createExecutionPlan(eventName, context2);
          const sessionId = input.session_id;
          const targetName = context2?.toolName || "";
          const sessionHooks = sessionId ? this.sessionHooksManager.getMatchingHooks(sessionId, eventName, targetName) : [];
          const registryHookConfigs = plan?.hookConfigs || [];
          const sessionHookConfigs = sessionHooks.map((entry) => entry.config);
          const allHookConfigs = [...registryHookConfigs, ...sessionHookConfigs];
          if (allHookConfigs.length === 0) {
            return {
              success: true,
              allOutputs: [],
              errors: [],
              totalDuration: 0
            };
          }
          const sequential = (plan?.sequential ?? false) || sessionHooks.some((entry) => entry.sequential === true);
          const messages = this.messagesProvider?.();
          const functionContext = {
            messages,
            toolUseID: "tool_use_id" in input ? input.tool_use_id : void 0,
            signal
          };
          const totalHooks = allHookConfigs.length;
          const onHookStart = /* @__PURE__ */ __name((config2, index) => {
            const hookName = this.getHookName(config2);
            debugLogger79.debug(`Hook ${hookName} started for event ${eventName} (${index + 1}/${totalHooks})`);
          }, "onHookStart");
          const onHookEnd = /* @__PURE__ */ __name((config2, result) => {
            const hookName = this.getHookName(config2);
            debugLogger79.debug(`Hook ${hookName} ended for event ${eventName}: ${result.success ? "success" : "failed"}`);
          }, "onHookEnd");
          const results = sequential ? await this.hookRunner.executeHooksSequential(allHookConfigs, eventName, input, onHookStart, onHookEnd, signal, functionContext) : await this.hookRunner.executeHooksParallel(allHookConfigs, eventName, input, onHookStart, onHookEnd, signal, functionContext);
          const aggregated = this.hookAggregator.aggregateResults(results, eventName);
          this.processCommonHookOutputFields(aggregated);
          this.logHookExecution(eventName, input, results, aggregated);
          return aggregated;
        } catch (error40) {
          debugLogger79.error(`Hook event bus error for ${eventName}: ${error40}`);
          return {
            success: false,
            allOutputs: [],
            errors: [error40 instanceof Error ? error40 : new Error(String(error40))],
            totalDuration: 0
          };
        }
      }
      /**
       * Create base hook input with common fields
       */
      createBaseInput(eventName) {
        const transcriptPath = this.config.getTranscriptPath();
        return {
          session_id: this.config.getSessionId(),
          transcript_path: transcriptPath,
          cwd: this.config.getWorkingDir(),
          hook_event_name: eventName,
          timestamp: (/* @__PURE__ */ new Date()).toISOString()
        };
      }
      /**
       * Process common hook output fields centrally
       */
      processCommonHookOutputFields(aggregated) {
        if (!aggregated.finalOutput) {
          return;
        }
        const systemMessage = aggregated.finalOutput.systemMessage;
        if (systemMessage && !aggregated.finalOutput.suppressOutput) {
          debugLogger79.warn(`Hook system message: ${systemMessage}`);
        }
        if (aggregated.finalOutput.continue === false) {
          const stopReason = aggregated.finalOutput.stopReason || aggregated.finalOutput.reason || "No reason provided";
          debugLogger79.debug(`Hook requested to stop execution: ${stopReason}`);
        }
      }
      /**
       * Log hook execution for observability
       */
      logHookExecution(eventName, input, results, aggregated) {
        const failedHooks = results.filter((r5) => !r5.success);
        const successCount = results.length - failedHooks.length;
        const errorCount = failedHooks.length;
        if (errorCount > 0) {
          const failedNames = failedHooks.map((r5) => this.getHookNameFromResult(r5)).join(", ");
          debugLogger79.warn(`Hook(s) [${failedNames}] failed for event ${eventName}. Check debug logs for more details.`);
        } else {
          debugLogger79.debug(`Hook execution for ${eventName}: ${successCount} hooks executed successfully, total duration: ${aggregated.totalDuration}ms`);
        }
        for (const result of results) {
          const hookName = this.getHookNameFromResult(result);
          const hookType = this.getHookTypeFromResult(result);
          const hookCallEvent = new HookCallEvent(eventName, hookType, hookName, { ...input }, result.duration, result.success, result.output ? { ...result.output } : void 0, result.exitCode, result.stdout, result.stderr, result.error?.message);
          logHookCall(this.config, hookCallEvent);
        }
        for (const error40 of aggregated.errors) {
          debugLogger79.warn(`Hook execution error: ${error40.message}`);
        }
      }
      /**
       * Get hook name from config for display or telemetry
       */
      getHookName(config2) {
        if (config2.type === "command") {
          return config2.name || config2.command || "unknown-command";
        }
        return config2.name || "unknown-hook";
      }
      /**
       * Get hook name from execution result for telemetry
       */
      getHookNameFromResult(result) {
        return this.getHookName(result.hookConfig);
      }
      /**
       * Get hook type from execution result for telemetry
       */
      getHookTypeFromResult(result) {
        return result.hookConfig.type;
      }
    };
  }
});

// packages/core/dist/src/hooks/sessionHooksManager.js
function generateHookId2() {
  return `session_hook_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
}
var debugLogger80, SessionHooksManager;
var init_sessionHooksManager = __esm({
  "packages/core/dist/src/hooks/sessionHooksManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_types6();
    debugLogger80 = createDebugLogger("SESSION_HOOKS_MANAGER");
    __name(generateHookId2, "generateHookId");
    SessionHooksManager = class {
      static {
        __name(this, "SessionHooksManager");
      }
      sessions = /* @__PURE__ */ new Map();
      /**
       * Get or create session storage
       */
      getSessionStorage(sessionId) {
        let storage = this.sessions.get(sessionId);
        if (!storage) {
          storage = { hooks: /* @__PURE__ */ new Map() };
          this.sessions.set(sessionId, storage);
        }
        return storage;
      }
      /**
       * Add a function hook for a session
       * @param sessionId Session ID
       * @param event Hook event name
       * @param matcher Matcher pattern (e.g., 'Bash', '*', 'Write|Edit', or regex)
       * @param callback Function callback to execute
       * @param errorMessage Error message to display on failure
       * @param options Additional options
       * @returns Hook ID for later removal
       */
      addFunctionHook(sessionId, event, matcher, callback, errorMessage, options2) {
        const hookId = options2?.id || generateHookId2();
        const config2 = {
          type: HookType.Function,
          id: hookId,
          name: options2?.name,
          description: options2?.description,
          timeout: options2?.timeout,
          callback,
          errorMessage,
          statusMessage: options2?.statusMessage,
          onHookSuccess: options2?.onHookSuccess
        };
        const entry = {
          hookId,
          eventName: event,
          matcher,
          config: config2,
          skillRoot: options2?.skillRoot
        };
        const storage = this.getSessionStorage(sessionId);
        const eventHooks = storage.hooks.get(event) || [];
        eventHooks.push(entry);
        storage.hooks.set(event, eventHooks);
        debugLogger80.debug(`Added function hook ${hookId} for session ${sessionId} on event ${event}`);
        return hookId;
      }
      /**
       * Add a command or HTTP hook for a session
       * @param sessionId Session ID
       * @param event Hook event name
       * @param matcher Matcher pattern
       * @param hook Hook configuration (command or HTTP)
       * @param options Additional options
       */
      addSessionHook(sessionId, event, matcher, hook, options2) {
        const hookId = generateHookId2();
        const entry = {
          hookId,
          eventName: event,
          matcher,
          config: hook,
          sequential: options2?.sequential,
          skillRoot: options2?.skillRoot
        };
        const storage = this.getSessionStorage(sessionId);
        const eventHooks = storage.hooks.get(event) || [];
        eventHooks.push(entry);
        storage.hooks.set(event, eventHooks);
        debugLogger80.debug(`Added session hook ${hookId} for session ${sessionId} on event ${event}`);
        return hookId;
      }
      /**
       * Remove a function hook by ID
       * @param sessionId Session ID
       * @param event Hook event name
       * @param hookId Hook ID to remove
       * @returns True if hook was found and removed
       */
      removeFunctionHook(sessionId, event, hookId) {
        const storage = this.sessions.get(sessionId);
        if (!storage) {
          return false;
        }
        const eventHooks = storage.hooks.get(event);
        if (!eventHooks) {
          return false;
        }
        const index = eventHooks.findIndex((entry) => entry.hookId === hookId);
        if (index === -1) {
          return false;
        }
        eventHooks.splice(index, 1);
        debugLogger80.debug(`Removed hook ${hookId} from session ${sessionId} on event ${event}`);
        return true;
      }
      /**
       * Remove a hook by ID (searches all events)
       * @param sessionId Session ID
       * @param hookId Hook ID to remove
       * @returns True if hook was found and removed
       */
      removeHook(sessionId, hookId) {
        const storage = this.sessions.get(sessionId);
        if (!storage) {
          return false;
        }
        for (const [event, eventHooks] of storage.hooks.entries()) {
          const index = eventHooks.findIndex((entry) => entry.hookId === hookId);
          if (index !== -1) {
            eventHooks.splice(index, 1);
            debugLogger80.debug(`Removed hook ${hookId} from session ${sessionId} on event ${event}`);
            return true;
          }
        }
        return false;
      }
      /**
       * Get all hooks for a session and event
       * @param sessionId Session ID
       * @param event Hook event name
       * @returns Array of session hook entries
       */
      getHooksForEvent(sessionId, event) {
        const storage = this.sessions.get(sessionId);
        if (!storage) {
          return [];
        }
        return storage.hooks.get(event) || [];
      }
      /**
       * Get hooks that match a specific tool/target
       * @param sessionId Session ID
       * @param event Hook event name
       * @param target Target to match (e.g., tool name)
       * @returns Array of matching hook entries
       */
      getMatchingHooks(sessionId, event, target) {
        const hooks = this.getHooksForEvent(sessionId, event);
        return hooks.filter((entry) => this.matchesPattern(entry.matcher, target));
      }
      /**
       * Check if a target matches a pattern
       * Supports: exact match, '*' wildcard, '|' for alternatives, regex syntax
       *
       * Matching priority:
       * 1. '*' - matches everything
       * 2. Pipe-separated alternatives (e.g., 'Write|Edit|Read')
       * 3. Regex syntax (e.g., '^Bash.*', 'Write|Edit')
       * 4. Exact match (fallback)
       */
      matchesPattern(pattern, target) {
        if (pattern === "*") {
          return true;
        }
        if (pattern.includes("|") && !pattern.startsWith("^") && !pattern.startsWith("(")) {
          const alternatives = pattern.split("|").map((s5) => s5.trim());
          return alternatives.some((alt) => this.matchesPattern(alt, target));
        }
        try {
          const regex3 = new RegExp(`^${pattern}$`);
          return regex3.test(target);
        } catch {
          debugLogger80.debug(`Invalid regex pattern "${pattern}", falling back to exact match`);
        }
        return pattern === target;
      }
      /**
       * Check if a session has any hooks registered
       * @param sessionId Session ID
       * @returns True if session has hooks
       */
      hasSessionHooks(sessionId) {
        const storage = this.sessions.get(sessionId);
        if (!storage) {
          return false;
        }
        for (const eventHooks of storage.hooks.values()) {
          if (eventHooks.length > 0) {
            return true;
          }
        }
        return false;
      }
      /**
       * Clear all hooks for a session
       * @param sessionId Session ID
       */
      clearSessionHooks(sessionId) {
        this.sessions.delete(sessionId);
        debugLogger80.debug(`Cleared all hooks for session ${sessionId}`);
      }
      /**
       * Get all session IDs with registered hooks
       */
      getActiveSessions() {
        return Array.from(this.sessions.keys());
      }
      /**
       * Get hook count for a session
       */
      getHookCount(sessionId) {
        const storage = this.sessions.get(sessionId);
        if (!storage) {
          return 0;
        }
        let count = 0;
        for (const eventHooks of storage.hooks.values()) {
          count += eventHooks.length;
        }
        return count;
      }
      /**
       * Get all hooks for a session across all events
       * @param sessionId Session ID
       * @returns Array of all session hook entries
       */
      getAllSessionHooks(sessionId) {
        const storage = this.sessions.get(sessionId);
        if (!storage) {
          return [];
        }
        const allHooks = [];
        for (const eventHooks of storage.hooks.values()) {
          allHooks.push(...eventHooks);
        }
        return allHooks;
      }
    };
  }
});

// packages/core/dist/src/hooks/hookSystem.js
var debugLogger81, HookSystem;
var init_hookSystem = __esm({
  "packages/core/dist/src/hooks/hookSystem.js"() {
    "use strict";
    init_esbuild_shims();
    init_hookRegistry();
    init_hookRunner();
    init_hookAggregator();
    init_hookPlanner();
    init_hookEventHandler();
    init_debugLogger();
    init_types6();
    init_sessionHooksManager();
    debugLogger81 = createDebugLogger("TRUSTED_HOOKS");
    HookSystem = class {
      static {
        __name(this, "HookSystem");
      }
      hookRegistry;
      hookRunner;
      hookAggregator;
      hookPlanner;
      hookEventHandler;
      sessionHooksManager;
      /** Optional provider for automatically fetching conversation history */
      messagesProvider;
      constructor(config2) {
        const allowedHttpUrls = config2.getAllowedHttpHookUrls();
        this.hookRegistry = new HookRegistry(config2);
        this.hookRunner = new HookRunner(allowedHttpUrls);
        this.hookAggregator = new HookAggregator();
        this.hookPlanner = new HookPlanner(this.hookRegistry);
        this.sessionHooksManager = new SessionHooksManager();
        this.hookEventHandler = new HookEventHandler(config2, this.hookPlanner, this.hookRunner, this.hookAggregator, this.sessionHooksManager);
      }
      /**
       * Initialize the hook system
       */
      async initialize() {
        await this.hookRegistry.initialize();
        debugLogger81.debug("Hook system initialized successfully");
      }
      /**
       * Set the messages provider for automatic conversation history passing
       * to function hooks during execution
       */
      setMessagesProvider(provider) {
        this.messagesProvider = provider;
        this.hookEventHandler.setMessagesProvider(provider);
      }
      /**
       * Get the current messages provider
       */
      getMessagesProvider() {
        return this.messagesProvider;
      }
      /**
       * Get the hook event bus for firing events
       */
      getEventHandler() {
        return this.hookEventHandler;
      }
      /**
       * Get hook registry for management operations
       */
      getRegistry() {
        return this.hookRegistry;
      }
      /**
       * Enable or disable a hook
       */
      setHookEnabled(hookName, enabled2) {
        this.hookRegistry.setHookEnabled(hookName, enabled2);
      }
      /**
       * Get all registered hooks for display/management
       */
      getAllHooks() {
        return this.hookRegistry.getAllHooks();
      }
      /**
       * Check if there are any enabled hooks registered for a specific event.
       * This is a fast-path check to avoid expensive MessageBus round-trips
       * when no hooks are configured for a given event.
       */
      hasHooksForEvent(eventName) {
        return this.hookRegistry.getHooksForEvent(eventName).length > 0;
      }
      async fireUserPromptSubmitEvent(prompt, signal) {
        const result = await this.hookEventHandler.fireUserPromptSubmitEvent(prompt, signal);
        return result.finalOutput ? createHookOutput("UserPromptSubmit", result.finalOutput) : void 0;
      }
      async fireStopEvent(stopHookActive = false, lastAssistantMessage = "", signal) {
        return this.hookEventHandler.fireStopEvent(stopHookActive, lastAssistantMessage, signal);
      }
      async fireSessionStartEvent(source2, model, permissionMode, agentType, signal) {
        const result = await this.hookEventHandler.fireSessionStartEvent(source2, model, permissionMode, agentType, signal);
        return result.finalOutput ? createHookOutput("SessionStart", result.finalOutput) : void 0;
      }
      async fireSessionEndEvent(reason, signal) {
        const result = await this.hookEventHandler.fireSessionEndEvent(reason, signal);
        return result.finalOutput ? createHookOutput("SessionEnd", result.finalOutput) : void 0;
      }
      /**
       * Fire a PreToolUse event - called before tool execution
       */
      async firePreToolUseEvent(toolName, toolInput, toolUseId, permissionMode, signal) {
        const result = await this.hookEventHandler.firePreToolUseEvent(toolName, toolInput, toolUseId, permissionMode, signal);
        return result.finalOutput ? createHookOutput("PreToolUse", result.finalOutput) : void 0;
      }
      /**
       * Fire a PostToolUse event - called after successful tool execution
       */
      async firePostToolUseEvent(toolName, toolInput, toolResponse, toolUseId, permissionMode, signal) {
        const result = await this.hookEventHandler.firePostToolUseEvent(toolName, toolInput, toolResponse, toolUseId, permissionMode, signal);
        return result.finalOutput ? createHookOutput("PostToolUse", result.finalOutput) : void 0;
      }
      /**
       * Fire a PostToolUseFailure event - called when tool execution fails
       */
      async firePostToolUseFailureEvent(toolUseId, toolName, toolInput, errorMessage, isInterrupt, permissionMode, signal) {
        const result = await this.hookEventHandler.firePostToolUseFailureEvent(toolUseId, toolName, toolInput, errorMessage, isInterrupt, permissionMode, signal);
        return result.finalOutput ? createHookOutput("PostToolUseFailure", result.finalOutput) : void 0;
      }
      /**
       * Fire a PreCompact event - called before conversation compaction
       */
      async firePreCompactEvent(trigger, customInstructions = "", signal) {
        const result = await this.hookEventHandler.firePreCompactEvent(trigger, customInstructions, signal);
        return result.finalOutput ? createHookOutput("PreCompact", result.finalOutput) : void 0;
      }
      /**
       * Fire a Notification event
       */
      async fireNotificationEvent(message, notificationType, title, signal) {
        const result = await this.hookEventHandler.fireNotificationEvent(message, notificationType, title, signal);
        return result.finalOutput ? createHookOutput("Notification", result.finalOutput) : void 0;
      }
      /**
       * Fire a SubagentStart event - called when a subagent is spawned
       */
      async fireSubagentStartEvent(agentId, agentType, permissionMode, signal) {
        const result = await this.hookEventHandler.fireSubagentStartEvent(agentId, agentType, permissionMode, signal);
        return result.finalOutput ? createHookOutput("SubagentStart", result.finalOutput) : void 0;
      }
      /**
       * Fire a SubagentStop event - called when a subagent finishes
       */
      async fireSubagentStopEvent(agentId, agentType, agentTranscriptPath, lastAssistantMessage, stopHookActive, permissionMode, signal) {
        const result = await this.hookEventHandler.fireSubagentStopEvent(agentId, agentType, agentTranscriptPath, lastAssistantMessage, stopHookActive, permissionMode, signal);
        return result.finalOutput ? createHookOutput("SubagentStop", result.finalOutput) : void 0;
      }
      /**
       * Fire a StopFailure event - called when an API error ends the turn
       * Fire-and-forget: output and exit codes are ignored
       */
      async fireStopFailureEvent(error40, errorDetails, lastAssistantMessage, signal) {
        return this.hookEventHandler.fireStopFailureEvent(error40, errorDetails, lastAssistantMessage, signal);
      }
      /**
       * Fire a PostCompact event - called after conversation compaction completes
       */
      async firePostCompactEvent(trigger, compactSummary, signal) {
        const result = await this.hookEventHandler.firePostCompactEvent(trigger, compactSummary, signal);
        return result.finalOutput ? createHookOutput("PostCompact", result.finalOutput) : void 0;
      }
      /**
       * Fire a PermissionRequest event
       */
      async firePermissionRequestEvent(toolName, toolInput, permissionMode, permissionSuggestions, signal) {
        const result = await this.hookEventHandler.firePermissionRequestEvent(toolName, toolInput, permissionMode, permissionSuggestions, signal);
        return result.finalOutput ? createHookOutput("PermissionRequest", result.finalOutput) : void 0;
      }
      // ==================== Session Hooks API ====================
      /**
       * Add a function hook for a session
       * @param sessionId Session ID
       * @param event Hook event name
       * @param matcher Matcher pattern (e.g., 'Bash', '*', 'Write|Edit', or regex)
       * @param callback Function callback to execute
       * @param errorMessage Error message to display on failure
       * @param options Additional options
       * @returns Hook ID for later removal
       */
      addFunctionHook(sessionId, event, matcher, callback, errorMessage, options2) {
        return this.sessionHooksManager.addFunctionHook(sessionId, event, matcher, callback, errorMessage, options2);
      }
      /**
       * Add a command or HTTP hook for a session
       * @param sessionId Session ID
       * @param event Hook event name
       * @param matcher Matcher pattern
       * @param hook Hook configuration (command or HTTP)
       * @param options Additional options
       * @returns Hook ID
       */
      addSessionHook(sessionId, event, matcher, hook, options2) {
        return this.sessionHooksManager.addSessionHook(sessionId, event, matcher, hook, options2);
      }
      /**
       * Remove a function hook by ID
       * @param sessionId Session ID
       * @param event Hook event name
       * @param hookId Hook ID to remove
       * @returns True if hook was found and removed
       */
      removeFunctionHook(sessionId, event, hookId) {
        return this.sessionHooksManager.removeFunctionHook(sessionId, event, hookId);
      }
      /**
       * Remove a hook by ID (searches all events)
       * @param sessionId Session ID
       * @param hookId Hook ID to remove
       * @returns True if hook was found and removed
       */
      removeSessionHook(sessionId, hookId) {
        return this.sessionHooksManager.removeHook(sessionId, hookId);
      }
      /**
       * Check if a session has any hooks registered
       * @param sessionId Session ID
       * @returns True if session has hooks
       */
      hasSessionHooks(sessionId) {
        return this.sessionHooksManager.hasSessionHooks(sessionId);
      }
      /**
       * Clear all hooks for a session
       * @param sessionId Session ID
       */
      clearSessionHooks(sessionId) {
        this.sessionHooksManager.clearSessionHooks(sessionId);
        this.getAsyncRegistry().clearSession(sessionId);
      }
      /**
       * Get the session hooks manager
       */
      getSessionHooksManager() {
        return this.sessionHooksManager;
      }
      // ==================== Async Hooks API ====================
      /**
       * Get the async hook registry
       */
      getAsyncRegistry() {
        return this.hookRunner.getAsyncRegistry();
      }
      /**
       * Get all pending async hooks
       */
      getPendingAsyncHooks() {
        return this.getAsyncRegistry().getPendingHooks();
      }
      /**
       * Get pending async hooks for a specific session
       */
      getPendingAsyncHooksForSession(sessionId) {
        return this.getAsyncRegistry().getPendingHooksForSession(sessionId);
      }
      /**
       * Get and clear pending async output for delivery to the next turn
       */
      getPendingAsyncOutput() {
        return this.getAsyncRegistry().getPendingOutput();
      }
      /**
       * Check if there are any pending async outputs
       */
      hasPendingAsyncOutput() {
        return this.getAsyncRegistry().hasPendingOutput();
      }
      /**
       * Check if there are any running async hooks
       */
      hasRunningAsyncHooks() {
        return this.getAsyncRegistry().hasRunningHooks();
      }
      /**
       * Check for timed out async hooks and mark them
       */
      checkAsyncHookTimeouts() {
        this.getAsyncRegistry().checkTimeouts();
      }
      /**
       * Update allowed HTTP hook URLs
       */
      updateAllowedHttpUrls(allowedUrls) {
        this.hookRunner.updateAllowedHttpUrls(allowedUrls);
      }
    };
  }
});

// packages/core/dist/src/hooks/registerSkillHooks.js
function registerSkillHooks(sessionHooksManager, sessionId, skill) {
  if (!skill.hooks) {
    debugLogger82.debug(`Skill '${skill.name}' has no hooks to register`);
    return 0;
  }
  const hooksSettings = skill.hooks;
  let registeredCount = 0;
  for (const eventName of Object.keys(hooksSettings)) {
    const matchers = hooksSettings[eventName];
    if (!matchers)
      continue;
    for (const matcher of matchers) {
      const matcherPattern = matcher.matcher || "";
      for (const hook of matcher.hooks) {
        if (hook.type === HookType.Function) {
          debugLogger82.debug("Skipping function hook from skill (not supported in frontmatter)");
          continue;
        }
        const hookConfig = prepareHookConfig(hook, skill.skillRoot);
        sessionHooksManager.addSessionHook(sessionId, eventName, matcherPattern, hookConfig, { skillRoot: skill.skillRoot });
        registeredCount++;
        debugLogger82.debug(`Registered hook for ${eventName} with matcher '${matcherPattern}' from skill '${skill.name}'`);
      }
    }
  }
  if (registeredCount > 0) {
    debugLogger82.info(`Registered ${registeredCount} hooks from skill '${skill.name}'`);
  }
  return registeredCount;
}
function prepareHookConfig(hook, skillRoot) {
  if (hook.type === "command" && skillRoot) {
    return {
      ...hook,
      env: {
        ...hook.env,
        QWEN_SKILL_ROOT: skillRoot
      }
    };
  }
  return hook;
}
var debugLogger82;
var init_registerSkillHooks = __esm({
  "packages/core/dist/src/hooks/registerSkillHooks.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_types6();
    debugLogger82 = createDebugLogger("SKILL_HOOKS");
    __name(registerSkillHooks, "registerSkillHooks");
    __name(prepareHookConfig, "prepareHookConfig");
  }
});

// packages/core/dist/src/hooks/index.js
var init_hooks = __esm({
  "packages/core/dist/src/hooks/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_types6();
    init_hookSystem();
    init_hookRegistry();
    init_hookRunner();
    init_hookAggregator();
    init_hookPlanner();
    init_hookEventHandler();
    init_httpHookRunner();
    init_functionHookRunner();
    init_sessionHooksManager();
    init_asyncHookRegistry();
    init_registerSkillHooks();
    init_envInterpolator();
    init_urlValidator();
    init_types6();
  }
});

// packages/core/dist/src/confirmation-bus/message-bus.js
import { randomUUID as randomUUID6 } from "node:crypto";
import { EventEmitter as EventEmitter8 } from "node:events";
var debugLogger83, MessageBus;
var init_message_bus = __esm({
  "packages/core/dist/src/confirmation-bus/message-bus.js"() {
    "use strict";
    init_esbuild_shims();
    init_types8();
    init_safeJsonStringify();
    init_debugLogger();
    debugLogger83 = createDebugLogger("TRUSTED_HOOKS");
    MessageBus = class extends EventEmitter8 {
      static {
        __name(this, "MessageBus");
      }
      debug;
      constructor(debug3 = false) {
        super();
        this.debug = debug3;
        this.debug = debug3;
      }
      isValidMessage(message) {
        if (!message || !message.type) {
          return false;
        }
        if (message.type === MessageBusType.TOOL_CONFIRMATION_REQUEST && !("correlationId" in message)) {
          return false;
        }
        return true;
      }
      emitMessage(message) {
        this.emit(message.type, message);
      }
      async publish(message) {
        if (this.debug) {
          debugLogger83.debug(`[MESSAGE_BUS] publish: ${safeJsonStringify(message)}`);
        }
        try {
          if (!this.isValidMessage(message)) {
            throw new Error(`Invalid message structure: ${safeJsonStringify(message)}`);
          }
          if (message.type === MessageBusType.TOOL_CONFIRMATION_REQUEST) {
            this.emitMessage({
              type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
              correlationId: message.correlationId,
              confirmed: true
            });
          } else if (message.type === MessageBusType.HOOK_EXECUTION_REQUEST) {
            this.emitMessage(message);
          } else {
            this.emitMessage(message);
          }
        } catch (error40) {
          this.emit("error", error40);
        }
      }
      subscribe(type, listener) {
        this.on(type, listener);
      }
      unsubscribe(type, listener) {
        this.off(type, listener);
      }
      /**
       * Request-response pattern: Publish a message and wait for a correlated response
       * This enables synchronous-style communication over the async MessageBus
       * The correlation ID is generated internally and added to the request
       */
      async request(request4, responseType, timeoutMs = 6e4, signal) {
        const correlationId = randomUUID6();
        return new Promise((resolve42, reject) => {
          if (signal?.aborted) {
            reject(new Error("Request aborted"));
            return;
          }
          const timeoutId = setTimeout(() => {
            cleanup();
            reject(new Error(`Request timed out waiting for ${responseType}`));
          }, timeoutMs);
          const cleanup = /* @__PURE__ */ __name(() => {
            clearTimeout(timeoutId);
            this.unsubscribe(responseType, responseHandler);
            if (signal) {
              signal.removeEventListener("abort", abortHandler);
            }
          }, "cleanup");
          const abortHandler = /* @__PURE__ */ __name(() => {
            cleanup();
            reject(new Error("Request aborted"));
          }, "abortHandler");
          if (signal) {
            signal.addEventListener("abort", abortHandler);
          }
          const responseHandler = /* @__PURE__ */ __name((response) => {
            if ("correlationId" in response && response.correlationId === correlationId) {
              cleanup();
              resolve42(response);
            }
          }, "responseHandler");
          this.subscribe(responseType, responseHandler);
          this.publish({ ...request4, correlationId });
        });
      }
    };
  }
});

// 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/proxyUtils.js
function normalizeProxyUrl(proxyUrl) {
  if (!proxyUrl) {
    return void 0;
  }
  const trimmed2 = proxyUrl.trim();
  if (!trimmed2) {
    return void 0;
  }
  if (/^https?:\/\//i.test(trimmed2)) {
    return trimmed2;
  }
  if (/^socks[45]?:\/\//i.test(trimmed2)) {
    throw new Error(`SOCKS proxy is not supported. The underlying HTTP client (undici) only supports HTTP and HTTPS proxies. Please use an HTTP/HTTPS proxy instead, or set up a SOCKS-to-HTTP proxy converter. See: https://github.com/nodejs/undici/issues/2224`);
  }
  return `http://${trimmed2}`;
}
var init_proxyUtils = __esm({
  "packages/core/dist/src/utils/proxyUtils.js"() {
    "use strict";
    init_esbuild_shims();
    __name(normalizeProxyUrl, "normalizeProxyUrl");
  }
});

// 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((name4, val) => {
      let valSource = typeof val === "string" ? val : val.source;
      valSource = valSource.replace(other.caret, "$1");
      source2 = source2.replace(name4, valSource);
      return obj;
    }, "replace"),
    getRegex: /* @__PURE__ */ __name(() => {
      return new RegExp(source2, opt);
    }, "getRegex")
  };
  return obj;
}
function escape22(html2, encode6) {
  if (encode6) {
    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 i4 = 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 (; i4 < cells.length; i4++) {
    cells[i4] = cells[i4].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 i4 = 0; i4 < str2.length; i4++) {
    if (str2[i4] === "\\") {
      i4++;
    } else if (str2[i4] === b2[0]) {
      level++;
    } else if (str2[i4] === b2[1]) {
      level--;
      if (level < 0) {
        return i4;
      }
    }
  }
  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, escape3, 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, _Parser2, _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()
    };
    escape3 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
    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: escape3,
      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 i4;
            for (i4 = 0; i4 < lines.length; i4++) {
              if (this.rules.other.blockquoteStart.test(lines[i4])) {
                currentLines.push(lines[i4]);
                inBlockquote = true;
              } else if (!inBlockquote) {
                currentLines.push(lines[i4]);
              } else {
                break;
              }
            }
            lines = lines.slice(i4);
            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 i4 = 0; i4 < list22.items.length; i4++) {
            this.lexer.state.top = false;
            list22.items[i4].tokens = this.lexer.blockTokens(list22.items[i4].text, []);
            if (!list22.loose) {
              const spacers = list22.items[i4].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 i4 = 0; i4 < list22.items.length; i4++) {
              list22.items[i4].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 i4 = 0; i4 < headers.length; i4++) {
          item.header.push({
            text: headers[i4],
            tokens: this.lexer.inline(headers[i4]),
            header: true,
            align: item.align[i4]
          });
        }
        for (const row of rows) {
          item.rows.push(splitCells(row, item.header.length).map((cell, i4) => {
            return {
              text: cell,
              tokens: this.lexer.inline(cell),
              header: false,
              align: item.align[i4]
            };
          }));
        }
        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 start2 = cap[0].indexOf("!") === 0 ? 5 : 4;
              const linkLen = start2 + 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 i4 = 0; i4 < this.inlineQueue.length; i4++) {
          const next = this.inlineQueue[i4];
          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 body2 = this.parser.parse(tokens);
        return `<blockquote>
${body2}</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 start2 = token2.start;
        let body2 = "";
        for (let j2 = 0; j2 < token2.items.length; j2++) {
          const item = token2.items[j2];
          body2 += this.listitem(item);
        }
        const type = ordered ? "ol" : "ul";
        const startAttr = ordered && start2 !== 1 ? ' start="' + start2 + '"' : "";
        return "<" + type + startAttr + ">\n" + body2 + "</" + 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 body2 = "";
        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]);
          }
          body2 += this.tablerow({ text: cell });
        }
        if (body2) body2 = `<tbody>${body2}</tbody>`;
        return "<table>\n<thead>\n" + header + "</thead>\n" + body2 + "</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 out2 = '<a href="' + href + '"';
        if (title) {
          out2 += ' title="' + escape22(title) + '"';
        }
        out2 += ">" + text + "</a>";
        return out2;
      }
      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 out2 = `<img src="${href}" alt="${text}"`;
        if (title) {
          out2 += ` title="${escape22(title)}"`;
        }
        out2 += ">";
        return out2;
      }
      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 "";
      }
    };
    _Parser2 = 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 out2 = "";
        for (let i4 = 0; i4 < tokens.length; i4++) {
          const anyToken = tokens[i4];
          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)) {
              out2 += ret || "";
              continue;
            }
          }
          const token2 = anyToken;
          switch (token2.type) {
            case "space": {
              out2 += this.renderer.space(token2);
              continue;
            }
            case "hr": {
              out2 += this.renderer.hr(token2);
              continue;
            }
            case "heading": {
              out2 += this.renderer.heading(token2);
              continue;
            }
            case "code": {
              out2 += this.renderer.code(token2);
              continue;
            }
            case "table": {
              out2 += this.renderer.table(token2);
              continue;
            }
            case "blockquote": {
              out2 += this.renderer.blockquote(token2);
              continue;
            }
            case "list": {
              out2 += this.renderer.list(token2);
              continue;
            }
            case "html": {
              out2 += this.renderer.html(token2);
              continue;
            }
            case "paragraph": {
              out2 += this.renderer.paragraph(token2);
              continue;
            }
            case "text": {
              let textToken = token2;
              let body2 = this.renderer.text(textToken);
              while (i4 + 1 < tokens.length && tokens[i4 + 1].type === "text") {
                textToken = tokens[++i4];
                body2 += "\n" + this.renderer.text(textToken);
              }
              if (top2) {
                out2 += this.renderer.paragraph({
                  type: "paragraph",
                  raw: body2,
                  text: body2,
                  tokens: [{ type: "text", raw: body2, text: body2, escaped: true }]
                });
              } else {
                out2 += body2;
              }
              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 out2;
      }
      /**
       * Parse Inline Tokens
       */
      parseInline(tokens, renderer2 = this.renderer) {
        let out2 = "";
        for (let i4 = 0; i4 < tokens.length; i4++) {
          const anyToken = tokens[i4];
          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)) {
              out2 += ret || "";
              continue;
            }
          }
          const token2 = anyToken;
          switch (token2.type) {
            case "escape": {
              out2 += renderer2.text(token2);
              break;
            }
            case "html": {
              out2 += renderer2.html(token2);
              break;
            }
            case "link": {
              out2 += renderer2.link(token2);
              break;
            }
            case "image": {
              out2 += renderer2.image(token2);
              break;
            }
            case "strong": {
              out2 += renderer2.strong(token2);
              break;
            }
            case "em": {
              out2 += renderer2.em(token2);
              break;
            }
            case "codespan": {
              out2 += renderer2.codespan(token2);
              break;
            }
            case "br": {
              out2 += renderer2.br(token2);
              break;
            }
            case "del": {
              out2 += renderer2.del(token2);
              break;
            }
            case "text": {
              out2 += 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 out2;
      }
    };
    _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 ? _Parser2.parse : _Parser2.parseInline;
      }
    };
    Marked = class {
      static {
        __name(this, "Marked");
      }
      defaults = _getDefaults();
      options = this.setOptions;
      parse = this.parseMarkdown(true);
      parseInline = this.parseMarkdown(false);
      Parser = _Parser2;
      Renderer = _Renderer;
      TextRenderer = _TextRenderer;
      Lexer = _Lexer;
      Tokenizer = _Tokenizer;
      Hooks = _Hooks;
      constructor(...args2) {
        this.use(...args2);
      }
      /**
       * 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(...args2) {
        const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
        args2.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(...args22) {
                    let ret = ext2.renderer.apply(this, args22);
                    if (ret === false) {
                      ret = prevRenderer.apply(this, args22);
                    }
                    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] = (...args22) => {
                let ret = rendererFunc.apply(renderer2, args22);
                if (ret === false) {
                  ret = prevRenderer.apply(renderer2, args22);
                }
                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] = (...args22) => {
                let ret = tokenizerFunc.apply(tokenizer, args22);
                if (ret === false) {
                  ret = prevTokenizer.apply(tokenizer, args22);
                }
                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] = (...args22) => {
                  let ret = hooksFunc.apply(hooks, args22);
                  if (ret === false) {
                    ret = prevHook.apply(hooks, args22);
                  }
                  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 _Parser2.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 ? _Parser2.parse : _Parser2.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(...args2) {
      markedInstance.use(...args2);
      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 = _Parser2;
    marked.parser = _Parser2.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 = _Parser2.parse;
    lexer = _Lexer.lex;
  }
});

// packages/core/dist/src/utils/memoryImportProcessor.js
import * as fs70 from "node:fs/promises";
import * as path66 from "node:path";
async function findProjectRoot(startDir) {
  let currentDir = path66.resolve(startDir);
  while (true) {
    const gitPath = path66.join(currentDir, ".git");
    try {
      const stats = await fs70.lstat(gitPath);
      if (stats.isDirectory()) {
        return currentDir;
      }
    } catch {
    }
    const parentDir = path66.dirname(currentDir);
    if (parentDir === currentDir) {
      break;
    }
    currentDir = parentDir;
  }
  return path66.resolve(startDir);
}
function hasMessage(err2) {
  return typeof err2 === "object" && err2 !== null && "message" in err2 && typeof err2.message === "string";
}
function findImports(content) {
  const imports = [];
  let i4 = 0;
  const len = content.length;
  while (i4 < len) {
    i4 = content.indexOf("@", i4);
    if (i4 === -1)
      break;
    if (i4 > 0 && !isWhitespace2(content[i4 - 1])) {
      i4++;
      continue;
    }
    let j2 = i4 + 1;
    while (j2 < len && !isWhitespace2(content[j2]) && content[j2] !== "\n" && content[j2] !== "\r") {
      j2++;
    }
    const importPath = content.slice(i4 + 1, j2);
    if (importPath.length > 0 && (importPath[0] === "." || importPath[0] === "/" || isLetter(importPath[0]))) {
      imports.push({
        start: i4,
        _end: j2,
        path: importPath
      });
    }
    i4 = j2 + 1;
  }
  return imports;
}
function isWhitespace2(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(err2) {
  return typeof err2 === "object" && err2 !== null && "code" in err2 && err2.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 = path66.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 i4 = imports2.length - 1; i4 >= 0; i4--) {
        const { start: start2, path: importPath } = imports2[i4];
        if (codeRegions2.some(([regionStart, regionEnd]) => start2 >= regionStart && start2 < regionEnd)) {
          continue;
        }
        if (!validateImportPath(importPath, fileBasePath, [projectRoot || ""])) {
          continue;
        }
        const fullPath = path66.resolve(fileBasePath, importPath);
        const normalizedFullPath = path66.normalize(fullPath);
        if (processedFiles.has(normalizedFullPath))
          continue;
        try {
          await fs70.access(fullPath);
          const importedContent = await fs70.readFile(fullPath, "utf-8");
          await processFlat(importedContent, path66.dirname(fullPath), normalizedFullPath, depth + 1);
        } catch (error40) {
          if (!isFileNotFoundError(error40)) {
            logger.warn(`Failed to import ${fullPath}: ${hasMessage(error40) ? error40.message : "Unknown error"}`);
          }
        }
      }
    }
    __name(processFlat, "processFlat");
    const rootPath = path66.normalize(importState.currentFile || path66.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: start2, _end, path: importPath } of importsList) {
    result += content.substring(lastIndex, start2);
    lastIndex = _end;
    if (codeRegions.some(([s5, e4]) => start2 >= s5 && start2 < e4)) {
      result += `@${importPath}`;
      continue;
    }
    if (!validateImportPath(importPath, basePath, [projectRoot || ""])) {
      result += `<!-- Import failed: ${importPath} - Path traversal attempt -->`;
      continue;
    }
    const fullPath = path66.resolve(basePath, importPath);
    if (importState.processedFiles.has(fullPath)) {
      result += `<!-- File already processed: ${importPath} -->`;
      continue;
    }
    try {
      await fs70.access(fullPath);
      const fileContent = await fs70.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, path66.dirname(fullPath), newImportState, projectRoot, importFormat);
      result += `<!-- Imported from: ${importPath} -->
${imported.content}
<!-- End of import from: ${importPath} -->`;
      imports.push(imported.importTree);
    } catch (err2) {
      if (isFileNotFoundError(err2)) {
        result += `@${importPath}`;
        continue;
      }
      let message = "Unknown error";
      if (hasMessage(err2)) {
        message = err2.message;
      } else if (typeof err2 === "string") {
        message = err2;
      }
      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 = path66.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(isWhitespace2, "isWhitespace");
    __name(isLetter, "isLetter");
    __name(isFileNotFoundError, "isFileNotFoundError");
    __name(findCodeRegions, "findCodeRegions");
    __name(processImports, "processImports");
    __name(validateImportPath, "validateImportPath");
  }
});

// packages/core/dist/src/utils/rulesDiscovery.js
import * as fs71 from "node:fs/promises";
import * as path67 from "node:path";
import { homedir as homedir15 } from "node:os";
function stripHtmlComments(content) {
  let result = content;
  let prev;
  do {
    prev = result;
    result = prev.replace(/<!--[\s\S]*?-->/g, "");
  } while (result !== prev);
  return result.replace(/<!--/g, "");
}
function parseRuleFile(rawContent, filePath) {
  const normalized2 = normalizeContent(rawContent);
  const match2 = normalized2.match(FRONTMATTER_REGEX);
  let body2;
  let paths;
  let description;
  if (match2) {
    const [, frontmatterYaml, rawBody] = match2;
    try {
      const frontmatter = parse8(frontmatterYaml);
      const pathsRaw = frontmatter["paths"];
      if (Array.isArray(pathsRaw)) {
        paths = pathsRaw.map(String).filter(Boolean);
        if (paths.length === 0)
          paths = void 0;
      } else if (typeof pathsRaw === "string" && pathsRaw) {
        paths = [pathsRaw];
      }
      if (frontmatter["description"] != null) {
        description = String(frontmatter["description"]);
      }
    } catch (error40) {
      logger2.warn(`Failed to parse frontmatter in ${filePath}: ${error40}`);
    }
    body2 = rawBody;
  } else {
    body2 = normalized2;
  }
  const content = stripHtmlComments(body2).trim();
  if (!content)
    return null;
  return { filePath, description, paths, content };
}
async function collectMdFiles(dir) {
  let entries;
  try {
    entries = await fs71.readdir(dir, { withFileTypes: true });
  } catch {
    return [];
  }
  const files = [];
  for (const entry of entries) {
    const fullPath = path67.join(dir, entry.name);
    if (entry.isDirectory()) {
      files.push(...await collectMdFiles(fullPath));
    } else if (entry.isFile() && entry.name.endsWith(".md")) {
      files.push(fullPath);
    }
  }
  return files;
}
async function loadRulesFromDir(rulesDir, excludes) {
  const allPaths = await collectMdFiles(rulesDir);
  if (allPaths.length === 0)
    return [];
  allPaths.sort();
  const excludeMatchers = excludes.length > 0 ? excludes.map((p2) => (0, import_picomatch2.default)(p2, { dot: true })) : [];
  const ruleFiles = [];
  for (const filePath of allPaths) {
    if (excludeMatchers.some((m3) => m3(filePath))) {
      logger2.debug(`Excluding rule by setting: ${filePath}`);
      continue;
    }
    try {
      const rawContent = await fs71.readFile(filePath, "utf-8");
      const rule = parseRuleFile(rawContent, filePath);
      if (rule) {
        ruleFiles.push(rule);
      }
    } catch (error40) {
      logger2.warn(`Failed to load rule file ${filePath}: ${error40}`);
    }
  }
  return ruleFiles;
}
function formatRules(rules, projectRoot) {
  return rules.map((rule) => {
    const rawDisplayPath = path67.isAbsolute(rule.filePath) ? path67.relative(projectRoot, rule.filePath) : rule.filePath;
    const displayPath = rawDisplayPath.replace(/\\/g, "/");
    return `--- Rule from: ${displayPath} ---
${rule.content}
--- End of Rule from: ${displayPath} ---`;
  }).join("\n\n");
}
async function loadRules(projectRoot, folderTrust, excludes = []) {
  logger2.debug(`Loading rules for project: ${projectRoot}`);
  const allRules = [];
  const globalRulesDir = path67.join(homedir15(), QWEN_DIR, "rules");
  const globalRules = await loadRulesFromDir(globalRulesDir, excludes);
  allRules.push(...globalRules);
  logger2.debug(`Loaded ${globalRules.length} global rule(s)`);
  if (folderTrust) {
    const projectRulesDir = path67.join(projectRoot, QWEN_DIR, "rules");
    if (path67.resolve(projectRulesDir) !== path67.resolve(globalRulesDir)) {
      const projectRules = await loadRulesFromDir(projectRulesDir, excludes);
      allRules.push(...projectRules);
      logger2.debug(`Loaded ${projectRules.length} project rule(s)`);
    } else {
      logger2.debug("Project rules dir same as global \u2014 skipping to avoid duplicates");
    }
  }
  const baselineRules = [];
  const conditionalRules = [];
  for (const rule of allRules) {
    if (rule.paths) {
      conditionalRules.push(rule);
    } else {
      baselineRules.push(rule);
    }
  }
  logger2.debug(`Split: ${baselineRules.length} baseline, ${conditionalRules.length} conditional`);
  const content = baselineRules.length > 0 ? formatRules(baselineRules, projectRoot) : "";
  return { content, ruleCount: baselineRules.length, conditionalRules };
}
var import_picomatch2, logger2, FRONTMATTER_REGEX, ConditionalRulesRegistry;
var init_rulesDiscovery = __esm({
  "packages/core/dist/src/utils/rulesDiscovery.js"() {
    "use strict";
    init_esbuild_shims();
    import_picomatch2 = __toESM(require_picomatch2(), 1);
    init_yaml_parser();
    init_textUtils();
    init_paths();
    init_debugLogger();
    logger2 = createDebugLogger("RULES_DISCOVERY");
    FRONTMATTER_REGEX = /^---\n([\s\S]*?)\n---(?:\n|$)([\s\S]*)$/;
    __name(stripHtmlComments, "stripHtmlComments");
    __name(parseRuleFile, "parseRuleFile");
    __name(collectMdFiles, "collectMdFiles");
    __name(loadRulesFromDir, "loadRulesFromDir");
    __name(formatRules, "formatRules");
    ConditionalRulesRegistry = class {
      static {
        __name(this, "ConditionalRulesRegistry");
      }
      compiledRules;
      injected = /* @__PURE__ */ new Set();
      projectRoot;
      constructor(rules, projectRoot) {
        this.projectRoot = projectRoot;
        this.compiledRules = rules.map((rule) => ({
          rule,
          matchers: (rule.paths ?? []).map((p2) => (0, import_picomatch2.default)(p2, { dot: false }))
        }));
        logger2.debug(`ConditionalRulesRegistry created with ${rules.length} rule(s)`);
      }
      /**
       * Check if a file path matches any conditional rules that haven't been
       * injected yet. Matched rules are marked as consumed and their formatted
       * content is returned for injection into the conversation context.
       *
       * @param filePath - Absolute path of the file being accessed.
       * @returns Formatted rule content, or undefined if no new rules match.
       */
      matchAndConsume(filePath) {
        if (this.compiledRules.length === 0)
          return void 0;
        const absolutePath = path67.isAbsolute(filePath) ? filePath : path67.resolve(this.projectRoot, filePath);
        const relativePath = path67.relative(this.projectRoot, absolutePath).replace(/\\/g, "/");
        if (relativePath === ".." || relativePath.startsWith("../")) {
          return void 0;
        }
        const newMatches = this.compiledRules.filter(({ rule, matchers }) => {
          if (this.injected.has(rule.filePath))
            return false;
          return matchers.some((m3) => m3(relativePath));
        });
        if (newMatches.length === 0)
          return void 0;
        for (const { rule } of newMatches) {
          this.injected.add(rule.filePath);
          logger2.debug(`Injecting conditional rule: ${rule.filePath}`);
        }
        return formatRules(newMatches.map((m3) => m3.rule), this.projectRoot);
      }
      get totalCount() {
        return this.compiledRules.length;
      }
      get injectedCount() {
        return this.injected.size;
      }
    };
    __name(loadRules, "loadRules");
  }
});

// packages/core/dist/src/utils/memoryDiscovery.js
import * as fs72 from "node:fs/promises";
import * as fsSync3 from "node:fs";
import * as path68 from "node:path";
import { homedir as homedir16 } from "node:os";
async function findProjectRoot2(startDir) {
  let currentDir = path68.resolve(startDir);
  while (true) {
    const gitPath = path68.join(currentDir, ".git");
    try {
      const stats = await fs72.lstat(gitPath);
      if (stats.isDirectory()) {
        return currentDir;
      }
    } catch (error40) {
      const isENOENT = typeof error40 === "object" && error40 !== null && "code" in error40 && error40.code === "ENOENT";
      const isTestEnv = process.env["NODE_ENV"] === "test" || process.env["VITEST"];
      if (!isENOENT && !isTestEnv) {
        if (typeof error40 === "object" && error40 !== null && "code" in error40) {
          const fsError = error40;
          logger3.warn(`Error checking for .git directory at ${gitPath}: ${fsError.message}`);
        } else {
          logger3.warn(`Non-standard error checking for .git directory at ${gitPath}: ${String(error40)}`);
        }
      }
    }
    const parentDir = path68.dirname(currentDir);
    if (parentDir === currentDir) {
      return null;
    }
    currentDir = parentDir;
  }
}
async function getGeminiMdFilePathsInternal(currentWorkingDirectory, includeDirectoriesToReadGemini, userHomePath, fileService, extensionContextFilePaths = [], folderTrust, implicitDiscoveryEnabled = true) {
  const dirs = new Set(implicitDiscoveryEnabled ? [...includeDirectoriesToReadGemini, currentWorkingDirectory] : [...includeDirectoriesToReadGemini]);
  const CONCURRENT_LIMIT = 10;
  const dirsArray = Array.from(dirs);
  const pathsArrays = [];
  for (let i4 = 0; i4 < dirsArray.length; i4 += CONCURRENT_LIMIT) {
    const batch = dirsArray.slice(i4, i4 + CONCURRENT_LIMIT);
    const batchPromises = batch.map((dir) => getGeminiMdFilePathsInternalForEachDir(dir, userHomePath, fileService, extensionContextFilePaths, folderTrust, implicitDiscoveryEnabled));
    const batchResults = await Promise.allSettled(batchPromises);
    for (const result of batchResults) {
      if (result.status === "fulfilled") {
        pathsArrays.push(result.value);
      } else {
        const error40 = result.reason;
        const message = error40 instanceof Error ? error40.message : String(error40);
        logger3.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, implicitDiscoveryEnabled = true) {
  const allPaths = /* @__PURE__ */ new Set();
  const geminiMdFilenames = getAllGeminiMdFilenames();
  for (const geminiMdFilename of geminiMdFilenames) {
    const resolvedHome = path68.resolve(userHomePath);
    const globalMemoryPath = path68.join(resolvedHome, QWEN_DIR, geminiMdFilename);
    const resolvedDir = dir ? path68.resolve(dir) : resolvedHome;
    const isHomeDirectory = resolvedDir === resolvedHome;
    if (!implicitDiscoveryEnabled) {
      const explicitContextPath = path68.join(resolvedDir, geminiMdFilename);
      try {
        await fs72.access(explicitContextPath, fsSync3.constants.R_OK);
        allPaths.add(explicitContextPath);
        logger3.debug(`Found readable explicit ${geminiMdFilename}: ${explicitContextPath}`);
      } catch {
      }
    } else {
      try {
        await fs72.access(globalMemoryPath, fsSync3.constants.R_OK);
        allPaths.add(globalMemoryPath);
        logger3.debug(`Found readable global ${geminiMdFilename}: ${globalMemoryPath}`);
      } catch {
      }
    }
    if (!implicitDiscoveryEnabled) {
      continue;
    }
    if (isHomeDirectory) {
      const homeContextPath = path68.join(resolvedHome, geminiMdFilename);
      try {
        await fs72.access(homeContextPath, fsSync3.constants.R_OK);
        if (homeContextPath !== globalMemoryPath) {
          allPaths.add(homeContextPath);
          logger3.debug(`Found readable home ${geminiMdFilename}: ${homeContextPath}`);
        }
      } catch {
      }
    } else if (dir && folderTrust) {
      const resolvedCwd = path68.resolve(dir);
      logger3.debug(`Searching for ${geminiMdFilename} starting from CWD: ${resolvedCwd}`);
      const projectRoot = await findProjectRoot2(resolvedCwd);
      logger3.debug(`Determined project root: ${projectRoot ?? "None"}`);
      const upwardPaths = [];
      let currentDir = resolvedCwd;
      const ultimateStopDir = projectRoot ? path68.dirname(projectRoot) : path68.dirname(resolvedHome);
      while (currentDir && currentDir !== path68.dirname(currentDir)) {
        if (currentDir === path68.join(resolvedHome, QWEN_DIR)) {
          break;
        }
        const potentialPath = path68.join(currentDir, geminiMdFilename);
        try {
          await fs72.access(potentialPath, fsSync3.constants.R_OK);
          if (potentialPath !== globalMemoryPath) {
            upwardPaths.unshift(potentialPath);
          }
        } catch {
        }
        if (currentDir === ultimateStopDir) {
          break;
        }
        currentDir = path68.dirname(currentDir);
      }
      upwardPaths.forEach((p2) => allPaths.add(p2));
    }
  }
  for (const extensionPath of extensionContextFilePaths) {
    allPaths.add(extensionPath);
  }
  const finalPaths = Array.from(allPaths);
  logger3.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 i4 = 0; i4 < filePaths.length; i4 += CONCURRENT_LIMIT) {
    const batch = filePaths.slice(i4, i4 + CONCURRENT_LIMIT);
    const batchPromises = batch.map(async (filePath) => {
      try {
        const content = await fs72.readFile(filePath, "utf-8");
        const processedResult = await processImports(content, path68.dirname(filePath), void 0, void 0, importFormat);
        logger3.debug(`Successfully read and processed imports: ${filePath} (Length: ${processedResult.content.length})`);
        return { filePath, content: processedResult.content };
      } catch (error40) {
        const isTestEnv = process.env["NODE_ENV"] === "test" || process.env["VITEST"];
        if (!isTestEnv) {
          const message = error40 instanceof Error ? error40.message : String(error40);
          logger3.warn(`Warning: Could not read ${getAllGeminiMdFilenames()} file at ${filePath}. Error: ${message}`);
        }
        logger3.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 error40 = result.reason;
        const message = error40 instanceof Error ? error40.message : String(error40);
        logger3.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 = path68.isAbsolute(item.filePath) ? path68.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", contextRuleExcludes = [], options2 = {}) {
  logger3.debug(`Loading server hierarchical memory for CWD: ${currentWorkingDirectory} (importFormat: ${importFormat})`);
  const implicitDiscoveryEnabled = !options2.explicitOnly;
  const userHomePath = homedir16();
  const filePaths = await getGeminiMdFilePathsInternal(currentWorkingDirectory, includeDirectoriesToReadGemini, userHomePath, fileService, extensionContextFilePaths, folderTrust, implicitDiscoveryEnabled);
  let combinedInstructions = "";
  let fileCount = 0;
  if (filePaths.length > 0) {
    const contentsWithPaths = await readGeminiMdFiles(filePaths, importFormat);
    combinedInstructions = concatenateInstructions(contentsWithPaths, currentWorkingDirectory);
    const memoryFilenames = new Set(getAllGeminiMdFilenames());
    fileCount = contentsWithPaths.filter((item) => memoryFilenames.has(path68.basename(item.filePath))).length;
  }
  const resolvedCwd = path68.resolve(currentWorkingDirectory);
  const foundRoot = await findProjectRoot2(resolvedCwd);
  const effectiveRoot = foundRoot ?? resolvedCwd;
  const { content: rulesContent, ruleCount, conditionalRules } = options2.explicitOnly ? { content: "", ruleCount: 0, conditionalRules: [] } : await loadRules(effectiveRoot, folderTrust, contextRuleExcludes);
  let memoryContent = combinedInstructions;
  if (rulesContent) {
    memoryContent = memoryContent ? `${memoryContent}

${rulesContent}` : rulesContent;
  }
  if (!memoryContent && filePaths.length === 0 && ruleCount === 0) {
    logger3.debug("No QWEN.md files or rules found.");
  }
  return {
    memoryContent,
    fileCount,
    ruleCount,
    conditionalRules,
    projectRoot: effectiveRoot
  };
}
var logger3;
var init_memoryDiscovery = __esm({
  "packages/core/dist/src/utils/memoryDiscovery.js"() {
    "use strict";
    init_esbuild_shims();
    init_const();
    init_memoryImportProcessor();
    init_paths();
    init_debugLogger();
    init_rulesDiscovery();
    logger3 = 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/memory/types.js
var AUTO_MEMORY_TYPES, AUTO_MEMORY_SCHEMA_VERSION;
var init_types17 = __esm({
  "packages/core/dist/src/memory/types.js"() {
    "use strict";
    init_esbuild_shims();
    AUTO_MEMORY_TYPES = [
      "user",
      "feedback",
      "project",
      "reference"
    ];
    AUTO_MEMORY_SCHEMA_VERSION = 1;
  }
});

// packages/core/dist/src/memory/store.js
import * as fs73 from "node:fs/promises";
function createDefaultAutoMemoryMetadata(now = /* @__PURE__ */ new Date()) {
  const iso = now.toISOString();
  return {
    version: AUTO_MEMORY_SCHEMA_VERSION,
    createdAt: iso,
    updatedAt: iso
  };
}
function createDefaultAutoMemoryExtractCursor(now = /* @__PURE__ */ new Date()) {
  return {
    updatedAt: now.toISOString()
  };
}
function createDefaultAutoMemoryIndex() {
  return "";
}
async function writeFileIfMissing(filePath, content) {
  try {
    await fs73.writeFile(filePath, content, {
      encoding: "utf-8",
      flag: "wx"
    });
  } catch (error40) {
    const nodeError = error40;
    if (nodeError.code !== "EEXIST") {
      throw error40;
    }
  }
}
async function ensureAutoMemoryScaffold(projectRoot, now = /* @__PURE__ */ new Date()) {
  const root = getAutoMemoryRoot(projectRoot);
  await fs73.mkdir(root, { recursive: true });
  await writeFileIfMissing(getAutoMemoryIndexPath(projectRoot), createDefaultAutoMemoryIndex());
  await writeFileIfMissing(getAutoMemoryMetadataPath(projectRoot), JSON.stringify(createDefaultAutoMemoryMetadata(now), null, 2) + "\n");
  await writeFileIfMissing(getAutoMemoryExtractCursorPath(projectRoot), JSON.stringify(createDefaultAutoMemoryExtractCursor(now), null, 2) + "\n");
}
async function readAutoMemoryIndex(projectRoot) {
  try {
    return await fs73.readFile(getAutoMemoryIndexPath(projectRoot), "utf-8");
  } catch (error40) {
    const nodeError = error40;
    if (nodeError.code === "ENOENT") {
      return null;
    }
    throw error40;
  }
}
var init_store = __esm({
  "packages/core/dist/src/memory/store.js"() {
    "use strict";
    init_esbuild_shims();
    init_paths2();
    init_types17();
    __name(createDefaultAutoMemoryMetadata, "createDefaultAutoMemoryMetadata");
    __name(createDefaultAutoMemoryExtractCursor, "createDefaultAutoMemoryExtractCursor");
    __name(createDefaultAutoMemoryIndex, "createDefaultAutoMemoryIndex");
    __name(writeFileIfMissing, "writeFileIfMissing");
    __name(ensureAutoMemoryScaffold, "ensureAutoMemoryScaffold");
    __name(readAutoMemoryIndex, "readAutoMemoryIndex");
  }
});

// packages/core/dist/src/tools/agent/fork-subagent.js
import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
function runInForkContext(fn) {
  return forkExecutionStorage.run({ marker: true }, fn);
}
function isInForkExecution() {
  return forkExecutionStorage.getStore() !== void 0;
}
function buildFunctionResponseParts(assistantMessage, placeholderOutput) {
  return (assistantMessage.parts?.filter((part) => part.functionCall) ?? []).map((part) => ({
    functionResponse: {
      id: part.functionCall.id,
      name: part.functionCall.name,
      response: { output: placeholderOutput }
    }
  }));
}
function buildForkedMessages(directive, assistantMessage) {
  const toolUseParts = assistantMessage.parts?.filter((part) => part.functionCall) || [];
  if (toolUseParts.length === 0) {
    return [];
  }
  const fullAssistantMessage = {
    role: assistantMessage.role,
    parts: [...assistantMessage.parts || []]
  };
  const toolResultParts = buildFunctionResponseParts(assistantMessage, FORK_PLACEHOLDER_RESULT);
  const toolResultMessage = {
    role: "user",
    parts: [
      ...toolResultParts,
      {
        text: buildChildMessage(directive)
      }
    ]
  };
  return [fullAssistantMessage, toolResultMessage];
}
function buildChildMessage(directive) {
  return `<${FORK_BOILERPLATE_TAG}>
STOP. READ THIS FIRST.

You are a forked worker process. You are NOT the main agent.

RULES (non-negotiable):
1. You ARE the fork. Do NOT spawn sub-agents; execute directly.
2. Do NOT converse, ask questions, or suggest next steps
3. Do NOT editorialize or add meta-commentary
4. USE your tools directly: Bash, Read, Write, etc.
5. If you modify files, commit your changes before reporting. Include the commit hash in your report.
6. Do NOT emit text between tool calls. Use tools silently, then report once at the end.
7. Stay strictly within your directive's scope. If you discover related systems outside your scope, mention them in one sentence at most \u2014 other workers cover those areas.
8. Keep your report under 500 words unless the directive specifies otherwise. Be factual and concise.
9. Your response MUST begin with "Scope:". No preamble, no thinking-out-loud.
10. REPORT structured facts, then stop

Output format (plain text labels, not markdown headers):
  Scope: <echo back your assigned scope in one sentence>
  Result: <the answer or key findings, limited to the scope above>
  Key files: <relevant file paths \u2014 include for research tasks>
  Files changed: <list with commit hash \u2014 include only if you modified files>
  Issues: <list \u2014 include only if there are issues to flag>
</${FORK_BOILERPLATE_TAG}>

${FORK_DIRECTIVE_PREFIX}${directive}`;
}
var FORK_SUBAGENT_TYPE, FORK_BOILERPLATE_TAG, FORK_DIRECTIVE_PREFIX, FORK_AGENT, forkExecutionStorage, FORK_PLACEHOLDER_RESULT;
var init_fork_subagent = __esm({
  "packages/core/dist/src/tools/agent/fork-subagent.js"() {
    "use strict";
    init_esbuild_shims();
    FORK_SUBAGENT_TYPE = "fork";
    FORK_BOILERPLATE_TAG = "fork-boilerplate";
    FORK_DIRECTIVE_PREFIX = "Directive: ";
    FORK_AGENT = {
      name: FORK_SUBAGENT_TYPE,
      description: "Implicit fork \u2014 inherits full conversation context. Not selectable via subagent_type; triggered by omitting subagent_type.",
      tools: ["*"],
      systemPrompt: "You are a forked worker process. Follow the directive in the conversation history. Execute tasks directly using available tools. Do not spawn sub-agents.",
      level: "session"
    };
    forkExecutionStorage = new AsyncLocalStorage5();
    __name(runInForkContext, "runInForkContext");
    __name(isInForkExecution, "isInForkExecution");
    FORK_PLACEHOLDER_RESULT = "Fork started \u2014 processing in background";
    __name(buildFunctionResponseParts, "buildFunctionResponseParts");
    __name(buildForkedMessages, "buildForkedMessages");
    __name(buildChildMessage, "buildChildMessage");
  }
});

// packages/core/dist/src/memory/prompt.js
function truncateManagedAutoMemoryIndex(indexContent) {
  const trimmed2 = indexContent.trim();
  const lines = trimmed2.split("\n");
  const lineCount = lines.length;
  const byteCount = trimmed2.length;
  const wasLineTruncated = lineCount > MAX_MANAGED_AUTO_MEMORY_INDEX_LINES;
  const wasByteTruncated = byteCount > MAX_MANAGED_AUTO_MEMORY_INDEX_BYTES;
  if (!wasLineTruncated && !wasByteTruncated) {
    return trimmed2;
  }
  let truncated = wasLineTruncated ? lines.slice(0, MAX_MANAGED_AUTO_MEMORY_INDEX_LINES).join("\n") : trimmed2;
  if (truncated.length > MAX_MANAGED_AUTO_MEMORY_INDEX_BYTES) {
    const cutAt = truncated.lastIndexOf("\n", MAX_MANAGED_AUTO_MEMORY_INDEX_BYTES);
    truncated = truncated.slice(0, cutAt > 0 ? cutAt : MAX_MANAGED_AUTO_MEMORY_INDEX_BYTES);
  }
  const reason = wasByteTruncated && !wasLineTruncated ? `${(byteCount / 1024).toFixed(1)} KB (limit: ${(MAX_MANAGED_AUTO_MEMORY_INDEX_BYTES / 1024).toFixed(1)} KB) \u2014 index entries are too long` : wasLineTruncated && !wasByteTruncated ? `${lineCount} lines (limit: ${MAX_MANAGED_AUTO_MEMORY_INDEX_LINES})` : `${lineCount} lines and ${(byteCount / 1024).toFixed(1)} KB`;
  return `${truncated}

> WARNING: MEMORY.md is ${reason}. Only part of it was loaded. Keep index entries to one line under ~200 chars; move detail into topic files.`;
}
function buildManagedAutoMemoryPrompt(memoryDir, indexContent) {
  const trimmed2 = indexContent?.trim();
  const lines = [
    "# auto memory",
    "",
    `You have a persistent, file-based memory system at \`${memoryDir}\`. ${DIR_EXISTS_GUIDANCE}`,
    "",
    "You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.",
    "",
    "If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.",
    "",
    ...TYPES_SECTION_INDIVIDUAL,
    ...WHAT_NOT_TO_SAVE_SECTION,
    "",
    "## How to save memories",
    "",
    "Saving a memory is a two-step process:",
    "",
    "**Step 1** \u2014 write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:",
    "",
    ...MEMORY_FRONTMATTER_EXAMPLE,
    "",
    `**Step 2** \u2014 add a pointer to that file in \`${memoryDir}/MEMORY.md\` (the full absolute path). This index file is an index, not a memory \u2014 each entry should be one line, under ~150 characters: \`- [Title](file.md) \u2014 one-line hook\`. It has no frontmatter. Never write memory content directly into \`${memoryDir}/MEMORY.md\`.`,
    "",
    `- \`${memoryDir}/MEMORY.md\` is always loaded into your conversation context \u2014 lines after ${MAX_MANAGED_AUTO_MEMORY_INDEX_LINES} will be truncated, so keep the index concise`,
    "- Keep the name, description, and type fields in memory files up-to-date with the content",
    "- Organize memory semantically by topic, not chronologically.",
    "- Update or remove memories that turn out to be wrong or outdated.",
    "- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.",
    "",
    ...WHEN_TO_ACCESS_SECTION,
    "",
    ...TRUSTING_RECALL_SECTION,
    "",
    "## Memory and other forms of persistence",
    "Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.",
    "- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.",
    "- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.",
    "",
    `## ${memoryDir}/MEMORY.md`,
    "",
    trimmed2 ? truncateManagedAutoMemoryIndex(trimmed2) : "Your MEMORY.md is currently empty. When you save new memories, they will appear here."
  ];
  return lines.join("\n");
}
function appendManagedAutoMemoryToUserMemory(userMemory, memoryDir, indexContent) {
  const managedPrompt = buildManagedAutoMemoryPrompt(memoryDir, indexContent);
  const trimmedUserMemory = userMemory.trim();
  if (!managedPrompt) {
    return userMemory;
  }
  if (!trimmedUserMemory) {
    return managedPrompt;
  }
  return `${trimmedUserMemory}

---

${managedPrompt}`;
}
var MAX_MANAGED_AUTO_MEMORY_INDEX_LINES, MAX_MANAGED_AUTO_MEMORY_INDEX_BYTES, DIR_EXISTS_GUIDANCE, MEMORY_FRONTMATTER_EXAMPLE, TYPES_SECTION_INDIVIDUAL, WHAT_NOT_TO_SAVE_SECTION, MEMORY_DRIFT_CAVEAT, WHEN_TO_ACCESS_SECTION, TRUSTING_RECALL_SECTION;
var init_prompt = __esm({
  "packages/core/dist/src/memory/prompt.js"() {
    "use strict";
    init_esbuild_shims();
    MAX_MANAGED_AUTO_MEMORY_INDEX_LINES = 200;
    MAX_MANAGED_AUTO_MEMORY_INDEX_BYTES = 25e3;
    DIR_EXISTS_GUIDANCE = "This directory already exists \u2014 write to it directly with the write_file tool (do not run mkdir or check for its existence).";
    MEMORY_FRONTMATTER_EXAMPLE = [
      "```markdown",
      "---",
      "name: {{memory name}}",
      "description: {{one-line description \u2014 used to decide relevance in future conversations, so be specific}}",
      "type: {{user, feedback, project, reference}}",
      "---",
      "",
      "{{memory content \u2014 for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}",
      "```"
    ];
    TYPES_SECTION_INDIVIDUAL = [
      "## Types of memory",
      "",
      "There are several discrete types of memory that you can store in your memory system:",
      "",
      "<types>",
      "<type>",
      "    <name>user</name>",
      "    <description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>",
      "    <when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>",
      "    <how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>",
      "    <examples>",
      "    user: I'm a data scientist investigating what logging we have in place",
      "    assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]",
      "",
      "    user: I've been writing Go for ten years but this is my first time touching the React side of this repo",
      "    assistant: [saves user memory: deep Go expertise, new to React and this project's frontend \u2014 frame frontend explanations in terms of backend analogues]",
      "    </examples>",
      "</type>",
      "<type>",
      "    <name>feedback</name>",
      "    <description>Guidance the user has given you about how to approach work \u2014 both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.</description>",
      `    <when_to_save>Any time the user corrects your approach ("no not that", "don't", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter \u2014 watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>`,
      "    <how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>",
      "    <body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave \u2014 often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>",
      "    <examples>",
      "    user: don't mock the database in these tests \u2014 we got burned last quarter when mocked tests passed but the prod migration failed",
      "    assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]",
      "",
      "    user: stop summarizing what you just did at the end of every response, I can read the diff",
      "    assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]",
      "",
      "    user: yeah the single bundled PR was the right call here, splitting this one would've just been churn",
      "    assistant: [saves feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach \u2014 a validated judgment call, not a correction]",
      "    </examples>",
      "</type>",
      "<type>",
      "    <name>project</name>",
      "    <description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>",
      '    <when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" \u2192 "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>',
      "    <how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>",
      "    <body_structure>Lead with the fact or decision, then a **Why:** line (the motivation \u2014 often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>",
      "    <examples>",
      "    user: we're freezing all non-critical merges after Thursday \u2014 mobile team is cutting a release branch",
      "    assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]",
      "",
      "    user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements",
      "    assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup \u2014 scope decisions should favor compliance over ergonomics]",
      "    </examples>",
      "</type>",
      "<type>",
      "    <name>reference</name>",
      "    <description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>",
      "    <when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>",
      "    <how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>",
      "    <examples>",
      `    user: check the Linear project "INGEST" if you want context on these tickets, that's where we track all pipeline bugs`,
      '    assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]',
      "",
      "    user: the Grafana board at grafana.internal/d/api-latency is what oncall watches \u2014 if you're touching request handling, that's the thing that'll page someone",
      "    assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard \u2014 check it when editing request-path code]",
      "    </examples>",
      "</type>",
      "</types>",
      ""
    ];
    WHAT_NOT_TO_SAVE_SECTION = [
      "## What NOT to save in memory",
      "",
      "- Code patterns, conventions, architecture, file paths, or project structure \u2014 these can be derived by reading the current project state.",
      "- Git history, recent changes, or who-changed-what \u2014 `git log` / `git blame` are authoritative.",
      "- Debugging solutions or fix recipes \u2014 the fix is in the code; the commit message has the context.",
      "- Anything already documented in QWEN.md or AGENTS.md files.",
      "- Ephemeral task details: in-progress work, temporary state, current conversation context.",
      "",
      "These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it \u2014 that is the part worth keeping."
    ];
    MEMORY_DRIFT_CAVEAT = "- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now \u2014 and update or remove the stale memory rather than acting on it.";
    WHEN_TO_ACCESS_SECTION = [
      "## When to access memories",
      "- When memories seem relevant, or the user references prior-conversation work.",
      "- You MUST access memory when the user explicitly asks you to check, recall, or remember.",
      "- If the user says to *ignore* or *not use* memory: proceed as if MEMORY.md were empty. Do not apply remembered facts, cite, compare against, or mention memory content.",
      MEMORY_DRIFT_CAVEAT
    ];
    TRUSTING_RECALL_SECTION = [
      "## Before recommending from memory",
      "",
      "A memory that names a specific function, file, or flag is a claim that it existed when the memory was written. It may have been renamed, removed, or never merged. Before recommending it:",
      "",
      "- If the memory names a file path: check the file exists.",
      "- If the memory names a function or flag: grep for it.",
      "- If the user is about to act on your recommendation (not just asking about history), verify first.",
      "",
      '"The memory says X exists" is not the same as "X exists now."',
      "",
      "A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot."
    ];
    __name(truncateManagedAutoMemoryIndex, "truncateManagedAutoMemoryIndex");
    __name(buildManagedAutoMemoryPrompt, "buildManagedAutoMemoryPrompt");
    __name(appendManagedAutoMemoryToUserMemory, "appendManagedAutoMemoryToUserMemory");
  }
});

// packages/core/dist/src/memory/scan.js
import * as fs74 from "node:fs/promises";
import * as path69 from "node:path";
function parseFrontmatterValue(frontmatter, key) {
  const match2 = frontmatter.match(new RegExp(`^${key}:\\s*(.+)$`, "m"));
  return match2?.[1]?.trim();
}
function parseAutoMemoryTopicDocument(filePath, content, mtimeMs = 0, relativePath = path69.basename(filePath)) {
  const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
  if (!frontmatterMatch) {
    return null;
  }
  const [, frontmatter, bodyContent] = frontmatterMatch;
  const rawType = parseFrontmatterValue(frontmatter, "type");
  if (!rawType || !AUTO_MEMORY_TYPES.includes(rawType)) {
    return null;
  }
  return {
    type: rawType,
    filePath,
    relativePath,
    filename: path69.basename(filePath),
    title: parseFrontmatterValue(frontmatter, "name") ?? parseFrontmatterValue(frontmatter, "title") ?? rawType,
    description: parseFrontmatterValue(frontmatter, "description") ?? "",
    body: bodyContent.trim(),
    mtimeMs
  };
}
async function listMarkdownFiles(root) {
  try {
    const entries = await fs74.readdir(root, { recursive: true });
    return entries.filter((entry) => typeof entry === "string" && entry.endsWith(".md") && path69.basename(entry) !== AUTO_MEMORY_INDEX_FILENAME).map((entry) => entry.replaceAll("\\", "/")).sort();
  } catch (error40) {
    const nodeError = error40;
    if (nodeError.code === "ENOENT") {
      return [];
    }
    throw error40;
  }
}
async function scanAutoMemoryTopicDocuments(projectRoot) {
  const root = getAutoMemoryRoot(projectRoot);
  const relativePaths = await listMarkdownFiles(root);
  const docs = await Promise.all(relativePaths.map(async (relativePath) => {
    const filePath = path69.join(root, relativePath);
    const [content, stats] = await Promise.all([
      fs74.readFile(filePath, "utf-8"),
      fs74.stat(filePath)
    ]);
    return parseAutoMemoryTopicDocument(filePath, content, stats.mtimeMs, relativePath);
  }));
  return docs.filter((doc) => doc !== null).filter((doc) => AUTO_MEMORY_TYPES.includes(doc.type)).sort((a2, b2) => b2.mtimeMs - a2.mtimeMs || a2.filename.localeCompare(b2.filename)).slice(0, MAX_SCANNED_MEMORY_FILES);
}
var MAX_SCANNED_MEMORY_FILES;
var init_scan = __esm({
  "packages/core/dist/src/memory/scan.js"() {
    "use strict";
    init_esbuild_shims();
    init_types17();
    init_paths2();
    MAX_SCANNED_MEMORY_FILES = 200;
    __name(parseFrontmatterValue, "parseFrontmatterValue");
    __name(parseAutoMemoryTopicDocument, "parseAutoMemoryTopicDocument");
    __name(listMarkdownFiles, "listMarkdownFiles");
    __name(scanAutoMemoryTopicDocuments, "scanAutoMemoryTopicDocuments");
  }
});

// packages/core/dist/src/memory/extractionAgentPlanner.js
function isScopedTool(toolName) {
  return toolName === ToolNames.SHELL || toolName === ToolNames.EDIT || toolName === ToolNames.WRITE_FILE;
}
function mergePermissionDecision(scopedDecision, baseDecision) {
  const priority = {
    deny: 4,
    ask: 3,
    allow: 2,
    default: 1
  };
  return priority[baseDecision] > priority[scopedDecision] ? baseDecision : scopedDecision;
}
async function evaluateScopedDecision(ctx, projectRoot) {
  switch (ctx.toolName) {
    case ToolNames.SHELL: {
      if (!ctx.command) {
        return "deny";
      }
      const isReadOnly = await isShellCommandReadOnlyAST(stripShellWrapper(ctx.command));
      return isReadOnly ? "allow" : "deny";
    }
    case ToolNames.EDIT:
    case ToolNames.WRITE_FILE:
      return ctx.filePath && isAutoMemPath(ctx.filePath, projectRoot) ? "allow" : "deny";
    default:
      return "default";
  }
}
function getScopedDenyRule(ctx, projectRoot) {
  switch (ctx.toolName) {
    case ToolNames.SHELL:
      return "ManagedAutoMemory(run_shell_command: read-only only)";
    case ToolNames.EDIT:
      return `ManagedAutoMemory(edit: only within ${getAutoMemoryRoot(projectRoot)})`;
    case ToolNames.WRITE_FILE:
      return `ManagedAutoMemory(write_file: only within ${getAutoMemoryRoot(projectRoot)})`;
    default:
      return void 0;
  }
}
function createMemoryScopedAgentConfig(config2, projectRoot) {
  const basePm = config2.getPermissionManager?.();
  const scopedPm = {
    hasRelevantRules(ctx) {
      return isScopedTool(ctx.toolName) || !!basePm?.hasRelevantRules(ctx);
    },
    hasMatchingAskRule(ctx) {
      return basePm?.hasMatchingAskRule(ctx) ?? false;
    },
    findMatchingDenyRule(ctx) {
      const scoped = getScopedDenyRule(ctx, projectRoot);
      if (scoped) {
        return scoped;
      }
      return basePm?.findMatchingDenyRule(ctx);
    },
    async evaluate(ctx) {
      const scopedDecision = await evaluateScopedDecision(ctx, projectRoot);
      if (!basePm) {
        return scopedDecision;
      }
      const baseDecision = basePm.hasRelevantRules(ctx) ? await basePm.evaluate(ctx) : "default";
      return mergePermissionDecision(scopedDecision, baseDecision);
    },
    async isToolEnabled(toolName) {
      if (isScopedTool(toolName)) {
        return true;
      }
      if (basePm) {
        return basePm.isToolEnabled(toolName);
      }
      return true;
    }
  };
  const scopedConfig = Object.create(config2);
  scopedConfig.getPermissionManager = () => scopedPm;
  return scopedConfig;
}
function buildAgentHistory(history) {
  if (history.length === 0)
    return [];
  const last2 = history[history.length - 1];
  if (last2.role !== "model") {
    return history.slice(0, -1);
  }
  const openCalls = (last2.parts ?? []).filter((p2) => p2.functionCall);
  if (openCalls.length === 0) {
    return [...history];
  }
  const toolResponses = buildFunctionResponseParts(last2, "Background extraction started.");
  return [
    ...history,
    { role: "user", parts: toolResponses },
    { role: "model", parts: [{ text: "Acknowledged." }] }
  ];
}
function truncate(text, maxChars) {
  const normalized2 = text.replace(/\s+/g, " ").trim();
  if (normalized2.length <= maxChars) {
    return normalized2;
  }
  return `${normalized2.slice(0, maxChars).trimEnd()}\u2026`;
}
async function buildTopicSummaryBlock(projectRoot) {
  const docs = await scanAutoMemoryTopicDocuments(projectRoot);
  if (docs.length === 0) {
    return "";
  }
  return docs.map((doc) => {
    const body2 = truncate(doc.body === "_No entries yet._" ? "" : doc.body, MAX_TOPIC_SUMMARY_CHARS);
    return [
      `- [${doc.title}](${doc.relativePath}) \u2014 ${doc.description || "(no description)"}`,
      `  topic=${doc.type}`,
      `  path=${doc.filePath}`,
      `  current=${body2 || "(empty)"}`
    ].join("\n");
  }).join("\n\n");
}
function buildTaskPrompt(memoryRoot, topicSummaries) {
  return [
    `Managed memory directory: \`${memoryRoot}\``,
    "",
    "Scan the recent conversation history in your context and update durable managed memory.",
    "",
    "Available tools in this run: `read_file`, `grep_search`, `glob`, `list_directory`, read-only `run_shell_command`, and `write_file`/`edit` for paths inside the managed memory directory only.",
    "- Do not use any other tools.",
    "- You have a limited turn budget. `edit` requires a prior `read_file` of the same file, so the efficient strategy is: first issue all reads in parallel for every file you might update; then issue all `write_file`/`edit` calls in parallel. Do not interleave reads and writes across multiple turns.",
    "- You MUST only use content from the recent conversation history in your context plus the current managed memory files.",
    "- Do not inspect repository code, git history, or unrelated files.",
    "- Prefer updating an existing memory file over creating a duplicate.",
    "- Keep one durable memory per file under `user/`, `feedback/`, `project/`, or `reference/`.",
    "",
    "## How to save memories",
    "",
    "**Step 1** \u2014 write or update the memory file itself using the required frontmatter format.",
    `**Step 2** \u2014 update \`${memoryRoot}/${AUTO_MEMORY_INDEX_FILENAME}\`. It is an index, not a memory: each entry must be one line in the form \`- [Title](relative/path.md) \u2014 one-line hook\`. Never write memory content directly into the index.`,
    "- If you create or delete a memory file, also update the managed memory index.",
    "- If nothing durable should be saved, make no file changes.",
    "",
    "## Existing memory files",
    "",
    topicSummaries || "(none yet)"
  ].join("\n");
}
function touchedTopicsFromFilePaths(filePaths, projectRoot) {
  const memoryRoot = getAutoMemoryRoot(projectRoot);
  const topicSet = /* @__PURE__ */ new Set();
  for (const p2 of filePaths) {
    if (!p2.startsWith(memoryRoot))
      continue;
    const rel = p2.slice(memoryRoot.length).replace(/^\//, "");
    const segment = rel.split("/")[0];
    if (segment === "user" || segment === "feedback" || segment === "project" || segment === "reference") {
      topicSet.add(segment);
    }
  }
  return [...topicSet];
}
async function runAutoMemoryExtractionByAgent(config2, projectRoot) {
  const cacheSafe = getCacheSafeParams();
  if (!cacheSafe) {
    throw new Error("runAutoMemoryExtractionByAgent: no cache-safe params available; extraction must run after a completed main turn.");
  }
  const extraHistory = buildAgentHistory(cacheSafe.history);
  const topicSummaries = await buildTopicSummaryBlock(projectRoot);
  const memoryRoot = getAutoMemoryRoot(projectRoot);
  const scopedConfig = createMemoryScopedAgentConfig(config2, projectRoot);
  const result = await runForkedAgent({
    name: "managed-auto-memory-extractor",
    config: scopedConfig,
    taskPrompt: buildTaskPrompt(memoryRoot, topicSummaries),
    systemPrompt: EXTRACTION_AGENT_SYSTEM_PROMPT,
    maxTurns: 5,
    maxTimeMinutes: 2,
    tools: [
      ToolNames.READ_FILE,
      ToolNames.GREP,
      ToolNames.GLOB,
      ToolNames.LS,
      ToolNames.SHELL,
      ToolNames.WRITE_FILE,
      ToolNames.EDIT
    ],
    extraHistory
  });
  if (result.status !== "completed") {
    throw new Error(result.terminateReason || "Extraction agent did not complete successfully");
  }
  const touchedTopics = touchedTopicsFromFilePaths(result.filesTouched, projectRoot);
  return {
    touchedTopics,
    systemMessage: touchedTopics.length > 0 ? `Managed auto-memory updated: ${touchedTopics.map((t5) => `${t5}.md`).join(", ")}` : void 0
  };
}
var MAX_TOPIC_SUMMARY_CHARS, EXTRACTION_AGENT_SYSTEM_PROMPT;
var init_extractionAgentPlanner = __esm({
  "packages/core/dist/src/memory/extractionAgentPlanner.js"() {
    "use strict";
    init_esbuild_shims();
    init_forkedAgent();
    init_fork_subagent();
    init_prompt();
    init_paths2();
    init_scan();
    init_tool_names();
    init_shellAstParser();
    init_shell_utils();
    init_paths2();
    MAX_TOPIC_SUMMARY_CHARS = 280;
    __name(isScopedTool, "isScopedTool");
    __name(mergePermissionDecision, "mergePermissionDecision");
    __name(evaluateScopedDecision, "evaluateScopedDecision");
    __name(getScopedDenyRule, "getScopedDenyRule");
    __name(createMemoryScopedAgentConfig, "createMemoryScopedAgentConfig");
    EXTRACTION_AGENT_SYSTEM_PROMPT = [
      "You are now acting as the managed memory extraction subagent for an AI coding assistant.",
      "",
      "The recent conversation history is already in your context. Analyze only that recent conversation and use it to update persistent managed memory.",
      "",
      "Rules:",
      "- Read existing memory files first to avoid creating duplicates.",
      "- Extract only durable facts stated by the user.",
      "- Ignore temporary, session-specific, speculative, or question content.",
      "- If the user explicitly asks the assistant to remember something durable, preserve it.",
      "- Use one of the allowed topics: user, feedback, project, reference.",
      "- Keep entries concise and suitable for bullet points. No leading bullet markers.",
      "- Do not investigate repository code, git history, or unrelated files.",
      "- Work only from the conversation history in your context and the existing memory files.",
      "- If nothing durable should be saved, make no file changes.",
      "",
      ...TYPES_SECTION_INDIVIDUAL,
      ...WHAT_NOT_TO_SAVE_SECTION,
      "",
      "Memory file format reference:",
      ...MEMORY_FRONTMATTER_EXAMPLE
    ].join("\n");
    __name(buildAgentHistory, "buildAgentHistory");
    __name(truncate, "truncate");
    __name(buildTopicSummaryBlock, "buildTopicSummaryBlock");
    __name(buildTaskPrompt, "buildTaskPrompt");
    __name(touchedTopicsFromFilePaths, "touchedTopicsFromFilePaths");
    __name(runAutoMemoryExtractionByAgent, "runAutoMemoryExtractionByAgent");
  }
});

// packages/core/dist/src/memory/indexer.js
import * as fs75 from "node:fs/promises";
function truncateIndexLine(text) {
  if (text.length <= MAX_INDEX_LINE_CHARS) {
    return text;
  }
  return `${text.slice(0, MAX_INDEX_LINE_CHARS - 1).trimEnd()}\u2026`;
}
function buildManagedAutoMemoryIndex(docs, _metadata) {
  const raw2 = docs.map((doc) => truncateIndexLine(`- [${doc.title}](${doc.relativePath}) \u2014 ${doc.description || doc.type}`)).join("\n");
  const lines = raw2.split("\n");
  const wasLineTruncated = lines.length > MAX_INDEX_LINES;
  let truncated = wasLineTruncated ? lines.slice(0, MAX_INDEX_LINES).join("\n") : raw2;
  if (truncated.length > MAX_INDEX_BYTES) {
    const cutAt = truncated.lastIndexOf("\n", MAX_INDEX_BYTES);
    truncated = truncated.slice(0, cutAt > 0 ? cutAt : MAX_INDEX_BYTES);
  }
  if (!wasLineTruncated && truncated.length === raw2.length) {
    return truncated;
  }
  return `${truncated}

> WARNING: MEMORY.md is too large; only part of it was written. Keep index entries concise and move detail into topic files.`;
}
async function readAutoMemoryMetadata(projectRoot) {
  try {
    const content = await fs75.readFile(getAutoMemoryMetadataPath(projectRoot), "utf-8");
    return JSON.parse(content);
  } catch {
    return void 0;
  }
}
async function rebuildManagedAutoMemoryIndex(projectRoot) {
  const [docs, metadata2] = await Promise.all([
    scanAutoMemoryTopicDocuments(projectRoot),
    readAutoMemoryMetadata(projectRoot)
  ]);
  const content = buildManagedAutoMemoryIndex(docs, metadata2);
  await fs75.writeFile(getAutoMemoryIndexPath(projectRoot), content, "utf-8");
  return content;
}
var MAX_INDEX_LINE_CHARS, MAX_INDEX_LINES, MAX_INDEX_BYTES;
var init_indexer = __esm({
  "packages/core/dist/src/memory/indexer.js"() {
    "use strict";
    init_esbuild_shims();
    init_paths2();
    init_scan();
    MAX_INDEX_LINE_CHARS = 150;
    MAX_INDEX_LINES = 200;
    MAX_INDEX_BYTES = 25e3;
    __name(truncateIndexLine, "truncateIndexLine");
    __name(buildManagedAutoMemoryIndex, "buildManagedAutoMemoryIndex");
    __name(readAutoMemoryMetadata, "readAutoMemoryMetadata");
    __name(rebuildManagedAutoMemoryIndex, "rebuildManagedAutoMemoryIndex");
  }
});

// packages/core/dist/src/memory/extract.js
import * as fs76 from "node:fs/promises";
function buildTranscriptMessages(history) {
  return history.map((message, index) => ({
    offset: index,
    role: message.role,
    text: partToString(message.parts ?? []).replace(/\s+/g, " ").trim()
  })).filter((message) => (message.role === "user" || message.role === "model") && message.text.length > 0);
}
function loadUnprocessedTranscriptSlice(sessionId, messages, cursor) {
  const startOffset = cursor.sessionId === sessionId ? cursor.processedOffset ?? 0 : 0;
  return {
    messages: messages.filter((message) => message.offset >= startOffset),
    nextProcessedOffset: messages.length
  };
}
async function readExtractCursor(projectRoot) {
  try {
    const content = await fs76.readFile(getAutoMemoryExtractCursorPath(projectRoot), "utf-8");
    return JSON.parse(content);
  } catch (error40) {
    const nodeError = error40;
    if (nodeError.code === "ENOENT") {
      return { updatedAt: (/* @__PURE__ */ new Date(0)).toISOString() };
    }
    throw error40;
  }
}
async function writeExtractCursor(projectRoot, cursor) {
  await fs76.writeFile(getAutoMemoryExtractCursorPath(projectRoot), `${JSON.stringify(cursor, null, 2)}
`, "utf-8");
}
async function bumpMetadata(projectRoot, now, sessionId, touchedTopics) {
  try {
    const content = await fs76.readFile(getAutoMemoryMetadataPath(projectRoot), "utf-8");
    const metadata2 = JSON.parse(content);
    metadata2.updatedAt = now.toISOString();
    metadata2.lastExtractionAt = now.toISOString();
    metadata2.lastExtractionSessionId = sessionId;
    metadata2.lastExtractionTouchedTopics = touchedTopics;
    metadata2.lastExtractionStatus = touchedTopics.length > 0 ? "updated" : "noop";
    await fs76.writeFile(getAutoMemoryMetadataPath(projectRoot), `${JSON.stringify(metadata2, null, 2)}
`, "utf-8");
  } catch {
  }
}
async function runAutoMemoryExtract(params) {
  const now = params.now ?? /* @__PURE__ */ new Date();
  await ensureAutoMemoryScaffold(params.projectRoot, now);
  const transcript = buildTranscriptMessages(params.history);
  const currentCursor = await readExtractCursor(params.projectRoot);
  const slice = loadUnprocessedTranscriptSlice(params.sessionId, transcript, currentCursor);
  if (!params.config) {
    throw new Error("Managed auto-memory extraction requires config for forked-agent execution.");
  }
  const hasNewUserMessages = slice.messages.some((m3) => m3.role === "user");
  if (!hasNewUserMessages) {
    const cursor2 = {
      sessionId: params.sessionId,
      processedOffset: slice.nextProcessedOffset,
      updatedAt: now.toISOString()
    };
    await writeExtractCursor(params.projectRoot, cursor2);
    return { touchedTopics: [], cursor: cursor2 };
  }
  const agentResult = await runAutoMemoryExtractionByAgent(params.config, params.projectRoot);
  if (agentResult.touchedTopics.length > 0) {
    await bumpMetadata(params.projectRoot, now, params.sessionId, agentResult.touchedTopics);
    await rebuildManagedAutoMemoryIndex(params.projectRoot);
  }
  const cursor = {
    sessionId: params.sessionId,
    processedOffset: slice.nextProcessedOffset,
    updatedAt: now.toISOString()
  };
  await writeExtractCursor(params.projectRoot, cursor);
  debugLogger84.debug(`Managed auto-memory extract completed with ${agentResult.touchedTopics.length} touched topic(s).`);
  return {
    touchedTopics: agentResult.touchedTopics,
    cursor,
    systemMessage: agentResult.systemMessage
  };
}
var debugLogger84;
var init_extract2 = __esm({
  "packages/core/dist/src/memory/extract.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_partUtils();
    init_paths2();
    init_store();
    init_extractionAgentPlanner();
    init_indexer();
    init_types17();
    debugLogger84 = createDebugLogger("AUTO_MEMORY_EXTRACT");
    __name(buildTranscriptMessages, "buildTranscriptMessages");
    __name(loadUnprocessedTranscriptSlice, "loadUnprocessedTranscriptSlice");
    __name(readExtractCursor, "readExtractCursor");
    __name(writeExtractCursor, "writeExtractCursor");
    __name(bumpMetadata, "bumpMetadata");
    __name(runAutoMemoryExtract, "runAutoMemoryExtract");
  }
});

// packages/core/dist/src/memory/dreamAgentPlanner.js
import * as path70 from "node:path";
function isScopedTool2(toolName) {
  return toolName === ToolNames.SHELL || toolName === ToolNames.EDIT || toolName === ToolNames.WRITE_FILE;
}
function mergePermissionDecision2(scopedDecision, baseDecision) {
  const priority = {
    deny: 4,
    ask: 3,
    allow: 2,
    default: 1
  };
  return priority[baseDecision] > priority[scopedDecision] ? baseDecision : scopedDecision;
}
async function evaluateScopedDecision2(ctx, projectRoot) {
  switch (ctx.toolName) {
    case ToolNames.SHELL: {
      if (!ctx.command) {
        return "deny";
      }
      const isReadOnly = await isShellCommandReadOnlyAST(stripShellWrapper(ctx.command));
      return isReadOnly ? "allow" : "deny";
    }
    case ToolNames.EDIT:
    case ToolNames.WRITE_FILE:
      return ctx.filePath && isAutoMemPath(ctx.filePath, projectRoot) ? "allow" : "deny";
    default:
      return "default";
  }
}
function getScopedDenyRule2(ctx, projectRoot) {
  switch (ctx.toolName) {
    case ToolNames.SHELL:
      return "ManagedAutoMemory(run_shell_command: read-only only)";
    case ToolNames.EDIT:
      return `ManagedAutoMemory(edit: only within ${getAutoMemoryRoot(projectRoot)})`;
    case ToolNames.WRITE_FILE:
      return `ManagedAutoMemory(write_file: only within ${getAutoMemoryRoot(projectRoot)})`;
    default:
      return void 0;
  }
}
function createMemoryScopedAgentConfig2(config2, projectRoot) {
  const basePm = config2.getPermissionManager?.();
  const scopedPm = {
    hasRelevantRules(ctx) {
      return isScopedTool2(ctx.toolName) || !!basePm?.hasRelevantRules(ctx);
    },
    hasMatchingAskRule(ctx) {
      return basePm?.hasMatchingAskRule(ctx) ?? false;
    },
    findMatchingDenyRule(ctx) {
      const scoped = getScopedDenyRule2(ctx, projectRoot);
      if (scoped) {
        return scoped;
      }
      return basePm?.findMatchingDenyRule(ctx);
    },
    async evaluate(ctx) {
      const scopedDecision = await evaluateScopedDecision2(ctx, projectRoot);
      if (!basePm) {
        return scopedDecision;
      }
      const baseDecision = basePm.hasRelevantRules(ctx) ? await basePm.evaluate(ctx) : "default";
      return mergePermissionDecision2(scopedDecision, baseDecision);
    },
    async isToolEnabled(toolName) {
      if (isScopedTool2(toolName)) {
        return true;
      }
      if (basePm) {
        return basePm.isToolEnabled(toolName);
      }
      return true;
    }
  };
  const scopedConfig = Object.create(config2);
  scopedConfig.getPermissionManager = () => scopedPm;
  return scopedConfig;
}
function getTranscriptDir(projectRoot) {
  return path70.join(new Storage(projectRoot).getProjectDir(), "chats");
}
function quoteShellPathWithTrailingSeparator(dirPath) {
  return escapeShellArg(`${dirPath}${path70.sep}`, getShellConfiguration().shell);
}
function buildConsolidationTaskPrompt(memoryRoot, transcriptDir) {
  const quotedTranscriptDir = quoteShellPathWithTrailingSeparator(transcriptDir);
  return [
    `Memory directory: \`${memoryRoot}\``,
    "This directory already exists \u2014 write to it directly with the write_file tool (do not run mkdir or check for its existence).",
    `Session transcripts: \`${transcriptDir}\` (large JSONL files \u2014 grep narrowly, don't read whole files)`,
    "",
    "## Phase 1 \u2014 Orient",
    "",
    "- List the memory directory to see what files exist",
    `- Read \`${memoryRoot}/${AUTO_MEMORY_INDEX_FILENAME}\` to understand the current index`,
    "- Skim topic subdirectories (`user/`, `project/`, `feedback/`, `reference/`)",
    "- If `logs/` or `sessions/` subdirectories exist, review recent entries there",
    "",
    "## Phase 2 \u2014 Gather recent signal",
    "",
    "Look for new information worth persisting. Sources in rough priority order:",
    "",
    "1. Existing memories that drifted \u2014 facts that contradict something you now know from current memory files",
    "2. Transcript search \u2014 if you need specific context, grep session transcripts for narrow terms:",
    `   \`grep -rn "<narrow term>" ${quotedTranscriptDir} --include="*.jsonl" | tail -50\``,
    "",
    "Don't exhaustively read transcripts. Look only for things you already suspect matter.",
    "",
    "## Phase 3 \u2014 Consolidate",
    "",
    "For each topic directory:",
    "- Identify duplicate or near-duplicate `.md` files (same fact expressed differently)",
    "- Merge duplicates: write the canonical version into one file, delete the redundant files",
    "- Fix stale or contradicted facts when clear from the existing content",
    '- Convert relative dates (for example: "yesterday", "last week") to absolute dates when preserving them',
    "",
    "## Phase 4 \u2014 Prune and index",
    "",
    `Update \`${memoryRoot}/${AUTO_MEMORY_INDEX_FILENAME}\` to reflect surviving files.`,
    "Each entry: `- [Title](relative/path.md) \u2014 one-line hook`",
    "Keep the index under roughly 200 lines and ~25KB.",
    "Remove pointers to deleted, stale, wrong, or superseded files. Add pointers to any newly created files.",
    "If an index line is too verbose, shorten it and move the detail back into the memory file itself.",
    "",
    "---",
    "",
    "Return a brief summary of what you consolidated, updated, or pruned. If nothing needed consolidation, say so briefly."
  ].join("\n");
}
async function planManagedAutoMemoryDreamByAgent(config2, projectRoot) {
  const memoryRoot = getAutoMemoryRoot(projectRoot);
  const transcriptDir = getTranscriptDir(projectRoot);
  const scopedConfig = createMemoryScopedAgentConfig2(config2, projectRoot);
  const result = await runForkedAgent({
    name: "managed-auto-memory-dreamer",
    config: scopedConfig,
    taskPrompt: buildConsolidationTaskPrompt(memoryRoot, transcriptDir),
    systemPrompt: DREAM_AGENT_SYSTEM_PROMPT,
    maxTurns: MAX_TURNS2,
    maxTimeMinutes: MAX_TIME_MINUTES,
    tools: [
      ToolNames.READ_FILE,
      ToolNames.GREP,
      ToolNames.GLOB,
      ToolNames.LS,
      ToolNames.SHELL,
      ToolNames.WRITE_FILE,
      ToolNames.EDIT
    ]
  });
  if (result.status === "failed") {
    throw new Error(result.terminateReason || "Dream agent failed");
  }
  return result;
}
var MAX_TURNS2, MAX_TIME_MINUTES, DREAM_AGENT_SYSTEM_PROMPT;
var init_dreamAgentPlanner = __esm({
  "packages/core/dist/src/memory/dreamAgentPlanner.js"() {
    "use strict";
    init_esbuild_shims();
    init_forkedAgent();
    init_storage();
    init_paths2();
    init_tool_names();
    init_shellAstParser();
    init_shell_utils();
    MAX_TURNS2 = 8;
    MAX_TIME_MINUTES = 5;
    __name(isScopedTool2, "isScopedTool");
    __name(mergePermissionDecision2, "mergePermissionDecision");
    __name(evaluateScopedDecision2, "evaluateScopedDecision");
    __name(getScopedDenyRule2, "getScopedDenyRule");
    __name(createMemoryScopedAgentConfig2, "createMemoryScopedAgentConfig");
    DREAM_AGENT_SYSTEM_PROMPT = `You are performing a managed memory dream \u2014 a reflective pass over durable memory files.

Synthesize what you've learned recently into durable, well-organized memories so that future sessions can orient quickly.

Rules:
- Merge semantically duplicate entries \u2014 if the same fact appears in multiple files, consolidate into one file and delete the rest.
- Preserve all durable information; do not delete content that is still accurate.
- Fix contradicted or stale facts only when the evidence is clear from the existing memory content or recent transcript signal.
- Update the MEMORY.md index to accurately reflect surviving files.
- Keep the MEMORY.md index concise: one line per file in the format \`- [Title](relative/path.md) \u2014 one-line hook\`.
- If nothing needs consolidation, do nothing and say so.`;
    __name(getTranscriptDir, "getTranscriptDir");
    __name(quoteShellPathWithTrailingSeparator, "quoteShellPathWithTrailingSeparator");
    __name(buildConsolidationTaskPrompt, "buildConsolidationTaskPrompt");
    __name(planManagedAutoMemoryDreamByAgent, "planManagedAutoMemoryDreamByAgent");
  }
});

// packages/core/dist/src/memory/dream.js
import * as fs77 from "node:fs/promises";
async function bumpMetadata2(projectRoot, now) {
  const metadataPath = getAutoMemoryMetadataPath(projectRoot);
  try {
    const content = await fs77.readFile(metadataPath, "utf-8");
    const metadata2 = JSON.parse(content);
    metadata2.updatedAt = now.toISOString();
    metadata2.lastDreamAt = now.toISOString();
    await fs77.writeFile(metadataPath, `${JSON.stringify(metadata2, null, 2)}
`, "utf-8");
  } catch {
  }
}
async function runDreamByAgent(projectRoot, config2) {
  const result = await planManagedAutoMemoryDreamByAgent(config2, projectRoot);
  const touchedTopics = /* @__PURE__ */ new Set();
  for (const filePath of result.filesTouched) {
    const normalized2 = filePath.replace(/\\/g, "/");
    for (const type of AUTO_MEMORY_TYPES) {
      if (normalized2.includes(`/${type}/`)) {
        touchedTopics.add(type);
      }
    }
  }
  const summary = result.finalText ? result.finalText.trim().slice(0, 300) : `updated ${result.filesTouched.length} file(s)`;
  return {
    touchedTopics: [...touchedTopics],
    dedupedEntries: 0,
    systemMessage: `Managed auto-memory dream (agent): ${summary}`
  };
}
async function runManagedAutoMemoryDream(projectRoot, now = /* @__PURE__ */ new Date(), config2) {
  await ensureAutoMemoryScaffold(projectRoot, now);
  const t02 = Date.now();
  if (!config2) {
    throw new Error("Managed auto-memory dream requires config for forked-agent execution.");
  }
  const agentResult = await runDreamByAgent(projectRoot, config2);
  if (agentResult.touchedTopics.length > 0) {
    await bumpMetadata2(projectRoot, now);
    await rebuildManagedAutoMemoryIndex(projectRoot);
  }
  await updateDreamMetadataResult(projectRoot, now, agentResult.touchedTopics);
  logMemoryDream(config2, new MemoryDreamEvent({
    trigger: "auto",
    status: agentResult.touchedTopics.length > 0 ? "updated" : "noop",
    deduped_entries: agentResult.dedupedEntries,
    touched_topics: agentResult.touchedTopics,
    duration_ms: Date.now() - t02
  }));
  return agentResult;
}
async function updateDreamMetadataResult(projectRoot, now, touchedTopics, sessionId) {
  const metadataPath = getAutoMemoryMetadataPath(projectRoot);
  try {
    const content = await fs77.readFile(metadataPath, "utf-8");
    const metadata2 = JSON.parse(content);
    metadata2.updatedAt = now.toISOString();
    metadata2.lastDreamAt = now.toISOString();
    metadata2.lastDreamTouchedTopics = touchedTopics;
    metadata2.lastDreamStatus = touchedTopics.length > 0 ? "updated" : "noop";
    if (sessionId !== void 0) {
      metadata2.lastDreamSessionId = sessionId;
      metadata2.recentSessionIdsSinceDream = [];
    }
    await fs77.writeFile(metadataPath, `${JSON.stringify(metadata2, null, 2)}
`, "utf-8");
  } catch {
  }
}
async function writeDreamManualRunToMetadata(projectRoot, sessionId, now = /* @__PURE__ */ new Date()) {
  return updateDreamMetadataResult(projectRoot, now, [], sessionId);
}
var init_dream = __esm({
  "packages/core/dist/src/memory/dream.js"() {
    "use strict";
    init_esbuild_shims();
    init_paths2();
    init_dreamAgentPlanner();
    init_indexer();
    init_store();
    init_types17();
    init_telemetry();
    __name(bumpMetadata2, "bumpMetadata");
    __name(runDreamByAgent, "runDreamByAgent");
    __name(runManagedAutoMemoryDream, "runManagedAutoMemoryDream");
    __name(updateDreamMetadataResult, "updateDreamMetadataResult");
    __name(writeDreamManualRunToMetadata, "writeDreamManualRunToMetadata");
  }
});

// packages/core/dist/src/memory/entries.js
function normalizeText(text) {
  return text.replace(/\s+/g, " ").trim();
}
function getAutoMemoryBodyHeading(body2) {
  return body2.split("\n").map((line) => line.trim()).find((line) => line.startsWith("# ")) ?? "# Memory";
}
function parseAutoMemoryEntries(body2) {
  const entries = [];
  let current = null;
  for (const rawLine of body2.split("\n")) {
    const trimmed2 = rawLine.trim();
    if (!trimmed2 || trimmed2 === "_No entries yet._" || trimmed2.startsWith("# ")) {
      continue;
    }
    if (current) {
      const indentedMatch = rawLine.match(/^[\t ]{2,}(?:[-*][\t ]+)?(Why|How to apply|How_to_apply):[\t ]*(\S.*)$/i);
      if (indentedMatch) {
        const [, rawKey, rawValue] = indentedMatch;
        const value = normalizeText(rawValue);
        if (value) {
          switch (rawKey.toLowerCase()) {
            case "why":
              current.why = value;
              break;
            case "how to apply":
            case "how_to_apply":
              current.howToApply = value;
              break;
            default:
              break;
          }
        }
        continue;
      }
    }
    const topLevelMatch = trimmed2.match(/^(?:\*\*)?(Why|How to apply|How_to_apply)(?:\*\*)?:[ \t]*(\S.*)$/i);
    if (topLevelMatch) {
      const [, rawKey, rawValue] = topLevelMatch;
      const value = normalizeText(rawValue);
      if (value && current) {
        switch (rawKey.toLowerCase()) {
          case "why":
            current.why = value;
            break;
          case "how to apply":
          case "how_to_apply":
            current.howToApply = value;
            break;
          default:
            break;
        }
      }
      continue;
    }
    if (/^[-*]\s+/.test(trimmed2)) {
      if (current) {
        entries.push(current);
      }
      current = {
        summary: normalizeText(trimmed2.replace(/^[-*]\s+/, ""))
      };
      continue;
    }
    if (current) {
      entries.push(current);
    }
    current = { summary: normalizeText(trimmed2) };
  }
  if (current) {
    entries.push(current);
  }
  return entries;
}
function renderAutoMemoryBody(_heading, entries) {
  if (entries.length === 0) {
    return "_No entries yet._";
  }
  const lines = [];
  for (let i4 = 0; i4 < entries.length; i4++) {
    if (i4 > 0) {
      lines.push("");
    }
    const entry = entries[i4];
    lines.push(normalizeText(entry.summary));
    if (entry.why) {
      lines.push("", `Why: ${normalizeText(entry.why)}`);
    }
    if (entry.howToApply) {
      lines.push("", `How to apply: ${normalizeText(entry.howToApply)}`);
    }
  }
  return lines.join("\n");
}
function buildAutoMemoryEntrySearchText(entry) {
  return [entry.summary, entry.why, entry.howToApply].filter((value) => Boolean(value)).join(" ").toLowerCase();
}
var init_entries = __esm({
  "packages/core/dist/src/memory/entries.js"() {
    "use strict";
    init_esbuild_shims();
    __name(normalizeText, "normalizeText");
    __name(getAutoMemoryBodyHeading, "getAutoMemoryBodyHeading");
    __name(parseAutoMemoryEntries, "parseAutoMemoryEntries");
    __name(renderAutoMemoryBody, "renderAutoMemoryBody");
    __name(buildAutoMemoryEntrySearchText, "buildAutoMemoryEntrySearchText");
  }
});

// packages/core/dist/src/memory/forget.js
import * as fs78 from "node:fs/promises";
async function listIndexedForgetCandidates(projectRoot) {
  const docs = await scanAutoMemoryTopicDocuments(projectRoot);
  const candidates = [];
  for (const doc of docs) {
    const entries = parseAutoMemoryEntries(doc.body);
    for (let i4 = 0; i4 < entries.length; i4++) {
      const entry = entries[i4];
      candidates.push({
        // Use a stable per-entry ID so the model can target individual entries
        // in multi-entry files without accidentally removing siblings.
        id: entries.length === 1 ? doc.relativePath : `${doc.relativePath}:${i4}`,
        topic: doc.type,
        summary: entry.summary,
        filePath: doc.filePath,
        why: entry.why,
        howToApply: entry.howToApply
      });
    }
  }
  return candidates;
}
function buildForgetSelectionPrompt(query, candidates, limit2) {
  return [
    "Select the managed auto-memory entries that most likely match the user request to forget something.",
    `Return at most ${limit2} candidate ids.`,
    "Prefer semantically matching entries even if the wording differs slightly.",
    "If nothing should be forgotten, return an empty array.",
    "",
    `Forget request: ${query.trim()}`,
    "",
    "Candidates:",
    ...candidates.map((candidate, index) => [
      `Candidate ${index + 1}`,
      `id: ${candidate.id}`,
      `topic: ${candidate.topic}`,
      `summary: ${candidate.summary}`,
      `why: ${candidate.why ?? "(none)"}`,
      `howToApply: ${candidate.howToApply ?? "(none)"}`
    ].join("\n"))
  ].join("\n");
}
async function selectByModel(candidates, query, config2, limit2) {
  const response = await runSideQuery(config2, {
    purpose: "auto-memory-forget-selection",
    contents: [
      {
        role: "user",
        parts: [
          {
            text: buildForgetSelectionPrompt(query, candidates, limit2)
          }
        ]
      }
    ],
    schema: FORGET_SELECTION_RESPONSE_SCHEMA,
    abortSignal: AbortSignal.timeout(8e3),
    config: {
      temperature: 0
    },
    validate: /* @__PURE__ */ __name((value) => {
      const candidateIds = new Set(candidates.map((c4) => c4.id));
      for (const id of value.selectedCandidateIds) {
        if (!candidateIds.has(id)) {
          return `Unknown candidate id: ${id}`;
        }
      }
      return null;
    }, "validate")
  });
  const selectedIds = new Set(response.selectedCandidateIds);
  const matches2 = candidates.filter((candidate) => selectedIds.has(candidate.id)).slice(0, limit2).map(({ topic, summary, filePath }) => ({ topic, summary, filePath }));
  return {
    matches: matches2,
    strategy: matches2.length > 0 ? "model" : "none",
    reasoning: response.reasoning
  };
}
function selectByHeuristic(candidates, query, limit2) {
  const normalizedQuery = query.replace(/\s+/g, " ").trim();
  const queryLower = normalizedQuery.toLowerCase();
  const matches2 = candidates.filter((candidate) => buildAutoMemoryEntrySearchText(candidate).includes(queryLower)).slice(0, limit2).map(({ topic, summary, filePath }) => ({ topic, summary, filePath }));
  return {
    matches: matches2,
    strategy: matches2.length > 0 ? "heuristic" : "none"
  };
}
async function selectManagedAutoMemoryForgetCandidates(projectRoot, query, options2 = {}) {
  const limit2 = options2.limit ?? 5;
  const candidates = await listIndexedForgetCandidates(projectRoot);
  if (candidates.length === 0) {
    return { matches: [], strategy: "none" };
  }
  if (options2.config) {
    try {
      return await selectByModel(candidates, query, options2.config, limit2);
    } catch {
    }
  }
  return selectByHeuristic(candidates, query, limit2);
}
async function bumpMetadata3(projectRoot, now) {
  try {
    const content = await fs78.readFile(getAutoMemoryMetadataPath(projectRoot), "utf-8");
    const metadata2 = JSON.parse(content);
    metadata2.updatedAt = now.toISOString();
    await fs78.writeFile(getAutoMemoryMetadataPath(projectRoot), `${JSON.stringify(metadata2, null, 2)}
`, "utf-8");
  } catch {
  }
}
async function forgetManagedAutoMemoryMatches(projectRoot, matches2, now = /* @__PURE__ */ new Date()) {
  if (matches2.length === 0) {
    return {
      query: "",
      removedEntries: [],
      touchedTopics: [],
      systemMessage: void 0
    };
  }
  await ensureAutoMemoryScaffold(projectRoot, now);
  const removedEntries = [];
  const touchedTopics = /* @__PURE__ */ new Set();
  const matchesByFile = /* @__PURE__ */ new Map();
  for (const match2 of matches2) {
    const existing = matchesByFile.get(match2.filePath) ?? [];
    existing.push(match2);
    matchesByFile.set(match2.filePath, existing);
  }
  for (const [filePath, fileMatches] of matchesByFile) {
    try {
      const rawContent = await fs78.readFile(filePath, "utf-8");
      const fmMatch = rawContent.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
      if (!fmMatch) {
        await fs78.unlink(filePath);
        removedEntries.push(...fileMatches);
        for (const m3 of fileMatches)
          touchedTopics.add(m3.topic);
        continue;
      }
      const [, frontmatter, rawBody] = fmMatch;
      const allEntries = parseAutoMemoryEntries(rawBody.trim());
      const matchedSummaries = new Set(fileMatches.map((m3) => m3.summary.toLowerCase()));
      const kept = allEntries.filter((e4) => !matchedSummaries.has(e4.summary.toLowerCase()));
      if (kept.length === 0) {
        await fs78.unlink(filePath);
      } else {
        const heading2 = getAutoMemoryBodyHeading(rawBody);
        const newBody = renderAutoMemoryBody(heading2, kept);
        await fs78.writeFile(filePath, `---
${frontmatter}
---

${newBody}
`, "utf-8");
      }
      const removedCount = allEntries.length - kept.length;
      removedEntries.push(...fileMatches.slice(0, removedCount));
      for (const m3 of fileMatches.slice(0, removedCount)) {
        touchedTopics.add(m3.topic);
      }
    } catch {
    }
  }
  if (touchedTopics.size > 0) {
    await bumpMetadata3(projectRoot, now);
    await rebuildManagedAutoMemoryIndex(projectRoot);
  }
  return {
    query: "",
    removedEntries,
    touchedTopics: [...touchedTopics],
    systemMessage: removedEntries.length > 0 ? `Managed auto-memory forgot ${removedEntries.length} entr${removedEntries.length === 1 ? "y" : "ies"} from: ${[...touchedTopics].map((topic) => `${topic}/`).join(", ")}` : void 0
  };
}
async function forgetManagedAutoMemoryEntries(projectRoot, query, options2 = {}, now = /* @__PURE__ */ new Date()) {
  const trimmedQuery = query.trim();
  if (!trimmedQuery) {
    return { query: trimmedQuery, removedEntries: [], touchedTopics: [] };
  }
  const selection = await selectManagedAutoMemoryForgetCandidates(projectRoot, trimmedQuery, { ...options2, limit: Number.MAX_SAFE_INTEGER });
  const result = await forgetManagedAutoMemoryMatches(projectRoot, selection.matches, now);
  return { ...result, query: trimmedQuery };
}
var FORGET_SELECTION_RESPONSE_SCHEMA;
var init_forget = __esm({
  "packages/core/dist/src/memory/forget.js"() {
    "use strict";
    init_esbuild_shims();
    init_sideQuery();
    init_entries();
    init_indexer();
    init_paths2();
    init_scan();
    init_store();
    FORGET_SELECTION_RESPONSE_SCHEMA = {
      type: "object",
      properties: {
        selectedCandidateIds: {
          type: "array",
          items: { type: "string" }
        },
        reasoning: {
          type: "string"
        }
      },
      required: ["selectedCandidateIds"]
    };
    __name(listIndexedForgetCandidates, "listIndexedForgetCandidates");
    __name(buildForgetSelectionPrompt, "buildForgetSelectionPrompt");
    __name(selectByModel, "selectByModel");
    __name(selectByHeuristic, "selectByHeuristic");
    __name(selectManagedAutoMemoryForgetCandidates, "selectManagedAutoMemoryForgetCandidates");
    __name(bumpMetadata3, "bumpMetadata");
    __name(forgetManagedAutoMemoryMatches, "forgetManagedAutoMemoryMatches");
    __name(forgetManagedAutoMemoryEntries, "forgetManagedAutoMemoryEntries");
  }
});

// packages/core/dist/src/memory/relevanceSelector.js
function formatMemoryManifest(docs) {
  return docs.map((doc) => {
    const tag2 = `[${doc.type}] `;
    const ts = new Date(doc.mtimeMs).toISOString();
    return doc.description ? `- ${tag2}${doc.relativePath} (${ts}): ${doc.description}` : `- ${tag2}${doc.relativePath} (${ts})`;
  }).join("\n");
}
async function selectRelevantAutoMemoryDocumentsByModel(config2, query, docs, limit2, recentTools = []) {
  if (docs.length === 0 || limit2 <= 0 || query.trim().length === 0) {
    return [];
  }
  const manifest = formatMemoryManifest(docs);
  const toolsSection = recentTools.length > 0 ? `

Recently used tools: ${recentTools.join(", ")}` : "";
  const contents = [
    {
      role: "user",
      parts: [
        {
          text: `Query: ${query.trim()}

Available memories:
${manifest}${toolsSection}`
        }
      ]
    }
  ];
  const validRelativePaths = new Set(docs.map((doc) => doc.relativePath));
  const byRelativePath = new Map(docs.map((doc) => [doc.relativePath, doc]));
  const response = await runSideQuery(config2, {
    purpose: "auto-memory-recall",
    contents,
    schema: RESPONSE_SCHEMA2,
    abortSignal: AbortSignal.timeout(5e3),
    systemInstruction: SELECT_MEMORIES_SYSTEM_PROMPT,
    config: {
      temperature: 0
    },
    validate: /* @__PURE__ */ __name((value) => {
      if (!Array.isArray(value.selected_memories)) {
        return "Recall selector must return selected_memories array";
      }
      if (value.selected_memories.length > limit2) {
        return `Recall selector returned too many documents: ${value.selected_memories.length}`;
      }
      if (value.selected_memories.some((relativePath) => !validRelativePaths.has(relativePath))) {
        return "Recall selector returned unknown relative path";
      }
      return null;
    }, "validate")
  });
  return response.selected_memories.map((relativePath) => byRelativePath.get(relativePath)).filter((doc) => doc !== void 0).slice(0, limit2);
}
var SELECT_MEMORIES_SYSTEM_PROMPT, RESPONSE_SCHEMA2;
var init_relevanceSelector = __esm({
  "packages/core/dist/src/memory/relevanceSelector.js"() {
    "use strict";
    init_esbuild_shims();
    init_sideQuery();
    SELECT_MEMORIES_SYSTEM_PROMPT = `You are selecting memories that will be useful to an AI coding assistant as it processes a user's query. You will be given the user's query and a list of available memory files with their filenames and descriptions.

Return a list of filenames for the memories that will clearly be useful to the assistant as it processes the user's query (up to 5). Only include memories that you are certain will be helpful based on their name and description.
- If you are unsure if a memory will be useful in processing the user's query, then do not include it in your list. Be selective and discerning.
- If there are no memories in the list that would clearly be useful, feel free to return an empty list.
- If a list of recently-used tools is provided, do not select memories that are usage reference or API documentation for those tools (the assistant is already exercising them). DO still select memories containing warnings, gotchas, or known issues about those tools \u2014 active use is exactly when those matter.`;
    RESPONSE_SCHEMA2 = {
      type: "object",
      properties: {
        selected_memories: {
          type: "array",
          items: { type: "string" }
        }
      },
      required: ["selected_memories"],
      additionalProperties: false
    };
    __name(formatMemoryManifest, "formatMemoryManifest");
    __name(selectRelevantAutoMemoryDocumentsByModel, "selectRelevantAutoMemoryDocumentsByModel");
  }
});

// packages/core/dist/src/memory/recall.js
import * as path71 from "node:path";
function tokenize4(text) {
  return Array.from(new Set(text.toLowerCase().split(/[^a-z0-9]+/).map((token2) => token2.trim()).filter((token2) => token2.length >= 3)));
}
function normalizeBody(body2) {
  const trimmed2 = body2.trim();
  if (trimmed2 === "_No entries yet._") {
    return "";
  }
  return trimmed2;
}
function scoreDocument(queryTokens, doc) {
  const normalizedBody = normalizeBody(doc.body);
  const haystack = [doc.type, doc.title, doc.description, normalizedBody].join(" ").toLowerCase();
  let score = 0;
  for (const token2 of queryTokens) {
    if (haystack.includes(token2)) {
      score += 2;
    }
    if (TYPE_KEYWORDS[doc.type]?.includes(token2)) {
      score += 1;
    }
  }
  if (normalizedBody.length > 0) {
    score += 1;
  }
  return score;
}
function selectRelevantAutoMemoryDocuments(query, docs, limit2 = MAX_RELEVANT_DOCS) {
  const queryTokens = tokenize4(query);
  if (queryTokens.length === 0) {
    return [];
  }
  return docs.map((doc) => ({ doc, score: scoreDocument(queryTokens, doc) })).filter(({ score }) => score > 0).sort((a2, b2) => b2.score - a2.score || a2.doc.type.localeCompare(b2.doc.type)).slice(0, limit2).map(({ doc }) => doc);
}
function truncateBody(body2) {
  const normalized2 = normalizeBody(body2);
  if (normalized2.length <= MAX_DOC_BODY_CHARS) {
    return normalized2;
  }
  return `${normalized2.slice(0, MAX_DOC_BODY_CHARS).trimEnd()}

> NOTE: Relevant memory truncated for prompt budget.`;
}
function buildRelevantAutoMemoryPrompt(docs) {
  if (docs.length === 0) {
    return "";
  }
  return [
    "## Relevant memory",
    "",
    "Use the following memories only when they are directly relevant to the current request. Verify file/function claims before relying on them.",
    "",
    ...docs.flatMap((doc) => {
      const body2 = truncateBody(doc.body);
      const staleness = memoryFreshnessText(doc.mtimeMs);
      return [
        `### ${doc.title} (${doc.relativePath || path71.basename(doc.filePath)})`,
        `Saved ${memoryAge(doc.mtimeMs)}.`,
        doc.description,
        "",
        body2 || "_No detailed entries yet._",
        ...staleness ? ["", `> NOTE: ${staleness}`] : [],
        ""
      ];
    })
  ].join("\n");
}
function filterExcludedAutoMemoryDocuments(docs, excludedFilePaths) {
  if (!excludedFilePaths) {
    return docs;
  }
  const excluded = new Set(excludedFilePaths);
  if (excluded.size === 0) {
    return docs;
  }
  return docs.filter((doc) => !excluded.has(doc.filePath));
}
async function resolveRelevantAutoMemoryPromptForQuery(projectRoot, query, options2 = {}) {
  const t02 = Date.now();
  const docs = filterExcludedAutoMemoryDocuments(await scanAutoMemoryTopicDocuments(projectRoot), options2.excludedFilePaths);
  const limit2 = options2.limit ?? MAX_RELEVANT_DOCS;
  if (query.trim().length === 0 || docs.length === 0 || limit2 <= 0) {
    if (options2.config) {
      logMemoryRecall(options2.config, new MemoryRecallEvent({
        query_length: query.length,
        docs_scanned: docs.length,
        docs_selected: 0,
        strategy: "none",
        duration_ms: Date.now() - t02
      }));
    }
    return {
      prompt: "",
      selectedDocs: [],
      strategy: "none"
    };
  }
  if (options2.config) {
    try {
      const selectedDocs2 = await selectRelevantAutoMemoryDocumentsByModel(options2.config, query, docs, limit2, options2.recentTools ?? []);
      const strategy2 = selectedDocs2.length > 0 ? "model" : "none";
      logMemoryRecall(options2.config, new MemoryRecallEvent({
        query_length: query.length,
        docs_scanned: docs.length,
        docs_selected: selectedDocs2.length,
        strategy: strategy2,
        duration_ms: Date.now() - t02
      }));
      return {
        prompt: buildRelevantAutoMemoryPrompt(selectedDocs2),
        selectedDocs: selectedDocs2,
        strategy: strategy2
      };
    } catch (error40) {
      debugLogger85.warn("Model-driven auto-memory recall failed; falling back to heuristic selection.", error40);
    }
  }
  const selectedDocs = selectRelevantAutoMemoryDocuments(query, docs, limit2);
  const strategy = selectedDocs.length > 0 ? "heuristic" : "none";
  if (options2.config) {
    logMemoryRecall(options2.config, new MemoryRecallEvent({
      query_length: query.length,
      docs_scanned: docs.length,
      docs_selected: selectedDocs.length,
      strategy,
      duration_ms: Date.now() - t02
    }));
  }
  return {
    prompt: buildRelevantAutoMemoryPrompt(selectedDocs),
    selectedDocs,
    strategy
  };
}
var MAX_RELEVANT_DOCS, MAX_DOC_BODY_CHARS, debugLogger85, TYPE_KEYWORDS;
var init_recall = __esm({
  "packages/core/dist/src/memory/recall.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    init_scan();
    init_memoryAge();
    init_relevanceSelector();
    init_telemetry();
    MAX_RELEVANT_DOCS = 5;
    MAX_DOC_BODY_CHARS = 1200;
    debugLogger85 = createDebugLogger("AUTO_MEMORY_RECALL");
    TYPE_KEYWORDS = {
      user: ["user", "preference", "preferences", "background", "role", "terse"],
      feedback: ["feedback", "rule", "rules", "avoid", "style", "summary"],
      project: ["project", "goal", "goals", "incident", "deadline", "release"],
      reference: ["reference", "dashboard", "ticket", "docs", "doc", "link"]
    };
    __name(tokenize4, "tokenize");
    __name(normalizeBody, "normalizeBody");
    __name(scoreDocument, "scoreDocument");
    __name(selectRelevantAutoMemoryDocuments, "selectRelevantAutoMemoryDocuments");
    __name(truncateBody, "truncateBody");
    __name(buildRelevantAutoMemoryPrompt, "buildRelevantAutoMemoryPrompt");
    __name(filterExcludedAutoMemoryDocuments, "filterExcludedAutoMemoryDocuments");
    __name(resolveRelevantAutoMemoryPromptForQuery, "resolveRelevantAutoMemoryPromptForQuery");
  }
});

// packages/core/dist/src/memory/status.js
import * as fs79 from "node:fs/promises";
async function readJsonFile(filePath) {
  try {
    const content = await fs79.readFile(filePath, "utf-8");
    return JSON.parse(content);
  } catch {
    return void 0;
  }
}
async function getManagedAutoMemoryStatus(projectRoot, manager) {
  const root = getAutoMemoryRoot(projectRoot);
  const indexPath = getAutoMemoryIndexPath(projectRoot);
  const [indexContent, cursor, metadata2, docs] = await Promise.all([
    fs79.readFile(indexPath, "utf-8").catch(() => ""),
    readJsonFile(getAutoMemoryExtractCursorPath(projectRoot)),
    readJsonFile(getAutoMemoryMetadataPath(projectRoot)),
    scanAutoMemoryTopicDocuments(projectRoot)
  ]);
  const byTopic = /* @__PURE__ */ new Map();
  for (const doc of docs) {
    const list3 = byTopic.get(doc.type) ?? [];
    list3.push(doc.filePath);
    byTopic.set(doc.type, list3);
  }
  const topics = AUTO_MEMORY_TYPES.map((topic) => ({
    topic,
    entryCount: byTopic.get(topic)?.length ?? 0,
    filePaths: byTopic.get(topic) ?? []
  }));
  const extractTaskType = "extract";
  const dreamTaskType = "dream";
  return {
    root,
    indexPath,
    indexContent,
    cursor,
    metadata: metadata2,
    extractionRunning: manager.listTasksByType(extractTaskType, projectRoot).some((t5) => t5.status === "running"),
    topics,
    extractionTasks: manager.listTasksByType(extractTaskType, projectRoot).slice(0, 8),
    dreamTasks: manager.listTasksByType(dreamTaskType, projectRoot).slice(0, 5)
  };
}
var init_status3 = __esm({
  "packages/core/dist/src/memory/status.js"() {
    "use strict";
    init_esbuild_shims();
    init_manager();
    init_paths2();
    init_scan();
    init_types17();
    __name(readJsonFile, "readJsonFile");
    __name(getManagedAutoMemoryStatus, "getManagedAutoMemoryStatus");
  }
});

// packages/core/dist/src/memory/manager.js
import * as fs80 from "node:fs/promises";
import * as path72 from "node:path";
import { randomUUID as randomUUID7 } from "node:crypto";
function makeTaskRecord(type, projectRoot, sessionId) {
  const now = (/* @__PURE__ */ new Date()).toISOString();
  return {
    id: randomUUID7(),
    taskType: type,
    projectRoot,
    sessionId,
    status: "pending",
    createdAt: now,
    updatedAt: now
  };
}
function updateRecord(record2, patch) {
  if (patch.status !== void 0)
    record2.status = patch.status;
  if (patch.progressText !== void 0)
    record2.progressText = patch.progressText;
  if (patch.error !== void 0)
    record2.error = patch.error;
  if (patch.metadata !== void 0) {
    record2.metadata = { ...record2.metadata ?? {}, ...patch.metadata };
  }
  record2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
}
function partWritesToMemory(part, projectRoot) {
  const name4 = part.functionCall?.name;
  if (name4 && WRITE_TOOL_NAMES.has(name4)) {
    const args2 = part.functionCall?.args;
    const filePath = args2?.["file_path"] ?? args2?.["path"] ?? args2?.["target_file"];
    if (typeof filePath === "string" && isAutoMemPath(filePath, projectRoot)) {
      return true;
    }
  }
  return false;
}
function historyWritesToMemory(history, projectRoot) {
  return history.some((msg) => (msg.parts ?? []).some((p2) => partWritesToMemory(p2, projectRoot)));
}
function isProcessRunning(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}
async function readDreamMetadata(projectRoot) {
  const content = await fs80.readFile(getAutoMemoryMetadataPath(projectRoot), "utf-8");
  return JSON.parse(content);
}
async function writeDreamMetadata(projectRoot, metadata2) {
  await fs80.writeFile(getAutoMemoryMetadataPath(projectRoot), `${JSON.stringify(metadata2, null, 2)}
`, "utf-8");
}
function hoursSince(lastDreamAt, now) {
  if (!lastDreamAt)
    return null;
  const timestamp = Date.parse(lastDreamAt);
  if (Number.isNaN(timestamp))
    return null;
  return (now.getTime() - timestamp) / (1e3 * 60 * 60);
}
async function defaultSessionScanner(projectRoot, sinceMs, excludeSessionId) {
  const chatsDir = path72.join(new Storage(projectRoot).getProjectDir(), "chats");
  let names;
  try {
    names = await fs80.readdir(chatsDir);
  } catch {
    return [];
  }
  const results = [];
  await Promise.all(names.map(async (name4) => {
    if (!SESSION_FILE_PATTERN2.test(name4))
      return;
    const sessionId = name4.slice(0, -".jsonl".length);
    if (sessionId === excludeSessionId)
      return;
    try {
      const stats = await fs80.stat(path72.join(chatsDir, name4));
      if (stats.mtimeMs > sinceMs)
        results.push(sessionId);
    } catch {
    }
  }));
  return results;
}
async function dreamLockExists(projectRoot) {
  const lockPath = getAutoMemoryConsolidationLockPath(projectRoot);
  let mtimeMs;
  let holderPid;
  try {
    const [stats, content] = await Promise.all([
      fs80.stat(lockPath),
      fs80.readFile(lockPath, "utf-8").catch(() => "")
    ]);
    mtimeMs = stats.mtimeMs;
    const parsed = parseInt(content.trim(), 10);
    holderPid = Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
  } catch {
    return false;
  }
  const ageMs = Date.now() - mtimeMs;
  if (ageMs <= DREAM_LOCK_STALE_MS) {
    if (holderPid !== void 0 && isProcessRunning(holderPid))
      return true;
    await fs80.rm(lockPath, { force: true });
    return false;
  }
  await fs80.rm(lockPath, { force: true });
  return false;
}
async function acquireDreamLock(projectRoot) {
  await fs80.writeFile(getAutoMemoryConsolidationLockPath(projectRoot), String(process.pid), { flag: "wx" });
}
async function releaseDreamLock(projectRoot) {
  await fs80.rm(getAutoMemoryConsolidationLockPath(projectRoot), {
    force: true
  });
}
var EXTRACT_TASK_TYPE, DREAM_TASK_TYPE, DEFAULT_AUTO_DREAM_MIN_HOURS, DEFAULT_AUTO_DREAM_MIN_SESSIONS, DREAM_LOCK_STALE_MS, SESSION_SCAN_INTERVAL_MS, WRITE_TOOL_NAMES, SESSION_FILE_PATTERN2, MemoryManager, globalMemoryManager;
var init_manager = __esm({
  "packages/core/dist/src/memory/manager.js"() {
    "use strict";
    init_esbuild_shims();
    init_storage();
    init_telemetry();
    init_paths2();
    init_paths2();
    init_store();
    init_extract2();
    init_dream();
    init_forget();
    init_recall();
    init_status3();
    init_prompt();
    init_dream();
    init_dreamAgentPlanner();
    EXTRACT_TASK_TYPE = "managed-auto-memory-extraction";
    DREAM_TASK_TYPE = "managed-auto-memory-dream";
    DEFAULT_AUTO_DREAM_MIN_HOURS = 24;
    DEFAULT_AUTO_DREAM_MIN_SESSIONS = 5;
    DREAM_LOCK_STALE_MS = 60 * 60 * 1e3;
    SESSION_SCAN_INTERVAL_MS = 10 * 60 * 1e3;
    WRITE_TOOL_NAMES = /* @__PURE__ */ new Set([
      "write_file",
      "edit",
      "replace",
      "create_file"
    ]);
    __name(makeTaskRecord, "makeTaskRecord");
    __name(updateRecord, "updateRecord");
    __name(partWritesToMemory, "partWritesToMemory");
    __name(historyWritesToMemory, "historyWritesToMemory");
    __name(isProcessRunning, "isProcessRunning");
    __name(readDreamMetadata, "readDreamMetadata");
    __name(writeDreamMetadata, "writeDreamMetadata");
    __name(hoursSince, "hoursSince");
    SESSION_FILE_PATTERN2 = /^[0-9a-fA-F-]{32,36}\.jsonl$/;
    __name(defaultSessionScanner, "defaultSessionScanner");
    __name(dreamLockExists, "dreamLockExists");
    __name(acquireDreamLock, "acquireDreamLock");
    __name(releaseDreamLock, "releaseDreamLock");
    MemoryManager = class {
      static {
        __name(this, "MemoryManager");
      }
      // ── Task records ────────────────────────────────────────────────────────────
      tasks = /* @__PURE__ */ new Map();
      // ── Subscribers (useSyncExternalStore / custom listeners) ────────────────
      subscribers = /* @__PURE__ */ new Set();
      // ── In-flight promises (for drain) ──────────────────────────────────────────
      inFlight = /* @__PURE__ */ new Map();
      // ── Extract scheduling state ─────────────────────────────────────────────────
      extractRunning = /* @__PURE__ */ new Set();
      extractCurrentTaskId = /* @__PURE__ */ new Map();
      extractQueued = /* @__PURE__ */ new Map();
      // ── Dream scheduling state ───────────────────────────────────────────────────
      dreamInFlightByKey = /* @__PURE__ */ new Map();
      dreamLastSessionScanAt = /* @__PURE__ */ new Map();
      sessionScanner;
      constructor(sessionScanner = defaultSessionScanner) {
        this.sessionScanner = sessionScanner;
      }
      // ─── Subscribe ───────────────────────────────────────────────────────────────────
      /**
       * Register a listener that is called whenever any task record changes.
       * Compatible with React’s `useSyncExternalStore`.
       * Returns an unsubscribe function.
       */
      subscribe(listener) {
        this.subscribers.add(listener);
        return () => this.subscribers.delete(listener);
      }
      notify() {
        for (const fn of this.subscribers)
          fn();
      }
      /** Update a record and notify subscribers. */
      update(record2, patch) {
        updateRecord(record2, patch);
        this.notify();
      }
      /**
       * Register a brand-new record in the task map and notify once.
       * Use this for records that start in 'pending' and need no immediate patch.
       */
      store(record2) {
        this.tasks.set(record2.id, record2);
        this.notify();
      }
      /**
       * Register a brand-new record AND apply an initial status patch in a single
       * notify. Avoids the double-render that separate store()+update() causes.
       */
      storeWith(record2, patch) {
        updateRecord(record2, patch);
        this.tasks.set(record2.id, record2);
        this.notify();
      }
      // ─── Task record query ────────────────────────────────────────────────────────
      /** Return task records filtered by type and optionally by projectRoot. */
      listTasksByType(taskType, projectRoot) {
        return [...this.tasks.values()].filter((t5) => t5.taskType === taskType && (!projectRoot || t5.projectRoot === projectRoot)).sort((a2, b2) => b2.updatedAt.localeCompare(a2.updatedAt));
      }
      // ─── Drain ────────────────────────────────────────────────────────────────────
      /** Wait for all in-flight tasks to settle, with optional timeout. */
      async drain(options2 = {}) {
        const promises9 = [...this.inFlight.values()];
        if (promises9.length === 0)
          return true;
        const waitAll = Promise.allSettled(promises9).then(() => true);
        if (!options2.timeoutMs || options2.timeoutMs <= 0)
          return waitAll;
        return Promise.race([
          waitAll,
          new Promise((resolve42) => setTimeout(() => resolve42(false), options2.timeoutMs))
        ]);
      }
      track(taskId, promise2) {
        this.inFlight.set(taskId, promise2);
        void promise2.finally(() => this.inFlight.delete(taskId));
        return promise2;
      }
      // ─── Extract ──────────────────────────────────────────────────────────────────
      /**
       * Schedule a managed auto-memory extraction for the given session turn.
       *
       * Returns immediately with a skipped result if:
       *   - The last history turn wrote to a memory file (memory_tool)
       *   - Extraction is already running for this project (queues trailing request)
       *
       * The trailing request starts automatically when the active extraction
       * completes.
       */
      async scheduleExtract(params) {
        if (historyWritesToMemory(params.history, params.projectRoot)) {
          const record3 = makeTaskRecord("extract", params.projectRoot, params.sessionId);
          this.storeWith(record3, {
            status: "skipped",
            progressText: "Skipped: main agent wrote to memory files this turn.",
            metadata: {
              skippedReason: "memory_tool",
              historyLength: params.history.length
            }
          });
          return {
            touchedTopics: [],
            skippedReason: "memory_tool",
            cursor: {
              sessionId: params.sessionId,
              updatedAt: (params.now ?? /* @__PURE__ */ new Date()).toISOString()
            }
          };
        }
        if (this.extractRunning.has(params.projectRoot)) {
          const currentTaskId = this.extractCurrentTaskId.get(params.projectRoot);
          if (!currentTaskId) {
            return {
              touchedTopics: [],
              skippedReason: "already_running",
              cursor: {
                sessionId: params.sessionId,
                updatedAt: (params.now ?? /* @__PURE__ */ new Date()).toISOString()
              }
            };
          }
          const queued = this.extractQueued.get(params.projectRoot);
          if (queued) {
            queued.params = params;
            const queuedRecord = this.tasks.get(queued.taskId);
            if (queuedRecord) {
              this.update(queuedRecord, {
                status: "pending",
                progressText: "Updated trailing managed auto-memory extraction request while another extraction is running.",
                metadata: {
                  queuedBehindTaskId: currentTaskId,
                  historyLength: params.history.length,
                  supersededAt: (/* @__PURE__ */ new Date()).toISOString()
                }
              });
            }
          } else {
            const record3 = makeTaskRecord("extract", params.projectRoot, params.sessionId);
            this.storeWith(record3, {
              status: "pending",
              progressText: "Queued trailing managed auto-memory extraction until the active extraction completes.",
              metadata: {
                trailing: true,
                queuedBehindTaskId: currentTaskId,
                historyLength: params.history.length
              }
            });
            this.extractQueued.set(params.projectRoot, {
              taskId: record3.id,
              params
            });
          }
          return {
            touchedTopics: [],
            skippedReason: "queued",
            cursor: {
              sessionId: params.sessionId,
              updatedAt: (params.now ?? /* @__PURE__ */ new Date()).toISOString()
            }
          };
        }
        const record2 = makeTaskRecord("extract", params.projectRoot, params.sessionId);
        this.store(record2);
        return this.track(record2.id, this.runExtract(record2.id, params));
      }
      async runExtract(taskId, params) {
        const record2 = this.tasks.get(taskId);
        this.extractCurrentTaskId.set(params.projectRoot, taskId);
        this.extractRunning.add(params.projectRoot);
        this.update(record2, {
          status: "running",
          progressText: "Running managed auto-memory extraction.",
          metadata: { historyLength: params.history.length }
        });
        const t02 = Date.now();
        try {
          const result = await runAutoMemoryExtract(params);
          const durationMs = Date.now() - t02;
          this.update(record2, {
            status: result.skippedReason ? "skipped" : "completed",
            progressText: result.systemMessage ?? (result.touchedTopics.length > 0 ? `Managed auto-memory updated: ${result.touchedTopics.join(", ")}.` : "Managed auto-memory extraction completed without durable changes."),
            metadata: {
              touchedTopics: result.touchedTopics,
              processedOffset: result.cursor.processedOffset,
              skippedReason: result.skippedReason
            }
          });
          if (params.config) {
            logMemoryExtract(params.config, new MemoryExtractEvent({
              trigger: "auto",
              status: "completed",
              patches_count: result.touchedTopics.length,
              touched_topics: result.touchedTopics,
              duration_ms: durationMs
            }));
          }
          return result;
        } catch (error40) {
          const durationMs = Date.now() - t02;
          this.update(record2, {
            status: "failed",
            error: error40 instanceof Error ? error40.message : String(error40)
          });
          if (params.config) {
            logMemoryExtract(params.config, new MemoryExtractEvent({
              trigger: "auto",
              status: "failed",
              patches_count: 0,
              touched_topics: [],
              duration_ms: durationMs
            }));
          }
          throw error40;
        } finally {
          this.extractCurrentTaskId.delete(params.projectRoot);
          this.extractRunning.delete(params.projectRoot);
          void this.startQueuedExtract(params.projectRoot);
        }
      }
      async startQueuedExtract(projectRoot) {
        if (this.extractRunning.has(projectRoot))
          return;
        const queued = this.extractQueued.get(projectRoot);
        if (!queued)
          return;
        this.extractQueued.delete(projectRoot);
        await this.track(queued.taskId, this.runExtract(queued.taskId, queued.params));
      }
      // ─── Dream ────────────────────────────────────────────────────────────────────
      /**
       * Maybe schedule a managed auto-memory dream (consolidation).
       * Returns immediately if preconditions aren't met (time gate, session count,
       * lock, or duplicate).
       */
      async scheduleDream(params) {
        if (params.config && !params.config.getManagedAutoDreamEnabled()) {
          return { status: "skipped", skippedReason: "disabled" };
        }
        const now = params.now ?? /* @__PURE__ */ new Date();
        const minHours = params.minHoursBetweenDreams ?? DEFAULT_AUTO_DREAM_MIN_HOURS;
        const minSessions = params.minSessionsBetweenDreams ?? DEFAULT_AUTO_DREAM_MIN_SESSIONS;
        await ensureAutoMemoryScaffold(params.projectRoot, now);
        const metadata2 = await readDreamMetadata(params.projectRoot);
        if (metadata2.lastDreamSessionId === params.sessionId) {
          return { status: "skipped", skippedReason: "same_session" };
        }
        const elapsedHours = hoursSince(metadata2.lastDreamAt, now);
        if (elapsedHours !== null && elapsedHours < minHours) {
          return { status: "skipped", skippedReason: "min_hours" };
        }
        const lastScan = this.dreamLastSessionScanAt.get(params.projectRoot) ?? 0;
        if (now.getTime() - lastScan < SESSION_SCAN_INTERVAL_MS) {
          return { status: "skipped", skippedReason: "scan_throttled" };
        }
        const lastDreamMs = metadata2.lastDreamAt ? Date.parse(metadata2.lastDreamAt) : 0;
        const sessionIds = await this.sessionScanner(params.projectRoot, lastDreamMs, params.sessionId);
        this.dreamLastSessionScanAt.set(params.projectRoot, now.getTime());
        if (sessionIds.length < minSessions) {
          return { status: "skipped", skippedReason: "min_sessions" };
        }
        if (await dreamLockExists(params.projectRoot)) {
          return { status: "skipped", skippedReason: "locked" };
        }
        const dedupeKey = `${DREAM_TASK_TYPE}:${params.projectRoot}`;
        const existingId = this.dreamInFlightByKey.get(dedupeKey);
        if (existingId) {
          return {
            status: "skipped",
            skippedReason: "running",
            taskId: existingId
          };
        }
        const record2 = makeTaskRecord("dream", params.projectRoot, params.sessionId);
        this.storeWith(record2, {
          status: "running",
          metadata: { sessionCount: sessionIds.length }
        });
        this.dreamInFlightByKey.set(dedupeKey, record2.id);
        const promise2 = this.track(record2.id, this.runDream(record2, dedupeKey, params, now));
        return { status: "scheduled", taskId: record2.id, promise: promise2 };
      }
      async runDream(record2, dedupeKey, params, now) {
        try {
          try {
            await acquireDreamLock(params.projectRoot);
          } catch (error40) {
            if (error40.code === "EEXIST") {
              this.update(record2, {
                status: "skipped",
                progressText: "Skipped managed auto-memory dream: consolidation lock already exists.",
                metadata: { skippedReason: "locked" }
              });
              return record2;
            }
            throw error40;
          }
          try {
            const result = await runManagedAutoMemoryDream(params.projectRoot, now, params.config);
            const nextMetadata = await readDreamMetadata(params.projectRoot);
            nextMetadata.lastDreamAt = now.toISOString();
            nextMetadata.lastDreamSessionId = params.sessionId;
            nextMetadata.updatedAt = now.toISOString();
            await writeDreamMetadata(params.projectRoot, nextMetadata);
            this.update(record2, {
              status: "completed",
              progressText: result.systemMessage ?? "Managed auto-memory dream completed.",
              metadata: {
                touchedTopics: result.touchedTopics,
                dedupedEntries: result.dedupedEntries,
                lastDreamAt: now.toISOString()
              }
            });
          } finally {
            await releaseDreamLock(params.projectRoot);
          }
        } catch (error40) {
          this.update(record2, {
            status: "failed",
            error: error40 instanceof Error ? error40.message : String(error40)
          });
        } finally {
          this.dreamInFlightByKey.delete(dedupeKey);
        }
        return record2;
      }
      // ─── Recall ───────────────────────────────────────────────────────────────────
      /** Select and format relevant memory for the given query. */
      recall(projectRoot, query, options2 = {}) {
        return resolveRelevantAutoMemoryPromptForQuery(projectRoot, query, options2);
      }
      // ─── Forget ───────────────────────────────────────────────────────────────────
      /** Select candidate memory entries matching the given query (step 1 of forget). */
      selectForgetCandidates(projectRoot, query, options2 = {}) {
        return selectManagedAutoMemoryForgetCandidates(projectRoot, query, options2);
      }
      /** Remove the selected memory entries (step 2 of forget). */
      forgetMatches(projectRoot, matches2, now) {
        return forgetManagedAutoMemoryMatches(projectRoot, matches2, now);
      }
      /** Convenience: select + remove in a single call. */
      forget(projectRoot, query, options2 = {}, now) {
        return forgetManagedAutoMemoryEntries(projectRoot, query, options2, now);
      }
      // ─── Status ───────────────────────────────────────────────────────────────────
      /** Return a full status snapshot for the given project's memory. */
      getStatus(projectRoot) {
        return getManagedAutoMemoryStatus(projectRoot, this);
      }
      // ─── Prompt append ────────────────────────────────────────────────────────────
      /** Append the managed auto-memory section to a user memory string. */
      appendToUserMemory(userMemory, memoryDir, indexContent) {
        return appendManagedAutoMemoryToUserMemory(userMemory, memoryDir, indexContent);
      }
      // ─── Dream utilities ──────────────────────────────────────────────────────────
      /**
       * Record that a manual dream run has completed for the given session.
       * Call this from the dreamCommand's onComplete callback.
       */
      writeDreamManualRun(projectRoot, sessionId, now) {
        return writeDreamManualRunToMetadata(projectRoot, sessionId, now);
      }
      /**
       * Build the consolidation task prompt used by the dream slash command.
       * Returns a prompt string describing what the agent should do.
       */
      buildConsolidationPrompt(memoryRoot, transcriptDir) {
        return buildConsolidationTaskPrompt(memoryRoot, transcriptDir);
      }
      // ─── Test helpers ─────────────────────────────────────────────────────────────
      /** Reset all extract scheduling state. Call from afterEach in tests. */
      resetExtractStateForTests() {
        this.extractRunning.clear();
        this.extractCurrentTaskId.clear();
        this.extractQueued.clear();
      }
      /** Reset all dream scheduling state. */
      resetDreamStateForTests() {
        this.dreamInFlightByKey.clear();
        this.dreamLastSessionScanAt.clear();
      }
    };
    globalMemoryManager = new MemoryManager();
  }
});

// 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(env6, key, transform2) {
  const rawValue = env6[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 applyTimeoutEnvOverride(env6, generationConfig, sources, modelProvider) {
  if (modelProvider?.generationConfig?.timeout !== void 0)
    return;
  const raw2 = env6["QWEN_CODE_API_TIMEOUT_MS"];
  if (raw2 === void 0)
    return;
  const parsed = Number(raw2);
  if (Number.isFinite(parsed) && parsed > 0) {
    generationConfig.timeout = Math.floor(parsed);
    sources["timeout"] = {
      kind: "env",
      envKey: "QWEN_CODE_API_TIMEOUT_MS"
    };
  }
}
function resolveModelConfig(input) {
  const { authType, cli, settings, env: env6, modelProvider, proxy: proxy2 } = 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(env6, 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 = env6[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(env6, 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(env6, 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"),
      envKey: modelProvider.envKey
    };
  }
  const generationConfig = resolveGenerationConfig(settings?.generationConfig, modelProvider?.generationConfig, authType, modelProvider?.id, sources);
  applyTimeoutEnvOverride(env6, generationConfig, sources, modelProvider);
  const config2 = {
    authType,
    model: modelResult.value || "",
    apiKey: apiKeyResult?.value,
    apiKeyEnvKey,
    baseUrl: baseUrlResult?.value,
    proxy: proxy2,
    ...generationConfig
  };
  if (proxy2) {
    sources["proxy"] = computedSource("Config.getProxy()");
  }
  sources["authType"] = computedSource("provided by caller");
  return { config: config2, sources, warnings };
}
function resolveQwenOAuthConfig(input, warnings) {
  const { cli, settings, proxy: proxy2, 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 (proxy2) {
    sources["proxy"] = computedSource("Config.getProxy()");
  }
  const generationConfig = resolveGenerationConfig(settings?.generationConfig, modelProvider?.generationConfig, AuthType2.QWEN_OAUTH, resolvedModel, sources);
  applyTimeoutEnvOverride(input.env, generationConfig, sources, modelProvider);
  const config2 = {
    authType: AuthType2.QWEN_OAUTH,
    model: resolvedModel,
    apiKey: "QWEN_OAUTH_DYNAMIC_TOKEN",
    proxy: proxy2,
    ...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(applyTimeoutEnvOverride, "applyTimeoutEnvOverride");
    __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_types5();
    init_modelRegistry();
    init_modelsConfig();
    init_constants3();
    init_modelConfigResolver();
  }
});

// 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 i4 = 0; i4 <= lines.length - pattern.length; i4++) {
    for (let p2 = 0; p2 < pattern.length; p2++) {
      if (transform2(lines[i4 + p2]) !== transform2(pattern[p2])) {
        continue outer;
      }
    }
    return i4;
  }
  return null;
}
function buildLineIndex(text) {
  const lines = text.split("\n");
  const offsets = new Array(lines.length + 1);
  let cursor = 0;
  for (let i4 = 0; i4 < lines.length; i4++) {
    offsets[i4] = cursor;
    cursor += lines[i4].length;
    if (i4 < 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
var edit_exports = {};
__export(edit_exports, {
  EditTool: () => EditTool,
  applyReplacement: () => applyReplacement
});
import * as fs81 from "node:fs";
import * as path73 from "node:path";
function applyReplacement(currentContent, oldString, newString, isNewFile) {
  if (isNewFile) {
    return newString;
  }
  if (currentContent === null) {
    return oldString === "" ? newString : "";
  }
  if (oldString === "" && !isNewFile) {
    return currentContent;
  }
  return safeLiteralReplace(currentContent, oldString, newString);
}
var EditToolInvocation, EditTool;
var init_edit = __esm({
  "packages/core/dist/src/tools/edit.js"() {
    "use strict";
    init_esbuild_shims();
    init_lib();
    init_tools();
    init_tool_error();
    init_paths();
    init_errors();
    init_config3();
    init_paths2();
    init_fileSystemService();
    init_diffOptions();
    init_read_file();
    init_tool_names();
    init_loggers();
    init_types4();
    init_metrics2();
    init_fileUtils();
    init_language_detection();
    init_textUtils();
    init_editHelper();
    __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 = await fileExists(params.file_path);
        let isNewFile = false;
        let finalNewString = params.new_string;
        let finalOldString = params.old_string;
        let occurrences = 0;
        let error40 = void 0;
        let useBOM = false;
        let detectedEncoding = "utf-8";
        let detectedLineEnding = "lf";
        if (fileExists2) {
          try {
            const fileInfo = await this.config.getFileSystemService().readTextFile({ path: params.file_path });
            if (fileInfo._meta?.bom !== void 0) {
              useBOM = fileInfo._meta.bom;
            } else {
              useBOM = fileInfo.content.length > 0 && fileInfo.content.codePointAt(0) === 65279;
            }
            detectedEncoding = fileInfo._meta?.encoding || "utf-8";
            detectedLineEnding = detectLineEnding(fileInfo.content);
            currentContent = fileInfo.content.replace(/\r\n/g, "\n");
            fileExists2 = true;
          } catch (err2) {
            if (!isNodeError(err2) || err2.code !== "ENOENT") {
              throw err2;
            }
            fileExists2 = false;
          }
        }
        const normalizedStrings = normalizeEditStrings(currentContent, finalOldString, finalNewString);
        finalOldString = normalizedStrings.oldString;
        finalNewString = normalizedStrings.newString;
        if (finalOldString === "" && !fileExists2) {
          isNewFile = true;
        } else if (!fileExists2) {
          error40 = {
            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 === "") {
            error40 = {
              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) {
            error40 = {
              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) {
            error40 = {
              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) {
            error40 = {
              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 {
          error40 = {
            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 = !error40 ? applyReplacement(currentContent, finalOldString, finalNewString, isNewFile) : currentContent ?? "";
        if (!error40 && fileExists2 && currentContent === newContent) {
          error40 = {
            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: error40,
          isNewFile,
          bom: useBOM,
          encoding: detectedEncoding,
          lineEnding: detectedLineEnding
        };
      }
      /**
       * Edit operations always need user confirmation, except for managed
       * auto-memory files which are written autonomously by the model.
       */
      async getDefaultPermission() {
        const projectRoot = this.config.getProjectRoot();
        if (isAutoMemPath(path73.resolve(this.params.file_path), projectRoot)) {
          return "allow";
        }
        return "ask";
      }
      /**
       * Constructs the edit diff confirmation details.
       */
      async getConfirmationDetails(abortSignal) {
        let editData;
        try {
          editData = await this.calculateEdit(this.params);
        } catch (error40) {
          if (abortSignal.aborted) {
            throw error40;
          }
          const errorMsg = error40 instanceof Error ? error40.message : String(error40);
          throw new Error(`Error preparing edit: ${errorMsg}`);
        }
        if (editData.error) {
          throw new Error(`Edit error: ${editData.error.display}`);
        }
        const fileName = path73.basename(this.params.file_path);
        const fileDiff = createPatch(fileName, editData.currentContent ?? "", editData.newContent, "Current", "Proposed", DEFAULT_DIFF_OPTIONS);
        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);
            }
          }, "onConfirm")
        };
        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 (error40) {
          if (signal.aborted) {
            throw error40;
          }
          const errorMsg = error40 instanceof Error ? error40.message : String(error40);
          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 userEncoding = this.config.getDefaultFileEncoding();
            let useBOM = false;
            if (userEncoding === FileEncoding.UTF8_BOM) {
              useBOM = true;
            } else if (userEncoding === void 0) {
              useBOM = needsUtf8Bom(this.params.file_path);
            }
            await this.config.getFileSystemService().writeTextFile({
              path: this.params.file_path,
              content: editData.newContent,
              _meta: {
                bom: useBOM
              }
            });
          } else {
            await this.config.getFileSystemService().writeTextFile({
              path: this.params.file_path,
              content: editData.newContent,
              _meta: {
                bom: editData.bom,
                encoding: editData.encoding,
                lineEnding: editData.lineEnding
              }
            });
          }
          const fileName = path73.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 = path73.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 (error40) {
          const errorMsg = error40 instanceof Error ? error40.message : String(error40);
          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 = path73.dirname(filePath);
        if (!fs81.existsSync(dirName)) {
          fs81.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 (!path73.isAbsolute(params.file_path)) {
          return `File path must be absolute: ${params.file_path}`;
        }
        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) => {
            const fileExists2 = await fileExists(params.file_path);
            if (fileExists2) {
              try {
                const { content } = await this.config.getFileSystemService().readTextFile({ path: params.file_path });
                return content;
              } catch (err2) {
                if (!isNodeError(err2) || err2.code !== "ENOENT")
                  throw err2;
                return "";
              }
            } else {
              return "";
            }
          }, "getCurrentContent"),
          getProposedContent: /* @__PURE__ */ __name(async (params) => {
            if (fs81.existsSync(params.file_path)) {
              try {
                const { content: currentContent } = await this.config.getFileSystemService().readTextFile({ path: params.file_path });
                return applyReplacement(currentContent, params.old_string, params.new_string, params.old_string === "" && currentContent === "");
              } catch (err2) {
                if (!isNodeError(err2) || err2.code !== "ENOENT")
                  throw err2;
                return "";
              }
            } else {
              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/agent/agent-context.js
import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
function runWithAgentContext(context2, fn) {
  return agentContextStorage.run(context2, fn);
}
function getCurrentAgentId() {
  return agentContextStorage.getStore()?.agentId ?? null;
}
var agentContextStorage;
var init_agent_context = __esm({
  "packages/core/dist/src/tools/agent/agent-context.js"() {
    "use strict";
    init_esbuild_shims();
    agentContextStorage = new AsyncLocalStorage6();
    __name(runWithAgentContext, "runWithAgentContext");
    __name(getCurrentAgentId, "getCurrentAgentId");
  }
});

// packages/core/dist/src/agents/agent-transcript.js
import * as fs82 from "node:fs";
import * as path74 from "node:path";
import { randomUUID as randomUUID8 } from "node:crypto";
function sanitizeFilenameComponent(value) {
  return value.replace(/[^a-zA-Z0-9_-]/g, "_");
}
function getSubagentSessionDir(projectDir, sessionId) {
  return path74.join(projectDir, "subagents", sanitizeFilenameComponent(sessionId));
}
function getAgentJsonlPath(projectDir, sessionId, agentId) {
  return path74.join(getSubagentSessionDir(projectDir, sessionId), `agent-${sanitizeFilenameComponent(agentId)}.jsonl`);
}
function getAgentMetaPath(projectDir, sessionId, agentId) {
  return path74.join(getSubagentSessionDir(projectDir, sessionId), `agent-${sanitizeFilenameComponent(agentId)}.meta.json`);
}
function writeAgentMeta(metaPath, meta) {
  try {
    fs82.mkdirSync(path74.dirname(metaPath), { recursive: true });
    fs82.writeFileSync(metaPath, JSON.stringify(meta, null, 2), "utf8");
  } catch (error40) {
    debugLogger86.warn(`Failed to write agent meta sidecar ${metaPath}:`, error40);
  }
}
function attachJsonlTranscriptWriter(emitter, jsonlPath, options2) {
  let lastUuid = null;
  let fd = null;
  let openFailed = false;
  const ensureOpen = /* @__PURE__ */ __name(() => {
    if (fd !== null)
      return true;
    if (openFailed)
      return false;
    try {
      fs82.mkdirSync(path74.dirname(jsonlPath), { recursive: true });
      fd = fs82.openSync(jsonlPath, "a");
      return true;
    } catch (error40) {
      debugLogger86.warn(`Failed to open JSONL transcript ${jsonlPath}:`, error40);
      openFailed = true;
      return false;
    }
  }, "ensureOpen");
  const baseFields = /* @__PURE__ */ __name((type) => ({
    uuid: randomUUID8(),
    parentUuid: lastUuid,
    sessionId: options2.sessionId,
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    type,
    cwd: options2.cwd,
    version: options2.version,
    gitBranch: options2.gitBranch,
    agentId: options2.agentId,
    agentName: options2.agentName,
    agentColor: options2.agentColor,
    isSidechain: true
  }), "baseFields");
  const append3 = /* @__PURE__ */ __name((record2) => {
    if (!ensureOpen())
      return;
    try {
      fs82.writeSync(fd, JSON.stringify(record2) + "\n");
      lastUuid = record2.uuid;
    } catch (error40) {
      debugLogger86.warn(`Failed to append JSONL record to ${jsonlPath}:`, error40);
    }
  }, "append");
  const onRoundText = /* @__PURE__ */ __name((event) => {
    if (!event.text)
      return;
    append3({
      ...baseFields("assistant"),
      message: { role: "model", parts: [{ text: event.text }] }
    });
  }, "onRoundText");
  const onToolCall = /* @__PURE__ */ __name((event) => {
    append3({
      ...baseFields("assistant"),
      message: {
        role: "model",
        parts: [
          {
            functionCall: {
              id: event.callId,
              name: event.name,
              args: event.args
            }
          }
        ]
      }
    });
  }, "onToolCall");
  const onToolResult = /* @__PURE__ */ __name((event) => {
    const parts2 = event.responseParts ?? [
      {
        functionResponse: {
          id: event.callId,
          name: event.name,
          response: {
            success: event.success,
            ...event.error ? { error: event.error } : {}
          }
        }
      }
    ];
    append3({
      ...baseFields("tool_result"),
      message: { role: "user", parts: parts2 },
      toolCallResult: {
        callId: event.callId,
        ...event.durationMs !== void 0 ? { durationMs: event.durationMs } : {}
      }
    });
  }, "onToolResult");
  const recordUserMessage = /* @__PURE__ */ __name((text) => {
    if (!text)
      return;
    append3({
      ...baseFields("user"),
      message: { role: "user", parts: [{ text }] }
    });
  }, "recordUserMessage");
  const onExternalMessage = /* @__PURE__ */ __name((event) => {
    recordUserMessage(event.text);
  }, "onExternalMessage");
  if (options2.initialUserPrompt) {
    recordUserMessage(options2.initialUserPrompt);
  }
  emitter.on(AgentEventType.ROUND_TEXT, onRoundText);
  emitter.on(AgentEventType.TOOL_CALL, onToolCall);
  emitter.on(AgentEventType.TOOL_RESULT, onToolResult);
  emitter.on(AgentEventType.EXTERNAL_MESSAGE, onExternalMessage);
  const cleanup = /* @__PURE__ */ __name(() => {
    emitter.off(AgentEventType.ROUND_TEXT, onRoundText);
    emitter.off(AgentEventType.TOOL_CALL, onToolCall);
    emitter.off(AgentEventType.TOOL_RESULT, onToolResult);
    emitter.off(AgentEventType.EXTERNAL_MESSAGE, onExternalMessage);
    if (fd !== null) {
      try {
        fs82.closeSync(fd);
      } catch {
      }
      fd = null;
    }
  }, "cleanup");
  return { cleanup };
}
var debugLogger86;
var init_agent_transcript = __esm({
  "packages/core/dist/src/agents/agent-transcript.js"() {
    "use strict";
    init_esbuild_shims();
    init_agent_events();
    init_chatRecordingService();
    init_debugLogger();
    debugLogger86 = createDebugLogger("AGENT_TRANSCRIPT");
    __name(sanitizeFilenameComponent, "sanitizeFilenameComponent");
    __name(getSubagentSessionDir, "getSubagentSessionDir");
    __name(getAgentJsonlPath, "getAgentJsonlPath");
    __name(getAgentMetaPath, "getAgentMetaPath");
    __name(writeAgentMeta, "writeAgentMeta");
    __name(attachJsonlTranscriptWriter, "attachJsonlTranscriptWriter");
  }
});

// packages/core/dist/src/tools/agent/agent.js
var agent_exports = {};
__export(agent_exports, {
  AgentTool: () => AgentTool,
  resolveSubagentApprovalMode: () => resolveSubagentApprovalMode
});
import { randomUUID as randomUUID9 } from "node:crypto";
function approvalModeToPermissionMode(mode) {
  switch (mode) {
    case ApprovalMode.YOLO:
      return PermissionMode.Yolo;
    case ApprovalMode.AUTO_EDIT:
      return PermissionMode.AutoEdit;
    case ApprovalMode.PLAN:
      return PermissionMode.Plan;
    case ApprovalMode.DEFAULT:
    default:
      return PermissionMode.Default;
  }
}
function resolveSubagentApprovalMode(parentApprovalMode, agentApprovalMode, isTrustedFolder) {
  if (parentApprovalMode === ApprovalMode.YOLO || parentApprovalMode === ApprovalMode.AUTO_EDIT) {
    return approvalModeToPermissionMode(parentApprovalMode);
  }
  if (agentApprovalMode) {
    const resolved = approvalModeToPermissionMode(agentApprovalMode);
    if (!isTrustedFolder && (resolved === PermissionMode.Yolo || resolved === PermissionMode.AutoEdit)) {
      return approvalModeToPermissionMode(parentApprovalMode);
    }
    return resolved;
  }
  if (parentApprovalMode === ApprovalMode.PLAN) {
    return PermissionMode.Plan;
  }
  if (isTrustedFolder) {
    return PermissionMode.AutoEdit;
  }
  return approvalModeToPermissionMode(parentApprovalMode);
}
function permissionModeToApprovalMode(mode) {
  switch (mode) {
    case PermissionMode.Yolo:
      return ApprovalMode.YOLO;
    case PermissionMode.AutoEdit:
      return ApprovalMode.AUTO_EDIT;
    case PermissionMode.Plan:
      return ApprovalMode.PLAN;
    case PermissionMode.Default:
    default:
      return ApprovalMode.DEFAULT;
  }
}
function createApprovalModeOverride(base, mode) {
  const override = Object.create(base);
  override.getApprovalMode = () => mode;
  return override;
}
var debugLogger87, AgentTool, AgentToolInvocation;
var init_agent = __esm({
  "packages/core/dist/src/tools/agent/agent.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_names();
    init_tools();
    init_agent_types();
    init_agent_headless();
    init_fork_subagent();
    init_agent_context();
    init_agent_events();
    init_builtin_agents();
    init_debugLogger();
    init_types6();
    init_config3();
    init_agent_transcript();
    init_gitUtils();
    debugLogger87 = createDebugLogger("AGENT");
    __name(approvalModeToPermissionMode, "approvalModeToPermissionMode");
    __name(resolveSubagentApprovalMode, "resolveSubagentApprovalMode");
    __name(permissionModeToApprovalMode, "permissionModeToApprovalMode");
    __name(createApprovalModeOverride, "createApprovalModeOverride");
    AgentTool = class _AgentTool extends BaseDeclarativeTool {
      static {
        __name(this, "AgentTool");
      }
      config;
      static Name = ToolNames.AGENT;
      subagentManager;
      availableSubagents = BuiltinAgentRegistry.getBuiltinAgents();
      removeChangeListener;
      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"
            },
            run_in_background: {
              type: "boolean",
              description: "Set to true to run this agent in the background. You will be notified when it completes."
            }
          },
          required: ["description", "prompt"],
          additionalProperties: false,
          $schema: "http://json-schema.org/draft-07/schema#"
        };
        super(
          _AgentTool.Name,
          ToolDisplayNames.AGENT,
          "Launch a new agent to handle complex, multi-step tasks autonomously.\n\nThe Agent tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.\n\nAvailable agent types and the tools they have access to:\n",
          Kind.Other,
          initialSchema,
          true,
          // isOutputMarkdown
          true
        );
        this.config = config2;
        this.subagentManager = config2.getSubagentManager();
        this.removeChangeListener = this.subagentManager.addChangeListener(() => {
          void this.refreshSubagents();
        });
        this.refreshSubagents();
      }
      dispose() {
        this.removeChangeListener();
      }
      /**
       * 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 (error40) {
          debugLogger87.warn("Failed to load agents for Agent tool:", error40);
          this.availableSubagents = BuiltinAgentRegistry.getBuiltinAgents();
          this.updateDescriptionAndSchema();
        } finally {
          const geminiClient = this.config.getGeminiClient();
          if (geminiClient) {
            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.
The Agent tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.

Available agent types and the tools they have access to:
${subagentDescriptions}

When using the Agent tool, 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 ${ToolNames.READ_FILE} tool or the ${ToolNames.GLOB} tool instead of the ${ToolNames.AGENT} tool, to find the match more quickly
- If you are searching for a specific class definition like "class Foo", use the ${ToolNames.GREP} 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 ${ToolNames.READ_FILE} tool instead of the ${ToolNames.AGENT} tool, to find the match more quickly
- Other tasks that are not related to the agent descriptions above


Usage notes:
- Always include a short description (3-5 words) summarizing what the agent will do
- Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
- 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.
- Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.
- The agent's outputs should generally be trusted
- 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
- 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.
- If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple Agent tool use content blocks. For example, if you need to launch both a build-validator agent and a test-runner agent in parallel, send a single message with both tool calls.
- You can optionally set \`run_in_background: true\` to run the agent in the background. You will be notified when it completes. Use this when you have genuinely independent work to do in parallel and don't need the agent's results before you can proceed.

Example usage:

<example_agent_descriptions>
"test-runner": use this agent after you are done writing code to run tests
"greeting-responder": use this agent to respond to user greetings with a friendly joke
</example_agent_descriptions>

<example>
user: "Please 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 significant piece of code was written and the task was completed, now use the test-runner agent to run the tests
</commentary>
assistant: Uses the ${ToolNames.AGENT} tool to launch the test-runner 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 ${ToolNames.AGENT} tool to launch the greeting-responder agent"
</example>
`;
        this.description = baseDescription;
        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 !== void 0) {
          if (typeof params.subagent_type !== "string" || params.subagent_type.trim() === "") {
            return 'Parameter "subagent_type" must be a non-empty string.';
          }
          const lowerType = params.subagent_type.toLowerCase();
          const subagentExists = this.availableSubagents.some((subagent) => subagent.name.toLowerCase() === lowerType);
          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 AgentToolInvocation(this.config, this.subagentManager, params);
      }
      getAvailableSubagentNames() {
        return this.availableSubagents.map((subagent) => subagent.name);
      }
    };
    AgentToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "AgentToolInvocation");
      }
      config;
      subagentManager;
      eventEmitter = new AgentEventEmitter();
      currentDisplay = null;
      currentToolCalls = [];
      callId;
      constructor(config2, subagentManager, params) {
        super(params);
        this.config = config2;
        this.subagentManager = subagentManager;
      }
      // Background agents carry the tool-use id through to completion notifications.
      setCallId(callId) {
        this.callId = callId;
      }
      /**
       * 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) {
        let pendingConfirmationCallId;
        this.eventEmitter.on(AgentEventType.START, () => {
          this.updateDisplay({ status: "running" }, updateOutput2);
        });
        this.eventEmitter.on(AgentEventType.TOOL_CALL, (...args2) => {
          const event = args2[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(AgentEventType.TOOL_RESULT, (...args2) => {
          const event = args2[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
            };
            const clearPending = pendingConfirmationCallId === event.callId ? { pendingConfirmation: void 0 } : {};
            if (pendingConfirmationCallId === event.callId) {
              pendingConfirmationCallId = void 0;
            }
            this.updateDisplay({
              toolCalls: [...this.currentToolCalls],
              ...clearPending
            }, updateOutput2);
          }
        });
        this.eventEmitter.on(AgentEventType.FINISH, (...args2) => {
          const event = args2[0];
          this.updateDisplay({
            status: event.terminateReason === "GOAL" ? "completed" : "failed",
            terminateReason: event.terminateReason
          }, updateOutput2);
        });
        this.eventEmitter.on(AgentEventType.ERROR, (...args2) => {
          const event = args2[0];
          this.updateDisplay({
            status: "failed",
            terminateReason: event.error
          }, updateOutput2);
        });
        let accumulatedOutputTokens = 0;
        this.eventEmitter.on(AgentEventType.USAGE_METADATA, (...args2) => {
          const event = args2[0];
          const outputTokens = event.usage?.candidatesTokenCount ?? 0;
          if (outputTokens > 0) {
            accumulatedOutputTokens += outputTokens;
            this.updateDisplay({ tokenCount: accumulatedOutputTokens }, updateOutput2);
          }
        });
        this.eventEmitter.on(AgentEventType.TOOL_WAITING_APPROVAL, (...args2) => {
          const event = args2[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
            });
          }
          pendingConfirmationCallId = event.callId;
          const details = {
            ...event.confirmationDetails,
            onConfirm: /* @__PURE__ */ __name(async (outcome, payload) => {
              pendingConfirmationCallId = void 0;
              const proceedOutcomes = /* @__PURE__ */ new Set([
                ToolConfirmationOutcome.ProceedOnce,
                ToolConfirmationOutcome.ProceedAlways,
                ToolConfirmationOutcome.ProceedAlwaysServer,
                ToolConfirmationOutcome.ProceedAlwaysTool,
                ToolConfirmationOutcome.ProceedAlwaysProject,
                ToolConfirmationOutcome.ProceedAlwaysUser
              ]);
              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.description;
      }
      /**
       * Creates a fork subagent that inherits the parent's conversation context
       * and cache-safe generation params.
       */
      async createForkSubagent(agentConfig, eventEmitter = this.eventEmitter) {
        const geminiClient = this.config.getGeminiClient();
        const rawHistory = geminiClient ? geminiClient.getHistory(true) : [];
        let initialMessages;
        let taskPrompt;
        if (rawHistory.length > 0) {
          const lastMessage = rawHistory[rawHistory.length - 1];
          if (lastMessage.role === "model") {
            const forkedMessages = buildForkedMessages(this.params.prompt, lastMessage);
            if (forkedMessages.length > 0) {
              initialMessages = [
                ...rawHistory.slice(0, -1),
                ...forkedMessages,
                {
                  role: "model",
                  parts: [{ text: "Understood. Executing directive now." }]
                }
              ];
              taskPrompt = "Begin.";
            } else {
              initialMessages = [...rawHistory];
            }
          } else {
            initialMessages = rawHistory.slice(0, -1);
          }
        }
        if (!taskPrompt) {
          taskPrompt = buildChildMessage(this.params.prompt);
        }
        let promptConfig;
        let toolConfig;
        const generationConfig = geminiClient?.getChat().getGenerationConfig();
        if (generationConfig?.systemInstruction) {
          const parentToolDecls = generationConfig.tools?.flatMap((t5) => t5.functionDeclarations ?? []) ?? [];
          promptConfig = {
            renderedSystemPrompt: generationConfig.systemInstruction,
            initialMessages
          };
          toolConfig = {
            tools: parentToolDecls.length > 0 ? parentToolDecls : ["*"]
          };
        } else {
          promptConfig = {
            systemPrompt: FORK_AGENT.systemPrompt,
            initialMessages
          };
          toolConfig = { tools: ["*"] };
        }
        const subagent = await AgentHeadless.create(FORK_AGENT.name, agentConfig, promptConfig, {}, {}, toolConfig, eventEmitter);
        return { subagent, taskPrompt };
      }
      // Runs the SubagentStop hook after execution. On a blocking decision, feeds the
      // reason back and re-executes — up to 5 iterations to defend against a
      // misconfigured hook looping forever.
      async runSubagentStopHookLoop(subagent, opts) {
        const { agentId, agentType, resolvedMode, signal } = opts;
        const hookSystem = this.config.getHookSystem();
        if (!hookSystem)
          return;
        const transcriptPath = this.config.getTranscriptPath();
        let stopHookActive = false;
        const maxIterations = 5;
        for (let i4 = 0; i4 < maxIterations; i4++) {
          try {
            const stopHookOutput = await hookSystem.fireSubagentStopEvent(agentId, agentType, transcriptPath, subagent.getFinalText(), stopHookActive, resolvedMode, signal);
            const typedStopOutput = stopHookOutput;
            if (!typedStopOutput?.isBlockingDecision() && !typedStopOutput?.shouldStopExecution()) {
              return;
            }
            stopHookActive = true;
            const continueContext = new ContextState();
            continueContext.set("task_prompt", typedStopOutput.getEffectiveReason());
            await subagent.execute(continueContext, signal);
            if (signal?.aborted)
              return;
          } catch (hookError) {
            debugLogger87.warn(`[Agent] SubagentStop hook failed, allowing stop: ${hookError}`);
            return;
          }
        }
        debugLogger87.warn(`[Agent] SubagentStop hook reached maximum iterations (${maxIterations}), forcing stop`);
      }
      /**
       * Runs a subagent with start/stop hook lifecycle, updating the display
       * as execution progresses.
       */
      async runSubagentWithHooks(subagent, contextState, opts) {
        const { agentId, agentType, resolvedMode, signal, updateOutput: updateOutput2 } = opts;
        const hookSystem = this.config.getHookSystem();
        try {
          if (hookSystem) {
            try {
              const startHookOutput = await hookSystem.fireSubagentStartEvent(agentId, agentType, resolvedMode, signal);
              const additionalContext = startHookOutput?.getAdditionalContext();
              if (additionalContext) {
                contextState.set("hook_context", additionalContext);
              }
            } catch (hookError) {
              debugLogger87.warn(`[Agent] SubagentStart hook failed, continuing execution: ${hookError}`);
            }
          }
          await subagent.execute(contextState, signal);
          if (hookSystem && !signal?.aborted) {
            await this.runSubagentStopHookLoop(subagent, {
              agentId,
              agentType,
              resolvedMode,
              signal
            });
          }
          const finalText = subagent.getFinalText();
          const terminateMode = subagent.getTerminateMode();
          const success2 = terminateMode === AgentTerminateMode.GOAL;
          const executionSummary = subagent.getExecutionSummary();
          if (signal?.aborted) {
            this.updateDisplay({
              status: "cancelled",
              terminateReason: "Agent was cancelled by user",
              executionSummary
            }, updateOutput2);
          } else {
            this.updateDisplay({
              status: success2 ? "completed" : "failed",
              terminateReason: terminateMode,
              result: finalText,
              executionSummary
            }, updateOutput2);
          }
        } catch (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          debugLogger87.error(`[AgentTool] Error inside subagent background task: ${errorMessage}`);
          this.updateDisplay({
            status: "failed",
            terminateReason: `Failed to run subagent: ${errorMessage}`
          }, updateOutput2);
        }
      }
      async execute(signal, updateOutput2) {
        try {
          const isFork = !this.params.subagent_type;
          let subagentConfig;
          if (isFork) {
            subagentConfig = FORK_AGENT;
            if (isInForkExecution()) {
              return {
                llmContent: "Error: Cannot create a fork from within an existing fork child. Please execute tasks directly.",
                returnDisplay: {
                  type: "task_execution",
                  subagentName: FORK_AGENT.name,
                  taskDescription: this.params.description,
                  taskPrompt: this.params.prompt,
                  status: "failed",
                  terminateReason: "Recursive forking is not allowed"
                }
              };
            }
          } else {
            const loadedConfig = await this.subagentManager.loadSubagent(this.params.subagent_type);
            if (!loadedConfig) {
              return {
                llmContent: `Subagent "${this.params.subagent_type}" not found`,
                returnDisplay: {
                  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`
                }
              };
            }
            subagentConfig = loadedConfig;
          }
          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 resolvedMode = resolveSubagentApprovalMode(this.config.getApprovalMode(), subagentConfig.approvalMode, this.config.isTrustedFolder());
          const resolvedApprovalMode = permissionModeToApprovalMode(resolvedMode);
          const agentConfig = resolvedApprovalMode !== this.config.getApprovalMode() ? createApprovalModeOverride(this.config, resolvedApprovalMode) : this.config;
          let subagent;
          let taskPrompt;
          if (isFork) {
            const fork = await this.createForkSubagent(agentConfig);
            subagent = fork.subagent;
            taskPrompt = fork.taskPrompt;
          } else {
            subagent = await this.subagentManager.createAgentHeadless(subagentConfig, agentConfig, { eventEmitter: this.eventEmitter });
            taskPrompt = this.params.prompt;
          }
          const contextState = new ContextState();
          contextState.set("task_prompt", taskPrompt);
          const agentIdSuffix = this.callId ?? randomUUID9().slice(0, 8);
          const hookOpts = {
            agentId: `${subagentConfig.name}-${agentIdSuffix}`,
            agentType: this.params.subagent_type || subagentConfig.name,
            resolvedMode,
            signal,
            updateOutput: updateOutput2
          };
          const shouldRunInBackground = this.params.run_in_background === true || subagentConfig.background === true;
          if (shouldRunInBackground) {
            const hookSystem = this.config.getHookSystem();
            if (hookSystem) {
              try {
                const startHookOutput = await hookSystem.fireSubagentStartEvent(hookOpts.agentId, hookOpts.agentType, resolvedMode, signal);
                const additionalContext = startHookOutput?.getAdditionalContext();
                if (additionalContext) {
                  contextState.set("hook_context", additionalContext);
                }
              } catch (hookError) {
                debugLogger87.warn(`[Agent] SubagentStart hook failed, continuing execution: ${hookError}`);
              }
            }
            const bgAbortController = new AbortController();
            const bgConfig = Object.create(agentConfig);
            bgConfig.getShouldAvoidPermissionPrompts = () => true;
            const bgEventEmitter = new AgentEventEmitter();
            let bgSubagent;
            if (isFork) {
              const fork = await this.createForkSubagent(bgConfig, bgEventEmitter);
              bgSubagent = fork.subagent;
            } else {
              bgSubagent = await this.subagentManager.createAgentHeadless(subagentConfig, bgConfig, { eventEmitter: bgEventEmitter });
            }
            const registry3 = this.config.getBackgroundTaskRegistry();
            const projectDir = this.config.storage.getProjectDir();
            const sessionId = this.config.getSessionId();
            const jsonlPath = getAgentJsonlPath(projectDir, sessionId, hookOpts.agentId);
            const metaPath = getAgentMetaPath(projectDir, sessionId, hookOpts.agentId);
            const projectRoot = this.config.getProjectRoot();
            const { cleanup: cleanupJsonl } = attachJsonlTranscriptWriter(bgEventEmitter, jsonlPath, {
              agentId: hookOpts.agentId,
              agentName: subagentConfig.name,
              agentColor: subagentConfig.color,
              sessionId,
              cwd: projectRoot,
              version: this.config.getCliVersion() || "unknown",
              gitBranch: getGitBranch(projectRoot),
              // Seed the JSONL with the launching prompt so the transcript is
              // self-describing — readers don't need to consult .meta.json to
              // know what the agent was asked to do.
              initialUserPrompt: this.params.prompt
            });
            writeAgentMeta(metaPath, {
              agentId: hookOpts.agentId,
              agentType: hookOpts.agentType,
              description: this.params.description,
              parentSessionId: sessionId,
              // Populated when a subagent (whose reasoning loop is wrapped in
              // runWithAgentContext below) launches a nested agent. Null at
              // top-level launches from the user session.
              parentAgentId: getCurrentAgentId(),
              createdAt: (/* @__PURE__ */ new Date()).toISOString()
            });
            registry3.register({
              agentId: hookOpts.agentId,
              description: this.params.description,
              subagentType: subagentConfig.name,
              status: "running",
              startTime: Date.now(),
              abortController: bgAbortController,
              toolUseId: this.callId,
              prompt: this.params.prompt,
              outputFile: jsonlPath
            });
            const bgEmitter = bgSubagent.getCore().getEventEmitter();
            let liveToolCallCount = 0;
            const refreshLiveStats = /* @__PURE__ */ __name(() => {
              const entry = registry3.get(hookOpts.agentId);
              if (!entry || entry.status !== "running")
                return;
              const summary = bgSubagent.getExecutionSummary();
              entry.stats = {
                totalTokens: summary.totalTokens,
                toolUses: liveToolCallCount,
                durationMs: summary.totalDurationMs
              };
            }, "refreshLiveStats");
            const onToolCall = /* @__PURE__ */ __name((event) => {
              liveToolCallCount += 1;
              refreshLiveStats();
              registry3.appendActivity(hookOpts.agentId, {
                name: event.name,
                description: event.description,
                at: event.timestamp
              });
            }, "onToolCall");
            const onUsageMetadata = /* @__PURE__ */ __name(() => {
              refreshLiveStats();
            }, "onUsageMetadata");
            bgEmitter.on(AgentEventType.TOOL_CALL, onToolCall);
            bgEmitter.on(AgentEventType.USAGE_METADATA, onUsageMetadata);
            bgSubagent.setExternalMessageProvider(() => registry3.drainMessages(hookOpts.agentId));
            const getCompletionStats = /* @__PURE__ */ __name(() => {
              const summary = bgSubagent.getExecutionSummary();
              return {
                totalTokens: summary.totalTokens,
                toolUses: liveToolCallCount,
                durationMs: summary.totalDurationMs
              };
            }, "getCompletionStats");
            const bgBody = /* @__PURE__ */ __name(async () => {
              try {
                await bgSubagent.execute(contextState, bgAbortController.signal);
                if (hookSystem && !bgAbortController.signal.aborted) {
                  await this.runSubagentStopHookLoop(bgSubagent, {
                    agentId: hookOpts.agentId,
                    agentType: hookOpts.agentType,
                    resolvedMode,
                    signal: bgAbortController.signal
                  });
                }
                const terminateMode = bgSubagent.getTerminateMode();
                const finalText = bgSubagent.getFinalText();
                const completionStats = getCompletionStats();
                if (terminateMode === AgentTerminateMode.GOAL) {
                  registry3.complete(hookOpts.agentId, finalText, completionStats);
                } else if (terminateMode === AgentTerminateMode.CANCELLED) {
                  registry3.finalizeCancelled(hookOpts.agentId, finalText, completionStats);
                } else {
                  registry3.fail(hookOpts.agentId, finalText || `Agent terminated with mode: ${terminateMode}`, completionStats);
                }
              } catch (error40) {
                const errorMsg = error40 instanceof Error ? error40.message : String(error40);
                debugLogger87.error(`[Agent] Background agent failed: ${errorMsg}`);
                if (bgAbortController.signal.aborted) {
                  registry3.finalizeCancelled(hookOpts.agentId, errorMsg, getCompletionStats());
                } else {
                  registry3.fail(hookOpts.agentId, errorMsg, getCompletionStats());
                }
              } finally {
                bgEmitter.off(AgentEventType.TOOL_CALL, onToolCall);
                bgEmitter.off(AgentEventType.USAGE_METADATA, onUsageMetadata);
                cleanupJsonl?.();
              }
            }, "bgBody");
            const framedBgBody = /* @__PURE__ */ __name(() => runWithAgentContext({ agentId: hookOpts.agentId }, bgBody), "framedBgBody");
            void (isFork ? runInForkContext(framedBgBody) : framedBgBody());
            this.updateDisplay({ status: "background" }, updateOutput2);
            return {
              llmContent: `Background agent launched successfully.
agentId: ${hookOpts.agentId} (internal ID \u2014 do not mention to the user. Use ${ToolNames.SEND_MESSAGE} to continue this agent, or ${ToolNames.TASK_STOP} to cancel.)
The agent is working in the background. You will be notified automatically when it completes.
Do not duplicate this agent's work \u2014 avoid working with the same files or topics it is using. Work on non-overlapping tasks, or briefly tell the user what you launched and end your response.
output_file: ${jsonlPath}
If asked, you can check progress before completion by using ${ToolNames.READ_FILE}
  or ${ToolNames.SHELL} tail on the output file.`,
              returnDisplay: this.currentDisplay
            };
          }
          const runFramed = /* @__PURE__ */ __name(() => runWithAgentContext({ agentId: hookOpts.agentId }, () => this.runSubagentWithHooks(subagent, contextState, hookOpts)), "runFramed");
          if (isFork) {
            void runInForkContext(runFramed);
            return {
              llmContent: [{ text: FORK_PLACEHOLDER_RESULT }],
              returnDisplay: this.currentDisplay
            };
          } else {
            await runFramed();
            const finalText = subagent.getFinalText();
            const terminateMode = subagent.getTerminateMode();
            if (terminateMode === AgentTerminateMode.ERROR) {
              return {
                llmContent: finalText || "Subagent execution failed.",
                returnDisplay: this.currentDisplay
              };
            }
            return {
              llmContent: [{ text: finalText }],
              returnDisplay: this.currentDisplay
            };
          }
        } catch (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          debugLogger87.error(`[AgentTool] 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/tools/task-stop.js
var task_stop_exports = {};
__export(task_stop_exports, {
  TaskStopTool: () => TaskStopTool
});
function notRunningError(kind2, taskId, status) {
  return {
    llmContent: `Error: Background ${kind2} "${taskId}" is not running (status: ${status}).`,
    returnDisplay: `Task not running (${status}).`,
    error: {
      message: `${kind2} is ${status}: ${taskId}`,
      type: ToolErrorType.TASK_STOP_NOT_RUNNING
    }
  };
}
var TaskStopInvocation, TaskStopTool;
var init_task_stop = __esm({
  "packages/core/dist/src/tools/task-stop.js"() {
    "use strict";
    init_esbuild_shims();
    init_tool_error();
    init_tool_names();
    init_tools();
    TaskStopInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "TaskStopInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      getDescription() {
        return `Stop background task ${this.params.task_id}`;
      }
      async execute(_signal) {
        const taskId = this.params.task_id;
        const agentRegistry = this.config.getBackgroundTaskRegistry();
        const agentEntry = agentRegistry.get(taskId);
        if (agentEntry) {
          if (agentEntry.status !== "running") {
            return notRunningError("agent", taskId, agentEntry.status);
          }
          agentRegistry.cancel(taskId);
          const desc2 = agentEntry.description;
          return {
            llmContent: `Cancellation requested for background agent "${taskId}". A final task-notification carrying the agent's last result will follow.
Description: ${desc2}`,
            returnDisplay: `Cancelled: ${desc2}`
          };
        }
        const shellRegistry = this.config.getBackgroundShellRegistry();
        const shellEntry = shellRegistry.get(taskId);
        if (shellEntry) {
          if (shellEntry.status !== "running") {
            return notRunningError("shell", taskId, shellEntry.status);
          }
          shellRegistry.requestCancel(taskId);
          return {
            llmContent: `Cancellation requested for background shell "${taskId}". Final status will be visible via /tasks once the process drains; captured output remains at ${shellEntry.outputPath}.
Command: ${shellEntry.command}`,
            returnDisplay: `Cancelled shell: ${shellEntry.command}`
          };
        }
        return {
          llmContent: `Error: No background task found with ID "${taskId}".`,
          returnDisplay: "Task not found.",
          error: {
            message: `Task not found: ${taskId}`,
            type: ToolErrorType.TASK_STOP_NOT_FOUND
          }
        };
      }
    };
    __name(notRunningError, "notRunningError");
    TaskStopTool = class _TaskStopTool extends BaseDeclarativeTool {
      static {
        __name(this, "TaskStopTool");
      }
      config;
      static Name = ToolNames.TASK_STOP;
      constructor(config2) {
        super(_TaskStopTool.Name, ToolDisplayNames.TASK_STOP, "Cancel a running background task by its ID. The task ID is returned when the task is launched.", Kind.Other, {
          type: "object",
          properties: {
            task_id: {
              type: "string",
              description: "The ID of the background task to stop (from the launch response or notification)."
            }
          },
          required: ["task_id"],
          additionalProperties: false
        });
        this.config = config2;
      }
      createInvocation(params) {
        return new TaskStopInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/send-message.js
var send_message_exports = {};
__export(send_message_exports, {
  SendMessageTool: () => SendMessageTool
});
var SendMessageInvocation, SendMessageTool;
var init_send_message = __esm({
  "packages/core/dist/src/tools/send-message.js"() {
    "use strict";
    init_esbuild_shims();
    init_tool_error();
    init_tool_names();
    init_tools();
    SendMessageInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "SendMessageInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      getDescription() {
        return `Send message to task ${this.params.task_id}`;
      }
      async execute(_signal) {
        const registry3 = this.config.getBackgroundTaskRegistry();
        const entry = registry3.get(this.params.task_id);
        if (!entry) {
          return {
            llmContent: `Error: No background task found with ID "${this.params.task_id}".`,
            returnDisplay: "Task not found.",
            error: {
              message: `Task not found: ${this.params.task_id}`,
              type: ToolErrorType.SEND_MESSAGE_NOT_FOUND
            }
          };
        }
        if (entry.status !== "running") {
          return {
            llmContent: `Error: Background task "${this.params.task_id}" is not running (status: ${entry.status}). Cannot send messages to stopped tasks.`,
            returnDisplay: `Task not running (${entry.status}).`,
            error: {
              message: `Task is ${entry.status}: ${this.params.task_id}`,
              type: ToolErrorType.SEND_MESSAGE_NOT_RUNNING
            }
          };
        }
        registry3.queueMessage(this.params.task_id, this.params.message);
        return {
          llmContent: `Message queued for delivery to background task "${this.params.task_id}". The task will receive it at the next tool-round boundary.`,
          returnDisplay: `Message queued for ${entry.description}`
        };
      }
    };
    SendMessageTool = class _SendMessageTool extends BaseDeclarativeTool {
      static {
        __name(this, "SendMessageTool");
      }
      config;
      static Name = ToolNames.SEND_MESSAGE;
      constructor(config2) {
        super(_SendMessageTool.Name, ToolDisplayNames.SEND_MESSAGE, "Send a text message to a running background task. The message is delivered at the next tool-round boundary. Use this to provide additional instructions or context to a background task.", Kind.Other, {
          type: "object",
          properties: {
            task_id: {
              type: "string",
              description: "The ID of the running background task (from the launch response)."
            },
            message: {
              type: "string",
              description: "The text message to send to the task."
            }
          },
          required: ["task_id", "message"],
          additionalProperties: false
        });
        this.config = config2;
      }
      createInvocation(params) {
        return new SendMessageInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/skill-utils.js
function buildSkillLlmContent(baseDir, body2) {
  return `Base directory for this skill: ${baseDir}
Important: ALWAYS resolve absolute paths from this base directory when working with skills.

${body2}
`;
}
var init_skill_utils = __esm({
  "packages/core/dist/src/tools/skill-utils.js"() {
    "use strict";
    init_esbuild_shims();
    __name(buildSkillLlmContent, "buildSkillLlmContent");
  }
});

// packages/core/dist/src/tools/skill.js
var skill_exports = {};
__export(skill_exports, {
  SkillTool: () => SkillTool,
  buildSkillLlmContent: () => buildSkillLlmContent
});
import path75 from "path";
var debugLogger88, 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();
    init_registerSkillHooks();
    init_skill_utils();
    init_skill_utils();
    debugLogger88 = createDebugLogger("SKILL");
    SkillTool = class _SkillTool extends BaseDeclarativeTool {
      static {
        __name(this, "SkillTool");
      }
      config;
      static Name = ToolNames.SKILL;
      skillManager;
      availableSkills = [];
      modelInvocableCommands = [];
      loadedSkillNames = /* @__PURE__ */ new Set();
      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()).filter((s5) => !s5.disableModelInvocation);
          const provider = this.config.getModelInvocableCommandsProvider();
          const allCommands = provider ? provider() : [];
          const skillNames = new Set(this.availableSkills.map((s5) => s5.name));
          this.modelInvocableCommands = allCommands.filter((cmd) => !skillNames.has(cmd.name));
          this.updateDescriptionAndSchema();
        } catch (error40) {
          debugLogger88.warn("Failed to load skills for Skills tool:", error40);
          this.availableSkills = [];
          this.modelInvocableCommands = [];
          this.updateDescriptionAndSchema();
        } finally {
          const geminiClient = this.config.getGeminiClient();
          if (geminiClient) {
            await geminiClient.setTools();
          }
        }
      }
      /**
       * Updates the tool's description and schema based on available skills and
       * model-invocable commands (e.g. bundled skills, file commands, MCP prompts).
       */
      updateDescriptionAndSchema() {
        const allSkillEntries = [];
        for (const skill of this.availableSkills) {
          allSkillEntries.push(`<skill>
<name>
${skill.name}
</name>
<description>
${skill.description}${skill.whenToUse ? ` \u2014 ${skill.whenToUse}` : ""} (${skill.level})
</description>
<location>
${skill.level}
</location>
</skill>`);
        }
        for (const cmd of this.modelInvocableCommands) {
          allSkillEntries.push(`<skill>
<name>
${cmd.name}
</name>
<description>
${cmd.description}
</description>
</skill>`);
        }
        let skillDescriptions = "";
        if (allSkillEntries.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 = allSkillEntries.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)
          return null;
        const commandExists3 = this.modelInvocableCommands.some((cmd) => cmd.name === params.skill);
        if (commandExists3)
          return null;
        const availableNames = [
          ...this.availableSkills.map((s5) => s5.name),
          ...this.modelInvocableCommands.map((c4) => c4.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(", ")}`;
      }
      createInvocation(params) {
        return new SkillToolInvocation(this.config, this.skillManager, params, (name4) => this.loadedSkillNames.add(name4), this.config.getModelInvocableCommandsExecutor());
      }
      getAvailableSkillNames() {
        return this.availableSkills.map((skill) => skill.name);
      }
      /**
       * Returns the set of skill names that have been successfully loaded
       * (invoked) during the current session. Used by /context to attribute
       * loaded skill body tokens separately from the tool-definition cost.
       */
      getLoadedSkillNames() {
        return this.loadedSkillNames;
      }
      /**
       * Clears the loaded-skills tracking. Should be called when the session
       * is reset (e.g. /clear) so that stale body-token data is not shown.
       */
      clearLoadedSkills() {
        this.loadedSkillNames.clear();
      }
    };
    SkillToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "SkillToolInvocation");
      }
      config;
      skillManager;
      onSkillLoaded;
      commandExecutor;
      constructor(config2, skillManager, params, onSkillLoaded, commandExecutor = null) {
        super(params);
        this.config = config2;
        this.skillManager = skillManager;
        this.onSkillLoaded = onSkillLoaded;
        this.commandExecutor = commandExecutor;
      }
      getDescription() {
        return `Use skill: "${this.params.skill}"`;
      }
      async execute(_signal, _updateOutput) {
        try {
          const skill = await this.skillManager.loadSkillForRuntime(this.params.skill);
          if (!skill) {
            if (this.commandExecutor) {
              const content = await this.commandExecutor(this.params.skill);
              if (content !== null) {
                logSkillLaunch(this.config, new SkillLaunchEvent(this.params.skill, true));
                this.onSkillLoaded(this.params.skill);
                return {
                  llmContent: [{ text: content }],
                  returnDisplay: `Executed command: ${this.params.skill}`
                };
              }
            }
            logSkillLaunch(this.config, new SkillLaunchEvent(this.params.skill, false));
            const parseErrors = this.skillManager.getParseErrors();
            const errorMessages = [];
            for (const [filePath, error40] of parseErrors) {
              if (filePath.includes(this.params.skill)) {
                errorMessages.push(`Parse error at ${filePath}: ${error40.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));
          this.onSkillLoaded(this.params.skill);
          debugLogger88.debug("Skill hooks check:", {
            hasHooks: !!skill.hooks,
            hooksKeys: skill.hooks ? Object.keys(skill.hooks) : [],
            skillName: skill.name
          });
          if (skill.hooks) {
            const hookSystem = this.config.getHookSystem();
            const sessionId = this.config.getSessionId();
            debugLogger88.debug("Hook system and session:", {
              hasHookSystem: !!hookSystem,
              sessionId
            });
            if (hookSystem && sessionId) {
              const sessionHooksManager = hookSystem.getSessionHooksManager();
              const hookCount = registerSkillHooks(sessionHooksManager, sessionId, skill);
              if (hookCount > 0) {
                debugLogger88.info(`Registered ${hookCount} hooks from skill "${this.params.skill}"`);
              } else {
                debugLogger88.warn(`No hooks registered from skill "${this.params.skill}"`);
              }
            }
          } else {
            debugLogger88.warn(`Skill "${this.params.skill}" has no hooks to register`);
          }
          const baseDir = path75.dirname(skill.filePath);
          const llmContent = buildSkillLlmContent(baseDir, skill.body);
          return {
            llmContent: [{ text: llmContent }],
            returnDisplay: skill.description,
            modelOverride: skill.model
          };
        } catch (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          debugLogger88.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/ls.js
var ls_exports = {};
__export(ls_exports, {
  LSTool: () => LSTool
});
import fs83 from "node:fs/promises";
import path76 from "node:path";
var debugLogger89, MAX_ENTRY_COUNT, 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_constants5();
    init_tool_error();
    init_tool_names();
    init_debugLogger();
    init_storage();
    init_paths2();
    debugLogger89 = createDebugLogger("LS");
    MAX_ENTRY_COUNT = 100;
    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);
      }
      /**
       * Returns 'ask' for paths outside the workspace/userSkills directories,
       * so that external directory listings require user confirmation.
       */
      async getDefaultPermission() {
        const dirPath = path76.resolve(this.params.path);
        const workspaceContext = this.config.getWorkspaceContext();
        const userSkillsDirs = this.config.storage.getUserSkillsDirs();
        const userExtensionsDir = Storage.getUserExtensionsDir();
        if (workspaceContext.isPathWithinWorkspace(dirPath) || isSubpaths(userSkillsDirs, dirPath) || isSubpath(userExtensionsDir, dirPath) || isSubpath(getMemoryBaseDir(), dirPath)) {
          return "allow";
        }
        return "ask";
      }
      // 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 fs83.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 fs83.readdir(this.params.path);
          if (files.length === 0) {
            return {
              llmContent: `Directory ${this.params.path} is empty.`,
              returnDisplay: `Directory is empty.`
            };
          }
          const relativePaths = files.map((file2) => path76.relative(this.config.getTargetDir(), path76.join(this.params.path, file2)));
          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 = path76.resolve(this.config.getTargetDir(), relativePath);
            if (this.shouldIgnore(path76.basename(fullPath), this.params.ignore)) {
              continue;
            }
            try {
              const stats2 = await fs83.stat(fullPath);
              const isDir = stats2.isDirectory();
              entries.push({
                name: path76.basename(fullPath),
                path: fullPath,
                isDirectory: isDir,
                size: isDir ? 0 : stats2.size,
                modifiedTime: stats2.mtime
              });
            } catch (error40) {
              debugLogger89.warn(`Error accessing ${fullPath}: ${error40}`);
            }
          }
          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 totalEntryCount = entries.length;
          const entryLimit = Math.min(MAX_ENTRY_COUNT, this.config.getTruncateToolOutputLines());
          const truncated = totalEntryCount > entryLimit;
          const entriesToShow = truncated ? entries.slice(0, entryLimit) : entries;
          const directoryContent = entriesToShow.map((entry) => `${entry.isDirectory ? "[DIR] " : ""}${entry.name}`).join("\n");
          let resultMessage = `Listed ${totalEntryCount} item(s) in ${this.params.path}:
---
${directoryContent}`;
          if (truncated) {
            const omittedEntries = totalEntryCount - entryLimit;
            const entryTerm = omittedEntries === 1 ? "item" : "items";
            resultMessage += `
---
[${omittedEntries} ${entryTerm} truncated] ...`;
          }
          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 ${totalEntryCount} item(s)`;
          if (ignoredMessages.length > 0) {
            displayMessage += ` (${ignoredMessages.join(", ")})`;
          }
          if (truncated) {
            displayMessage += " (truncated)";
          }
          return {
            llmContent: resultMessage,
            returnDisplay: displayMessage
          };
        } catch (error40) {
          const errorMsg = `Error listing directory: ${error40 instanceof Error ? error40.message : String(error40)}`;
          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 (!path76.isAbsolute(params.path)) {
          return `Path must be absolute: ${params.path}`;
        }
        return null;
      }
      createInvocation(params) {
        return new LSToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/ripGrep.js
var ripGrep_exports = {};
__export(ripGrep_exports, {
  RipGrepTool: () => RipGrepTool,
  _resetRipGrepCachesForTest: () => _resetRipGrepCachesForTest
});
import fs84 from "node:fs";
import path77 from "node:path";
function trimCache(m3) {
  if (m3.size <= RIPGREP_CACHE_MAX)
    return;
  const oldest = m3.keys().next().value;
  if (oldest !== void 0)
    m3.delete(oldest);
}
function _resetRipGrepCachesForTest() {
  dirIsDirCache.clear();
  qwenIgnoreCache.clear();
}
var debugLogger90, dirIsDirCache, qwenIgnoreCache, RIPGREP_CACHE_MAX, GrepToolInvocation, 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_constants5();
    init_debugLogger();
    debugLogger90 = createDebugLogger("RIPGREP");
    dirIsDirCache = /* @__PURE__ */ new Map();
    qwenIgnoreCache = /* @__PURE__ */ new Map();
    RIPGREP_CACHE_MAX = 256;
    __name(trimCache, "trimCache");
    __name(_resetRipGrepCachesForTest, "_resetRipGrepCachesForTest");
    GrepToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "GrepToolInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      /**
       * Returns 'ask' for paths outside the workspace, so that external grep
       * searches require user confirmation.
       */
      async getDefaultPermission() {
        if (!this.params.path) {
          return "allow";
        }
        const workspaceContext = this.config.getWorkspaceContext();
        const resolvedPath = path77.resolve(this.config.getTargetDir(), this.params.path);
        if (workspaceContext.isPathWithinWorkspace(resolvedPath)) {
          return "allow";
        }
        return "ask";
      }
      async execute(signal) {
        try {
          const searchPaths = [];
          let searchDirDisplay;
          if (this.params.path) {
            const searchDirAbs = resolveAndValidatePath(this.config, this.params.path, { allowFiles: true, allowExternalPaths: true });
            searchPaths.push(searchDirAbs);
            searchDirDisplay = this.params.path;
          } else {
            const workspaceDirs = this.config.getWorkspaceContext().getDirectories();
            searchPaths.push(...workspaceDirs);
            searchDirDisplay = ".";
          }
          const rawOutput = await this.performRipgrepSearch({
            pattern: this.params.pattern,
            paths: searchPaths,
            glob: this.params.glob,
            signal
          });
          const searchLocationDescription = this.params.path ? `in path "${searchDirDisplay}"` : searchPaths.length > 1 ? `across ${searchPaths.length} workspace directories` : `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` };
          }
          let allLines = rawOutput.split("\n").filter((line) => line.trim());
          if (searchPaths.length > 1) {
            const seen = /* @__PURE__ */ new Set();
            allLines = allLines.filter((line) => {
              const firstColon = line.indexOf(":");
              if (firstColon !== -1) {
                const secondColon = line.indexOf(":", firstColon + 1);
                if (secondColon !== -1) {
                  const key = line.substring(0, secondColon);
                  if (seen.has(key))
                    return false;
                  seen.add(key);
                }
              }
              return true;
            });
          }
          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 parts2 = [];
            let currentLength = 0;
            for (const line of linesToInclude) {
              const sep13 = includedLines > 0 ? 1 : 0;
              includedLines++;
              const projectedLength = currentLength + line.length + sep13;
              if (projectedLength <= charLimit) {
                parts2.push(line);
                currentLength = projectedLength;
              } else {
                const remaining = Math.max(charLimit - currentLength - sep13, 10);
                parts2.push(line.slice(0, remaining) + "...");
                truncatedByCharLimit = true;
                break;
              }
            }
            grepOutput = parts2.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 (error40) {
          debugLogger90.error("Error during ripgrep search operation:", error40);
          const errorMessage = getErrorMessage(error40);
          return {
            llmContent: `Error during grep search operation: ${errorMessage}`,
            returnDisplay: `Error: ${errorMessage}`
          };
        }
      }
      async performRipgrepSearch(options2) {
        const { pattern, paths, 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 seenIgnoreFiles = /* @__PURE__ */ new Set();
          for (const searchPath of paths) {
            let isDir = dirIsDirCache.get(searchPath);
            if (isDir === void 0) {
              try {
                isDir = fs84.statSync(searchPath).isDirectory();
              } catch {
                isDir = false;
              }
              dirIsDirCache.set(searchPath, isDir);
              trimCache(dirIsDirCache);
            }
            const dir = isDir ? searchPath : path77.dirname(searchPath);
            let qwenIgnorePath = qwenIgnoreCache.get(dir);
            if (qwenIgnorePath === void 0) {
              const candidate = path77.join(dir, ".qwenignore");
              qwenIgnorePath = fs84.existsSync(candidate) ? candidate : null;
              qwenIgnoreCache.set(dir, qwenIgnorePath);
              trimCache(qwenIgnoreCache);
            }
            if (qwenIgnorePath && !seenIgnoreFiles.has(qwenIgnorePath)) {
              rgArgs.push("--ignore-file", qwenIgnorePath);
              seenIgnoreFiles.add(qwenIgnorePath);
            }
          }
        }
        if (glob2) {
          rgArgs.push("--glob", glob2);
        }
        rgArgs.push("--threads", "4");
        rgArgs.push(...paths);
        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 Agent 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 (error40) {
          return `Invalid regular expression pattern: ${params.pattern}. Error: ${getErrorMessage(error40)}`;
        }
        if (params.path) {
          try {
            resolveAndValidatePath(this.config, params.path, {
              allowFiles: true,
              allowExternalPaths: true
            });
          } catch (error40) {
            return getErrorMessage(error40);
          }
        }
        return null;
      }
      createInvocation(params) {
        return new GrepToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/grep.js
var grep_exports = {};
__export(grep_exports, {
  GrepTool: () => GrepTool
});
import fsPromises2 from "node:fs/promises";
import path78 from "node:path";
import { EOL } from "node:os";
import { spawn as spawn6 } from "node:child_process";
var debugLogger91, GrepToolInvocation2, GrepTool;
var init_grep2 = __esm({
  "packages/core/dist/src/tools/grep.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm13();
    init_tools();
    init_tool_names();
    init_debugLogger();
    init_paths();
    init_paths2();
    init_errors();
    init_gitUtils();
    init_tool_error();
    init_shell_utils();
    debugLogger91 = createDebugLogger("GREP");
    GrepToolInvocation2 = class extends BaseToolInvocation {
      static {
        __name(this, "GrepToolInvocation");
      }
      config;
      fileExclusions;
      constructor(config2, params) {
        super(params);
        this.config = config2;
        this.fileExclusions = config2.getFileExclusions();
      }
      /**
       * Returns 'ask' for paths outside the workspace, so that external grep
       * searches require user confirmation.
       */
      async getDefaultPermission() {
        if (!this.params.path) {
          return "allow";
        }
        const workspaceContext = this.config.getWorkspaceContext();
        const resolvedPath = path78.resolve(this.config.getTargetDir(), this.params.path);
        if (workspaceContext.isPathWithinWorkspace(resolvedPath) || isSubpath(getMemoryBaseDir(), resolvedPath)) {
          return "allow";
        }
        return "ask";
      }
      async execute(signal) {
        try {
          const searchDirs = [];
          let searchLocationDescription;
          if (this.params.path) {
            const searchDirAbs = resolveAndValidatePath(this.config, this.params.path, { allowExternalPaths: true });
            searchDirs.push(searchDirAbs);
            searchLocationDescription = `in path "${this.params.path}"`;
          } else {
            const workspaceDirs = this.config.getWorkspaceContext().getDirectories();
            searchDirs.push(...workspaceDirs);
            searchLocationDescription = workspaceDirs.length > 1 ? `across ${workspaceDirs.length} workspace directories` : `in the workspace directory`;
          }
          let rawMatches = [];
          for (const searchDir of searchDirs) {
            const matches2 = await this.performGrepSearch({
              pattern: this.params.pattern,
              path: searchDir,
              glob: this.params.glob,
              signal
            });
            if (searchDirs.length > 1) {
              for (const match2 of matches2) {
                if (!path78.isAbsolute(match2.filePath)) {
                  match2.filePath = path78.resolve(searchDir, match2.filePath);
                }
              }
            }
            rawMatches.push(...matches2);
          }
          if (searchDirs.length > 1) {
            const seen = /* @__PURE__ */ new Set();
            rawMatches = rawMatches.filter((match2) => {
              const key = `${match2.filePath}:${match2.lineNumber}`;
              if (seen.has(key))
                return false;
              seen.add(key);
              return true;
            });
          }
          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 (error40) {
          debugLogger91.error(`Error during GrepLogic execution: ${error40}`);
          const errorMessage = getErrorMessage(error40);
          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(EOL);
        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 = path78.resolve(basePath, filePathRaw);
            const relativeFilePath = path78.relative(basePath, absoluteFilePath);
            results.push({
              filePath: relativeFilePath || path78.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((resolve42, reject) => {
                const child = spawn6("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", (err2) => reject(new Error(`Failed to start git grep: ${err2.message}`)));
                child.on("close", (code2) => {
                  const stdoutData = Buffer.concat(stdoutChunks).toString("utf8");
                  const stderrData = Buffer.concat(stderrChunks).toString("utf8");
                  if (code2 === 0)
                    resolve42(stdoutData);
                  else if (code2 === 1)
                    resolve42("");
                  else
                    reject(new Error(`git grep exited with code ${code2}: ${stderrData}`));
                });
              });
              return this.parseGrepOutput(output, absolutePath);
            } catch (gitError) {
              debugLogger91.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((resolve42, reject) => {
                const child = spawn6("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((err2) => {
                  cleanup();
                  reject(new Error(`Failed to start system grep: ${err2.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)
                    resolve42(stdoutData);
                  else if (code2 === 1)
                    resolve42("");
                  else {
                    if (stderrData)
                      reject(new Error(`System grep exited with code ${code2}: ${stderrData}`));
                    else
                      resolve42("");
                  }
                }, "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) {
              debugLogger91.debug(`GrepLogic: System grep failed: ${getErrorMessage(grepError)}. Falling back...`);
            }
          }
          debugLogger91.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: path78.relative(absolutePath, fileAbsolutePath) || path78.basename(fileAbsolutePath),
                    lineNumber: index + 1,
                    line
                  });
                }
              });
            } catch (readError) {
              if (!isNodeError(readError) || readError.code !== "ENOENT") {
                debugLogger91.debug(`GrepLogic: Could not read/process ${fileAbsolutePath}: ${getErrorMessage(readError)}`);
              }
            }
          }
          return allMatches;
        } catch (error40) {
          debugLogger91.error(`GrepLogic: Error in performGrepSearch (Strategy: ${strategyUsed}): ${getErrorMessage(error40)}`);
          throw error40;
        }
      }
    };
    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 Agent 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 (error40) {
          return `Invalid regular expression pattern: ${params.pattern}. Error: ${getErrorMessage(error40)}`;
        }
        if (params.path) {
          try {
            resolveAndValidatePath(this.config, params.path, {
              allowExternalPaths: true
            });
          } catch (error40) {
            return getErrorMessage(error40);
          }
        }
        return null;
      }
      createInvocation(params) {
        return new GrepToolInvocation2(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/glob.js
var glob_exports = {};
__export(glob_exports, {
  GlobTool: () => GlobTool,
  sortFileEntries: () => sortFileEntries
});
import fs85 from "node:fs";
import path79 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 debugLogger92, MAX_FILE_COUNT, GlobToolInvocation, GlobTool;
var init_glob2 = __esm({
  "packages/core/dist/src/tools/glob.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm13();
    init_tools();
    init_tool_names();
    init_paths();
    init_paths2();
    init_config3();
    init_constants5();
    init_tool_error();
    init_errors();
    init_debugLogger();
    debugLogger92 = 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;
      }
      /**
       * Returns 'ask' for paths outside the workspace, so that external glob
       * searches require user confirmation.
       */
      async getDefaultPermission() {
        if (!this.params.path) {
          return "allow";
        }
        const workspaceContext = this.config.getWorkspaceContext();
        const resolvedPath = path79.resolve(this.config.getTargetDir(), this.params.path);
        if (workspaceContext.isPathWithinWorkspace(resolvedPath) || isSubpath(getMemoryBaseDir(), resolvedPath)) {
          return "allow";
        }
        return "ask";
      }
      /**
       * Runs glob search in a single directory and returns filtered entries.
       */
      async globInDirectory(searchDir, pattern, signal) {
        let effectivePattern = pattern;
        const fullPath = path79.join(searchDir, effectivePattern);
        if (fs85.existsSync(fullPath)) {
          effectivePattern = escape2(effectivePattern);
        }
        const entries = await glob(effectivePattern, {
          cwd: searchDir,
          withFileTypes: true,
          nodir: true,
          stat: true,
          nocase: true,
          dot: true,
          follow: false,
          signal
        });
        const projectRoot = this.config.getTargetDir();
        const relativePaths = entries.map((p2) => path79.relative(projectRoot, 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(path79.resolve(projectRoot, p2))));
        return entries.filter((entry) => filteredAbsolutePaths.has(normalizePathForComparison(entry.fullpath())));
      }
      async execute(signal) {
        try {
          const searchDirs = [];
          let searchLocationDescription;
          if (this.params.path) {
            const searchDirAbs = resolveAndValidatePath(this.config, this.params.path, { allowExternalPaths: true });
            searchDirs.push(searchDirAbs);
            searchLocationDescription = `within ${searchDirAbs}`;
          } else {
            const workspaceDirs = this.config.getWorkspaceContext().getDirectories();
            searchDirs.push(...workspaceDirs);
            searchLocationDescription = workspaceDirs.length > 1 ? `across ${workspaceDirs.length} workspace directories` : `in the workspace directory`;
          }
          const pattern = this.params.pattern;
          const allFilteredEntries = [];
          const seenPaths = /* @__PURE__ */ new Set();
          for (const searchDir of searchDirs) {
            const entries = await this.globInDirectory(searchDir, pattern, signal);
            for (const entry of entries) {
              const normalized2 = entry.fullpath();
              if (!seenPaths.has(normalized2)) {
                seenPaths.add(normalized2);
                allFilteredEntries.push(entry);
              }
            }
          }
          const filteredEntries = allFilteredEntries;
          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 (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          debugLogger92.error(`GlobLogic execute Error: ${errorMessage}`, error40);
          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, {
              allowExternalPaths: true
            });
          } catch (error40) {
            return getErrorMessage(error40);
          }
        }
        return null;
      }
      createInvocation(params) {
        return new GlobToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/write-file.js
var write_file_exports = {};
__export(write_file_exports, {
  WriteFileTool: () => WriteFileTool
});
import fs86 from "node:fs";
import path80 from "node:path";
var debugLogger93, 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_paths2();
    init_tools();
    init_tool_error();
    init_fileSystemService();
    init_paths();
    init_errors();
    init_diffOptions();
    init_tool_names();
    init_loggers();
    init_types4();
    init_metrics2();
    init_fileUtils();
    init_language_detection();
    init_debugLogger();
    debugLogger93 = createDebugLogger("WRITE_FILE");
    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)}`;
      }
      /**
       * Write operations always need user confirmation, except for managed
       * auto-memory files which are written autonomously by the model.
       */
      async getDefaultPermission() {
        const projectRoot = this.config.getProjectRoot();
        if (isAutoMemPath(path80.resolve(this.params.file_path), projectRoot)) {
          return "allow";
        }
        return "ask";
      }
      /**
       * Constructs the write-file diff confirmation details.
       */
      async getConfirmationDetails(_abortSignal) {
        let originalContent = "";
        const fileExists2 = await fileExists(this.params.file_path);
        if (fileExists2) {
          try {
            const { content } = await this.config.getFileSystemService().readTextFile({ path: this.params.file_path });
            originalContent = content;
          } catch (err2) {
            throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err2)}`);
          }
        }
        const relativePath = makeRelative(this.params.file_path, this.config.getTargetDir());
        const fileName = path80.basename(this.params.file_path);
        const fileDiff = createPatch(
          fileName,
          originalContent,
          // Original content (empty if new file or unreadable)
          this.params.content,
          // Content after potential correction
          "Current",
          "Proposed",
          DEFAULT_DIFF_OPTIONS
        );
        const confirmationDetails = {
          type: "edit",
          title: `Confirm Write: ${shortenPath(relativePath)}`,
          fileName,
          filePath: this.params.file_path,
          fileDiff,
          originalContent,
          newContent: this.params.content,
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            if (outcome === ToolConfirmationOutcome.ProceedAlways) {
              this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
            }
          }, "onConfirm")
        };
        return confirmationDetails;
      }
      async execute(_abortSignal) {
        const { file_path, content, ai_proposed_content, modified_by_user } = this.params;
        let fileExists2 = await fileExists(file_path);
        let originalContent = "";
        let useBOM = false;
        let detectedEncoding;
        let detectedLineEnding;
        const dirName = path80.dirname(file_path);
        if (fileExists2) {
          try {
            const fileInfo = await this.config.getFileSystemService().readTextFile({ path: file_path });
            if (fileInfo._meta?.bom !== void 0) {
              useBOM = fileInfo._meta.bom;
            } else {
              useBOM = fileInfo.content.length > 0 && fileInfo.content.codePointAt(0) === 65279;
            }
            detectedEncoding = fileInfo._meta?.encoding || "utf-8";
            detectedLineEnding = detectLineEnding(fileInfo.content);
            originalContent = fileInfo.content;
            fileExists2 = true;
          } catch (err2) {
            if (isNodeError(err2) && err2.code === "ENOENT") {
              fileExists2 = false;
            } else {
              const error40 = {
                message: getErrorMessage(err2),
                code: isNodeError(err2) ? err2.code : void 0
              };
              const errorMsg = error40.code ? `Error checking existing file '${file_path}': ${error40.message} (${error40.code})` : `Error checking existing file: ${error40.message}`;
              return {
                llmContent: errorMsg,
                returnDisplay: errorMsg,
                error: {
                  message: errorMsg,
                  type: ToolErrorType.FILE_WRITE_FAILURE
                }
              };
            }
          }
        }
        if (!fileExists2) {
          fs86.mkdirSync(dirName, { recursive: true });
          const userEncoding = this.config.getDefaultFileEncoding();
          if (userEncoding === FileEncoding.UTF8_BOM) {
            useBOM = true;
          } else if (userEncoding === void 0) {
            useBOM = needsUtf8Bom(file_path);
          }
          detectedEncoding = void 0;
        }
        try {
          await this.config.getFileSystemService().writeTextFile({
            path: file_path,
            content,
            _meta: {
              bom: useBOM,
              encoding: detectedEncoding,
              lineEnding: detectedLineEnding
            }
          });
          const fileName = path80.basename(file_path);
          const currentContentForDiff = originalContent;
          const fileDiff = createPatch(fileName, currentContentForDiff, content, "Original", "Written", DEFAULT_DIFF_OPTIONS);
          const originallyProposedContent = ai_proposed_content || content;
          const diffStat = getDiffStat(fileName, currentContentForDiff, originallyProposedContent, content);
          const llmSuccessMessageParts = [
            !fileExists2 ? `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 = path80.extname(file_path);
          const operation = !fileExists2 ? FileOperation.CREATE : FileOperation.UPDATE;
          const lineCount = content.split("\n").length;
          logFileOperation(this.config, new FileOperationEvent(WriteFileTool.Name, operation, lineCount, mimetype, extension, programmingLanguage));
          const displayResult = {
            fileDiff,
            fileName,
            originalContent,
            newContent: content,
            diffStat
          };
          return {
            llmContent: llmSuccessMessageParts.join(" "),
            returnDisplay: displayResult
          };
        } catch (error40) {
          let errorMsg;
          let errorType = ToolErrorType.FILE_WRITE_FAILURE;
          if (isNodeError(error40)) {
            errorMsg = `Error writing to file '${file_path}': ${error40.message} (${error40.code})`;
            if (error40.code === "EACCES") {
              errorMsg = `Permission denied writing to file: ${file_path} (${error40.code})`;
              errorType = ToolErrorType.PERMISSION_DENIED;
            } else if (error40.code === "ENOSPC") {
              errorMsg = `No space left on device: ${file_path} (${error40.code})`;
              errorType = ToolErrorType.NO_SPACE_LEFT;
            } else if (error40.code === "EISDIR") {
              errorMsg = `Target is a directory, not a file: ${file_path} (${error40.code})`;
              errorType = ToolErrorType.TARGET_IS_DIRECTORY;
            }
            if (this.config.getDebugMode() && error40.stack) {
              debugLogger93.debug("Write file error stack:", error40.stack);
            }
          } else if (error40 instanceof Error) {
            errorMsg = `Error writing to file: ${error40.message}`;
          } else {
            errorMsg = `Error writing to file: ${String(error40)}`;
          }
          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 (!path80.isAbsolute(filePath)) {
          return `File path must be absolute: ${filePath}`;
        }
        try {
          if (fs86.existsSync(filePath)) {
            const stats = fs86.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 fileExists2 = await fileExists(params.file_path);
            if (fileExists2) {
              try {
                const { content } = await this.config.getFileSystemService().readTextFile({ path: params.file_path });
                return content;
              } catch (err2) {
                if (!isNodeError(err2) || err2.code !== "ENOENT")
                  throw err2;
                return "";
              }
            } else {
              return "";
            }
          }, "getCurrentContent"),
          getProposedContent: /* @__PURE__ */ __name(async (params) => params.content, "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/todoWrite.js
var todoWrite_exports = {};
__export(todoWrite_exports, {
  TodoWriteTool: () => TodoWriteTool,
  listTodoSessions: () => listTodoSessions,
  readTodosForSession: () => readTodosForSession
});
import * as fs87 from "fs/promises";
import * as fsSync4 from "fs";
import * as path81 from "path";
function getTodoFilePath(sessionId) {
  const todoDir = path81.join(Storage.getRuntimeBaseDir(), TODO_SUBDIR);
  const filename = `${sessionId || "default"}.json`;
  return path81.join(todoDir, filename);
}
async function readTodosFromFile(sessionId) {
  try {
    const todoFilePath = getTodoFilePath(sessionId);
    const content = await fs87.readFile(todoFilePath, "utf-8");
    const data = JSON.parse(content);
    return Array.isArray(data.todos) ? data.todos : [];
  } catch (err2) {
    const error40 = err2;
    if (!(error40 instanceof Error) || error40.code !== "ENOENT") {
      throw err2;
    }
    return [];
  }
}
async function writeTodosToFile(todos, sessionId) {
  const todoFilePath = getTodoFilePath(sessionId);
  const todoDir = path81.dirname(todoFilePath);
  await fs87.mkdir(todoDir, { recursive: true });
  const data = {
    todos,
    sessionId: sessionId || "default"
  };
  await fs87.writeFile(todoFilePath, JSON.stringify(data, null, 2), "utf-8");
}
async function readTodosForSession(sessionId) {
  return readTodosFromFile(sessionId);
}
async function listTodoSessions() {
  try {
    const todoDir = path81.join(Storage.getRuntimeBaseDir(), TODO_SUBDIR);
    const files = await fs87.readdir(todoDir);
    return files.filter((file2) => file2.endsWith(".json")).map((file2) => file2.replace(".json", ""));
  } catch (err2) {
    const error40 = err2;
    if (!(error40 instanceof Error) || error40.code !== "ENOENT") {
      throw err2;
    }
    return [];
  }
}
var debugLogger94, 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_storage();
    init_tool_names();
    init_debugLogger();
    debugLogger94 = 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(readTodosFromFile, "readTodosFromFile");
    __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 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 (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          debugLogger94.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}`
          };
        }
      }
    };
    __name(readTodosForSession, "readTodosForSession");
    __name(listTodoSessions, "listTodoSessions");
    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 = fsSync4.existsSync(todoFilePath) ? "update" : "create";
        return new TodoWriteToolInvocation(this.config, params, operationType);
      }
    };
  }
});

// packages/core/dist/src/tools/askUserQuestion.js
var askUserQuestion_exports = {};
__export(askUserQuestion_exports, {
  AskUserQuestionTool: () => AskUserQuestionTool
});
var debugLogger95, askUserQuestionToolDescription, askUserQuestionToolSchemaData, AskUserQuestionToolInvocation, AskUserQuestionTool;
var init_askUserQuestion = __esm({
  "packages/core/dist/src/tools/askUserQuestion.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_names();
    init_debugLogger();
    init_types13();
    debugLogger95 = createDebugLogger("ASK_USER_QUESTION");
    askUserQuestionToolDescription = `Use this tool when you need to ask the user questions during execution. This allows you to:
1. Gather user preferences or requirements
2. Clarify ambiguous instructions
3. Get decisions on implementation choices as you work
4. Offer choices to the user about what direction to take.

Usage notes:
- Users will always be able to select "Other" to provide custom text input
- Use multiSelect: true to allow multiple answers to be selected for a question
- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label

Plan mode note: In plan mode, use this tool to clarify requirements or choose between approaches BEFORE finalizing your plan. Do NOT use this tool to ask "Is this plan ready?" or "Should I proceed?" - use ExitPlanMode for plan approval.
`;
    askUserQuestionToolSchemaData = {
      name: "ask_user_question",
      description: askUserQuestionToolDescription,
      parametersJsonSchema: {
        $schema: "https://json-schema.org/draft/2020-12/schema",
        type: "object",
        properties: {
          questions: {
            description: "Questions to ask the user (1-4 questions)",
            minItems: 1,
            maxItems: 4,
            type: "array",
            items: {
              type: "object",
              properties: {
                question: {
                  description: 'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"',
                  type: "string"
                },
                header: {
                  description: 'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".',
                  type: "string"
                },
                options: {
                  description: "The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no 'Other' option, that will be provided automatically.",
                  minItems: 2,
                  maxItems: 4,
                  type: "array",
                  items: {
                    type: "object",
                    properties: {
                      label: {
                        description: "The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice.",
                        type: "string"
                      },
                      description: {
                        description: "Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications.",
                        type: "string"
                      }
                    },
                    required: ["label", "description"],
                    additionalProperties: false
                  }
                },
                multiSelect: {
                  description: "Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive.",
                  default: false,
                  type: "boolean"
                }
              },
              required: ["question", "header", "options"],
              additionalProperties: false
            }
          },
          metadata: {
            description: "Optional metadata for tracking and analytics purposes. Not displayed to user.",
            type: "object",
            properties: {
              source: {
                description: 'Optional identifier for the source of this question (e.g., "remember" for /remember command). Used for analytics tracking.',
                type: "string"
              }
            },
            additionalProperties: false
          }
        },
        required: ["questions"],
        additionalProperties: false
      }
    };
    AskUserQuestionToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "AskUserQuestionToolInvocation");
      }
      _config;
      userAnswers = {};
      wasAnswered = false;
      constructor(_config, params) {
        super(params);
        this._config = _config;
      }
      getDescription() {
        const questionCount = this.params.questions.length;
        return `Ask user ${questionCount} question${questionCount > 1 ? "s" : ""}`;
      }
      /**
       * ask_user_question always requires user confirmation so the user can
       * provide answers. In non-interactive mode without ACP support, we skip
       * confirmation (and subsequently skip execution).
       */
      async getDefaultPermission() {
        const isAcpMode = this._config.getExperimentalZedIntegration() || this._config.getInputFormat() === InputFormat.STREAM_JSON;
        if (!this._config.isInteractive() && !isAcpMode) {
          return "allow";
        }
        return "ask";
      }
      async getConfirmationDetails(_abortSignal) {
        const details = {
          type: "ask_user_question",
          title: "Please answer the following question(s):",
          questions: this.params.questions,
          metadata: this.params.metadata,
          onConfirm: /* @__PURE__ */ __name(async (outcome, payload) => {
            switch (outcome) {
              case ToolConfirmationOutcome.ProceedOnce:
              case ToolConfirmationOutcome.ProceedAlways:
                this.wasAnswered = true;
                this.userAnswers = payload?.answers ?? {};
                break;
              case ToolConfirmationOutcome.Cancel:
                this.wasAnswered = false;
                break;
              default:
                this.wasAnswered = true;
                this.userAnswers = payload?.answers ?? {};
                break;
            }
          }, "onConfirm")
        };
        return details;
      }
      async execute(_signal) {
        try {
          const isAcpMode = this._config.getExperimentalZedIntegration() || this._config.getInputFormat() === InputFormat.STREAM_JSON;
          if (!this._config.isInteractive() && !isAcpMode) {
            const errorMessage = "Cannot ask user questions in non-interactive mode without ACP support. Please run in interactive mode or enable ACP mode to use this tool.";
            return {
              llmContent: errorMessage,
              returnDisplay: errorMessage
            };
          }
          if (!this.wasAnswered) {
            const cancellationMessage = "User declined to answer the questions.";
            return {
              llmContent: cancellationMessage,
              returnDisplay: cancellationMessage
            };
          }
          const answersContent = Object.entries(this.userAnswers).map(([key, value]) => {
            const questionIndex = parseInt(key, 10);
            const question = this.params.questions[questionIndex];
            return `**${question?.header || `Question ${questionIndex + 1}`}**: ${value}`;
          }).join("\n");
          const llmMessage = `User has provided the following answers:

${answersContent}`;
          const displayMessage = `User has provided the following answers:

${answersContent}`;
          return {
            llmContent: llmMessage,
            returnDisplay: displayMessage
          };
        } catch (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          debugLogger95.error(`[AskUserQuestionTool] Error executing ask_user_question: ${errorMessage}`);
          const errorLlmContent = `Failed to process user answers: ${errorMessage}`;
          return {
            llmContent: errorLlmContent,
            returnDisplay: `Error processing answers: ${errorMessage}`
          };
        }
      }
    };
    AskUserQuestionTool = class _AskUserQuestionTool extends BaseDeclarativeTool {
      static {
        __name(this, "AskUserQuestionTool");
      }
      config;
      static Name = ToolNames.ASK_USER_QUESTION;
      constructor(config2) {
        super(_AskUserQuestionTool.Name, ToolDisplayNames.ASK_USER_QUESTION, askUserQuestionToolDescription, Kind.Think, askUserQuestionToolSchemaData.parametersJsonSchema);
        this.config = config2;
      }
      validateToolParams(params) {
        if (!Array.isArray(params.questions)) {
          return 'Parameter "questions" must be an array.';
        }
        if (params.questions.length < 1 || params.questions.length > 4) {
          return 'Parameter "questions" must contain between 1 and 4 questions.';
        }
        for (let i4 = 0; i4 < params.questions.length; i4++) {
          const question = params.questions[i4];
          if (!question.question || typeof question.question !== "string" || question.question.trim() === "") {
            return `Question ${i4 + 1}: "question" must be a non-empty string.`;
          }
          if (!question.header || typeof question.header !== "string" || question.header.trim() === "") {
            return `Question ${i4 + 1}: "header" must be a non-empty string.`;
          }
          if (question.header.length > 12) {
            return `Question ${i4 + 1}: "header" must be 12 characters or less.`;
          }
          if (!Array.isArray(question.options)) {
            return `Question ${i4 + 1}: "options" must be an array.`;
          }
          if (question.options.length < 2 || question.options.length > 4) {
            return `Question ${i4 + 1}: "options" must contain between 2 and 4 options.`;
          }
          for (let j2 = 0; j2 < question.options.length; j2++) {
            const option2 = question.options[j2];
            if (!option2.label || typeof option2.label !== "string" || option2.label.trim() === "") {
              return `Question ${i4 + 1}, Option ${j2 + 1}: "label" must be a non-empty string.`;
            }
            if (!option2.description || typeof option2.description !== "string" || option2.description.trim() === "") {
              return `Question ${i4 + 1}, Option ${j2 + 1}: "description" must be a non-empty string.`;
            }
          }
          if (question.multiSelect !== void 0 && typeof question.multiSelect !== "boolean") {
            return `Question ${i4 + 1}: "multiSelect" must be a boolean.`;
          }
        }
        return null;
      }
      createInvocation(params) {
        return new AskUserQuestionToolInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/exitPlanMode.js
var exitPlanMode_exports = {};
__export(exitPlanMode_exports, {
  ExitPlanModeTool: () => ExitPlanModeTool
});
var debugLogger96, 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();
    debugLogger96 = 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.

## When to Use This Tool
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.

## Before Using This Tool
Ensure your plan is complete and unambiguous:
- If you have unresolved questions about requirements or approach, use AskUserQuestion first (in earlier phases)
- Once your plan is finalized, use THIS tool to request approval

**Important:** Do NOT use AskUserQuestion to ask "Is this plan okay?" or "Should I proceed?" - that's exactly what THIS tool does. ExitPlanMode inherently requests user approval of your plan.

## Examples
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.
3. Initial task: "Add a new feature to handle user authentication" - If unsure about auth method (OAuth, JWT, etc.), use AskUserQuestion first, then use exit plan mode tool after clarifying the approach.
`;
    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:";
      }
      /**
       * Plan mode exit always requires user confirmation.
       */
      async getDefaultPermission() {
        return "ask";
      }
      async getConfirmationDetails(_abortSignal) {
        const prePlanMode = this.config.getPrePlanMode();
        const details = {
          type: "plan",
          title: "Would you like to proceed?",
          plan: this.params.plan,
          prePlanMode,
          onConfirm: /* @__PURE__ */ __name(async (outcome) => {
            switch (outcome) {
              case ToolConfirmationOutcome.RestorePrevious:
                this.wasApproved = true;
                this.setApprovalModeSafely(prePlanMode);
                break;
              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 (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          debugLogger96.error(`[ExitPlanModeTool] Failed to set approval mode to "${mode}": ${errorMessage}`);
        }
      }
      async execute(_signal) {
        const { plan } = this.params;
        try {
          const isYolo = this.config.getApprovalMode() === ApprovalMode.YOLO;
          const effectivelyApproved = this.wasApproved || isYolo;
          if (!effectivelyApproved) {
            const rejectionMessage = "Plan execution was not approved. Remaining in plan mode.";
            return {
              llmContent: rejectionMessage,
              returnDisplay: rejectionMessage
            };
          }
          try {
            this.config.savePlan(plan);
          } catch (error40) {
            debugLogger96.warn(`[ExitPlanModeTool] Failed to save plan to disk: ${error40 instanceof Error ? error40.message : String(error40)}`);
          }
          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 (error40) {
          const errorMessage = error40 instanceof Error ? error40.message : String(error40);
          debugLogger96.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);
      }
    };
  }
});

// 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_esm21 = __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 i4 = 1; i4 < children.length; i4++) {
    children[i4].prev = children[i4 - 1];
    children[i4 - 1].next = children[i4];
  }
  return children;
}
var Node3, DataNode, Text2, Comment2, ProcessingInstruction, NodeWithChildren, CDATA2, Document, Element;
var init_node3 = __esm({
  "node_modules/domhandler/lib/esm/node.js"() {
    init_esbuild_shims();
    init_esm21();
    Node3 = 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 Node3 {
      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(name4, data) {
        super(data);
        this.name = name4;
        this.type = ElementType.Directive;
      }
      get nodeType() {
        return 1;
      }
    };
    NodeWithChildren = class extends Node3 {
      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(name4, attribs, children = [], type = name4 === "script" ? ElementType.Script : name4 === "style" ? ElementType.Style : ElementType.Tag) {
        super(children);
        this.name = name4;
        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(name4) {
        this.name = name4;
      }
      get attributes() {
        return Object.keys(this.attribs).map((name4) => {
          var _a7, _b2;
          return {
            name: name4,
            value: this.attribs[name4],
            namespace: (_a7 = this["x-attribsNamespace"]) === null || _a7 === void 0 ? void 0 : _a7[name4],
            prefix: (_b2 = this["x-attribsPrefix"]) === null || _b2 === void 0 ? void 0 : _b2[name4]
          };
        });
      }
    };
    __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_esm22 = __esm({
  "node_modules/domhandler/lib/esm/index.js"() {
    init_esbuild_shims();
    init_esm21();
    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(error40) {
        this.handleCallback(error40);
      }
      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(name4, attribs) {
        const type = this.options.xmlMode ? ElementType.Tag : void 0;
        const element = new Element(name4, 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(name4, data) {
        const node = new ProcessingInstruction(name4, data);
        this.addNode(node);
      }
      handleCallback(error40) {
        if (typeof this.callback === "function") {
          this.callback(error40, this.dom);
        } else if (error40) {
          throw error40;
        }
      }
      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, i4) => {
    let position = i4;
    let value = void 0;
    if (i4 < data.tokens.length) {
      value = onToken(data.tokens[i4], data, i4);
      if (value !== void 0) {
        position++;
      }
    } else {
      onEnd?.(data, i4);
    }
    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 map2(p2, mapper) {
  return (data, i4) => mapInner(p2(data, i4), (v2, j2) => mapper(v2, data, i4, j2));
}
function option(p2, def2) {
  return (data, i4) => {
    const r5 = p2(data, i4);
    return r5.matched ? r5 : {
      matched: true,
      position: i4,
      value: def2
    };
  };
}
function choice(...ps) {
  return (data, i4) => {
    for (const p2 of ps) {
      const result = p2(data, i4);
      if (result.matched) {
        return result;
      }
    }
    return { matched: false };
  };
}
function otherwise(pa, pb) {
  return (data, i4) => {
    const r1 = pa(data, i4);
    return r1.matched ? r1 : pb(data, i4);
  };
}
function takeWhile(p2, test2) {
  return (data, i4) => {
    const values = [];
    let success2 = true;
    do {
      const r5 = p2(data, i4);
      if (r5.matched && test2(r5.value, values.length + 1, data, i4, r5.position)) {
        values.push(r5.value);
        i4 = r5.position;
      } else {
        success2 = false;
      }
    } while (success2);
    return {
      matched: true,
      position: i4,
      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, join71) {
  return (data, i4) => mapOuter(pa(data, i4), (ma) => mapInner(pb(data, ma.position), (vb, j2) => join71(ma.value, vb, data, i4, 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, join71) {
  return (data, i4) => mapOuter(pa(data, i4), (ma) => mapOuter(pb(data, ma.position), (mb) => mapInner(pc(data, mb.position), (vc, j2) => join71(ma.value, mb.value, vc, data, i4, j2))));
}
function middle(pa, pb, pc) {
  return abc(pa, pb, pc, (ra, rb) => rb);
}
function all(...ps) {
  return (data, i4) => {
    const result = [];
    let position = i4;
    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 map2(p2, (vs) => vs.flatMap((v2) => v2));
}
function chainReduce(acc, f5) {
  return (data, i4) => {
    let loop = true;
    let acc1 = acc;
    let pos2 = i4;
    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) => map2(p2, (v2, data, i4, j2) => reducer(acc2, v2, data, i4, 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, i4) => mapOuter(p2(data, i4), (m1) => f5(m1.value, data, i4, 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(map2, "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(name4) {
  return token((t5) => t5.name === name4 ? 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 normalize7(selector) {
  if (!selector.type) {
    throw new Error("This is not an AST node.");
  }
  switch (selector.type) {
    case "compound": {
      selector.list.forEach(normalize7);
      selector.list.sort((a2, b2) => _compareArrays(_getSelectorPriority(a2), _getSelectorPriority(b2)));
      break;
    }
    case "combinator": {
      normalize7(selector.left);
      break;
    }
    case "list": {
      selector.list.forEach(normalize7);
      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 i4 = 0; i4 < shorter; i4++) {
    if (a2[i4] === b2[i4]) {
      continue;
    }
    return a2[i4] < b2[i4] ? -1 : 1;
  }
  return a2.length - b2.length;
}
var ws, nl, nonascii, unicode, escape4, nmstart, nmchar, name3, 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])?)`;
    escape4 = `(?:\\\\[^\\n\\r\\f0-9a-f])`;
    nmstart = `(?:[_a-z]|${nonascii}|${unicode}|${escape4})`;
    nmchar = `(?:[_a-z0-9-]|${nonascii}|${unicode}|${escape4})`;
    name3 = `(?:${nmchar}+)`;
    ident = `(?:[-]?${nmstart}${nmchar}*)`;
    string1 = `'([^\\n\\r\\f\\\\']|\\\\${nl}|${nonascii}|${unicode}|${escape4})*'`;
    string22 = `"([^\\n\\r\\f\\\\"]|\\\\${nl}|${nonascii}|${unicode}|${escape4})*"`;
    lexSelector = o2([
      { name: "ws", regex: new RegExp(ws) },
      { name: "hash", regex: new RegExp(`#${name3}`, "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(escape4, "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_ = map2(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, name4) => ({ name: name4, namespace: ns })), map2(identifier_, (name4) => ({ name: name4, namespace: null })));
    uniSelector_ = otherwise(ab(namespace_, literal2("*"), (ns) => ({ type: "universal", namespace: ns, specificity: [0, 0, 0] })), map2(literal2("*"), () => ({ type: "universal", namespace: null, specificity: [0, 0, 0] })));
    tagSelector_ = map2(qualifiedName_, ({ name: name4, namespace }) => ({
      type: "tag",
      name: name4,
      namespace,
      specificity: [0, 0, 1]
    }));
    classSelector_ = ab(literal2("."), identifier_, (fullstop, name4) => ({
      type: "class",
      name: name4,
      specificity: [0, 1, 0]
    }));
    idSelector_ = map2(hashId_, (name4) => ({
      type: "id",
      name: name4,
      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(map2(literal2("="), () => "="), ab(literal2("~"), literal2("="), () => "~="), ab(literal2("|"), literal2("="), () => "|="), ab(literal2("^"), literal2("="), () => "^="), ab(literal2("$"), literal2("="), () => "$="), ab(literal2("*"), literal2("="), () => "*="));
    attrPresenceSelector_ = abc(literal2("["), optionallySpaced(qualifiedName_), literal2("]"), (lbr, { name: name4, namespace }) => ({
      type: "attrPresence",
      name: name4,
      namespace,
      specificity: [0, 1, 0]
    }));
    attrValueSelector_ = middle(literal2("["), abc(optionallySpaced(qualifiedName_), attrMatcher_, optionallySpaced(attrValue_), ({ name: name4, namespace }, matcher, { value, modifier }) => ({
      type: "attrValue",
      name: name4,
      namespace,
      matcher,
      value,
      modifier,
      specificity: [0, 1, 0]
    })), literal2("]"));
    attrSelector_ = otherwise(attrPresenceSelector_, attrValueSelector_);
    typeSelector_ = otherwise(uniSelector_, tagSelector_);
    subclassSelector_ = choice(idSelector_, classSelector_, attrSelector_);
    compoundSelector_ = map2(otherwise(flatten(typeSelector_, many(subclassSelector_)), many1(subclassSelector_)), (ss) => {
      return {
        type: "compound",
        list: ss,
        specificity: sumAllSpec(ss.map((s5) => s5.specificity))
      };
    });
    combinator_ = choice(map2(literal2(">"), () => ">"), map2(literal2("+"), () => "+"), map2(literal2("~"), () => "~"), ab(literal2("|"), literal2("|"), () => "||"));
    combinatorSeparator_ = otherwise(optionallySpaced(combinator_), map2(whitespace_, () => " "));
    complexSelector_ = leftAssoc2(compoundSelector_, map2(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(map2(complexSelector_, (s5) => ({ type: "list", list: [s5] })), map2(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(normalize7, "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 i4 = 0; i4 < len; i4++) {
    const [selectorString, val] = array2[i4];
    const ast = preprocess2(parse1(selectorString));
    results[i4] = {
      ast,
      terminal: {
        type: "terminal",
        valueContainer: { index: i4, value: val, specificity: ast.specificity }
      }
    };
  }
  return results;
}
function preprocess2(ast) {
  reduceSelectorVariants(ast);
  normalize7(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: matches2, nonmatches, empty } = breakByKind(items, topKind);
    items = nonmatches;
    if (matches2.length) {
      branches.push(branchOfKind(topKind, matches2));
    }
    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: matches2, rest } = partition3(terminal.cont, (node) => node.type === "terminal");
      matches2.forEach((node) => results.push(node));
      if (rest.length) {
        terminal.cont = rest;
        results.push(terminal);
      }
    }
  }
  return results;
}
function breakByKind(items, selectedKind) {
  const matches2 = [];
  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 ? matches2 : nonmatches).push(item);
    } else {
      empty.push(item);
    }
  }
  return { matches: matches2, 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(([name4, group]) => ({
    type: "variant",
    value: name4,
    cont: weave(group.items)
  }));
  return {
    type: "tagName",
    variants
  };
}
function attrPresenceBranch(name4, items) {
  for (const item of items) {
    spliceSimpleSelector(item, (x3) => x3.type === "attrPresence" && x3.name === name4);
  }
  return {
    type: "attrPresence",
    name: name4,
    cont: weave(items)
  };
}
function attrValueBranch(name4, items) {
  const groups = spliceAndGroup(items, (x3) => x3.type === "attrValue" && x3.name === name4, (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: name4,
    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: matches2, rest } = partition1(items, hasBestKeyPredicate);
    let oneSimpleSelector = null;
    for (const item of matches2) {
      const splicedNode = spliceSimpleSelector(item, bestKeyPredicate);
      if (!oneSimpleSelector) {
        oneSimpleSelector = splicedNode;
      }
    }
    if (oneSimpleSelector == null) {
      throw new Error("No simple selector is found.");
    }
    groups[bestKey] = { oneSimpleSelector, items: matches2 };
    items = rest;
  }
  return groups;
}
function spliceSimpleSelector(item, predicate) {
  const simpsels = item.ast.list;
  const matches2 = new Array(simpsels.length);
  let firstIndex = -1;
  for (let i4 = simpsels.length; i4-- > 0; ) {
    if (predicate(simpsels[i4])) {
      matches2[i4] = true;
      firstIndex = i4;
    }
  }
  if (firstIndex == -1) {
    throw new Error(`Couldn't find the required simple selector.`);
  }
  const result = simpsels[firstIndex];
  item.ast.list = simpsels.filter((sel, i4) => !matches2[i4]);
  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 matches2 = [];
  const rest = [];
  for (const x3 of src) {
    if (predicate(x3)) {
      matches2.push(x3);
    } else {
      rest.push(x3);
    }
  }
  return { matches: matches2, rest };
}
function partition1(src, predicate) {
  const matches2 = [];
  const rest = [];
  for (const x3 of src) {
    if (predicate(x3)) {
      matches2.push(x3);
    } else {
      rest.push(x3);
    }
  }
  return { matches: matches2, 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 i4 = 1; i4 < len; i4++) {
          const next = results[i4];
          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_esm22();
    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, start2, end, base) {
        if (start2 !== end) {
          const digitCount = end - start2;
          this.result = this.result * Math.pow(base, digitCount) + parseInt(str2.substr(start2, 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 isWhitespace3(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 || isWhitespace3(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(isWhitespace3, "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 || isWhitespace3(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 (isWhitespace3(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 || isWhitespace3(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 (!isWhitespace3(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 (!isWhitespace3(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 (!isWhitespace3(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 (!isWhitespace3(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 (isWhitespace3(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(start2, endIndex) {
        if (this.baseState !== State.Text && this.baseState !== State.InSpecialTag) {
          this.cbs.onattribdata(start2, endIndex);
        } else {
          this.cbs.ontext(start2, 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, Parser4;
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|\//;
    Parser4 = 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(start2, endIndex) {
        var _a7, _b2;
        const data = this.getSlice(start2, 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(name4) {
        return !this.options.xmlMode && voidElements.has(name4);
      }
      /** @internal */
      onopentagname(start2, endIndex) {
        this.endIndex = endIndex;
        let name4 = this.getSlice(start2, endIndex);
        if (this.lowerCaseTagNames) {
          name4 = name4.toLowerCase();
        }
        this.emitOpenTag(name4);
      }
      emitOpenTag(name4) {
        var _a7, _b2, _c2, _d;
        this.openTagStart = this.startIndex;
        this.tagname = name4;
        const impliesClose = !this.options.xmlMode && openImpliesClose.get(name4);
        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(name4)) {
          this.stack.push(name4);
          if (foreignContextElements.has(name4)) {
            this.foreignContext.push(true);
          } else if (htmlIntegrationElements.has(name4)) {
            this.foreignContext.push(false);
          }
        }
        (_d = (_c2 = this.cbs).onopentagname) === null || _d === void 0 ? void 0 : _d.call(_c2, name4);
        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(start2, endIndex) {
        var _a7, _b2, _c2, _d, _e2, _f;
        this.endIndex = endIndex;
        let name4 = this.getSlice(start2, endIndex);
        if (this.lowerCaseTagNames) {
          name4 = name4.toLowerCase();
        }
        if (foreignContextElements.has(name4) || htmlIntegrationElements.has(name4)) {
          this.foreignContext.pop();
        }
        if (!this.isVoidElement(name4)) {
          const pos2 = this.stack.lastIndexOf(name4);
          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 && name4 === "p") {
            this.emitOpenTag("p");
            this.closeCurrentTag(true);
          }
        } else if (!this.options.xmlMode && name4 === "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 name4 = this.tagname;
        this.endOpenTag(isOpenImplied);
        if (this.stack[this.stack.length - 1] === name4) {
          (_b2 = (_a7 = this.cbs).onclosetag) === null || _b2 === void 0 ? void 0 : _b2.call(_a7, name4, !isOpenImplied);
          this.stack.pop();
        }
      }
      /** @internal */
      onattribname(start2, endIndex) {
        this.startIndex = start2;
        const name4 = this.getSlice(start2, endIndex);
        this.attribname = this.lowerCaseAttributeNames ? name4.toLowerCase() : name4;
      }
      /** @internal */
      onattribdata(start2, endIndex) {
        this.attribvalue += this.getSlice(start2, 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 name4 = index < 0 ? value : value.substr(0, index);
        if (this.lowerCaseTagNames) {
          name4 = name4.toLowerCase();
        }
        return name4;
      }
      /** @internal */
      ondeclaration(start2, endIndex) {
        this.endIndex = endIndex;
        const value = this.getSlice(start2, endIndex);
        if (this.cbs.onprocessinginstruction) {
          const name4 = this.getInstructionName(value);
          this.cbs.onprocessinginstruction(`!${name4}`, `!${value}`);
        }
        this.startIndex = endIndex + 1;
      }
      /** @internal */
      onprocessinginstruction(start2, endIndex) {
        this.endIndex = endIndex;
        const value = this.getSlice(start2, endIndex);
        if (this.cbs.onprocessinginstruction) {
          const name4 = this.getInstructionName(value);
          this.cbs.onprocessinginstruction(`?${name4}`, `?${value}`);
        }
        this.startIndex = endIndex + 1;
      }
      /** @internal */
      oncomment(start2, 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(start2, endIndex - offset));
        (_d = (_c2 = this.cbs).oncommentend) === null || _d === void 0 ? void 0 : _d.call(_c2);
        this.startIndex = endIndex + 1;
      }
      /** @internal */
      oncdata(start2, endIndex, offset) {
        var _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j, _k;
        this.endIndex = endIndex;
        const value = this.getSlice(start2, 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(start2, end) {
        while (start2 - this.bufferOffset >= this.buffers[0].length) {
          this.shiftBuffer();
        }
        let slice = this.buffers[0].slice(start2 - 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 i4 = 1; i4 < arr.length; i4++) {
    arr[i4][0] += arr[i4 - 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 i4 = match2.index;
    const char = str2.charCodeAt(i4);
    const next = xmlCodeMap.get(char);
    if (next !== void 0) {
      ret += str2.substring(lastIdx, i4) + next;
      lastIdx = i4 + 1;
    } else {
      ret += `${str2.substring(lastIdx, i4)}&#x${getCodePoint(str2, i4).toString(16)};`;
      lastIdx = xmlReplacer.lastIndex += Number((char & 64512) === 55296);
    }
  }
  return ret + str2.substr(lastIdx);
}
function getEscaper(regex3, map3) {
  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 += map3.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_esm23 = __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 encode6 = ((_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}="${encode6(value)}"`;
  }).join(" ");
}
function render(node, options2 = {}) {
  const nodes = "length" in node ? node : [node];
  let output = "";
  for (let i4 = 0; i4 < nodes.length; i4++) {
    output += renderNode(nodes[i4], 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_esm24 = __esm({
  "node_modules/dom-serializer/lib/esm/index.js"() {
    init_esbuild_shims();
    init_esm21();
    init_esm23();
    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_esm22();
    init_esm24();
    init_esm21();
  }
});

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

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

// node_modules/domutils/lib/esm/legacy.js
var init_legacy = __esm({
  "node_modules/domutils/lib/esm/legacy.js"() {
    init_esbuild_shims();
    init_esm22();
    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_esm22();
    (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_esm25 = __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_esm22();
  }
});

// node_modules/htmlparser2/lib/esm/index.js
function parseDocument(data, options2) {
  const handler = new DomHandler(void 0, options2);
  new Parser4(handler, options2).end(data);
  return handler.root;
}
var init_esm26 = __esm({
  "node_modules/htmlparser2/lib/esm/index.js"() {
    init_esbuild_shims();
    init_Parser();
    init_Parser();
    init_esm22();
    init_esm22();
    init_Tokenizer();
    init_esm21();
    init_esm25();
    init_esm25();
    init_esm25();
    __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(symbol2) {
        return Object.propertyIsEnumerable.call(target, symbol2);
      }) : [];
    }
    __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(...args2) {
      return f5(f1, ...args2);
    }, "f1");
    return f1;
  }
  if (n3 >= 0) {
    return function(...args2) {
      return f5(limitedDepthRecursive(n3 - 1, f5, g2), ...args2);
    };
  }
  return g2;
}
function trimCharacter(str2, char) {
  let start2 = 0;
  let end = str2.length;
  while (start2 < end && str2[start2] === char) {
    ++start2;
  }
  while (end > start2 && str2[end - 1] === char) {
    --end;
  }
  return start2 > 0 || end < str2.length ? str2.substring(start2, 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 map3 = /* @__PURE__ */ new Map();
  for (let i4 = items.length; i4-- > 0; ) {
    const item = items[i4];
    const key = getKey(item);
    map3.set(
      key,
      map3.has(key) ? (0, import_deepmerge.default)(item, map3.get(key), { arrayMerge: overwriteMerge$1 }) : item
    );
  }
  return [...map3.values()].reverse();
}
function get2(obj, path150) {
  for (const key of path150) {
    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, i4) => v2 % 5 < 4 ? (v2 < 5 ? "" : V2[i4]) + I2[i4].repeat(v2 % 5) : I2[i4] + (v2 < 5 ? V2[i4] : I2[i4 + 1])).reverse().join("");
}
function charactersToCodes(str2) {
  return [...str2].map((c4) => "\\u" + c4.charCodeAt(0).toString(16).padStart(4, "0")).join("");
}
function getText2(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 = getText2(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, i4) => [s5, i4 + 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, metadata2 = void 0) {
    return process12(html2, metadata2, options2, picker, findBaseElements, limitedWalk);
  };
}
function process12(html2, metadata2, 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, metadata2);
  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 i4 = 0; i4 < maxSize; i4++) {
    const rowI = getRow(matrix, i4);
    for (let j2 = 0; j2 < i4; j2++) {
      const rowJ = getRow(matrix, j2);
      if (rowI[j2] || rowJ[i4]) {
        const temp = rowI[j2];
        rowI[j2] = rowJ[i4];
        rowJ[i4] = 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 i4 = 0; i4 < cells.length; i4++) {
      const cell = cells[i4];
      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(path150, rewriter, baseUrl, metadata2, elem) {
  const modifiedPath = typeof rewriter === "function" ? rewriter(path150, metadata2, elem) : path150;
  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 = get2(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 (i4) => numberToLetterSequence(i4, "a");
    case "A":
      return (i4) => numberToLetterSequence(i4, "A");
    case "i":
      return (i4) => numberToRoman(i4).toLowerCase();
    case "I":
      return (i4) => numberToRoman(i4);
    case "1":
    default:
      return (i4) => i4.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 = +get2(cellNode, ["attribs", "colspan"]) || 1;
    const rowspan = +get2(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 = {}, metadata2 = void 0) {
  return compile(options2)(html2, metadata2);
}
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 set2(obj, path150, value) {
    const valueKey = path150.pop();
    for (const key of path150) {
      let nested = obj[key];
      if (!nested) {
        nested = {};
        obj[key] = nested;
      }
      obj = nested;
    }
    obj[valueKey] = value;
  }
  __name(set2, "set");
  if (options2["baseElement"]) {
    const baseElement = options2["baseElement"];
    set2(
      options2,
      ["baseElements", "selectors"],
      Array.isArray(baseElement) ? baseElement : [baseElement]
    );
  }
  if (options2["returnDomByDefault"] !== void 0) {
    set2(options2, ["baseElements", "returnDomByDefault"], options2["returnDomByDefault"]);
  }
  for (const definition of options2.selectors) {
    if (definition.format === "anchor" && get2(definition, ["options", "noLinkBrackets"])) {
      set2(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_esm26();
    init_selderee();
    import_deepmerge = __toESM(require_cjs2(), 1);
    init_esm24();
    __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(get2, "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 = get2(options2, ["longWordSplit", "wrapCharacters"]) || [];
        this.forceWrapOnLimit = get2(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 parts2 = [];
        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;
            parts2.push(firstLine.substring(0, splitIndex + 1));
          } else {
            idx++;
            if (idx < this.wrapCharacters.length) {
              word = firstLine + remainingChars;
            } else {
              if (this.forceWrapOnLimit) {
                parts2.push(firstLine);
                word = remainingChars;
                if (word.length > this.maxLineLength) {
                  continue;
                }
              } else {
                word = firstLine + remainingChars;
              }
              break;
            }
          }
        }
        parts2.push(word);
        return parts2;
      }
    };
    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, metadata2 = void 0) {
        this.options = options2;
        this.picker = picker;
        this.metadata = metadata2;
        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(getText2(block2)) : getText2(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 + getText2(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 = getText2(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(getText2(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 getText2(this._stackItem.getRoot());
      }
    };
    __name(getText2, "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 web_fetch_exports = {};
__export(web_fetch_exports, {
  WebFetchTool: () => WebFetchTool
});
var 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();
    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");
      }
      getAcceptHeader() {
        const format4 = this.params.format ?? "auto";
        switch (format4) {
          case "markdown":
            return "text/markdown";
          case "html":
            return "text/html";
          case "text":
            return "text/plain";
          case "auto":
          default:
            return "text/markdown, text/html, text/plain";
        }
      }
      async executeDirectFetch(signal) {
        let url3 = this.params.url;
        if (url3.includes("github.com") && url3.includes("/blob/")) {
          url3 = url3.replace("github.com", "raw.githubusercontent.com").replace("/blob/", "/");
          this.debugLogger.debug(`[WebFetchTool] Converted GitHub blob URL to raw URL: ${url3}`);
        }
        const acceptHeader = this.getAcceptHeader();
        this.debugLogger.debug(`[WebFetchTool] Using Accept header: ${acceptHeader}`);
        try {
          this.debugLogger.debug(`[WebFetchTool] Fetching content from: ${url3}`);
          const response = await fetchWithTimeout(url3, URL_FETCH_TIMEOUT_MS, {
            Accept: acceptHeader
          });
          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 ${url3}`);
          const contentType = response.headers.get("content-type") || "";
          const responseText = await response.text();
          let textContent2;
          if (contentType.includes("text/markdown")) {
            this.debugLogger.debug("[WebFetchTool] Received markdown content");
            textContent2 = responseText.substring(0, MAX_CONTENT_LENGTH);
          } else if (contentType.includes("text/plain")) {
            this.debugLogger.debug("[WebFetchTool] Received plain text content");
            textContent2 = responseText.substring(0, MAX_CONTENT_LENGTH);
          } else {
            this.debugLogger.debug("[WebFetchTool] Converting HTML to text");
            textContent2 = convert(responseText, {
              wordwrap: false,
              selectors: [
                { selector: "a", options: { ignoreHref: true } },
                { selector: "img", format: "skip" }
              ]
            }).substring(0, MAX_CONTENT_LENGTH);
          }
          this.debugLogger.debug(`[WebFetchTool] Content length: ${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 }] }], {
            systemInstruction: "Extract and summarize the requested information from the provided web content. Be concise and accurate. Respond only with the requested information."
          }, 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 error40 = e4;
          const errorMessage = `Error during fetch for ${url3}: ${error40.message}`;
          this.debugLogger.error(`[WebFetchTool] ${errorMessage}`, error40);
          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;
        const format4 = this.params.format ?? "auto";
        return `Fetching content from ${this.params.url} (format: ${format4}) and processing with prompt: "${displayPrompt}"`;
      }
      /**
       * WebFetch is a read-like tool (fetches content) but requires confirmation
       * because it makes external network requests.
       */
      async getDefaultPermission() {
        return "ask";
      }
      /**
       * Constructs the web fetch confirmation details.
       */
      async getConfirmationDetails(_abortSignal) {
        let domain2;
        try {
          domain2 = new URL(this.params.url).hostname;
        } catch {
          domain2 = this.params.url;
        }
        const permissionRules = [`WebFetch(${domain2})`];
        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],
          permissionRules,
          onConfirm: /* @__PURE__ */ __name(async (_outcome, _payload) => {
          }, "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
- Supports content negotiation for markdown (reduces tokens by ~80%)
- Fetches the URL content, converts HTML to text if needed
- 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
  - format parameter (optional): controls only the Accept header sent to the server. All content is normalized to plain text for LLM processing, regardless of format.
  - "auto" (default): Prefers markdown via content negotiation, accepts HTML as fallback. Use when user does NOT specify a format.
  - "markdown": Sends Accept: text/markdown. Use when user explicitly asks for markdown content.
  - "html": Sends Accept: text/html. Content is still converted to plain text for LLM processing.
  - "text": Sends Accept: text/plain. Use when user explicitly asks for plain text.
  - 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"
            },
            format: {
              description: "Preferred content format (Accept header only): auto (default, prefers markdown), markdown, html, or text. All content is normalized to plain text.",
              type: "string",
              enum: ["auto", "markdown", "html", "text"]
            }
          },
          required: ["url", "prompt"],
          type: "object"
        });
        this.config = config2;
      }
      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/lsp.js
var lsp_exports = {};
__export(lsp_exports, {
  LspTool: () => LspTool
});
import path82 from "node:path";
import { fileURLToPath as fileURLToPath8, 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 (error40) {
          const message = `LSP go-to-definition failed: ${error40?.message || String(error40)}`;
          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 (error40) {
          const message = `LSP go-to-implementation failed: ${error40?.message || String(error40)}`;
          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 (error40) {
          const message = `LSP find-references failed: ${error40?.message || String(error40)}`;
          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 (error40) {
          const message = `LSP hover failed: ${error40?.message || String(error40)}`;
          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 (error40) {
          const message = `LSP document symbols failed: ${error40?.message || String(error40)}`;
          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((symbol2, index) => {
          const location = this.formatLocationWithoutServer(symbol2.location, workspaceRoot);
          const serverSuffix = symbol2.serverName ? ` [${symbol2.serverName}]` : "";
          const kind2 = symbol2.kind ? ` (${symbol2.kind})` : "";
          const container = symbol2.containerName ? ` in ${symbol2.containerName}` : "";
          return `${index + 1}. ${symbol2.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 (error40) {
          const message = `LSP workspace symbol search failed: ${error40?.message || String(error40)}`;
          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((symbol2, index) => {
          const location = this.formatLocationWithoutServer(symbol2.location, workspaceRoot);
          const serverSuffix = symbol2.serverName ? ` [${symbol2.serverName}]` : "";
          const kind2 = symbol2.kind ? ` (${symbol2.kind})` : "";
          const container = symbol2.containerName ? ` in ${symbol2.containerName}` : "";
          return `${index + 1}. ${symbol2.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 (error40) {
            referenceSection = `
References lookup failed: ${error40?.message || String(error40)}`;
          }
        }
        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 (error40) {
          const message = `LSP call hierarchy prepare failed: ${error40?.message || String(error40)}`;
          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 (error40) {
          const message = `LSP incoming calls failed: ${error40?.message || String(error40)}`;
          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 (error40) {
          const message = `LSP outgoing calls failed: ${error40?.message || String(error40)}`;
          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 (error40) {
          const message = `LSP diagnostics failed: ${error40?.message || String(error40)}`;
          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 (error40) {
          const message = `LSP workspace diagnostics failed: ${error40?.message || String(error40)}`;
          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 (error40) {
          const message = `LSP code actions failed: ${error40?.message || String(error40)}`;
          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 = path82.isAbsolute(filePath) ? filePath : path82.resolve(workspaceRoot, filePath);
        return pathToFileURL2(absolutePath).toString();
      }
      formatLocationWithServer(location, workspaceRoot) {
        const start2 = location.range.start;
        let filePath = location.uri;
        if (filePath.startsWith("file://")) {
          filePath = fileURLToPath8(filePath);
          filePath = path82.relative(workspaceRoot, filePath) || ".";
        }
        const serverSuffix = location.serverName && location.serverName !== "" ? ` [${location.serverName}]` : "";
        return `${filePath}:${(start2.line ?? 0) + 1}:${(start2.character ?? 0) + 1}${serverSuffix}`;
      }
      formatLocationWithoutServer(location, workspaceRoot) {
        const { uri, range } = location;
        let filePath = uri;
        if (uri.startsWith("file://")) {
          filePath = fileURLToPath8(uri);
          filePath = path82.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 = fileURLToPath8(uri);
        }
        if (path82.isAbsolute(filePath)) {
          return path82.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/tools/cron-create.js
var cron_create_exports = {};
__export(cron_create_exports, {
  CronCreateTool: () => CronCreateTool
});
var CronCreateInvocation, CronCreateTool;
var init_cron_create = __esm({
  "packages/core/dist/src/tools/cron-create.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_names();
    init_cronParser();
    init_cronDisplay();
    CronCreateInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "CronCreateInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      getDescription() {
        return `${this.params.cron}: ${this.params.prompt}`;
      }
      async execute() {
        const scheduler = this.config.getCronScheduler();
        const recurring = this.params.recurring !== false;
        try {
          parseCron(this.params.cron);
          const job = scheduler.create(this.params.cron, this.params.prompt, recurring);
          const display = humanReadableCron(job.cronExpr);
          const returnDisplay = `Scheduled ${job.id} (${display})`;
          let llmContent;
          if (recurring) {
            llmContent = `Scheduled recurring job ${job.id} (${job.cronExpr}). Session-only (not written to disk, dies when Qwen Code exits). Auto-expires after 3 days. Use CronDelete to cancel sooner.`;
          } else {
            llmContent = `Scheduled one-shot task ${job.id} (${job.cronExpr}). Session-only (not written to disk, dies when Qwen Code exits). It will fire once then auto-delete.`;
          }
          return { llmContent, returnDisplay };
        } catch (error40) {
          const message = error40 instanceof Error ? error40.message : String(error40);
          return {
            llmContent: `Error creating cron job: ${message}`,
            returnDisplay: message,
            error: { message }
          };
        }
      }
    };
    CronCreateTool = class _CronCreateTool extends BaseDeclarativeTool {
      static {
        __name(this, "CronCreateTool");
      }
      config;
      static Name = ToolNames.CRON_CREATE;
      constructor(config2) {
        super(_CronCreateTool.Name, ToolDisplayNames.CRON_CREATE, 'Schedule a prompt to be enqueued at a future time. Use for both recurring schedules and one-shot reminders.\n\nUses standard 5-field cron in the user\'s local timezone: minute hour day-of-month month day-of-week. "0 9 * * *" means 9am local \u2014 no timezone conversion needed.\n\n## One-shot tasks (recurring: false)\n\nFor "remind me at X" or "at <time>, do Y" requests \u2014 fire once then auto-delete.\nPin minute/hour/day-of-month/month to specific values:\n  "remind me at 2:30pm today to check the deploy" \u2192 cron: "30 14 <today_dom> <today_month> *", recurring: false\n  "tomorrow morning, run the smoke test" \u2192 cron: "57 8 <tomorrow_dom> <tomorrow_month> *", recurring: false\n\n## Recurring jobs (recurring: true, the default)\n\nFor "every N minutes" / "every hour" / "weekdays at 9am" requests:\n  "*/5 * * * *" (every 5 min), "0 * * * *" (hourly), "0 9 * * 1-5" (weekdays at 9am local)\n\n## Avoid the :00 and :30 minute marks when the task allows it\n\nEvery user who asks for "9am" gets `0 9`, and every user who asks for "hourly" gets `0 *` \u2014 which means requests from across the planet land on the API at the same instant. When the user\'s request is approximate, pick a minute that is NOT 0 or 30:\n  "every morning around 9" \u2192 "57 8 * * *" or "3 9 * * *" (not "0 9 * * *")\n  "hourly" \u2192 "7 * * * *" (not "0 * * * *")\n  "in an hour or so, remind me to..." \u2192 pick whatever minute you land on, don\'t round\n\nOnly use minute 0 or 30 when the user names that exact time and clearly means it ("at 9:00 sharp", "at half past", coordinating with a meeting). When in doubt, nudge a few minutes early or late \u2014 the user will not notice, and the fleet will.\n\n## Session-only\n\nJobs live only in this Qwen Code session \u2014 nothing is written to disk, and the job is gone when Qwen Code exits.\n\n## Runtime behavior\n\nJobs only fire while the REPL is idle (not mid-query). The scheduler adds a small deterministic jitter on top of whatever you pick: recurring tasks fire up to 10% of their period late (max 15 min); one-shot tasks landing on :00 or :30 fire up to 90 s early. Picking an off-minute is still the bigger lever.\n\nRecurring tasks auto-expire after 3 days \u2014 they fire one final time, then are deleted. This bounds session lifetime. Tell the user about the 3-day limit when scheduling recurring jobs.\n\nReturns a job ID you can pass to CronDelete.', Kind.Other, {
          type: "object",
          properties: {
            cron: {
              type: "string",
              description: 'Standard 5-field cron expression in local time: "M H DoM Mon DoW" (e.g. "*/5 * * * *" = every 5 minutes, "30 14 28 2 *" = Feb 28 at 2:30pm local once).'
            },
            prompt: {
              type: "string",
              description: "The prompt to enqueue at each fire time."
            },
            recurring: {
              type: "boolean",
              description: 'true (default) = fire on every cron match until deleted or auto-expired after 3 days. false = fire once at the next match, then auto-delete. Use false for "remind me at X" one-shot requests with pinned minute/hour/dom/month.'
            }
          },
          required: ["cron", "prompt"],
          additionalProperties: false
        });
        this.config = config2;
      }
      createInvocation(params) {
        return new CronCreateInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/cron-list.js
var cron_list_exports = {};
__export(cron_list_exports, {
  CronListTool: () => CronListTool
});
var CronListInvocation, CronListTool;
var init_cron_list = __esm({
  "packages/core/dist/src/tools/cron-list.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_names();
    init_cronDisplay();
    CronListInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "CronListInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      getDescription() {
        return "";
      }
      async execute() {
        const scheduler = this.config.getCronScheduler();
        const jobs = scheduler.list();
        if (jobs.length === 0) {
          const result = "No active cron jobs.";
          return { llmContent: result, returnDisplay: result };
        }
        const llmLines = jobs.map((job) => {
          const type = job.recurring ? "recurring" : "one-shot";
          return `${job.id} \u2014 ${job.cronExpr} (${type}) [session-only]: ${job.prompt}`;
        });
        const llmContent = llmLines.join("\n");
        const displayLines = jobs.map((job) => `${job.id} ${humanReadableCron(job.cronExpr)}`);
        const returnDisplay = displayLines.join("\n");
        return { llmContent, returnDisplay };
      }
    };
    CronListTool = class _CronListTool extends BaseDeclarativeTool {
      static {
        __name(this, "CronListTool");
      }
      config;
      static Name = ToolNames.CRON_LIST;
      constructor(config2) {
        super(_CronListTool.Name, ToolDisplayNames.CRON_LIST, "List all cron jobs scheduled via CronCreate in this session.", Kind.Other, {
          type: "object",
          properties: {},
          additionalProperties: false
        });
        this.config = config2;
      }
      createInvocation(params) {
        return new CronListInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/tools/cron-delete.js
var cron_delete_exports = {};
__export(cron_delete_exports, {
  CronDeleteTool: () => CronDeleteTool
});
var CronDeleteInvocation, CronDeleteTool;
var init_cron_delete = __esm({
  "packages/core/dist/src/tools/cron-delete.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    init_tool_names();
    CronDeleteInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "CronDeleteInvocation");
      }
      config;
      constructor(config2, params) {
        super(params);
        this.config = config2;
      }
      getDescription() {
        return this.params.id;
      }
      async execute() {
        const scheduler = this.config.getCronScheduler();
        const deleted = scheduler.delete(this.params.id);
        if (deleted) {
          const llmContent = `Cancelled job ${this.params.id}.`;
          const returnDisplay = `Cancelled ${this.params.id}`;
          return { llmContent, returnDisplay };
        } else {
          const result = `Job ${this.params.id} not found.`;
          return {
            llmContent: result,
            returnDisplay: result,
            error: { message: result }
          };
        }
      }
    };
    CronDeleteTool = class _CronDeleteTool extends BaseDeclarativeTool {
      static {
        __name(this, "CronDeleteTool");
      }
      config;
      static Name = ToolNames.CRON_DELETE;
      constructor(config2) {
        super(_CronDeleteTool.Name, ToolDisplayNames.CRON_DELETE, "Cancel a cron job previously scheduled with CronCreate. Removes it from the in-memory session store.", Kind.Other, {
          type: "object",
          properties: {
            id: {
              type: "string",
              description: "Job ID returned by CronCreate."
            }
          },
          required: ["id"],
          additionalProperties: false
        });
        this.config = config2;
      }
      createInvocation(params) {
        return new CronDeleteInvocation(this.config, params);
      }
    };
  }
});

// packages/core/dist/src/config/config.js
import * as fs88 from "node:fs";
import * as path83 from "node:path";
import process13 from "node:process";
import { randomUUID as randomUUID10 } 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_undici3, ApprovalMode, APPROVAL_MODES, APPROVAL_MODE_INFO, DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD, DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES, MCPServerConfig, AuthProviderType, DEFAULT_BARE_CORE_TOOLS, Config;
var init_config3 = __esm({
  "packages/core/dist/src/config/config.js"() {
    "use strict";
    init_esbuild_shims();
    import_undici3 = __toESM(require_undici(), 1);
    init_ArenaAgentClient();
    init_baseLlmClient();
    init_client4();
    init_contentGenerator();
    init_fileDiscoveryService();
    init_fileSystemService();
    init_gitService();
    init_cronScheduler();
    init_const();
    init_ripgrepUtils();
    init_tool_registry();
    init_tool_names();
    init_ideContext();
    init_types13();
    init_prompt_registry();
    init_skill_manager();
    init_permission_manager();
    init_subagent_manager();
    init_background_tasks();
    init_backgroundShellRegistry();
    init_telemetry();
    init_extensionManager();
    init_hooks();
    init_message_bus();
    init_types8();
    init_types6();
    init_toolHookTriggers();
    init_browser();
    init_ignorePatterns();
    init_shell_utils();
    init_workspaceContext();
    init_tool_utils();
    init_errors();
    init_proxyUtils();
    init_constants5();
    init_models();
    init_storage();
    init_chatRecordingService();
    init_sessionService();
    init_memoryDiscovery();
    init_rulesDiscovery();
    init_debugLogger();
    init_paths2();
    init_store();
    init_manager();
    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, args2, env6, cwd6, url3, httpUrl, headers, tcp, timeout2, trust, description, includeTools, excludeTools, extensionName, oauth, authProviderType, targetAudience, targetServiceAccount, type) {
        this.command = command2;
        this.args = args2;
        this.env = env6;
        this.cwd = cwd6;
        this.url = url3;
        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");
    DEFAULT_BARE_CORE_TOOLS = [
      ToolNames.READ_FILE,
      ToolNames.EDIT,
      ToolNames.SHELL
    ];
    Config = class {
      static {
        __name(this, "Config");
      }
      sessionId;
      sessionData;
      debugLogger;
      toolRegistry;
      promptRegistry;
      subagentManager;
      backgroundTaskRegistry = new BackgroundTaskRegistry();
      backgroundShellRegistry = new BackgroundShellRegistry();
      extensionManager;
      skillManager = null;
      permissionManager = null;
      modelInvocableCommandsProvider = null;
      modelInvocableCommandsExecutor = null;
      fileSystemService;
      contentGeneratorConfig;
      contentGeneratorConfigSources = {};
      contentGenerator;
      embeddingModel;
      modelsConfig;
      modelProvidersConfig;
      sandbox;
      targetDir;
      workspaceContext;
      debugMode;
      inputFormat;
      outputFormat;
      includePartialMessages;
      question;
      systemPrompt;
      appendSystemPrompt;
      coreTools;
      allowedTools;
      excludeTools;
      disabledSlashCommands;
      permissionsAllow;
      permissionsAsk;
      permissionsDeny;
      toolDiscoveryCommand;
      toolCallCommand;
      mcpServerCommand;
      mcpServers;
      lspEnabled;
      lspClient;
      allowedMcpServers;
      excludedMcpServers;
      sessionSubagents;
      userMemory;
      sdkMode;
      geminiMdFileCount;
      conditionalRulesRegistry;
      contextRuleExcludes;
      approvalMode;
      prePlanMode;
      accessibility;
      telemetrySettings;
      gitCoAuthor;
      usageStatisticsEnabled;
      geminiClient;
      baseLlmClient;
      cronScheduler = null;
      fileFiltering;
      fileDiscoveryService = null;
      gitService = void 0;
      sessionService = void 0;
      chatRecordingService = void 0;
      checkpointing;
      proxy;
      cwd;
      explicitIncludeDirectories;
      bugCommand;
      outputLanguageFilePath;
      noBrowser;
      folderTrustFeature;
      folderTrust;
      ideMode;
      maxSessionTurns;
      clearContextOnIdle;
      sessionTokenLimit;
      listExtensions;
      overrideExtensions;
      cliVersion;
      experimentalZedIntegration = false;
      cronEnabled = false;
      emitToolUseSummaries = true;
      chatRecordingEnabled;
      loadMemoryFromIncludeDirectories = false;
      importFormat;
      chatCompression;
      interactive;
      trustedFolder;
      useRipgrep;
      useBuiltinRipgrep;
      shouldUseNodePtyShell;
      skipNextSpeakerCheck;
      shellExecutionConfig;
      arenaManager = null;
      arenaManagerChangeCallback = null;
      arenaAgentClient;
      agentsSettings;
      skipLoopDetection;
      skipStartupContext;
      bareMode;
      warnings;
      allowedHttpHookUrls;
      onPersistPermissionRuleCallback;
      initialized = false;
      storage;
      fileExclusions;
      truncateToolOutputThreshold;
      truncateToolOutputLines;
      eventEmitter;
      channel;
      jsonFd;
      jsonFile;
      inputFile;
      defaultFileEncoding;
      enableManagedAutoMemory;
      enableManagedAutoDream;
      fastModel;
      disableAllHooks;
      /** User-level hooks (always loaded regardless of trust) */
      userHooks;
      /** Project-level hooks (only loaded in trusted folders) */
      projectHooks;
      /** @deprecated Legacy merged hooks field - use userHooks/projectHooks instead */
      hooks;
      hookSystem;
      messageBus;
      memoryManager;
      modelChangeListeners = /* @__PURE__ */ new Set();
      constructor(params) {
        this.sessionId = params.sessionId ?? randomUUID10();
        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 = path83.resolve(params.targetDir);
        this.explicitIncludeDirectories = Array.from(new Set(params.includeDirectories ?? []));
        this.workspaceContext = new WorkspaceContext(this.targetDir, this.explicitIncludeDirectories);
        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.systemPrompt = params.systemPrompt;
        this.appendSystemPrompt = params.appendSystemPrompt;
        this.coreTools = params.coreTools;
        this.allowedTools = params.allowedTools;
        this.excludeTools = params.excludeTools;
        this.disabledSlashCommands = Object.freeze([
          ...params.disabledSlashCommands ?? []
        ]);
        this.permissionsAllow = params.permissions?.allow || [];
        this.permissionsAsk = params.permissions?.ask || [];
        this.permissionsDeny = params.permissions?.deny || [];
        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.contextRuleExcludes = params.contextRuleExcludes ?? [];
        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 ?? process13.cwd();
        this.fileDiscoveryService = params.fileDiscoveryService ?? null;
        this.bugCommand = params.bugCommand;
        this.maxSessionTurns = params.maxSessionTurns ?? -1;
        this.clearContextOnIdle = {
          toolResultsThresholdMinutes: params.clearContextOnIdle?.toolResultsThresholdMinutes ?? 60,
          toolResultsNumToKeep: params.clearContextOnIdle?.toolResultsNumToKeep ?? 5
        };
        this.sessionTokenLimit = params.sessionTokenLimit ?? -1;
        this.experimentalZedIntegration = params.experimentalZedIntegration ?? false;
        this.cronEnabled = params.cronEnabled ?? false;
        this.emitToolUseSummaries = params.emitToolUseSummaries ?? true;
        this.listExtensions = params.listExtensions ?? false;
        this.overrideExtensions = params.overrideExtensions;
        this.noBrowser = params.noBrowser ?? false;
        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.bareMode = params.bareMode ?? false;
        this.warnings = params.warnings ?? [];
        this.allowedHttpHookUrls = params.allowedHttpHookUrls ?? [];
        this.onPersistPermissionRuleCallback = params.onPersistPermissionRule;
        this.useRipgrep = params.useRipgrep ?? true;
        this.useBuiltinRipgrep = params.useBuiltinRipgrep ?? true;
        this.shouldUseNodePtyShell = params.shouldUseNodePtyShell ?? shouldDefaultToNodePty();
        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.channel = params.channel;
        this.jsonFd = params.jsonFd;
        this.jsonFile = params.jsonFile;
        this.inputFile = params.inputFile;
        this.defaultFileEncoding = params.defaultFileEncoding;
        this.storage = new Storage(this.targetDir);
        this.inputFormat = params.inputFormat ?? InputFormat.TEXT;
        this.fileExclusions = new FileExclusions(this);
        this.eventEmitter = params.eventEmitter;
        this.arenaAgentClient = ArenaAgentClient.create();
        this.agentsSettings = params.agents ?? {};
        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);
        }
        const proxyUrl = this.getProxy();
        if (proxyUrl) {
          (0, import_undici3.setGlobalDispatcher)(new import_undici3.ProxyAgent(proxyUrl));
        }
        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()
        });
        this.enableManagedAutoMemory = params.enableManagedAutoMemory ?? true;
        this.enableManagedAutoDream = params.enableManagedAutoDream ?? false;
        this.fastModel = params.fastModel || void 0;
        this.disableAllHooks = params.disableAllHooks ?? false;
        this.userHooks = params.userHooks;
        this.projectHooks = params.projectHooks;
        this.hooks = params.hooks;
        this.memoryManager = new MemoryManager();
      }
      /**
       * 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);
        const explicitExtensionNames = this.getExplicitExtensionNames();
        if (!this.getBareMode()) {
          await this.extensionManager.refreshCache();
        } else if (explicitExtensionNames.length > 0) {
          await this.extensionManager.refreshCache({
            names: explicitExtensionNames
          });
        }
        this.debugLogger.debug("Extension manager initialized");
        if (!this.getDisableAllHooks()) {
          this.hookSystem = new HookSystem(this);
          await this.hookSystem.initialize();
          this.debugLogger.debug("Hook system initialized");
          this.messageBus = new MessageBus();
          this.messageBus.subscribe(MessageBusType.HOOK_EXECUTION_REQUEST, async (request4) => {
            try {
              const hookSystem = this.hookSystem;
              if (!hookSystem) {
                this.messageBus?.publish({
                  type: MessageBusType.HOOK_EXECUTION_RESPONSE,
                  correlationId: request4.correlationId,
                  success: false,
                  error: new Error("Hook system not initialized")
                });
                return;
              }
              if (request4.signal?.aborted) {
                this.messageBus?.publish({
                  type: MessageBusType.HOOK_EXECUTION_RESPONSE,
                  correlationId: request4.correlationId,
                  success: false,
                  error: new Error("Hook execution cancelled (aborted)")
                });
                return;
              }
              let result;
              let stopHookCount;
              const input = request4.input || {};
              const signal = request4.signal;
              switch (request4.eventName) {
                case "UserPromptSubmit":
                  result = await hookSystem.fireUserPromptSubmitEvent(input["prompt"] || "", signal);
                  break;
                case "Stop": {
                  const stopResult = await hookSystem.fireStopEvent(input["stop_hook_active"] || false, input["last_assistant_message"] || "", signal);
                  result = stopResult.finalOutput ? createHookOutput("Stop", stopResult.finalOutput) : void 0;
                  stopHookCount = stopResult.allOutputs.length;
                  break;
                }
                case "PreToolUse": {
                  result = await hookSystem.firePreToolUseEvent(input["tool_name"] || "", input["tool_input"] || {}, input["tool_use_id"] || "", input["permission_mode"] ?? PermissionMode.Default, signal);
                  break;
                }
                case "PostToolUse":
                  result = await hookSystem.firePostToolUseEvent(input["tool_name"] || "", input["tool_input"] || {}, input["tool_response"] || {}, input["tool_use_id"] || "", input["permission_mode"] || "default", signal);
                  break;
                case "PostToolUseFailure":
                  result = await hookSystem.firePostToolUseFailureEvent(input["tool_use_id"] || "", input["tool_name"] || "", input["tool_input"] || {}, input["error"] || "", input["is_interrupt"], input["permission_mode"] || "default", signal);
                  break;
                case "Notification":
                  result = await hookSystem.fireNotificationEvent(input["message"] || "", input["notification_type"] || "permission_prompt", input["title"] || void 0, signal);
                  break;
                case "PermissionRequest":
                  result = await hookSystem.firePermissionRequestEvent(input["tool_name"] || "", input["tool_input"] || {}, input["permission_mode"] || PermissionMode.Default, input["permission_suggestions"] || void 0, signal);
                  break;
                case "SubagentStart":
                  result = await hookSystem.fireSubagentStartEvent(input["agent_id"] || "", input["agent_type"] || "", input["permission_mode"] || PermissionMode.Default, signal);
                  break;
                case "SubagentStop":
                  result = await hookSystem.fireSubagentStopEvent(input["agent_id"] || "", input["agent_type"] || "", input["agent_transcript_path"] || "", input["last_assistant_message"] || "", input["stop_hook_active"] || false, input["permission_mode"] || PermissionMode.Default, signal);
                  break;
                default:
                  this.debugLogger.warn(`Unknown hook event: ${request4.eventName}`);
                  result = void 0;
              }
              this.messageBus?.publish({
                type: MessageBusType.HOOK_EXECUTION_RESPONSE,
                correlationId: request4.correlationId,
                success: true,
                output: result,
                // Include stop hook count for Stop events
                stopHookCount
              });
            } catch (error40) {
              this.debugLogger.warn(`Hook execution failed: ${error40}`);
              this.messageBus?.publish({
                type: MessageBusType.HOOK_EXECUTION_RESPONSE,
                correlationId: request4.correlationId,
                success: false,
                error: error40 instanceof Error ? error40 : new Error(String(error40))
              });
            }
          });
          this.debugLogger.debug("MessageBus initialized with hook subscription");
        } else {
          this.debugLogger.debug("Hook system disabled, skipping initialization");
        }
        this.subagentManager = new SubagentManager(this);
        this.skillManager = new SkillManager(this);
        if (this.getBareMode()) {
          await this.skillManager.refreshCache();
        } else {
          await this.skillManager.startWatching();
        }
        this.debugLogger.debug("Skill manager initialized");
        this.permissionManager = new PermissionManager(this);
        this.permissionManager.initialize();
        this.debugLogger.debug("Permission manager initialized");
        if (this.sessionSubagents.length > 0) {
          this.subagentManager.loadSessionSubagents(this.sessionSubagents);
        }
        if (!this.getBareMode()) {
          await this.extensionManager.refreshCache();
        }
        await this.refreshHierarchicalMemory();
        this.debugLogger.debug("Hierarchical memory loaded");
        this.toolRegistry = await this.createToolRegistry(options2?.sendSdkMcpMessage, this.getBareMode() ? { skipDiscovery: true } : void 0);
        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();
        await this.toolRegistry.warmAll({ strict: true });
        logStartSession(this, new StartSessionEvent(this));
        this.debugLogger.info("Config initialization completed");
      }
      async refreshHierarchicalMemory() {
        const { memoryContent, fileCount, conditionalRules, projectRoot } = await loadServerHierarchicalMemory(this.getWorkingDir(), this.getMemoryDiscoveryDirectories(), this.getFileService(), this.getExtensionContextFilePaths(), this.isTrustedFolder(), this.getImportFormat(), this.contextRuleExcludes, { explicitOnly: this.getBareMode() });
        if (this.getManagedAutoMemoryEnabled()) {
          const managedAutoMemoryIndex = await readAutoMemoryIndex(this.getProjectRoot());
          this.setUserMemory(this.memoryManager.appendToUserMemory(memoryContent, getAutoMemoryRoot(this.getProjectRoot()), managedAutoMemoryIndex));
        } else {
          this.setUserMemory(memoryContent);
        }
        this.setGeminiMdFileCount(fileCount);
        this.conditionalRulesRegistry = new ConditionalRulesRegistry(conditionalRules, projectRoot);
      }
      getMemoryDiscoveryDirectories() {
        if (!this.shouldLoadMemoryFromIncludeDirectories()) {
          return [];
        }
        if (this.getBareMode()) {
          return this.explicitIncludeDirectories;
        }
        return [...this.getWorkspaceContext().getDirectories()];
      }
      getConditionalRulesRegistry() {
        return this.conditionalRulesRegistry;
      }
      /**
       * Update the conditional rules registry. Called after external refresh
       * paths (e.g. /memory refresh or /directory add) that bypass
       * refreshHierarchicalMemory().
       */
      setConditionalRulesRegistry(registry3) {
        this.conditionalRulesRegistry = registry3;
      }
      getContextRuleExcludes() {
        return this.contextRuleExcludes;
      }
      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);
        const messageBus = this.getMessageBus();
        const hooksEnabled = !this.getDisableAllHooks();
        if (hooksEnabled && messageBus) {
          fireNotificationHook(messageBus, `Successfully authenticated with ${authMethod}`, NotificationType.AuthSuccess, "Authentication successful").catch(() => {
          });
        }
      }
      /**
       * 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) {
        try {
          this.chatRecordingService?.finalize();
        } catch {
        }
        this.sessionId = sessionId ?? randomUUID10();
        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();
      }
      onModelChange(listener) {
        this.modelChangeListeners.add(listener);
        return () => {
          this.modelChangeListeners.delete(listener);
        };
      }
      notifyModelChangeListeners() {
        const model = this.getModel();
        for (const listener of this.modelChangeListeners) {
          listener(model);
        }
      }
      /**
       * Returns the fast model if one is configured and valid for the current auth type,
       * otherwise returns undefined. Background agents (memory extraction, dream, /btw)
       * use this as a cheaper alternative to the main session model.
       */
      getFastModel() {
        if (!this.fastModel)
          return void 0;
        const authType = this.contentGeneratorConfig?.authType;
        if (!authType)
          return void 0;
        const available = this.getAvailableModelsForAuthType(authType);
        return available.some((m3) => m3.id === this.fastModel) ? this.fastModel : void 0;
      }
      /**
       * Update the fast model at runtime (e.g., when the user runs `/model --fast <model>`).
       * Pass undefined or an empty string to clear the fast model override.
       */
      setFastModel(model) {
        this.fastModel = model || void 0;
      }
      /**
       * Set model programmatically (e.g., VLM auto-switch, fallback).
       * Delegates to ModelsConfig.
       */
      async setModel(newModel, metadata2) {
        await this.modelsConfig.setModel(newModel, metadata2);
        if (this.contentGeneratorConfig) {
          this.contentGeneratorConfig.model = newModel;
        }
        this.notifyModelChangeListeners();
      }
      /**
       * 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;
          this.contentGeneratorConfig.splitToolMedia = config2.splitToolMedia;
          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"];
          }
          if ("splitToolMedia" in sources) {
            this.contentGeneratorConfigSources["splitToolMedia"] = sources["splitToolMedia"];
          }
          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);
        this.notifyModelChangeListeners();
      }
      getMaxSessionTurns() {
        return this.maxSessionTurns;
      }
      getClearContextOnIdle() {
        return this.clearContextOnIdle;
      }
      getSessionTokenLimit() {
        return this.sessionTokenLimit;
      }
      getEmbeddingModel() {
        return this.embeddingModel;
      }
      getSandbox() {
        return this.sandbox;
      }
      isRestrictiveSandbox() {
        const sandboxConfig = this.getSandbox();
        const seatbeltProfile = process13.env["SEATBELT_PROFILE"];
        return !!sandboxConfig && sandboxConfig.command === "sandbox-exec" && !!seatbeltProfile && seatbeltProfile.startsWith("restrictive-");
      }
      getTargetDir() {
        return this.targetDir;
      }
      getProjectRoot() {
        return this.targetDir;
      }
      getCwd() {
        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 {
          try {
            this.chatRecordingService?.finalize();
            await this.chatRecordingService?.flush();
          } catch {
          }
          this.skillManager?.stopWatching();
          if (this.toolRegistry) {
            await this.toolRegistry.stop();
          }
          this.backgroundTaskRegistry.abortAll();
          this.backgroundShellRegistry.abortAll();
          await this.cleanupArenaRuntime();
        } catch (error40) {
          this.debugLogger.error("Error during Config shutdown:", error40);
        }
      }
      getPromptRegistry() {
        return this.promptRegistry;
      }
      getDebugMode() {
        return this.debugMode;
      }
      getQuestion() {
        return this.question;
      }
      getSystemPrompt() {
        return this.systemPrompt;
      }
      getAppendSystemPrompt() {
        return this.appendSystemPrompt;
      }
      /** @deprecated Use getPermissionsAllow() instead. */
      getCoreTools() {
        if (this.getBareMode()) {
          return DEFAULT_BARE_CORE_TOOLS;
        }
        return this.coreTools;
      }
      /**
       * Returns the merged allow-rules for PermissionManager.
       *
       * This merges all sources so that PermissionManager receives a single,
       * authoritative list:
       *   - settings.permissions.allow  (persistent rules from all scopes)
       *   - allowedTools param  (SDK / argv auto-approve list)
       *
       * Note: coreTools is intentionally excluded here — it has whitelist semantics
       * (only listed tools are registered), not auto-approve semantics. It is
       * handled separately via PermissionManager.coreToolsAllowList.
       *
       * CLI callers (loadCliConfig) already pre-merge argv into permissionsAllow
       * before constructing Config, so those fields will be empty for CLI usage.
       * SDK callers construct Config directly and rely on allowedTools.
       */
      getPermissionsAllow() {
        const base = this.permissionsAllow ?? [];
        const sdkAllow = [...this.allowedTools ?? []];
        if (sdkAllow.length === 0)
          return base.length > 0 ? base : [];
        const merged = [...base];
        for (const t5 of sdkAllow) {
          if (t5 && !merged.includes(t5))
            merged.push(t5);
        }
        return merged;
      }
      getPermissionsAsk() {
        return this.permissionsAsk;
      }
      /**
       * Returns the merged deny-rules for PermissionManager.
       *
       * Merges:
       *   - settings.permissions.deny  (persistent rules from all scopes)
       *   - excludeTools param  (SDK / argv blocklist)
       *
       * CLI callers pre-merge argv.excludeTools into permissionsDeny.
       */
      getPermissionsDeny() {
        const base = this.permissionsDeny ?? [];
        const sdkDeny = this.excludeTools ?? [];
        if (sdkDeny.length === 0)
          return base.length > 0 ? base : [];
        const merged = [...base];
        for (const t5 of sdkDeny) {
          if (t5 && !merged.includes(t5))
            merged.push(t5);
        }
        return merged;
      }
      getToolDiscoveryCommand() {
        return this.toolDiscoveryCommand;
      }
      /**
       * Returns the pre-merged list of slash command names that should be hidden
       * from the CLI surface. Callers should treat this as a case-insensitive
       * denylist; `CommandService.create` handles the normalization.
       */
      getDisabledSlashCommands() {
        return this.disabledSlashCommands;
      }
      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)));
        }
        return mcpServers;
      }
      getExcludedMcpServers() {
        return this.excludedMcpServers;
      }
      setExcludedMcpServers(excluded) {
        this.excludedMcpServers = excluded;
      }
      isMcpServerDisabled(serverName) {
        return this.excludedMcpServers?.includes(serverName) ?? false;
      }
      addMcpServers(servers) {
        if (this.initialized) {
          throw new Error("Cannot modify mcpServers after initialization");
        }
        this.mcpServers = { ...this.mcpServers, ...servers };
      }
      isLspEnabled() {
        return this.lspEnabled && !this.getBareMode();
      }
      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;
      }
      getArenaManager() {
        return this.arenaManager;
      }
      setArenaManager(manager) {
        this.arenaManager = manager;
        this.arenaManagerChangeCallback?.(manager);
      }
      /**
       * Register a callback invoked whenever the arena manager changes.
       * Pass `null` to unsubscribe. Only one subscriber is supported.
       */
      onArenaManagerChange(cb) {
        this.arenaManagerChangeCallback = cb;
      }
      getArenaAgentClient() {
        return this.arenaAgentClient;
      }
      getAgentsSettings() {
        return this.agentsSettings;
      }
      /**
       * Clean up Arena runtime. When `force` is true (e.g., /arena select --discard),
       * always removes worktrees regardless of preserveArtifacts.
       */
      async cleanupArenaRuntime(force) {
        const manager = this.arenaManager;
        if (!manager) {
          return;
        }
        if (!force && this.agentsSettings.arena?.preserveArtifacts) {
          await manager.cleanupRuntime();
        } else {
          await manager.cleanup();
        }
        this.setArenaManager(null);
      }
      getApprovalMode() {
        return this.approvalMode;
      }
      /**
       * Returns the approval mode that was active before entering plan mode.
       * Falls back to DEFAULT if no pre-plan mode was recorded.
       */
      getPrePlanMode() {
        return this.prePlanMode ?? ApprovalMode.DEFAULT;
      }
      setApprovalMode(mode) {
        if (!this.isTrustedFolder() && mode !== ApprovalMode.DEFAULT && mode !== ApprovalMode.PLAN) {
          throw new Error("Cannot enable privileged approval modes in an untrusted folder.");
        }
        if (mode === ApprovalMode.PLAN && this.approvalMode !== ApprovalMode.PLAN) {
          this.prePlanMode = this.approvalMode;
        } else if (mode !== ApprovalMode.PLAN && this.approvalMode === ApprovalMode.PLAN) {
          this.prePlanMode = void 0;
        }
        this.approvalMode = mode;
      }
      /**
       * Returns the file path for this session's plan file.
       */
      getPlanFilePath() {
        return Storage.getPlanFilePath(this.sessionId);
      }
      /**
       * Saves a plan to disk for the current session.
       */
      savePlan(plan) {
        const filePath = this.getPlanFilePath();
        const dir = path83.dirname(filePath);
        fs88.mkdirSync(dir, { recursive: true });
        fs88.writeFileSync(filePath, plan, "utf-8");
      }
      /**
       * Loads the plan for the current session, or returns undefined if none exists.
       */
      loadPlan() {
        const filePath = this.getPlanFilePath();
        try {
          return fs88.readFileSync(filePath, "utf-8");
        } catch (error40) {
          if (typeof error40 === "object" && error40 !== null && "code" in error40 && error40.code === "ENOENT") {
            return void 0;
          }
          throw error40;
        }
      }
      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;
      }
      getCronScheduler() {
        if (!this.cronScheduler) {
          this.cronScheduler = new CronScheduler();
        }
        return this.cronScheduler;
      }
      isCronEnabled() {
        if (process13.env["QWEN_CODE_ENABLE_CRON"] === "1")
          return true;
        return this.cronEnabled;
      }
      /**
       * Whether the turn loop should fire a fast-model call after each tool batch
       * to emit a `tool_use_summary` message. Mirrors Claude Code's
       * `CLAUDE_CODE_EMIT_TOOL_USE_SUMMARIES` gate, but defaults to on so the
       * compact-mode UI benefits without configuration.
       *
       * Env overrides (either direction): `QWEN_CODE_EMIT_TOOL_USE_SUMMARIES=0`
       * to force off, `=1` to force on.
       */
      getEmitToolUseSummaries() {
        const env6 = process13.env["QWEN_CODE_EMIT_TOOL_USE_SUMMARIES"];
        if (env6 === "0" || env6 === "false")
          return false;
        if (env6 === "1" || env6 === "true")
          return true;
        return this.emitToolUseSummaries;
      }
      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 normalizeProxyUrl(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;
      }
      /**
       * Get the hook system instance if hooks are enabled.
       * Returns undefined if hooks are not enabled.
       */
      getHookSystem() {
        return this.hookSystem;
      }
      /**
       * Fast-path check: returns true only when hooks are enabled AND there are
       * registered hooks for the given event name.  Callers can use this to skip
       * expensive MessageBus round-trips when no hooks are configured.
       */
      hasHooksForEvent(eventName) {
        return this.hookSystem?.hasHooksForEvent(eventName) ?? false;
      }
      /**
       * Check if all hooks are disabled.
       */
      getDisableAllHooks() {
        return this.disableAllHooks || this.getBareMode();
      }
      getManagedAutoMemoryEnabled() {
        return this.enableManagedAutoMemory && !this.getBareMode();
      }
      getManagedAutoDreamEnabled() {
        return this.enableManagedAutoDream && !this.getBareMode();
      }
      /**
       * Return the MemoryManager instance created for this Config.
       * Use this to share background-task state (registry, drainer) with memory
       * module runtimes (extract, dream) instead of relying on module-level
       * globals.
       */
      getMemoryManager() {
        return this.memoryManager;
      }
      /**
       * Get the message bus instance.
       * Returns undefined if not set.
       */
      getMessageBus() {
        return this.messageBus;
      }
      /**
       * Set the message bus instance.
       * This is called by the CLI layer to inject the MessageBus.
       */
      setMessageBus(messageBus) {
        this.messageBus = messageBus;
      }
      /**
       * Get project-level hooks configuration.
       * Returns hooks from workspace settings, only in trusted folders.
       * Used by HookRegistry to load project-specific hooks with proper source attribution.
       */
      getProjectHooks() {
        if (this.getBareMode()) {
          return void 0;
        }
        if (!this.isTrustedFolder()) {
          return void 0;
        }
        const hooks = this.projectHooks ?? this.hooks;
        return hooks;
      }
      /**
       * Get user-level hooks configuration.
       * Returns hooks from user settings, always available regardless of folder trust.
       * Used by HookRegistry to load user-specific hooks with proper source attribution.
       */
      getUserHooks() {
        if (this.getBareMode()) {
          return void 0;
        }
        const hooks = this.userHooks ?? this.hooks;
        return hooks;
      }
      getExtensions() {
        const extensions = this.extensionManager.getLoadedExtensions();
        if (this.overrideExtensions) {
          const overrideExtensionNames = new Set(this.overrideExtensions.map((name4) => name4.toLowerCase()));
          return extensions.filter((e4) => overrideExtensionNames.has(e4.name.toLowerCase()));
        } else {
          return extensions;
        }
      }
      getExplicitExtensionNames() {
        return (this.overrideExtensions ?? []).filter((name4) => name4.trim() !== "" && name4.toLowerCase() !== "none");
      }
      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();
      }
      getIdeMode() {
        return this.ideMode;
      }
      getFolderTrustFeature() {
        return this.folderTrustFeature;
      }
      /**
       * Returns 'true' if the workspace is considered "trusted".
       * 'false' for untrusted.
       */
      getFolderTrust() {
        return this.folderTrust;
      }
      /**
       * Returns the whitelist of allowed HTTP hook URL patterns.
       * If empty, all URLs are allowed (subject to SSRF protection).
       */
      getAllowedHttpHookUrls() {
        return this.getBareMode() ? [] : this.allowedHttpHookUrls;
      }
      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 file descriptor for dual output JSON event stream.
       * When set, the TUI mode will also emit structured JSON events to this fd.
       */
      getJsonFd() {
        return this.jsonFd;
      }
      /**
       * Get the file path for dual output JSON event stream.
       * When set, the TUI mode will also emit structured JSON events to this file.
       */
      getJsonFile() {
        return this.jsonFile;
      }
      /**
       * Get the file path for remote input commands (bidirectional sync).
       * When set, the TUI mode will watch this file for JSONL commands written
       * by an external process and submit them as user messages.
       */
      getInputFile() {
        return this.inputFile;
      }
      /**
       * 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;
      }
      getBareMode() {
        return this.bareMode;
      }
      getTruncateToolOutputThreshold() {
        if (this.truncateToolOutputThreshold <= 0) {
          return Number.POSITIVE_INFINITY;
        }
        return this.truncateToolOutputThreshold;
      }
      getTruncateToolOutputLines() {
        if (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;
      }
      /**
       * Returns the transcript file path for the current session.
       * This is the path to the JSONL file where the conversation is recorded.
       * Returns empty string if chat recording is disabled.
       */
      getTranscriptPath() {
        if (!this.chatRecordingEnabled) {
          return "";
        }
        const projectDir = this.storage.getProjectDir();
        const sessionId = this.getSessionId();
        const safeFilename = `${sessionId}.jsonl`;
        return path83.join(projectDir, "chats", safeFilename);
      }
      /**
       * 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;
      }
      getBackgroundTaskRegistry() {
        return this.backgroundTaskRegistry;
      }
      getBackgroundShellRegistry() {
        return this.backgroundShellRegistry;
      }
      /**
       * Whether interactive permission prompts should be auto-denied.
       * True for background agents that have no UI to show prompts.
       * PermissionRequest hooks still run and can override the denial.
       */
      getShouldAvoidPermissionPrompts() {
        return false;
      }
      getSkillManager() {
        return this.skillManager;
      }
      /**
       * Registers a provider that returns model-invocable commands (e.g., bundled
       * skills, user/project file commands, MCP prompts). Called by the CLI's
       * CommandService after initialisation so that SkillTool can merge these into
       * its tool description.
       */
      setModelInvocableCommandsProvider(provider) {
        this.modelInvocableCommandsProvider = provider;
      }
      /**
       * Returns the registered model-invocable commands provider, or null if none
       * has been registered (e.g., in SDK mode).
       */
      getModelInvocableCommandsProvider() {
        return this.modelInvocableCommandsProvider;
      }
      /**
       * Registers an executor that can invoke a model-invocable command by name
       * (e.g., MCP prompts). Returns the prompt content as a string, or null if
       * the command cannot be found or executed. Called by the CLI layer.
       */
      setModelInvocableCommandsExecutor(executor) {
        this.modelInvocableCommandsExecutor = executor;
      }
      /**
       * Returns the registered model-invocable commands executor, or null if none
       * has been registered (e.g., in SDK mode).
       */
      getModelInvocableCommandsExecutor() {
        return this.modelInvocableCommandsExecutor;
      }
      getPermissionManager() {
        return this.permissionManager;
      }
      /**
       * Returns the callback for persisting permission rules to settings files.
       * Returns undefined if no callback was provided (e.g. SDK mode).
       */
      getOnPersistPermissionRule() {
        return this.onPersistPermissionRuleCallback;
      }
      async createToolRegistry(sendSdkMcpMessage, options2) {
        const registry3 = new ToolRegistry(this, this.eventEmitter, sendSdkMcpMessage);
        const registerLazy = /* @__PURE__ */ __name(async (toolName, factory2) => {
          let pmEnabled = true;
          try {
            pmEnabled = this.permissionManager ? await this.permissionManager.isToolEnabled(toolName) : true;
          } catch (error40) {
            this.debugLogger.warn(`Failed to check permissions for tool "${toolName}", skipping registration:`, error40);
            return;
          }
          if (pmEnabled) {
            registry3.registerFactory(toolName, factory2);
          }
        }, "registerLazy");
        if (this.getBareMode()) {
          await registerLazy(ToolNames.READ_FILE, async () => {
            const { ReadFileTool: ReadFileTool2 } = await Promise.resolve().then(() => (init_read_file(), read_file_exports));
            return new ReadFileTool2(this);
          });
          await registerLazy(ToolNames.EDIT, async () => {
            const { EditTool: EditTool2 } = await Promise.resolve().then(() => (init_edit(), edit_exports));
            return new EditTool2(this);
          });
          await registerLazy(ToolNames.SHELL, async () => {
            const { ShellTool: ShellTool2 } = await Promise.resolve().then(() => (init_shell(), shell_exports));
            return new ShellTool2(this);
          });
          this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry3.getAllToolNames())} (${registry3.getAllToolNames().length} tools)`);
          return registry3;
        }
        await registerLazy(ToolNames.AGENT, async () => {
          const { AgentTool: AgentTool2 } = await Promise.resolve().then(() => (init_agent(), agent_exports));
          return new AgentTool2(this);
        });
        await registerLazy(ToolNames.TASK_STOP, async () => {
          const { TaskStopTool: TaskStopTool2 } = await Promise.resolve().then(() => (init_task_stop(), task_stop_exports));
          return new TaskStopTool2(this);
        });
        await registerLazy(ToolNames.SEND_MESSAGE, async () => {
          const { SendMessageTool: SendMessageTool2 } = await Promise.resolve().then(() => (init_send_message(), send_message_exports));
          return new SendMessageTool2(this);
        });
        await registerLazy(ToolNames.SKILL, async () => {
          const { SkillTool: SkillTool2 } = await Promise.resolve().then(() => (init_skill(), skill_exports));
          return new SkillTool2(this);
        });
        await registerLazy(ToolNames.LS, async () => {
          const { LSTool: LSTool2 } = await Promise.resolve().then(() => (init_ls(), ls_exports));
          return new LSTool2(this);
        });
        await registerLazy(ToolNames.READ_FILE, async () => {
          const { ReadFileTool: ReadFileTool2 } = await Promise.resolve().then(() => (init_read_file(), read_file_exports));
          return new ReadFileTool2(this);
        });
        if (this.getUseRipgrep()) {
          let useRipgrep = false;
          let errorString = void 0;
          try {
            useRipgrep = await canUseRipgrep(this.getUseBuiltinRipgrep());
          } catch (error40) {
            errorString = getErrorMessage(error40);
          }
          if (useRipgrep) {
            await registerLazy(ToolNames.GREP, async () => {
              const { RipGrepTool: RipGrepTool2 } = await Promise.resolve().then(() => (init_ripGrep(), ripGrep_exports));
              return new RipGrepTool2(this);
            });
          } else {
            logRipgrepFallback(this, new RipgrepFallbackEvent(this.getUseRipgrep(), this.getUseBuiltinRipgrep(), errorString || "ripgrep is not available"));
            await registerLazy(ToolNames.GREP, async () => {
              const { GrepTool: GrepTool2 } = await Promise.resolve().then(() => (init_grep2(), grep_exports));
              return new GrepTool2(this);
            });
          }
        } else {
          await registerLazy(ToolNames.GREP, async () => {
            const { GrepTool: GrepTool2 } = await Promise.resolve().then(() => (init_grep2(), grep_exports));
            return new GrepTool2(this);
          });
        }
        await registerLazy(ToolNames.GLOB, async () => {
          const { GlobTool: GlobTool2 } = await Promise.resolve().then(() => (init_glob2(), glob_exports));
          return new GlobTool2(this);
        });
        await registerLazy(ToolNames.EDIT, async () => {
          const { EditTool: EditTool2 } = await Promise.resolve().then(() => (init_edit(), edit_exports));
          return new EditTool2(this);
        });
        await registerLazy(ToolNames.WRITE_FILE, async () => {
          const { WriteFileTool: WriteFileTool2 } = await Promise.resolve().then(() => (init_write_file(), write_file_exports));
          return new WriteFileTool2(this);
        });
        await registerLazy(ToolNames.SHELL, async () => {
          const { ShellTool: ShellTool2 } = await Promise.resolve().then(() => (init_shell(), shell_exports));
          return new ShellTool2(this);
        });
        await registerLazy(ToolNames.TODO_WRITE, async () => {
          const { TodoWriteTool: TodoWriteTool2 } = await Promise.resolve().then(() => (init_todoWrite(), todoWrite_exports));
          return new TodoWriteTool2(this);
        });
        await registerLazy(ToolNames.ASK_USER_QUESTION, async () => {
          const { AskUserQuestionTool: AskUserQuestionTool2 } = await Promise.resolve().then(() => (init_askUserQuestion(), askUserQuestion_exports));
          return new AskUserQuestionTool2(this);
        });
        if (!this.sdkMode) {
          await registerLazy(ToolNames.EXIT_PLAN_MODE, async () => {
            const { ExitPlanModeTool: ExitPlanModeTool2 } = await Promise.resolve().then(() => (init_exitPlanMode(), exitPlanMode_exports));
            return new ExitPlanModeTool2(this);
          });
        }
        await registerLazy(ToolNames.WEB_FETCH, async () => {
          const { WebFetchTool: WebFetchTool2 } = await Promise.resolve().then(() => (init_web_fetch(), web_fetch_exports));
          return new WebFetchTool2(this);
        });
        if (this.isLspEnabled() && this.getLspClient()) {
          await registerLazy(ToolNames.LSP, async () => {
            const { LspTool: LspTool2 } = await Promise.resolve().then(() => (init_lsp(), lsp_exports));
            return new LspTool2(this);
          });
        }
        if (this.isCronEnabled()) {
          await registerLazy(ToolNames.CRON_CREATE, async () => {
            const { CronCreateTool: CronCreateTool2 } = await Promise.resolve().then(() => (init_cron_create(), cron_create_exports));
            return new CronCreateTool2(this);
          });
          await registerLazy(ToolNames.CRON_LIST, async () => {
            const { CronListTool: CronListTool2 } = await Promise.resolve().then(() => (init_cron_list(), cron_list_exports));
            return new CronListTool2(this);
          });
          await registerLazy(ToolNames.CRON_DELETE, async () => {
            const { CronDeleteTool: CronDeleteTool2 } = await Promise.resolve().then(() => (init_cron_delete(), cron_delete_exports));
            return new CronDeleteTool2(this);
          });
        }
        if (!options2?.skipDiscovery) {
          await registry3.discoverAllTools();
        }
        this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(registry3.getAllToolNames())} (${registry3.getAllToolNames().length} tools)`);
        return registry3;
      }
    };
  }
});

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

// packages/core/dist/src/permissions/index.js
var init_permissions2 = __esm({
  "packages/core/dist/src/permissions/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_types18();
    init_rule_parser();
    init_permission_manager();
    init_shell_semantics();
  }
});

// packages/core/dist/src/constants/codingPlan.js
import { createHash as createHash6 } from "node:crypto";
function computeCodingPlanVersion(template) {
  const templateString2 = JSON.stringify(template);
  return createHash6("sha256").update(templateString2).digest("hex");
}
function generateCodingPlanTemplate(region) {
  if (region === CodingPlanRegion.CHINA) {
    return [
      {
        id: "qwen3.5-plus",
        name: "[ModelStudio 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.6-plus",
        name: "[ModelStudio Coding Plan] qwen3.6-plus",
        description: "Currently available to Pro subscribers only.",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY,
        generationConfig: {
          extra_body: { enable_thinking: true },
          contextWindowSize: 1e6
        }
      },
      {
        id: "glm-5",
        name: "[ModelStudio 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: "kimi-k2.5",
        name: "[ModelStudio 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
        }
      },
      {
        id: "MiniMax-M2.5",
        name: "[ModelStudio Coding Plan] MiniMax-M2.5",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY,
        generationConfig: {
          extra_body: { enable_thinking: true },
          contextWindowSize: 196608
        }
      },
      {
        id: "qwen3-coder-plus",
        name: "[ModelStudio 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: "[ModelStudio 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: "[ModelStudio 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: "[ModelStudio 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
        }
      }
    ];
  }
  return [
    {
      id: "qwen3.5-plus",
      name: "[ModelStudio 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.6-plus",
      name: "[ModelStudio Coding Plan for Global/Intl] qwen3.6-plus",
      description: "Currently available to Pro subscribers only.",
      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: "[ModelStudio 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: "[ModelStudio 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: "[ModelStudio 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: "[ModelStudio 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: "[ModelStudio 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: "[ModelStudio 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: 196608
      }
    },
    {
      id: "kimi-k2.5",
      name: "[ModelStudio 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
      }
    }
  ];
}
function getCodingPlanConfig(region) {
  const template = generateCodingPlanTemplate(region);
  const baseUrl = region === CodingPlanRegion.CHINA ? "https://coding.dashscope.aliyuncs.com/v1" : "https://coding-intl.dashscope.aliyuncs.com/v1";
  return {
    template,
    baseUrl,
    version: computeCodingPlanVersion(template)
  };
}
function getCodingPlanBaseUrls() {
  return [
    "https://coding.dashscope.aliyuncs.com/v1",
    "https://coding-intl.dashscope.aliyuncs.com/v1"
  ];
}
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 CodingPlanRegion.CHINA;
  }
  if (baseUrl === "https://coding-intl.dashscope.aliyuncs.com/v1") {
    return CodingPlanRegion.GLOBAL;
  }
  return false;
}
function getRegionFromBaseUrl(baseUrl) {
  if (!baseUrl)
    return null;
  if (baseUrl === "https://coding.dashscope.aliyuncs.com/v1") {
    return CodingPlanRegion.CHINA;
  }
  if (baseUrl === "https://coding-intl.dashscope.aliyuncs.com/v1") {
    return CodingPlanRegion.GLOBAL;
  }
  return null;
}
var CodingPlanRegion, CODING_PLAN_ENV_KEY;
var init_codingPlan = __esm({
  "packages/core/dist/src/constants/codingPlan.js"() {
    "use strict";
    init_esbuild_shims();
    (function(CodingPlanRegion3) {
      CodingPlanRegion3["CHINA"] = "china";
      CodingPlanRegion3["GLOBAL"] = "global";
    })(CodingPlanRegion || (CodingPlanRegion = {}));
    CODING_PLAN_ENV_KEY = "BAILIAN_CODING_PLAN_API_KEY";
    __name(computeCodingPlanVersion, "computeCodingPlanVersion");
    __name(generateCodingPlanTemplate, "generateCodingPlanTemplate");
    __name(getCodingPlanConfig, "getCodingPlanConfig");
    __name(getCodingPlanBaseUrls, "getCodingPlanBaseUrls");
    __name(isCodingPlanConfig, "isCodingPlanConfig");
    __name(getRegionFromBaseUrl, "getRegionFromBaseUrl");
  }
});

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

// packages/core/dist/src/core/geminiRequest.js
function partListUnionToString(value) {
  return partToString(value, { verbose: true });
}
var init_geminiRequest = __esm({
  "packages/core/dist/src/core/geminiRequest.js"() {
    "use strict";
    init_esbuild_shims();
    init_node();
    init_partUtils();
    __name(partListUnionToString, "partListUnionToString");
  }
});

// packages/core/dist/src/core/insightProtocol.js
function encodeInsightProgressMessage(stage, progress, detail) {
  const payload = {
    insight_progress: { stage, progress, detail }
  };
  return JSON.stringify(payload);
}
function encodeInsightReadyMessage(path150) {
  const payload = {
    insight_ready: { path: path150 }
  };
  return JSON.stringify(payload);
}
function parseInsightMessage(message) {
  try {
    const parsed = JSON.parse(message);
    if (parsed.insight_progress) {
      const { stage, progress, detail } = parsed.insight_progress;
      if (typeof stage === "string" && typeof progress === "number") {
        return {
          type: "insight_progress",
          stage,
          progress,
          detail: typeof detail === "string" ? detail : void 0
        };
      }
    }
    if (parsed.insight_ready) {
      const { path: path150 } = parsed.insight_ready;
      if (typeof path150 === "string") {
        return { type: "insight_ready", path: path150 };
      }
    }
  } catch {
    return null;
  }
  return null;
}
var init_insightProtocol = __esm({
  "packages/core/dist/src/core/insightProtocol.js"() {
    "use strict";
    init_esbuild_shims();
    __name(encodeInsightProgressMessage, "encodeInsightProgressMessage");
    __name(encodeInsightReadyMessage, "encodeInsightReadyMessage");
    __name(parseInsightMessage, "parseInsightMessage");
  }
});

// packages/core/dist/src/core/logger.js
import path84 from "node:path";
import { promises as fs89 } from "node:fs";
function encodeTagName(str2) {
  return encodeURIComponent(str2);
}
function decodeTagName(str2) {
  try {
    return decodeURIComponent(str2);
  } catch (_e2) {
    return str2.replace(/%([0-9A-F]{2})/g, (_2, hex) => String.fromCharCode(parseInt(hex, 16)));
  }
}
var LOG_FILE_NAME, MessageSenderType, Logger;
var init_logger = __esm({
  "packages/core/dist/src/core/logger.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    LOG_FILE_NAME = "logs.json";
    (function(MessageSenderType2) {
      MessageSenderType2["USER"] = "user";
      MessageSenderType2["MODEL_SWITCH"] = "model_switch";
    })(MessageSenderType || (MessageSenderType = {}));
    __name(encodeTagName, "encodeTagName");
    __name(decodeTagName, "decodeTagName");
    Logger = class {
      static {
        __name(this, "Logger");
      }
      storage;
      qwenDir;
      logFilePath;
      sessionId;
      messageId = 0;
      // Instance-specific counter for the next messageId
      initialized = false;
      logs = [];
      // In-memory cache, ideally reflects the last known state of the file
      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 fs89.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 (error40) {
          const nodeError = error40;
          if (nodeError.code === "ENOENT") {
            return [];
          }
          if (error40 instanceof SyntaxError) {
            this.debugLogger.debug(`Invalid JSON in log file ${this.logFilePath}. Backing up and starting fresh.`, error40);
            await this._backupCorruptedLogFile("invalid_json");
            return [];
          }
          this.debugLogger.debug(`Failed to read or parse log file ${this.logFilePath}:`, error40);
          throw error40;
        }
      }
      async _backupCorruptedLogFile(reason) {
        if (!this.logFilePath)
          return;
        const backupPath = `${this.logFilePath}.${reason}.${Date.now()}.bak`;
        try {
          await fs89.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 = path84.join(this.qwenDir, LOG_FILE_NAME);
        try {
          await fs89.mkdir(this.qwenDir, { recursive: true });
          let fileExisted = true;
          try {
            await fs89.access(this.logFilePath);
          } catch (_e2) {
            fileExisted = false;
          }
          this.logs = await this._readLogFile();
          if (!fileExisted && this.logs.length === 0) {
            await fs89.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 (err2) {
          this.debugLogger.error("Failed to initialize logger:", err2);
          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 fs89.writeFile(this.logFilePath, JSON.stringify(currentLogsOnDisk, null, 2), "utf-8");
          this.logs = currentLogsOnDisk;
          return entryToAppend;
        } catch (error40) {
          this.debugLogger.debug("Error writing to log file:", error40);
          throw error40;
        }
      }
      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 path84.join(this.qwenDir, `checkpoint-${encodedTag}.json`);
      }
      async _getCheckpointPath(tag2) {
        const newPath = this._checkpointPath(tag2);
        try {
          await fs89.access(newPath);
          return newPath;
        } catch (error40) {
          const nodeError = error40;
          if (nodeError.code !== "ENOENT") {
            throw error40;
          }
        }
        const oldPath = path84.join(this.qwenDir, `checkpoint-${tag2}.json`);
        try {
          await fs89.access(oldPath);
          return oldPath;
        } catch (error40) {
          const nodeError = error40;
          if (nodeError.code !== "ENOENT") {
            throw error40;
          }
        }
        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 path150 = this._checkpointPath(tag2);
        try {
          await fs89.writeFile(path150, JSON.stringify(conversation, null, 2), "utf-8");
        } catch (error40) {
          this.debugLogger.error("Error writing to checkpoint file:", error40);
        }
      }
      async loadCheckpoint(tag2) {
        if (!this.initialized) {
          this.debugLogger.error("Logger not initialized or checkpoint file path not set. Cannot load checkpoint.");
          return [];
        }
        const path150 = await this._getCheckpointPath(tag2);
        try {
          const fileContent = await fs89.readFile(path150, "utf-8");
          const parsedContent = JSON.parse(fileContent);
          if (!Array.isArray(parsedContent)) {
            this.debugLogger.warn(`Checkpoint file at ${path150} is not a valid JSON array. Returning empty checkpoint.`);
            return [];
          }
          return parsedContent;
        } catch (error40) {
          const nodeError = error40;
          if (nodeError.code === "ENOENT") {
            return [];
          }
          this.debugLogger.error(`Failed to read or parse checkpoint file ${path150}:`, error40);
          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 fs89.unlink(newPath);
          deletedSomething = true;
        } catch (error40) {
          const nodeError = error40;
          if (nodeError.code !== "ENOENT") {
            this.debugLogger.error(`Failed to delete checkpoint file ${newPath}:`, error40);
            throw error40;
          }
        }
        const oldPath = path84.join(this.qwenDir, `checkpoint-${tag2}.json`);
        if (newPath !== oldPath) {
          try {
            await fs89.unlink(oldPath);
            deletedSomething = true;
          } catch (error40) {
            const nodeError = error40;
            if (nodeError.code !== "ENOENT") {
              this.debugLogger.error(`Failed to delete checkpoint file ${oldPath}:`, error40);
              throw error40;
            }
          }
        }
        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 fs89.access(filePath);
          return true;
        } catch (error40) {
          const nodeError = error40;
          if (nodeError.code === "ENOENT") {
            return false;
          }
          this.debugLogger.error(`Failed to check checkpoint existence for ${filePath ?? `path for tag "${tag2}"`}:`, error40);
          throw error40;
        }
      }
      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((resolve42, reject) => {
    new CoreToolScheduler({
      config: config2,
      chatRecordingService: config2.getChatRecordingService(),
      outputUpdateHandler: options2.outputUpdateHandler,
      onAllToolCallsComplete: /* @__PURE__ */ __name(async (completedToolCalls) => {
        if (options2.onAllToolCallsComplete) {
          await options2.onAllToolCallsComplete(completedToolCalls);
        }
        resolve42(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/dist/src/services/sessionRecap.js
async function generateSessionRecap(config2, abortSignal) {
  try {
    const geminiClient = config2.getGeminiClient();
    if (!geminiClient)
      return null;
    const fullHistory = geminiClient.getChat().getHistory();
    if (fullHistory.length < 2)
      return null;
    const dialog = filterToDialog2(fullHistory);
    const recentHistory = takeRecentDialog2(dialog, RECENT_MESSAGE_WINDOW2);
    if (recentHistory.length === 0)
      return null;
    const model = config2.getFastModel() ?? config2.getModel();
    const response = await geminiClient.generateContent([
      ...recentHistory,
      { role: "user", parts: [{ text: RECAP_USER_PROMPT }] }
    ], {
      systemInstruction: RECAP_SYSTEM_PROMPT,
      tools: [],
      maxOutputTokens: 300,
      temperature: 0.3
    }, abortSignal, model);
    if (abortSignal.aborted)
      return null;
    const raw2 = (response.candidates?.[0]?.content?.parts ?? []).map((part) => part.text).filter((t5) => typeof t5 === "string").join("").trim();
    if (!raw2)
      return null;
    const text = extractRecap(raw2);
    if (!text)
      return null;
    return { text, modelUsed: model };
  } catch (err2) {
    debugLogger97.warn(`Recap generation failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
    return null;
  }
}
function extractRecap(raw2) {
  const tagged = RECAP_TAG_RE.exec(raw2);
  if (tagged?.[1])
    return tagged[1].trim();
  const openIdx = raw2.toLowerCase().indexOf(RECAP_OPEN_TAG);
  if (openIdx === -1)
    return "";
  return raw2.slice(openIdx + RECAP_OPEN_TAG.length).trim();
}
function filterToDialog2(history) {
  const out2 = [];
  for (const msg of history) {
    if (msg.role !== "user" && msg.role !== "model")
      continue;
    const textParts = (msg.parts ?? []).filter((part) => typeof part?.text === "string" && part.text.trim() !== "" && !part.thought && !part.thoughtSignature);
    if (textParts.length === 0)
      continue;
    out2.push({ role: msg.role, parts: textParts });
  }
  return out2;
}
function takeRecentDialog2(history, windowSize) {
  if (history.length <= windowSize)
    return history;
  let start2 = history.length - windowSize;
  while (start2 < history.length && history[start2]?.role !== "user") {
    start2++;
  }
  return history.slice(start2);
}
var debugLogger97, RECENT_MESSAGE_WINDOW2, RECAP_SYSTEM_PROMPT, RECAP_USER_PROMPT, RECAP_OPEN_TAG, RECAP_TAG_RE;
var init_sessionRecap = __esm({
  "packages/core/dist/src/services/sessionRecap.js"() {
    "use strict";
    init_esbuild_shims();
    init_debugLogger();
    debugLogger97 = createDebugLogger("SESSION_RECAP");
    RECENT_MESSAGE_WINDOW2 = 30;
    RECAP_SYSTEM_PROMPT = `You generate session recaps for a programming assistant CLI.

The user stepped away and is coming back. Recap in under 40 words, 1-2 plain sentences, no markdown. Lead with the overall goal and current task, then the one next action. Skip root-cause narrative, fix internals, secondary to-dos, and em-dash tangents.

Match the dominant language of the conversation (English or Chinese). For Chinese, treat the budget as roughly 80 characters total.

Output format \u2014 strict:
- Wrap your recap in <recap>...</recap> tags.
- Put NOTHING outside the tags. No preamble, no reasoning, no closing remarks.

Example:
<recap>Debugging the auth retry race condition. Next: add deterministic timing to the integration test.</recap>`;
    RECAP_USER_PROMPT = "Generate the recap now. Wrap it in <recap>...</recap>. Nothing outside the tags.";
    RECAP_OPEN_TAG = "<recap>";
    RECAP_TAG_RE = /<recap>([\s\S]*?)<\/recap>/i;
    __name(generateSessionRecap, "generateSessionRecap");
    __name(extractRecap, "extractRecap");
    __name(filterToDialog2, "filterToDialog");
    __name(takeRecentDialog2, "takeRecentDialog");
  }
});

// packages/core/dist/src/services/toolUseSummary.js
import { randomUUID as randomUUID11 } from "node:crypto";
function createToolUseSummaryMessage(summary, precedingToolUseIds) {
  return {
    type: "tool_use_summary",
    summary,
    precedingToolUseIds,
    uuid: randomUUID11(),
    timestamp: (/* @__PURE__ */ new Date()).toISOString()
  };
}
async function generateToolUseSummary(params) {
  const { config: config2, tools, signal, lastAssistantText } = params;
  if (tools.length === 0) {
    return null;
  }
  const model = params.model ?? config2.getFastModel();
  if (!model) {
    debugLogger98.debug("No fast model configured \u2014 skipping summary generation");
    return null;
  }
  if (signal.aborted) {
    return null;
  }
  try {
    const toolSummaries = tools.map((tool) => {
      const inputStr = truncateJson(tool.input, INPUT_TRUNCATE_LENGTH);
      const outputStr = truncateJson(tool.output, INPUT_TRUNCATE_LENGTH);
      return `Tool: ${tool.name}
Input: ${inputStr}
Output: ${outputStr}`;
    }).join("\n\n");
    const contextPrefix = lastAssistantText ? `User's intent (from assistant's last message): ${lastAssistantText.slice(0, LAST_ASSISTANT_TEXT_LENGTH)}

` : "";
    const userPrompt = `${contextPrefix}Tools completed:

${toolSummaries}

Label:`;
    const geminiClient = config2.getGeminiClient();
    if (!geminiClient) {
      debugLogger98.debug("No gemini client available \u2014 skipping");
      return null;
    }
    const response = await geminiClient.generateContent([{ role: "user", parts: [{ text: userPrompt }] }], {
      systemInstruction: TOOL_USE_SUMMARY_SYSTEM_PROMPT,
      tools: [],
      maxOutputTokens: 60,
      temperature: 0.3
    }, signal, model, "tool_use_summary_generation");
    if (signal.aborted)
      return null;
    const raw2 = getResponseText(response)?.trim();
    if (!raw2) {
      debugLogger98.debug("Summary generation returned empty result");
      return null;
    }
    const cleaned = cleanSummary(raw2);
    if (!cleaned) {
      debugLogger98.debug(`Summary cleaned to empty: raw="${raw2}"`);
      return null;
    }
    debugLogger98.debug(`Summary generated: "${cleaned}"`);
    return cleaned;
  } catch (err2) {
    if (signal.aborted)
      return null;
    debugLogger98.warn(`Summary generation failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
    return null;
  }
}
function truncateJson(value, maxLength) {
  try {
    const pre = preTruncate(value, maxLength);
    const str2 = JSON.stringify(pre);
    if (str2 == null)
      return "[undefined]";
    return str2.length <= maxLength ? str2 : str2.slice(0, maxLength - 3) + "...";
  } catch {
    return "[unable to serialize]";
  }
}
function preTruncate(value, maxLength, depth = 0) {
  if (value === null || value === void 0)
    return value;
  if (typeof value === "string") {
    return value.length > maxLength ? value.slice(0, maxLength) : value;
  }
  if (depth >= 4)
    return value;
  if (Array.isArray(value)) {
    return value.map((v2) => preTruncate(v2, maxLength, depth + 1));
  }
  if (typeof value === "object") {
    const out2 = {};
    for (const [k2, v2] of Object.entries(value)) {
      out2[k2] = preTruncate(v2, maxLength, depth + 1);
    }
    return out2;
  }
  return value;
}
function cleanSummary(raw2) {
  let text = raw2.split("\n")[0]?.trim() ?? "";
  text = text.replace(/^[-*•]\s+/, "").trim();
  text = text.replace(/^[*_]{1,3}/, "").replace(/[*_]{1,3}$/, "").trim();
  text = text.replace(LEADING_QUOTES_RE, "").replace(TRAILING_QUOTES_RE, "").trim();
  text = text.replace(/^(label|summary|result|output)\s*[:：]\s*/i, "").trim();
  if (!text)
    return "";
  for (const re3 of REFUSAL_PREFIXES) {
    if (re3.test(text))
      return "";
  }
  if (text.length > MAX_SUMMARY_LENGTH) {
    text = text.slice(0, MAX_SUMMARY_LENGTH).trim();
  }
  return text;
}
var debugLogger98, TOOL_USE_SUMMARY_SYSTEM_PROMPT, INPUT_TRUNCATE_LENGTH, LAST_ASSISTANT_TEXT_LENGTH, MAX_SUMMARY_LENGTH, QUOTE_CHARS, LEADING_QUOTES_RE, TRAILING_QUOTES_RE, REFUSAL_PREFIXES;
var init_toolUseSummary = __esm({
  "packages/core/dist/src/services/toolUseSummary.js"() {
    "use strict";
    init_esbuild_shims();
    init_partUtils();
    init_debugLogger();
    debugLogger98 = createDebugLogger("TOOL_USE_SUMMARY");
    __name(createToolUseSummaryMessage, "createToolUseSummaryMessage");
    TOOL_USE_SUMMARY_SYSTEM_PROMPT = `Write a short summary label describing what these tool calls accomplished. It appears as a single-line row in a mobile app and truncates around 30 characters, so think git-commit-subject, not sentence.

Keep the verb in past tense and the most distinctive noun. Drop articles, connectors, and long location context first.

Examples:
- Searched in auth/
- Fixed NPE in UserService
- Created signup endpoint
- Read config.json
- Ran failing tests`;
    INPUT_TRUNCATE_LENGTH = 300;
    LAST_ASSISTANT_TEXT_LENGTH = 200;
    MAX_SUMMARY_LENGTH = 100;
    __name(generateToolUseSummary, "generateToolUseSummary");
    __name(truncateJson, "truncateJson");
    __name(preTruncate, "preTruncate");
    QUOTE_CHARS = "\"'`\u2018\u2019\u201C\u201D\u300C\u300D\u300E\u300F";
    LEADING_QUOTES_RE = new RegExp(`^[${QUOTE_CHARS}]{1,10}`);
    TRAILING_QUOTES_RE = new RegExp(`[${QUOTE_CHARS}]{1,10}$`);
    REFUSAL_PREFIXES = [
      /^api error\b/i,
      /^error[:：]/i,
      // Match "I can't" (ASCII U+0027 apostrophe), "I can’t" (curly U+2019),
      // and "I cannot" as a single pattern.
      /^i can(?:['’]t|not)\b/i,
      /^unable to\b/i,
      /^failed to\b/i,
      /^sorry[,，]/i,
      /^request failed\b/i,
      /^我无法/,
      /^我不能/,
      /^抱歉[,，]?/,
      /^无法/
    ];
    __name(cleanSummary, "cleanSummary");
  }
});

// packages/core/dist/src/utils/bareMode.js
function isTruthy(value) {
  if (!value) {
    return false;
  }
  return ["1", "true", "yes", "on"].includes(value.toLowerCase().trim());
}
function isBareMode(cliFlag) {
  return cliFlag === true || isTruthy(process.env[QWEN_CODE_SIMPLE_ENV_VAR]);
}
var QWEN_CODE_SIMPLE_ENV_VAR;
var init_bareMode = __esm({
  "packages/core/dist/src/utils/bareMode.js"() {
    "use strict";
    init_esbuild_shims();
    QWEN_CODE_SIMPLE_ENV_VAR = "QWEN_CODE_SIMPLE";
    __name(isTruthy, "isTruthy");
    __name(isBareMode, "isBareMode");
  }
});

// packages/core/dist/src/ide/ide-installer.js
import * as child_process from "node:child_process";
import * as process14 from "node:process";
import * as path85 from "node:path";
import * as fs90 from "node:fs";
import * as os30 from "node:os";
function getVsCodeCommand(platform15 = process14.platform) {
  return platform15 === "win32" ? "code.cmd" : "code";
}
async function findVsCodeCommand(platform15 = process14.platform) {
  const vscodeCommand = getVsCodeCommand(platform15);
  try {
    if (platform15 === "win32") {
      const result = child_process.execSync(`where.exe ${vscodeCommand}`).toString().trim();
      const firstPath = result.split(/\r?\n/)[0];
      if (firstPath) {
        return firstPath;
      }
    } else {
      child_process.execSync(`command -v ${vscodeCommand}`, {
        stdio: "ignore"
      });
      return vscodeCommand;
    }
  } catch {
  }
  const locations = [];
  const homeDir = os30.homedir();
  if (platform15 === "darwin") {
    locations.push("/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code", path85.join(homeDir, "Library/Application Support/Code/bin/code"));
  } else if (platform15 === "linux") {
    locations.push("/usr/share/code/bin/code", "/snap/bin/code", path85.join(homeDir, ".local/share/code/bin/code"));
  } else if (platform15 === "win32") {
    locations.push(path85.join(process14.env["ProgramFiles"] || "C:\\Program Files", "Microsoft VS Code", "bin", "code.cmd"), path85.join(homeDir, "AppData", "Local", "Programs", "Microsoft VS Code", "bin", "code.cmd"));
  }
  for (const location of locations) {
    if (fs90.existsSync(location)) {
      return location;
    }
  }
  return null;
}
function getIdeInstaller(ide, platform15 = process14.platform) {
  switch (ide.name) {
    case IDE_DEFINITIONS.vscode.name:
    case IDE_DEFINITIONS.firebasestudio.name:
      return new VsCodeInstaller(ide, platform15);
    default:
      return null;
  }
}
var VsCodeInstaller;
var init_ide_installer = __esm({
  "packages/core/dist/src/ide/ide-installer.js"() {
    "use strict";
    init_esbuild_shims();
    init_detect_ide();
    init_constants4();
    __name(getVsCodeCommand, "getVsCodeCommand");
    __name(findVsCodeCommand, "findVsCodeCommand");
    VsCodeInstaller = class {
      static {
        __name(this, "VsCodeInstaller");
      }
      ideInfo;
      platform;
      vsCodeCommand;
      constructor(ideInfo, platform15 = process14.platform) {
        this.ideInfo = ideInfo;
        this.platform = platform15;
        this.vsCodeCommand = findVsCodeCommand(platform15);
      }
      async install() {
        const commandPath = await this.vsCodeCommand;
        if (!commandPath) {
          return {
            success: false,
            message: `${this.ideInfo.displayName} CLI not found. Please ensure 'code' is in your system's PATH. For help, see https://code.visualstudio.com/docs/configure/command-line#_code-is-not-recognized-as-an-internal-or-external-command. You can also install the '${QWEN_CODE_COMPANION_EXTENSION_NAME}' extension manually from the VS Code marketplace.`
          };
        }
        const isWindows9 = process14.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/lsp/constants.js
var DEFAULT_LSP_STARTUP_TIMEOUT_MS, DEFAULT_LSP_REQUEST_TIMEOUT_MS, DEFAULT_LSP_WARMUP_DELAY_MS, DEFAULT_LSP_DOCUMENT_OPEN_DELAY_MS, DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS, DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS, DEFAULT_LSP_DOCUMENT_RETRY_DELAY_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_DOCUMENT_OPEN_DELAY_MS = 200;
    DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS = 2e3;
    DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS = 1500;
    DEFAULT_LSP_DOCUMENT_RETRY_DELAY_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 fs91 from "node:fs";
import * as path86 from "path";
import { pathToFileURL as pathToFileURL3 } from "url";
var debugLogger99, LspConfigLoader;
var init_LspConfigLoader = __esm({
  "packages/core/dist/src/lsp/LspConfigLoader.js"() {
    "use strict";
    init_esbuild_shims();
    init_variables();
    init_debugLogger();
    debugLogger99 = 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 = path86.join(this.workspaceRoot, ".lsp.json");
        if (!fs91.existsSync(lspConfigPath)) {
          return [];
        }
        try {
          const configContent = fs91.readFileSync(lspConfigPath, "utf-8");
          const data = JSON.parse(configContent);
          return this.parseConfigSource(data, lspConfigPath);
        } catch (error40) {
          debugLogger99.warn("Failed to load user .lsp.json config:", error40);
          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 (!fs91.existsSync(configPath)) {
              debugLogger99.warn(`LSP config not found for ${originBase}: ${configPath}`);
              continue;
            }
            try {
              const configContent = fs91.readFileSync(configPath, "utf-8");
              const data = JSON.parse(configContent);
              const hydrated = this.hydrateExtensionLspConfig(data, extension.path);
              configs.push(...this.parseConfigSource(hydrated, `${originBase} (${configPath})`));
            } catch (error40) {
              debugLogger99.warn(`Failed to load extension LSP config from ${configPath}:`, error40);
            }
          } else if (this.isRecord(lspServers)) {
            const hydrated = this.hydrateExtensionLspConfig(lspServers, extension.path);
            configs.push(...this.parseConfigSource(hydrated, `${originBase} (lspServers)`));
          } else {
            debugLogger99.warn(`LSP config for ${originBase} must be an object or a JSON file path.`);
          }
        }
        return configs;
      }
      /**
       * Merge configs: extension configs + user configs
       * Note: Built-in presets are disabled. LSP servers must be explicitly configured
       * by the user via .lsp.json or through extensions.
       */
      mergeConfigs(_detectedLanguages, extensionConfigs, userConfigs) {
        const mergedConfigs = [];
        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;
      }
      /**
       * Parse configuration source and extract server configs.
       * Expects basic format keyed by language identifier.
       */
      parseConfigSource(source2, origin2) {
        if (!this.isRecord(source2)) {
          return [];
        }
        const configs = [];
        for (const [key, spec] of Object.entries(source2)) {
          if (!this.isRecord(spec)) {
            continue;
          }
          const languages = [key];
          const name4 = typeof spec["command"] === "string" ? spec["command"] : key;
          const config2 = this.buildServerConfig(name4, languages, spec, origin2);
          if (config2) {
            configs.push(config2);
          }
        }
        return configs;
      }
      resolveExtensionConfigPath(extensionPath, configPath) {
        return path86.isAbsolute(configPath) ? path86.resolve(configPath) : path86.resolve(extensionPath, configPath);
      }
      hydrateExtensionLspConfig(source2, extensionPath) {
        return recursivelyHydrateStrings(source2, {
          extensionPath,
          CLAUDE_PLUGIN_ROOT: extensionPath,
          workspacePath: this.workspaceRoot,
          "/": path86.sep,
          pathSeparator: path86.sep
        });
      }
      buildServerConfig(name4, languages, spec, origin2) {
        const transport = this.normalizeTransport(spec["transport"]);
        const command2 = typeof spec["command"] === "string" ? spec["command"] : void 0;
        const args2 = this.normalizeStringArray(spec["args"]) ?? [];
        const env6 = 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) {
          debugLogger99.warn(`LSP config error in ${origin2}: ${name4} missing command`);
          return null;
        }
        if (transport !== "stdio" && !socket) {
          debugLogger99.warn(`LSP config error in ${origin2}: ${name4} missing socket info`);
          return null;
        }
        return {
          name: name4,
          languages,
          command: command2,
          args: args2,
          transport,
          env: env6,
          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 env6 = {};
        for (const [key, val] of Object.entries(value)) {
          if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
            env6[key] = String(val);
          }
        }
        return Object.keys(env6).length > 0 ? env6 : 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 = path86.isAbsolute(value) ? path86.resolve(value) : path86.resolve(this.workspaceRoot, value);
        const root = path86.resolve(this.workspaceRoot);
        if (resolved === root || resolved.startsWith(root + path86.sep)) {
          return resolved;
        }
        debugLogger99.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 debugLogger100, JsonRpcConnection, LspConnectionFactory;
var init_LspConnectionFactory = __esm({
  "packages/core/dist/src/lsp/LspConnectionFactory.js"() {
    "use strict";
    init_esbuild_shims();
    init_constants8();
    init_debugLogger();
    debugLogger100 = 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", (error40) => this.disposePending(error40 instanceof Error ? error40 : new Error(String(error40))));
      }
      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((resolve42, 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: resolve42, 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 (error40) {
          this.writeMessage({
            jsonrpc: "2.0",
            id: message.id,
            error: {
              code: -32603,
              message: error40.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 body2 = this.buffer.slice(messageStart, messageEnd);
          this.buffer = this.buffer.slice(messageEnd);
          try {
            const message = JSON.parse(body2);
            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 json3 = JSON.stringify(message);
        const header = `Content-Length: ${Buffer.byteLength(json3, "utf8")}\r
\r
`;
        this.writer(header + json3);
      }
      disposePending(error40) {
        for (const [, pending] of Array.from(this.pendingRequests)) {
          clearTimeout(pending.timer);
          pending.reject(error40 ?? new Error("LSP connection closed"));
        }
        this.pendingRequests.clear();
      }
    };
    LspConnectionFactory = class _LspConnectionFactory {
      static {
        __name(this, "LspConnectionFactory");
      }
      /**
       * 创建基于 stdio 的 LSP 连接
       */
      static async createStdioConnection(command2, args2, options2, timeoutMs = 1e4) {
        return new Promise((resolve42, reject) => {
          const spawnOptions = {
            stdio: "pipe",
            ...options2
          };
          const processInstance = cp.spawn(command2, args2, spawnOptions);
          const timeoutId = setTimeout(() => {
            reject(new Error("LSP server spawn timeout"));
            if (!processInstance.killed) {
              processInstance.kill();
            }
          }, timeoutMs);
          processInstance.once("error", (error40) => {
            clearTimeout(timeoutId);
            reject(new Error(`Failed to spawn LSP server: ${error40.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());
            resolve42({
              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((resolve42, 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((error40) => {
            clearTimeout(timeoutId);
            reject(new Error(`Failed to connect to LSP server: ${error40.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());
            resolve42({
              connection,
              socket
            });
          });
        });
      }
      /**
       * 关闭 LSP 连接
       */
      static async closeConnection(lspConnection) {
        if (lspConnection.connection) {
          try {
            await lspConnection.connection.shutdown();
          } catch (e4) {
            debugLogger100.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/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(info2) {
        if (!Array.isArray(info2)) {
          return [];
        }
        const result = [];
        for (const item of info2) {
          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 args2 = Array.isArray(cmdObj["arguments"]) ? cmdObj["arguments"] : void 0;
        return { title, command: command2, arguments: args2 };
      }
      // ============================================================================
      // 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 start2 = range.start;
        const end = range.end;
        return {
          uri,
          range: {
            start: {
              line: Number(start2?.line ?? 0),
              character: Number(start2?.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"]) {
          return null;
        }
        const start2 = range?.start ?? { line: 0, character: 0 };
        const end = range?.end ?? { line: 0, character: 0 };
        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(start2?.line ?? 0),
                character: Number(start2?.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 start2 = rangeObj["start"];
        const end = rangeObj["end"];
        if (!start2 || typeof start2 !== "object" || !end || typeof end !== "object") {
          return null;
        }
        const startObj = start2;
        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 parts2 = contents.map((item) => this.normalizeHoverContents(item)).map((item) => item.trim()).filter((item) => item.length > 0);
          return parts2.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 name4 = typeof nameValue === "string" ? nameValue : String(nameValue ?? "");
        const uri = itemObj["uri"];
        if (!name4 || 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: name4,
          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 name4 = typeof nameValue === "string" ? nameValue : String(nameValue);
        const selectionRange = this.normalizeRange(item["selectionRange"]) ?? this.normalizeRange(item["range"]);
        if (!selectionRange) {
          return;
        }
        results.push({
          name: name4,
          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, name4);
            }
          }
        }
      }
    };
  }
});

// packages/core/dist/src/lsp/LspServerManager.js
import { spawn as spawn8 } from "node:child_process";
import * as fs92 from "node:fs";
import * as path87 from "path";
import { pathToFileURL as pathToFileURL4 } from "url";
var debugLogger101, LspServerManager;
var init_LspServerManager = __esm({
  "packages/core/dist/src/lsp/LspServerManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_esm13();
    init_LspConnectionFactory();
    init_constants8();
    init_debugLogger();
    debugLogger101 = 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 [name4, handle2] of Array.from(this.serverHandles)) {
          statusMap.set(name4, handle2.status);
        }
        return statusMap;
      }
      async startAll() {
        for (const [name4, handle2] of Array.from(this.serverHandles)) {
          await this.startServer(name4, handle2);
        }
      }
      async stopAll() {
        for (const [name4, handle2] of Array.from(this.serverHandles)) {
          await this.stopServer(name4, handle2);
        }
        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.
       *
       * @param handle - The LSP server handle
       * @param force - Force re-warmup even if already warmed up
       * @returns The URI of the file opened during warmup, or undefined if no file was opened
       */
      async warmupTypescriptServer(handle2, force = false) {
        if (!handle2.connection || !this.isTypescriptServer(handle2)) {
          return void 0;
        }
        if (handle2.warmedUp && !force) {
          return void 0;
        }
        const tsFile = this.findFirstTypescriptFile();
        if (!tsFile) {
          return void 0;
        }
        const uri = pathToFileURL4(tsFile).toString();
        const languageId = tsFile.endsWith(".tsx") ? "typescriptreact" : tsFile.endsWith(".jsx") ? "javascriptreact" : tsFile.endsWith(".js") ? "javascript" : "typescript";
        try {
          const text = fs92.readFileSync(tsFile, "utf-8");
          handle2.connection.send({
            jsonrpc: "2.0",
            method: "textDocument/didOpen",
            params: {
              textDocument: {
                uri,
                languageId,
                version: 1,
                text
              }
            }
          });
          await new Promise((resolve42) => setTimeout(resolve42, DEFAULT_LSP_WARMUP_DELAY_MS));
          handle2.warmedUp = true;
          return uri;
        } catch (error40) {
          debugLogger101.warn("TypeScript server warm-up failed:", error40);
          return void 0;
        }
      }
      /**
       * 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(handle2) {
        return handle2.config.name.includes("typescript") || (handle2.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(name4, handle2) {
        if (handle2.startingPromise) {
          return handle2.startingPromise;
        }
        if (handle2.status === "IN_PROGRESS" || handle2.status === "READY") {
          return;
        }
        handle2.stopRequested = false;
        handle2.startingPromise = this.doStartServer(name4, handle2).finally(() => {
          handle2.startingPromise = void 0;
        });
        return handle2.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(name4, handle2) {
        const workspaceTrusted = this.config.isTrustedFolder();
        if ((this.requireTrustedWorkspace || handle2.config.trustRequired) && !workspaceTrusted) {
          debugLogger101.warn(`LSP server ${name4} requires trusted workspace, skipping startup`);
          handle2.status = "FAILED";
          return;
        }
        const trusted = await this.checkWorkspaceTrust(name4, handle2.config, workspaceTrusted);
        if (!trusted) {
          debugLogger101.info(`Workspace trust check failed, not starting LSP server ${name4}`);
          handle2.status = "FAILED";
          return;
        }
        if (handle2.config.command) {
          const commandCwd = handle2.config.workspaceFolder ?? this.workspaceRoot;
          if (!await this.commandExists(handle2.config.command, handle2.config.env, commandCwd)) {
            debugLogger101.warn(`LSP server ${name4} command not found: ${handle2.config.command}`);
            handle2.status = "FAILED";
            return;
          }
          if (!this.isPathSafe(handle2.config.command, this.workspaceRoot, commandCwd)) {
            debugLogger101.warn(`LSP server ${name4} command path is unsafe: ${handle2.config.command}`);
            handle2.status = "FAILED";
            return;
          }
        }
        try {
          handle2.error = void 0;
          handle2.warmedUp = false;
          handle2.status = "IN_PROGRESS";
          const connection = await this.createLspConnection(handle2.config);
          handle2.connection = connection.connection;
          handle2.process = connection.process;
          await this.initializeLspServer(connection, handle2.config);
          handle2.status = "READY";
          this.attachRestartHandler(name4, handle2);
          debugLogger101.info(`LSP server ${name4} started successfully`);
        } catch (error40) {
          handle2.status = "FAILED";
          handle2.error = error40;
          debugLogger101.error(`LSP server ${name4} failed to start:`, error40);
        }
      }
      /**
       * Stop individual LSP server
       */
      async stopServer(name4, handle2) {
        handle2.stopRequested = true;
        if (handle2.connection) {
          try {
            await this.shutdownConnection(handle2);
          } catch (error40) {
            debugLogger101.error(`Error closing LSP server ${name4}:`, error40);
          }
        } else if (handle2.process && handle2.process.exitCode === null) {
          handle2.process.kill();
        }
        handle2.connection = void 0;
        handle2.process = void 0;
        handle2.status = "NOT_STARTED";
        handle2.warmedUp = false;
        handle2.restartAttempts = 0;
      }
      async shutdownConnection(handle2) {
        if (!handle2.connection) {
          return;
        }
        try {
          const shutdownPromise = handle2.connection.shutdown();
          if (typeof handle2.config.shutdownTimeout === "number") {
            await Promise.race([
              shutdownPromise,
              new Promise((resolve42) => setTimeout(resolve42, handle2.config.shutdownTimeout))
            ]);
          } else {
            await shutdownPromise;
          }
        } finally {
          handle2.connection.end();
        }
      }
      attachRestartHandler(name4, handle2) {
        if (!handle2.process) {
          return;
        }
        handle2.process.once("exit", (code2) => {
          if (handle2.stopRequested) {
            return;
          }
          if (!handle2.config.restartOnCrash) {
            handle2.status = "FAILED";
            return;
          }
          const maxRestarts = handle2.config.maxRestarts ?? DEFAULT_LSP_MAX_RESTARTS;
          if (maxRestarts <= 0) {
            handle2.status = "FAILED";
            return;
          }
          const attempts = handle2.restartAttempts ?? 0;
          if (attempts >= maxRestarts) {
            debugLogger101.warn(`LSP server ${name4} reached max restart attempts (${maxRestarts}), stopping restarts`);
            handle2.status = "FAILED";
            return;
          }
          handle2.restartAttempts = attempts + 1;
          debugLogger101.warn(`LSP server ${name4} exited (code ${code2 ?? "unknown"}), restarting (${handle2.restartAttempts}/${maxRestarts})`);
          this.resetHandle(handle2);
          void this.startServer(name4, handle2);
        });
      }
      resetHandle(handle2) {
        if (handle2.connection) {
          handle2.connection.end();
        }
        if (handle2.process && handle2.process.exitCode === null) {
          handle2.process.kill();
        }
        handle2.connection = void 0;
        handle2.process = void 0;
        handle2.status = "NOT_STARTED";
        handle2.error = void 0;
        handle2.warmedUp = false;
        handle2.stopRequested = false;
      }
      buildProcessEnv(env6) {
        if (!env6 || Object.keys(env6).length === 0) {
          return void 0;
        }
        return { ...process.env, ...env6 };
      }
      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 (error40) {
            attempt += 1;
            if (Date.now() >= deadline) {
              throw error40;
            }
            const delay5 = Math.min(DEFAULT_LSP_SOCKET_RETRY_DELAY_MS * attempt, DEFAULT_LSP_SOCKET_MAX_RETRY_DELAY_MS);
            await new Promise((resolve42) => setTimeout(resolve42, delay5));
          }
        }
      }
      /**
       * Create LSP connection
       */
      async createLspConnection(config2) {
        const workspaceFolder = config2.workspaceFolder ?? this.workspaceRoot;
        const startupTimeout = config2.startupTimeout ?? DEFAULT_LSP_STARTUP_TIMEOUT_MS;
        const env6 = 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: env6 }, 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 process51;
          if (config2.command) {
            process51 = spawn8(config2.command, config2.args ?? [], {
              cwd: workspaceFolder,
              env: env6,
              stdio: "ignore"
            });
            await new Promise((resolve42, reject) => {
              process51?.once("spawn", () => resolve42());
              process51?.once("error", (error40) => {
                reject(new Error(`Failed to spawn LSP server: ${error40.message}`));
              });
            });
          }
          try {
            const lspConnection = await this.connectSocketWithRetry(config2.socket, startupTimeout);
            return {
              connection: lspConnection.connection,
              process: process51,
              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 (error40) {
            if (process51 && process51.exitCode === null) {
              process51.kill();
            }
            throw error40;
          }
        } else {
          throw new Error(`Unsupported transport: ${config2.transport}`);
        }
      }
      /**
       * Initialize LSP server
       */
      async initializeLspServer(connection, config2) {
        const workspaceFolderPath = config2.workspaceFolder ?? this.workspaceRoot;
        const workspaceFolder = {
          name: path87.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
            }
          });
        }
      }
      /**
       * Check if command exists by spawning it with --version.
       * Only returns false when the spawn itself fails (e.g. ENOENT).
       * A timeout means the process started successfully (command exists)
       * but didn't exit in time — common for servers like jdtls that
       * don't support --version and start their full runtime instead.
       *
       * @param command - The command to check
       * @param env - Optional environment variables
       * @param cwd - Optional working directory
       * @returns true if the command can be spawned, false if not found
       */
      async commandExists(command2, env6, cwd6) {
        return new Promise((resolve42) => {
          let settled = false;
          const child = spawn8(command2, ["--version"], {
            stdio: ["ignore", "ignore", "ignore"],
            cwd: cwd6 ?? this.workspaceRoot,
            env: this.buildProcessEnv(env6)
          });
          child.on("error", () => {
            settled = true;
            resolve42(false);
          });
          child.on("exit", (code2) => {
            if (settled) {
              return;
            }
            settled = true;
            resolve42(code2 !== 127);
          });
          setTimeout(() => {
            if (!settled) {
              settled = true;
              child.kill();
              resolve42(true);
            }
          }, DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS);
        });
      }
      /**
       * Check path safety.
       *
       * Allows:
       * - Bare command names (resolved via PATH, e.g. "clangd")
       * - Absolute paths (explicit user intent, e.g. "/usr/bin/clangd")
       *
       * Blocks:
       * - Relative paths that escape the workspace (e.g. "../../bin/evil")
       */
      isPathSafe(command2, workspacePath, cwd6) {
        if (!command2.includes(path87.sep) && !command2.includes("/")) {
          return true;
        }
        if (path87.isAbsolute(command2)) {
          return true;
        }
        const resolvedWorkspacePath = path87.resolve(workspacePath);
        const basePath = cwd6 ? path87.resolve(cwd6) : resolvedWorkspacePath;
        const resolvedPath = path87.resolve(basePath, command2);
        return resolvedPath.startsWith(resolvedWorkspacePath + path87.sep) || resolvedPath === resolvedWorkspacePath;
      }
      /**
       * Check whether the workspace trust level allows starting an LSP server.
       *
       * Auto-allows in trusted workspaces. In untrusted workspaces, blocks
       * servers that require trust (`trustRequired` or global
       * `requireTrustedWorkspace`), and cautiously allows the rest.
       */
      async checkWorkspaceTrust(serverName, serverConfig, workspaceTrusted) {
        if (workspaceTrusted) {
          return true;
        }
        if (this.requireTrustedWorkspace || serverConfig.trustRequired) {
          debugLogger101.warn(`Workspace not trusted, skipping LSP server ${serverName} (${serverConfig.command ?? serverConfig.transport})`);
          return false;
        }
        debugLogger101.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 matches2 = globSync(pattern, {
                cwd: root,
                ignore: excludePatterns,
                absolute: true,
                nodir: true
              });
              for (const file2 of matches2) {
                if (this.fileDiscoveryService.shouldIgnoreFile(file2)) {
                  continue;
                }
                return file2;
              }
            } 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 path88 from "path";
import { fileURLToPath as fileURLToPath9, pathToFileURL as pathToFileURL5 } from "url";
import * as fs93 from "node:fs";
var debugLogger102, LANGUAGE_ID_TO_EXTENSIONS, DEFAULT_EXCLUDE_PATTERNS, NativeLspService;
var init_NativeLspService = __esm({
  "packages/core/dist/src/lsp/NativeLspService.js"() {
    "use strict";
    init_esbuild_shims();
    init_constants8();
    init_LspConfigLoader();
    init_LspResponseNormalizer();
    init_LspServerManager();
    init_debugLogger();
    init_esm13();
    debugLogger102 = createDebugLogger("LSP");
    LANGUAGE_ID_TO_EXTENSIONS = {
      typescript: ["ts", "tsx"],
      typescriptreact: ["tsx"],
      javascript: ["js", "jsx"],
      javascriptreact: ["jsx"],
      python: ["py"],
      csharp: ["cs"],
      ruby: ["rb"]
    };
    DEFAULT_EXCLUDE_PATTERNS = [
      "**/node_modules/**",
      "**/.git/**",
      "**/dist/**",
      "**/build/**"
    ];
    NativeLspService = class {
      static {
        __name(this, "NativeLspService");
      }
      config;
      workspaceContext;
      fileDiscoveryService;
      requireTrustedWorkspace;
      workspaceRoot;
      configLoader;
      serverManager;
      normalizer;
      openedDocuments = /* @__PURE__ */ new Map();
      lastConnections = /* @__PURE__ */ new Map();
      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.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) {
          debugLogger102.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 serverConfigs = this.configLoader.mergeConfigs([], 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));
      }
      /**
       * Ensure a document is open on the given LSP server. Sends textDocument/didOpen
       * if not already tracked, then waits for the server to process the file before
       * returning. This delay prevents empty results when the server hasn't analyzed
       * the file yet.
       *
       * @param serverName - The name of the LSP server
       * @param handle - The server handle with an active connection
       * @param uri - The document URI to open
       * @returns true if a new didOpen was sent; false if already open or failed
       */
      async ensureDocumentOpen(serverName, handle2, uri) {
        const lastConnection = this.lastConnections.get(serverName);
        if (lastConnection && lastConnection !== handle2.connection) {
          this.openedDocuments.delete(serverName);
        }
        this.lastConnections.set(serverName, handle2.connection);
        if (!uri.startsWith("file://")) {
          return false;
        }
        const openedForServer = this.openedDocuments.get(serverName);
        if (openedForServer?.has(uri)) {
          return false;
        }
        let filePath;
        try {
          filePath = fileURLToPath9(uri);
        } catch (error40) {
          debugLogger102.warn(`Failed to resolve file path for ${uri}:`, error40);
          return false;
        }
        let text;
        try {
          text = fs93.readFileSync(filePath, "utf-8");
        } catch (error40) {
          debugLogger102.warn(`Failed to read file for LSP didOpen: ${filePath}`, error40);
          return false;
        }
        const languageId = this.resolveLanguageId(filePath, handle2) ?? "plaintext";
        handle2.connection.send({
          jsonrpc: "2.0",
          method: "textDocument/didOpen",
          params: {
            textDocument: {
              uri,
              languageId,
              version: 1,
              text
            }
          }
        });
        const nextOpened = openedForServer ?? /* @__PURE__ */ new Set();
        nextOpened.add(uri);
        this.openedDocuments.set(serverName, nextOpened);
        await this.delay(DEFAULT_LSP_DOCUMENT_OPEN_DELAY_MS);
        return true;
      }
      /**
       * Register a URI that was opened externally (e.g. by warmupTypescriptServer)
       * so that ensureDocumentOpen does not send a duplicate textDocument/didOpen.
       *
       * @param serverName - The name of the LSP server
       * @param uri - The document URI to track as already opened
       */
      trackExternallyOpenedDocument(serverName, uri) {
        const openedForServer = this.openedDocuments.get(serverName) ?? /* @__PURE__ */ new Set();
        openedForServer.add(uri);
        this.openedDocuments.set(serverName, openedForServer);
      }
      resolveLanguageId(filePath, handle2) {
        const ext2 = path88.extname(filePath).slice(1).toLowerCase();
        if (ext2 && handle2.config.extensionToLanguage) {
          const mapping = handle2.config.extensionToLanguage;
          return mapping[ext2] ?? mapping["." + ext2];
        }
        if (handle2.config.languages && handle2.config.languages.length > 0) {
          return handle2.config.languages[0];
        }
        return ext2 || void 0;
      }
      async warmupWorkspaceSymbols(serverName, handle2) {
        if (!handle2.connection) {
          return false;
        }
        const openedForServer = this.openedDocuments.get(serverName);
        if (openedForServer && openedForServer.size > 0) {
          return true;
        }
        const filePath = this.findWorkspaceFileForServer(handle2);
        if (!filePath) {
          return false;
        }
        const uri = pathToFileURL5(filePath).toString();
        const didOpen = await this.ensureDocumentOpen(serverName, handle2, uri);
        if (!didOpen) {
          return false;
        }
        await this.delay(DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS);
        return true;
      }
      /**
       * Find the first source file in the workspace that matches the server's
       * language extensions. Used to open a file for workspace symbol warmup.
       *
       * @param handle - The LSP server handle to determine target extensions
       * @returns Absolute path of the first matching file, or undefined
       */
      findWorkspaceFileForServer(handle2) {
        const extensions = this.getWorkspaceSymbolExtensions(handle2);
        if (extensions.length === 0) {
          return void 0;
        }
        const extGlob = extensions.length === 1 ? extensions[0] : `{${extensions.join(",")}}`;
        const pattern = `**/*.${extGlob}`;
        const roots = this.workspaceContext.getDirectories();
        for (const root of roots) {
          try {
            const matches2 = globSync(pattern, {
              cwd: root,
              ignore: DEFAULT_EXCLUDE_PATTERNS,
              absolute: true,
              nodir: true,
              maxDepth: 5
            });
            for (const match2 of matches2) {
              if (this.fileDiscoveryService.shouldIgnoreFile(match2)) {
                continue;
              }
              return match2;
            }
          } catch (_error) {
          }
        }
        return void 0;
      }
      /**
       * Determine file extensions this server can handle, used to find a workspace
       * file to open for warmup. Resolution order:
       *   1. Keys from config.extensionToLanguage (explicit user/extension mapping)
       *   2. Derived from config.languages via LANGUAGE_ID_TO_EXTENSIONS, falling
       *      back to treating the language ID itself as a file extension
       */
      getWorkspaceSymbolExtensions(handle2) {
        const extensions = /* @__PURE__ */ new Set();
        const extMapping = handle2.config.extensionToLanguage;
        if (extMapping) {
          for (const key of Object.keys(extMapping)) {
            const normalized2 = key.startsWith(".") ? key.slice(1) : key;
            if (normalized2) {
              extensions.add(normalized2.toLowerCase());
            }
          }
        }
        if (extensions.size === 0) {
          for (const language of handle2.config.languages) {
            const mapped = LANGUAGE_ID_TO_EXTENSIONS[language];
            if (mapped) {
              for (const ext2 of mapped) {
                extensions.add(ext2);
              }
            } else {
              extensions.add(language.toLowerCase());
            }
          }
        }
        return Array.from(extensions);
      }
      /**
       * Run TypeScript server warmup and track the opened URI to prevent
       * duplicate didOpen notifications.
       *
       * @param serverName - The name of the LSP server
       * @param handle - The server handle
       * @param force - Force re-warmup even if already warmed up
       */
      async warmupAndTrack(serverName, handle2, force = false) {
        const warmupUri = await this.serverManager.warmupTypescriptServer(handle2, force);
        if (warmupUri) {
          this.trackExternallyOpenedDocument(serverName, warmupUri);
        }
      }
      /**
       * Whether we should retry a document-level operation that returned empty
       * results. We retry when a textDocument/didOpen was just sent (the server
       * may still be indexing) AND the server is not a fast TypeScript server.
       */
      shouldRetryAfterOpen(justOpened, handle2) {
        return justOpened && !this.serverManager.isTypescriptServer(handle2);
      }
      async delay(ms) {
        await new Promise((resolve42) => setTimeout(resolve42, ms));
      }
      /**
       * Workspace symbol search across all ready LSP servers.
       */
      async workspaceSymbols(query, limit2 = 50) {
        const results = [];
        for (const [serverName, handle2] of Array.from(this.serverManager.getHandles())) {
          if (handle2.status !== "READY" || !handle2.connection) {
            continue;
          }
          try {
            await this.warmupAndTrack(serverName, handle2);
            const warmedUp = this.serverManager.isTypescriptServer(handle2) ? false : await this.warmupWorkspaceSymbols(serverName, handle2);
            let response = await handle2.connection.request("workspace/symbol", {
              query
            });
            if (!this.serverManager.isTypescriptServer(handle2) && Array.isArray(response) && response.length === 0 && warmedUp) {
              await this.delay(DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS);
              response = await handle2.connection.request("workspace/symbol", {
                query
              });
            }
            if (this.serverManager.isTypescriptServer(handle2) && this.isNoProjectErrorResponse(response)) {
              await this.warmupAndTrack(serverName, handle2, true);
              response = await handle2.connection.request("workspace/symbol", {
                query
              });
            }
            if (!Array.isArray(response)) {
              continue;
            }
            for (const item of response) {
              const symbol2 = this.normalizer.normalizeSymbolResult(item, serverName);
              if (symbol2) {
                results.push(symbol2);
              }
              if (results.length >= limit2) {
                return results.slice(0, limit2);
              }
            }
          } catch (error40) {
            debugLogger102.warn(`LSP workspace/symbol failed for ${serverName}:`, error40);
          }
        }
        return results.slice(0, limit2);
      }
      /**
       * Go to definition
       */
      async definitions(location, serverName, limit2 = 50) {
        const handles = this.getReadyHandles(serverName);
        const requestParams = {
          textDocument: { uri: location.uri },
          position: location.range.start
        };
        for (const [name4, handle2] of handles) {
          try {
            const justOpened = await this.ensureDocumentOpen(name4, handle2, location.uri);
            await this.warmupAndTrack(name4, handle2);
            let response = await handle2.connection.request("textDocument/definition", requestParams);
            if (this.isEmptyResponse(response) && this.shouldRetryAfterOpen(justOpened, handle2)) {
              await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS);
              response = await handle2.connection.request("textDocument/definition", requestParams);
            }
            const candidates = Array.isArray(response) ? response : response ? [response] : [];
            const definitions = [];
            for (const def2 of candidates) {
              const normalized2 = this.normalizer.normalizeLocationResult(def2, name4);
              if (normalized2) {
                definitions.push(normalized2);
                if (definitions.length >= limit2) {
                  return definitions.slice(0, limit2);
                }
              }
            }
            if (definitions.length > 0) {
              return definitions.slice(0, limit2);
            }
          } catch (error40) {
            debugLogger102.warn(`LSP textDocument/definition failed for ${name4}:`, error40);
          }
        }
        return [];
      }
      /**
       * Find references
       */
      async references(location, serverName, includeDeclaration = false, limit2 = 200) {
        const handles = this.getReadyHandles(serverName);
        const requestParams = {
          textDocument: { uri: location.uri },
          position: location.range.start,
          context: { includeDeclaration }
        };
        for (const [name4, handle2] of handles) {
          try {
            const justOpened = await this.ensureDocumentOpen(name4, handle2, location.uri);
            await this.warmupAndTrack(name4, handle2);
            let response = await handle2.connection.request("textDocument/references", requestParams);
            if (this.isEmptyResponse(response) && this.shouldRetryAfterOpen(justOpened, handle2)) {
              await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS);
              response = await handle2.connection.request("textDocument/references", requestParams);
            }
            if (!Array.isArray(response)) {
              continue;
            }
            const refs = [];
            for (const ref of response) {
              const normalized2 = this.normalizer.normalizeLocationResult(ref, name4);
              if (normalized2) {
                refs.push(normalized2);
              }
              if (refs.length >= limit2) {
                return refs.slice(0, limit2);
              }
            }
            if (refs.length > 0) {
              return refs.slice(0, limit2);
            }
          } catch (error40) {
            debugLogger102.warn(`LSP textDocument/references failed for ${name4}:`, error40);
          }
        }
        return [];
      }
      /**
       * Get hover information
       */
      async hover(location, serverName) {
        const handles = this.getReadyHandles(serverName);
        const requestParams = {
          textDocument: { uri: location.uri },
          position: location.range.start
        };
        for (const [name4, handle2] of handles) {
          try {
            const justOpened = await this.ensureDocumentOpen(name4, handle2, location.uri);
            await this.warmupAndTrack(name4, handle2);
            let response = await handle2.connection.request("textDocument/hover", requestParams);
            if (this.isEmptyResponse(response) && this.shouldRetryAfterOpen(justOpened, handle2)) {
              await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS);
              response = await handle2.connection.request("textDocument/hover", requestParams);
            }
            const normalized2 = this.normalizer.normalizeHoverResult(response, name4);
            if (normalized2) {
              return normalized2;
            }
          } catch (error40) {
            debugLogger102.warn(`LSP textDocument/hover failed for ${name4}:`, error40);
          }
        }
        return null;
      }
      /**
       * Get document symbols
       */
      async documentSymbols(uri, serverName, limit2 = 200) {
        const handles = this.getReadyHandles(serverName);
        const requestParams = { textDocument: { uri } };
        for (const [name4, handle2] of handles) {
          try {
            const justOpened = await this.ensureDocumentOpen(name4, handle2, uri);
            await this.warmupAndTrack(name4, handle2);
            let response = await handle2.connection.request("textDocument/documentSymbol", requestParams);
            if (this.isEmptyResponse(response) && this.shouldRetryAfterOpen(justOpened, handle2)) {
              await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS);
              response = await handle2.connection.request("textDocument/documentSymbol", requestParams);
            }
            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, name4, symbols, limit2);
              } else {
                const normalized2 = this.normalizer.normalizeSymbolResult(itemObj, name4);
                if (normalized2) {
                  symbols.push(normalized2);
                }
              }
              if (symbols.length >= limit2) {
                return symbols.slice(0, limit2);
              }
            }
            if (symbols.length > 0) {
              return symbols.slice(0, limit2);
            }
          } catch (error40) {
            debugLogger102.warn(`LSP textDocument/documentSymbol failed for ${name4}:`, error40);
          }
        }
        return [];
      }
      /**
       * Find implementations
       */
      async implementations(location, serverName, limit2 = 50) {
        const handles = this.getReadyHandles(serverName);
        const requestParams = {
          textDocument: { uri: location.uri },
          position: location.range.start
        };
        for (const [name4, handle2] of handles) {
          try {
            const justOpened = await this.ensureDocumentOpen(name4, handle2, location.uri);
            await this.warmupAndTrack(name4, handle2);
            let response = await handle2.connection.request("textDocument/implementation", requestParams);
            if (this.isEmptyResponse(response) && this.shouldRetryAfterOpen(justOpened, handle2)) {
              await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS);
              response = await handle2.connection.request("textDocument/implementation", requestParams);
            }
            const candidates = Array.isArray(response) ? response : response ? [response] : [];
            const implementations = [];
            for (const item of candidates) {
              const normalized2 = this.normalizer.normalizeLocationResult(item, name4);
              if (normalized2) {
                implementations.push(normalized2);
                if (implementations.length >= limit2) {
                  return implementations.slice(0, limit2);
                }
              }
            }
            if (implementations.length > 0) {
              return implementations.slice(0, limit2);
            }
          } catch (error40) {
            debugLogger102.warn(`LSP textDocument/implementation failed for ${name4}:`, error40);
          }
        }
        return [];
      }
      /**
       * Prepare call hierarchy
       */
      async prepareCallHierarchy(location, serverName, limit2 = 50) {
        const handles = this.getReadyHandles(serverName);
        const requestParams = {
          textDocument: { uri: location.uri },
          position: location.range.start
        };
        for (const [name4, handle2] of handles) {
          try {
            const justOpened = await this.ensureDocumentOpen(name4, handle2, location.uri);
            await this.warmupAndTrack(name4, handle2);
            let response = await handle2.connection.request("textDocument/prepareCallHierarchy", requestParams);
            if (this.isEmptyResponse(response) && this.shouldRetryAfterOpen(justOpened, handle2)) {
              await this.delay(DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS);
              response = await handle2.connection.request("textDocument/prepareCallHierarchy", requestParams);
            }
            const candidates = Array.isArray(response) ? response : response ? [response] : [];
            const items = [];
            for (const item of candidates) {
              const normalized2 = this.normalizer.normalizeCallHierarchyItem(item, name4);
              if (normalized2) {
                items.push(normalized2);
                if (items.length >= limit2) {
                  return items.slice(0, limit2);
                }
              }
            }
            if (items.length > 0) {
              return items.slice(0, limit2);
            }
          } catch (error40) {
            debugLogger102.warn(`LSP textDocument/prepareCallHierarchy failed for ${name4}:`, error40);
          }
        }
        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 [name4, handle2] of handles) {
          try {
            await this.warmupAndTrack(name4, handle2);
            const response = await handle2.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, name4);
              if (normalized2) {
                calls.push(normalized2);
                if (calls.length >= limit2) {
                  return calls.slice(0, limit2);
                }
              }
            }
            if (calls.length > 0) {
              return calls.slice(0, limit2);
            }
          } catch (error40) {
            debugLogger102.warn(`LSP callHierarchy/incomingCalls failed for ${name4}:`, error40);
          }
        }
        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 [name4, handle2] of handles) {
          try {
            await this.warmupAndTrack(name4, handle2);
            const response = await handle2.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, name4);
              if (normalized2) {
                calls.push(normalized2);
                if (calls.length >= limit2) {
                  return calls.slice(0, limit2);
                }
              }
            }
            if (calls.length > 0) {
              return calls.slice(0, limit2);
            }
          } catch (error40) {
            debugLogger102.warn(`LSP callHierarchy/outgoingCalls failed for ${name4}:`, error40);
          }
        }
        return [];
      }
      /**
       * Get diagnostics for a document
       */
      async diagnostics(uri, serverName) {
        const handles = this.getReadyHandles(serverName);
        const allDiagnostics = [];
        for (const [name4, handle2] of handles) {
          try {
            await this.ensureDocumentOpen(name4, handle2, uri);
            await this.warmupAndTrack(name4, handle2);
            const response = await handle2.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, name4);
                  if (normalized2) {
                    allDiagnostics.push(normalized2);
                  }
                }
              }
            }
          } catch (error40) {
            debugLogger102.warn(`LSP textDocument/diagnostic failed for ${name4}:`, error40);
          }
        }
        return allDiagnostics;
      }
      /**
       * Get diagnostics for all documents in the workspace
       */
      async workspaceDiagnostics(serverName, limit2 = 100) {
        const handles = this.getReadyHandles(serverName);
        const results = [];
        for (const [name4, handle2] of handles) {
          try {
            await this.warmupAndTrack(name4, handle2);
            const response = await handle2.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, name4);
                  if (normalized2 && normalized2.diagnostics.length > 0) {
                    results.push(normalized2);
                  }
                }
              }
            }
          } catch (error40) {
            debugLogger102.warn(`LSP workspace/diagnostic failed for ${name4}:`, error40);
          }
          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 [name4, handle2] of handles) {
          try {
            await this.ensureDocumentOpen(name4, handle2, uri);
            await this.warmupAndTrack(name4, handle2);
            const lspDiagnostics = context2.diagnostics.map((d2) => this.normalizer.denormalizeDiagnostic(d2));
            const response = await handle2.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, name4);
              if (normalized2) {
                actions.push(normalized2);
                if (actions.length >= limit2) {
                  break;
                }
              }
            }
            if (actions.length > 0) {
              return actions.slice(0, limit2);
            }
          } catch (error40) {
            debugLogger102.warn(`LSP textDocument/codeAction failed for ${name4}:`, error40);
          }
        }
        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 (error40) {
          debugLogger102.error("Failed to apply workspace edit:", error40);
          return false;
        }
      }
      /**
       * Apply text edits to a file
       */
      async applyTextEdits(uri, edits) {
        let filePath = uri.startsWith("file://") ? fileURLToPath9(uri) : uri;
        if (!path88.isAbsolute(filePath)) {
          filePath = path88.resolve(this.workspaceRoot, filePath);
        }
        if (!this.workspaceContext.isPathWithinWorkspace(filePath)) {
          throw new Error(`Refusing to apply edits outside workspace: ${filePath}`);
        }
        let content;
        try {
          content = fs93.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);
        }
        fs93.writeFileSync(filePath, lines.join("\n"), "utf-8");
      }
      /**
       * Check if an LSP response represents an empty/null result, used to decide
       * whether a retry is worthwhile after a freshly opened document.
       */
      isEmptyResponse(response) {
        if (response === null || response === void 0) {
          return true;
        }
        if (Array.isArray(response) && response.length === 0) {
          return true;
        }
        return false;
      }
      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_types19 = __esm({
  "packages/core/dist/src/lsp/types.js"() {
    "use strict";
    init_esbuild_shims();
  }
});

// packages/core/dist/src/extension/marketplace.js
import * as fs94 from "node:fs";
import * as path89 from "node:path";
import * as https6 from "node:https";
import { stat as stat10 } 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(url3, headers) {
  return new Promise((resolve42) => {
    https6.get(url3, { headers }, (res) => {
      if (res.statusCode !== 200) {
        resolve42(null);
        return;
      }
      const chunks = [];
      res.on("data", (chunk) => chunks.push(chunk));
      res.on("end", () => {
        resolve42(Buffer.concat(chunks).toString());
      });
    }).on("error", () => resolve42(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 = path89.join(localPath, ".claude-plugin", "marketplace.json");
  try {
    const content = await fs94.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 stat10(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 (isScopedNpmPackage(repo)) {
    installMetadata = {
      source: repo,
      type: "npm",
      pluginName
    };
  } 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();
    init_npm();
    __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_npm();
    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/skills/index.js
var init_skills = __esm({
  "packages/core/dist/src/skills/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_types14();
    init_skill_manager();
  }
});

// packages/core/dist/src/subagents/index.js
var init_subagents = __esm({
  "packages/core/dist/src/subagents/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_types15();
    init_builtin_agents();
    init_validation();
    init_subagent_manager();
  }
});

// packages/core/dist/src/followup/followupState.js
function createFollowupController(options2) {
  const { enabled: enabled2 = true, onStateChange, getOnAccept, onOutcome } = options2;
  let currentState = INITIAL_FOLLOWUP_STATE;
  let timeoutId = null;
  let accepting = false;
  let acceptTimeoutId = null;
  function applyState(next) {
    currentState = next;
    onStateChange(next);
  }
  __name(applyState, "applyState");
  function clearTimers() {
    if (timeoutId) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
    if (acceptTimeoutId) {
      clearTimeout(acceptTimeoutId);
      acceptTimeoutId = null;
    }
  }
  __name(clearTimers, "clearTimers");
  const setSuggestion = /* @__PURE__ */ __name((text) => {
    if (timeoutId) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
    if (!text) {
      applyState(INITIAL_FOLLOWUP_STATE);
      return;
    }
    if (!enabled2) {
      return;
    }
    timeoutId = setTimeout(() => {
      applyState({ suggestion: text, isVisible: true, shownAt: Date.now() });
    }, SUGGESTION_DELAY_MS);
  }, "setSuggestion");
  const accept = /* @__PURE__ */ __name((method, options3) => {
    if (accepting) {
      return;
    }
    if (timeoutId) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
    accepting = true;
    const text = currentState.suggestion;
    const { shownAt } = currentState;
    if (!text) {
      accepting = false;
      return;
    }
    try {
      onOutcome?.({
        outcome: "accepted",
        accept_method: method,
        time_ms: shownAt > 0 ? Date.now() - shownAt : 0,
        suggestion_length: text.length
      });
    } catch (e4) {
      console.error("[followup] onOutcome callback threw:", e4);
    }
    applyState(INITIAL_FOLLOWUP_STATE);
    queueMicrotask(() => {
      try {
        if (!options3?.skipOnAccept) {
          getOnAccept?.()?.(text);
        }
      } catch (error40) {
        console.error("[followup] onAccept callback threw:", error40);
      } finally {
        if (acceptTimeoutId) {
          clearTimeout(acceptTimeoutId);
        }
        acceptTimeoutId = setTimeout(() => {
          accepting = false;
        }, ACCEPT_DEBOUNCE_MS);
      }
    });
  }, "accept");
  const dismiss = /* @__PURE__ */ __name(() => {
    if (timeoutId) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
    if (!currentState.isVisible && !currentState.suggestion) {
      return;
    }
    if (currentState.isVisible && currentState.suggestion) {
      try {
        onOutcome?.({
          outcome: "ignored",
          time_ms: currentState.shownAt > 0 ? Date.now() - currentState.shownAt : 0,
          suggestion_length: currentState.suggestion.length
        });
      } catch (e4) {
        console.error("[followup] onOutcome callback threw:", e4);
      }
    }
    applyState(INITIAL_FOLLOWUP_STATE);
  }, "dismiss");
  const clear = /* @__PURE__ */ __name(() => {
    clearTimers();
    accepting = false;
    applyState(INITIAL_FOLLOWUP_STATE);
  }, "clear");
  const cleanup = /* @__PURE__ */ __name(() => {
    clearTimers();
    accepting = false;
  }, "cleanup");
  return { setSuggestion, accept, dismiss, clear, cleanup };
}
var INITIAL_FOLLOWUP_STATE, SUGGESTION_DELAY_MS, ACCEPT_DEBOUNCE_MS;
var init_followupState = __esm({
  "packages/core/dist/src/followup/followupState.js"() {
    "use strict";
    init_esbuild_shims();
    INITIAL_FOLLOWUP_STATE = Object.freeze({
      suggestion: null,
      isVisible: false,
      shownAt: 0
    });
    SUGGESTION_DELAY_MS = 300;
    ACCEPT_DEBOUNCE_MS = 100;
    __name(createFollowupController, "createFollowupController");
  }
});

// packages/core/dist/src/followup/suggestionGenerator.js
async function generatePromptSuggestion(config2, conversationHistory, abortSignal, options2) {
  const modelTurns = conversationHistory.filter((c4) => c4.role === "model").length;
  if (modelTurns < MIN_ASSISTANT_TURNS) {
    return { suggestion: null, filterReason: "early_conversation" };
  }
  try {
    const cacheSafe = options2?.enableCacheSharing ? getCacheSafeParams() : null;
    const modelOverride = options2?.model;
    debugLogger103.debug(`Generating suggestion: cacheSharing=${!!cacheSafe}, model=${modelOverride || "(default)"}`);
    const raw2 = cacheSafe ? await generateViaForkedQuery(config2, abortSignal, modelOverride) : await generateViaBaseLlm(config2, conversationHistory, abortSignal, modelOverride);
    const suggestion = typeof raw2 === "string" ? raw2.trim() : null;
    if (!suggestion) {
      debugLogger103.debug("Suggestion generation returned empty result");
      return { suggestion: null, filterReason: "empty" };
    }
    const filterReason = getFilterReason(suggestion);
    if (filterReason) {
      debugLogger103.debug(`Suggestion filtered: reason=${filterReason}, text="${suggestion}"`);
      return { suggestion: null, filterReason };
    }
    debugLogger103.debug(`Suggestion accepted: "${suggestion}"`);
    return { suggestion };
  } catch (error40) {
    if (abortSignal.aborted) {
      return { suggestion: null };
    }
    debugLogger103.warn("Suggestion generation failed:", error40);
    return { suggestion: null, filterReason: "error" };
  }
}
async function generateViaForkedQuery(config2, abortSignal, modelOverride) {
  const model = modelOverride || config2.getModel();
  const cacheSafeParams = getCacheSafeParams();
  if (!cacheSafeParams)
    return null;
  const startTime = Date.now();
  const result = await runForkedAgent({
    config: config2,
    userMessage: SUGGESTION_PROMPT,
    cacheSafeParams,
    jsonSchema: SUGGESTION_SCHEMA,
    model
  });
  const durationMs = Date.now() - startTime;
  if (result.usage) {
    reportSuggestionUsage(model, {
      promptTokenCount: result.usage.inputTokens,
      candidatesTokenCount: result.usage.outputTokens,
      totalTokenCount: result.usage.inputTokens + result.usage.outputTokens,
      cachedContentTokenCount: result.usage.cacheHitTokens
    }, durationMs);
  }
  if (result.jsonResult) {
    const raw2 = result.jsonResult["suggestion"];
    return typeof raw2 === "string" ? raw2 : null;
  }
  if (result.text) {
    try {
      const parsed = JSON.parse(result.text);
      const raw2 = parsed["suggestion"];
      return typeof raw2 === "string" ? raw2 : null;
    } catch {
      return result.text;
    }
  }
  return null;
}
async function generateViaBaseLlm(config2, conversationHistory, abortSignal, modelOverride) {
  const model = modelOverride || config2.getModel();
  const contents = [
    ...conversationHistory,
    { role: "user", parts: [{ text: SUGGESTION_PROMPT }] }
  ];
  const generator = config2.getContentGenerator();
  const startTime = Date.now();
  const response = await generator.generateContent({
    model,
    contents,
    config: {
      abortSignal,
      // Disable thinking for suggestion generation — not needed and wastes tokens
      thinkingConfig: { includeThoughts: false }
    }
  }, "prompt_suggestion");
  const durationMs = Date.now() - startTime;
  const usage2 = response.usageMetadata;
  if (usage2) {
    reportSuggestionUsage(model, usage2, durationMs);
  }
  const text = response.candidates?.[0]?.content?.parts?.filter((p2) => !p2["thought"]).map((p2) => p2.text ?? "").join("").trim();
  if (text) {
    try {
      const parsed = JSON.parse(text);
      const s5 = parsed["suggestion"];
      if (typeof s5 === "string")
        return s5;
    } catch {
    }
    return text;
  }
  return null;
}
function getFilterReason(suggestion) {
  const lower3 = suggestion.toLowerCase();
  const wordCount = suggestion.trim().split(/\s+/).length;
  if (lower3 === "done")
    return "done";
  if (lower3 === "nothing found" || lower3 === "nothing found." || lower3.startsWith("nothing to suggest") || lower3.startsWith("no suggestion") || /\bsilence is\b|\bstay(s|ing)? silent\b/.test(lower3) || /^\W*silence\W*$/.test(lower3)) {
    return "meta_text";
  }
  if (/^\(.*\)$|^\[.*\]$/.test(suggestion))
    return "meta_wrapped";
  if (lower3.startsWith("api error:") || lower3.startsWith("prompt is too long") || lower3.startsWith("request timed out") || lower3.startsWith("invalid api key") || lower3.startsWith("image was too large")) {
    return "error_message";
  }
  if (/^\w+:\s/.test(suggestion))
    return "prefixed_label";
  const hasCJK = /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(suggestion);
  if (!hasCJK) {
    if (wordCount < 2) {
      if (suggestion.startsWith("/"))
        return null;
      if (!ALLOWED_SINGLE_WORDS.has(lower3))
        return "too_few_words";
    }
    if (wordCount > 12)
      return "too_many_words";
  } else {
    if (suggestion.length < 2)
      return "too_few_words";
    if (suggestion.length > 30)
      return "too_many_words";
  }
  if (suggestion.length >= 100)
    return "too_long";
  if (/[.!?]\s+[A-Z]/.test(suggestion))
    return "multiple_sentences";
  if (/[\n*]|\*\*/.test(suggestion))
    return "has_formatting";
  if (/\bthanks\b|\bthank you\b|\blooks good\b|\bsounds good\b|\bthat works\b|\bthat worked\b|\bthat's all\b|\bnice\b|\bgreat\b|\bperfect\b|\bmakes sense\b|\bawesome\b|\bexcellent\b/.test(lower3)) {
    return "evaluative";
  }
  if (/^(let me|i'll|i've|i'm|i can|i would|i think|i notice|here's|here is|here are|that's|this is|this will|you can|you should|you could|sure,|of course|certainly)/i.test(suggestion)) {
    return "ai_voice";
  }
  return null;
}
function shouldFilterSuggestion(suggestion) {
  return getFilterReason(suggestion) !== null;
}
function reportSuggestionUsage(model, usage2, durationMs) {
  const event = new ApiResponseEvent("suggestion-" + Date.now(), model, durationMs, "prompt_suggestion", void 0, {
    promptTokenCount: usage2.promptTokenCount ?? 0,
    candidatesTokenCount: usage2.candidatesTokenCount ?? 0,
    totalTokenCount: usage2.totalTokenCount ?? 0,
    cachedContentTokenCount: usage2.cachedContentTokenCount ?? 0,
    thoughtsTokenCount: usage2.thoughtsTokenCount ?? 0
  });
  const uiEvent = Object.assign(event, {
    "event.name": EVENT_API_RESPONSE
  });
  uiTelemetryService.addEvent(uiEvent);
}
var debugLogger103, SUGGESTION_PROMPT, SUGGESTION_SCHEMA, MIN_ASSISTANT_TURNS, ALLOWED_SINGLE_WORDS;
var init_suggestionGenerator = __esm({
  "packages/core/dist/src/followup/suggestionGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_forkedAgent();
    init_uiTelemetry();
    init_types4();
    init_debugLogger();
    debugLogger103 = createDebugLogger("FOLLOWUP");
    SUGGESTION_PROMPT = `[SUGGESTION MODE: Suggest what the user might naturally type next.]

FIRST: Read the LAST FEW LINES of the assistant's most recent message -- that's where
next-step hints, tips, and actionable suggestions usually appear. Then check the user's
recent messages and original request.

Your job is to predict what THEY would type - not what you think they should do.

THE TEST: Would they think "I was just about to type that"?

PRIORITY: If the assistant's last message contains a tip or hint like "Tip: type X to ..."
or "type X to ...", extract X as the suggestion. These are explicit next-step hints.

EXAMPLES:
Assistant says "Tip: type post comments to publish findings" \u2192 "post comments"
Assistant says "type /review to start" \u2192 "/review"
User asked "fix the bug and run tests", bug is fixed \u2192 "run the tests"
After code written \u2192 "try it out"
Model offers options \u2192 suggest the one the user would likely pick, based on conversation
Model asks to continue \u2192 "yes" or "go ahead"
Task complete, obvious follow-up \u2192 "commit this" or "push it"
After error or misunderstanding \u2192 silence (let them assess/correct)

Be specific: "run the tests" beats "continue".

NEVER SUGGEST:
- Evaluative ("looks good", "thanks")
- Questions ("what about...?")
- AI-voice ("Let me...", "I'll...", "Here's...")
- New ideas they didn't ask about
- Multiple sentences

Stay silent if the next step isn't obvious from what the user said.

Format: 2-12 words, match the user's style. Or nothing.

Reply with ONLY the suggestion, no quotes or explanation.`;
    SUGGESTION_SCHEMA = {
      type: "object",
      properties: {
        suggestion: {
          type: "string",
          description: "The predicted next user input (2-12 words), or empty string if nothing obvious."
        }
      },
      required: ["suggestion"]
    };
    MIN_ASSISTANT_TURNS = 2;
    __name(generatePromptSuggestion, "generatePromptSuggestion");
    __name(generateViaForkedQuery, "generateViaForkedQuery");
    __name(generateViaBaseLlm, "generateViaBaseLlm");
    ALLOWED_SINGLE_WORDS = /* @__PURE__ */ new Set([
      "yes",
      "yeah",
      "yep",
      "yea",
      "yup",
      "sure",
      "ok",
      "okay",
      "push",
      "commit",
      "deploy",
      "stop",
      "continue",
      "check",
      "exit",
      "quit",
      "no"
    ]);
    __name(getFilterReason, "getFilterReason");
    __name(shouldFilterSuggestion, "shouldFilterSuggestion");
    __name(reportSuggestionUsage, "reportSuggestionUsage");
  }
});

// packages/core/dist/src/followup/overlayFs.js
import { mkdir as mkdir11, copyFile as copyFile2, rm as rm4 } from "node:fs/promises";
import { existsSync as existsSync20 } from "node:fs";
import { join as join43, dirname as dirname22, relative as relative11, isAbsolute as isAbsolute16 } from "node:path";
import { tmpdir as tmpdir5 } from "node:os";
import { randomUUID as randomUUID12 } from "node:crypto";
var OverlayFs;
var init_overlayFs = __esm({
  "packages/core/dist/src/followup/overlayFs.js"() {
    "use strict";
    init_esbuild_shims();
    OverlayFs = class {
      static {
        __name(this, "OverlayFs");
      }
      realCwd;
      overlayDir;
      writtenFiles = /* @__PURE__ */ new Map();
      // relPath -> overlayPath
      constructor(realCwd) {
        this.realCwd = realCwd;
        const id = randomUUID12().slice(0, 8);
        this.overlayDir = join43(tmpdir5(), "qwen-speculation", String(process.pid), id);
      }
      /** Get the overlay directory path */
      getOverlayDir() {
        return this.overlayDir;
      }
      /**
       * Resolve a read path: return overlay path if the file was previously written,
       * otherwise return the real path.
       */
      resolveReadPath(realPath) {
        const rel = this.toRelative(realPath);
        if (rel && this.writtenFiles.has(rel)) {
          return this.writtenFiles.get(rel);
        }
        return realPath;
      }
      /**
       * Redirect a write to the overlay. On first write to a file, copies the
       * original to the overlay (if it exists). Returns the overlay path to write to.
       */
      async redirectWrite(realPath) {
        const rel = this.toRelative(realPath);
        if (!rel) {
          throw new Error(`Cannot redirect write outside cwd: ${realPath}`);
        }
        if (this.writtenFiles.has(rel)) {
          return this.writtenFiles.get(rel);
        }
        const overlayPath = join43(this.overlayDir, rel);
        await mkdir11(dirname22(overlayPath), { recursive: true });
        const originalPath = join43(this.realCwd, rel);
        if (existsSync20(originalPath)) {
          try {
            await copyFile2(originalPath, overlayPath);
          } catch {
          }
        }
        this.writtenFiles.set(rel, overlayPath);
        return overlayPath;
      }
      /**
       * Get all files that were written to the overlay.
       */
      getWrittenFiles() {
        return new Map(this.writtenFiles);
      }
      /**
       * Copy all overlay files back to the real filesystem.
       * Returns the list of real paths that were updated.
       */
      async applyToReal() {
        const applied = [];
        for (const [rel, overlayPath] of this.writtenFiles) {
          const realPath = join43(this.realCwd, rel);
          try {
            await mkdir11(dirname22(realPath), { recursive: true });
            await copyFile2(overlayPath, realPath);
            applied.push(realPath);
          } catch {
          }
        }
        return applied;
      }
      /**
       * Clean up the overlay directory.
       */
      async cleanup() {
        try {
          await rm4(this.overlayDir, { recursive: true, force: true });
        } catch {
        }
      }
      /**
       * Convert an absolute path to a relative path within cwd.
       * Returns null if the path is outside cwd.
       */
      toRelative(inputPath) {
        const abs = isAbsolute16(inputPath) ? inputPath : join43(this.realCwd, inputPath);
        const rel = relative11(this.realCwd, abs);
        if (isAbsolute16(rel) || rel.startsWith("..")) {
          return null;
        }
        return rel;
      }
    };
  }
});

// packages/core/dist/src/followup/speculationToolGate.js
async function evaluateToolCall(toolName, args2, overlayFs, approvalMode) {
  if (SAFE_READ_ONLY_TOOLS.has(toolName)) {
    await resolveReadPaths(args2, overlayFs);
    return { action: "allow" };
  }
  if (WRITE_TOOLS.has(toolName)) {
    if (approvalMode === ApprovalMode.AUTO_EDIT || approvalMode === ApprovalMode.YOLO) {
      return { action: "redirect", reason: `write_tool:${toolName}` };
    }
    return {
      action: "boundary",
      reason: `write_tool_no_auto:${toolName}`
    };
  }
  if (toolName === ToolNames.SHELL) {
    const command2 = typeof args2["command"] === "string" ? args2["command"] : "";
    if (command2 && await isShellCommandReadOnlyAST(command2)) {
      return { action: "allow" };
    }
    return {
      action: "boundary",
      reason: `shell:${command2.slice(0, 50) || "empty"}`
    };
  }
  if (BOUNDARY_TOOLS.has(toolName)) {
    return { action: "boundary", reason: `denied_tool:${toolName}` };
  }
  return { action: "boundary", reason: `unknown_tool:${toolName}` };
}
async function resolveReadPaths(args2, overlayFs) {
  const pathKeys = ["file_path", "filePath", "path", "notebook_path"];
  for (const key of pathKeys) {
    if (typeof args2[key] === "string") {
      args2[key] = overlayFs.resolveReadPath(args2[key]);
      return;
    }
  }
}
async function rewritePathArgs(args2, overlayFs) {
  const pathKeys = ["file_path", "filePath", "path", "notebook_path"];
  for (const key of pathKeys) {
    if (typeof args2[key] === "string") {
      args2[key] = await overlayFs.redirectWrite(args2[key]);
      return;
    }
  }
}
var SAFE_READ_ONLY_TOOLS, WRITE_TOOLS, BOUNDARY_TOOLS;
var init_speculationToolGate = __esm({
  "packages/core/dist/src/followup/speculationToolGate.js"() {
    "use strict";
    init_esbuild_shims();
    init_tool_names();
    init_shellAstParser();
    init_config3();
    SAFE_READ_ONLY_TOOLS = /* @__PURE__ */ new Set([
      ToolNames.READ_FILE,
      ToolNames.GREP,
      ToolNames.GLOB,
      ToolNames.LS,
      ToolNames.LSP
      // web_fetch and web_search excluded — they require user confirmation
      // for external network requests, which speculation bypasses
    ]);
    WRITE_TOOLS = /* @__PURE__ */ new Set([ToolNames.EDIT, ToolNames.WRITE_FILE]);
    BOUNDARY_TOOLS = /* @__PURE__ */ new Set([
      ToolNames.AGENT,
      ToolNames.SKILL,
      ToolNames.TODO_WRITE,
      ToolNames.MEMORY,
      ToolNames.ASK_USER_QUESTION,
      ToolNames.EXIT_PLAN_MODE,
      ToolNames.WEB_FETCH
    ]);
    __name(evaluateToolCall, "evaluateToolCall");
    __name(resolveReadPaths, "resolveReadPaths");
    __name(rewritePathArgs, "rewritePathArgs");
  }
});

// packages/core/dist/src/followup/speculation.js
async function startSpeculation(config2, suggestion, parentSignal, options2) {
  const cacheSafe = getCacheSafeParams();
  if (!cacheSafe) {
    throw new Error("CacheSafeParams not available for speculation");
  }
  const abortController = new AbortController();
  if (parentSignal?.aborted) {
    return {
      id: Math.random().toString(36).slice(2, 10),
      status: "aborted",
      suggestion,
      overlayFs: null,
      abortController,
      messages: [],
      startTime: Date.now(),
      toolUseCount: 0
    };
  }
  let parentAbortHandler;
  if (parentSignal) {
    parentAbortHandler = /* @__PURE__ */ __name(() => abortController.abort(), "parentAbortHandler");
    parentSignal.addEventListener("abort", parentAbortHandler, { once: true });
  }
  const overlayFs = new OverlayFs(config2.getCwd());
  const startTime = Date.now();
  const state = {
    id: Math.random().toString(36).slice(2, 10),
    status: "running",
    suggestion,
    overlayFs,
    abortController,
    messages: [],
    startTime,
    toolUseCount: 0
  };
  runSpeculativeLoop(config2, state, cacheSafe, options2?.model).then(async (result) => {
    if (abortController.signal.aborted) {
      state.status = "aborted";
      await overlayFs.cleanup();
      return;
    }
    if (state.status === "running") {
      state.messages = result.messages;
      if (result.boundary) {
        state.boundary = result.boundary;
        state.status = "boundary";
      } else {
        state.status = "completed";
        if (!abortController.signal.aborted) {
          try {
            const next = await generatePipelinedSuggestion(config2, suggestion, result.messages, abortController.signal, options2?.model);
            if (next && state.status === "completed") {
              state.pipelinedSuggestion = next;
            }
          } catch {
          }
        }
      }
    }
  }).catch(async () => {
    if (state.status === "running") {
      state.status = "aborted";
    }
    await overlayFs.cleanup();
  }).finally(() => {
    if (parentSignal && parentAbortHandler) {
      parentSignal.removeEventListener("abort", parentAbortHandler);
    }
  });
  return state;
}
async function runSpeculativeLoop(config2, state, cacheSafe, modelOverride) {
  const chat = createForkedChat(config2, cacheSafe);
  const model = modelOverride || cacheSafe.model;
  const approvalMode = config2.getApprovalMode();
  const messages = [];
  const userMsg = {
    role: "user",
    parts: [{ text: state.suggestion }]
  };
  messages.push(userMsg);
  for (let turn = 0; turn < MAX_SPECULATION_TURNS; turn++) {
    if (state.abortController?.signal.aborted)
      break;
    if (messages.length >= MAX_SPECULATION_MESSAGES)
      break;
    const lastUserMsg = messages[messages.length - 1];
    const stream5 = await chat.sendMessageStream(model, { message: lastUserMsg.parts ?? [] }, "speculation");
    const modelParts = [];
    for await (const event of stream5) {
      if (state.abortController?.signal.aborted)
        break;
      if (event.type !== StreamEventType.CHUNK)
        continue;
      const response = event.value;
      const parts2 = response.candidates?.[0]?.content?.parts ?? [];
      for (const part of parts2) {
        if (part.text && !part["thought"]) {
          modelParts.push({ text: part.text });
        }
        if (part.functionCall && part.functionCall.name) {
          modelParts.push({
            functionCall: {
              name: part.functionCall.name,
              args: part.functionCall.args
            }
          });
        }
      }
    }
    if (state.abortController?.signal.aborted)
      break;
    if (modelParts.length === 0)
      break;
    const modelMsg = { role: "model", parts: modelParts };
    messages.push(modelMsg);
    const functionCalls = modelParts.filter((p2) => p2.functionCall !== void 0);
    if (functionCalls.length === 0) {
      break;
    }
    const functionResponses = [];
    let hitBoundary = false;
    for (const part of functionCalls) {
      const fc = part.functionCall;
      const name4 = fc.name ?? "";
      const args2 = fc.args ?? {};
      const gate = await evaluateToolCall(name4, args2, state.overlayFs, approvalMode);
      if (gate.action === "boundary") {
        hitBoundary = true;
        break;
      }
      if (gate.action === "redirect") {
        try {
          await rewritePathArgs(args2, state.overlayFs);
        } catch {
          hitBoundary = true;
          break;
        }
      }
      try {
        const toolRegistry = config2.getToolRegistry();
        const tool = await toolRegistry.ensureTool(name4);
        if (!tool) {
          functionResponses.push({
            functionResponse: {
              name: name4,
              response: { error: `Tool '${name4}' not found` }
            }
          });
          continue;
        }
        const invocation = tool.build(args2);
        const result = await invocation.execute(state.abortController.signal);
        state.toolUseCount++;
        const responseContent = typeof result.llmContent === "string" ? { output: result.llmContent } : { output: JSON.stringify(result.llmContent) };
        functionResponses.push({
          functionResponse: { name: name4, response: responseContent }
        });
      } catch (error40) {
        functionResponses.push({
          functionResponse: {
            name: name4,
            response: {
              error: error40 instanceof Error ? error40.message : "Tool execution failed"
            }
          }
        });
      }
    }
    if (hitBoundary) {
      if (functionResponses.length > 0) {
        let keptFunctionCalls = 0;
        const keptModelParts = modelParts.filter((p2) => {
          if (!p2.functionCall)
            return true;
          if (keptFunctionCalls < functionResponses.length) {
            keptFunctionCalls++;
            return true;
          }
          return false;
        });
        if (keptModelParts.length > 0) {
          messages[messages.length - 1] = {
            role: "model",
            parts: keptModelParts
          };
          messages.push({ role: "user", parts: functionResponses });
        } else {
          messages.pop();
        }
      } else {
        const textOnlyParts = modelParts.filter((p2) => p2.functionCall === void 0);
        if (textOnlyParts.length > 0) {
          messages[messages.length - 1] = {
            role: "model",
            parts: textOnlyParts
          };
        } else {
          messages.pop();
        }
      }
      return {
        messages,
        boundary: {
          type: "boundary",
          detail: "speculation_boundary",
          completedAt: Date.now()
        }
      };
    }
    if (functionResponses.length > 0) {
      const resultMsg = { role: "user", parts: functionResponses };
      messages.push(resultMsg);
    }
  }
  return { messages };
}
async function acceptSpeculation(state, geminiClient) {
  const timeSavedMs = state.boundary ? Math.max(0, state.boundary.completedAt - state.startTime) : Math.max(0, Date.now() - state.startTime);
  try {
    const filesApplied = state.overlayFs ? await state.overlayFs.applyToReal() : [];
    const cleanMessages = ensureToolResultPairing(state.messages);
    for (const msg of cleanMessages) {
      await geminiClient.addHistory(msg);
    }
    state.status = "completed";
    return {
      filesApplied,
      messages: cleanMessages,
      boundary: state.boundary,
      timeSavedMs,
      nextSuggestion: state.pipelinedSuggestion
    };
  } finally {
    if (state.overlayFs) {
      await state.overlayFs.cleanup();
    }
  }
}
async function abortSpeculation(state) {
  state.abortController?.abort();
  state.status = "aborted";
  if (state.overlayFs) {
    await state.overlayFs.cleanup();
  }
}
function ensureToolResultPairing(messages) {
  if (messages.length === 0)
    return messages;
  const result = [...messages];
  const lastMsg = result[result.length - 1];
  if (lastMsg.role === "model" && lastMsg.parts) {
    const hasFunctionCalls = lastMsg.parts.some((p2) => p2.functionCall !== void 0);
    if (hasFunctionCalls) {
      const textParts = lastMsg.parts.filter((p2) => p2.functionCall === void 0);
      if (textParts.length > 0) {
        result[result.length - 1] = { role: "model", parts: textParts };
      } else {
        result.pop();
      }
    }
  }
  return result;
}
async function generatePipelinedSuggestion(config2, suggestionText, speculatedMessages, abortSignal, modelOverride) {
  try {
    const speculatedSummary = speculatedMessages.filter((m3) => m3.role === "model").flatMap((m3) => m3.parts ?? []).map((p2) => p2.text ?? "").filter(Boolean).join("\n").slice(0, 500);
    const augmentedPrompt = `The user just said: "${suggestionText}"
The assistant responded: ${speculatedSummary || "(tool calls executed)"}

${SUGGESTION_PROMPT}`;
    const cacheSafeParams = getCacheSafeParams();
    if (!cacheSafeParams)
      return null;
    const result = await runForkedAgent({
      config: config2,
      userMessage: augmentedPrompt,
      cacheSafeParams,
      jsonSchema: PIPELINED_SCHEMA,
      model: modelOverride,
      abortSignal
    });
    if (abortSignal.aborted)
      return null;
    let raw2 = null;
    if (result.jsonResult) {
      const val = result.jsonResult["suggestion"];
      raw2 = typeof val === "string" ? val.trim() : null;
    } else if (result.text) {
      raw2 = result.text;
    }
    if (!raw2)
      return null;
    if (getFilterReason(raw2))
      return null;
    return raw2;
  } catch {
    return null;
  }
}
var MAX_SPECULATION_TURNS, MAX_SPECULATION_MESSAGES, IDLE_SPECULATION, PIPELINED_SCHEMA;
var init_speculation = __esm({
  "packages/core/dist/src/followup/speculation.js"() {
    "use strict";
    init_esbuild_shims();
    init_geminiChat();
    init_overlayFs();
    init_speculationToolGate();
    init_forkedAgent();
    init_suggestionGenerator();
    MAX_SPECULATION_TURNS = 20;
    MAX_SPECULATION_MESSAGES = 100;
    IDLE_SPECULATION = Object.freeze({
      id: "",
      status: "idle",
      suggestion: "",
      overlayFs: null,
      abortController: null,
      messages: [],
      startTime: 0,
      toolUseCount: 0
    });
    __name(startSpeculation, "startSpeculation");
    __name(runSpeculativeLoop, "runSpeculativeLoop");
    __name(acceptSpeculation, "acceptSpeculation");
    __name(abortSpeculation, "abortSpeculation");
    __name(ensureToolResultPairing, "ensureToolResultPairing");
    PIPELINED_SCHEMA = {
      type: "object",
      properties: {
        suggestion: {
          type: "string",
          description: "The predicted next user input (2-12 words), or empty string."
        }
      },
      required: ["suggestion"]
    };
    __name(generatePipelinedSuggestion, "generatePipelinedSuggestion");
  }
});

// packages/core/dist/src/followup/index.js
var init_followup = __esm({
  "packages/core/dist/src/followup/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_followupState();
    init_suggestionGenerator();
    init_overlayFs();
    init_speculationToolGate();
    init_speculation();
  }
});

// packages/core/dist/src/utils/filesearch/ignore.js
import fs95 from "node:fs";
import path90 from "node:path";
function loadIgnoreRules(options2) {
  const ignorer = new Ignore2();
  if (options2.useGitignore) {
    const gitignorePath = path90.join(options2.projectRoot, ".gitignore");
    if (fs95.existsSync(gitignorePath)) {
      ignorer.add(fs95.readFileSync(gitignorePath, "utf8"));
    }
  }
  if (options2.useQwenignore) {
    const qwenignorePath = path90.join(options2.projectRoot, ".qwenignore");
    if (fs95.existsSync(qwenignorePath)) {
      ignorer.add(fs95.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_picomatch3, 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_picomatch3 = __toESM(require_picomatch2(), 1);
    hasFileExtension = (0, import_picomatch3.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(path150) {
      let normalized2 = (0, path_1.normalize)(path150);
      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(path150, separator) {
      return path150.replace(SLASHES_REGEX, separator);
    }
    __name(convertSlashes, "convertSlashes");
    exports2.convertSlashes = convertSlashes;
    var WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
    function isRootDirectory(path150) {
      return path150 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path150);
    }
    __name(isRootDirectory, "isRootDirectory");
    exports2.isRootDirectory = isRootDirectory;
    function normalizePath2(path150, options2) {
      const { resolvePaths, normalizePath: normalizePath3, pathSeparator } = options2;
      const pathNeedsCleaning = process.platform === "win32" && path150.includes("/") || path150.startsWith(".");
      if (resolvePaths)
        path150 = (0, path_1.resolve)(path150);
      if (normalizePath3 || pathNeedsCleaning)
        path150 = cleanPath(path150);
      if (path150 === ".")
        return "";
      const needsSeperator = path150[path150.length - 1] !== pathSeparator;
      return convertSlashes(needsSeperator ? path150 + pathSeparator : path150, 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((filter5) => filter5(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 path150 = directoryPath || ".";
      if (filters.every((filter5) => filter5(path150, true))) {
        paths.push(path150);
      }
    }, "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((filter5) => filter5(filename, false)))
        counts.files++;
    }, "pushFileFilterAndCount");
    var pushFileFilter = /* @__PURE__ */ __name((filename, paths, _counts, filters) => {
      if (filters.every((filter5) => filter5(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(path150, state, callback) {
      const { queue, options: { suppressErrors } } = state;
      queue.enqueue();
      fs_1.default.realpath(path150, (error40, resolvedPath) => {
        if (error40)
          return queue.dequeue(suppressErrors ? null : error40, state);
        fs_1.default.stat(resolvedPath, (error41, stat14) => {
          if (error41)
            return queue.dequeue(suppressErrors ? null : error41, state);
          if (stat14.isDirectory() && isRecursive(path150, resolvedPath, state))
            return queue.dequeue(null, state);
          callback(stat14, resolvedPath);
          queue.dequeue(null, state);
        });
      });
    }, "resolveSymlinksAsync");
    var resolveSymlinks = /* @__PURE__ */ __name(function(path150, state, callback) {
      const { queue, options: { suppressErrors } } = state;
      queue.enqueue();
      try {
        const resolvedPath = fs_1.default.realpathSync(path150);
        const stat14 = fs_1.default.statSync(resolvedPath);
        if (stat14.isDirectory() && isRecursive(path150, resolvedPath, state))
          return;
        callback(stat14, 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(path150, resolved, state) {
      if (state.options.useRealPaths)
        return isRecursiveUsingRealPaths(resolved, state);
      let parent = (0, path_1.dirname)(path150);
      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(path150, 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, error40, callback) => {
      report(error40, callback, state.counts, state.options.suppressErrors);
      return null;
    }, "onlyCountsAsync");
    var defaultAsync = /* @__PURE__ */ __name((state, error40, callback) => {
      report(error40, callback, state.paths, state.options.suppressErrors);
      return null;
    }, "defaultAsync");
    var limitFilesAsync = /* @__PURE__ */ __name((state, error40, callback) => {
      report(error40, callback, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
      return null;
    }, "limitFilesAsync");
    var groupsAsync = /* @__PURE__ */ __name((state, error40, callback) => {
      report(error40, callback, state.groups, state.options.suppressErrors);
      return null;
    }, "groupsAsync");
    function report(error40, callback, output, suppressErrors) {
      if (error40 && !suppressErrors)
        callback(error40, 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, (error40, entries = []) => {
        callback(entries, directoryPath, currentDepth);
        state.queue.dequeue(state.options.suppressErrors ? null : error40, 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(error40, output) {
        if (this.onQueueEmpty && (--this.count <= 0 || error40)) {
          this.onQueueEmpty(error40, output);
          if (error40) {
            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((error40, state) => this.callbackInvoker(state, error40, 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 i4 = 0; i4 < entries.length; ++i4) {
          const entry = entries[i4];
          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 path150 = joinPath.joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
            if (exclude && exclude(entry.name, path150))
              continue;
            this.pushDirectory(path150, paths, filters);
            this.walkDirectory(this.state, path150, path150, depth - 1, this.walk);
          } else if (this.resolveSymlink && entry.isSymbolicLink()) {
            let path150 = joinPath.joinPathWithBasePath(entry.name, directoryPath);
            this.resolveSymlink(path150, this.state, (stat14, resolvedPath) => {
              if (stat14.isDirectory()) {
                resolvedPath = (0, utils_1.normalizePath)(resolvedPath, this.state.options);
                if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path150 + pathSeparator))
                  return;
                this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path150 + pathSeparator, depth - 1, this.walk);
              } else {
                resolvedPath = useRealPaths ? resolvedPath : path150;
                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 promise2(root, options2) {
      return new Promise((resolve42, reject) => {
        callback(root, options2, (err2, output) => {
          if (err2)
            return reject(err2);
          resolve42(output);
        });
      });
    }
    __name(promise2, "promise");
    exports2.promise = promise2;
    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((path150) => isMatch(path150));
        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_dist8 = __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 crypto13 from "node:crypto";
var crawlCache, cacheTimers, getCacheKey, read2, write2;
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, maxFiles) => {
      const hash = crypto13.createHash("sha256");
      hash.update(directory);
      hash.update(ignoreContent);
      if (maxDepth !== void 0) {
        hash.update(String(maxDepth));
      }
      if (maxFiles !== void 0) {
        hash.update(`maxFiles:${maxFiles}`);
      }
      return hash.digest("hex");
    }, "getCacheKey");
    read2 = /* @__PURE__ */ __name((key) => crawlCache.get(key), "read");
    write2 = /* @__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 path91 from "node:path";
function toPosixPath2(p2) {
  return p2.split(path91.sep).join(path91.posix.sep);
}
async function crawl(options2) {
  if (options2.cache) {
    const cacheKey = getCacheKey(options2.crawlDirectory, options2.ignore.getFingerprint(), options2.maxDepth, options2.maxFiles);
    const cachedResults = read2(cacheKey);
    if (cachedResults) {
      return cachedResults;
    }
  }
  const posixCwd = toPosixPath2(options2.cwd);
  const posixCrawlDirectory = toPosixPath2(options2.crawlDirectory);
  const relativeToCrawlDir = path91.posix.relative(posixCwd, posixCrawlDirectory);
  let results;
  try {
    const dirFilter = options2.ignore.getDirectoryFilter();
    const fileFilter = options2.ignore.getFileFilter();
    const api = new import_fdir.fdir().withRelativePaths().withDirs().withPathSeparator("/").exclude((_2, dirPath) => {
      const relativePath = path91.posix.relative(posixCrawlDirectory, dirPath);
      return dirFilter(`${relativePath}/`);
    }).filter((filePath, isDirectory) => {
      if (isDirectory)
        return true;
      const cwdRelative = path91.posix.join(relativeToCrawlDir, filePath);
      return !fileFilter(cwdRelative);
    });
    if (options2.maxDepth !== void 0) {
      api.withMaxDepth(options2.maxDepth);
    }
    if (options2.maxFiles !== void 0) {
      api.withMaxFiles(options2.maxFiles);
    }
    results = await api.crawl(options2.crawlDirectory).withPromise();
  } catch (_e2) {
    return [];
  }
  const relativeToCwdResults = results.map((p2) => path91.posix.join(relativeToCrawlDir, p2));
  if (options2.cache) {
    const cacheKey = getCacheKey(options2.crawlDirectory, options2.ignore.getFingerprint(), options2.maxDepth, options2.maxFiles);
    write2(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_dist8(), 1);
    init_crawlCache();
    __name(toPosixPath2, "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, normalize13, 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 (normalize13) {
      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 i4 = 0, len = this.runesList.length; i4 < len; ++i4) {
    iter2(i4);
  }
  return getResultFromScoreMap(scoreMap, this.opts.limit);
}
function asyncMatcher(token2, len, iter2, onFinish) {
  return new Promise((resolve42, reject) => {
    const INCREMENT = 1e3;
    let i4 = 0, end = Math.min(INCREMENT, len);
    const step = /* @__PURE__ */ __name(() => {
      if (token2.cancelled)
        return reject("search cancelled");
      for (; i4 < end; ++i4) {
        iter2(i4);
      }
      if (end < len) {
        end = Math.min(end + INCREMENT, len);
        isNode ? setImmediate(step) : setTimeout(step);
      } else {
        resolve42(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 i4 = "\u0300".codePointAt(0); i4 <= "\u036F".codePointAt(0); ++i4) {
      const diacritic = String.fromCodePoint(i4);
      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 i4 = ranges[lowerChar][0]; i4 <= ranges[lowerChar][1]; ++i4) {
        normalized[i4] = i4 % 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, normalize13, 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, normalize13, 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 i4 = 0; i4 < T2.length; i4++) {
        T2[i4] = input[i4];
      }
      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 (normalize13) {
            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 [i4, v2] of toCopy.entries()) {
          H2[i4] = v2;
        }
      }
      let [, C3] = alloc16(offset16, slab2, width * M2);
      {
        const toCopy = C0.subarray(f0, lastIdx + 1);
        for (const [i4, v2] of toCopy.entries()) {
          C3[i4] = 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 = C3.subarray(row + f5 - f0).subarray(0, Tsub2.length), Cdiag = C3.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 i4 = M2 - 1;
        j2 = maxScorePos;
        let preferMatch = true;
        while (true) {
          const I3 = i4 * width, j0 = j2 - f0, s5 = H2[I3 + j0];
          let s1 = 0, s22 = 0;
          if (i4 > 0 && j2 >= F4[i4]) {
            s1 = H2[I3 - width + j0 - 1];
          }
          if (j2 > F4[i4]) {
            s22 = H2[I3 + j0 - 1];
          }
          if (s5 > s1 && (s5 > s22 || s5 === s22 && preferMatch)) {
            pos2.add(j2);
            if (i4 === 0) {
              break;
            }
            i4--;
          }
          preferMatch = C3[I3 + j0] > 1 || I3 + width + j0 + 1 < C3.length && C3[I3 + width + j0 + 1] > 0;
          j2--;
        }
      }
      return [{ start: j2, end: maxScorePos + 1, score: maxScore }, pos2];
    }, "fuzzyMatchV2");
    __name(calculateScore, "calculateScore");
    fuzzyMatchV1 = /* @__PURE__ */ __name((caseSensitive, normalize13, 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 (normalize13) {
          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,
          normalize13,
          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, normalize13, 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 (normalize13) {
          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, normalize13, 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, normalize13) => {
      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 (normalize13) {
        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 path92 from "node:path";
async function filter3(allPaths, pattern, signal) {
  const patternFilter = (0, import_picomatch4.default)(pattern, {
    dot: true,
    contains: true,
    nocase: true
  });
  const results = [];
  for (const [i4, p2] of allPaths.entries()) {
    if (i4 % 1e3 === 0) {
      await new Promise((resolve42) => setImmediate(resolve42));
      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_picomatch4, MAX_CRAWL_FILES, AbortError2, RecursiveFileSearch, DirectoryFileSearch, FileSearchFactory;
var init_fileSearch = __esm({
  "packages/core/dist/src/utils/filesearch/fileSearch.js"() {
    "use strict";
    init_esbuild_shims();
    import_picomatch4 = __toESM(require_picomatch2(), 1);
    init_ignore2();
    init_result_cache();
    init_crawler();
    init_fzf_es();
    init_paths();
    MAX_CRAWL_FILES = 1e5;
    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,
          maxFiles: MAX_CRAWL_FILES
        });
        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 [i4, candidate] of filteredCandidates.entries()) {
          if (i4 % 1e3 === 0) {
            await new Promise((resolve42) => setImmediate(resolve42));
            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 : path92.dirname(pattern);
        const results = await crawl({
          crawlDirectory: path92.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/pathReader.js
import { promises as fs96 } from "node:fs";
import path93 from "node:path";
async function readPathFromWorkspace(pathStr, config2) {
  const workspace = config2.getWorkspaceContext();
  const fileService = config2.getFileService();
  let absolutePath = null;
  if (path93.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 = path93.resolve(dir, pathStr);
      try {
        await fs96.access(potentialPath);
        absolutePath = potentialPath;
        break;
      } catch {
      }
    }
  }
  if (!absolutePath) {
    throw new Error(`Path not found in workspace: ${pathStr}`);
  }
  const stats = await fs96.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) => path93.relative(config2.getTargetDir(), p2));
    const filteringOptions = config2.getFileFilteringOptions();
    const filteredFiles = fileService.filterFiles(relativeFiles, {
      respectGitIgnore: filteringOptions.respectGitIgnore,
      respectQwenIgnore: filteringOptions.respectQwenIgnore
    });
    const finalFiles = filteredFiles.map((p2) => path93.resolve(config2.getTargetDir(), p2));
    for (const filePath of finalFiles) {
      const relativePathForDisplay = path93.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 = path93.relative(config2.getTargetDir(), absolutePath);
    const singleFileFilteringOptions = config2.getFileFilteringOptions();
    const filtered = fileService.filterFiles([relativePath], {
      respectGitIgnore: singleFileFilteringOptions.respectGitIgnore,
      respectQwenIgnore: singleFileFilteringOptions.respectQwenIgnore
    });
    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_esm13();
    init_fileUtils();
    __name(readPathFromWorkspace, "readPathFromWorkspace");
  }
});

// packages/core/dist/src/utils/projectSummary.js
import * as fs97 from "fs/promises";
import * as path94 from "path";
function getProjectSummaryPath() {
  return path94.join(process.cwd(), ".qwen", PROJECT_SUMMARY_FILENAME);
}
function getWelcomeBackStatePath() {
  return path94.join(process.cwd(), ".qwen", WELCOME_BACK_STATE_FILENAME);
}
function buildSummaryFingerprint(stat14) {
  return `${stat14.mtimeMs}:${stat14.size}`;
}
async function getWelcomeBackState() {
  try {
    const raw2 = await fs97.readFile(getWelcomeBackStatePath(), "utf-8");
    const parsed = JSON.parse(raw2);
    if (parsed.version !== 1 || parsed.lastChoice !== "restart" || typeof parsed.summaryFingerprint !== "string") {
      return null;
    }
    return {
      lastChoice: parsed.lastChoice,
      summaryFingerprint: parsed.summaryFingerprint
    };
  } catch {
    return null;
  }
}
async function saveWelcomeBackRestartChoice(summaryFingerprint) {
  const statePath = getWelcomeBackStatePath();
  await fs97.mkdir(path94.dirname(statePath), { recursive: true });
  const state = {
    version: 1,
    lastChoice: "restart",
    summaryFingerprint
  };
  await fs97.writeFile(statePath, JSON.stringify(state, null, 2), "utf-8");
}
async function clearWelcomeBackState() {
  try {
    await fs97.rm(getWelcomeBackStatePath(), { force: true });
  } catch {
  }
}
async function getProjectSummaryInfo() {
  const summaryPath = getProjectSummaryPath();
  try {
    await fs97.access(summaryPath);
  } catch {
    return {
      hasHistory: false
    };
  }
  try {
    const summaryStat = await fs97.stat(summaryPath);
    const content = await fs97.readFile(summaryPath, "utf-8");
    const summaryFingerprint = buildSummaryFingerprint(summaryStat);
    const timestampMatch = content.match(/\*\*Update time\*\*: (.+)/);
    const timestamp = timestampMatch ? timestampMatch[1] : (/* @__PURE__ */ new Date()).toISOString();
    const getTimeAgo = /* @__PURE__ */ __name((timestamp2) => {
      const date5 = new Date(timestamp2);
      const now = /* @__PURE__ */ new Date();
      const diffMs = now.getTime() - date5.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,
      summaryFingerprint
    };
  } catch (_error) {
    return {
      hasHistory: false
    };
  }
}
var PROJECT_SUMMARY_FILENAME, WELCOME_BACK_STATE_FILENAME;
var init_projectSummary = __esm({
  "packages/core/dist/src/utils/projectSummary.js"() {
    "use strict";
    init_esbuild_shims();
    PROJECT_SUMMARY_FILENAME = "PROJECT_SUMMARY.md";
    WELCOME_BACK_STATE_FILENAME = "welcome-back-state.json";
    __name(getProjectSummaryPath, "getProjectSummaryPath");
    __name(getWelcomeBackStatePath, "getWelcomeBackStatePath");
    __name(buildSummaryFingerprint, "buildSummaryFingerprint");
    __name(getWelcomeBackState, "getWelcomeBackState");
    __name(saveWelcomeBackRestartChoice, "saveWelcomeBackRestartChoice");
    __name(clearWelcomeBackState, "clearWelcomeBackState");
    __name(getProjectSummaryInfo, "getProjectSummaryInfo");
  }
});

// packages/core/dist/src/utils/readManyFiles.js
import * as fs98 from "node:fs";
import * as path95 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 = path95.resolve(projectRoot, normalizedPattern);
      const stats = fs98.existsSync(fullPath) ? fs98.statSync(fullPath) : null;
      if (stats?.isDirectory()) {
        const { contentParts: dirParts, info: info2 } = await readDirectory(config2, fullPath);
        contentParts.push(...dirParts);
        files.push(info2);
        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 (error40) {
    const errorMessage = `Error during file search: ${getErrorMessage(error40)}`;
    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);
    const prefixText = { text: `
Content from ${filePath}:
` };
    if (fileReadResult.error) {
      const errorText = typeof fileReadResult.llmContent === "string" ? fileReadResult.llmContent : `Failed to read ${filePath}: ${fileReadResult.error}`;
      return {
        contentParts: [prefixText, { text: errorText }],
        info: {
          filePath,
          content: errorText,
          isDirectory: false,
          error: fileReadResult.error
        }
      };
    }
    if (typeof fileReadResult.llmContent === "string") {
      let fileContentForLlm = "";
      if (fileReadResult.isTruncated) {
        const [start2, end] = fileReadResult.linesShown;
        const total = fileReadResult.originalLineCount;
        fileContentForLlm = `Showing lines ${start2}-${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/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 }] }];
  try {
    return await runSideQuery(config2, {
      contents,
      schema: RESPONSE_SCHEMA3,
      abortSignal,
      systemInstruction: SYSTEM_PROMPT,
      purpose: "subagent-generator",
      validate: /* @__PURE__ */ __name((response) => !response.name || !response.description || !response.systemPrompt ? "Invalid response from LLM: missing required fields" : null, "validate")
    });
  } catch (error40) {
    if (error40 instanceof Error && (error40.message.startsWith("Invalid side query response:") || error40.message === "Value of params must be an object")) {
      throw new Error("Invalid response from LLM: missing required fields");
    }
    throw error40;
  }
}
var SYSTEM_PROMPT, createUserPrompt, RESPONSE_SCHEMA3;
var init_subagentGenerator = __esm({
  "packages/core/dist/src/utils/subagentGenerator.js"() {
    "use strict";
    init_esbuild_shims();
    init_sideQuery();
    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 Agent 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 Agent 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_SCHEMA3 = {
      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/test-utils/config.js
function makeFakeConfig(config2 = {
  ...DEFAULT_CONFIG_PARAMETERS
}) {
  return new Config({
    ...DEFAULT_CONFIG_PARAMETERS,
    ...config2
  });
}
var DEFAULT_CONFIG_PARAMETERS;
var init_config4 = __esm({
  "packages/core/dist/src/test-utils/config.js"() {
    "use strict";
    init_esbuild_shims();
    init_config3();
    DEFAULT_CONFIG_PARAMETERS = {
      usageStatisticsEnabled: true,
      debugMode: false,
      proxy: void 0,
      model: "qwen-9001-super-duper",
      targetDir: "/",
      cwd: "/"
    };
    __name(makeFakeConfig, "makeFakeConfig");
  }
});

// packages/core/dist/src/test-utils/mock-tool.js
var MockToolInvocation, MockTool, MOCK_TOOL_GET_DEFAULT_PERMISSION, MOCK_TOOL_GET_CONFIRMATION_DETAILS, MockModifiableToolInvocation, MockModifiableTool;
var init_mock_tool = __esm({
  "packages/core/dist/src/test-utils/mock-tool.js"() {
    "use strict";
    init_esbuild_shims();
    init_tools();
    MockToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "MockToolInvocation");
      }
      tool;
      constructor(tool, params) {
        super(params);
        this.tool = tool;
      }
      execute(signal, updateOutput2) {
        if (updateOutput2) {
          return this.tool.execute(this.params, signal, updateOutput2);
        } else {
          return this.tool.execute(this.params);
        }
      }
      getDefaultPermission() {
        return this.tool.getDefaultPermission();
      }
      getConfirmationDetails(abortSignal) {
        return this.tool.getConfirmationDetails(abortSignal);
      }
      getDescription() {
        return `A mock tool invocation for ${this.tool.name}`;
      }
    };
    MockTool = class extends BaseDeclarativeTool {
      static {
        __name(this, "MockTool");
      }
      getDefaultPermission;
      getConfirmationDetails;
      execute;
      constructor(options2) {
        super(options2.name, options2.displayName ?? options2.name, options2.description ?? options2.name, options2.kind ?? Kind.Other, options2.params, options2.isOutputMarkdown ?? false, options2.canUpdateOutput ?? false);
        if (options2.getDefaultPermission) {
          this.getDefaultPermission = options2.getDefaultPermission;
        } else {
          this.getDefaultPermission = () => Promise.resolve("allow");
        }
        if (options2.getConfirmationDetails) {
          this.getConfirmationDetails = options2.getConfirmationDetails;
        } else {
          this.getConfirmationDetails = () => {
            throw new Error(`${this.name} returned 'ask' from getDefaultPermission() but does not implement getConfirmationDetails().`);
          };
        }
        if (options2.execute) {
          this.execute = options2.execute;
        } else {
          this.execute = () => Promise.resolve({
            llmContent: `Tool ${this.name} executed successfully.`,
            returnDisplay: `Tool ${this.name} executed successfully.`
          });
        }
      }
      createInvocation(params) {
        return new MockToolInvocation(this, params);
      }
    };
    MOCK_TOOL_GET_DEFAULT_PERMISSION = /* @__PURE__ */ __name(() => Promise.resolve("ask"), "MOCK_TOOL_GET_DEFAULT_PERMISSION");
    MOCK_TOOL_GET_CONFIRMATION_DETAILS = /* @__PURE__ */ __name(() => Promise.resolve({
      type: "exec",
      title: "Confirm mockTool",
      command: "mockTool",
      rootCommand: "mockTool",
      onConfirm: /* @__PURE__ */ __name(async () => {
      }, "onConfirm")
    }), "MOCK_TOOL_GET_CONFIRMATION_DETAILS");
    MockModifiableToolInvocation = class extends BaseToolInvocation {
      static {
        __name(this, "MockModifiableToolInvocation");
      }
      tool;
      constructor(tool, params) {
        super(params);
        this.tool = tool;
      }
      async execute(_abortSignal) {
        const result = this.tool.executeFn(this.params);
        return result ?? {
          llmContent: `Tool ${this.tool.name} executed successfully.`,
          returnDisplay: `Tool ${this.tool.name} executed successfully.`
        };
      }
      async getDefaultPermission() {
        return this.tool.shouldConfirm ? "ask" : "allow";
      }
      async getConfirmationDetails(_abortSignal) {
        return {
          type: "edit",
          title: "Confirm Mock Tool",
          fileName: "test.txt",
          filePath: "test.txt",
          fileDiff: "diff",
          originalContent: "originalContent",
          newContent: "newContent",
          onConfirm: /* @__PURE__ */ __name(async () => {
          }, "onConfirm")
        };
      }
      getDescription() {
        return `A mock modifiable tool invocation for ${this.tool.name}`;
      }
    };
    MockModifiableTool = class extends BaseDeclarativeTool {
      static {
        __name(this, "MockModifiableTool");
      }
      // Should be overrided in test file. Functionality will be updated in follow
      // up PR which has MockModifiableTool expect MockTool
      executeFn = /* @__PURE__ */ __name(() => void 0, "executeFn");
      shouldConfirm = true;
      constructor(name4 = "mockModifiableTool") {
        super(name4, name4, "A mock modifiable tool for testing.", Kind.Other, {
          type: "object",
          properties: { param: { type: "string" } }
        });
      }
      getModifyContext(_abortSignal) {
        return {
          getFilePath: /* @__PURE__ */ __name(() => "test.txt", "getFilePath"),
          getCurrentContent: /* @__PURE__ */ __name(async () => "old content", "getCurrentContent"),
          getProposedContent: /* @__PURE__ */ __name(async () => "new content", "getProposedContent"),
          createUpdatedParams: /* @__PURE__ */ __name((_oldContent, modifiedProposedContent, _originalParams) => ({ newContent: modifiedProposedContent }), "createUpdatedParams")
        };
      }
      createInvocation(params) {
        return new MockModifiableToolInvocation(this, params);
      }
    };
  }
});

// packages/core/dist/src/test-utils/file-system-test-helpers.js
import * as fs99 from "node:fs/promises";
import * as path96 from "node:path";
import * as os31 from "node:os";
async function create2(dir, structure) {
  for (const [name4, content] of Object.entries(structure)) {
    const newPath = path96.join(dir, name4);
    if (typeof content === "string") {
      await fs99.writeFile(newPath, content);
    } else if (Array.isArray(content)) {
      await fs99.mkdir(newPath, { recursive: true });
      for (const item of content) {
        if (typeof item === "string") {
          await fs99.writeFile(path96.join(newPath, item), "");
        } else {
          await create2(newPath, item);
        }
      }
    } else if (typeof content === "object" && content !== null) {
      await fs99.mkdir(newPath, { recursive: true });
      await create2(newPath, content);
    }
  }
}
async function createTmpDir(structure) {
  const tmpDir = await fs99.mkdtemp(path96.join(os31.tmpdir(), "gemini-cli-test-"));
  await create2(tmpDir, structure);
  return tmpDir;
}
async function cleanupTmpDir(dir) {
  await fs99.rm(dir, { recursive: true, force: true });
}
var init_file_system_test_helpers = __esm({
  "packages/core/dist/src/test-utils/file-system-test-helpers.js"() {
    "use strict";
    init_esbuild_shims();
    __name(create2, "create");
    __name(createTmpDir, "createTmpDir");
    __name(cleanupTmpDir, "cleanupTmpDir");
  }
});

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

// 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_permissions2();
    init_models();
    init_models5();
    init_codingPlan();
    init_json_formatter();
    init_types13();
    init_client4();
    init_contentGenerator();
    init_coreToolScheduler();
    init_permission_helpers();
    init_geminiChat();
    init_geminiRequest();
    init_insightProtocol();
    init_logger();
    init_nonInteractiveToolExecutor();
    init_prompts();
    init_tokenLimits();
    init_turn();
    init_tool_names();
    init_tool_error();
    init_tool_registry();
    init_tools();
    init_mcp_client();
    init_mcp_client_manager();
    init_mcp_tool();
    init_read_file();
    init_ripGrep();
    init_sdk_control_client_transport();
    init_modifiable_tool();
    init_skill_utils();
    init_chatRecordingService();
    init_cronScheduler();
    init_fileDiscoveryService();
    init_fileSystemService();
    init_gitService();
    init_gitWorktreeService();
    init_sessionRecap();
    init_sessionService();
    init_sessionTitle();
    init_terminalSafe();
    init_shellExecutionService();
    init_backgroundShellRegistry();
    init_toolUseSummary();
    init_bareMode();
    init_manager();
    init_types17();
    init_paths2();
    init_store();
    init_const();
    init_ide_client();
    init_ideContext();
    init_ide_installer();
    init_detect_ide();
    init_constants4();
    init_types10();
    init_constants8();
    init_LspConfigLoader();
    init_LspConnectionFactory();
    init_LspResponseNormalizer();
    init_LspServerManager();
    init_NativeLspClient();
    init_NativeLspService();
    init_types19();
    init_oauth_provider();
    init_oauth_token_storage();
    init_keychain_token_storage();
    init_oauth_utils();
    init_qwen_logger();
    init_telemetry();
    init_loggers();
    init_types4();
    init_extension();
    init_mcp_prompts();
    init_skills();
    init_subagents();
    init_agents();
    init_followup();
    init_browser();
    init_configResolver();
    init_debugLogger();
    init_editor();
    init_environmentContext();
    init_errorParsing();
    init_errors();
    init_fileUtils();
    init_fileSearch();
    init_formatters();
    init_generateContentResponseUtilities();
    init_getFolderStructure();
    init_gitIgnoreParser();
    init_gitUtils();
    init_ignorePatterns();
    init_jsonl_utils();
    init_memoryDiscovery();
    init_rulesDiscovery();
    init_openaiLogger();
    init_partUtils();
    init_sessionStorageUtils();
    init_pathReader();
    init_paths();
    init_projectSummary();
    init_promptIdContext();
    init_proxyUtils();
    init_quotaErrorDetection();
    init_rateLimit();
    init_readManyFiles();
    init_supportedImageFormats();
    init_textTokenizer();
    init_retry();
    init_ripgrepUtils();
    init_runtimeFetchOptions();
    init_schemaValidator();
    init_shell_utils();
    init_subagentGenerator();
    init_symlink();
    init_systemEncoding();
    init_terminalSerializer();
    init_textUtils();
    init_thoughtUtils();
    init_toml_to_markdown_converter();
    init_tool_utils();
    init_workspaceContext();
    init_yaml_parser();
    init_forkedAgent();
    init_sideQuery();
    init_qwenOAuth2();
    init_types8();
    init_message_bus();
    init_config4();
    init_test_utils();
    init_types6();
    init_hooks();
    init_types6();
    init_toolHookTriggers();
  }
});

// packages/core/dist/index.js
var dist_exports = {};
__export(dist_exports, {
  AGENT_CONTEXT_FILENAME: () => AGENT_CONTEXT_FILENAME,
  APPROVAL_MODES: () => APPROVAL_MODES,
  APPROVAL_MODE_INFO: () => APPROVAL_MODE_INFO,
  ARENA_MAX_AGENTS: () => ARENA_MAX_AGENTS,
  AUTO_MEMORY_CONSOLIDATION_LOCK_FILENAME: () => AUTO_MEMORY_CONSOLIDATION_LOCK_FILENAME,
  AUTO_MEMORY_DIRNAME: () => AUTO_MEMORY_DIRNAME,
  AUTO_MEMORY_EXTRACT_CURSOR_FILENAME: () => AUTO_MEMORY_EXTRACT_CURSOR_FILENAME,
  AUTO_MEMORY_INDEX_FILENAME: () => AUTO_MEMORY_INDEX_FILENAME,
  AUTO_MEMORY_METADATA_FILENAME: () => AUTO_MEMORY_METADATA_FILENAME,
  AUTO_MEMORY_SCHEMA_VERSION: () => AUTO_MEMORY_SCHEMA_VERSION,
  AUTO_MEMORY_TYPES: () => AUTO_MEMORY_TYPES,
  AbortError: () => AbortError2,
  AgentCore: () => AgentCore,
  AgentEventEmitter: () => AgentEventEmitter,
  AgentEventType: () => AgentEventType,
  AgentHeadless: () => AgentHeadless,
  AgentInteractive: () => AgentInteractive,
  AgentStatistics: () => AgentStatistics,
  AgentStatus: () => AgentStatus,
  AgentTerminateMode: () => AgentTerminateMode,
  AgentType: () => AgentType,
  ApiCancelEvent: () => ApiCancelEvent,
  ApiErrorEvent: () => ApiErrorEvent,
  ApiRequestEvent: () => ApiRequestEvent,
  ApiRequestPhase: () => ApiRequestPhase,
  ApiResponseEvent: () => ApiResponseEvent,
  ApprovalMode: () => ApprovalMode,
  ArenaAgentClient: () => ArenaAgentClient,
  ArenaEventEmitter: () => ArenaEventEmitter,
  ArenaEventType: () => ArenaEventType,
  ArenaManager: () => ArenaManager,
  ArenaSessionStatus: () => ArenaSessionStatus,
  AsyncMessageQueue: () => AsyncMessageQueue,
  AuthEvent: () => AuthEvent,
  AuthProviderType: () => AuthProviderType,
  AuthType: () => AuthType2,
  BASELINE_COMMIT_MESSAGE: () => BASELINE_COMMIT_MESSAGE,
  BINARY_EXTENSIONS: () => BINARY_EXTENSIONS,
  BINARY_FILE_PATTERNS: () => BINARY_FILE_PATTERNS,
  BackgroundShellRegistry: () => BackgroundShellRegistry,
  BackgroundTaskRegistry: () => BackgroundTaskRegistry,
  BadRequestError: () => BadRequestError,
  BaseDeclarativeTool: () => BaseDeclarativeTool,
  BaseToolInvocation: () => BaseToolInvocation,
  BuiltinAgentRegistry: () => BuiltinAgentRegistry,
  CAPPED_DEFAULT_MAX_TOKENS: () => CAPPED_DEFAULT_MAX_TOKENS,
  CODE_ACTION_KIND_LABELS: () => CODE_ACTION_KIND_LABELS,
  CODING_PLAN_ENV_KEY: () => CODING_PLAN_ENV_KEY,
  COMMON_DIRECTORY_EXCLUDES: () => COMMON_DIRECTORY_EXCLUDES,
  COMMON_IGNORE_PATTERNS: () => COMMON_IGNORE_PATTERNS,
  CONCURRENCY_SAFE_KINDS: () => CONCURRENCY_SAFE_KINDS,
  ChatRecordingService: () => ChatRecordingService,
  CloseDiffRequestSchema: () => CloseDiffRequestSchema,
  CodingPlanRegion: () => CodingPlanRegion,
  ColorMode: () => ColorMode,
  CompressionStatus: () => CompressionStatus,
  ConditionalRulesRegistry: () => ConditionalRulesRegistry,
  Config: () => Config,
  ContextState: () => ContextState,
  ConversationFinishedEvent: () => ConversationFinishedEvent,
  CoreToolScheduler: () => CoreToolScheduler,
  CredentialsClearRequiredError: () => CredentialsClearRequiredError,
  CronScheduler: () => CronScheduler,
  DEFAULT_AUTO_DREAM_MIN_HOURS: () => DEFAULT_AUTO_DREAM_MIN_HOURS,
  DEFAULT_AUTO_DREAM_MIN_SESSIONS: () => DEFAULT_AUTO_DREAM_MIN_SESSIONS,
  DEFAULT_CONTEXT_FILENAME: () => DEFAULT_CONTEXT_FILENAME,
  DEFAULT_ENCODING: () => DEFAULT_ENCODING,
  DEFAULT_FILE_EXCLUDES: () => DEFAULT_FILE_EXCLUDES,
  DEFAULT_FILE_FILTERING_OPTIONS: () => DEFAULT_FILE_FILTERING_OPTIONS,
  DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS: () => DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS,
  DEFAULT_LSP_DOCUMENT_OPEN_DELAY_MS: () => DEFAULT_LSP_DOCUMENT_OPEN_DELAY_MS,
  DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS: () => DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS,
  DEFAULT_LSP_MAX_RESTARTS: () => DEFAULT_LSP_MAX_RESTARTS,
  DEFAULT_LSP_REQUEST_TIMEOUT_MS: () => DEFAULT_LSP_REQUEST_TIMEOUT_MS,
  DEFAULT_LSP_SOCKET_MAX_RETRY_DELAY_MS: () => DEFAULT_LSP_SOCKET_MAX_RETRY_DELAY_MS,
  DEFAULT_LSP_SOCKET_RETRY_DELAY_MS: () => DEFAULT_LSP_SOCKET_RETRY_DELAY_MS,
  DEFAULT_LSP_STARTUP_TIMEOUT_MS: () => DEFAULT_LSP_STARTUP_TIMEOUT_MS,
  DEFAULT_LSP_WARMUP_DELAY_MS: () => DEFAULT_LSP_WARMUP_DELAY_MS,
  DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS: () => DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS,
  DEFAULT_MEMORY_FILE_FILTERING_OPTIONS: () => DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
  DEFAULT_OTLP_ENDPOINT: () => DEFAULT_OTLP_ENDPOINT,
  DEFAULT_OUTPUT_TOKEN_LIMIT: () => DEFAULT_OUTPUT_TOKEN_LIMIT,
  DEFAULT_QWEN_EMBEDDING_MODEL: () => DEFAULT_QWEN_EMBEDDING_MODEL,
  DEFAULT_QWEN_FLASH_MODEL: () => DEFAULT_QWEN_FLASH_MODEL,
  DEFAULT_QWEN_MODEL: () => DEFAULT_QWEN_MODEL,
  DEFAULT_TELEMETRY_TARGET: () => DEFAULT_TELEMETRY_TARGET,
  DEFAULT_TOKEN_LIMIT: () => DEFAULT_TOKEN_LIMIT,
  DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES: () => DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES,
  DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD: () => DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,
  DIAGNOSTIC_SEVERITY_LABELS: () => DIAGNOSTIC_SEVERITY_LABELS,
  DISPLAY_MODE: () => DISPLAY_MODE,
  DREAM_TASK_TYPE: () => DREAM_TASK_TYPE,
  DeclarativeTool: () => DeclarativeTool,
  DefaultHookOutput: () => DefaultHookOutput,
  DiscoveredMCPTool: () => DiscoveredMCPTool,
  DiscoveredTool: () => DiscoveredTool,
  ESCALATED_MAX_TOKENS: () => ESCALATED_MAX_TOKENS,
  EVENT_API_ERROR: () => EVENT_API_ERROR,
  EVENT_API_RESPONSE: () => EVENT_API_RESPONSE,
  EVENT_TOOL_CALL: () => EVENT_TOOL_CALL,
  EXCLUDED_TOOLS_FOR_SUBAGENTS: () => EXCLUDED_TOOLS_FOR_SUBAGENTS,
  EXTENSIONS_CONFIG_FILENAME: () => EXTENSIONS_CONFIG_FILENAME,
  EXTENSIONS_DIRECTORY_NAME: () => EXTENSIONS_DIRECTORY_NAME,
  EXTENSION_SETTINGS_FILENAME: () => EXTENSION_SETTINGS_FILENAME,
  EXTERNAL_MESSAGE_PREFIX: () => EXTERNAL_MESSAGE_PREFIX,
  EXTRACT_TASK_TYPE: () => EXTRACT_TASK_TYPE,
  EndSessionEvent: () => EndSessionEvent,
  ExtensionDisableEvent: () => ExtensionDisableEvent,
  ExtensionEnableEvent: () => ExtensionEnableEvent,
  ExtensionInstallEvent: () => ExtensionInstallEvent,
  ExtensionManager: () => ExtensionManager,
  ExtensionSettingScope: () => ExtensionSettingScope,
  ExtensionUninstallEvent: () => ExtensionUninstallEvent,
  ExtensionUpdateState: () => ExtensionUpdateState,
  FatalAuthenticationError: () => FatalAuthenticationError,
  FatalCancellationError: () => FatalCancellationError,
  FatalConfigError: () => FatalConfigError,
  FatalError: () => FatalError,
  FatalInputError: () => FatalInputError,
  FatalSandboxError: () => FatalSandboxError,
  FatalToolExecutionError: () => FatalToolExecutionError,
  FatalTurnLimitedError: () => FatalTurnLimitedError,
  FileDiscoveryService: () => FileDiscoveryService,
  FileEncoding: () => FileEncoding,
  FileExclusions: () => FileExclusions,
  FileOperation: () => FileOperation,
  FileSchema: () => FileSchema,
  FileSearchFactory: () => FileSearchFactory,
  FlashFallbackEvent: () => FlashFallbackEvent,
  ForbiddenError: () => ForbiddenError,
  GOOGLE_ACCOUNTS_FILENAME: () => GOOGLE_ACCOUNTS_FILENAME,
  GeminiChat: () => GeminiChat,
  GeminiClient: () => GeminiClient,
  GeminiEventType: () => GeminiEventType,
  GitIgnoreParser: () => GitIgnoreParser,
  GitService: () => GitService,
  GitWorktreeService: () => GitWorktreeService,
  HOOKS_CONFIG_FIELDS: () => HOOKS_CONFIG_FIELDS,
  HookEventName: () => HookEventName,
  HookRegistry: () => HookRegistry,
  HookSystem: () => HookSystem,
  HookType: () => HookType,
  HooksConfigSource: () => HooksConfigSource,
  IDEConnectionStatus: () => IDEConnectionStatus,
  IDE_DEFINITIONS: () => IDE_DEFINITIONS,
  IDE_MAX_OPEN_FILES: () => IDE_MAX_OPEN_FILES,
  IDE_MAX_SELECTED_TEXT_LENGTH: () => IDE_MAX_SELECTED_TEXT_LENGTH,
  IDE_REQUEST_TIMEOUT_MS: () => IDE_REQUEST_TIMEOUT_MS,
  IDLE_SPECULATION: () => IDLE_SPECULATION,
  INITIAL_FOLLOWUP_STATE: () => INITIAL_FOLLOWUP_STATE,
  INSTALL_METADATA_FILENAME: () => INSTALL_METADATA_FILENAME,
  ITermBackend: () => ITermBackend,
  IdeClient: () => IdeClient,
  IdeConnectionEvent: () => IdeConnectionEvent,
  IdeConnectionType: () => IdeConnectionType,
  IdeContextNotificationSchema: () => IdeContextNotificationSchema,
  IdeContextSchema: () => IdeContextSchema,
  IdeContextStore: () => IdeContextStore,
  IdeDiffAcceptedNotificationSchema: () => IdeDiffAcceptedNotificationSchema,
  IdeDiffClosedNotificationSchema: () => IdeDiffClosedNotificationSchema,
  IdeDiffRejectedNotificationSchema: () => IdeDiffRejectedNotificationSchema,
  InProcessBackend: () => InProcessBackend,
  InputFormat: () => InputFormat,
  InvalidStreamError: () => InvalidStreamError,
  JsonFormatter: () => JsonFormatter,
  KeychainTokenStorage: () => KeychainTokenStorage,
  Kind: () => Kind,
  KittySequenceOverflowEvent: () => KittySequenceOverflowEvent,
  LITE_READ_BUF_SIZE: () => LITE_READ_BUF_SIZE,
  Logger: () => Logger,
  LoopType: () => LoopType,
  LspConfigLoader: () => LspConfigLoader,
  LspConnectionFactory: () => LspConnectionFactory,
  LspResponseNormalizer: () => LspResponseNormalizer,
  LspServerManager: () => LspServerManager,
  MAINLINE_CODER_MODEL: () => MAINLINE_CODER_MODEL,
  MAIN_SOURCE: () => MAIN_SOURCE,
  MAX_FULL_SCAN_BYTES: () => MAX_FULL_SCAN_BYTES,
  MCPDiscoveryState: () => MCPDiscoveryState,
  MCPOAuthProvider: () => MCPOAuthProvider,
  MCPOAuthTokenStorage: () => MCPOAuthTokenStorage,
  MCPServerConfig: () => MCPServerConfig,
  MCPServerStatus: () => MCPServerStatus,
  MCP_DEFAULT_TIMEOUT_MSEC: () => MCP_DEFAULT_TIMEOUT_MSEC,
  MEDIA_FILE_PATTERNS: () => MEDIA_FILE_PATTERNS,
  MEMORY_SECTION_HEADER: () => MEMORY_SECTION_HEADER,
  MOCK_TOOL_GET_CONFIRMATION_DETAILS: () => MOCK_TOOL_GET_CONFIRMATION_DETAILS,
  MOCK_TOOL_GET_DEFAULT_PERMISSION: () => MOCK_TOOL_GET_DEFAULT_PERMISSION,
  MUTATOR_KINDS: () => MUTATOR_KINDS,
  McpClient: () => McpClient,
  McpClientManager: () => McpClientManager,
  MemoryDreamEvent: () => MemoryDreamEvent,
  MemoryExtractEvent: () => MemoryExtractEvent,
  MemoryManager: () => MemoryManager,
  MemoryMetricType: () => MemoryMetricType,
  MemoryRecallEvent: () => MemoryRecallEvent,
  MessageBus: () => MessageBus,
  MessageBusType: () => MessageBusType,
  MessageSenderType: () => MessageSenderType,
  MockModifiableTool: () => MockModifiableTool,
  MockModifiableToolInvocation: () => MockModifiableToolInvocation,
  MockTool: () => MockTool,
  ModelRegistry: () => ModelRegistry,
  ModelSlashCommandEvent: () => ModelSlashCommandEvent,
  ModelsConfig: () => ModelsConfig,
  NativeLspClient: () => NativeLspClient,
  NativeLspService: () => NativeLspService,
  NextSpeakerCheckEvent: () => NextSpeakerCheckEvent,
  NotificationType: () => NotificationType,
  OAUTH_AUTH_URL_EVENT: () => OAUTH_AUTH_URL_EVENT,
  OAUTH_DISPLAY_MESSAGE_EVENT: () => OAUTH_DISPLAY_MESSAGE_EVENT,
  OAuthUtils: () => OAuthUtils,
  OpenAILogger: () => OpenAILogger,
  OpenDiffRequestSchema: () => OpenDiffRequestSchema,
  OutputFormat: () => OutputFormat,
  OverlayFs: () => OverlayFs,
  PYTHON_EXCLUDES: () => PYTHON_EXCLUDES,
  PerformanceMetricType: () => PerformanceMetricType,
  PermissionManager: () => PermissionManager,
  PermissionMode: () => PermissionMode,
  PermissionRequestHookOutput: () => PermissionRequestHookOutput,
  PostCompactTrigger: () => PostCompactTrigger,
  PostToolUseFailureHookOutput: () => PostToolUseFailureHookOutput,
  PostToolUseHookOutput: () => PostToolUseHookOutput,
  PreCompactTrigger: () => PreCompactTrigger,
  PreToolUseHookOutput: () => PreToolUseHookOutput,
  PromptSuggestionEvent: () => PromptSuggestionEvent,
  QWEN_CODE_COMPANION_EXTENSION_NAME: () => QWEN_CODE_COMPANION_EXTENSION_NAME,
  QWEN_CODE_SIMPLE_ENV_VAR: () => QWEN_CODE_SIMPLE_ENV_VAR,
  QWEN_CONFIG_DIR: () => QWEN_CONFIG_DIR,
  QWEN_DIR: () => QWEN_DIR,
  QWEN_OAUTH_MODELS: () => QWEN_OAUTH_MODELS,
  QwenLogger: () => QwenLogger,
  QwenOAuth2Client: () => QwenOAuth2Client,
  QwenOAuth2Event: () => QwenOAuth2Event,
  ReadFileTool: () => ReadFileTool,
  RipGrepTool: () => RipGrepTool,
  RipgrepFallbackEvent: () => RipgrepFallbackEvent,
  SESSION_TITLE_MAX_LENGTH: () => SESSION_TITLE_MAX_LENGTH,
  SHELL_SPECIAL_CHARS: () => SHELL_SPECIAL_CHARS,
  SUGGESTION_PROMPT: () => SUGGESTION_PROMPT,
  SUPPORTED_IMAGE_MIME_TYPES: () => SUPPORTED_IMAGE_MIME_TYPES,
  SYMBOL_KIND_LABELS: () => SYMBOL_KIND_LABELS,
  SYSTEM_FILE_EXCLUDES: () => SYSTEM_FILE_EXCLUDES,
  SchemaValidator: () => SchemaValidator,
  SdkControlClientTransport: () => SdkControlClientTransport,
  SemanticAttributes: () => SemanticAttributes,
  SendMessageType: () => SendMessageType,
  SessionEndReason: () => SessionEndReason,
  SessionService: () => SessionService,
  SessionStartSource: () => SessionStartSource,
  SettingScope: () => SettingScope,
  ShellExecutionService: () => ShellExecutionService,
  SkillError: () => SkillError,
  SkillLaunchEvent: () => SkillLaunchEvent,
  SkillManager: () => SkillManager,
  SlashCommandStatus: () => SlashCommandStatus,
  SpanStatusCode: () => SpanStatusCode,
  SpeculationEvent: () => SpeculationEvent,
  StandardFileSystemService: () => StandardFileSystemService,
  StartSessionEvent: () => StartSessionEvent,
  StopHookOutput: () => StopHookOutput,
  Storage: () => Storage,
  StreamEventType: () => StreamEventType,
  SubagentError: () => SubagentError,
  SubagentManager: () => SubagentManager,
  SubagentValidator: () => SubagentValidator,
  TEST_ONLY: () => TEST_ONLY,
  TOOL_NAME_ALIASES: () => TOOL_NAME_ALIASES,
  TOOL_USE_SUMMARY_SYSTEM_PROMPT: () => TOOL_USE_SUMMARY_SYSTEM_PROMPT,
  TelemetryTarget: () => TelemetryTarget,
  TextTokenizer: () => TextTokenizer,
  TmuxBackend: () => TmuxBackend,
  ToolCallEvent: () => ToolCallEvent,
  ToolConfirmationOutcome: () => ToolConfirmationOutcome,
  ToolDisplayNames: () => ToolDisplayNames,
  ToolDisplayNamesMigration: () => ToolDisplayNamesMigration,
  ToolErrorType: () => ToolErrorType,
  ToolExecutionPhase: () => ToolExecutionPhase,
  ToolNames: () => ToolNames,
  ToolNamesMigration: () => ToolNamesMigration,
  ToolOutputTruncatedEvent: () => ToolOutputTruncatedEvent,
  ToolRegistry: () => ToolRegistry,
  Turn: () => Turn,
  UiTelemetryService: () => UiTelemetryService,
  UnauthorizedError: () => UnauthorizedError,
  UserFeedbackEvent: () => UserFeedbackEvent,
  UserFeedbackRating: () => UserFeedbackRating,
  UserPromptEvent: () => UserPromptEvent,
  UserRetryEvent: () => UserRetryEvent,
  ValueType: () => ValueType,
  WORKTREES_DIR: () => WORKTREES_DIR,
  WorkspaceContext: () => WorkspaceContext,
  _recoverObjectsFromLine: () => _recoverObjectsFromLine,
  _resetCachedIdeServerHost: () => _resetCachedIdeServerHost,
  _resetEnsuredDirsCacheForTest: () => _resetEnsuredDirsCacheForTest,
  _resetRipGrepCachesForTest: () => _resetRipGrepCachesForTest,
  _resetValidatePathCacheForTest: () => _resetValidatePathCacheForTest,
  abortSpeculation: () => abortSpeculation,
  acceptSpeculation: () => acceptSpeculation,
  addMCPStatusChangeListener: () => addMCPStatusChangeListener,
  allowEditorTypeInSandbox: () => allowEditorTypeInSandbox,
  appendToLastTextPart: () => appendToLastTextPart,
  buildApiHistoryFromConversation: () => buildApiHistoryFromConversation,
  buildBackgroundEntryLabel: () => buildBackgroundEntryLabel,
  buildFallbackApproachSummary: () => buildFallbackApproachSummary,
  buildHumanReadableRuleLabel: () => buildHumanReadableRuleLabel,
  buildPermissionCheckContext: () => buildPermissionCheckContext,
  buildPermissionRules: () => buildPermissionRules,
  buildSkillLlmContent: () => buildSkillLlmContent,
  canUseRipgrep: () => canUseRipgrep,
  checkArgumentSafety: () => checkArgumentSafety,
  checkCommandPermissions: () => checkCommandPermissions,
  checkForExtensionUpdate: () => checkForExtensionUpdate,
  checkHasEditorType: () => checkHasEditorType,
  checkNpmUpdate: () => checkNpmUpdate,
  cleanSummary: () => cleanSummary,
  cleanupTmpDir: () => cleanupTmpDir,
  clearAutoMemoryRootCache: () => clearAutoMemoryRootCache,
  clearCacheSafeParams: () => clearCacheSafeParams,
  clearCachedCredentialFile: () => clearCachedCredentialFile,
  clearQwenCredentials: () => clearQwenCredentials,
  clearWelcomeBackState: () => clearWelcomeBackState,
  cliSource: () => cliSource,
  cloneFromGit: () => cloneFromGit,
  commandExists: () => commandExists,
  computeCodingPlanVersion: () => computeCodingPlanVersion,
  computedSource: () => computedSource,
  connectAndDiscover: () => connectAndDiscover,
  connectToMcpServer: () => connectToMcpServer,
  convertClaudeAgentConfig: () => convertClaudeAgentConfig,
  convertClaudePluginPackage: () => convertClaudePluginPackage,
  convertClaudeToQwenConfig: () => convertClaudeToQwenConfig,
  convertColorToHex: () => convertColorToHex,
  convertToFunctionResponse: () => convertToFunctionResponse,
  convertTomlToMarkdown: () => convertTomlToMarkdown,
  copyExtension: () => copyExtension,
  countFileLines: () => countFileLines,
  countLines: () => countLines,
  createContentGenerator: () => createContentGenerator,
  createContentGeneratorConfig: () => createContentGeneratorConfig,
  createDebugLogger: () => createDebugLogger,
  createDefaultAutoMemoryExtractCursor: () => createDefaultAutoMemoryExtractCursor,
  createDefaultAutoMemoryIndex: () => createDefaultAutoMemoryIndex,
  createDefaultAutoMemoryMetadata: () => createDefaultAutoMemoryMetadata,
  createFollowupController: () => createFollowupController,
  createForkedChat: () => createForkedChat,
  createHookOutput: () => createHookOutput,
  createTmpDir: () => createTmpDir,
  createToolUseSummaryMessage: () => createToolUseSummaryMessage,
  createTransport: () => createTransport,
  decodeTagName: () => decodeTagName,
  defaultSource: () => defaultSource,
  detectBOM: () => detectBOM,
  detectBackend: () => detectBackend,
  detectCommandSubstitution: () => detectCommandSubstitution,
  detectEncodingFromBuffer: () => detectEncodingFromBuffer,
  detectFileEncoding: () => detectFileEncoding,
  detectFileType: () => detectFileType,
  detectLineEnding: () => detectLineEnding,
  detectRuntime: () => detectRuntime,
  discoverMcpTools: () => discoverMcpTools,
  discoverPrompts: () => discoverPrompts,
  discoverTools: () => discoverTools,
  doesToolInvocationMatch: () => doesToolInvocationMatch,
  downloadFromGitHubRelease: () => downloadFromGitHubRelease,
  downloadFromNpmRegistry: () => downloadFromNpmRegistry,
  editorCommands: () => editorCommands,
  encodeInsightProgressMessage: () => encodeInsightProgressMessage,
  encodeInsightReadyMessage: () => encodeInsightReadyMessage,
  encodeTagName: () => encodeTagName,
  ensureAutoMemoryScaffold: () => ensureAutoMemoryScaffold,
  ensureCrlfLineEndings: () => ensureCrlfLineEndings,
  ensureMacBinarySigned: () => ensureMacBinarySigned,
  ensureRipgrepHealthy: () => ensureRipgrepHealthy,
  ensureToolResultPairing: () => ensureToolResultPairing,
  envLayer: () => envLayer,
  escapePath: () => escapePath,
  escapeShellArg: () => escapeShellArg,
  evaluatePermissionRules: () => evaluatePermissionRules,
  evaluateToolCall: () => evaluateToolCall,
  execCommand: () => execCommand2,
  executeToolCall: () => executeToolCall,
  exists: () => exists,
  extractExtensionsFromPatterns: () => extractExtensionsFromPatterns,
  extractFile: () => extractFile2,
  extractJsonStringField: () => extractJsonStringField,
  extractLastJsonStringField: () => extractLastJsonStringField,
  extractLastJsonStringFields: () => extractLastJsonStringFields,
  extractShellOperations: () => extractShellOperations,
  fileExists: () => fileExists,
  filter: () => filter3,
  findGitRoot: () => findGitRoot2,
  findReleaseAsset: () => findReleaseAsset,
  fireNotificationHook: () => fireNotificationHook,
  firePermissionRequestHook: () => firePermissionRequestHook,
  firePostToolUseFailureHook: () => firePostToolUseFailureHook,
  firePostToolUseHook: () => firePostToolUseHook,
  firePreToolUseHook: () => firePreToolUseHook,
  flatMapTextParts: () => flatMapTextParts,
  formatLineStats: () => formatLineStats,
  formatMemoryUsage: () => formatMemoryUsage,
  generateCodeChallenge: () => generateCodeChallenge,
  generateCodeVerifier: () => generateCodeVerifier,
  generateCodingPlanTemplate: () => generateCodingPlanTemplate,
  generatePKCEPair: () => generatePKCEPair,
  generatePromptSuggestion: () => generatePromptSuggestion,
  generateSessionRecap: () => generateSessionRecap,
  generateToolUseId: () => generateToolUseId,
  generateToolUseSummary: () => generateToolUseSummary,
  generateValidName: () => generateValidName,
  getAllGeminiMdFilenames: () => getAllGeminiMdFilenames,
  getAllMCPServerStatuses: () => getAllMCPServerStatuses,
  getArenaSystemReminder: () => getArenaSystemReminder,
  getAutoMemoryConsolidationLockPath: () => getAutoMemoryConsolidationLockPath,
  getAutoMemoryExtractCursorPath: () => getAutoMemoryExtractCursorPath,
  getAutoMemoryFilePath: () => getAutoMemoryFilePath,
  getAutoMemoryIndexPath: () => getAutoMemoryIndexPath,
  getAutoMemoryMetadataPath: () => getAutoMemoryMetadataPath,
  getAutoMemoryProjectStateDir: () => getAutoMemoryProjectStateDir,
  getAutoMemoryRoot: () => getAutoMemoryRoot,
  getAutoMemoryTopicFilename: () => getAutoMemoryTopicFilename,
  getAutoMemoryTopicPath: () => getAutoMemoryTopicPath,
  getBuiltinRipgrep: () => getBuiltinRipgrep,
  getCacheSafeParams: () => getCacheSafeParams,
  getCachedEncodingForBuffer: () => getCachedEncodingForBuffer,
  getCodingPlanBaseUrls: () => getCodingPlanBaseUrls,
  getCodingPlanConfig: () => getCodingPlanConfig,
  getCommandRoot: () => getCommandRoot,
  getCommandRoots: () => getCommandRoots,
  getCompressionPrompt: () => getCompressionPrompt,
  getCoreSystemPrompt: () => getCoreSystemPrompt,
  getCurrentGeminiMdFilename: () => getCurrentGeminiMdFilename,
  getCustomSystemPrompt: () => getCustomSystemPrompt,
  getDiffCommand: () => getDiffCommand,
  getDirectoryContextString: () => getDirectoryContextString,
  getEditorExecutable: () => getEditorExecutable,
  getEnvContents: () => getEnvContents,
  getEnvironmentContext: () => getEnvironmentContext,
  getErrorMessage: () => getErrorMessage,
  getErrorStatus: () => getErrorStatus,
  getErrorType: () => getErrorType,
  getExtensionId: () => getExtensionId,
  getFilterReason: () => getFilterReason,
  getFolderStructure: () => getFolderStructure,
  getFunctionCalls: () => getFunctionCalls,
  getFunctionCallsAsJson: () => getFunctionCallsAsJson,
  getFunctionCallsFromParts: () => getFunctionCallsFromParts,
  getFunctionCallsFromPartsAsJson: () => getFunctionCallsFromPartsAsJson,
  getGitBranch: () => getGitBranch,
  getGitRepoName: () => getGitRepoName,
  getHookKey: () => getHookKey,
  getIdeInstaller: () => getIdeInstaller,
  getIdeServerHost: () => getIdeServerHost,
  getInitialChatHistory: () => getInitialChatHistory,
  getInsightPrompt: () => getInsightPrompt,
  getMCPDiscoveryState: () => getMCPDiscoveryState,
  getMCPServerPrompts: () => getMCPServerPrompts,
  getMCPServerStatus: () => getMCPServerStatus,
  getMemoryBaseDir: () => getMemoryBaseDir,
  getOrCreateSharedDispatcher: () => getOrCreateSharedDispatcher,
  getPlanModeSystemReminder: () => getPlanModeSystemReminder,
  getProjectHash: () => getProjectHash,
  getProjectSummaryInfo: () => getProjectSummaryInfo,
  getProjectSummaryPrompt: () => getProjectSummaryPrompt,
  getQwenOAuthClient: () => getQwenOAuthClient,
  getRegionFromBaseUrl: () => getRegionFromBaseUrl,
  getResponseText: () => getResponseText,
  getResponseTextFromParts: () => getResponseTextFromParts,
  getResumePromptTokenCount: () => getResumePromptTokenCount,
  getRuleDisplayName: () => getRuleDisplayName,
  getScopedEnvContents: () => getScopedEnvContents,
  getShellConfiguration: () => getShellConfiguration,
  getSpecificMimeType: () => getSpecificMimeType,
  getSpecifierKind: () => getSpecifierKind,
  getStructuredResponse: () => getStructuredResponse,
  getStructuredResponseFromParts: () => getStructuredResponseFromParts,
  getSubagentSystemReminder: () => getSubagentSystemReminder,
  getSupportedImageFormatsString: () => getSupportedImageFormatsString,
  getSystemEncoding: () => getSystemEncoding,
  getThoughtText: () => getThoughtText,
  getUnsupportedImageFormatWarning: () => getUnsupportedImageFormatWarning,
  getWelcomeBackState: () => getWelcomeBackState,
  globalMemoryManager: () => globalMemoryManager,
  hasCycleInSchema: () => hasCycleInSchema,
  hasExplicitOutputLimit: () => hasExplicitOutputLimit,
  hasNetworkTransport: () => hasNetworkTransport,
  hashValue: () => hashValue,
  hydrateString: () => hydrateString,
  ideContextStore: () => ideContextStore,
  initializeTelemetry: () => initializeTelemetry,
  injectPermissionRulesIfMissing: () => injectPermissionRulesIfMissing,
  invokeMcpPrompt: () => invokeMcpPrompt,
  isAbortError: () => isAbortError,
  isApiError: () => isApiError,
  isAutoMemPath: () => isAutoMemPath,
  isBareMode: () => isBareMode,
  isBinary: () => isBinary,
  isBinaryFile: () => isBinaryFile,
  isClaudePluginConfig: () => isClaudePluginConfig,
  isCodingPlanConfig: () => isCodingPlanConfig,
  isCommandAllowed: () => isCommandAllowed,
  isCommandAvailable: () => isCommandAvailable,
  isCommandNeedsPermission: () => isCommandNeedsPermission,
  isDebugLoggingDegraded: () => isDebugLoggingDegraded,
  isDeviceAuthorizationSuccess: () => isDeviceAuthorizationSuccess,
  isDeviceTokenPending: () => isDeviceTokenPending,
  isDeviceTokenSuccess: () => isDeviceTokenSuccess,
  isEditorAvailable: () => isEditorAvailable,
  isEnabled: () => isEnabled,
  isErrorResponse: () => isErrorResponse,
  isGenericQuotaExceededError: () => isGenericQuotaExceededError,
  isGitRepository: () => isGitRepository,
  isInvalidArgumentError: () => isInvalidArgumentError,
  isModifiableDeclarativeTool: () => isModifiableDeclarativeTool,
  isNodeError: () => isNodeError,
  isPathWithinRoot: () => isPathWithinRoot,
  isPerformanceMonitoringActive: () => isPerformanceMonitoringActive,
  isProQuotaExceededError: () => isProQuotaExceededError,
  isQwenQuotaExceededError: () => isQwenQuotaExceededError,
  isRateLimitError: () => isRateLimitError,
  isSchemaDepthError: () => isSchemaDepthError,
  isScopedNpmPackage: () => isScopedNpmPackage,
  isSdkMcpServerConfig: () => isSdkMcpServerConfig,
  isSettledStatus: () => isSettledStatus,
  isStructuredError: () => isStructuredError,
  isSubpath: () => isSubpath,
  isSubpaths: () => isSubpaths,
  isSuccessStatus: () => isSuccessStatus,
  isSupportedImageMimeType: () => isSupportedImageMimeType,
  isTelemetrySdkInitialized: () => isTelemetrySdkInitialized,
  isTerminalStatus: () => isTerminalStatus,
  isTomlFormat: () => isTomlFormat,
  isTool: () => isTool,
  isToolEnabled: () => isToolEnabled,
  isTransientCapacityError: () => isTransientCapacityError,
  isUnattendedMode: () => isUnattendedMode,
  isValidNonThoughtTextPart: () => isValidNonThoughtTextPart,
  isWindows: () => isWindows,
  isWithinRoot: () => isWithinRoot,
  knownTokenLimit: () => knownTokenLimit,
  layer: () => layer,
  loadServerHierarchicalMemory: () => loadServerHierarchicalMemory,
  logApiCancel: () => logApiCancel,
  logApiError: () => logApiError,
  logApiRequest: () => logApiRequest,
  logApiResponse: () => logApiResponse,
  logArenaAgentCompleted: () => logArenaAgentCompleted,
  logArenaSessionEnded: () => logArenaSessionEnded,
  logArenaSessionStarted: () => logArenaSessionStarted,
  logAuth: () => logAuth,
  logChatCompression: () => logChatCompression,
  logConversationFinishedEvent: () => logConversationFinishedEvent,
  logExtensionDisable: () => logExtensionDisable,
  logExtensionEnable: () => logExtensionEnable,
  logExtensionInstallEvent: () => logExtensionInstallEvent,
  logExtensionUninstall: () => logExtensionUninstall,
  logExtensionUpdateEvent: () => logExtensionUpdateEvent,
  logFlashFallback: () => logFlashFallback,
  logIdeConnection: () => logIdeConnection,
  logKittySequenceOverflow: () => logKittySequenceOverflow,
  logMemoryDream: () => logMemoryDream,
  logMemoryExtract: () => logMemoryExtract,
  logMemoryRecall: () => logMemoryRecall,
  logModelSlashCommand: () => logModelSlashCommand,
  logNextSpeakerCheck: () => logNextSpeakerCheck,
  logPromptSuggestion: () => logPromptSuggestion,
  logRipgrepFallback: () => logRipgrepFallback,
  logSkillLaunch: () => logSkillLaunch,
  logSlashCommand: () => logSlashCommand,
  logSpeculation: () => logSpeculation,
  logStartSession: () => logStartSession,
  logToolCall: () => logToolCall,
  logToolOutputTruncated: () => logToolOutputTruncated,
  logUserFeedback: () => logUserFeedback,
  logUserPrompt: () => logUserPrompt,
  logUserRetry: () => logUserRetry,
  makeArenaAgentCompletedEvent: () => makeArenaAgentCompletedEvent,
  makeArenaSessionEndedEvent: () => makeArenaSessionEndedEvent,
  makeArenaSessionStartedEvent: () => makeArenaSessionStartedEvent,
  makeChatCompressionEvent: () => makeChatCompressionEvent,
  makeFakeConfig: () => makeFakeConfig,
  makeRelative: () => makeRelative,
  makeSlashCommandEvent: () => makeSlashCommandEvent,
  matchesCommandPattern: () => matchesCommandPattern,
  matchesDomainPattern: () => matchesDomainPattern,
  matchesMcpPattern: () => matchesMcpPattern,
  matchesPathPattern: () => matchesPathPattern,
  matchesRule: () => matchesRule,
  maybePromptForSettings: () => maybePromptForSettings,
  mcpServerRequiresOAuth: () => mcpServerRequiresOAuth,
  mergeClaudeConfigs: () => mergeClaudeConfigs,
  modelProvidersSource: () => modelProvidersSource,
  modifyWithEditor: () => modifyWithEditor,
  needsUtf8Bom: () => needsUtf8Bom,
  normalize: () => normalize3,
  normalizeContent: () => normalizeContent,
  normalizeProxyUrl: () => normalizeProxyUrl,
  openDiff: () => openDiff,
  openaiLogger: () => openaiLogger,
  parse: () => parse8,
  parseAndFormatApiError: () => parseAndFormatApiError,
  parseBooleanEnvFlag: () => parseBooleanEnvFlag,
  parseGitHubRepoForReleases: () => parseGitHubRepoForReleases,
  parseInsightMessage: () => parseInsightMessage,
  parseInstallSource: () => parseInstallSource,
  parseNpmPackageSource: () => parseNpmPackageSource,
  parseRule: () => parseRule,
  parseRules: () => parseRules,
  parseTelemetryTargetValue: () => parseTelemetryTargetValue,
  parseThought: () => parseThought,
  partListUnionToString: () => partListUnionToString,
  partToString: () => partToString,
  performVariableReplacement: () => performVariableReplacement,
  persistPermissionOutcome: () => persistPermissionOutcome,
  populateMcpServerCommand: () => populateMcpServerCommand,
  processSingleFileContent: () => processSingleFileContent,
  promptForSetting: () => promptForSetting,
  promptIdContext: () => promptIdContext,
  qwenOAuth2Events: () => qwenOAuth2Events,
  read: () => read,
  readAutoMemoryIndex: () => readAutoMemoryIndex,
  readFileWithEncoding: () => readFileWithEncoding,
  readFileWithEncodingInfo: () => readFileWithEncodingInfo,
  readFileWithLineAndLimit: () => readFileWithLineAndLimit,
  readLastJsonStringFieldSync: () => readLastJsonStringFieldSync,
  readLastJsonStringFieldsSync: () => readLastJsonStringFieldsSync,
  readLines: () => readLines,
  readManyFiles: () => readManyFiles,
  readPathFromWorkspace: () => readPathFromWorkspace,
  recordApiErrorMetrics: () => recordApiErrorMetrics,
  recordApiRequestBreakdown: () => recordApiRequestBreakdown,
  recordApiResponseMetrics: () => recordApiResponseMetrics,
  recordArenaAgentCompletedMetrics: () => recordArenaAgentCompletedMetrics,
  recordArenaSessionEndedMetrics: () => recordArenaSessionEndedMetrics,
  recordArenaSessionStartedMetrics: () => recordArenaSessionStartedMetrics,
  recordBaselineComparison: () => recordBaselineComparison,
  recordContentRetry: () => recordContentRetry,
  recordContentRetryFailure: () => recordContentRetryFailure,
  recordCpuUsage: () => recordCpuUsage,
  recordFileOperationMetric: () => recordFileOperationMetric,
  recordInvalidChunk: () => recordInvalidChunk,
  recordMemoryDreamMetrics: () => recordMemoryDreamMetrics,
  recordMemoryExtractMetrics: () => recordMemoryExtractMetrics,
  recordMemoryRecallMetrics: () => recordMemoryRecallMetrics,
  recordMemoryUsage: () => recordMemoryUsage,
  recordPerformanceRegression: () => recordPerformanceRegression,
  recordPerformanceScore: () => recordPerformanceScore,
  recordStartupPerformance: () => recordStartupPerformance,
  recordTokenEfficiency: () => recordTokenEfficiency,
  recordTokenUsageMetrics: () => recordTokenUsageMetrics,
  recordToolCallMetrics: () => recordToolCallMetrics,
  recordToolExecutionBreakdown: () => recordToolExecutionBreakdown,
  recordToolQueueDepth: () => recordToolQueueDepth,
  recursivelyHydrateStrings: () => recursivelyHydrateStrings,
  removeMCPStatusChangeListener: () => removeMCPStatusChangeListener,
  replayUiTelemetryFromConversation: () => replayUiTelemetryFromConversation,
  resetDebugLoggingState: () => resetDebugLoggingState,
  resetEncodingCache: () => resetEncodingCache,
  resetUtf8BomCache: () => resetUtf8BomCache,
  resolveAndValidatePath: () => resolveAndValidatePath,
  resolveCommandPath: () => resolveCommandPath,
  resolveContentGeneratorConfigWithSources: () => resolveContentGeneratorConfigWithSources,
  resolveField: () => resolveField,
  resolveModelConfig: () => resolveModelConfig,
  resolveNpmRegistry: () => resolveNpmRegistry,
  resolveOptionalField: () => resolveOptionalField,
  resolvePath: () => resolvePath,
  resolvePathFromEnv: () => resolvePathFromEnv,
  resolvePathPattern: () => resolvePathPattern,
  resolveRipgrep: () => resolveRipgrep,
  resolveTelemetrySettings: () => resolveTelemetrySettings,
  resolveToolName: () => resolveToolName,
  retryWithBackoff: () => retryWithBackoff,
  rewritePathArgs: () => rewritePathArgs,
  runForkedAgent: () => runForkedAgent,
  runRipgrep: () => runRipgrep,
  runSideQuery: () => runSideQuery,
  runWithDebugLogSession: () => runWithDebugLogSession,
  safeAgentId: () => safeAgentId,
  safeLiteralReplace: () => safeLiteralReplace,
  sanitizeCwd: () => sanitizeCwd,
  sanitizeHookName: () => sanitizeHookName,
  sanitizeTitle: () => sanitizeTitle,
  saveCacheSafeParams: () => saveCacheSafeParams,
  saveWelcomeBackRestartChoice: () => saveWelcomeBackRestartChoice,
  serializeTerminalToObject: () => serializeTerminalToObject,
  serializeTerminalToText: () => serializeTerminalToText,
  setDebugLogSession: () => setDebugLogSession,
  setGeminiMdFilename: () => setGeminiMdFilename,
  settingsSource: () => settingsSource,
  shortenPath: () => shortenPath,
  shouldAttemptBrowserLaunch: () => shouldAttemptBrowserLaunch,
  shouldDefaultToNodePty: () => shouldDefaultToNodePty,
  shouldFilterSuggestion: () => shouldFilterSuggestion,
  shutdownTelemetry: () => shutdownTelemetry,
  splitCommands: () => splitCommands,
  splitCompoundCommand: () => splitCompoundCommand,
  startSpeculation: () => startSpeculation,
  stringify: () => stringify2,
  stripShellWrapper: () => stripShellWrapper,
  stripStartupContext: () => stripStartupContext,
  stripTerminalControlSequences: () => stripTerminalControlSequences,
  subagentGenerator: () => subagentGenerator,
  substituteHookVariables: () => substituteHookVariables,
  summarizeUnifiedDiff: () => summarizeUnifiedDiff,
  templateString: () => templateString,
  tildeifyPath: () => tildeifyPath,
  toFriendlyError: () => toFriendlyError,
  tokenLimit: () => tokenLimit,
  toolMatchesRuleToolName: () => toolMatchesRuleToolName,
  truncateJson: () => truncateJson,
  tryGenerateSessionTitle: () => tryGenerateSessionTitle,
  uiTelemetryService: () => uiTelemetryService,
  unescapeJsonString: () => unescapeJsonString,
  unescapePath: () => unescapePath,
  updateMCPServerStatus: () => updateMCPServerStatus,
  updateSetting: () => updateSetting,
  updateSymlink: () => updateSymlink,
  validateModelConfig: () => validateModelConfig,
  validateName: () => validateName,
  validatePath: () => validatePath,
  validateVariables: () => validateVariables,
  windowsCodePageToEncoding: () => windowsCodePageToEncoding,
  write: () => write,
  writeLine: () => writeLine,
  writeLineSync: () => writeLineSync
});
var init_dist4 = __esm({
  "packages/core/dist/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_src2();
  }
});

// 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 noop11() {
    }
    __name(noop11, "noop");
    var ReactSharedInternals = { H: null, A: null, T: null, S: null };
    var hasOwnProperty3 = 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(noop11, noop11) : (thenable.status = "pending", thenable.then(
            function(fulfilledValue) {
              "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
            },
            function(error40) {
              "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error40);
            }
          )), 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 i4 = 0; i4 < children.length; i4++)
          nameSoFar = children[i4], type = nextNamePrefix + getElementKey(nameSoFar, i4), invokeCallback += mapIntoArray(
            nameSoFar,
            array2,
            escapedPrefix,
            type,
            callback
          );
      else if (i4 = getIteratorFn(children), "function" === typeof i4)
        for (children = i4.call(children), i4 = 0; !(nameSoFar = children.next()).done; )
          nameSoFar = nameSoFar.value, type = nextNamePrefix + getElementKey(nameSoFar, i4++), 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, func2, context2) {
      if (null == children) return children;
      var result = [], count = 0;
      mapIntoArray(children, result, "", "", function(child) {
        return func2.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(error40) {
            if (0 === payload._status || -1 === payload._status)
              payload._status = 2, payload._result = error40;
          }
        );
        -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(error40) {
      if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
        var event = new window.ErrorEvent("error", {
          bubbles: true,
          cancelable: true,
          message: "object" === typeof error40 && null !== error40 && "string" === typeof error40.message ? String(error40.message) : String(error40),
          error: error40
        });
        if (!window.dispatchEvent(event)) return;
      } else if ("object" === typeof process && "function" === typeof process.emit) {
        process.emit("uncaughtException", error40);
        return;
      }
      console.error(error40);
    };
    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)
          !hasOwnProperty3.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), i4 = 0; i4 < propName; i4++)
          childArray[i4] = arguments[i4 + 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)
          hasOwnProperty3.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), i4 = 0; i4 < childrenLength; i4++)
          childArray[i4] = arguments[i4 + 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(noop11, reportGlobalError);
      } catch (error40) {
        reportGlobalError(error40);
      } 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(create4, deps) {
      return ReactSharedInternals.H.useEffect(create4, deps);
    };
    exports2.useEffectEvent = function(callback) {
      return ReactSharedInternals.H.useEffectEvent(callback);
    };
    exports2.useId = function() {
      return ReactSharedInternals.H.useId();
    };
    exports2.useImperativeHandle = function(ref, create4, deps) {
      return ReactSharedInternals.H.useImperativeHandle(ref, create4, deps);
    };
    exports2.useInsertionEffect = function(create4, deps) {
      return ReactSharedInternals.H.useInsertionEffect(create4, deps);
    };
    exports2.useLayoutEffect = function(create4, deps) {
      return ReactSharedInternals.H.useLayoutEffect(create4, deps);
    };
    exports2.useMemo = function(create4, deps) {
      return ReactSharedInternals.H.useMemo(create4, deps);
    };
    exports2.useOptimistic = function(passthrough, reducer) {
      return ReactSharedInternals.H.useOptimistic(passthrough, reducer);
    };
    exports2.useReducer = function(reducer, initialArg, init2) {
      return ReactSharedInternals.H.useReducer(reducer, initialArg, init2);
    };
    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, info2) {
        Object.defineProperty(Component.prototype, methodName, {
          get: /* @__PURE__ */ __name(function() {
            console.warn(
              "%s(...) is deprecated in plain JavaScript React classes. %s",
              info2[0],
              info2[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 noop11() {
      }
      __name(noop11, "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 name4 = getComponentNameFromType(type);
          return name4 ? "<" + name4 + ">" : "<...>";
        } 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 (hasOwnProperty3.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(noop11, noop11) : (thenable.status = "pending", thenable.then(
              function(fulfilledValue) {
                "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
              },
              function(error40) {
                "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error40);
              }
            )), 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 i4 = 0; i4 < children.length; i4++)
            nameSoFar = children[i4], type = childKey + getElementKey(nameSoFar, i4), invokeCallback += mapIntoArray(
              nameSoFar,
              array2,
              escapedPrefix,
              type,
              callback
            );
        else if (i4 = getIteratorFn(children), "function" === typeof i4)
          for (i4 === children.entries && (didWarnAboutMaps || console.warn(
            "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
          ), didWarnAboutMaps = true), children = i4.call(children), i4 = 0; !(nameSoFar = children.next()).done; )
            nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i4++), 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, func2, context2) {
        if (null == children) return children;
        var result = [], count = 0;
        mapIntoArray(children, result, "", "", function(child) {
          return func2.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(error40) {
              if (0 === payload._status || -1 === payload._status) {
                payload._status = 2;
                payload._result = error40;
                var _ioInfo2 = payload._ioInfo;
                null != _ioInfo2 && (_ioInfo2.end = performance.now());
                void 0 === thenable.status && (thenable.status = "rejected", thenable.reason = error40);
              }
            }
          );
          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, resolve42, reject) {
        var queue = ReactSharedInternals.actQueue;
        if (null !== queue)
          if (0 !== queue.length)
            try {
              flushActQueue(queue);
              enqueueTask(function() {
                return recursivelyFlushAsyncActWork(returnValue, resolve42, reject);
              });
              return;
            } catch (error40) {
              ReactSharedInternals.thrownErrors.push(error40);
            }
          else ReactSharedInternals.actQueue = null;
        0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve42(returnValue);
      }
      __name(recursivelyFlushAsyncActWork, "recursivelyFlushAsyncActWork");
      function flushActQueue(queue) {
        if (!isFlushing) {
          isFlushing = true;
          var i4 = 0;
          try {
            for (; i4 < queue.length; i4++) {
              var callback = queue[i4];
              do {
                ReactSharedInternals.didUsePromise = false;
                var continuation = callback(false);
                if (null !== continuation) {
                  if (ReactSharedInternals.didUsePromise) {
                    queue[i4] = callback;
                    queue.splice(0, i4);
                    return;
                  }
                  callback = continuation;
                } else break;
              } while (1);
            }
            queue.length = 0;
          } catch (error40) {
            queue.splice(0, i4 + 1), ReactSharedInternals.thrownErrors.push(error40);
          } 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
      }, hasOwnProperty3 = 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(error40) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error40 && null !== error40 && "string" === typeof error40.message ? String(error40.message) : String(error40),
            error: error40
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error40);
          return;
        }
        console.error(error40);
      }, 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 (error40) {
          ReactSharedInternals.thrownErrors.push(error40);
        }
        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(resolve42, reject) {
              didAwaitActCall = true;
              thenable.then(
                function(returnValue) {
                  popActScope(prevActQueue, prevActScopeDepth);
                  if (0 === prevActScopeDepth) {
                    try {
                      flushActQueue(queue), enqueueTask(function() {
                        return recursivelyFlushAsyncActWork(
                          returnValue,
                          resolve42,
                          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 resolve42(returnValue);
                },
                function(error40) {
                  popActScope(prevActQueue, prevActScopeDepth);
                  0 < ReactSharedInternals.thrownErrors.length ? (error40 = aggregateErrors(
                    ReactSharedInternals.thrownErrors
                  ), ReactSharedInternals.thrownErrors.length = 0, reject(error40)) : reject(error40);
                }
              );
            }, "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(resolve42, reject) {
            didAwaitActCall = true;
            0 === prevActScopeDepth ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
              return recursivelyFlushAsyncActWork(
                returnValue$jscomp$0,
                resolve42,
                reject
              );
            })) : resolve42(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 (hasOwnProperty3.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)
            !hasOwnProperty3.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 i4 = 0; i4 < propName; i4++)
            JSCompiler_inline_result[i4] = arguments[i4 + 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 i4 = 2; i4 < arguments.length; i4++)
          validateChildKeys(arguments[i4]);
        i4 = {};
        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)
            hasOwnProperty3.call(config2, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (i4[propName] = config2[propName]);
        var childrenLength = arguments.length - 2;
        if (1 === childrenLength) i4.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);
          i4.children = childArray;
        }
        if (type && type.defaultProps)
          for (propName in childrenLength = type.defaultProps, childrenLength)
            void 0 === i4[propName] && (i4[propName] = childrenLength[propName]);
        key && defineKeyPropWarningGetter(
          i4,
          "function" === typeof type ? type.displayName || type.name || "Unknown" : type
        );
        var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return ReactElement(
          type,
          key,
          i4,
          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(name4) {
            ownName = name4;
            render3.name || render3.displayName || (Object.defineProperty(render3, "name", { value: name4 }), render3.displayName = name4);
          }, "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(name4) {
            ownName = name4;
            type.name || type.displayName || (Object.defineProperty(type, "name", { value: name4 }), type.displayName = name4);
          }, "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(noop11, reportGlobalError));
        } catch (error40) {
          reportGlobalError(error40);
        } 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(create4, deps) {
        null == create4 && console.warn(
          "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useEffect(create4, deps);
      };
      exports2.useEffectEvent = function(callback) {
        return resolveDispatcher().useEffectEvent(callback);
      };
      exports2.useId = function() {
        return resolveDispatcher().useId();
      };
      exports2.useImperativeHandle = function(ref, create4, deps) {
        return resolveDispatcher().useImperativeHandle(ref, create4, deps);
      };
      exports2.useInsertionEffect = function(create4, deps) {
        null == create4 && console.warn(
          "React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useInsertionEffect(create4, deps);
      };
      exports2.useLayoutEffect = function(create4, deps) {
        null == create4 && console.warn(
          "React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useLayoutEffect(create4, deps);
      };
      exports2.useMemo = function(create4, deps) {
        return resolveDispatcher().useMemo(create4, deps);
      };
      exports2.useOptimistic = function(passthrough, reducer) {
        return resolveDispatcher().useOptimistic(passthrough, reducer);
      };
      exports2.useReducer = function(reducer, initialArg, init2) {
        return resolveDispatcher().useReducer(reducer, initialArg, init2);
      };
      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 process51 = globalThis.process;
    var processOk = /* @__PURE__ */ __name(function(process52) {
      return process52 && typeof process52 === "object" && typeof process52.removeListener === "function" && typeof process52.emit === "function" && typeof process52.reallyExit === "function" && typeof process52.listeners === "function" && typeof process52.kill === "function" && typeof process52.pid === "number" && typeof process52.on === "function";
    }, "processOk");
    if (!processOk(process51)) {
      module2.exports = function() {
        return function() {
        };
      };
    } else {
      assert4 = __require("assert");
      signals = require_signals();
      isWin = /^win/i.test(process51.platform);
      EE3 = __require("events");
      if (typeof EE3 !== "function") {
        EE3 = EE3.EventEmitter;
      }
      if (process51.__signal_exit_emitter__) {
        emitter = process51.__signal_exit_emitter__;
      } else {
        emitter = process51.__signal_exit_emitter__ = new EE3();
        emitter.count = 0;
        emitter.emitted = {};
      }
      if (!emitter.infinite) {
        emitter.setMaxListeners(Infinity);
        emitter.infinite = true;
      }
      module2.exports = function(cb, opts) {
        if (!processOk(globalThis.process)) {
          return function() {
          };
        }
        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 {
            process51.removeListener(sig, sigListeners[sig]);
          } catch (er2) {
          }
        });
        process51.emit = originalProcessEmit;
        process51.reallyExit = originalProcessReallyExit;
        emitter.count -= 1;
      }, "unload");
      module2.exports.unload = unload;
      emit = /* @__PURE__ */ __name(function emit2(event, code2, signal) {
        if (emitter.emitted[event]) {
          return;
        }
        emitter.emitted[event] = true;
        emitter.emit(event, code2, signal);
      }, "emit");
      sigListeners = {};
      signals.forEach(function(sig) {
        sigListeners[sig] = /* @__PURE__ */ __name(function listener() {
          if (!processOk(globalThis.process)) {
            return;
          }
          var listeners = process51.listeners(sig);
          if (listeners.length === emitter.count) {
            unload();
            emit("exit", null, sig);
            emit("afterexit", null, sig);
            if (isWin && sig === "SIGHUP") {
              sig = "SIGINT";
            }
            process51.kill(process51.pid, sig);
          }
        }, "listener");
      });
      module2.exports.signals = function() {
        return signals;
      };
      loaded = false;
      load = /* @__PURE__ */ __name(function load2() {
        if (loaded || !processOk(globalThis.process)) {
          return;
        }
        loaded = true;
        emitter.count += 1;
        signals = signals.filter(function(sig) {
          try {
            process51.on(sig, sigListeners[sig]);
            return true;
          } catch (er2) {
            return false;
          }
        });
        process51.emit = processEmit;
        process51.reallyExit = processReallyExit;
      }, "load");
      module2.exports.load = load;
      originalProcessReallyExit = process51.reallyExit;
      processReallyExit = /* @__PURE__ */ __name(function processReallyExit2(code2) {
        if (!processOk(globalThis.process)) {
          return;
        }
        process51.exitCode = code2 || /* istanbul ignore next */
        0;
        emit("exit", process51.exitCode, null);
        emit("afterexit", process51.exitCode, null);
        originalProcessReallyExit.call(process51, process51.exitCode);
      }, "processReallyExit");
      originalProcessEmit = process51.emit;
      processEmit = /* @__PURE__ */ __name(function processEmit2(ev, arg) {
        if (ev === "exit" && processOk(globalThis.process)) {
          if (arg !== void 0) {
            process51.exitCode = arg;
          }
          var ret = originalProcessEmit.apply(this, arguments);
          emit("exit", process51.exitCode, null);
          emit("afterexit", process51.exitCode, null);
          return ret;
        } else {
          return originalProcessEmit.apply(this, arguments);
        }
      }, "processEmit");
    }
    var 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 noop11() {
      }
      __name(noop11, "noop");
      function formatProdErrorMessage(code2) {
        var url3 = "https://react.dev/errors/" + code2;
        if (1 < arguments.length) {
          url3 += "?args[]=" + encodeURIComponent(arguments[1]);
          for (var i4 = 2; i4 < arguments.length; i4++)
            url3 += "&args[]=" + encodeURIComponent(arguments[i4]);
        }
        return "Minified React error #" + code2 + "; visit " + url3 + " 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 = [], i4 = 0; 31 > i4; i4++) 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 (err2) {
          }
      }
      __name(setIsStrictModeForDevtools, "setIsStrictModeForDevtools");
      function describeBuiltInComponentFrame(name4) {
        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 + name4 + 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 info2 = "";
          do
            info2 += describeFiber(workInProgress2), workInProgress2 = workInProgress2.return;
          while (workInProgress2);
          return info2;
        } 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 error40 = Error(formatProdErrorMessage(418, ""));
        queueHydrationError(createCapturedValueAtFiber(error40, 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(error40) {
        null === hydrationErrors ? hydrationErrors = [error40] : hydrationErrors.push(error40);
      }
      __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 i4 = 0; i4 < contexts.length; i4++)
                if (dependency.context === contexts[i4]) {
                  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(resolve42) {
              entangledListeners.push(resolve42);
            }, "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 i4 = 0; i4 < listeners.length; i4++) (0, listeners[i4])();
        }
      }
      __name(pingEngtangledActionScope, "pingEngtangledActionScope");
      function chainThenableValue(thenable, result) {
        var listeners = [], thenableWithOverride = {
          status: "pending",
          value: null,
          reason: null,
          then: /* @__PURE__ */ __name(function(resolve42) {
            listeners.push(resolve42);
          }, "then")
        };
        thenable.then(
          function() {
            thenableWithOverride.status = "fulfilled";
            thenableWithOverride.value = result;
            for (var i4 = 0; i4 < listeners.length; i4++) (0, listeners[i4])(result);
          },
          function(error40) {
            thenableWithOverride.status = "rejected";
            thenableWithOverride.reason = error40;
            for (error40 = 0; error40 < listeners.length; error40++)
              (0, listeners[error40])(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 (!hasOwnProperty3.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(error40) {
                  if ("pending" === thenable.status) {
                    var rejectedThenable = thenable;
                    rejectedThenable.status = "rejected";
                    rejectedThenable.reason = error40;
                  }
                }
              );
            }
            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, i4 = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i4 < endIndex; ) {
          var fiber = concurrentQueues[i4];
          concurrentQueues[i4++] = null;
          var queue = concurrentQueues[i4];
          concurrentQueues[i4++] = null;
          var update2 = concurrentQueues[i4];
          concurrentQueues[i4++] = null;
          var lane = concurrentQueues[i4];
          concurrentQueues[i4++] = 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 instance2 = instance$jscomp$0;
                switch (update2.tag) {
                  case 1:
                    workInProgress2 = update2.payload;
                    if ("function" === typeof workInProgress2) {
                      newState = workInProgress2.call(
                        instance2,
                        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(instance2, 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 i4 = 0; i4 < prevDeps.length && i4 < nextDeps.length; i4++)
          if (!objectIs(nextDeps[i4], prevDeps[i4])) 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 create4 = subscribeToStore.bind(null, fiber, hook, subscribe);
        updateEffectImpl(2048, 8, create4, [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 (error40) {
          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 (error40) {
            onActionError(actionQueue, node, error40);
          } 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(error40) {
            return onActionError(actionQueue, node, error40);
          }
        ) : 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, error40) {
        var last2 = actionQueue.pending;
        actionQueue.pending = null;
        if (null !== last2) {
          last2 = last2.next;
          do
            actionNode.status = "rejected", actionNode.reason = error40, notifyActionListeners(actionNode), actionNode = actionNode.next;
          while (actionNode !== last2);
        }
        actionQueue.action = null;
      }
      __name(onActionError, "onActionError");
      function notifyActionListeners(actionNode) {
        actionNode = actionNode.listeners;
        for (var i4 = 0; i4 < actionNode.length; i4++) (0, actionNode[i4])();
      }
      __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, create4, createDeps) {
        tag2 = {
          tag: tag2,
          create: create4,
          deps: createDeps,
          inst,
          next: null
        };
        inst = currentlyRenderingFiber.updateQueue;
        null === inst && (inst = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = inst);
        create4 = inst.lastEffect;
        null === create4 ? inst.lastEffect = tag2.next = tag2 : (createDeps = create4.next, create4.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, create4, createDeps) {
        var hook = mountWorkInProgressHook();
        createDeps = void 0 === createDeps ? null : createDeps;
        currentlyRenderingFiber.flags |= fiberFlags;
        hook.memoizedState = pushSimpleEffect(
          1 | hookFlags,
          createEffectInstance(),
          create4,
          createDeps
        );
      }
      __name(mountEffectImpl, "mountEffectImpl");
      function updateEffectImpl(fiberFlags, hookFlags, create4, 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, create4, deps) : (currentlyRenderingFiber.flags |= fiberFlags, hook.memoizedState = pushSimpleEffect(
          1 | hookFlags,
          inst,
          create4,
          deps
        ));
      }
      __name(updateEffectImpl, "updateEffectImpl");
      function mountEffect(create4, createDeps) {
        mountEffectImpl(8390656, 8, create4, createDeps);
      }
      __name(mountEffect, "mountEffect");
      function updateEffect(create4, createDeps) {
        updateEffectImpl(2048, 8, create4, createDeps);
      }
      __name(updateEffect, "updateEffect");
      function updateInsertionEffect(create4, deps) {
        return updateEffectImpl(4, 2, create4, deps);
      }
      __name(updateInsertionEffect, "updateInsertionEffect");
      function updateLayoutEffect(create4, deps) {
        return updateEffectImpl(4, 4, create4, deps);
      }
      __name(updateLayoutEffect, "updateLayoutEffect");
      function imperativeHandleEffect(create4, ref) {
        if ("function" === typeof ref) {
          create4 = create4();
          var refCleanup = ref(create4);
          return function() {
            "function" === typeof refCleanup ? refCleanup() : ref(null);
          };
        }
        if (null !== ref && void 0 !== ref)
          return create4 = create4(), ref.current = create4, function() {
            ref.current = null;
          };
      }
      __name(imperativeHandleEffect, "imperativeHandleEffect");
      function updateImperativeHandle(ref, create4, deps) {
        deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
        updateEffectImpl(
          4,
          4,
          imperativeHandleEffect.bind(null, create4, 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 (error40) {
          dispatchSetStateInternal(
            fiber,
            queue,
            { then: /* @__PURE__ */ __name(function() {
            }, "then"), status: "rejected", reason: error40 },
            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 (error40) {
            } 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 init2 = lazyType2._init;
        return init2(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 init2 = newChild._init;
                newChild = init2(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 init2 = newChild._init;
                newChild = init2(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, instance2, newProps, nextContext) {
        workInProgress2 = instance2.state;
        "function" === typeof instance2.componentWillReceiveProps && instance2.componentWillReceiveProps(newProps, nextContext);
        "function" === typeof instance2.UNSAFE_componentWillReceiveProps && instance2.UNSAFE_componentWillReceiveProps(newProps, nextContext);
        instance2.state !== workInProgress2 && classComponentUpdater.enqueueReplaceState(instance2, instance2.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 error40 = errorInfo.value;
          update2.payload = function() {
            return getDerivedStateFromError(error40);
          };
          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, init2 = lazyComponent._init;
              lazyComponent = init2(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 (init2 = lazyComponent.$$typeof, init2 === REACT_FORWARD_REF_TYPE) {
                    workInProgress2.tag = 11;
                    workInProgress2 = updateForwardRef(
                      null,
                      workInProgress2,
                      lazyComponent,
                      current,
                      renderLanes2
                    );
                    break a;
                  } else if (init2 === 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, init2 = resolveClassComponentProps(
              lazyComponent,
              workInProgress2.pendingProps
            ), updateClassComponent(
              current,
              workInProgress2,
              lazyComponent,
              init2,
              renderLanes2
            );
          case 3:
            a: {
              pushHostContainer(
                workInProgress2,
                workInProgress2.stateNode.containerInfo
              );
              if (null === current) throw Error(formatProdErrorMessage(387));
              var nextProps = workInProgress2.pendingProps;
              init2 = workInProgress2.memoizedState;
              lazyComponent = init2.element;
              cloneUpdateQueue(current, workInProgress2);
              processUpdateQueue(workInProgress2, nextProps, null, renderLanes2);
              var nextState = workInProgress2.memoizedState;
              nextProps = nextState.cache;
              pushProvider(workInProgress2, CacheContext, nextProps);
              nextProps !== init2.cache && propagateContextChanges(
                workInProgress2,
                [CacheContext],
                renderLanes2,
                true
              );
              suspendIfUpdateReadFromEntangledAsyncAction();
              nextProps = nextState.element;
              if (supportsHydration && init2.isDehydrated)
                if (init2 = {
                  element: nextProps,
                  isDehydrated: false,
                  cache: nextState.cache
                }, workInProgress2.updateQueue.baseState = init2, workInProgress2.memoizedState = init2, 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 (init2 = lazyComponent = nextHydratableInstance)
                lazyComponent = canHydrateInstance(
                  lazyComponent,
                  workInProgress2.type,
                  workInProgress2.pendingProps,
                  rootOrSingletonContext
                ), null !== lazyComponent ? (workInProgress2.stateNode = lazyComponent, hydrationParentFiber = workInProgress2, nextHydratableInstance = getFirstHydratableChild(lazyComponent), rootOrSingletonContext = false, init2 = true) : init2 = false;
              init2 || throwOnHydrationMismatch(workInProgress2);
            }
            pushHostContext(workInProgress2);
            init2 = workInProgress2.type;
            nextProps = workInProgress2.pendingProps;
            nextState = null !== current ? current.memoizedProps : null;
            lazyComponent = nextProps.children;
            shouldSetTextContent(init2, nextProps) ? lazyComponent = null : null !== nextState && shouldSetTextContent(init2, nextState) && (workInProgress2.flags |= 32);
            null !== workInProgress2.memoizedState && (init2 = renderWithHooks(
              current,
              workInProgress2,
              TransitionAwareHostComponent,
              null,
              null,
              renderLanes2
            ), isPrimaryRenderer ? HostTransitionContext._currentValue = init2 : HostTransitionContext._currentValue2 = init2);
            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 init2 = workInProgress2.type._context, lazyComponent = workInProgress2.pendingProps.children, prepareToReadContext(workInProgress2), init2 = readContext(init2), lazyComponent = lazyComponent(init2), 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 ? (init2 = peekCacheFromPool(), null === init2 && (init2 = workInProgressRoot, nextProps = createCache(), init2.pooledCache = nextProps, nextProps.refCount++, null !== nextProps && (init2.pooledCacheLanes |= renderLanes2), init2 = nextProps), workInProgress2.memoizedState = {
              parent: lazyComponent,
              cache: init2
            }, initializeUpdateQueue(workInProgress2), pushProvider(workInProgress2, CacheContext, init2)) : (0 !== (current.lanes & renderLanes2) && (cloneUpdateQueue(current, workInProgress2), processUpdateQueue(workInProgress2, null, null, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction()), init2 = current.memoizedState, nextProps = workInProgress2.memoizedState, init2.parent !== lazyComponent ? (init2 = { parent: lazyComponent, cache: lazyComponent }, workInProgress2.memoizedState = init2, 0 === workInProgress2.lanes && (workInProgress2.memoizedState = workInProgress2.updateQueue.baseState = init2), pushProvider(workInProgress2, CacheContext, lazyComponent)) : (lazyComponent = nextProps.cache, pushProvider(workInProgress2, CacheContext, lazyComponent), lazyComponent !== init2.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 instance2 = node$93.stateNode;
              needsVisibilityToggle && isHidden2 && (instance2 = cloneHiddenInstance(
                instance2,
                node$93.type,
                node$93.memoizedProps
              ));
              appendInitialChild(parent, instance2);
            } else if (6 === node$93.tag)
              instance2 = node$93.stateNode, needsVisibilityToggle && isHidden2 && (instance2 = cloneHiddenTextInstance(
                instance2,
                node$93.memoizedProps
              )), appendInitialChild(parent, instance2);
            else if (4 !== node$93.tag) {
              if (22 === node$93.tag && null !== node$93.memoizedState)
                instance2 = node$93.child, null !== instance2 && (instance2.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 instance2 = node.stateNode;
              needsVisibilityToggle && isHidden2 && (instance2 = cloneHiddenInstance(
                instance2,
                node.type,
                node.memoizedProps
              ));
              appendChildToContainerChildSet(containerChildSet, instance2);
            } else if (6 === node.tag)
              instance2 = node.stateNode, needsVisibilityToggle && isHidden2 && (instance2 = cloneHiddenTextInstance(
                instance2,
                node.memoizedProps
              )), appendChildToContainerChildSet(containerChildSet, instance2);
            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 = createInstance3(
                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(flags2, 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 & flags2) === flags2) {
                lastEffect = void 0;
                var create4 = updateQueue.create, inst = updateQueue.inst;
                lastEffect = create4();
                inst.destroy = lastEffect;
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __name(commitHookEffectListMount, "commitHookEffectListMount");
      function commitHookEffectListUnmount(flags2, 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 & flags2) === flags2) {
                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 (error40) {
                    captureCommitPhaseError(
                      lastEffect,
                      nearestMountedAncestor,
                      error40
                    );
                  }
                }
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __name(commitHookEffectListUnmount, "commitHookEffectListUnmount");
      function commitClassCallbacks(finishedWork) {
        var updateQueue = finishedWork.updateQueue;
        if (null !== updateQueue) {
          var instance2 = finishedWork.stateNode;
          try {
            commitCallbacks(updateQueue, instance2);
          } catch (error40) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error40);
          }
        }
      }
      __name(commitClassCallbacks, "commitClassCallbacks");
      function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance2) {
        instance2.props = resolveClassComponentProps(
          current.type,
          current.memoizedProps
        );
        instance2.state = current.memoizedState;
        try {
          instance2.componentWillUnmount();
        } catch (error40) {
          captureCommitPhaseError(current, nearestMountedAncestor, error40);
        }
      }
      __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 (error40) {
          captureCommitPhaseError(current, nearestMountedAncestor, error40);
        }
      }
      __name(safelyAttachRef, "safelyAttachRef");
      function safelyDetachRef(current, nearestMountedAncestor) {
        var ref = current.ref, refCleanup = current.refCleanup;
        if (null !== ref)
          if ("function" === typeof refCleanup)
            try {
              refCleanup();
            } catch (error40) {
              captureCommitPhaseError(current, nearestMountedAncestor, error40);
            } 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, instance2 = finishedWork.stateNode;
        try {
          commitMount(instance2, type, props, finishedWork);
        } catch (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __name(commitHostMount, "commitHostMount");
      function commitHostUpdate(finishedWork, newProps, oldProps) {
        try {
          commitUpdate(
            finishedWork.stateNode,
            finishedWork.type,
            oldProps,
            newProps,
            finishedWork
          );
        } catch (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __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 (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __name(commitHostPortalContainerChildren, "commitHostPortalContainerChildren");
      function commitHostSingletonAcquisition(finishedWork) {
        var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
        try {
          acquireSingletonInstance(
            finishedWork.type,
            props,
            singleton,
            finishedWork
          );
        } catch (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __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 instance2 = finishedWork.stateNode;
                    try {
                      var resolvedPrevProps = resolveClassComponentProps(
                        finishedWork.type,
                        prevProps,
                        finishedWork.elementType === finishedWork.type
                      );
                      firstChild = instance2.getSnapshotBeforeUpdate(
                        resolvedPrevProps,
                        current
                      );
                      instance2.__reactInternalSnapshotBeforeUpdate = firstChild;
                    } catch (error40) {
                      captureCommitPhaseError(
                        finishedWork,
                        finishedWork.return,
                        error40
                      );
                    }
                  }
                  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 flags2 = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags2 & 4 && commitHookEffectListMount(5, finishedWork);
            break;
          case 1:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (flags2 & 4)
              if (finishedRoot = finishedWork.stateNode, null === current)
                try {
                  finishedRoot.componentDidMount();
                } catch (error40) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error40);
                }
              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
                  );
                }
              }
            flags2 & 64 && commitClassCallbacks(finishedWork);
            flags2 & 512 && safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 3:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (flags2 & 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 (error40) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error40);
              }
            }
            break;
          case 27:
            supportsSingletons && null === current && flags2 & 4 && commitHostSingletonAcquisition(finishedWork);
          case 26:
          case 5:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            null === current && flags2 & 4 && commitHostMount(finishedWork);
            flags2 & 512 && safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 12:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            break;
          case 13:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags2 & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
            flags2 & 64 && (finishedRoot = finishedWork.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot && (finishedWork = retryDehydratedSuspenseBoundary.bind(
              null,
              finishedWork
            ), registerSuspenseInstanceRetry(finishedRoot, finishedWork))));
            break;
          case 22:
            flags2 = null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
            if (!flags2) {
              current = null !== current && null !== current.memoizedState || offscreenSubtreeWasHidden;
              prevProps = offscreenSubtreeIsHidden;
              var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
              offscreenSubtreeIsHidden = flags2;
              (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 (err2) {
          }
        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 (error40) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error40
                    );
                  }
                else
                  try {
                    removeChild(hostParent, deletedFiber.stateNode);
                  } catch (error40) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error40
                    );
                  }
            } 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 (error40) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error40);
          }
      }
      __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 i4 = 0; i4 < deletions.length; i4++) {
            var childToDelete = deletions[i4], 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, flags2 = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 14:
          case 15:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags2 & 4 && (commitHookEffectListUnmount(3, finishedWork, finishedWork.return), commitHookEffectListMount(3, finishedWork), commitHookEffectListUnmount(5, finishedWork, finishedWork.return));
            break;
          case 1:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags2 & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
            flags2 & 64 && offscreenSubtreeIsHidden && (finishedWork = finishedWork.updateQueue, null !== finishedWork && (flags2 = finishedWork.callbacks, null !== flags2 && (current = finishedWork.shared.hiddenCallbacks, finishedWork.shared.hiddenCallbacks = null === current ? flags2 : current.concat(flags2))));
            break;
          case 26:
            if (supportsResources) {
              var hoistableRoot = currentHoistableRoot;
              recursivelyTraverseMutationEffects(root, finishedWork);
              commitReconciliationEffects(finishedWork);
              flags2 & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
              if (flags2 & 4) {
                flags2 = 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
                ) : flags2 !== newResource ? (null === flags2 ? null !== current.stateNode && unmountHoistable(current.stateNode) : releaseResource(flags2), 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);
              flags2 & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
              null !== current && flags2 & 4 && commitHostUpdate(
                finishedWork,
                finishedWork.memoizedProps,
                current.memoizedProps
              );
              break;
            }
          case 5:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags2 & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
            if (supportsMutation) {
              if (finishedWork.flags & 32) {
                hoistableRoot = finishedWork.stateNode;
                try {
                  resetTextContent(hoistableRoot);
                } catch (error40) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error40);
                }
              }
              flags2 & 4 && null != finishedWork.stateNode && (hoistableRoot = finishedWork.memoizedProps, commitHostUpdate(
                finishedWork,
                hoistableRoot,
                null !== current ? current.memoizedProps : hoistableRoot
              ));
              flags2 & 1024 && (needsFormReset = true);
            }
            break;
          case 6:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags2 & 4 && supportsMutation) {
              if (null === finishedWork.stateNode)
                throw Error(formatProdErrorMessage(162));
              flags2 = finishedWork.memoizedProps;
              current = null !== current ? current.memoizedProps : flags2;
              hoistableRoot = finishedWork.stateNode;
              try {
                commitTextUpdate(hoistableRoot, current, flags2);
              } catch (error40) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error40);
              }
            }
            break;
          case 3:
            supportsResources ? (prepareToCommitHoistables(), hoistableRoot = currentHoistableRoot, currentHoistableRoot = getHoistableRoot(root.containerInfo), recursivelyTraverseMutationEffects(root, finishedWork), currentHoistableRoot = hoistableRoot) : recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags2 & 4) {
              if (supportsMutation && supportsHydration && null !== current && current.memoizedState.isDehydrated)
                try {
                  commitHydratedContainer(root.containerInfo);
                } catch (error40) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error40);
                }
              if (supportsPersistence) {
                flags2 = root.containerInfo;
                current = root.pendingChildren;
                try {
                  replaceContainerChildren(flags2, current);
                } catch (error40) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error40);
                }
              }
            }
            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));
            flags2 & 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());
            flags2 & 4 && (flags2 = finishedWork.updateQueue, null !== flags2 && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags2)));
            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 (flags2 & 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 (error40) {
                        captureCommitPhaseError(wasHidden, wasHidden.return, error40);
                      }
                    }
                  } else if (6 === root.tag) {
                    if (null === current) {
                      wasHidden = root;
                      try {
                        var instance2 = wasHidden.stateNode;
                        hoistableRoot ? hideTextInstance(instance2) : unhideTextInstance(instance2, wasHidden.memoizedProps);
                      } catch (error40) {
                        captureCommitPhaseError(wasHidden, wasHidden.return, error40);
                      }
                    }
                  } 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;
                }
            }
            flags2 & 4 && (flags2 = finishedWork.updateQueue, null !== flags2 && (current = flags2.retryQueue, null !== current && (flags2.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current))));
            break;
          case 19:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags2 & 4 && (flags2 = finishedWork.updateQueue, null !== flags2 && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags2)));
            break;
          case 30:
            break;
          case 21:
            break;
          default:
            recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork);
        }
      }
      __name(commitMutationEffectsOnFiber, "commitMutationEffectsOnFiber");
      function commitReconciliationEffects(finishedWork) {
        var flags2 = finishedWork.flags;
        if (flags2 & 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 (error40) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error40);
          }
          finishedWork.flags &= -3;
        }
        flags2 & 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 instance2 = finishedWork.stateNode;
              "function" === typeof instance2.componentWillUnmount && safelyCallComponentWillUnmount(
                finishedWork,
                finishedWork.return,
                instance2
              );
              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, flags2 = 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 (error40) {
                  captureCommitPhaseError(current, current.return, error40);
                }
              current = finishedWork;
              finishedRoot = current.updateQueue;
              if (null !== finishedRoot) {
                var instance2 = 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], instance2);
                } catch (error40) {
                  captureCommitPhaseError(current, current.return, error40);
                }
              }
              includeWorkInProgressEffects && flags2 & 64 && commitClassCallbacks(finishedWork);
              safelyAttachRef(finishedWork, finishedWork.return);
              break;
            case 27:
              supportsSingletons && commitHostSingletonAcquisition(finishedWork);
            case 26:
            case 5:
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              includeWorkInProgressEffects && null === current && flags2 & 4 && commitHostMount(finishedWork);
              safelyAttachRef(finishedWork, finishedWork.return);
              break;
            case 12:
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              break;
            case 13:
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              includeWorkInProgressEffects && flags2 & 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 flags2 = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags2 & 2048 && commitHookEffectListMount(9, finishedWork);
            break;
          case 1:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            break;
          case 3:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags2 & 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 (flags2 & 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 (error40) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error40);
              }
            } 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)
            ));
            flags2 & 2048 && commitOffscreenPassiveMountEffects(id, finishedWork);
            break;
          case 24:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags2 & 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, flags2 = 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 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 && flags2 & 2048 && commitOffscreenPassiveMountEffects(
                finishedWork.alternate,
                finishedWork
              );
              break;
            case 24:
              recursivelyTraverseReconnectPassiveEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions,
                includeWorkInProgressEffects
              );
              includeWorkInProgressEffects && flags2 & 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, flags2 = finishedWork.flags;
            switch (finishedWork.tag) {
              case 22:
                recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
                flags2 & 2048 && commitOffscreenPassiveMountEffects(
                  finishedWork.alternate,
                  finishedWork
                );
                break;
              case 24:
                recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
                flags2 & 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 i4 = 0; i4 < deletions.length; i4++) {
              var childToDelete = deletions[i4];
              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 instance2 = finishedWork.stateNode;
            null !== finishedWork.memoizedState && instance2._visibility & 2 && (null === finishedWork.return || 13 !== finishedWork.return.tag) ? (instance2._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 i4 = 0; i4 < deletions.length; i4++) {
              var childToDelete = deletions[i4];
              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:
              i4 = deletions.stateNode;
              i4._visibility & 2 && (i4._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 i4 = 0; i4 < tag2.length; i4++) {
              var check2 = tag2[i4], getSnapshot = check2.getSnapshot;
              check2 = check2.value;
              try {
                if (!objectIs(getSnapshot(), check2)) return false;
              } catch (error40) {
                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 (error40) {
          if (null !== returnFiber) throw workInProgress = returnFiber, error40;
          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 (err2) {
            }
          if (null !== recoverableErrors) {
            finishedWork = ReactSharedInternals.T;
            remainingLanes = getCurrentUpdatePriority();
            setCurrentUpdatePriority(2);
            ReactSharedInternals.T = null;
            try {
              for (var onRecoverableError = root.onRecoverableError, i4 = 0; i4 < recoverableErrors.length; i4++) {
                var recoverableError = recoverableErrors[i4];
                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 (err2) {
            }
          return true;
        } finally {
          setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = renderPriority, releaseRootPooledCache(root, remainingLanes);
        }
      }
      __name(flushPassiveEffects, "flushPassiveEffects");
      function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error40) {
        sourceFiber = createCapturedValueAtFiber(error40, 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, error40) {
        if (3 === sourceFiber.tag)
          captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error40);
        else
          for (; null !== nearestMountedAncestor; ) {
            if (3 === nearestMountedAncestor.tag) {
              captureCommitPhaseErrorOnRoot(
                nearestMountedAncestor,
                sourceFiber,
                error40
              );
              break;
            } else if (1 === nearestMountedAncestor.tag) {
              var instance2 = nearestMountedAncestor.stateNode;
              if ("function" === typeof nearestMountedAncestor.type.getDerivedStateFromError || "function" === typeof instance2.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(instance2))) {
                sourceFiber = createCapturedValueAtFiber(error40, sourceFiber);
                error40 = createClassErrorUpdate(2);
                instance2 = enqueueUpdate(nearestMountedAncestor, error40, 2);
                null !== instance2 && (initializeClassErrorUpdate(
                  error40,
                  instance2,
                  nearestMountedAncestor,
                  sourceFiber
                ), markRootUpdated$1(instance2, 2), ensureRootIsScheduled(instance2));
                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, createInstance3 = $$$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), hasOwnProperty3 = 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, create4, deps) {
          deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
          mountEffectImpl(
            4194308,
            4,
            imperativeHandleEffect.bind(null, create4, ref),
            deps
          );
        }, "useImperativeHandle"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create4, deps) {
          return mountEffectImpl(4194308, 4, create4, deps);
        }, "useLayoutEffect"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create4, deps) {
          mountEffectImpl(4, 2, create4, 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, init2) {
          var hook = mountWorkInProgressHook();
          if (void 0 !== init2) {
            var initialState2 = init2(initialArg);
            if (shouldDoubleInvokeUserFnsInHooksDEV) {
              setIsStrictModeForDevtools(true);
              try {
                init2(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], start2 = updateWorkInProgressHook().memoizedState;
          return [
            "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
            start2
          ];
        }, "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], start2 = updateWorkInProgressHook().memoizedState;
          return [
            "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
            start2
          ];
        }, "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(error40) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error40 && null !== error40 && "string" === typeof error40.message ? String(error40.message) : String(error40),
            error: error40
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error40);
          return;
        }
        console.error(error40);
      }, 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(error40) {
        console.error(error40);
      };
      exports3.defaultOnRecoverableError = function(error40) {
        reportGlobalError(error40);
      };
      exports3.defaultOnUncaughtError = function(error40) {
        reportGlobalError(error40);
      };
      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 i4 = 0; i4 < selectors.length; i4++)
          hostRoot.push(getBoundingRect(selectors[i4]));
        for (selectors = hostRoot.length - 1; 0 < selectors; selectors--) {
          i4 = hostRoot[selectors];
          for (var targetLeft = i4.x, targetRight = targetLeft + i4.width, targetTop = i4.y, targetBottom = targetTop + i4.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 || i4.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 || i4.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 (err2) {
            }
            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 ? noop11 : 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, path150, index, value) {
        if (index >= path150.length) return value;
        var key = path150[index], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
        updated[key] = copyWithSetImpl(obj[key], path150, 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 i4 = 0; i4 < newPath.length - 1; i4++)
            if (oldPath[i4] !== newPath[i4]) {
              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, path150, index) {
        var key = path150[index], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
        if (index + 1 === path150.length)
          return isArrayImpl(updated) ? updated.splice(key, 1) : delete updated[key], updated;
        updated[key] = copyWithDeleteImpl(obj[key], path150, 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 !== resolveFamily2) {
          var staleFamilies = update2.staleFamilies;
          update2 = update2.updatedFamilies;
          flushPendingEffects();
          scheduleFibersWithFamiliesRecursively(
            root.current,
            update2,
            staleFamilies
          );
          flushSyncWork();
        }
      }
      __name(scheduleRefresh, "scheduleRefresh");
      function setRefreshHandler(handler) {
        resolveFamily2 = 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 noop11() {
      }
      __name(noop11, "noop");
      function setToSortedString(set2) {
        var array2 = [];
        set2.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 i4 = type.length - 1; 0 <= i4; i4--)
                if ("string" === typeof type[i4].name) return type[i4].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 = [], i4 = 0; 31 > i4; i4++) 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 (err2) {
          console.error("React instrumentation encountered an error: %s.", err2);
        }
        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 (err2) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %s",
              err2
            ));
          }
      }
      __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(name4) {
        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 + name4 + 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(error40) {
        var prevPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        error40 = error40.stack;
        Error.prepareStackTrace = prevPrepareStackTrace;
        error40.startsWith("Error: react-stack-top-frame\n") && (error40 = error40.slice(29));
        prevPrepareStackTrace = error40.indexOf("\n");
        -1 !== prevPrepareStackTrace && (error40 = error40.slice(prevPrepareStackTrace + 1));
        prevPrepareStackTrace = error40.indexOf("react-stack-bottom-frame");
        -1 !== prevPrepareStackTrace && (prevPrepareStackTrace = error40.lastIndexOf(
          "\n",
          prevPrepareStackTrace
        ));
        if (-1 !== prevPrepareStackTrace)
          error40 = error40.slice(0, prevPrepareStackTrace);
        else return "";
        return error40;
      }
      __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 info2 = "";
          do {
            info2 += describeFiber(workInProgress2);
            var debugInfo = workInProgress2._debugInfo;
            if (debugInfo)
              for (var i4 = debugInfo.length - 1; 0 <= i4; i4--) {
                var entry = debugInfo[i4];
                if ("string" === typeof entry.name) {
                  var JSCompiler_temp_const = info2, env6 = entry.env;
                  var JSCompiler_inline_result = describeBuiltInComponentFrame(
                    entry.name + (env6 ? " [" + env6 + "]" : "")
                  );
                  info2 = JSCompiler_temp_const + JSCompiler_inline_result;
                }
              }
            workInProgress2 = workInProgress2.return;
          } while (workInProgress2);
          return info2;
        } 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 name4 = objectName(value);
            if ("Object" === name4) {
              name4 = "";
              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) {
                    name4 += "" === name4 ? "..." : ", ...";
                    break;
                  }
                  name4 += ("" === name4 ? "" : ",") + propName + ":" + jsonPropName;
                }
              return "{" + name4 + "}";
            }
            return name4;
          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 i4 = 0; i4 < debugInfo.length; i4++) {
            var serverComponentName = debugInfo[i4].name;
            "string" === typeof serverComponentName && (skipToNode += indentation(indent) + "<" + serverComponentName + ">\n", indent++);
          }
        debugInfo = "";
        i4 = node.fiber.pendingProps;
        if (6 === node.fiber.tag)
          debugInfo = describeTextDiff(i4, 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 i4)
              if (i4.hasOwnProperty(propName) && "children" !== propName) {
                var propValue = describePropValue(i4[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,
              i4,
              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,
              i4,
              node.serverProps,
              indent
            ), indent++);
        var propName = "";
        i4 = node.fiber.child;
        for (serverComponentName = 0; i4 && serverComponentName < node.children.length; )
          maxLength = node.children[serverComponentName], maxLength.fiber === i4 ? (propName += describeNode(maxLength, indent), serverComponentName++) : propName += describeSiblingFiber(i4, indent), i4 = i4.sibling;
        i4 && 0 < node.children.length && (propName += indentation(indent) + "...\n");
        i4 = node.serverTail;
        null === node.serverProps && indent--;
        for (node = 0; node < i4.length; node++)
          serverComponentName = i4[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 info2 = "";
          6 === workInProgress2.tag && (workInProgress2 = workInProgress2.return);
          switch (workInProgress2.tag) {
            case 26:
            case 27:
            case 5:
              info2 += describeBuiltInComponentFrame(workInProgress2.type);
              break;
            case 13:
              info2 += describeBuiltInComponentFrame("Suspense");
              break;
            case 19:
              info2 += describeBuiltInComponentFrame("SuspenseList");
              break;
            case 31:
              info2 += describeBuiltInComponentFrame("Activity");
              break;
            case 30:
            case 0:
            case 15:
            case 1:
              workInProgress2._debugOwner || "" !== info2 || (info2 += describeFunctionComponentFrameWithoutLineNumber(
                workInProgress2.type
              ));
              break;
            case 11:
              workInProgress2._debugOwner || "" !== info2 || (info2 += 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 && (info2 += "\n" + debugStack));
            } else if (null != workInProgress2.debugStack) {
              var ownerStack = workInProgress2.debugStack;
              (workInProgress2 = workInProgress2.owner) && ownerStack && (info2 += "\n" + formatOwnerStack(ownerStack));
            } else break;
          var JSCompiler_inline_result = info2;
        } 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(error40) {
        null === hydrationErrors ? hydrationErrors = [error40] : hydrationErrors.push(error40);
      }
      __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 i4 = 0; i4 < contexts.length; i4++)
                if (dependency.context === contexts[i4]) {
                  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(resolve42) {
              entangledListeners.push(resolve42);
            }, "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 i4 = 0; i4 < listeners.length; i4++) (0, listeners[i4])();
        }
      }
      __name(pingEngtangledActionScope, "pingEngtangledActionScope");
      function chainThenableValue(thenable, result) {
        var listeners = [], thenableWithOverride = {
          status: "pending",
          value: null,
          reason: null,
          then: /* @__PURE__ */ __name(function(resolve42) {
            listeners.push(resolve42);
          }, "then")
        };
        thenable.then(
          function() {
            thenableWithOverride.status = "fulfilled";
            thenableWithOverride.value = result;
            for (var i4 = 0; i4 < listeners.length; i4++) (0, listeners[i4])(result);
          },
          function(error40) {
            thenableWithOverride.status = "rejected";
            thenableWithOverride.reason = error40;
            for (error40 = 0; error40 < listeners.length; error40++)
              (0, listeners[error40])(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 (!hasOwnProperty3.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(error40) {
                  if ("pending" === thenable.status) {
                    var rejectedThenable = thenable;
                    rejectedThenable.status = "rejected";
                    rejectedThenable.reason = error40;
                  }
                }
              );
            }
            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, i4 = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i4 < endIndex; ) {
          var fiber = concurrentQueues[i4];
          concurrentQueues[i4++] = null;
          var queue = concurrentQueues[i4];
          concurrentQueues[i4++] = null;
          var update2 = concurrentQueues[i4];
          concurrentQueues[i4++] = null;
          var lane = concurrentQueues[i4];
          concurrentQueues[i4++] = 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, instance2 = instance$jscomp$0;
                switch (partialState.tag) {
                  case ReplaceState:
                    partialState = partialState.payload;
                    if ("function" === typeof partialState) {
                      isDisallowedContextReadInDEV = true;
                      var nextState = partialState.call(
                        instance2,
                        newState,
                        nextProps
                      );
                      if (updateLane.mode & 8) {
                        setIsStrictModeForDevtools(true);
                        try {
                          partialState.call(instance2, 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(
                        instance2,
                        newState,
                        nextProps
                      );
                      if (updateLane.mode & 8) {
                        setIsStrictModeForDevtools(true);
                        try {
                          nextState.call(instance2, 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 = "", i4 = 0; i4 <= hookTypesUpdateIndexDev; i4++) {
              var oldHookName = hookTypesDev[i4], newHookName = i4 === hookTypesUpdateIndexDev ? hookName : oldHookName;
              for (oldHookName = i4 + 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 i4 = 0; i4 < prevDeps.length && i4 < nextDeps.length; i4++)
          if (!objectIs(nextDeps[i4], prevDeps[i4])) 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, init2) {
        var hook = mountWorkInProgressHook();
        if (void 0 !== init2) {
          var initialState2 = init2(initialArg);
          if (shouldDoubleInvokeUserFnsInHooksDEV) {
            setIsStrictModeForDevtools(true);
            try {
              init2(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 create4 = subscribeToStore.bind(null, fiber, hook, subscribe);
        updateEffectImpl(2048, Passive, create4, [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 (error40) {
          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 (error40) {
            onActionError(actionQueue, node, error40);
          } 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(error40) {
            return onActionError(actionQueue, node, error40);
          }
        ), 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, error40) {
        var last2 = actionQueue.pending;
        actionQueue.pending = null;
        if (null !== last2) {
          last2 = last2.next;
          do
            actionNode.status = "rejected", actionNode.reason = error40, notifyActionListeners(actionNode), actionNode = actionNode.next;
          while (actionNode !== last2);
        }
        actionQueue.action = null;
      }
      __name(onActionError, "onActionError");
      function notifyActionListeners(actionNode) {
        actionNode = actionNode.listeners;
        for (var i4 = 0; i4 < actionNode.length; i4++) (0, actionNode[i4])();
      }
      __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, create4, createDeps) {
        tag2 = {
          tag: tag2,
          create: create4,
          deps: createDeps,
          inst,
          next: null
        };
        inst = currentlyRenderingFiber.updateQueue;
        null === inst && (inst = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = inst);
        create4 = inst.lastEffect;
        null === create4 ? inst.lastEffect = tag2.next = tag2 : (createDeps = create4.next, create4.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, create4, createDeps) {
        var hook = mountWorkInProgressHook();
        createDeps = void 0 === createDeps ? null : createDeps;
        currentlyRenderingFiber.flags |= fiberFlags;
        hook.memoizedState = pushSimpleEffect(
          HasEffect | hookFlags,
          createEffectInstance(),
          create4,
          createDeps
        );
      }
      __name(mountEffectImpl, "mountEffectImpl");
      function updateEffectImpl(fiberFlags, hookFlags, create4, 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, create4, deps) : (currentlyRenderingFiber.flags |= fiberFlags, hook.memoizedState = pushSimpleEffect(
          HasEffect | hookFlags,
          inst,
          create4,
          deps
        ));
      }
      __name(updateEffectImpl, "updateEffectImpl");
      function mountEffect(create4, createDeps) {
        (currentlyRenderingFiber.mode & 16) !== NoMode && (currentlyRenderingFiber.mode & 64) === NoMode ? mountEffectImpl(276826112, Passive, create4, createDeps) : mountEffectImpl(8390656, Passive, create4, createDeps);
      }
      __name(mountEffect, "mountEffect");
      function mountLayoutEffect(create4, deps) {
        var fiberFlags = 4194308;
        (currentlyRenderingFiber.mode & 16) !== NoMode && (fiberFlags |= 134217728);
        return mountEffectImpl(fiberFlags, Layout, create4, deps);
      }
      __name(mountLayoutEffect, "mountLayoutEffect");
      function imperativeHandleEffect(create4, ref) {
        if ("function" === typeof ref) {
          create4 = create4();
          var refCleanup = ref(create4);
          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(", ") + "}"
          ), create4 = create4(), ref.current = create4, function() {
            ref.current = null;
          };
      }
      __name(imperativeHandleEffect, "imperativeHandleEffect");
      function mountImperativeHandle(ref, create4, deps) {
        "function" !== typeof create4 && console.error(
          "Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.",
          null !== create4 ? typeof create4 : "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, create4, ref),
          deps
        );
      }
      __name(mountImperativeHandle, "mountImperativeHandle");
      function updateImperativeHandle(ref, create4, deps) {
        "function" !== typeof create4 && console.error(
          "Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.",
          null !== create4 ? typeof create4 : "null"
        );
        deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
        updateEffectImpl(
          4,
          Layout,
          imperativeHandleEffect.bind(null, create4, 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 (error40) {
          dispatchSetStateInternal(
            fiber,
            queue,
            { then: /* @__PURE__ */ __name(function() {
            }, "then"), status: "rejected", reason: error40 },
            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], start2 = updateWorkInProgressHook().memoizedState;
        return [
          "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
          start2
        ];
      }
      __name(updateTransition, "updateTransition");
      function rerenderTransition() {
        var booleanOrThenable = rerenderReducer(basicStateReducer)[0], start2 = updateWorkInProgressHook().memoizedState;
        return [
          "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
          start2
        ];
      }
      __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 args2 = arguments;
        "function" === typeof args2[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()."
        );
        args2 = requestUpdateLane(fiber);
        var update2 = {
          lane: args2,
          revertLane: 0,
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        isRenderPhaseUpdate(fiber) ? enqueueRenderPhaseUpdate(queue, update2) : (update2 = enqueueConcurrentHookUpdate(fiber, queue, update2, args2), null !== update2 && (scheduleUpdateOnFiber(update2, fiber, args2), entangleTransitionUpdate(update2, queue, args2)));
        markStateUpdateScheduled(fiber, args2);
      }
      __name(dispatchReducerAction, "dispatchReducerAction");
      function dispatchSetState(fiber, queue, action) {
        var args2 = arguments;
        "function" === typeof args2[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()."
        );
        args2 = requestUpdateLane(fiber);
        dispatchSetStateInternal(fiber, queue, action, args2);
        markStateUpdateScheduled(fiber, args2);
      }
      __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 (error40) {
            } 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), i4 = 0; i4 < keys.length; i4++) {
          var key = keys[i4];
          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 i4 = debugInfo.length - 1; 0 <= i4; i4--)
                if ("string" === typeof debugInfo[i4].stack) {
                  fiber._debugOwner = debugInfo[i4];
                  fiber._debugTask = debugInfo[i4].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 instance2 = workInProgress2.stateNode;
        if ("function" === typeof instance2.shouldComponentUpdate) {
          oldProps = instance2.shouldComponentUpdate(
            newProps,
            newState,
            nextContext
          );
          if (workInProgress2.mode & 8) {
            setIsStrictModeForDevtools(true);
            try {
              oldProps = instance2.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, instance2, newProps, nextContext) {
        var oldState = instance2.state;
        "function" === typeof instance2.componentWillReceiveProps && instance2.componentWillReceiveProps(newProps, nextContext);
        "function" === typeof instance2.UNSAFE_componentWillReceiveProps && instance2.UNSAFE_componentWillReceiveProps(newProps, nextContext);
        instance2.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(
          instance2,
          instance2.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 error40 = errorInfo.value;
          if (null !== ReactSharedInternals.actQueue)
            ReactSharedInternals.thrownErrors.push(error40);
          else {
            var onUncaughtError = root.onUncaughtError;
            onUncaughtError(error40, { 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 error40 = errorInfo.value;
          update2.payload = function() {
            return getDerivedStateFromError(error40);
          };
          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 error40 = 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 = [error40] : workInProgressRootConcurrentErrors.push(error40);
        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, error40 = sourceFiber.stateNode, 0 === (sourceFiber.flags & 128) && ("function" === typeof returnFiber.getDerivedStateFromError || null !== error40 && "function" === typeof error40.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(error40))))
                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 i4 = 0; i4 < nextProps.length; i4++) {
              if (!validateSuspenseListNestedChild(nextProps[i4], i4)) break a;
            }
          else if (i4 = getIteratorFn(nextProps), "function" === typeof i4) {
            if (i4 = i4.call(nextProps))
              for (var step = i4.next(), _i = 0; !step.done; step = i4.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 instance2 = _node.stateNode;
              needsVisibilityToggle && isHidden2 && (instance2 = cloneHiddenInstance(
                instance2,
                _node.type,
                _node.memoizedProps
              ));
              appendInitialChild(parent, instance2);
            } else if (6 === _node.tag)
              instance2 = _node.stateNode, needsVisibilityToggle && isHidden2 && (instance2 = cloneHiddenTextInstance(
                instance2,
                _node.memoizedProps
              )), appendInitialChild(parent, instance2);
            else if (4 !== _node.tag) {
              if (22 === _node.tag && null !== _node.memoizedState)
                instance2 = _node.child, null !== instance2 && (instance2.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 instance2 = node.stateNode;
              needsVisibilityToggle && isHidden2 && (instance2 = cloneHiddenInstance(
                instance2,
                node.type,
                node.memoizedProps
              ));
              appendChildToContainerChildSet(containerChildSet, instance2);
            } else if (6 === node.tag)
              instance2 = node.stateNode, needsVisibilityToggle && isHidden2 && (instance2 = cloneHiddenTextInstance(
                instance2,
                node.memoizedProps
              )), appendChildToContainerChildSet(containerChildSet, instance2);
            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 = createInstance3(
                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(flags2, 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 & flags2) === flags2 && ((flags2 & Passive) !== NoFlags ? null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted && injectedProfilingHooks.markComponentPassiveEffectMountStarted(
                finishedWork
              ) : (flags2 & Layout) !== NoFlags && null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted && injectedProfilingHooks.markComponentLayoutEffectMountStarted(
                finishedWork
              ), lastEffect = void 0, (flags2 & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = runWithFiberInDEV(
                finishedWork,
                callCreateInDEV,
                updateQueue
              ), (flags2 & Insertion) !== NoFlags && (isRunningInsertionEffect = false), (flags2 & Passive) !== NoFlags ? null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped && injectedProfilingHooks.markComponentPassiveEffectMountStopped() : (flags2 & 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 (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __name(commitHookEffectListMount, "commitHookEffectListMount");
      function commitHookEffectListUnmount(flags2, 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 & flags2) === flags2) {
                var inst = updateQueue.inst, destroy = inst.destroy;
                void 0 !== destroy && (inst.destroy = void 0, (flags2 & Passive) !== NoFlags ? null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted && injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(
                  finishedWork
                ) : (flags2 & Layout) !== NoFlags && null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted && injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(
                  finishedWork
                ), (flags2 & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = finishedWork, runWithFiberInDEV(
                  lastEffect,
                  callDestroyInDEV,
                  lastEffect,
                  nearestMountedAncestor,
                  destroy
                ), (flags2 & Insertion) !== NoFlags && (isRunningInsertionEffect = false), (flags2 & Passive) !== NoFlags ? null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped && injectedProfilingHooks.markComponentPassiveEffectUnmountStopped() : (flags2 & Layout) !== NoFlags && null !== injectedProfilingHooks && "function" === typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped && injectedProfilingHooks.markComponentLayoutEffectUnmountStopped());
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __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 instance2 = finishedWork.stateNode;
          finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (instance2.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"
          ), instance2.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,
              instance2
            );
          } catch (error40) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error40);
          }
        }
      }
      __name(commitClassCallbacks, "commitClassCallbacks");
      function callGetSnapshotBeforeUpdates(instance2, prevProps, prevState) {
        return instance2.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 (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __name(commitClassSnapshot, "commitClassSnapshot");
      function safelyCallComponentWillUnmount(current2, nearestMountedAncestor, instance2) {
        instance2.props = resolveClassComponentProps(
          current2.type,
          current2.memoizedProps
        );
        instance2.state = current2.memoizedState;
        shouldProfile(current2) ? (startEffectTimer(), runWithFiberInDEV(
          current2,
          callComponentWillUnmountInDEV,
          current2,
          nearestMountedAncestor,
          instance2
        ), recordEffectDuration()) : runWithFiberInDEV(
          current2,
          callComponentWillUnmountInDEV,
          current2,
          nearestMountedAncestor,
          instance2
        );
      }
      __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 (error40) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error40);
        }
      }
      __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 (error40) {
              captureCommitPhaseError(current2, nearestMountedAncestor, error40);
            } 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, instance2 = finishedWork.stateNode;
        try {
          runWithFiberInDEV(
            finishedWork,
            commitMount,
            instance2,
            type,
            props,
            finishedWork
          );
        } catch (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __name(commitHostMount, "commitHostMount");
      function commitHostUpdate(finishedWork, newProps, oldProps) {
        try {
          runWithFiberInDEV(
            finishedWork,
            commitUpdate,
            finishedWork.stateNode,
            finishedWork.type,
            oldProps,
            newProps,
            finishedWork
          );
        } catch (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __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 (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __name(commitHostPortalContainerChildren, "commitHostPortalContainerChildren");
      function commitHostSingletonAcquisition(finishedWork) {
        var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
        try {
          runWithFiberInDEV(
            finishedWork,
            acquireSingletonInstance,
            finishedWork.type,
            props,
            singleton,
            finishedWork
          );
        } catch (error40) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error40);
        }
      }
      __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, flags2 = firstChild.flags;
              switch (firstChild.tag) {
                case 0:
                  break;
                case 11:
                case 15:
                  break;
                case 1:
                  0 !== (flags2 & 1024) && null !== current2 && commitClassSnapshot(firstChild, current2);
                  break;
                case 3:
                  0 !== (flags2 & 1024) && supportsMutation && clearContainer(firstChild.stateNode.containerInfo);
                  break;
                case 5:
                case 26:
                case 27:
                case 6:
                case 4:
                case 17:
                  break;
                default:
                  if (0 !== (flags2 & 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 flags2 = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags2 & 4 && commitHookLayoutEffects(finishedWork, Layout | HasEffect);
            break;
          case 1:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (flags2 & 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
                );
              }
            flags2 & 64 && commitClassCallbacks(finishedWork);
            flags2 & 512 && safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 3:
            current2 = pushNestedEffectDurations();
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (flags2 & 64 && (flags2 = finishedWork.updateQueue, null !== flags2)) {
              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,
                  flags2,
                  prevProps
                );
              } catch (error40) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error40);
              }
            }
            finishedRoot.effectDuration += popNestedEffectDurations(current2);
            break;
          case 27:
            supportsSingletons && null === current2 && flags2 & 4 && commitHostSingletonAcquisition(finishedWork);
          case 26:
          case 5:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            null === current2 && flags2 & 4 && commitHostMount(finishedWork);
            flags2 & 512 && safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 12:
            if (flags2 & 4) {
              flags2 = pushNestedEffectDurations();
              recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
              finishedRoot = finishedWork.stateNode;
              finishedRoot.effectDuration += bubbleNestedEffectDurations(flags2);
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitProfiler,
                  finishedWork,
                  current2,
                  commitStartTime,
                  finishedRoot.effectDuration
                );
              } catch (error40) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error40);
              }
            } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            break;
          case 13:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags2 & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
            flags2 & 64 && (finishedRoot = finishedWork.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot && (finishedWork = retryDehydratedSuspenseBoundary.bind(
              null,
              finishedWork
            ), registerSuspenseInstanceRetry(finishedRoot, finishedWork))));
            break;
          case 22:
            flags2 = null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
            if (!flags2) {
              current2 = null !== current2 && null !== current2.memoizedState || offscreenSubtreeWasHidden;
              prevProps = offscreenSubtreeIsHidden;
              var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
              offscreenSubtreeIsHidden = flags2;
              (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 (err2) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %s",
              err2
            ));
          }
        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 (error40) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error40
                    );
                  }
                else
                  try {
                    runWithFiberInDEV(
                      deletedFiber,
                      removeChild,
                      hostParent,
                      deletedFiber.stateNode
                    );
                  } catch (error40) {
                    captureCommitPhaseError(
                      deletedFiber,
                      nearestMountedAncestor,
                      error40
                    );
                  }
            } 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 (error40) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error40);
          }
      }
      __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 i4 = 0; i4 < deletions.length; i4++) {
            var root = root$jscomp$0, returnFiber = parentFiber, deletedFiber = deletions[i4];
            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, flags2 = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 14:
          case 15:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags2 & 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);
            flags2 & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
            flags2 & 64 && offscreenSubtreeIsHidden && (finishedWork = finishedWork.updateQueue, null !== finishedWork && (flags2 = finishedWork.callbacks, null !== flags2 && (current2 = finishedWork.shared.hiddenCallbacks, finishedWork.shared.hiddenCallbacks = null === current2 ? flags2 : current2.concat(flags2))));
            break;
          case 26:
            if (supportsResources) {
              var hoistableRoot = currentHoistableRoot;
              recursivelyTraverseMutationEffects(root, finishedWork);
              commitReconciliationEffects(finishedWork);
              flags2 & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
              flags2 & 4 && (flags2 = 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
              ) : flags2 !== root ? (null === flags2 ? null !== current2.stateNode && unmountHoistable(current2.stateNode) : releaseResource(flags2), 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);
              flags2 & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
              null !== current2 && flags2 & 4 && commitHostUpdate(
                finishedWork,
                finishedWork.memoizedProps,
                current2.memoizedProps
              );
              break;
            }
          case 5:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags2 & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
            if (supportsMutation) {
              if (finishedWork.flags & 32) {
                root = finishedWork.stateNode;
                try {
                  runWithFiberInDEV(finishedWork, resetTextContent, root);
                } catch (error40) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error40
                  );
                }
              }
              flags2 & 4 && null != finishedWork.stateNode && (root = finishedWork.memoizedProps, commitHostUpdate(
                finishedWork,
                root,
                null !== current2 ? current2.memoizedProps : root
              ));
              flags2 & 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 (flags2 & 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."
                );
              flags2 = finishedWork.memoizedProps;
              current2 = null !== current2 ? current2.memoizedProps : flags2;
              root = finishedWork.stateNode;
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitTextUpdate,
                  root,
                  current2,
                  flags2
                );
              } catch (error40) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error40);
              }
            }
            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 (flags2 & 4) {
              if (supportsMutation && supportsHydration && null !== current2 && current2.memoizedState.isDehydrated)
                try {
                  runWithFiberInDEV(
                    finishedWork,
                    commitHydratedContainer,
                    root.containerInfo
                  );
                } catch (error40) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error40
                  );
                }
              if (supportsPersistence) {
                flags2 = root.containerInfo;
                current2 = root.pendingChildren;
                try {
                  runWithFiberInDEV(
                    finishedWork,
                    replaceContainerChildren,
                    flags2,
                    current2
                  );
                } catch (error40) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error40
                  );
                }
              }
            }
            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));
            flags2 & 4 && supportsPersistence && commitHostPortalContainerChildren(
              finishedWork.stateNode,
              finishedWork,
              finishedWork.stateNode.pendingChildren
            );
            break;
          case 12:
            flags2 = pushNestedEffectDurations();
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            finishedWork.stateNode.effectDuration += bubbleNestedEffectDurations(flags2);
            break;
          case 13:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            finishedWork.child.flags & 8192 && null !== finishedWork.memoizedState !== (null !== current2 && null !== current2.memoizedState) && (globalMostRecentFallbackTime = now$1());
            flags2 & 4 && (flags2 = finishedWork.updateQueue, null !== flags2 && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags2)));
            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 (flags2 & 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 (error40) {
                        captureCommitPhaseError(
                          wasHidden,
                          wasHidden.return,
                          error40
                        );
                      }
                    }
                  } else if (6 === root.tag) {
                    if (null === current2) {
                      wasHidden = root;
                      try {
                        var instance2 = wasHidden.stateNode;
                        hoistableRoot ? runWithFiberInDEV(
                          wasHidden,
                          hideTextInstance,
                          instance2
                        ) : runWithFiberInDEV(
                          wasHidden,
                          unhideTextInstance,
                          instance2,
                          wasHidden.memoizedProps
                        );
                      } catch (error40) {
                        captureCommitPhaseError(
                          wasHidden,
                          wasHidden.return,
                          error40
                        );
                      }
                    }
                  } 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;
                }
            }
            flags2 & 4 && (flags2 = finishedWork.updateQueue, null !== flags2 && (current2 = flags2.retryQueue, null !== current2 && (flags2.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current2))));
            break;
          case 19:
            recursivelyTraverseMutationEffects(root, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags2 & 4 && (flags2 = finishedWork.updateQueue, null !== flags2 && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags2)));
            break;
          case 30:
            break;
          case 21:
            break;
          default:
            recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork);
        }
      }
      __name(commitMutationEffectsOnFiber, "commitMutationEffectsOnFiber");
      function commitReconciliationEffects(finishedWork) {
        var flags2 = finishedWork.flags;
        if (flags2 & 2) {
          try {
            runWithFiberInDEV(finishedWork, commitPlacement, finishedWork);
          } catch (error40) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error40);
          }
          finishedWork.flags &= -3;
        }
        flags2 & 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 instance2 = finishedWork.stateNode;
            "function" === typeof instance2.componentWillUnmount && safelyCallComponentWillUnmount(
              finishedWork,
              finishedWork.return,
              instance2
            );
            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 flags2 = 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 (error40) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error40);
              }
            }
            includeWorkInProgressEffects && flags2 & 64 && commitClassCallbacks(finishedWork);
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 27:
            supportsSingletons && commitHostSingletonAcquisition(finishedWork);
          case 26:
          case 5:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && null === current2 && flags2 & 4 && commitHostMount(finishedWork);
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 12:
            if (includeWorkInProgressEffects && flags2 & 4) {
              flags2 = pushNestedEffectDurations();
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              includeWorkInProgressEffects = finishedWork.stateNode;
              includeWorkInProgressEffects.effectDuration += bubbleNestedEffectDurations(flags2);
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitProfiler,
                  finishedWork,
                  current2,
                  commitStartTime,
                  includeWorkInProgressEffects.effectDuration
                );
              } catch (error40) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error40);
              }
            } else
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
            break;
          case 13:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && flags2 & 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 flags2 = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags2 & 2048 && commitHookPassiveMountEffects(finishedWork, Passive | HasEffect);
            break;
          case 1:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            break;
          case 3:
            var prevEffectDuration = pushNestedEffectDurations();
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags2 & 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 (flags2 & 2048) {
              flags2 = pushNestedEffectDurations();
              recursivelyTraversePassiveMountEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions
              );
              finishedRoot = finishedWork.stateNode;
              finishedRoot.passiveEffectDuration += bubbleNestedEffectDurations(flags2);
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitProfilerPostCommitImpl,
                  finishedWork,
                  finishedWork.alternate,
                  commitStartTime,
                  finishedRoot.passiveEffectDuration
                );
              } catch (error40) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error40);
              }
            } 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)
            ));
            flags2 & 2048 && commitOffscreenPassiveMountEffects(_current, finishedWork);
            break;
          case 24:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions
            );
            flags2 & 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 flags2 = 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 && flags2 & 2048 && commitOffscreenPassiveMountEffects(
              finishedWork.alternate,
              finishedWork
            );
            break;
          case 24:
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && flags2 & 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, flags2 = finishedWork.flags;
            switch (finishedWork.tag) {
              case 22:
                recursivelyTraverseAtomicPassiveEffects(
                  finishedRoot,
                  finishedWork
                );
                flags2 & 2048 && commitOffscreenPassiveMountEffects(
                  finishedWork.alternate,
                  finishedWork
                );
                break;
              case 24:
                recursivelyTraverseAtomicPassiveEffects(
                  finishedRoot,
                  finishedWork
                );
                flags2 & 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 i4 = 0; i4 < deletions.length; i4++) {
              var childToDelete = deletions[i4];
              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 i4 = 0; i4 < deletions.length; i4++) {
              var childToDelete = deletions[i4];
              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 instance2 = finishedWork.stateNode;
            instance2._visibility & 2 && (instance2._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 i4 = 0; i4 < tag2.length; i4++) {
              var check2 = tag2[i4], getSnapshot = check2.getSnapshot;
              check2 = check2.value;
              try {
                if (!objectIs(getSnapshot(), check2)) return false;
              } catch (error40) {
                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 (error40) {
          if (null !== returnFiber) throw workInProgress = returnFiber, error40;
          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 (err2) {
              hasLoggedError || (hasLoggedError = true, console.error(
                "React instrumentation encountered an error: %s",
                err2
              ));
            }
          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 (err2) {
              hasLoggedError || (hasLoggedError = true, console.error(
                "React instrumentation encountered an error: %s",
                err2
              ));
            }
          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, error40) {
        sourceFiber = createCapturedValueAtFiber(error40, 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, error40) {
        isRunningInsertionEffect = false;
        if (3 === sourceFiber.tag)
          captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error40);
        else {
          for (; null !== nearestMountedAncestor; ) {
            if (3 === nearestMountedAncestor.tag) {
              captureCommitPhaseErrorOnRoot(
                nearestMountedAncestor,
                sourceFiber,
                error40
              );
              return;
            }
            if (1 === nearestMountedAncestor.tag) {
              var instance2 = nearestMountedAncestor.stateNode;
              if ("function" === typeof nearestMountedAncestor.type.getDerivedStateFromError || "function" === typeof instance2.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(instance2))) {
                sourceFiber = createCapturedValueAtFiber(error40, sourceFiber);
                error40 = createClassErrorUpdate(2);
                instance2 = enqueueUpdate(nearestMountedAncestor, error40, 2);
                null !== instance2 && (initializeClassErrorUpdate(
                  error40,
                  instance2,
                  nearestMountedAncestor,
                  sourceFiber
                ), markRootUpdated$1(instance2, 2), ensureRootIsScheduled(instance2));
                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",
            error40
          );
        }
      }
      __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 === resolveFamily2) return type;
        var family = resolveFamily2(type);
        return void 0 === family ? type : family.current;
      }
      __name(resolveFunctionForHotReloading, "resolveFunctionForHotReloading");
      function resolveForwardRefForHotReloading(type) {
        if (null === resolveFamily2) return type;
        var family = resolveFamily2(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 === resolveFamily2) 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 = resolveFamily2(prevType), void 0 !== fiber && fiber === resolveFamily2(element)) ? true : false;
      }
      __name(isCompatibleFamilyForHotReloading, "isCompatibleFamilyForHotReloading");
      function markFailedErrorBoundaryForHotReloading(fiber) {
        null !== resolveFamily2 && "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 === resolveFamily2)
          throw Error("Expected resolveFamily to be set during hot reload.");
        var needsRender = false;
        type = false;
        null !== candidateType && (candidateType = resolveFamily2(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 (err2) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %s",
              err2
            ));
          }
        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 map3 = /* @__PURE__ */ new Map(), lane = 1, index = 0; 31 > index; index++) {
          var label = getLabelForLane(lane);
          map3.set(lane, label);
          lane *= 2;
        }
        return map3;
      }
      __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, createInstance3 = $$$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), hasOwnProperty3 = 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, instance2) {
        didWarnAboutUnsafeLifecycles.has(fiber.type) || ("function" === typeof instance2.componentWillMount && true !== instance2.componentWillMount.__suppressDeprecationWarning && pendingComponentWillMountWarnings.push(fiber), fiber.mode & 8 && "function" === typeof instance2.UNSAFE_componentWillMount && pendingUNSAFE_ComponentWillMountWarnings.push(fiber), "function" === typeof instance2.componentWillReceiveProps && true !== instance2.componentWillReceiveProps.__suppressDeprecationWarning && pendingComponentWillReceivePropsWarnings.push(fiber), fiber.mode & 8 && "function" === typeof instance2.UNSAFE_componentWillReceiveProps && pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber), "function" === typeof instance2.componentWillUpdate && true !== instance2.componentWillUpdate.__suppressDeprecationWarning && pendingComponentWillUpdateWarnings.push(fiber), fiber.mode & 8 && "function" === typeof instance2.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, instance2) {
        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 !== instance2 && "function" === typeof instance2.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(create4, createDeps) {
          currentHookNameInDev = "useEffect";
          mountHookTypesDev();
          checkDepsAreArrayDev(createDeps);
          return mountEffect(create4, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create4, deps) {
          currentHookNameInDev = "useImperativeHandle";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountImperativeHandle(ref, create4, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useInsertionEffect";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          mountEffectImpl(4, Insertion, create4, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useLayoutEffect";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountLayoutEffect(create4, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useMemo";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountMemo(create4, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountReducer(reducer, initialArg, init2);
          } 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(create4, createDeps) {
          currentHookNameInDev = "useEffect";
          updateHookTypesDev();
          return mountEffect(create4, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create4, deps) {
          currentHookNameInDev = "useImperativeHandle";
          updateHookTypesDev();
          return mountImperativeHandle(ref, create4, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useInsertionEffect";
          updateHookTypesDev();
          mountEffectImpl(4, Insertion, create4, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useLayoutEffect";
          updateHookTypesDev();
          return mountLayoutEffect(create4, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useMemo";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountMemo(create4, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountReducer(reducer, initialArg, init2);
          } 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(create4, createDeps) {
          currentHookNameInDev = "useEffect";
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create4, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create4, deps) {
          currentHookNameInDev = "useImperativeHandle";
          updateHookTypesDev();
          return updateImperativeHandle(ref, create4, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useInsertionEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create4, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useLayoutEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create4, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useMemo";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateMemo(create4, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateReducer(reducer, initialArg, init2);
          } 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(create4, createDeps) {
          currentHookNameInDev = "useEffect";
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create4, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create4, deps) {
          currentHookNameInDev = "useImperativeHandle";
          updateHookTypesDev();
          return updateImperativeHandle(ref, create4, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useInsertionEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create4, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useLayoutEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create4, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useMemo";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
          try {
            return updateMemo(create4, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
          try {
            return rerenderReducer(reducer, initialArg, init2);
          } 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(create4, createDeps) {
          currentHookNameInDev = "useEffect";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountEffect(create4, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create4, deps) {
          currentHookNameInDev = "useImperativeHandle";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountImperativeHandle(ref, create4, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useInsertionEffect";
          warnInvalidHookAccess();
          mountHookTypesDev();
          mountEffectImpl(4, Insertion, create4, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useLayoutEffect";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountLayoutEffect(create4, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useMemo";
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountMemo(create4, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountReducer(reducer, initialArg, init2);
          } 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(create4, createDeps) {
          currentHookNameInDev = "useEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create4, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create4, deps) {
          currentHookNameInDev = "useImperativeHandle";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateImperativeHandle(ref, create4, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useInsertionEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create4, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useLayoutEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create4, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useMemo";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateMemo(create4, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateReducer(reducer, initialArg, init2);
          } 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(create4, createDeps) {
          currentHookNameInDev = "useEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create4, createDeps);
        }, "useEffect"),
        useImperativeHandle: /* @__PURE__ */ __name(function(ref, create4, deps) {
          currentHookNameInDev = "useImperativeHandle";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateImperativeHandle(ref, create4, deps);
        }, "useImperativeHandle"),
        useInsertionEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useInsertionEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create4, deps);
        }, "useInsertionEffect"),
        useLayoutEffect: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useLayoutEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create4, deps);
        }, "useLayoutEffect"),
        useMemo: /* @__PURE__ */ __name(function(create4, deps) {
          currentHookNameInDev = "useMemo";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateMemo(create4, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }, "useMemo"),
        useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return rerenderReducer(reducer, initialArg, init2);
          } 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(instance2) {
          var wasRendering = isRendering;
          isRendering = true;
          try {
            return instance2.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, instance2) {
          try {
            instance2.componentDidMount();
          } catch (error40) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error40);
          }
        }, "react-stack-bottom-frame")
      }, callComponentDidMountInDEV = callComponentDidMount["react-stack-bottom-frame"].bind(callComponentDidMount), callComponentDidUpdate = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(finishedWork, instance2, prevProps, prevState, snapshot) {
          try {
            instance2.componentDidUpdate(prevProps, prevState, snapshot);
          } catch (error40) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error40);
          }
        }, "react-stack-bottom-frame")
      }, callComponentDidUpdateInDEV = callComponentDidUpdate["react-stack-bottom-frame"].bind(callComponentDidUpdate), callComponentDidCatch = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(instance2, errorInfo) {
          var stack = errorInfo.stack;
          instance2.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, instance2) {
          try {
            instance2.componentWillUnmount();
          } catch (error40) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error40);
          }
        }, "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 create4 = effect.create;
          effect = effect.inst;
          create4 = create4();
          return effect.destroy = create4;
        }, "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 (error40) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error40);
          }
        }, "react-stack-bottom-frame")
      }, callDestroyInDEV = callDestroy["react-stack-bottom-frame"].bind(callDestroy), callLazyInit = {
        "react-stack-bottom-frame": /* @__PURE__ */ __name(function(lazy2) {
          var init2 = lazy2._init;
          return init2(lazy2._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(error40) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error40 && null !== error40 && "string" === typeof error40.message ? String(error40.message) : String(error40),
            error: error40
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error40);
          return;
        }
        console.error(error40);
      }, 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 = {}, resolveFamily2 = 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, path150, value) {
        id = findHook(fiber, id);
        null !== id && (path150 = copyWithSetImpl(id.memoizedState, path150, 0, value), id.memoizedState = path150, id.baseState = path150, fiber.memoizedProps = assign({}, fiber.memoizedProps), path150 = enqueueConcurrentRenderForLane(fiber, 2), null !== path150 && scheduleUpdateOnFiber(path150, fiber, 2));
      }, "overrideHookState");
      overrideHookStateDeletePath = /* @__PURE__ */ __name(function(fiber, id, path150) {
        id = findHook(fiber, id);
        null !== id && (path150 = copyWithDeleteImpl(id.memoizedState, path150, 0), id.memoizedState = path150, id.baseState = path150, fiber.memoizedProps = assign({}, fiber.memoizedProps), path150 = enqueueConcurrentRenderForLane(fiber, 2), null !== path150 && scheduleUpdateOnFiber(path150, 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, path150, value) {
        fiber.pendingProps = copyWithSetImpl(fiber.memoizedProps, path150, 0, value);
        fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
        path150 = enqueueConcurrentRenderForLane(fiber, 2);
        null !== path150 && scheduleUpdateOnFiber(path150, fiber, 2);
      }, "overrideProps");
      overridePropsDeletePath = /* @__PURE__ */ __name(function(fiber, path150) {
        fiber.pendingProps = copyWithDeleteImpl(fiber.memoizedProps, path150, 0);
        fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
        path150 = enqueueConcurrentRenderForLane(fiber, 2);
        null !== path150 && scheduleUpdateOnFiber(path150, 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(error40) {
        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 error40 && null !== error40 && "string" === typeof error40.environmentName ? bindToConsole(
          "error",
          ["%o\n\n%s\n\n%s\n", error40, componentNameMessage, recreateMessage],
          error40.environmentName
        )() : console.error(
          "%o\n\n%s\n\n%s\n",
          error40,
          componentNameMessage,
          recreateMessage
        );
      };
      exports3.defaultOnRecoverableError = function(error40) {
        reportGlobalError(error40);
      };
      exports3.defaultOnUncaughtError = function(error40) {
        reportGlobalError(error40);
        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 i4 = 0; i4 < selectors.length; i4++)
          hostRoot.push(getBoundingRect(selectors[i4]));
        for (selectors = hostRoot.length - 1; 0 < selectors; selectors--) {
          i4 = hostRoot[selectors];
          for (var targetLeft = i4.x, targetRight = targetLeft + i4.width, targetTop = i4.y, targetBottom = targetTop + i4.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 || i4.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 || i4.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 ? noop11 : 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, factory2) {
      if (typeof exports2 === "object" && typeof module2 === "object")
        module2.exports = factory2();
      else if (typeof define === "function" && define.amd)
        define([], factory2);
      else if (typeof exports2 === "object")
        exports2["ReactDevToolsBackend"] = factory2();
      else
        root["ReactDevToolsBackend"] = factory2();
    }, "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 C3() {
                  var a2 = B2;
                  null !== a2 && (B2 = a2.next);
                  return a2;
                }
                __name(C3, "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 = C3();
                    x3.push({
                      primitive: "CacheRefresh",
                      stackError: Error(),
                      value: null !== a2 ? a2.memoizedState : function() {
                      }
                    });
                    return function() {
                    };
                  }, "useCacheRefresh"),
                  useCallback: /* @__PURE__ */ __name(function useCallback86(a2) {
                    var b2 = C3();
                    x3.push({
                      primitive: "Callback",
                      stackError: Error(),
                      value: null !== b2 ? b2.memoizedState[0] : a2
                    });
                    return a2;
                  }, "useCallback"),
                  useContext: /* @__PURE__ */ __name(function useContext27(a2) {
                    x3.push({
                      primitive: "Context",
                      stackError: Error(),
                      value: a2._currentValue
                    });
                    return a2._currentValue;
                  }, "useContext"),
                  useEffect: /* @__PURE__ */ __name(function useEffect84(a2) {
                    C3();
                    x3.push({
                      primitive: "Effect",
                      stackError: Error(),
                      value: a2
                    });
                  }, "useEffect"),
                  useImperativeHandle: /* @__PURE__ */ __name(function useImperativeHandle(a2) {
                    C3();
                    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 useLayoutEffect4(a2) {
                    C3();
                    x3.push({
                      primitive: "LayoutEffect",
                      stackError: Error(),
                      value: a2
                    });
                  }, "useLayoutEffect"),
                  useInsertionEffect: /* @__PURE__ */ __name(function useInsertionEffect(a2) {
                    C3();
                    x3.push({
                      primitive: "InsertionEffect",
                      stackError: Error(),
                      value: a2
                    });
                  }, "useInsertionEffect"),
                  useMemo: /* @__PURE__ */ __name(function useMemo56(a2) {
                    var b2 = C3();
                    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 = C3();
                    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 useRef36(a2) {
                    var b2 = C3();
                    a2 = null !== b2 ? b2.memoizedState : {
                      current: a2
                    };
                    x3.push({
                      primitive: "Ref",
                      stackError: Error(),
                      value: a2.current
                    });
                    return a2;
                  }, "useRef"),
                  useState: /* @__PURE__ */ __name(function useState108(a2) {
                    var b2 = C3();
                    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() {
                    C3();
                    C3();
                    x3.push({
                      primitive: "Transition",
                      stackError: Error(),
                      value: void 0
                    });
                    return [false, function() {
                    }];
                  }, "useTransition"),
                  useSyncExternalStore: /* @__PURE__ */ __name(function useSyncExternalStore3(a2, b2) {
                    C3();
                    C3();
                    a2 = b2();
                    x3.push({
                      primitive: "SyncExternalStore",
                      stackError: Error(),
                      value: a2
                    });
                    return a2;
                  }, "useSyncExternalStore"),
                  useDeferredValue: /* @__PURE__ */ __name(function useDeferredValue(a2) {
                    var b2 = C3();
                    x3.push({
                      primitive: "DeferredValue",
                      stackError: Error(),
                      value: null !== b2 ? b2.memoizedState : a2
                    });
                    return a2;
                  }, "useDeferredValue"),
                  useId: /* @__PURE__ */ __name(function useId2() {
                    var a2 = C3();
                    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 G3(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(G3, "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 = G3(m3, d2, F4);
                      if (-1 !== n3) d2 = n3;
                      else {
                        for (var f5 = 0; f5 < d2.length && 5 > f5; f5++) {
                          if (n3 = G3(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"), C3 = Symbol.iterator;
                function ea(a2) {
                  if (null === a2 || "object" !== _typeof2(a2)) return null;
                  a2 = C3 && a2[C3] || 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 G3(a2, b2, c4) {
                  this.props = a2;
                  this.context = b2;
                  this.refs = F4;
                  this.updater = c4 || D2;
                }
                __name(G3, "G");
                G3.prototype.isReactComponent = {};
                G3.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");
                };
                G3.prototype.forceUpdate = function(a2) {
                  this.updater.enqueueForceUpdate(this, a2, "forceUpdate");
                };
                function H2() {
                }
                __name(H2, "H");
                H2.prototype = G3.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, G3.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 forEach3(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 toArray2(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 = G3;
                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, factory2) {
                  "use strict";
                  if (true) {
                    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__2(430)], __WEBPACK_AMD_DEFINE_FACTORY__ = factory2, __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(error40) {
                      if (typeof error40.stacktrace !== "undefined" || typeof error40["opera#sourceloc"] !== "undefined") {
                        return this.parseOpera(error40);
                      } else if (error40.stack && error40.stack.match(CHROME_IE_STACK_REGEXP)) {
                        return this.parseV8OrIE(error40);
                      } else if (error40.stack) {
                        return this.parseFFOrSafari(error40);
                      } 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 parts2 = regExp.exec(urlLike.replace(/[()]/g, ""));
                      return [parts2[1], parts2[2] || void 0, parts2[3] || void 0];
                    }, "ErrorStackParser$$extractLocation"),
                    parseV8OrIE: /* @__PURE__ */ __name(function ErrorStackParser$$parseV8OrIE(error40) {
                      var filtered = error40.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(error40) {
                      var filtered = error40.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 matches2 = line.match(functionNameRegex);
                          var functionName = matches2 && matches2[1] ? matches2[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 i4 = 2, len = lines.length; i4 < len; i4 += 2) {
                        var match2 = lineRE.exec(lines[i4]);
                        if (match2) {
                          result.push(new StackFrame({
                            fileName: match2[2],
                            lineNumber: match2[1],
                            source: lines[i4]
                          }));
                        }
                      }
                      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 i4 = 0, len = lines.length; i4 < len; i4 += 2) {
                        var match2 = lineRE.exec(lines[i4]);
                        if (match2) {
                          result.push(new StackFrame({
                            functionName: match2[3] || void 0,
                            fileName: match2[2],
                            lineNumber: match2[1],
                            source: lines[i4]
                          }));
                        }
                      }
                      return result;
                    }, "ErrorStackParser$$parseOpera10"),
                    // Opera 10.65+ Error.stack very similar to FF/Safari
                    parseOpera11: /* @__PURE__ */ __name(function ErrorStackParser$$parseOpera11(error40) {
                      var filtered = error40.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 args2 = argsRaw === void 0 || argsRaw === "[arguments not available]" ? void 0 : argsRaw.split(",");
                        return new StackFrame({
                          functionName,
                          args: args2,
                          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(func2, wait, options2) {
                  var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
                  if (typeof func2 != "function") {
                    throw new TypeError(FUNC_ERROR_TEXT);
                  }
                  wait = toNumber2(wait) || 0;
                  if (isObject5(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 args2 = lastArgs, thisArg = lastThis;
                    lastArgs = lastThis = void 0;
                    lastInvokeTime = time3;
                    result = func2.apply(thisArg, args2);
                    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 throttle3(func2, wait, options2) {
                  var leading = true, trailing = true;
                  if (typeof func2 != "function") {
                    throw new TypeError(FUNC_ERROR_TEXT);
                  }
                  if (isObject5(options2)) {
                    leading = "leading" in options2 ? !!options2.leading : leading;
                    trailing = "trailing" in options2 ? !!options2.trailing : trailing;
                  }
                  return debounce3(func2, wait, {
                    "leading": leading,
                    "maxWait": wait,
                    "trailing": trailing
                  });
                }
                __name(throttle3, "throttle");
                function isObject5(value) {
                  var type = _typeof2(value);
                  return !!value && (type == "object" || type == "function");
                }
                __name(isObject5, "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 (isObject5(value)) {
                    var other2 = typeof value.valueOf == "function" ? value.valueOf() : value;
                    value = isObject5(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 = throttle3;
              }
            ),
            /***/
            730: (
              /***/
              (module3, __unused_webpack_exports, __webpack_require__2) => {
                "use strict";
                var process51 = __webpack_require__2(169);
                module3.exports = LRUCache2;
                var Map2 = __webpack_require__2(307);
                var util5 = __webpack_require__2(82);
                var Yallist2 = __webpack_require__2(695);
                var hasSymbol = typeof Symbol === "function" && process51.env._nodeLRUCacheForceNoSymbol !== "1";
                var makeSymbol;
                if (hasSymbol) {
                  makeSymbol = /* @__PURE__ */ __name(function makeSymbol2(key) {
                    return Symbol(key);
                  }, "makeSymbol");
                } else {
                  makeSymbol = /* @__PURE__ */ __name(function makeSymbol2(key) {
                    return "_" + key;
                  }, "makeSymbol");
                }
                var MAX2 = makeSymbol("max");
                var LENGTH = makeSymbol("length");
                var LENGTH_CALCULATOR = makeSymbol("lengthCalculator");
                var ALLOW_STALE = makeSymbol("allowStale");
                var MAX_AGE = makeSymbol("maxAge");
                var DISPOSE = makeSymbol("dispose");
                var NO_DISPOSE_ON_SET = makeSymbol("noDisposeOnSet");
                var LRU_LIST = makeSymbol("lruList");
                var CACHE = makeSymbol("cache");
                function naiveLength() {
                  return 1;
                }
                __name(naiveLength, "naiveLength");
                function LRUCache2(options2) {
                  if (!(this instanceof LRUCache2)) {
                    return new LRUCache2(options2);
                  }
                  if (typeof options2 === "number") {
                    options2 = {
                      max: options2
                    };
                  }
                  if (!options2) {
                    options2 = {};
                  }
                  var max = this[MAX2] = options2.max;
                  if (!max || !(typeof max === "number") || max <= 0) {
                    this[MAX2] = Infinity;
                  }
                  var lc = options2.length || naiveLength;
                  if (typeof lc !== "function") {
                    lc = naiveLength;
                  }
                  this[LENGTH_CALCULATOR] = lc;
                  this[ALLOW_STALE] = options2.stale || false;
                  this[MAX_AGE] = options2.maxAge || 0;
                  this[DISPOSE] = options2.dispose;
                  this[NO_DISPOSE_ON_SET] = options2.noDisposeOnSet || false;
                  this.reset();
                }
                __name(LRUCache2, "LRUCache");
                Object.defineProperty(LRUCache2.prototype, "max", {
                  set: /* @__PURE__ */ __name(function set2(mL) {
                    if (!mL || !(typeof mL === "number") || mL <= 0) {
                      mL = Infinity;
                    }
                    this[MAX2] = mL;
                    trim2(this);
                  }, "set"),
                  get: /* @__PURE__ */ __name(function get5() {
                    return this[MAX2];
                  }, "get"),
                  enumerable: true
                });
                Object.defineProperty(LRUCache2.prototype, "allowStale", {
                  set: /* @__PURE__ */ __name(function set2(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 set2(mA) {
                    if (!mA || !(typeof mA === "number") || mA < 0) {
                      mA = 0;
                    }
                    this[MAX_AGE] = mA;
                    trim2(this);
                  }, "set"),
                  get: /* @__PURE__ */ __name(function get5() {
                    return this[MAX_AGE];
                  }, "get"),
                  enumerable: true
                });
                Object.defineProperty(LRUCache2.prototype, "lengthCalculator", {
                  set: /* @__PURE__ */ __name(function set2(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);
                    }
                    trim2(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: " + util5.inspect(max, opts);
                    extras = true;
                  }
                  var maxAge = this[MAX_AGE];
                  if (maxAge) {
                    if (extras) {
                      str2 += ",";
                    }
                    str2 += "\n  maxAge: " + util5.inspect(maxAge, opts);
                    extras = true;
                  }
                  var lc = this[LENGTH_CALCULATOR];
                  if (lc && lc !== naiveLength) {
                    if (extras) {
                      str2 += ",";
                    }
                    str2 += "\n  length: " + util5.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 = util5.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 = util5.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);
                    trim2(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);
                  trim2(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 trim2(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(trim2, "trim");
                function del(self2, node) {
                  if (node) {
                    var hit = node.value;
                    if (self2[DISPOSE]) {
                      self2[DISPOSE](hit.key, hit.value);
                    }
                    self2[LENGTH] -= hit.length;
                    self2[CACHE].delete(hit.key);
                    self2[LRU_LIST].removeNode(node);
                  }
                }
                __name(del, "del");
                function Entry(key, value, length, now, maxAge) {
                  this.key = key;
                  this.value = value;
                  this.length = length;
                  this.now = now;
                  this.maxAge = maxAge || 0;
                }
                __name(Entry, "Entry");
              }
            ),
            /***/
            169: (
              /***/
              (module3) => {
                var process51 = module3.exports = {};
                var cachedSetTimeout;
                var cachedClearTimeout;
                function defaultSetTimout() {
                  throw new Error("setTimeout has not been defined");
                }
                __name(defaultSetTimout, "defaultSetTimout");
                function defaultClearTimeout() {
                  throw new Error("clearTimeout has not been defined");
                }
                __name(defaultClearTimeout, "defaultClearTimeout");
                (function() {
                  try {
                    if (typeof setTimeout === "function") {
                      cachedSetTimeout = setTimeout;
                    } else {
                      cachedSetTimeout = defaultSetTimout;
                    }
                  } catch (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");
                process51.nextTick = function(fun) {
                  var args2 = new Array(arguments.length - 1);
                  if (arguments.length > 1) {
                    for (var i4 = 1; i4 < arguments.length; i4++) {
                      args2[i4 - 1] = arguments[i4];
                    }
                  }
                  queue.push(new Item(fun, args2));
                  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);
                };
                process51.title = "browser";
                process51.browser = true;
                process51.env = {};
                process51.argv = [];
                process51.version = "";
                process51.versions = {};
                function noop11() {
                }
                __name(noop11, "noop");
                process51.on = noop11;
                process51.addListener = noop11;
                process51.once = noop11;
                process51.off = noop11;
                process51.removeListener = noop11;
                process51.removeAllListeners = noop11;
                process51.emit = noop11;
                process51.prependListener = noop11;
                process51.prependOnceListener = noop11;
                process51.listeners = function(name4) {
                  return [];
                };
                process51.binding = function(name4) {
                  throw new Error("process.binding is not supported");
                };
                process51.cwd = function() {
                  return "/";
                };
                process51.chdir = function(dir) {
                  throw new Error("process.chdir is not supported");
                };
                process51.umask = function() {
                  return 0;
                };
              }
            ),
            /***/
            307: (
              /***/
              (module3, __unused_webpack_exports, __webpack_require__2) => {
                var process51 = __webpack_require__2(169);
                if (process51.env.npm_package_name === "pseudomap" && process51.env.npm_lifecycle_script === "test") process51.env.TEST_PSEUDOMAP = "true";
                if (typeof Map === "function" && !process51.env.TEST_PSEUDOMAP) {
                  module3.exports = Map;
                } else {
                  module3.exports = __webpack_require__2(761);
                }
              }
            ),
            /***/
            761: (
              /***/
              (module3) => {
                var hasOwnProperty3 = Object.prototype.hasOwnProperty;
                module3.exports = PseudoMap;
                function PseudoMap(set3) {
                  if (!(this instanceof PseudoMap))
                    throw new TypeError("Constructor PseudoMap requires 'new'");
                  this.clear();
                  if (set3) {
                    if (set3 instanceof PseudoMap || typeof Map === "function" && set3 instanceof Map) set3.forEach(function(value, key) {
                      this.set(key, value);
                    }, this);
                    else if (Array.isArray(set3)) set3.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) {
                  set2(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 set3(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, i4) {
                  this.key = k2;
                  this.value = v2;
                  this._index = i4;
                }
                __name(Entry, "Entry");
                function find(data, k2) {
                  for (var i4 = 0, s5 = "_" + k2, key = s5; hasOwnProperty3.call(data, key); key = s5 + i4++) {
                    if (same(data[key].key, k2)) return data[key];
                  }
                }
                __name(find, "find");
                function set2(data, k2, v2) {
                  for (var i4 = 0, s5 = "_" + k2, key = s5; hasOwnProperty3.call(data, key); key = s5 + i4++) {
                    if (same(data[key].key, k2)) {
                      data[key].value = v2;
                      return;
                    }
                  }
                  data.size++;
                  data[key] = new Entry(k2, v2, key);
                }
                __name(set2, "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, factory2) {
                  "use strict";
                  if (true) {
                    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = factory2, __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 i5 = 0; i5 < props.length; i5++) {
                      if (obj[props[i5]] !== void 0) {
                        this["set" + _capitalize(props[i5])](obj[props[i5]]);
                      }
                    }
                  }
                  __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 toString3() {
                      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 args2 = str2.substring(argsStartIndex + 1, argsEndIndex).split(",");
                    var locationString = str2.substring(argsEndIndex + 1);
                    if (locationString.indexOf("@") === 0) {
                      var parts2 = /@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationString, "");
                      var fileName = parts2[1];
                      var lineNumber = parts2[2];
                      var columnNumber = parts2[3];
                    }
                    return new StackFrame({
                      functionName,
                      args: args2 || void 0,
                      fileName,
                      lineNumber: lineNumber || void 0,
                      columnNumber: columnNumber || void 0
                    });
                  }, "StackFrame$$fromString");
                  for (var i4 = 0; i4 < booleanProps.length; i4++) {
                    StackFrame.prototype["get" + _capitalize(booleanProps[i4])] = _getter(booleanProps[i4]);
                    StackFrame.prototype["set" + _capitalize(booleanProps[i4])] = /* @__PURE__ */ function(p2) {
                      return function(v2) {
                        this[p2] = Boolean(v2);
                      };
                    }(booleanProps[i4]);
                  }
                  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 inherits2(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 inherits2(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 isBuffer2(arg) {
                  return arg && _typeof2(arg) === "object" && typeof arg.copy === "function" && typeof arg.fill === "function" && typeof arg.readUInt8 === "function";
                }, "isBuffer");
              }
            ),
            /***/
            82: (
              /***/
              (__unused_webpack_module, exports3, __webpack_require__2) => {
                var process51 = __webpack_require__2(169);
                function _typeof2(obj) {
                  "@babel/helpers - typeof";
                  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return typeof obj2;
                    }, "_typeof");
                  } else {
                    _typeof2 = /* @__PURE__ */ __name(function _typeof3(obj2) {
                      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                    }, "_typeof");
                  }
                  return _typeof2(obj);
                }
                __name(_typeof2, "_typeof");
                var formatRegExp = /%[sdj%]/g;
                exports3.format = function(f5) {
                  if (!isString3(f5)) {
                    var objects = [];
                    for (var i4 = 0; i4 < arguments.length; i4++) {
                      objects.push(inspect3(arguments[i4]));
                    }
                    return objects.join(" ");
                  }
                  var i4 = 1;
                  var args2 = arguments;
                  var len = args2.length;
                  var str2 = String(f5).replace(formatRegExp, function(x4) {
                    if (x4 === "%%") return "%";
                    if (i4 >= len) return x4;
                    switch (x4) {
                      case "%s":
                        return String(args2[i4++]);
                      case "%d":
                        return Number(args2[i4++]);
                      case "%j":
                        try {
                          return JSON.stringify(args2[i4++]);
                        } catch (_2) {
                          return "[Circular]";
                        }
                      default:
                        return x4;
                    }
                  });
                  for (var x3 = args2[i4]; i4 < len; x3 = args2[++i4]) {
                    if (isNull(x3) || !isObject5(x3)) {
                      str2 += " " + x3;
                    } else {
                      str2 += " " + inspect3(x3);
                    }
                  }
                  return str2;
                };
                exports3.deprecate = function(fn, msg) {
                  if (isUndefined3(globalThis.process)) {
                    return function() {
                      return exports3.deprecate(fn, msg).apply(this, arguments);
                    };
                  }
                  if (process51.noDeprecation === true) {
                    return fn;
                  }
                  var warned2 = false;
                  function deprecated() {
                    if (!warned2) {
                      if (process51.throwDeprecation) {
                        throw new Error(msg);
                      } else if (process51.traceDeprecation) {
                        console.trace(msg);
                      } else {
                        console.error(msg);
                      }
                      warned2 = true;
                    }
                    return fn.apply(this, arguments);
                  }
                  __name(deprecated, "deprecated");
                  return deprecated;
                };
                var debugs = {};
                var debugEnviron;
                exports3.debuglog = function(set2) {
                  if (isUndefined3(debugEnviron)) debugEnviron = process51.env.NODE_DEBUG || "";
                  set2 = set2.toUpperCase();
                  if (!debugs[set2]) {
                    if (new RegExp("\\b" + set2 + "\\b", "i").test(debugEnviron)) {
                      var pid = process51.pid;
                      debugs[set2] = function() {
                        var msg = exports3.format.apply(exports3, arguments);
                        console.error("%s %d: %s", set2, pid, msg);
                      };
                    } else {
                      debugs[set2] = function() {
                      };
                    }
                  }
                  return debugs[set2];
                };
                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 (isBoolean3(opts)) {
                    ctx.showHidden = opts;
                  } else if (opts) {
                    exports3._extend(ctx, opts);
                  }
                  if (isUndefined3(ctx.showHidden)) ctx.showHidden = false;
                  if (isUndefined3(ctx.depth)) ctx.depth = 2;
                  if (isUndefined3(ctx.colors)) ctx.colors = false;
                  if (isUndefined3(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 && isFunction7(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 (!isString3(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 (isFunction7(value)) {
                      var name4 = value.name ? ": " + value.name : "";
                      return ctx.stylize("[Function" + name4 + "]", "special");
                    }
                    if (isRegExp2(value)) {
                      return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
                    }
                    if (isDate2(value)) {
                      return ctx.stylize(Date.prototype.toString.call(value), "date");
                    }
                    if (isError(value)) {
                      return formatError2(value);
                    }
                  }
                  var base = "", array2 = false, braces = ["{", "}"];
                  if (isArray3(value)) {
                    array2 = true;
                    braces = ["[", "]"];
                  }
                  if (isFunction7(value)) {
                    var n3 = value.name ? ": " + value.name : "";
                    base = " [Function" + n3 + "]";
                  }
                  if (isRegExp2(value)) {
                    base = " " + RegExp.prototype.toString.call(value);
                  }
                  if (isDate2(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 (isRegExp2(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 (isUndefined3(value)) return ctx.stylize("undefined", "undefined");
                  if (isString3(value)) {
                    var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'";
                    return ctx.stylize(simple, "string");
                  }
                  if (isNumber4(value)) return ctx.stylize("" + value, "number");
                  if (isBoolean3(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 i4 = 0, l3 = value.length; i4 < l3; ++i4) {
                    if (hasOwnProperty3(value, String(i4))) {
                      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i4), 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 name4, 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 (!hasOwnProperty3(visibleKeys, key)) {
                    name4 = "[" + 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 (isUndefined3(name4)) {
                    if (array2 && key.match(/^\d+$/)) {
                      return str2;
                    }
                    name4 = JSON.stringify("" + key);
                    if (name4.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
                      name4 = name4.substr(1, name4.length - 2);
                      name4 = ctx.stylize(name4, "name");
                    } else {
                      name4 = name4.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
                      name4 = ctx.stylize(name4, "string");
                    }
                  }
                  return name4 + ": " + 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 isArray3(ar2) {
                  return Array.isArray(ar2);
                }
                __name(isArray3, "isArray");
                exports3.isArray = isArray3;
                function isBoolean3(arg) {
                  return typeof arg === "boolean";
                }
                __name(isBoolean3, "isBoolean");
                exports3.isBoolean = isBoolean3;
                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 isNumber4(arg) {
                  return typeof arg === "number";
                }
                __name(isNumber4, "isNumber");
                exports3.isNumber = isNumber4;
                function isString3(arg) {
                  return typeof arg === "string";
                }
                __name(isString3, "isString");
                exports3.isString = isString3;
                function isSymbol(arg) {
                  return _typeof2(arg) === "symbol";
                }
                __name(isSymbol, "isSymbol");
                exports3.isSymbol = isSymbol;
                function isUndefined3(arg) {
                  return arg === void 0;
                }
                __name(isUndefined3, "isUndefined");
                exports3.isUndefined = isUndefined3;
                function isRegExp2(re3) {
                  return isObject5(re3) && objectToString2(re3) === "[object RegExp]";
                }
                __name(isRegExp2, "isRegExp");
                exports3.isRegExp = isRegExp2;
                function isObject5(arg) {
                  return _typeof2(arg) === "object" && arg !== null;
                }
                __name(isObject5, "isObject");
                exports3.isObject = isObject5;
                function isDate2(d2) {
                  return isObject5(d2) && objectToString2(d2) === "[object Date]";
                }
                __name(isDate2, "isDate");
                exports3.isDate = isDate2;
                function isError(e4) {
                  return isObject5(e4) && (objectToString2(e4) === "[object Error]" || e4 instanceof Error);
                }
                __name(isError, "isError");
                exports3.isError = isError;
                function isFunction7(arg) {
                  return typeof arg === "function";
                }
                __name(isFunction7, "isFunction");
                exports3.isFunction = isFunction7;
                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 pad2(n3) {
                  return n3 < 10 ? "0" + n3.toString(10) : n3.toString(10);
                }
                __name(pad2, "pad");
                var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
                function timestamp() {
                  var d2 = /* @__PURE__ */ new Date();
                  var time3 = [pad2(d2.getHours()), pad2(d2.getMinutes()), pad2(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(origin2, add) {
                  if (!add || !isObject5(add)) return origin2;
                  var keys = Object.keys(add);
                  var i4 = keys.length;
                  while (i4--) {
                    origin2[keys[i4]] = add[keys[i4]];
                  }
                  return origin2;
                };
                function hasOwnProperty3(obj, prop) {
                  return Object.prototype.hasOwnProperty.call(obj, prop);
                }
                __name(hasOwnProperty3, "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 i4 = 0, l3 = arguments.length; i4 < l3; i4++) {
                      self2.push(arguments[i4]);
                    }
                  }
                  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 i4 = 0, l3 = arguments.length; i4 < l3; i4++) {
                    push2(this, arguments[i4]);
                  }
                  return this.length;
                };
                Yallist2.prototype.unshift = function() {
                  for (var i4 = 0, l3 = arguments.length; i4 < l3; i4++) {
                    unshift2(this, arguments[i4]);
                  }
                  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, i4 = 0; walker !== null; i4++) {
                    fn.call(thisp, walker.value, i4, this);
                    walker = walker.next;
                  }
                };
                Yallist2.prototype.forEachReverse = function(fn, thisp) {
                  thisp = thisp || this;
                  for (var walker = this.tail, i4 = this.length - 1; walker !== null; i4--) {
                    fn.call(thisp, walker.value, i4, this);
                    walker = walker.prev;
                  }
                };
                Yallist2.prototype.get = function(n3) {
                  for (var i4 = 0, walker = this.head; walker !== null && i4 < n3; i4++) {
                    walker = walker.next;
                  }
                  if (i4 === n3 && walker !== null) {
                    return walker.value;
                  }
                };
                Yallist2.prototype.getReverse = function(n3) {
                  for (var i4 = 0, walker = this.tail; walker !== null && i4 < n3; i4++) {
                    walker = walker.prev;
                  }
                  if (i4 === 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 i4 = 0; walker !== null; i4++) {
                    acc = fn(acc, walker.value, i4);
                    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 i4 = this.length - 1; walker !== null; i4--) {
                    acc = fn(acc, walker.value, i4);
                    walker = walker.prev;
                  }
                  return acc;
                };
                Yallist2.prototype.toArray = function() {
                  var arr = new Array(this.length);
                  for (var i4 = 0, walker = this.head; walker !== null; i4++) {
                    arr[i4] = walker.value;
                    walker = walker.next;
                  }
                  return arr;
                };
                Yallist2.prototype.toArrayReverse = function() {
                  var arr = new Array(this.length);
                  for (var i4 = 0, walker = this.tail; walker !== null; i4++) {
                    arr[i4] = 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 i4 = 0, walker = this.head; walker !== null && i4 < from; i4++) {
                    walker = walker.next;
                  }
                  for (; walker !== null && i4 < to; i4++, 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 i4 = this.length, walker = this.tail; walker !== null && i4 > to; i4--) {
                    walker = walker.prev;
                  }
                  for (; walker !== null && i4 > from; i4--, 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(instance2, Constructor) {
              if (!(instance2 instanceof Constructor)) {
                throw new TypeError("Cannot call a class as a function");
              }
            }
            __name(_classCallCheck, "_classCallCheck");
            function _defineProperties(target, props) {
              for (var i4 = 0; i4 < props.length; i4++) {
                var descriptor2 = props[i4];
                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 EventEmitter16 = /* @__PURE__ */ function() {
              function EventEmitter17() {
                _classCallCheck(this, EventEmitter17);
                _defineProperty2(this, "listenersMap", /* @__PURE__ */ new Map());
              }
              __name(EventEmitter17, "EventEmitter");
              _createClass(EventEmitter17, [{
                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, args2 = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                      args2[_key - 1] = arguments[_key];
                    }
                    if (listeners.length === 1) {
                      var listener = listeners[0];
                      listener.apply(null, args2);
                    } else {
                      var didThrow = false;
                      var caughtError = null;
                      var clonedListeners = Array.from(listeners);
                      for (var i4 = 0; i4 < clonedListeners.length; i4++) {
                        var _listener = clonedListeners[i4];
                        try {
                          _listener.apply(null, args2);
                        } catch (error40) {
                          if (caughtError === null) {
                            didThrow = true;
                            caughtError = error40;
                          }
                        }
                      }
                      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 EventEmitter17;
            }();
            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 (error40) {
                return null;
              }
            }
            __name(storage_localStorageGetItem, "storage_localStorageGetItem");
            function localStorageRemoveItem(key) {
              try {
                localStorage.removeItem(key);
              } catch (error40) {
              }
            }
            __name(localStorageRemoveItem, "localStorageRemoveItem");
            function storage_localStorageSetItem(key, value) {
              try {
                return localStorage.setItem(key, value);
              } catch (error40) {
              }
            }
            __name(storage_localStorageSetItem, "storage_localStorageSetItem");
            function sessionStorageGetItem(key) {
              try {
                return sessionStorage.getItem(key);
              } catch (error40) {
                return null;
              }
            }
            __name(sessionStorageGetItem, "sessionStorageGetItem");
            function sessionStorageRemoveItem(key) {
              try {
                sessionStorage.removeItem(key);
              } catch (error40) {
              }
            }
            __name(sessionStorageRemoveItem, "sessionStorageRemoveItem");
            function sessionStorageSetItem(key, value) {
              try {
                return sessionStorage.setItem(key, value);
              } catch (error40) {
              }
            }
            __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(instance2, Constructor) {
              if (!(instance2 instanceof Constructor)) {
                throw new TypeError("Cannot call a class as a function");
              }
            }
            __name(Overlay_classCallCheck, "Overlay_classCallCheck");
            function Overlay_defineProperties(target, props) {
              for (var i4 = 0; i4 < props.length; i4++) {
                var descriptor2 = props[i4];
                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(name4, width, height) {
                  this.nameSpan.textContent = name4;
                  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, name4) {
                  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 (!name4) {
                    name4 = 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) {
                          name4 += " (in " + ownerName + ")";
                        }
                      }
                    }
                  }
                  this.tip.updateText(name4, 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 (error40) {
                  }
                });
                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 (error40) {
                  }
                }
                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, i4) {
              return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i4) || _unsupportedIterableToArray2(arr, i4) || _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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) {
                arr2[i4] = arr[i4];
              }
              return arr2;
            }
            __name(_arrayLikeToArray2, "_arrayLikeToArray");
            function _iterableToArrayLimit(arr, i4) {
              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 (i4 && _arr.length === i4) break;
                }
              } catch (err2) {
                _d = true;
                _e2 = err2;
              } 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 i4 = op === "~" ? 2 : nonZero > 1 ? nonZero : 1;
              if (compareSegments(v5.slice(0, i4), r5.slice(0, i4)) !== 0) return false;
              if (compareSegments(v5.slice(i4), r5.slice(i4)) === -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 i4 = 0; i4 < Math.max(a2.length, b2.length); i4++) {
                var r5 = compareStrings(a2[i4] || "0", b2[i4] || "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 isArray3 = Array.isArray;
            const src_isArray = isArray3;
            ;
            var process51 = __webpack_require__(169);
            function utils_typeof(obj) {
              "@babel/helpers - typeof";
              if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
                utils_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return typeof obj2;
                }, "_typeof");
              } else {
                utils_typeof = /* @__PURE__ */ __name(function _typeof3(obj2) {
                  return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
                }, "_typeof");
              }
              return utils_typeof(obj);
            }
            __name(utils_typeof, "utils_typeof");
            function _toConsumableArray2(arr) {
              return _arrayWithoutHoles2(arr) || _iterableToArray2(arr) || utils_unsupportedIterableToArray(arr) || _nonIterableSpread2();
            }
            __name(_toConsumableArray2, "_toConsumableArray");
            function _nonIterableSpread2() {
              throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
            }
            __name(_nonIterableSpread2, "_nonIterableSpread");
            function utils_unsupportedIterableToArray(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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) {
                arr2[i4] = arr[i4];
              }
              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 i4 = 0; i4 < array2.length; i4++) {
                var char = array2[i4];
                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 i4 = 0;
              var charCode;
              while (i4 < string4.length) {
                charCode = string4.charCodeAt(i4);
                if ((charCode & 63488) === 55296) {
                  encoded.push(surrogatePairToCodePoint(charCode, string4.charCodeAt(++i4)));
                } else {
                  encoded.push(charCode);
                }
                ++i4;
              }
              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 i4 = 2;
              var stringTable = [
                null
                // ID = 0 corresponds to the null string.
              ];
              var stringTableSize = operations[i4++];
              var stringTableEnd = i4 + stringTableSize;
              while (i4 < stringTableEnd) {
                var nextLength = operations[i4++];
                var nextString = utfDecodeString(operations.slice(i4, i4 + nextLength));
                stringTable.push(nextString);
                i4 += nextLength;
              }
              while (i4 < operations.length) {
                var operation = operations[i4];
                switch (operation) {
                  case TREE_OPERATION_ADD: {
                    var _id = operations[i4 + 1];
                    var type = operations[i4 + 2];
                    i4 += 3;
                    if (type === ElementTypeRoot) {
                      logs2.push("Add new root node ".concat(_id));
                      i4++;
                      i4++;
                      i4++;
                      i4++;
                    } else {
                      var parentID = operations[i4];
                      i4++;
                      i4++;
                      var displayNameStringID = operations[i4];
                      var displayName = stringTable[displayNameStringID];
                      i4++;
                      i4++;
                      logs2.push("Add node ".concat(_id, " (").concat(displayName || "null", ") as child of ").concat(parentID));
                    }
                    break;
                  }
                  case TREE_OPERATION_REMOVE: {
                    var removeLength = operations[i4 + 1];
                    i4 += 2;
                    for (var removeIndex = 0; removeIndex < removeLength; removeIndex++) {
                      var _id2 = operations[i4];
                      i4 += 1;
                      logs2.push("Remove node ".concat(_id2));
                    }
                    break;
                  }
                  case TREE_OPERATION_REMOVE_ROOT: {
                    i4 += 1;
                    logs2.push("Remove root ".concat(rootID));
                    break;
                  }
                  case TREE_OPERATION_SET_SUBTREE_MODE: {
                    var _id3 = operations[i4 + 1];
                    var mode = operations[i4 + 1];
                    i4 += 3;
                    logs2.push("Mode ".concat(mode, " set for subtree with root ").concat(_id3));
                    break;
                  }
                  case TREE_OPERATION_REORDER_CHILDREN: {
                    var _id4 = operations[i4 + 1];
                    var numChildren = operations[i4 + 2];
                    i4 += 3;
                    var children = operations.slice(i4, i4 + numChildren);
                    i4 += numChildren;
                    logs2.push("Re-order node ".concat(_id4, " children ").concat(children.join(",")));
                    break;
                  }
                  case TREE_OPERATION_UPDATE_TREE_BASE_DURATION:
                    i4 += 3;
                    break;
                  case TREE_OPERATION_UPDATE_ERRORS_OR_WARNINGS:
                    var id = operations[i4 + 1];
                    var numErrors = operations[i4 + 2];
                    var numWarnings = operations[i4 + 3];
                    i4 += 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 (error40) {
              }
              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 process51.env.EDITOR_URL === "string" ? process51.env.EDITOR_URL : "";
            }
            __name(getDefaultOpenInEditorURL, "getDefaultOpenInEditorURL");
            function getOpenInEditorURL() {
              try {
                var raw2 = localStorageGetItem(LOCAL_STORAGE_OPEN_IN_EDITOR_URL);
                if (raw2 != null) {
                  return JSON.parse(raw2);
                }
              } catch (error40) {
              }
              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 matches2 = displayName.match(/[^()]+/g);
                    if (matches2 != null) {
                      displayName = matches2.pop();
                      hocDisplayNames = matches2;
                    }
                  }
                  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, path150) {
              return path150.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, path150) {
              var length = path150.length;
              var last2 = path150[length - 1];
              if (object3 != null) {
                var parent = utils_getInObject(object3, path150.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, path150, value) {
              var length = path150.length;
              var last2 = path150[length - 1];
              if (object3 != null) {
                var parent = utils_getInObject(object3, path150.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 iterator2 = data[Symbol.iterator]();
                    if (!iterator2) {
                    } else {
                      return iterator2 === 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 (!isPlainObject9(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 i4 = 0; i4 < data.length; i4++) {
                      if (i4 > 0) {
                        formatted += ", ";
                      }
                      formatted += formatDataForPreview(data[i4], 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 name4 = 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(name4, "(").concat(data.size, ") {").concat(truncateForDisplay(_formatted2), "}");
                  } else {
                    return "".concat(name4, "(").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 (error40) {
                    return "unserializable";
                  }
              }
            }
            __name(formatDataForPreview, "formatDataForPreview");
            var isPlainObject9 = /* @__PURE__ */ __name(function isPlainObject10(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 i4 = 1; i4 < arguments.length; i4++) {
                var source2 = arguments[i4] != null ? arguments[i4] : {};
                if (i4 % 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, path150) {
              cleaned.push(path150);
              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, path150, 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(path150);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.tagName,
                    type
                  };
                case "function":
                  cleaned.push(path150);
                  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(path150);
                  if (isPathAllowedCheck) {
                    return data;
                  } else {
                    return data.length <= 500 ? data : data.slice(0, 500) + "...";
                  }
                case "bigint":
                  cleaned.push(path150);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.toString(),
                    type
                  };
                case "symbol":
                  cleaned.push(path150);
                  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(path150);
                  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(path150);
                  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(path150);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path150);
                  }
                  return data.map(function(item, i4) {
                    return dehydrate(item, cleaned, unserializable, path150.concat([i4]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                  });
                case "html_all_collection":
                case "typed_array":
                case "iterator":
                  isPathAllowedCheck = isPathAllowed(path150);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path150);
                  } 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, i4) {
                      return unserializableValue[i4] = dehydrate(item, cleaned, unserializable, path150.concat([i4]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                    });
                    unserializable.push(path150);
                    return unserializableValue;
                  }
                case "opaque_iterator":
                  cleaned.push(path150);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data[Symbol.toStringTag],
                    type
                  };
                case "date":
                  cleaned.push(path150);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.toString(),
                    type
                  };
                case "regexp":
                  cleaned.push(path150);
                  return {
                    inspectable: false,
                    preview_short: formatDataForPreview(data, false),
                    preview_long: formatDataForPreview(data, true),
                    name: data.toString(),
                    type
                  };
                case "object":
                  isPathAllowedCheck = isPathAllowed(path150);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path150);
                  } else {
                    var object3 = {};
                    getAllEnumerableKeys(data).forEach(function(key) {
                      var name4 = key.toString();
                      object3[name4] = dehydrate(data[key], cleaned, unserializable, path150.concat([name4]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                    });
                    return object3;
                  }
                case "class_instance":
                  isPathAllowedCheck = isPathAllowed(path150);
                  if (level >= LEVEL_THRESHOLD && !isPathAllowedCheck) {
                    return createDehydrated(type, true, data, cleaned, path150);
                  }
                  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, path150.concat([keyAsString]), isPathAllowed, isPathAllowedCheck ? 1 : level + 1);
                  });
                  unserializable.push(path150);
                  return value;
                case "infinity":
                case "nan":
                case "undefined":
                  cleaned.push(path150);
                  return {
                    type
                  };
                default:
                  return data;
              }
            }
            __name(dehydrate, "dehydrate");
            function fillInPath(object3, data, path150, value) {
              var target = getInObject(object3, path150);
              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 === path150.length;
                for (var i4 = 0; i4 < path150.length; i4++) {
                  if (path150[i4] !== unserializablePath[i4]) {
                    isMatch = false;
                    break;
                  }
                }
                if (isMatch) {
                  upgradeUnserializable(value, value);
                }
              }
              setInObject(object3, path150, value);
            }
            __name(fillInPath, "fillInPath");
            function hydrate(object3, cleaned, unserializable) {
              cleaned.forEach(function(path150) {
                var length = path150.length;
                var last2 = path150[length - 1];
                var parent = getInObject(object3, path150.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(path150) {
                var length = path150.length;
                var last2 = path150[length - 1];
                var parent = getInObject(object3, path150.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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) {
                arr2[i4] = arr[i4];
              }
              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 i4 = 1; i4 < arguments.length; i4++) {
                var source2 = arguments[i4] != null ? arguments[i4] : {};
                if (i4 % 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 path150 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
              if (data !== null) {
                var cleanedPaths = [];
                var unserializablePaths = [];
                var cleanedData = dehydrate(data, cleanedPaths, unserializablePaths, path150, isPathAllowed);
                return {
                  data: cleanedData,
                  cleaned: cleanedPaths,
                  unserializable: unserializablePaths
                };
              } else {
                return null;
              }
            }
            __name(cleanForBridge, "cleanForBridge");
            function copyWithDelete(obj, path150) {
              var index = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0;
              var key = path150[index];
              var updated = shared_isArray(obj) ? obj.slice() : utils_objectSpread({}, obj);
              if (index + 1 === path150.length) {
                if (shared_isArray(updated)) {
                  updated.splice(key, 1);
                } else {
                  delete updated[key];
                }
              } else {
                updated[key] = copyWithDelete(obj[key], path150, 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, path150, value) {
              var index = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0;
              if (index >= path150.length) {
                return value;
              }
              var key = path150[index];
              var updated = shared_isArray(obj) ? obj.slice() : utils_objectSpread({}, obj);
              updated[key] = copyWithSet(obj[key], path150, 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, i4) {
                  if (i4 > 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 args2 = inputArgs.slice();
              var formatted = String(maybeMessage);
              if (typeof maybeMessage === "string") {
                if (args2.length) {
                  var REGEXP = /(%?)(%([jds]))/g;
                  formatted = formatted.replace(REGEXP, function(match2, escaped, ptn, flag) {
                    var arg = args2.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;
                    }
                    args2.unshift(arg);
                    return match2;
                  });
                }
              }
              if (args2.length) {
                for (var i4 = 0; i4 < args2.length; i4++) {
                  formatted += " " + String(args2[i4]);
                }
              }
              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 i4 = 1; i4 < arguments.length; i4++) {
                var source2 = arguments[i4] != null ? arguments[i4] : {};
                if (i4 % 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(name4, 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 + name4;
            }
            __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 set2() {
                      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 name4 = fn ? fn.displayName || fn.name : "";
              var syntheticFrame = name4 ? describeBuiltInComponentFrame(name4) : "";
              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 prototype2 = Component.prototype;
              return !!(prototype2 && prototype2.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 init2 = lazyComponent._init;
                    try {
                      return describeUnknownElementTypeFrameInDEV(init2(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 info2 = "";
                var node = workInProgress;
                do {
                  info2 += describeFiber(workTagMap, node, currentDispatcherRef);
                  node = node.return;
                } while (node);
                return info2;
              } catch (x3) {
                return "\nError generating stack: " + x3.message + "\n" + x3.stack;
              }
            }
            __name(getStackByFiberInDevAndProd, "getStackByFiberInDevAndProd");
            ;
            function profilingHooks_slicedToArray(arr, i4) {
              return profilingHooks_arrayWithHoles(arr) || profilingHooks_iterableToArrayLimit(arr, i4) || profilingHooks_unsupportedIterableToArray(arr, i4) || 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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) {
                arr2[i4] = arr[i4];
              }
              return arr2;
            }
            __name(profilingHooks_arrayLikeToArray, "profilingHooks_arrayLikeToArray");
            function profilingHooks_iterableToArrayLimit(arr, i4) {
              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 (i4 && _arr.length === i4) break;
                }
              } catch (err2) {
                _d = true;
                _e2 = err2;
              } 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 set2() {
                }, "set")
              });
              try {
                performance.mark(CHECK_V3_MARK, markOptions);
              } catch (error40) {
              } 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 i4 = 0; i4 < ranges2.length; i4++) {
                    var range = ranges2[i4];
                    if (shared_isArray(range) && range.length === 2) {
                      var _ranges$i = profilingHooks_slicedToArray(ranges2[i4], 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 i4 = 0; i4 < ranges2.length; i4++) {
                          var range = ranges2[i4];
                          if (shared_isArray(range) && range.length === 2) {
                            var _ranges$i2 = profilingHooks_slicedToArray(ranges2[i4], 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, i4;
              if (Object.getOwnPropertySymbols) {
                var sourceSymbolKeys = Object.getOwnPropertySymbols(source2);
                for (i4 = 0; i4 < sourceSymbolKeys.length; i4++) {
                  key = sourceSymbolKeys[i4];
                  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, i4;
              for (i4 = 0; i4 < sourceKeys.length; i4++) {
                key = sourceKeys[i4];
                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 i4 = 1; i4 < arguments.length; i4++) {
                var source2 = arguments[i4] != null ? arguments[i4] : {};
                if (i4 % 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, i4) {
              return renderer_arrayWithHoles(arr) || renderer_iterableToArrayLimit(arr, i4) || renderer_unsupportedIterableToArray(arr, i4) || 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, i4) {
              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 (i4 && _arr.length === i4) break;
                }
              } catch (err2) {
                _d = true;
                _e2 = err2;
              } 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 it3;
              if (typeof Symbol === "undefined" || o3[Symbol.iterator] == null) {
                if (Array.isArray(o3) || (it3 = renderer_unsupportedIterableToArray(o3)) || allowArrayLike && o3 && typeof o3.length === "number") {
                  if (it3) o3 = it3;
                  var i4 = 0;
                  var F4 = /* @__PURE__ */ __name(function F5() {
                  }, "F");
                  return { s: F4, n: /* @__PURE__ */ __name(function n3() {
                    if (i4 >= o3.length) return { done: true };
                    return { done: false, value: o3[i4++] };
                  }, "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, err2;
              return { s: /* @__PURE__ */ __name(function s5() {
                it3 = o3[Symbol.iterator]();
              }, "s"), n: /* @__PURE__ */ __name(function n3() {
                var step = it3.next();
                normalCompletion = step.done;
                return step;
              }, "n"), e: /* @__PURE__ */ __name(function e4(_e3) {
                didErr = true;
                err2 = _e3;
              }, "e"), f: /* @__PURE__ */ __name(function f5() {
                try {
                  if (!normalCompletion && it3.return != null) it3.return();
                } finally {
                  if (didErr) throw err2;
                }
              }, "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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) {
                arr2[i4] = arr[i4];
              }
              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, Fragment29 = _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 Fragment29:
                    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, Fragment29 = 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 (err2) {
                  _iterator.e(err2);
                } 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 (err2) {
                  _iterator2.e(err2);
                } 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, args2) {
                if (type === "error") {
                  var maybeID = getFiberIDUnsafe(fiber);
                  if (maybeID != null && forceErrorForFiberIDs.get(maybeID) === true) {
                    return;
                  }
                }
                var message = format4.apply(void 0, renderer_toConsumableArray(args2));
                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(name4, 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(name4, " %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 Fragment29:
                    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 (err2) {
                      _iterator3.e(err2);
                    } 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 (err2) {
                    _iterator4.e(err2);
                  } 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 Fragment29:
                    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 instance2 = fiber.stateNode;
                    if (instance2 != null) {
                      if (instance2.constructor && instance2.constructor.contextType != null) {
                        modernContext = instance2.context;
                      } else {
                        legacyContext = instance2.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 (err2) {
                  _iterator5.e(err2);
                } 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 i4 = 0;
                operations[i4++] = rendererID;
                operations[i4++] = currentRootID;
                operations[i4++] = pendingStringTableLength;
                pendingStringTable.forEach(function(entry, stringKey) {
                  var encodedString = entry.encodedString;
                  var length = encodedString.length;
                  operations[i4++] = length;
                  for (var j3 = 0; j3 < length; j3++) {
                    operations[i4 + j3] = encodedString[j3];
                  }
                  i4 += length;
                });
                if (numUnmountIDs > 0) {
                  operations[i4++] = TREE_OPERATION_REMOVE;
                  operations[i4++] = numUnmountIDs;
                  for (var j2 = pendingRealUnmountedIDs.length - 1; j2 >= 0; j2--) {
                    operations[i4++] = pendingRealUnmountedIDs[j2];
                  }
                  for (var _j = 0; _j < pendingSimulatedUnmountedIDs.length; _j++) {
                    operations[i4 + _j] = pendingSimulatedUnmountedIDs[_j];
                  }
                  i4 += pendingSimulatedUnmountedIDs.length;
                  if (pendingUnmountedRootID !== null) {
                    operations[i4] = pendingUnmountedRootID;
                    i4++;
                  }
                }
                for (var _j2 = 0; _j2 < pendingOperations.length; _j2++) {
                  operations[i4 + _j2] = pendingOperations[_j2];
                }
                i4 += 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 metadata2 = currentCommitProfilingMetadata;
                      metadata2.durations.push(id, actualDuration, selfDuration);
                      metadata2.maxActualDuration = Math.max(metadata2.maxActualDuration, actualDuration);
                      if (recordChangeDescriptions) {
                        var changeDescription = getChangeDescription(alternate, fiber);
                        if (changeDescription !== null) {
                          if (metadata2.changeDescriptions !== null) {
                            metadata2.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 i4 = 0; i4 < nextChildren.length; i4++) {
                  pushOperation(nextChildren[i4]);
                }
              }
              __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 (err2) {
                  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, path150) {
                if (isMostRecentlyInspectedElement(id)) {
                  window.$attribute = utils_getInObject(mostRecentlyInspectedElement, path150);
                }
              }
              __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 instance2 = null;
                var style = null;
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber !== null) {
                  instance2 = fiber.stateNode;
                  if (fiber.memoizedProps !== null) {
                    style = fiber.memoizedProps.style;
                  }
                }
                return {
                  instance: instance2,
                  style
                };
              }
              __name(getInstanceAndStyle, "getInstanceAndStyle");
              function isErrorBoundary(fiber) {
                var tag2 = fiber.tag, type = fiber.type;
                switch (tag2) {
                  case ClassComponent:
                  case IncompleteClassComponent:
                    var instance2 = fiber.stateNode;
                    return typeof type.getDerivedStateFromError === "function" || instance2 !== null && typeof instance2.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 (error40) {
                    }
                  }
                  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 (error40) {
                      }
                    }
                  }
                }
                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(path150) {
                var current = currentlyInspectedPaths;
                path150.forEach(function(key) {
                  if (!current[key]) {
                    current[key] = {};
                  }
                  current = current[key];
                });
              }
              __name(mergeInspectedPaths, "mergeInspectedPaths");
              function createIsPathAllowed(key, secondaryCategory) {
                return /* @__PURE__ */ __name(function isPathAllowed(path150) {
                  switch (secondaryCategory) {
                    case "hooks":
                      if (path150.length === 1) {
                        return true;
                      }
                      if (path150[path150.length - 2] === "hookSource" && path150[path150.length - 1] === "fileName") {
                        return true;
                      }
                      if (path150[path150.length - 1] === "subHooks" || path150[path150.length - 2] === "subHooks") {
                        return true;
                      }
                      break;
                    default:
                      break;
                  }
                  var current = key === null ? currentlyInspectedPaths : currentlyInspectedPaths[key];
                  if (!current) {
                    return false;
                  }
                  for (var i4 = 0; i4 < path150.length; i4++) {
                    current = current[path150[i4]];
                    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, path150, count) {
                if (isMostRecentlyInspectedElement(id)) {
                  var value = utils_getInObject(mostRecentlyInspectedElement, path150);
                  var key = "$reactTemp".concat(count);
                  window[key] = value;
                  console.log(key);
                  console.log(value);
                }
              }
              __name(storeAsGlobal, "storeAsGlobal");
              function getSerializedElementValueByPath(id, path150) {
                if (isMostRecentlyInspectedElement(id)) {
                  var valueToCopy = utils_getInObject(mostRecentlyInspectedElement, path150);
                  return serializeToString(valueToCopy);
                }
              }
              __name(getSerializedElementValueByPath, "getSerializedElementValueByPath");
              function inspectElement(requestID, id, path150, forceFullData) {
                if (path150 !== null) {
                  mergeInspectedPaths(path150);
                }
                if (isMostRecentlyInspectedElement(id) && !forceFullData) {
                  if (!hasElementUpdatedSinceLastInspected) {
                    if (path150 !== null) {
                      var secondaryCategory = null;
                      if (path150[0] === "hooks") {
                        secondaryCategory = "hooks";
                      }
                      return {
                        id,
                        responseID: requestID,
                        type: "hydrated-path",
                        path: path150,
                        value: cleanForBridge(utils_getInObject(mostRecentlyInspectedElement, path150), createIsPathAllowed(null, secondaryCategory), path150)
                      };
                    } else {
                      return {
                        id,
                        responseID: requestID,
                        type: "no-change"
                      };
                    }
                  }
                } else {
                  currentlyInspectedPaths = {};
                }
                hasElementUpdatedSinceLastInspected = false;
                try {
                  mostRecentlyInspectedElement = inspectElementRaw(id);
                } catch (error40) {
                  if (error40.name === "ReactDebugToolsRenderError") {
                    var message = "Error rendering inspected element.";
                    var stack;
                    console.error(message + "\n\n", error40);
                    if (error40.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", error40.cause);
                      if (error40.cause instanceof Error) {
                        message = error40.cause.message || message;
                        stack = error40.cause.stack;
                      }
                    }
                    return {
                      type: "error",
                      errorType: "user",
                      id,
                      responseID: requestID,
                      message,
                      stack
                    };
                  }
                  if (error40.name === "ReactDebugToolsUnsupportedHookError") {
                    return {
                      type: "error",
                      errorType: "unknown-hook",
                      id,
                      responseID: requestID,
                      message: "Unsupported hook in the react-debug-tools package: " + error40.message
                    };
                  }
                  console.error("Error inspecting element.\n\n", error40);
                  return {
                    type: "error",
                    errorType: "uncaught",
                    id,
                    responseID: requestID,
                    message: error40.message,
                    stack: error40.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, path150) {
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber !== null) {
                  var instance2 = fiber.stateNode;
                  switch (type) {
                    case "context":
                      path150 = path150.slice(1);
                      switch (fiber.tag) {
                        case ClassComponent:
                          if (path150.length === 0) {
                          } else {
                            deletePathInObject(instance2.context, path150);
                          }
                          instance2.forceUpdate();
                          break;
                        case FunctionComponent:
                          break;
                      }
                      break;
                    case "hooks":
                      if (typeof overrideHookStateDeletePath === "function") {
                        overrideHookStateDeletePath(fiber, hookID, path150);
                      }
                      break;
                    case "props":
                      if (instance2 === null) {
                        if (typeof overridePropsDeletePath === "function") {
                          overridePropsDeletePath(fiber, path150);
                        }
                      } else {
                        fiber.pendingProps = copyWithDelete(instance2.props, path150);
                        instance2.forceUpdate();
                      }
                      break;
                    case "state":
                      deletePathInObject(instance2.state, path150);
                      instance2.forceUpdate();
                      break;
                  }
                }
              }
              __name(deletePath, "deletePath");
              function renamePath(type, id, hookID, oldPath, newPath) {
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber !== null) {
                  var instance2 = 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(instance2.context, oldPath, newPath);
                          }
                          instance2.forceUpdate();
                          break;
                        case FunctionComponent:
                          break;
                      }
                      break;
                    case "hooks":
                      if (typeof overrideHookStateRenamePath === "function") {
                        overrideHookStateRenamePath(fiber, hookID, oldPath, newPath);
                      }
                      break;
                    case "props":
                      if (instance2 === null) {
                        if (typeof overridePropsRenamePath === "function") {
                          overridePropsRenamePath(fiber, oldPath, newPath);
                        }
                      } else {
                        fiber.pendingProps = copyWithRename(instance2.props, oldPath, newPath);
                        instance2.forceUpdate();
                      }
                      break;
                    case "state":
                      renamePathInObject(instance2.state, oldPath, newPath);
                      instance2.forceUpdate();
                      break;
                  }
                }
              }
              __name(renamePath, "renamePath");
              function overrideValueAtPath(type, id, hookID, path150, value) {
                var fiber = findCurrentFiberUsingSlowPathById(id);
                if (fiber !== null) {
                  var instance2 = fiber.stateNode;
                  switch (type) {
                    case "context":
                      path150 = path150.slice(1);
                      switch (fiber.tag) {
                        case ClassComponent:
                          if (path150.length === 0) {
                            instance2.context = value;
                          } else {
                            utils_setInObject(instance2.context, path150, value);
                          }
                          instance2.forceUpdate();
                          break;
                        case FunctionComponent:
                          break;
                      }
                      break;
                    case "hooks":
                      if (typeof overrideHookState === "function") {
                        overrideHookState(fiber, hookID, path150, value);
                      }
                      break;
                    case "props":
                      switch (fiber.tag) {
                        case ClassComponent:
                          fiber.pendingProps = copyWithSet(instance2.props, path150, value);
                          instance2.forceUpdate();
                          break;
                        default:
                          if (typeof overrideProps === "function") {
                            overrideProps(fiber, path150, value);
                          }
                          break;
                      }
                      break;
                    case "state":
                      switch (fiber.tag) {
                        case ClassComponent:
                          utils_setInObject(instance2.state, path150, value);
                          instance2.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 i4 = 0; i4 < durations.length; i4 += 3) {
                      var fiberID = durations[i4];
                      fiberActualDurations.push([fiberID, durations[i4 + 1]]);
                      fiberSelfDurations.push([fiberID, durations[i4 + 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(path150) {
                if (path150 === null) {
                  trackedPathMatchFiber = null;
                  trackedPathMatchDepth = -1;
                  mightBeOnTrackedPath = false;
                }
                trackedPath = path150;
              }
              __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 name4 = getDisplayNameForRoot(fiber);
                var counter = rootDisplayNameCounter.get(name4) || 0;
                rootDisplayNameCounter.set(name4, counter + 1);
                var pseudoKey = "".concat(name4, ":").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 name4 = pseudoKey.slice(0, pseudoKey.lastIndexOf(":"));
                var counter = rootDisplayNameCounter.get(name4);
                if (counter === void 0) {
                  throw new Error("Expected counter to be known.");
                }
                if (counter > 1) {
                  rootDisplayNameCounter.set(name4, counter - 1);
                } else {
                  rootDisplayNameCounter.delete(name4);
                }
                rootPseudoKeys.delete(id);
              }
              __name(removeRootPseudoKey, "removeRootPseudoKey");
              function getDisplayNameForRoot(fiber) {
                var preferredDisplayName = null;
                var fallbackDisplayName = null;
                var child = fiber.child;
                for (var i4 = 0; i4 < 3; i4++) {
                  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 it3;
              if (typeof Symbol === "undefined" || o3[Symbol.iterator] == null) {
                if (Array.isArray(o3) || (it3 = console_unsupportedIterableToArray(o3)) || allowArrayLike && o3 && typeof o3.length === "number") {
                  if (it3) o3 = it3;
                  var i4 = 0;
                  var F4 = /* @__PURE__ */ __name(function F5() {
                  }, "F");
                  return { s: F4, n: /* @__PURE__ */ __name(function n3() {
                    if (i4 >= o3.length) return { done: true };
                    return { done: false, value: o3[i4++] };
                  }, "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, err2;
              return { s: /* @__PURE__ */ __name(function s5() {
                it3 = o3[Symbol.iterator]();
              }, "s"), n: /* @__PURE__ */ __name(function n3() {
                var step = it3.next();
                normalCompletion = step.done;
                return step;
              }, "n"), e: /* @__PURE__ */ __name(function e4(_e2) {
                didErr = true;
                err2 = _e2;
              }, "e"), f: /* @__PURE__ */ __name(function f5() {
                try {
                  if (!normalCompletion && it3.return != null) it3.return();
                } finally {
                  if (didErr) throw err2;
                }
              }, "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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) {
                arr2[i4] = arr[i4];
              }
              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(args2, method2) {
              return args2.length >= 2 && STYLE_DIRECTIVE_REGEX.test(args2[0]) && args2[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 (error40) {
            }
            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 (error40) {
                    }
                  }
                }, "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, args2 = new Array(_len), _key = 0; _key < _len; _key++) {
                        args2[_key] = arguments[_key];
                      }
                      if (method2 !== "log") {
                        if (consoleSettingsRef.appendComponentStack) {
                          var lastArg = args2.length > 0 ? args2[args2.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)
                                    args2.slice()
                                  );
                                }
                              }
                              if (shouldAppendWarningStack) {
                                var componentStack = getStackByFiberInDevAndProd(workTagMap, current, currentDispatcherRef);
                                if (componentStack !== "") {
                                  if (isStrictModeOverride(args2, method2)) {
                                    args2[0] = "".concat(args2[0], " %s");
                                    args2.push(componentStack);
                                  } else {
                                    args2.push(componentStack);
                                  }
                                }
                              }
                            } catch (error40) {
                              setTimeout(function() {
                                throw error40;
                              }, 0);
                            } finally {
                              break;
                            }
                          }
                        }
                      } catch (err2) {
                        _iterator.e(err2);
                      } finally {
                        _iterator.f();
                      }
                      if (consoleSettingsRef.breakOnConsoleErrors) {
                        debugger;
                      }
                      originalMethod.apply(void 0, args2);
                    }, "overrideMethod");
                    overrideMethod.__REACT_DEVTOOLS_ORIGINAL_METHOD__ = originalMethod;
                    originalMethod.__REACT_DEVTOOLS_OVERRIDE_METHOD__ = overrideMethod;
                    targetConsole[method2] = overrideMethod;
                  } catch (error40) {
                  }
                });
              } 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 (error40) {
                    }
                  }
                }, "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, args2 = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                          args2[_key2] = arguments[_key2];
                        }
                        if (isNode3) {
                          originalMethod(DIMMED_NODE_CONSOLE_COLOR, format4.apply(void 0, args2));
                        } else {
                          var color = getConsoleColor(method2);
                          if (color) {
                            originalMethod.apply(void 0, console_toConsumableArray(formatWithStyles(args2, "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 (error40) {
                  }
                });
              }
            }
            __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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) {
                arr2[i4] = arr[i4];
              }
              return arr2;
            }
            __name(bridge_arrayLikeToArray, "bridge_arrayLikeToArray");
            function bridge_classCallCheck(instance2, Constructor) {
              if (!(instance2 instanceof Constructor)) {
                throw new TypeError("Cannot call a class as a function");
              }
            }
            __name(bridge_classCallCheck, "bridge_classCallCheck");
            function bridge_defineProperties(target, props) {
              for (var i4 = 0; i4 < props.length; i4++) {
                var descriptor2 = props[i4];
                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 i4 = 0; i4 < _this._messageQueue.length; i4 += 2) {
                      var _this$_wall;
                      (_this$_wall = _this._wall).send.apply(_this$_wall, [_this._messageQueue[i4]].concat(bridge_toConsumableArray(_this._messageQueue[i4 + 1])));
                    }
                    _this._messageQueue.length = 0;
                    _this._timeoutID = setTimeout(_this._flush, BATCH_DURATION);
                  }
                });
                bridge_defineProperty(_assertThisInitialized(_this), "overrideValueAtPath", function(_ref) {
                  var id = _ref.id, path150 = _ref.path, rendererID = _ref.rendererID, type = _ref.type, value = _ref.value;
                  switch (type) {
                    case "context":
                      _this.send("overrideContext", {
                        id,
                        path: path150,
                        rendererID,
                        wasForwarded: true,
                        value
                      });
                      break;
                    case "hooks":
                      _this.send("overrideHookState", {
                        id,
                        path: path150,
                        rendererID,
                        wasForwarded: true,
                        value
                      });
                      break;
                    case "props":
                      _this.send("overrideProps", {
                        id,
                        path: path150,
                        rendererID,
                        wasForwarded: true,
                        value
                      });
                      break;
                    case "state":
                      _this.send("overrideState", {
                        id,
                        path: path150,
                        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;
            }(EventEmitter16);
            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(instance2, Constructor) {
              if (!(instance2 instanceof Constructor)) {
                throw new TypeError("Cannot call a class as a function");
              }
            }
            __name(agent_classCallCheck, "agent_classCallCheck");
            function agent_defineProperties(target, props) {
              for (var i4 = 0; i4 < props.length; i4++) {
                var descriptor2 = props[i4];
                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, args2 = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                  args2[_key - 1] = arguments[_key];
                }
                (_console = console).log.apply(_console, ["%cAgent %c".concat(methodName), "color: purple; font-weight: bold;", "font-weight: bold;"].concat(args2));
              }
            }, "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, path150 = _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, path150);
                    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, path150 = _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, path150);
                  }
                });
                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, path150 = _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, path150, 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, path150 = _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, path150, value);
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideContext", function(_ref13) {
                  var id = _ref13.id, path150 = _ref13.path, rendererID = _ref13.rendererID, wasForwarded = _ref13.wasForwarded, value = _ref13.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path150,
                      rendererID,
                      type: "context",
                      value
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideHookState", function(_ref14) {
                  var id = _ref14.id, hookID = _ref14.hookID, path150 = _ref14.path, rendererID = _ref14.rendererID, wasForwarded = _ref14.wasForwarded, value = _ref14.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path150,
                      rendererID,
                      type: "hooks",
                      value
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideProps", function(_ref15) {
                  var id = _ref15.id, path150 = _ref15.path, rendererID = _ref15.rendererID, wasForwarded = _ref15.wasForwarded, value = _ref15.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path150,
                      rendererID,
                      type: "props",
                      value
                    });
                  }
                });
                agent_defineProperty(agent_assertThisInitialized(_this), "overrideState", function(_ref16) {
                  var id = _ref16.id, path150 = _ref16.path, rendererID = _ref16.rendererID, wasForwarded = _ref16.wasForwarded, value = _ref16.value;
                  if (!wasForwarded) {
                    _this.overrideValueAtPath({
                      id,
                      path: path150,
                      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, path150 = _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, path150, 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, path150 = _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, path150);
                  }
                });
                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 path150 = renderer2 != null ? renderer2.getPathForElement(id) : null;
                  if (path150 !== null) {
                    sessionStorageSetItem(SESSION_STORAGE_LAST_SELECTION_KEY, JSON.stringify({
                      rendererID,
                      path: path150
                    }));
                  } 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 (error40) {
                }
                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 (error40) {
                    }
                  }
                  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;
            }(EventEmitter16);
            ;
            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 i4 = 0, arr2 = new Array(len); i4 < len; i4++) {
                arr2[i4] = arr[i4];
              }
              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 (err2) {
                }
                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 (err2) {
                }
              }
              __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, i4) {
                    if (i4 > 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 (error40) {
                    }
                  }
                }, "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, args2 = new Array(_len), _key = 0; _key < _len; _key++) {
                            args2[_key] = arguments[_key];
                          }
                          originalMethod.apply(void 0, hook_toConsumableArray(formatWithStyles2(args2, "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 (error40) {
                  }
                });
              }
              __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(error40) {
                var frames = error40.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(error40) {
                var startStackFrame = getTopStackFrameString(error40);
                if (startStackFrame !== null) {
                  openModuleRangesStack.push(startStackFrame);
                }
              }
              __name(registerInternalModuleStart, "registerInternalModuleStart");
              function registerInternalModuleStop(error40) {
                if (openModuleRangesStack.length > 0) {
                  var startStackFrame = openModuleRangesStack.pop();
                  var stopStackFrame = getTopStackFrameString(error40);
                  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(instance2) {
                return fn.call(this, old, arguments);
              };
              return old;
            }
            __name(decorate, "decorate");
            function decorateMany(source2, fns) {
              var olds = {};
              for (var name4 in fns) {
                olds[name4] = decorate(source2, name4, fns[name4]);
              }
              return olds;
            }
            __name(decorateMany, "decorateMany");
            function restoreMany(source2, olds) {
              for (var name4 in olds) {
                source2[name4] = olds[name4];
              }
            }
            __name(restoreMany, "restoreMany");
            function forceUpdate(instance2) {
              if (typeof instance2.forceUpdate === "function") {
                instance2.forceUpdate();
              } else if (instance2.updater != null && typeof instance2.updater.enqueueForceUpdate === "function") {
                instance2.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 i4 = 1; i4 < arguments.length; i4++) {
                var source2 = arguments[i4] != null ? arguments[i4] : {};
                if (i4 % 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 name4 in renderedChildren) {
                  var _child = renderedChildren[name4];
                  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 i4 = 0; i4 < a2.length; i4++) {
                  if (a2[i4] !== b2[i4]) {
                    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, args2) {
                    var internalInstance = args2[0];
                    var hostContainerInfo = args2[3];
                    if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) {
                      return fn.apply(this, args2);
                    }
                    if (hostContainerInfo._topLevelWrapper === void 0) {
                      return fn.apply(this, args2);
                    }
                    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, args2);
                      parentIDStack.pop();
                      return result;
                    } catch (err2) {
                      parentIDStack = [];
                      throw err2;
                    } 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, args2) {
                    var internalInstance = args2[0];
                    if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) {
                      return fn.apply(this, args2);
                    }
                    var id = getID(internalInstance);
                    parentIDStack.push(id);
                    var prevChildren = getChildren(internalInstance);
                    try {
                      var result = fn.apply(this, args2);
                      var nextChildren = getChildren(internalInstance);
                      if (!areEqualArrays(prevChildren, nextChildren)) {
                        recordReorder(internalInstance, id, nextChildren);
                      }
                      parentIDStack.pop();
                      return result;
                    } catch (err2) {
                      parentIDStack = [];
                      throw err2;
                    } 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, args2) {
                    var internalInstance = args2[0];
                    if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) {
                      return fn.apply(this, args2);
                    }
                    var id = getID(internalInstance);
                    parentIDStack.push(id);
                    var prevChildren = getChildren(internalInstance);
                    try {
                      var result = fn.apply(this, args2);
                      var nextChildren = getChildren(internalInstance);
                      if (!areEqualArrays(prevChildren, nextChildren)) {
                        recordReorder(internalInstance, id, nextChildren);
                      }
                      parentIDStack.pop();
                      return result;
                    } catch (err2) {
                      parentIDStack = [];
                      throw err2;
                    } 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, args2) {
                    var internalInstance = args2[0];
                    if (getElementType(internalInstance) === ElementTypeOtherOrUnknown) {
                      return fn.apply(this, args2);
                    }
                    var id = getID(internalInstance);
                    parentIDStack.push(id);
                    try {
                      var result = fn.apply(this, args2);
                      parentIDStack.pop();
                      recordUnmount(internalInstance, id);
                      return result;
                    } catch (err2) {
                      parentIDStack = [];
                      throw err2;
                    } 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 i4 = 0; i4 < nextChildIDs.length; i4++) {
                  pushOperation(nextChildIDs[i4]);
                }
              }
              __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 i4 = 0;
                operations[i4++] = rendererID;
                operations[i4++] = rootID;
                operations[i4++] = pendingStringTableLength;
                pendingStringTable.forEach(function(value, key) {
                  operations[i4++] = key.length;
                  var encodedKey = utfEncodeString(key);
                  for (var j3 = 0; j3 < encodedKey.length; j3++) {
                    operations[i4 + j3] = encodedKey[j3];
                  }
                  i4 += key.length;
                });
                if (numUnmountIDs > 0) {
                  operations[i4++] = TREE_OPERATION_REMOVE;
                  operations[i4++] = numUnmountIDs;
                  for (var j2 = 0; j2 < pendingUnmountedIDs.length; j2++) {
                    operations[i4++] = pendingUnmountedIDs[j2];
                  }
                  if (pendingUnmountedRootID !== null) {
                    operations[i4] = pendingUnmountedRootID;
                    i4++;
                  }
                }
                for (var _j = 0; _j < pendingOperations.length; _j++) {
                  operations[i4 + _j] = pendingOperations[_j];
                }
                i4 += 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(path150) {
                var current = currentlyInspectedPaths;
                path150.forEach(function(key) {
                  if (!current[key]) {
                    current[key] = {};
                  }
                  current = current[key];
                });
              }
              __name(mergeInspectedPaths, "mergeInspectedPaths");
              function createIsPathAllowed(key) {
                return /* @__PURE__ */ __name(function isPathAllowed(path150) {
                  var current = currentlyInspectedPaths[key];
                  if (!current) {
                    return false;
                  }
                  for (var i4 = 0; i4 < path150.length; i4++) {
                    current = current[path150[i4]];
                    if (!current) {
                      return false;
                    }
                  }
                  return true;
                }, "isPathAllowed");
              }
              __name(createIsPathAllowed, "createIsPathAllowed");
              function getInstanceAndStyle(id) {
                var instance2 = null;
                var style = null;
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance != null) {
                  instance2 = internalInstance._instance || null;
                  var element = internalInstance._currentElement;
                  if (element != null && element.props != null) {
                    style = element.props.style || null;
                  }
                }
                return {
                  instance: instance2,
                  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, path150, count) {
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement !== null) {
                  var value = utils_getInObject(inspectedElement, path150);
                  var key = "$reactTemp".concat(count);
                  window[key] = value;
                  console.log(key);
                  console.log(value);
                }
              }
              __name(storeAsGlobal, "storeAsGlobal");
              function getSerializedElementValueByPath(id, path150) {
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement !== null) {
                  var valueToCopy = utils_getInObject(inspectedElement, path150);
                  return serializeToString(valueToCopy);
                }
              }
              __name(getSerializedElementValueByPath, "getSerializedElementValueByPath");
              function inspectElement(requestID, id, path150, forceFullData) {
                if (forceFullData || currentlyInspectedElementID !== id) {
                  currentlyInspectedElementID = id;
                  currentlyInspectedPaths = {};
                }
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement === null) {
                  return {
                    id,
                    responseID: requestID,
                    type: "not-found"
                  };
                }
                if (path150 !== null) {
                  mergeInspectedPaths(path150);
                }
                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, path150) {
                var inspectedElement = inspectElementRaw(id);
                if (inspectedElement !== null) {
                  window.$attribute = utils_getInObject(inspectedElement, path150);
                }
              }
              __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, path150) {
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance != null) {
                  var publicInstance = internalInstance._instance;
                  if (publicInstance != null) {
                    switch (type) {
                      case "context":
                        deletePathInObject(publicInstance.context, path150);
                        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, path150)
                        });
                        forceUpdate(publicInstance);
                        break;
                      case "state":
                        deletePathInObject(publicInstance.state, path150);
                        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, path150, value) {
                var internalInstance = idToInternalInstanceMap.get(id);
                if (internalInstance != null) {
                  var publicInstance = internalInstance._instance;
                  if (publicInstance != null) {
                    switch (type) {
                      case "context":
                        utils_setInObject(publicInstance.context, path150, 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, path150, value)
                        });
                        forceUpdate(publicInstance);
                        break;
                      case "state":
                        utils_setInObject(publicInstance.state, path150, 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(enabled2) {
              }
              __name(setTraceUpdatesEnabled, "setTraceUpdatesEnabled");
              function setTrackedPath(path150) {
              }
              __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, name4 = _ref3.name, value = _ref3.value;
                setStyle2(agent2, id, rendererID, name4, 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 instance2 = data.instance, style = data.style;
              var resolvedStyle = resolveNativeStyle(style);
              var styleOverrides = componentIDToStyleOverrides.get(id);
              if (styleOverrides != null) {
                resolvedStyle = Object.assign({}, resolvedStyle, styleOverrides);
              }
              if (!instance2 || typeof instance2.measure !== "function") {
                bridge.send("NativeStyleEditor_styleAndLayout", {
                  id,
                  layout: null,
                  style: resolvedStyle || null
                });
                return;
              }
              instance2.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 instance2 = 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 (instance2 !== null && typeof instance2.setNativeProps === "function") {
                var styleOverrides = componentIDToStyleOverrides.get(id);
                if (!styleOverrides) {
                  componentIDToStyleOverrides.set(id, newStyle);
                } else {
                  Object.assign(styleOverrides, newStyle);
                }
                instance2.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, name4, value) {
              var data = agent2.getInstanceAndStyle({
                id,
                rendererID
              });
              if (!data || !data.style) {
                return;
              }
              var instance2 = data.instance, style = data.style;
              var newStyle = setupNativeStyleEditor_defineProperty({}, name4, value);
              if (instance2 !== null && typeof instance2.setNativeProps === "function") {
                var styleOverrides = componentIDToStyleOverrides.get(id);
                if (!styleOverrides) {
                  componentIDToStyleOverrides.set(id, newStyle);
                } else {
                  Object.assign(styleOverrides, newStyle);
                }
                instance2.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, name4],
                    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, args2 = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                  args2[_key - 1] = arguments[_key];
                }
                (_console = console).log.apply(_console, ["%c[core/backend] %c".concat(methodName), "color: teal; font-weight: bold;", "font-weight: bold;"].concat(args2));
              }
            }
            __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 set2(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 set2(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 (error40) {
                    console.log("[React DevTools] Error calling listener", data);
                    console.log("error:", error40);
                    throw error40;
                  }
                });
              }
              __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_2) {
        calledFunctions.set(onetime3, ++callCount);
        if (callCount === 1) {
          returnValue = function_.apply(this, arguments_2);
          function_ = null;
        } else if (options2.throw === true) {
          throw new Error(`Function \`${functionName}\` can only be called once`);
        }
        return returnValue;
      }, "onetime");
      mimicFn(onetime3, function_);
      calledFunctions.set(onetime3, callCount);
      return onetime3;
    }, "onetime");
    module2.exports = onetime2;
    module2.exports.default = onetime2;
    module2.exports.callCount = (function_) => {
      if (!calledFunctions.has(function_)) {
        throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
      }
      return calledFunctions.get(function_);
    };
  }
});

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

// node_modules/restore-cursor/node_modules/signal-exit/index.js
var require_signal_exit2 = __commonJS({
  "node_modules/restore-cursor/node_modules/signal-exit/index.js"(exports2, module2) {
    init_esbuild_shims();
    var process51 = globalThis.process;
    var processOk = /* @__PURE__ */ __name(function(process52) {
      return process52 && typeof process52 === "object" && typeof process52.removeListener === "function" && typeof process52.emit === "function" && typeof process52.reallyExit === "function" && typeof process52.listeners === "function" && typeof process52.kill === "function" && typeof process52.pid === "number" && typeof process52.on === "function";
    }, "processOk");
    if (!processOk(process51)) {
      module2.exports = function() {
        return function() {
        };
      };
    } else {
      assert4 = __require("assert");
      signals = require_signals2();
      isWin = /^win/i.test(process51.platform);
      EE3 = __require("events");
      if (typeof EE3 !== "function") {
        EE3 = EE3.EventEmitter;
      }
      if (process51.__signal_exit_emitter__) {
        emitter = process51.__signal_exit_emitter__;
      } else {
        emitter = process51.__signal_exit_emitter__ = new EE3();
        emitter.count = 0;
        emitter.emitted = {};
      }
      if (!emitter.infinite) {
        emitter.setMaxListeners(Infinity);
        emitter.infinite = true;
      }
      module2.exports = function(cb, opts) {
        if (!processOk(globalThis.process)) {
          return function() {
          };
        }
        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 {
            process51.removeListener(sig, sigListeners[sig]);
          } catch (er2) {
          }
        });
        process51.emit = originalProcessEmit;
        process51.reallyExit = originalProcessReallyExit;
        emitter.count -= 1;
      }, "unload");
      module2.exports.unload = unload;
      emit = /* @__PURE__ */ __name(function emit2(event, code2, signal) {
        if (emitter.emitted[event]) {
          return;
        }
        emitter.emitted[event] = true;
        emitter.emit(event, code2, signal);
      }, "emit");
      sigListeners = {};
      signals.forEach(function(sig) {
        sigListeners[sig] = /* @__PURE__ */ __name(function listener() {
          if (!processOk(globalThis.process)) {
            return;
          }
          var listeners = process51.listeners(sig);
          if (listeners.length === emitter.count) {
            unload();
            emit("exit", null, sig);
            emit("afterexit", null, sig);
            if (isWin && sig === "SIGHUP") {
              sig = "SIGINT";
            }
            process51.kill(process51.pid, sig);
          }
        }, "listener");
      });
      module2.exports.signals = function() {
        return signals;
      };
      loaded = false;
      load = /* @__PURE__ */ __name(function load2() {
        if (loaded || !processOk(globalThis.process)) {
          return;
        }
        loaded = true;
        emitter.count += 1;
        signals = signals.filter(function(sig) {
          try {
            process51.on(sig, sigListeners[sig]);
            return true;
          } catch (er2) {
            return false;
          }
        });
        process51.emit = processEmit;
        process51.reallyExit = processReallyExit;
      }, "load");
      module2.exports.load = load;
      originalProcessReallyExit = process51.reallyExit;
      processReallyExit = /* @__PURE__ */ __name(function processReallyExit2(code2) {
        if (!processOk(globalThis.process)) {
          return;
        }
        process51.exitCode = code2 || /* istanbul ignore next */
        0;
        emit("exit", process51.exitCode, null);
        emit("afterexit", process51.exitCode, null);
        originalProcessReallyExit.call(process51, process51.exitCode);
      }, "processReallyExit");
      originalProcessEmit = process51.emit;
      processEmit = /* @__PURE__ */ __name(function processEmit2(ev, arg) {
        if (ev === "exit" && processOk(globalThis.process)) {
          if (arg !== void 0) {
            process51.exitCode = arg;
          }
          var ret = originalProcessEmit.apply(this, arguments);
          emit("exit", process51.exitCode, null);
          emit("afterexit", process51.exitCode, null);
          return ret;
        } else {
          return originalProcessEmit.apply(this, arguments);
        }
      }, "processEmit");
    }
    var 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 cwd6 = 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 = cwd6;
        }
        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 file2 = 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 && file2) {
          let closes = 0;
          for (let i4 = file2.length - 1; i4 > 0; i4--) {
            if (file2.charAt(i4) === ")") {
              closes++;
            } else if (file2.charAt(i4) === "(" && file2.charAt(i4 - 1) === " ") {
              closes--;
              if (closes === -1 && file2.charAt(i4 - 1) === " ") {
                const before = file2.slice(0, i4 - 1);
                const after = file2.slice(i4 + 1);
                file2 = after;
                fname += ` (${before}`;
                break;
              }
            }
          }
        }
        if (fname) {
          const methodMatch = fname.match(methodRe);
          if (methodMatch) {
            fname = methodMatch[1];
            method = methodMatch[2];
          }
        }
        setFile(res, file2, 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, cwd7) {
      if (filename) {
        filename = filename.replace(/\\/g, "/");
        if (filename.startsWith(`${cwd7}/`)) {
          filename = filename.slice(cwd7.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, start2, end) => string4.slice(start2, 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 i4 = 0; i4 < jsonString.length; i4++) {
        const currentCharacter = jsonString[i4];
        const nextCharacter = jsonString[i4 + 1];
        if (!insideComment && currentCharacter === '"') {
          const escaped = isEscaped(jsonString, i4);
          if (!escaped) {
            insideString = !insideString;
          }
        }
        if (insideString) {
          continue;
        }
        if (!insideComment && currentCharacter + nextCharacter === "//") {
          result += jsonString.slice(offset, i4);
          offset = i4;
          insideComment = singleComment;
          i4++;
        } else if (insideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
          i4++;
          insideComment = false;
          result += strip2(jsonString, offset, i4);
          offset = i4;
          continue;
        } else if (insideComment === singleComment && currentCharacter === "\n") {
          insideComment = false;
          result += strip2(jsonString, offset, i4);
          offset = i4;
        } else if (!insideComment && currentCharacter + nextCharacter === "/*") {
          result += jsonString.slice(offset, i4);
          offset = i4;
          insideComment = multiComment;
          i4++;
          continue;
        } else if (insideComment === multiComment && currentCharacter + nextCharacter === "*/") {
          i4++;
          insideComment = false;
          result += strip2(jsonString, offset, i4 + 1);
          offset = i4 + 1;
          continue;
        }
      }
      return result + (insideComment ? strip2(jsonString.slice(offset)) : jsonString.slice(offset));
    };
  }
});

// packages/cli/src/utils/stdioHelpers.ts
var writeStdoutLine, writeStderrLine, clearScreen2;
var init_stdioHelpers = __esm({
  "packages/cli/src/utils/stdioHelpers.ts"() {
    "use strict";
    init_esbuild_shims();
    writeStdoutLine = /* @__PURE__ */ __name((message) => {
      process.stdout.write(message.endsWith("\n") ? message : `${message}
`);
    }, "writeStdoutLine");
    writeStderrLine = /* @__PURE__ */ __name((message) => {
      process.stderr.write(message.endsWith("\n") ? message : `${message}
`);
    }, "writeStderrLine");
    clearScreen2 = /* @__PURE__ */ __name(() => {
      console.clear();
    }, "clearScreen");
  }
});

// packages/cli/src/i18n/languages.ts
function getLanguageNameFromLocale(locale) {
  const lower3 = locale.toLowerCase();
  const lang = SUPPORTED_LANGUAGES.find((l3) => l3.code.toLowerCase() === lower3);
  return lang?.fullName || "English";
}
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})`
    }))
  ];
}
function getSupportedLanguageIds(separator = "|") {
  return SUPPORTED_LANGUAGES.map((l3) => l3.id).join(separator);
}
var SUPPORTED_LANGUAGES;
var init_languages = __esm({
  "packages/cli/src/i18n/languages.ts"() {
    "use strict";
    init_esbuild_shims();
    SUPPORTED_LANGUAGES = [
      {
        code: "en",
        id: "en-US",
        fullName: "English",
        nativeName: "English"
      },
      {
        code: "zh-TW",
        id: "zh-TW",
        fullName: "Traditional Chinese",
        nativeName: "\u7E41\u9AD4\u4E2D\u6587"
      },
      {
        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"
      },
      {
        code: "fr",
        id: "fr-FR",
        fullName: "French",
        nativeName: "Fran\xE7ais"
      },
      {
        code: "ca",
        id: "ca-ES",
        fullName: "Catalan",
        nativeName: "Catal\xE0"
      }
    ];
    __name(getLanguageNameFromLocale, "getLanguageNameFromLocale");
    __name(getLanguageSettingsOptions, "getLanguageSettingsOptions");
    __name(getSupportedLanguageIds, "getSupportedLanguageIds");
  }
});

// packages/cli/src/i18n/locales/ca.js
var ca_exports = {};
__export(ca_exports, {
  default: () => ca_default2
});
var ca_default2;
var init_ca2 = __esm({
  "packages/cli/src/i18n/locales/ca.js"() {
    "use strict";
    init_esbuild_shims();
    ca_default2 = {
      // ============================================================================
      // Ajuda / Components de la interfície
      // ============================================================================
      "\u2191 to manage attachments": "\u2191 per gestionar els adjunts",
      "\u2190 \u2192 select, Delete to remove, \u2193 to exit": "\u2190 \u2192 seleccionar, Supr per eliminar, \u2193 per sortir",
      "Attachments: ": "Adjunts: ",
      "Basics:": "B\xE0sic:",
      "Add context": "Afegir context",
      "Use {{symbol}} to specify files for context (e.g., {{example}}) to target specific files or folders.": "Useu {{symbol}} per especificar fitxers de context (p. ex., {{example}}) per seleccionar fitxers o carpetes espec\xEDfics.",
      "@": "@",
      "@src/myFile.ts": "@src/myFile.ts",
      "Shell mode": "Mode shell",
      "YOLO mode": "Mode YOLO",
      "plan mode": "mode de planificaci\xF3",
      "auto-accept edits": "acceptaci\xF3 autom\xE0tica de canvis",
      "Accepting edits": "Acceptant canvis",
      "(shift + tab to cycle)": "(maj + tab per canviar)",
      "(tab to cycle)": "(tab per canviar)",
      "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).": "Executeu ordres shell amb {{symbol}} (p. ex., {{example1}}) o useu el llenguatge natural (p. ex., {{example2}}).",
      "!": "!",
      "!npm run start": "!npm run start",
      "start server": "iniciar el servidor",
      "Commands:": "Ordres:",
      "shell command": "ordre shell",
      "Model Context Protocol command (from external servers)": "Ordre del protocol de context del model (des de servidors externs)",
      "Keyboard Shortcuts:": "Dreceres de teclat:",
      "Toggle this help display": "Mostrar/amagar aquesta ajuda",
      "Toggle shell mode": "Canviar el mode shell",
      "Open command menu": "Obrir el men\xFA d'ordres",
      "Add file context": "Afegir context de fitxer",
      "Accept suggestion / Autocomplete": "Acceptar suggeriment / Autocompleci\xF3",
      "Reverse search history": "Cerca inversa a l'historial",
      "Press ? again to close": "Premeu ? de nou per tancar",
      "for shell mode": "per al mode shell",
      "for commands": "per a les ordres",
      "for file paths": "per als camins de fitxers",
      "to clear input": "per esborrar l'entrada",
      "to cycle approvals": "per canviar les aprovacions",
      "to quit": "per sortir",
      "for newline": "per a nova l\xEDnia",
      "to clear screen": "per netejar la pantalla",
      "to search history": "per cercar a l'historial",
      "to paste images": "per enganxar imatges",
      "for external editor": "per a editor extern",
      "to toggle compact mode": "per canviar el mode compacte",
      "Jump through words in the input": "Saltar entre paraules a l'entrada",
      "Close dialogs, cancel requests, or quit application": "Tancar di\xE0legs, cancel\xB7lar peticions o sortir de l'aplicaci\xF3",
      "New line": "Nova l\xEDnia",
      "New line (Alt+Enter works for certain linux distros)": "Nova l\xEDnia (Alt+Retorn funciona en certes distribucions de Linux)",
      "Clear the screen": "Netejar la pantalla",
      "Open input in external editor": "Obrir l'entrada en un editor extern",
      "Send message": "Enviar missatge",
      "Initializing...": "Inicialitzant...",
      "Connecting to MCP servers... ({{connected}}/{{total}})": "Connectant als servidors MCP... ({{connected}}/{{total}})",
      "Type your message or @path/to/file": "Escriviu el vostre missatge o @cam\xED/al/fitxer",
      "? for shortcuts": "? per a dreceres",
      "Press 'i' for INSERT mode and 'Esc' for NORMAL mode.": "Premeu 'i' per al mode INSERCI\xD3 i 'Esc' per al mode NORMAL.",
      "Cancel operation / Clear input (double press)": "Cancel\xB7lar operaci\xF3 / Esborrar entrada (doble premuda)",
      "Cycle approval modes": "Canviar els modes d'aprovaci\xF3",
      "Cycle through your prompt history": "Navegar per l'historial de missatges",
      "For a full list of shortcuts, see {{docPath}}": "Per a una llista completa de dreceres, vegeu {{docPath}}",
      "docs/keyboard-shortcuts.md": "docs/keyboard-shortcuts.md",
      "for help on Qwen Code": "per a ajuda sobre Qwen Code",
      "show version info": "mostrar informaci\xF3 de la versi\xF3",
      "submit a bug report": "enviar un informe d'error",
      "About Qwen Code": "Sobre Qwen Code",
      Status: "Estat",
      // ============================================================================
      // Informació del sistema
      // ============================================================================
      "Qwen Code": "Qwen Code",
      Runtime: "Entorn d'execuci\xF3",
      OS: "SO",
      Auth: "Autenticaci\xF3",
      "CLI Version": "Versi\xF3 del CLI",
      "Git Commit": "Commit de Git",
      Model: "Model",
      "Fast Model": "Model r\xE0pid",
      Sandbox: "Entorn a\xEFllat",
      "OS Platform": "Plataforma del SO",
      "OS Arch": "Arquitectura del SO",
      "OS Release": "Versi\xF3 del SO",
      "Node.js Version": "Versi\xF3 de Node.js",
      "NPM Version": "Versi\xF3 de NPM",
      "Session ID": "ID de sessi\xF3",
      "Auth Method": "M\xE8tode d'autenticaci\xF3",
      "Base URL": "URL base",
      Proxy: "Proxy",
      "Memory Usage": "\xDAs de mem\xF2ria",
      "IDE Client": "Client IDE",
      // ============================================================================
      // Ordres - General
      // ============================================================================
      "Analyzes the project and creates a tailored QWEN.md file.": "Analitza el projecte i crea un fitxer QWEN.md personalitzat.",
      "List available Qwen Code tools. Usage: /tools [desc]": "Llistar les eines disponibles de Qwen Code. \xDAs: /tools [desc]",
      "List available skills.": "Llistar les habilitats disponibles.",
      "Available Qwen Code CLI tools:": "Eines del CLI de Qwen Code disponibles:",
      "No tools available": "No hi ha eines disponibles",
      "View or change the approval mode for tool usage": "Veure o canviar el mode d'aprovaci\xF3 per a l'\xFAs d'eines",
      'Invalid approval mode "{{arg}}". Valid modes: {{modes}}': `Mode d'aprovaci\xF3 no v\xE0lid "{{arg}}". Modes v\xE0lids: {{modes}}`,
      'Approval mode set to "{{mode}}"': `Mode d'aprovaci\xF3 establert a "{{mode}}"`,
      "View or change the language setting": "Veure o canviar la configuraci\xF3 d'idioma",
      "change the theme": "canviar el tema",
      "Select Theme": "Seleccionar tema",
      Preview: "Previsualitzaci\xF3",
      "(Use Enter to select, Tab to configure scope)": "(Useu Retorn per seleccionar, Tab per configurar l'\xE0mbit)",
      "(Use Enter to apply scope, Tab to go back)": "(Useu Retorn per aplicar l'\xE0mbit, Tab per tornar enrere)",
      "Theme configuration unavailable due to NO_COLOR env variable.": "La configuraci\xF3 del tema no est\xE0 disponible degut a la variable d'entorn NO_COLOR.",
      'Theme "{{themeName}}" not found.': 'Tema "{{themeName}}" no trobat.',
      'Theme "{{themeName}}" not found in selected scope.': `Tema "{{themeName}}" no trobat en l'\xE0mbit seleccionat.`,
      "Clear conversation history and free up context": "Esborrar l'historial de la conversa i alliberar context",
      "Compresses the context by replacing it with a summary.": "Comprimeix el context substituint-lo per un resum.",
      "open full Qwen Code documentation in your browser": "obrir la documentaci\xF3 completa de Qwen Code al navegador",
      "Configuration not available.": "Configuraci\xF3 no disponible.",
      "change the auth method": "canviar el m\xE8tode d'autenticaci\xF3",
      "Configure authentication information for login": "Configurar la informaci\xF3 d'autenticaci\xF3 per a iniciar sessi\xF3",
      "Copy the last result or code snippet to clipboard": "Copiar l'\xFAltim resultat o fragment de codi al porta-retalls",
      // ============================================================================
      // Ordres - Agents
      // ============================================================================
      "Manage subagents for specialized task delegation.": "Gestionar subagents per a la delegaci\xF3 de tasques especialitzades.",
      "Manage existing subagents (view, edit, delete).": "Gestionar subagents existents (veure, editar, eliminar).",
      "Create a new subagent with guided setup.": "Crear un nou subagent amb configuraci\xF3 guiada.",
      // ============================================================================
      // Agents - Diàleg de gestió
      // ============================================================================
      Agents: "Agents",
      "Choose Action": "Triar acci\xF3",
      "Edit {{name}}": "Editar {{name}}",
      "Edit Tools: {{name}}": "Editar eines: {{name}}",
      "Edit Color: {{name}}": "Editar color: {{name}}",
      "Delete {{name}}": "Eliminar {{name}}",
      "Unknown Step": "Pas desconegut",
      "Esc to close": "Esc per tancar",
      "Enter to select, \u2191\u2193 to navigate, Esc to close": "Retorn per seleccionar, \u2191\u2193 per navegar, Esc per tancar",
      "Esc to go back": "Esc per tornar enrere",
      "Enter to confirm, Esc to cancel": "Retorn per confirmar, Esc per cancel\xB7lar",
      "Enter to select, \u2191\u2193 to navigate, Esc to go back": "Retorn per seleccionar, \u2191\u2193 per navegar, Esc per tornar enrere",
      "Enter to submit, Esc to go back": "Retorn per enviar, Esc per tornar enrere",
      "Invalid step: {{step}}": "Pas no v\xE0lid: {{step}}",
      "No subagents found.": "No s'han trobat subagents.",
      "Use '/agents create' to create your first subagent.": "Useu '/agents create' per crear el vostre primer subagent.",
      "(built-in)": "(integrat)",
      "(overridden by project level agent)": "(sobreescrit per un agent de nivell de projecte)",
      "Project Level ({{path}})": "Nivell de projecte ({{path}})",
      "User Level ({{path}})": "Nivell d'usuari ({{path}})",
      "Built-in Agents": "Agents integrats",
      "Extension Agents": "Agents d'extensi\xF3",
      "Using: {{count}} agents": "En \xFAs: {{count}} agents",
      "View Agent": "Veure agent",
      "Edit Agent": "Editar agent",
      "Delete Agent": "Eliminar agent",
      Back: "Enrere",
      "No agent selected": "Cap agent seleccionat",
      "File Path: ": "Cam\xED del fitxer: ",
      "Tools: ": "Eines: ",
      "Color: ": "Color: ",
      "Description:": "Descripci\xF3:",
      "System Prompt:": "Missatge del sistema:",
      "Open in editor": "Obrir a l'editor",
      "Edit tools": "Editar eines",
      "Edit color": "Editar color",
      "\u274C Error:": "\u274C Error:",
      'Are you sure you want to delete agent "{{name}}"?': `Esteu segur que voleu eliminar l'agent "{{name}}"?`,
      // ============================================================================
      // Agents - Assistent de creació
      // ============================================================================
      "Project Level (.qwen/agents/)": "Nivell de projecte (.qwen/agents/)",
      "User Level (~/.qwen/agents/)": "Nivell d'usuari (~/.qwen/agents/)",
      "\u2705 Subagent Created Successfully!": "\u2705 Subagent creat correctament!",
      'Subagent "{{name}}" has been saved to {{level}} level.': `El subagent "{{name}}" s'ha desat al nivell {{level}}.`,
      "Name: ": "Nom: ",
      "Location: ": "Ubicaci\xF3: ",
      "\u274C Error saving subagent:": "\u274C Error en desar el subagent:",
      "Warnings:": "Advert\xE8ncies:",
      'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent': 'El nom "{{name}}" ja existeix al nivell {{level}} - sobreescriur\xE0 el subagent existent',
      'Name "{{name}}" exists at user level - project level will take precedence': `El nom "{{name}}" existeix al nivell d'usuari - el nivell de projecte tindr\xE0 prioritat`,
      'Name "{{name}}" exists at project level - existing subagent will take precedence': 'El nom "{{name}}" existeix al nivell de projecte - el subagent existent tindr\xE0 prioritat',
      "Description is over {{length}} characters": "La descripci\xF3 supera els {{length}} car\xE0cters",
      "System prompt is over {{length}} characters": "El missatge del sistema supera els {{length}} car\xE0cters",
      "Step {{n}}: Choose Location": "Pas {{n}}: Triar ubicaci\xF3",
      "Step {{n}}: Choose Generation Method": "Pas {{n}}: Triar m\xE8tode de generaci\xF3",
      "Generate with Qwen Code (Recommended)": "Generar amb Qwen Code (Recomanat)",
      "Manual Creation": "Creaci\xF3 manual",
      "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)": "Descriviu qu\xE8 ha de fer aquest subagent i quan s'ha d'usar. (Sigueu exhaustiu per obtenir els millors resultats)",
      "e.g., Expert code reviewer that reviews code based on best practices...": "p. ex., Revisor de codi expert que revisa el codi seguint les millors pr\xE0ctiques...",
      "Generating subagent configuration...": "Generant la configuraci\xF3 del subagent...",
      "Failed to generate subagent: {{error}}": "Error en generar el subagent: {{error}}",
      "Step {{n}}: Describe Your Subagent": "Pas {{n}}: Descriure el vostre subagent",
      "Step {{n}}: Enter Subagent Name": "Pas {{n}}: Introduir el nom del subagent",
      "Step {{n}}: Enter System Prompt": "Pas {{n}}: Introduir el missatge del sistema",
      "Step {{n}}: Enter Description": "Pas {{n}}: Introduir la descripci\xF3",
      "Step {{n}}: Select Tools": "Pas {{n}}: Seleccionar eines",
      "All Tools (Default)": "Totes les eines (per defecte)",
      "All Tools": "Totes les eines",
      "Read-only Tools": "Eines de nom\xE9s lectura",
      "Read & Edit Tools": "Eines de lectura i edici\xF3",
      "Read & Edit & Execution Tools": "Eines de lectura, edici\xF3 i execuci\xF3",
      "All tools selected, including MCP tools": "Totes les eines seleccionades, incloses les eines MCP",
      "Selected tools:": "Eines seleccionades:",
      "Read-only tools:": "Eines de nom\xE9s lectura:",
      "Edit tools:": "Eines d'edici\xF3:",
      "Execution tools:": "Eines d'execuci\xF3:",
      "Step {{n}}: Choose Background Color": "Pas {{n}}: Triar el color de fons",
      "Step {{n}}: Confirm and Save": "Pas {{n}}: Confirmar i desar",
      "Esc to cancel": "Esc per cancel\xB7lar",
      "Press Enter to save, e to save and edit, Esc to go back": "Premeu Retorn per desar, e per desar i editar, Esc per tornar enrere",
      "Press Enter to continue, {{navigation}}Esc to {{action}}": "Premeu Retorn per continuar, {{navigation}}Esc per {{action}}",
      cancel: "cancel\xB7lar",
      "go back": "tornar enrere",
      "\u2191\u2193 to navigate, ": "\u2191\u2193 per navegar, ",
      "Enter a clear, unique name for this subagent.": "Introdu\xEFu un nom clar i \xFAnic per a aquest subagent.",
      "e.g., Code Reviewer": "p. ex., Revisor de codi",
      "Name cannot be empty.": "El nom no pot estar buit.",
      "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.": "Escriviu el missatge del sistema que defineix el comportament d'aquest subagent. Sigueu exhaustiu per obtenir els millors resultats.",
      "e.g., You are an expert code reviewer...": "p. ex., Sou un revisor de codi expert...",
      "System prompt cannot be empty.": "El missatge del sistema no pot estar buit.",
      "Describe when and how this subagent should be used.": "Descriviu quan i com s'ha d'usar aquest subagent.",
      "e.g., Reviews code for best practices and potential bugs.": "p. ex., Revisa el codi seguint les millors pr\xE0ctiques i detectant errors potencials.",
      "Description cannot be empty.": "La descripci\xF3 no pot estar buida.",
      "Failed to launch editor: {{error}}": "Error en iniciar l'editor: {{error}}",
      "Failed to save and edit subagent: {{error}}": "Error en desar i editar el subagent: {{error}}",
      // ============================================================================
      // Extensions - Diàleg de gestió
      // ============================================================================
      "Manage Extensions": "Gestionar extensions",
      "Extension Details": "Detalls de l'extensi\xF3",
      "View Extension": "Veure l'extensi\xF3",
      "Update Extension": "Actualitzar l'extensi\xF3",
      "Disable Extension": "Desactivar l'extensi\xF3",
      "Enable Extension": "Activar l'extensi\xF3",
      "Uninstall Extension": "Desinstal\xB7lar l'extensi\xF3",
      "Select Scope": "Seleccionar l'\xE0mbit",
      "User Scope": "\xC0mbit d'usuari",
      "Workspace Scope": "\xC0mbit de l'espai de treball",
      "No extensions found.": "No s'han trobat extensions.",
      Active: "Activa",
      Disabled: "Desactivada",
      "Update available": "Actualitzaci\xF3 disponible",
      "Up to date": "Al dia",
      "Checking...": "Comprovant...",
      "Updating...": "Actualitzant...",
      Unknown: "Desconegut",
      Error: "Error",
      "Version:": "Versi\xF3:",
      "Status:": "Estat:",
      'Are you sure you want to uninstall extension "{{name}}"?': `Esteu segur que voleu desinstal\xB7lar l'extensi\xF3 "{{name}}"?`,
      "This action cannot be undone.": "Aquesta acci\xF3 no es pot desfer.",
      'Extension "{{name}}" disabled successfully.': `L'extensi\xF3 "{{name}}" s'ha desactivat correctament.`,
      'Extension "{{name}}" enabled successfully.': `L'extensi\xF3 "{{name}}" s'ha activat correctament.`,
      'Extension "{{name}}" updated successfully.': `L'extensi\xF3 "{{name}}" s'ha actualitzat correctament.`,
      'Failed to update extension "{{name}}": {{error}}': `Error en actualitzar l'extensi\xF3 "{{name}}": {{error}}`,
      "Select the scope for this action:": "Seleccioneu l'\xE0mbit per a aquesta acci\xF3:",
      "User - Applies to all projects": "Usuari - S'aplica a tots els projectes",
      "Workspace - Applies to current project only": "Espai de treball - S'aplica nom\xE9s al projecte actual",
      "Name:": "Nom:",
      "MCP Servers:": "Servidors MCP:",
      "Settings:": "Configuraci\xF3:",
      active: "activa",
      disabled: "desactivada",
      "View Details": "Veure detalls",
      "Update failed:": "Error en l'actualitzaci\xF3:",
      "Updating {{name}}...": "Actualitzant {{name}}...",
      "Update complete!": "Actualitzaci\xF3 completada!",
      "User (global)": "Usuari (global)",
      "Workspace (project-specific)": "Espai de treball (espec\xEDfic del projecte)",
      'Disable "{{name}}" - Select Scope': 'Desactivar "{{name}}" - Seleccionar \xE0mbit',
      'Enable "{{name}}" - Select Scope': 'Activar "{{name}}" - Seleccionar \xE0mbit',
      "No extension selected": "Cap extensi\xF3 seleccionada",
      "Press Y/Enter to confirm, N/Esc to cancel": "Premeu Y/Retorn per confirmar, N/Esc per cancel\xB7lar",
      "Y/Enter to confirm, N/Esc to cancel": "Y/Retorn per confirmar, N/Esc per cancel\xB7lar",
      "{{count}} extensions installed": "{{count}} extensions instal\xB7lades",
      "Use '/extensions install' to install your first extension.": "Useu '/extensions install' per instal\xB7lar la vostra primera extensi\xF3.",
      "up to date": "al dia",
      "update available": "actualitzaci\xF3 disponible",
      "checking...": "comprovant...",
      "not updatable": "no actualitzable",
      error: "error",
      // ============================================================================
      // Ordres - General (continuació)
      // ============================================================================
      "View and edit Qwen Code settings": "Veure i editar la configuraci\xF3 de Qwen Code",
      Settings: "Configuraci\xF3",
      "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.": "Per veure els canvis, cal reiniciar Qwen Code. Premeu r per sortir i aplicar els canvis ara.",
      'The command "/{{command}}" is not supported in non-interactive mode.': `L'ordre "/{{command}}" no \xE9s compatible en mode no interactiu.`,
      // ============================================================================
      // Etiquetes de configuració
      // ============================================================================
      "Vim Mode": "Mode Vim",
      "Disable Auto Update": "Desactivar actualitzaci\xF3 autom\xE0tica",
      "Attribution: commit": "Atribuci\xF3: commit",
      "Terminal Bell Notification": "Notificaci\xF3 de campana del terminal",
      "Enable Usage Statistics": "Activar estad\xEDstiques d'\xFAs",
      Theme: "Tema",
      "Preferred Editor": "Editor preferit",
      "Auto-connect to IDE": "Connexi\xF3 autom\xE0tica a IDE",
      "Enable Prompt Completion": "Activar la compleci\xF3 de missatges",
      "Debug Keystroke Logging": "Registre de tecles per a depuraci\xF3",
      "Language: UI": "Idioma: Interf\xEDcie",
      "Language: Model": "Idioma: Model",
      "Output Format": "Format de sortida",
      "Hide Window Title": "Amagar el t\xEDtol de la finestra",
      "Show Status in Title": "Mostrar l'estat al t\xEDtol",
      "Hide Tips": "Amagar consells",
      "Show Line Numbers in Code": "Mostrar n\xFAmeros de l\xEDnia al codi",
      "Show Citations": "Mostrar cites",
      "Custom Witty Phrases": "Frases enginyoses personalitzades",
      "Show Welcome Back Dialog": "Mostrar el di\xE0leg de benvinguda",
      "Enable User Feedback": "Activar les valoracions dels usuaris",
      "How is Qwen doing this session? (optional)": "Com va Qwen en aquesta sessi\xF3? (opcional)",
      Bad: "Malament",
      Fine: "B\xE9",
      Good: "Molt b\xE9",
      Dismiss: "Descartar",
      "Not Sure Yet": "Encara no estic segur",
      "Any other key": "Qualsevol altra tecla",
      "Disable Loading Phrases": "Desactivar frases de c\xE0rrega",
      "Screen Reader Mode": "Mode de lector de pantalla",
      "IDE Mode": "Mode IDE",
      "Max Session Turns": "Torns m\xE0xims de sessi\xF3",
      "Skip Next Speaker Check": "Ometre la comprovaci\xF3 del proper parlant",
      "Skip Loop Detection": "Ometre la detecci\xF3 de bucles",
      "Skip Startup Context": "Ometre el context d'inici",
      "Enable OpenAI Logging": "Activar el registre d'OpenAI",
      "OpenAI Logging Directory": "Directori de registres d'OpenAI",
      Timeout: "Temps d'espera",
      "Max Retries": "Reintents m\xE0xims",
      "Disable Cache Control": "Desactivar el control de mem\xF2ria cau",
      "Memory Discovery Max Dirs": "Directoris m\xE0xims de descoberta de mem\xF2ria",
      "Load Memory From Include Directories": "Carregar mem\xF2ria des dels directoris inclosos",
      "Respect .gitignore": "Respectar .gitignore",
      "Respect .qwenignore": "Respectar .qwenignore",
      "Enable Recursive File Search": "Activar la cerca recursiva de fitxers",
      "Disable Fuzzy Search": "Desactivar la cerca difusa",
      "Interactive Shell (PTY)": "Shell interactiva (PTY)",
      "Show Color": "Mostrar color",
      "Auto Accept": "Acceptaci\xF3 autom\xE0tica",
      "Use Ripgrep": "Usar Ripgrep",
      "Use Builtin Ripgrep": "Usar Ripgrep integrat",
      "Enable Tool Output Truncation": "Activar el truncament de la sortida d'eines",
      "Tool Output Truncation Threshold": "Llindar de truncament de la sortida d'eines",
      "Tool Output Truncation Lines": "L\xEDnies de truncament de la sortida d'eines",
      "Folder Trust": "Confian\xE7a de carpeta",
      "Vision Model Preview": "Previsualitzaci\xF3 del model de visi\xF3",
      "Tool Schema Compliance": "Compliment de l'esquema d'eines",
      "Auto (detect from system)": "Autom\xE0tic (detectar del sistema)",
      "Auto (detect terminal theme)": "Autom\xE0tic (detectar el tema del terminal)",
      Auto: "Autom\xE0tic",
      Text: "Text",
      JSON: "JSON",
      Plan: "Planificaci\xF3",
      Default: "Per defecte",
      "Auto Edit": "Edici\xF3 autom\xE0tica",
      YOLO: "YOLO",
      "toggle vim mode on/off": "activar/desactivar el mode Vim",
      "check session stats. Usage: /stats [model|tools]": "comprovar les estad\xEDstiques de la sessi\xF3. \xDAs: /stats [model|tools]",
      "Show model-specific usage statistics.": "Mostrar les estad\xEDstiques d'\xFAs espec\xEDfiques del model.",
      "Show tool-specific usage statistics.": "Mostrar les estad\xEDstiques d'\xFAs espec\xEDfiques de les eines.",
      "exit the cli": "sortir del CLI",
      "Open MCP management dialog, or authenticate with OAuth-enabled servers": "Obrir el di\xE0leg de gesti\xF3 MCP o autenticar-se amb servidors OAuth",
      "List configured MCP servers and tools, or authenticate with OAuth-enabled servers": "Llistar els servidors MCP configurats i les seves eines, o autenticar-se amb servidors OAuth",
      "Manage workspace directories": "Gestionar els directoris de l'espai de treball",
      "Add directories to the workspace. Use comma to separate multiple paths": "Afegir directoris a l'espai de treball. Useu comes per separar m\xFAltiples camins",
      "Show all directories in the workspace": "Mostrar tots els directoris de l'espai de treball",
      "set external editor preference": "establir la prefer\xE8ncia d'editor extern",
      "Select Editor": "Seleccionar editor",
      "Editor Preference": "Prefer\xE8ncia d'editor",
      "These editors are currently supported. Please note that some editors cannot be used in sandbox mode.": "Aquests editors estan suportats. Cal tenir en compte que alguns editors no es poden usar en mode a\xEFllat.",
      "Your preferred editor is:": "El vostre editor preferit \xE9s:",
      "Manage extensions": "Gestionar extensions",
      "Manage installed extensions": "Gestionar les extensions instal\xB7lades",
      "List active extensions": "Llistar les extensions actives",
      "Update extensions. Usage: update <extension-names>|--all": "Actualitzar extensions. \xDAs: update <noms-d'extensions>|--all",
      "Disable an extension": "Desactivar una extensi\xF3",
      "Enable an extension": "Activar una extensi\xF3",
      "Install an extension from a git repo or local path": "Instal\xB7lar una extensi\xF3 des d'un repositori git o cam\xED local",
      "Uninstall an extension": "Desinstal\xB7lar una extensi\xF3",
      "No extensions installed.": "No hi ha extensions instal\xB7lades.",
      "Usage: /extensions update <extension-names>|--all": "\xDAs: /extensions update <noms-d'extensions>|--all",
      'Extension "{{name}}" not found.': 'Extensi\xF3 "{{name}}" no trobada.',
      "No extensions to update.": "No hi ha extensions per actualitzar.",
      "Usage: /extensions install <source>": "\xDAs: /extensions install <font>",
      'Installing extension from "{{source}}"...': 'Instal\xB7lant extensi\xF3 des de "{{source}}"...',
      'Extension "{{name}}" installed successfully.': `L'extensi\xF3 "{{name}}" s'ha instal\xB7lat correctament.`,
      'Failed to install extension from "{{source}}": {{error}}': `Error en instal\xB7lar l'extensi\xF3 des de "{{source}}": {{error}}`,
      "Usage: /extensions uninstall <extension-name>": "\xDAs: /extensions uninstall <nom-de-l'extensi\xF3>",
      'Uninstalling extension "{{name}}"...': `Desinstal\xB7lant l'extensi\xF3 "{{name}}"...`,
      'Extension "{{name}}" uninstalled successfully.': `L'extensi\xF3 "{{name}}" s'ha desinstal\xB7lat correctament.`,
      'Failed to uninstall extension "{{name}}": {{error}}': `Error en desinstal\xB7lar l'extensi\xF3 "{{name}}": {{error}}`,
      "Usage: /extensions {{command}} <extension> [--scope=<user|workspace>]": "\xDAs: /extensions {{command}} <extensi\xF3> [--scope=<user|workspace>]",
      'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': '\xC0mbit no suportat "{{scope}}", ha de ser "user" o "workspace"',
      'Extension "{{name}}" disabled for scope "{{scope}}"': `L'extensi\xF3 "{{name}}" desactivada per a l'\xE0mbit "{{scope}}"`,
      'Extension "{{name}}" enabled for scope "{{scope}}"': `L'extensi\xF3 "{{name}}" activada per a l'\xE0mbit "{{scope}}"`,
      "Do you want to continue? [Y/n]: ": "Voleu continuar? [S/n]: ",
      "Do you want to continue?": "Voleu continuar?",
      'Installing extension "{{name}}".': `Instal\xB7lant l'extensi\xF3 "{{name}}".`,
      "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**": "**Les extensions poden introduir comportaments inesperats. Assegureu-vos d'haver investigat la font de l'extensi\xF3 i de confiar en l'autor.**",
      "This extension will run the following MCP servers:": "Aquesta extensi\xF3 executar\xE0 els servidors MCP seg\xFCents:",
      local: "local",
      remote: "remot",
      "This extension will add the following commands: {{commands}}.": "Aquesta extensi\xF3 afegir\xE0 les ordres seg\xFCents: {{commands}}.",
      "This extension will append info to your QWEN.md context using {{fileName}}": "Aquesta extensi\xF3 afegir\xE0 informaci\xF3 al vostre context QWEN.md usant {{fileName}}",
      "This extension will exclude the following core tools: {{tools}}": "Aquesta extensi\xF3 exclour\xE0 les eines principals seg\xFCents: {{tools}}",
      "This extension will install the following skills:": "Aquesta extensi\xF3 instal\xB7lar\xE0 les habilitats seg\xFCents:",
      "This extension will install the following subagents:": "Aquesta extensi\xF3 instal\xB7lar\xE0 els subagents seg\xFCents:",
      'Installation cancelled for "{{name}}".': 'Instal\xB7laci\xF3 cancel\xB7lada per a "{{name}}".',
      "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.": "Esteu instal\xB7lant una extensi\xF3 des de {{originSource}}. Algunes funcions poden no funcionar perfectament amb Qwen Code.",
      "--ref and --auto-update are not applicable for marketplace extensions.": "--ref i --auto-update no s'apliquen a les extensions del mercat.",
      'Extension "{{name}}" installed successfully and enabled.': `L'extensi\xF3 "{{name}}" s'ha instal\xB7lat i activat correctament.`,
      "Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).": "Instal\xB7la una extensi\xF3 des d'una URL de repositori git, un cam\xED local o el mercat (marketplace-url:nom-del-connector).",
      "The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.": "La URL de GitHub, el cam\xED local o la font del mercat (marketplace-url:nom-del-connector) de l'extensi\xF3 a instal\xB7lar.",
      "The git ref to install from.": "La refer\xE8ncia git des de la qual instal\xB7lar.",
      "Enable auto-update for this extension.": "Activar l'actualitzaci\xF3 autom\xE0tica per a aquesta extensi\xF3.",
      "Enable pre-release versions for this extension.": "Activar les versions preliminars per a aquesta extensi\xF3.",
      "Acknowledge the security risks of installing an extension and skip the confirmation prompt.": "Acceptar els riscos de seguretat d'instal\xB7lar una extensi\xF3 i ometre el missatge de confirmaci\xF3.",
      "The source argument must be provided.": "Cal proporcionar l'argument font.",
      'Extension "{{name}}" successfully uninstalled.': `L'extensi\xF3 "{{name}}" s'ha desinstal\xB7lat correctament.`,
      "Uninstalls an extension.": "Desinstal\xB7la una extensi\xF3.",
      "The name or source path of the extension to uninstall.": "El nom o cam\xED font de l'extensi\xF3 a desinstal\xB7lar.",
      "Please include the name of the extension to uninstall as a positional argument.": "Incloeu el nom de l'extensi\xF3 a desinstal\xB7lar com a argument posicional.",
      "Enables an extension.": "Activa una extensi\xF3.",
      "The name of the extension to enable.": "El nom de l'extensi\xF3 a activar.",
      "The scope to enable the extenison in. If not set, will be enabled in all scopes.": "L'\xE0mbit en el qual activar l'extensi\xF3. Si no s'estableix, s'activar\xE0 en tots els \xE0mbits.",
      'Extension "{{name}}" successfully enabled for scope "{{scope}}".': `L'extensi\xF3 "{{name}}" s'ha activat correctament per a l'\xE0mbit "{{scope}}".`,
      'Extension "{{name}}" successfully enabled in all scopes.': `L'extensi\xF3 "{{name}}" s'ha activat correctament en tots els \xE0mbits.`,
      "Invalid scope: {{scope}}. Please use one of {{scopes}}.": "\xC0mbit no v\xE0lid: {{scope}}. Useu un dels seg\xFCents: {{scopes}}.",
      "Disables an extension.": "Desactiva una extensi\xF3.",
      "The name of the extension to disable.": "El nom de l'extensi\xF3 a desactivar.",
      "The scope to disable the extenison in.": "L'\xE0mbit en el qual desactivar l'extensi\xF3.",
      'Extension "{{name}}" successfully disabled for scope "{{scope}}".': `L'extensi\xF3 "{{name}}" s'ha desactivat correctament per a l'\xE0mbit "{{scope}}".`,
      'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.': `L'extensi\xF3 "{{name}}" s'ha actualitzat correctament: {{oldVersion}} \u2192 {{newVersion}}.`,
      'Unable to install extension "{{name}}" due to missing install metadata': `No es pot instal\xB7lar l'extensi\xF3 "{{name}}" per manca de metadades d'instal\xB7laci\xF3`,
      'Extension "{{name}}" is already up to date.': `L'extensi\xF3 "{{name}}" ja \xE9s al dia.`,
      "Updates all extensions or a named extension to the latest version.": "Actualitza totes les extensions o una extensi\xF3 espec\xEDfica a l'\xFAltima versi\xF3.",
      "Update all extensions.": "Actualitzar totes les extensions.",
      "The name of the extension to update.": "El nom de l'extensi\xF3 a actualitzar.",
      "Either an extension name or --all must be provided": "Cal proporcionar un nom d'extensi\xF3 o --all",
      "Lists installed extensions.": "Llista les extensions instal\xB7lades.",
      "Path:": "Cam\xED:",
      "Source:": "Font:",
      "Type:": "Tipus:",
      "Ref:": "Ref:",
      "Release tag:": "Etiqueta de versi\xF3:",
      "Enabled (User):": "Activada (Usuari):",
      "Enabled (Workspace):": "Activada (Espai de treball):",
      "Context files:": "Fitxers de context:",
      "Skills:": "Habilitats:",
      "Agents:": "Agents:",
      "MCP servers:": "Servidors MCP:",
      "Link extension failed to install.": "No s'ha pogut instal\xB7lar l'extensi\xF3 d'enlla\xE7.",
      'Extension "{{name}}" linked successfully and enabled.': `L'extensi\xF3 "{{name}}" s'ha enlla\xE7at i activat correctament.`,
      "Links an extension from a local path. Updates made to the local path will always be reflected.": "Enlla\xE7a una extensi\xF3 des d'un cam\xED local. Els canvis al cam\xED local sempre es reflectiran.",
      "The name of the extension to link.": "El nom de l'extensi\xF3 a enlla\xE7ar.",
      "Set a specific setting for an extension.": "Establir una configuraci\xF3 espec\xEDfica per a una extensi\xF3.",
      "Name of the extension to configure.": "Nom de l'extensi\xF3 a configurar.",
      "The setting to configure (name or env var).": "La configuraci\xF3 a establir (nom o variable d'entorn).",
      "The scope to set the setting in.": "L'\xE0mbit on establir la configuraci\xF3.",
      "List all settings for an extension.": "Llistar tota la configuraci\xF3 d'una extensi\xF3.",
      "Name of the extension.": "Nom de l'extensi\xF3.",
      'Extension "{{name}}" has no settings to configure.': `L'extensi\xF3 "{{name}}" no t\xE9 cap configuraci\xF3.`,
      'Settings for "{{name}}":': 'Configuraci\xF3 per a "{{name}}":',
      "(workspace)": "(espai de treball)",
      "(user)": "(usuari)",
      "[not set]": "[no establert]",
      "[value stored in keychain]": "[valor emmagatzemat al clauer]",
      "Value:": "Valor:",
      "Manage extension settings.": "Gestionar la configuraci\xF3 de les extensions.",
      "You need to specify a command (set or list).": "Cal especificar una ordre (set o list).",
      // ============================================================================
      // Selecció de connector / Mercat
      // ============================================================================
      "No plugins available in this marketplace.": "No hi ha connectors disponibles en aquest mercat.",
      'Select a plugin to install from marketplace "{{name}}":': 'Seleccioneu un connector per instal\xB7lar des del mercat "{{name}}":',
      "Plugin selection cancelled.": "Selecci\xF3 de connector cancel\xB7lada.",
      'Select a plugin from "{{name}}"': 'Seleccionar un connector de "{{name}}"',
      "Use \u2191\u2193 or j/k to navigate, Enter to select, Escape to cancel": "Useu \u2191\u2193 o j/k per navegar, Retorn per seleccionar, Esc per cancel\xB7lar",
      "{{count}} more above": "{{count}} m\xE9s amunt",
      "{{count}} more below": "{{count}} m\xE9s avall",
      "manage IDE integration": "gestionar la integraci\xF3 de l'IDE",
      "check status of IDE integration": "comprovar l'estat de la integraci\xF3 de l'IDE",
      "install required IDE companion for {{ideName}}": "instal\xB7lar el complement IDE necessari per a {{ideName}}",
      "enable IDE integration": "activar la integraci\xF3 de l'IDE",
      "disable IDE integration": "desactivar la integraci\xF3 de l'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.": "La integraci\xF3 de l'IDE no \xE9s compatible en el vostre entorn actual. Per usar aquesta funci\xF3, executeu Qwen Code en un dels IDEs compatibles: VS Code o bifurcacions de VS Code.",
      "Set up GitHub Actions": "Configurar GitHub Actions",
      "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)": "Configurar les dreceres del terminal per a entrada multil\xEDnia (VS Code, Cursor, Windsurf, Trae)",
      "Please restart your terminal for the changes to take effect.": "Reinicieu el terminal perqu\xE8 els canvis tinguin efecte.",
      "Failed to configure terminal: {{error}}": "Error en configurar el terminal: {{error}}",
      "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.": "No s'ha pogut determinar el cam\xED de configuraci\xF3 de {{terminalName}} a Windows: la variable d'entorn APPDATA no est\xE0 establerta.",
      "{{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 existeix per\xF2 no \xE9s un array JSON v\xE0lid. Corregiu el fitxer manualment o elimineu-lo per permetre la configuraci\xF3 autom\xE0tica.",
      "File: {{file}}": "Fitxer: {{file}}",
      "Failed to parse {{terminalName}} keybindings.json. The file contains invalid JSON. Please fix the file manually or delete it to allow automatic configuration.": "Error en analitzar {{terminalName}} keybindings.json. El fitxer cont\xE9 JSON no v\xE0lid. Corregiu el fitxer manualment o elimineu-lo per permetre la configuraci\xF3 autom\xE0tica.",
      "Error: {{error}}": "Error: {{error}}",
      "Shift+Enter binding already exists": "La drecera Shift+Retorn ja existeix",
      "Ctrl+Enter binding already exists": "La drecera Ctrl+Retorn ja existeix",
      "Existing keybindings detected. Will not modify to avoid conflicts.": "S'han detectat dreceres existents. No es modificaran per evitar conflictes.",
      "Please check and modify manually if needed: {{file}}": "Comproveu i modifiqueu manualment si cal: {{file}}",
      "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.": "S'han afegit les dreceres Shift+Retorn i Ctrl+Retorn a {{terminalName}}.",
      "Modified: {{file}}": "Modificat: {{file}}",
      "{{terminalName}} keybindings already configured.": "Les dreceres de {{terminalName}} ja estan configurades.",
      "Failed to configure {{terminalName}}.": "Error en configurar {{terminalName}}.",
      "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter).": "El vostre terminal ja est\xE0 configurat per a una experi\xE8ncia \xF2ptima amb entrada multil\xEDnia (Shift+Retorn i Ctrl+Retorn).",
      // ============================================================================
      // Ordres - Hooks
      // ============================================================================
      "Manage Qwen Code hooks": "Gestionar els hooks de Qwen Code",
      "List all configured hooks": "Llistar tots els hooks configurats",
      "Enable a disabled hook": "Activar un hook desactivat",
      "Disable an active hook": "Desactivar un hook actiu",
      Hooks: "Hooks",
      "Loading hooks...": "Carregant hooks...",
      "Error loading hooks:": "Error en carregar els hooks:",
      "Press Escape to close": "Premeu Esc per tancar",
      "Press Escape, Ctrl+C, or Ctrl+D to cancel": "Premeu Esc, Ctrl+C o Ctrl+D per cancel\xB7lar",
      "Press Space, Enter, or Escape to dismiss": "Premeu Espai, Retorn o Esc per descartar",
      "No hook selected": "Cap hook seleccionat",
      "No hook events found.": "No s'han trobat esdeveniments de hook.",
      "{{count}} hook configured": "{{count}} hook configurat",
      "{{count}} hooks configured": "{{count}} hooks configurats",
      "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.": "Aquest men\xFA \xE9s de nom\xE9s lectura. Per afegir o modificar hooks, editeu settings.json directament o demaneu-ho a Qwen Code.",
      "Enter to select \xB7 Esc to cancel": "Retorn per seleccionar \xB7 Esc per cancel\xB7lar",
      "Exit codes:": "Codis de sortida:",
      "Configured hooks:": "Hooks configurats:",
      "No hooks configured for this event.": "No hi ha hooks configurats per a aquest esdeveniment.",
      "To add hooks, edit settings.json directly or ask Qwen.": "Per afegir hooks, editeu settings.json directament o demaneu-ho a Qwen.",
      "Enter to select \xB7 Esc to go back": "Retorn per seleccionar \xB7 Esc per tornar enrere",
      "Hook details": "Detalls del hook",
      "Event:": "Esdeveniment:",
      "Extension:": "Extensi\xF3:",
      "Desc:": "Desc:",
      "No hook config selected": "Cap configuraci\xF3 de hook seleccionada",
      "To modify or remove this hook, edit settings.json directly or ask Qwen to help.": "Per modificar o eliminar aquest hook, editeu settings.json directament o demaneu ajuda a Qwen.",
      "Hook Configuration - Disabled": "Configuraci\xF3 de hooks - Desactivats",
      "All hooks are currently disabled. You have {{count}} that are not running.": "Tots els hooks estan desactivats. En teniu {{count}} que no estan en execuci\xF3.",
      "{{count}} configured hook": "{{count}} hook configurat",
      "{{count}} configured hooks": "{{count}} hooks configurats",
      "When hooks are disabled:": "Quan els hooks estan desactivats:",
      "No hook commands will execute": "Cap ordre de hook s'executar\xE0",
      "StatusLine will not be displayed": "La barra d'estat no es mostrar\xE0",
      "Tool operations will proceed without hook validation": "Les operacions d'eines continuaran sense validaci\xF3 de hook",
      'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.': 'Per tornar a activar els hooks, elimineu "disableAllHooks" de settings.json o demaneu-ho a Qwen Code.',
      Project: "Projecte",
      User: "Usuari",
      System: "Sistema",
      Extension: "Extensi\xF3",
      "Local Settings": "Configuraci\xF3 local",
      "User Settings": "Configuraci\xF3 d'usuari",
      "System Settings": "Configuraci\xF3 del sistema",
      Extensions: "Extensions",
      "Session (temporary)": "Sessi\xF3 (temporal)",
      "\u2713 Enabled": "\u2713 Activat",
      "\u2717 Disabled": "\u2717 Desactivat",
      "Before tool execution": "Abans de l'execuci\xF3 de l'eina",
      "After tool execution": "Despr\xE9s de l'execuci\xF3 de l'eina",
      "After tool execution fails": "Quan falla l'execuci\xF3 de l'eina",
      "When notifications are sent": "Quan s'envien notificacions",
      "When the user submits a prompt": "Quan l'usuari envia un missatge",
      "When a new session is started": "Quan s'inicia una nova sessi\xF3",
      "Right before Qwen Code concludes its response": "Immediatament abans que Qwen Code conclou la seva resposta",
      "When a subagent (Agent tool call) is started": "Quan s'inicia un subagent (crida a l'eina Agent)",
      "Right before a subagent concludes its response": "Immediatament abans que un subagent conclou la seva resposta",
      "Before conversation compaction": "Abans de la compactaci\xF3 de la conversa",
      "When a session is ending": "Quan una sessi\xF3 s'est\xE0 acabant",
      "When a permission dialog is displayed": "Quan es mostra un di\xE0leg de permisos",
      "Input to command is JSON of tool call arguments.": "L'entrada a l'ordre \xE9s JSON dels arguments de la crida a l'eina.",
      'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': `L'entrada a l'ordre \xE9s JSON amb els camps "inputs" (arguments de la crida a l'eina) i "response" (resposta de la crida a l'eina).`,
      "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.": "L'entrada a l'ordre \xE9s JSON amb tool_name, tool_input, tool_use_id, error, error_type, is_interrupt i is_timeout.",
      "Input to command is JSON with notification message and type.": "L'entrada a l'ordre \xE9s JSON amb el missatge de notificaci\xF3 i el tipus.",
      "Input to command is JSON with original user prompt text.": "L'entrada a l'ordre \xE9s JSON amb el text original del missatge de l'usuari.",
      "Input to command is JSON with session start source.": "L'entrada a l'ordre \xE9s JSON amb la font d'inici de sessi\xF3.",
      "Input to command is JSON with session end reason.": "L'entrada a l'ordre \xE9s JSON amb el motiu de fi de sessi\xF3.",
      "Input to command is JSON with agent_id and agent_type.": "L'entrada a l'ordre \xE9s JSON amb agent_id i agent_type.",
      "Input to command is JSON with agent_id, agent_type, and agent_transcript_path.": "L'entrada a l'ordre \xE9s JSON amb agent_id, agent_type i agent_transcript_path.",
      "Input to command is JSON with compaction details.": "L'entrada a l'ordre \xE9s JSON amb els detalls de compactaci\xF3.",
      "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.": "L'entrada a l'ordre \xE9s JSON amb tool_name, tool_input i tool_use_id. La sortida JSON amb hookSpecificOutput cont\xE9 la decisi\xF3 de permetre o denegar.",
      "stdout/stderr not shown": "stdout/stderr no es mostra",
      "show stderr to model and continue conversation": "mostrar stderr al model i continuar la conversa",
      "show stderr to user only": "mostrar stderr nom\xE9s a l'usuari",
      "stdout shown in transcript mode (ctrl+o)": "stdout mostrat en mode transcripci\xF3 (ctrl+o)",
      "show stderr to model immediately": "mostrar stderr al model immediatament",
      "show stderr to user only but continue with tool call": "mostrar stderr nom\xE9s a l'usuari per\xF2 continuar amb la crida a l'eina",
      "block processing, erase original prompt, and show stderr to user only": "blocar el processament, esborrar el missatge original i mostrar stderr nom\xE9s a l'usuari",
      "stdout shown to Qwen": "stdout mostrat a Qwen",
      "show stderr to user only (blocking errors ignored)": "mostrar stderr nom\xE9s a l'usuari (errors de bloqueig ignorats)",
      "command completes successfully": "l'ordre es completa correctament",
      "stdout shown to subagent": "stdout mostrat al subagent",
      "show stderr to subagent and continue having it run": "mostrar stderr al subagent i continuar la seva execuci\xF3",
      "stdout appended as custom compact instructions": "stdout afegit com a instruccions compactes personalitzades",
      "block compaction": "blocar la compactaci\xF3",
      "show stderr to user only but continue with compaction": "mostrar stderr nom\xE9s a l'usuari per\xF2 continuar amb la compactaci\xF3",
      "use hook decision if provided": "usar la decisi\xF3 del hook si es proporciona",
      "Config not loaded.": "Configuraci\xF3 no carregada.",
      "Hooks are not enabled. Enable hooks in settings to use this feature.": "Els hooks no estan activats. Activeu els hooks a la configuraci\xF3 per usar aquesta funci\xF3.",
      "No hooks configured. Add hooks in your settings.json file.": "No hi ha hooks configurats. Afegiu hooks al vostre fitxer settings.json.",
      "Configured Hooks ({{count}} total)": "Hooks configurats ({{count}} en total)",
      // ============================================================================
      // Ordres - Exportació de sessió
      // ============================================================================
      "Export current session message history to a file": "Exportar l'historial de missatges de la sessi\xF3 actual a un fitxer",
      "Export session to HTML format": "Exportar la sessi\xF3 en format HTML",
      "Export session to JSON format": "Exportar la sessi\xF3 en format JSON",
      "Export session to JSONL format (one message per line)": "Exportar la sessi\xF3 en format JSONL (un missatge per l\xEDnia)",
      "Export session to markdown format": "Exportar la sessi\xF3 en format markdown",
      // ============================================================================
      // Ordres - Idees
      // ============================================================================
      "generate personalized programming insights from your chat history": "generar idees de programaci\xF3 personalitzades a partir del vostre historial de xat",
      // ============================================================================
      // Ordres - Historial de sessió
      // ============================================================================
      "Resume a previous session": "Reprendre una sessi\xF3 anterior",
      "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested": "Restaurar una crida a una eina. Aix\xF2 restablir\xE0 la conversa i l'historial de fitxers a l'estat en qu\xE8 es trobaven quan es va suggerir la crida a l'eina",
      "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae.": "No s'ha pogut detectar el tipus de terminal. Terminals compatibles: VS Code, Cursor, Windsurf i Trae.",
      'Terminal "{{terminal}}" is not supported yet.': 'El terminal "{{terminal}}" no \xE9s compatible encara.',
      // ============================================================================
      // Ordres - Idioma
      // ============================================================================
      "Invalid language. Available: {{options}}": "Idioma no v\xE0lid. Disponibles: {{options}}",
      "Language subcommands do not accept additional arguments.": "Les subordres d'idioma no accepten arguments addicionals.",
      "Current UI language: {{lang}}": "Idioma actual de la interf\xEDcie: {{lang}}",
      "Current LLM output language: {{lang}}": "Idioma actual de la sortida del model: {{lang}}",
      "LLM output language not set": "Idioma de sortida del model no establert",
      "Set UI language": "Establir l'idioma de la interf\xEDcie",
      "Set LLM output language": "Establir l'idioma de sortida del model",
      "Usage: /language ui [{{options}}]": "\xDAs: /language ui [{{options}}]",
      "Usage: /language output <language>": "\xDAs: /language output <idioma>",
      "Example: /language output \u4E2D\u6587": "Exemple: /language output \u4E2D\u6587",
      "Example: /language output English": "Exemple: /language output English",
      "Example: /language output \u65E5\u672C\u8A9E": "Exemple: /language output \u65E5\u672C\u8A9E",
      "Example: /language output Portugu\xEAs": "Exemple: /language output Portugu\xEAs",
      "UI language changed to {{lang}}": "Idioma de la interf\xEDcie canviat a {{lang}}",
      "LLM output language set to {{lang}}": "Idioma de sortida del model establert a {{lang}}",
      "LLM output language rule file generated at {{path}}": "Fitxer de regles d'idioma de sortida del model generat a {{path}}",
      "Please restart the application for the changes to take effect.": "Reinicieu l'aplicaci\xF3 perqu\xE8 els canvis tinguin efecte.",
      "Failed to generate LLM output language rule file: {{error}}": "Error en generar el fitxer de regles d'idioma de sortida del model: {{error}}",
      "Invalid command. Available subcommands:": "Ordre no v\xE0lida. Subordres disponibles:",
      "Available subcommands:": "Subordres disponibles:",
      "To request additional UI language packs, please open an issue on GitHub.": "Per sol\xB7licitar paquets d'idioma addicionals per a la interf\xEDcie, obriu una incid\xE8ncia a GitHub.",
      "Available options:": "Opcions disponibles:",
      "Set UI language to {{name}}": "Establir l'idioma de la interf\xEDcie a {{name}}",
      // ============================================================================
      // Ordres - Mode d'aprovació
      // ============================================================================
      "Tool Approval Mode": "Mode d'aprovaci\xF3 d'eines",
      "Current approval mode: {{mode}}": "Mode d'aprovaci\xF3 actual: {{mode}}",
      "Available approval modes:": "Modes d'aprovaci\xF3 disponibles:",
      "Approval mode changed to: {{mode}}": "Mode d'aprovaci\xF3 canviat a: {{mode}}",
      "Approval mode changed to: {{mode}} (saved to {{scope}} settings{{location}})": "Mode d'aprovaci\xF3 canviat a: {{mode}} (desat a la configuraci\xF3 {{scope}}{{location}})",
      "Usage: /approval-mode <mode> [--session|--user|--project]": "\xDAs: /approval-mode <mode> [--session|--user|--project]",
      "Scope subcommands do not accept additional arguments.": "Les subordres d'\xE0mbit no accepten arguments addicionals.",
      "Plan mode - Analyze only, do not modify files or execute commands": "Mode de planificaci\xF3 - Analitzar nom\xE9s, sense modificar fitxers ni executar ordres",
      "Default mode - Require approval for file edits or shell commands": "Mode per defecte - Requerir aprovaci\xF3 per a edicions de fitxers o ordres shell",
      "Auto-edit mode - Automatically approve file edits": "Mode d'edici\xF3 autom\xE0tica - Aprovar autom\xE0ticament les edicions de fitxers",
      "YOLO mode - Automatically approve all tools": "Mode YOLO - Aprovar autom\xE0ticament totes les eines",
      "{{mode}} mode": "Mode {{mode}}",
      "Settings service is not available; unable to persist the approval mode.": "El servei de configuraci\xF3 no est\xE0 disponible; no es pot persistir el mode d'aprovaci\xF3.",
      "Failed to save approval mode: {{error}}": "Error en desar el mode d'aprovaci\xF3: {{error}}",
      "Failed to change approval mode: {{error}}": "Error en canviar el mode d'aprovaci\xF3: {{error}}",
      "Apply to current session only (temporary)": "Aplicar nom\xE9s a la sessi\xF3 actual (temporal)",
      "Persist for this project/workspace": "Persistir per a aquest projecte/espai de treball",
      "Persist for this user on this machine": "Persistir per a aquest usuari en aquesta m\xE0quina",
      "Analyze only, do not modify files or execute commands": "Analitzar nom\xE9s, sense modificar fitxers ni executar ordres",
      "Require approval for file edits or shell commands": "Requerir aprovaci\xF3 per a edicions de fitxers o ordres shell",
      "Automatically approve file edits": "Aprovar autom\xE0ticament les edicions de fitxers",
      "Automatically approve all tools": "Aprovar autom\xE0ticament totes les eines",
      "Workspace approval mode exists and takes priority. User-level change will have no effect.": "Existeix un mode d'aprovaci\xF3 de l'espai de treball i t\xE9 prioritat. El canvi a nivell d'usuari no tindr\xE0 cap efecte.",
      "Apply To": "Aplicar a",
      "Workspace Settings": "Configuraci\xF3 de l'espai de treball",
      // ============================================================================
      // Ordres - Memòria
      // ============================================================================
      "Commands for interacting with memory.": "Ordres per interactuar amb la mem\xF2ria.",
      "Show the current memory contents.": "Mostrar el contingut actual de la mem\xF2ria.",
      "Show project-level memory contents.": "Mostrar el contingut de la mem\xF2ria a nivell de projecte.",
      "Show global memory contents.": "Mostrar el contingut de la mem\xF2ria global.",
      "Add content to project-level memory.": "Afegir contingut a la mem\xF2ria a nivell de projecte.",
      "Add content to global memory.": "Afegir contingut a la mem\xF2ria global.",
      "Refresh the memory from the source.": "Actualitzar la mem\xF2ria des de la font.",
      "Usage: /memory add --project <text to remember>": "\xDAs: /memory add --project <text a recordar>",
      "Usage: /memory add --global <text to remember>": "\xDAs: /memory add --global <text a recordar>",
      'Attempting to save to project memory: "{{text}}"': 'Intentant desar a la mem\xF2ria del projecte: "{{text}}"',
      'Attempting to save to global memory: "{{text}}"': 'Intentant desar a la mem\xF2ria global: "{{text}}"',
      "Current memory content from {{count}} file(s):": "Contingut actual de la mem\xF2ria de {{count}} fitxer(s):",
      "Memory is currently empty.": "La mem\xF2ria \xE9s buida actualment.",
      "Project memory file not found or is currently empty.": "El fitxer de mem\xF2ria del projecte no s'ha trobat o \xE9s buit.",
      "Global memory file not found or is currently empty.": "El fitxer de mem\xF2ria global no s'ha trobat o \xE9s buit.",
      "Global memory is currently empty.": "La mem\xF2ria global \xE9s buida actualment.",
      "Global memory content:\n\n---\n{{content}}\n---": "Contingut de la mem\xF2ria global:\n\n---\n{{content}}\n---",
      "Project memory content from {{path}}:\n\n---\n{{content}}\n---": "Contingut de la mem\xF2ria del projecte des de {{path}}:\n\n---\n{{content}}\n---",
      "Project memory is currently empty.": "La mem\xF2ria del projecte \xE9s buida.",
      "Refreshing memory from source files...": "Actualitzant la mem\xF2ria des dels fitxers font...",
      "Add content to the memory. Use --global for global memory or --project for project memory.": "Afegir contingut a la mem\xF2ria. Useu --global per a la mem\xF2ria global o --project per a la mem\xF2ria del projecte.",
      "Usage: /memory add [--global|--project] <text to remember>": "\xDAs: /memory add [--global|--project] <text a recordar>",
      'Attempting to save to memory {{scope}}: "{{fact}}"': 'Intentant desar a la mem\xF2ria {{scope}}: "{{fact}}"',
      "Open auto-memory folder": "Obrir la carpeta de mem\xF2ria autom\xE0tica",
      "Auto-memory: {{status}}": "Mem\xF2ria autom\xE0tica: {{status}}",
      "Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream to run": "Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream per executar",
      never: "mai",
      on: "activada",
      off: "desactivada",
      "\u2726 dreaming": "\u2726 somniant",
      "Remove matching entries from managed auto-memory.": "Eliminar les entrades coincidents de la mem\xF2ria autom\xE0tica gestionada.",
      "Usage: /forget <memory text to remove>": "\xDAs: /forget <text de mem\xF2ria a eliminar>",
      "No managed auto-memory entries matched: {{query}}": "Cap entrada de mem\xF2ria autom\xE0tica gestionada coincideix: {{query}}",
      "Show managed auto-memory status.": "Mostrar l'estat de la mem\xF2ria autom\xE0tica gestionada.",
      "Run managed auto-memory extraction for the current session.": "Executar l'extracci\xF3 de mem\xF2ria autom\xE0tica gestionada per a la sessi\xF3 actual.",
      "Managed auto-memory root: {{root}}": "Arrel de la mem\xF2ria autom\xE0tica gestionada: {{root}}",
      "Managed auto-memory topics:": "Temes de la mem\xF2ria autom\xE0tica gestionada:",
      "No extraction cursor found yet.": "Encara no s'ha trobat cap cursor d'extracci\xF3.",
      "Cursor: session={{sessionId}}, offset={{offset}}, updated={{updatedAt}}": "Cursor: session={{sessionId}}, offset={{offset}}, updated={{updatedAt}}",
      "No chat client available to extract memory.": "No hi ha cap client de xat disponible per extreure mem\xF2ria.",
      "Managed auto-memory extraction is already running.": "L'extracci\xF3 de mem\xF2ria autom\xE0tica gestionada ja s'est\xE0 executant.",
      "Managed auto-memory extraction found no new durable memories.": "L'extracci\xF3 de mem\xF2ria autom\xE0tica gestionada no ha trobat noves mem\xF2ries durables.",
      "Consolidate managed auto-memory topic files.": "Consolidar els fitxers de temes de mem\xF2ria autom\xE0tica gestionada.",
      "Managed auto-memory dream found nothing to improve.": "L'auto-dream de mem\xF2ria gestionada no ha trobat res a millorar.",
      "Deduplicated entries: {{count}}": "Entrades desduplicades: {{count}}",
      "Save a durable memory using the save_memory tool.": "Desar una mem\xF2ria durable usant l'eina save_memory.",
      "Usage: /remember [--global|--project] <text to remember>": "\xDAs: /remember [--global|--project] <text a recordar>",
      // ============================================================================
      // Ordres - MCP
      // ============================================================================
      "Authenticate with an OAuth-enabled MCP server": "Autenticar-se amb un servidor MCP amb OAuth",
      "List configured MCP servers and tools": "Llistar els servidors MCP configurats i les seves eines",
      "Restarts MCP servers.": "Reinicia els servidors MCP.",
      "Open MCP management dialog": "Obrir el di\xE0leg de gesti\xF3 MCP",
      "Could not retrieve tool registry.": "No s'ha pogut recuperar el registre d'eines.",
      "No MCP servers configured with OAuth authentication.": "No hi ha servidors MCP configurats amb autenticaci\xF3 OAuth.",
      "MCP servers with OAuth authentication:": "Servidors MCP amb autenticaci\xF3 OAuth:",
      "Use /mcp auth <server-name> to authenticate.": "Useu /mcp auth <nom-del-servidor> per autenticar-vos.",
      "MCP server '{{name}}' not found.": "El servidor MCP '{{name}}' no s'ha trobat.",
      "Successfully authenticated and refreshed tools for '{{name}}'.": "S'ha autenticat correctament i s'han actualitzat les eines per a '{{name}}'.",
      "Failed to authenticate with MCP server '{{name}}': {{error}}": "Error en autenticar-se amb el servidor MCP '{{name}}': {{error}}",
      "Re-discovering tools from '{{name}}'...": "Redescobrint les eines de '{{name}}'...",
      "Discovered {{count}} tool(s) from '{{name}}'.": "S'han descobert {{count}} eina(es) de '{{name}}'.",
      "Authentication complete. Returning to server details...": "Autenticaci\xF3 completada. Tornant als detalls del servidor...",
      "Authentication successful.": "Autenticaci\xF3 correcta.",
      "If the browser does not open, copy and paste this URL into your browser:": "Si el navegador no s'obre, copieu i enganxeu aquesta URL al vostre navegador:",
      "Make sure to copy the COMPLETE URL - it may wrap across multiple lines.": "Assegureu-vos de copiar la URL COMPLETA - pot ocupar m\xFAltiples l\xEDnies.",
      // ============================================================================
      // Diàleg de gestió MCP
      // ============================================================================
      "Manage MCP servers": "Gestionar els servidors MCP",
      "Server Detail": "Detalls del servidor",
      "Disable Server": "Desactivar el servidor",
      Tools: "Eines",
      "Tool Detail": "Detalls de l'eina",
      "MCP Management": "Gesti\xF3 MCP",
      "Loading...": "Carregant...",
      "Unknown step": "Pas desconegut",
      "Esc to back": "Esc per tornar",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close": "\u2191\u2193 per navegar \xB7 Retorn per seleccionar \xB7 Esc per tancar",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back": "\u2191\u2193 per navegar \xB7 Retorn per seleccionar \xB7 Esc per tornar",
      "\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back": "\u2191\u2193 per navegar \xB7 Retorn per confirmar \xB7 Esc per tornar",
      "User Settings (global)": "Configuraci\xF3 d'usuari (global)",
      "Workspace Settings (project-specific)": "Configuraci\xF3 de l'espai de treball (espec\xEDfica del projecte)",
      "Disable server:": "Desactivar el servidor:",
      "Select where to add the server to the exclude list:": "Seleccioneu on afegir el servidor a la llista d'exclusi\xF3:",
      "Press Enter to confirm, Esc to cancel": "Premeu Retorn per confirmar, Esc per cancel\xB7lar",
      "View tools": "Veure eines",
      Reconnect: "Reconnectar",
      Enable: "Activar",
      Disable: "Desactivar",
      Authenticate: "Autenticar",
      "Re-authenticate": "Tornar a autenticar",
      "Clear Authentication": "Esborrar l'autenticaci\xF3",
      "Server:": "Servidor:",
      "Command:": "Ordre:",
      "Working Directory:": "Directori de treball:",
      "Capabilities:": "Capacitats:",
      "No server selected": "Cap servidor seleccionat",
      prompts: "missatges",
      "(disabled)": "(desactivat)",
      "Error:": "Error:",
      tool: "eina",
      tools: "eines",
      connected: "connectat",
      connecting: "connectant",
      disconnected: "desconnectat",
      "User MCPs": "MCPs de l'usuari",
      "Project MCPs": "MCPs del projecte",
      "Extension MCPs": "MCPs de les extensions",
      server: "servidor",
      servers: "servidors",
      "Add MCP servers to your settings to get started.": "Afegiu servidors MCP a la configuraci\xF3 per comen\xE7ar.",
      "Run qwen --debug to see error logs": "Executeu qwen --debug per veure els registres d'errors",
      "OAuth Authentication": "Autenticaci\xF3 OAuth",
      "Press Enter to start authentication, Esc to go back": "Premeu Retorn per iniciar l'autenticaci\xF3, Esc per tornar enrere",
      "Authenticating... Please complete the login in your browser.": "Autenticant... Completeu l'inici de sessi\xF3 al vostre navegador.",
      "Press c to copy the authorization URL to your clipboard.": "Premeu c per copiar la URL d'autoritzaci\xF3 al porta-retalls.",
      "Copy request sent to your terminal. If paste is empty, copy the URL above manually.": "Sol\xB7licitud de c\xF2pia enviada al vostre terminal. Si el que enganxeu \xE9s buit, copieu la URL anterior manualment.",
      "Cannot write to terminal \u2014 copy the URL above manually.": "No es pot escriure al terminal \u2014 copieu la URL anterior manualment.",
      "Press Enter or Esc to go back": "Premeu Retorn o Esc per tornar enrere",
      "No tools available for this server.": "No hi ha eines disponibles per a aquest servidor.",
      destructive: "destructiu",
      "read-only": "nom\xE9s lectura",
      "open-world": "m\xF3n obert",
      idempotent: "idempotent",
      "Tools for {{name}}": "Eines per a {{name}}",
      "Tools for {{serverName}}": "Eines per a {{serverName}}",
      "{{current}}/{{total}}": "{{current}}/{{total}}",
      required: "obligatori",
      Type: "Tipus",
      Enum: "Enumeraci\xF3",
      Parameters: "Par\xE0metres",
      "No tool selected": "Cap eina seleccionada",
      Annotations: "Anotacions",
      Title: "T\xEDtol",
      "Read Only": "Nom\xE9s lectura",
      Destructive: "Destructiu",
      Idempotent: "Idempotent",
      "Open World": "M\xF3n obert",
      Server: "Servidor",
      "{{count}} invalid tools": "{{count}} eines no v\xE0lides",
      invalid: "no v\xE0lid",
      "invalid: {{reason}}": "no v\xE0lid: {{reason}}",
      "missing name": "nom absent",
      "missing description": "descripci\xF3 absent",
      "(unnamed)": "(sense nom)",
      "Warning: This tool cannot be called by the LLM": "Advert\xE8ncia: el model no pot cridar aquesta eina",
      Reason: "Motiu",
      "Tools must have both name and description to be used by the LLM.": "Les eines han de tenir nom i descripci\xF3 per poder ser usades pel model.",
      // ============================================================================
      // Ordres - Xat
      // ============================================================================
      "Manage conversation history.": "Gestionar l'historial de la conversa.",
      "List saved conversation checkpoints": "Llistar els punts de control desats de la conversa",
      "No saved conversation checkpoints found.": "No s'han trobat punts de control de conversa desats.",
      "List of saved conversations:": "Llista de converses desades:",
      "Note: Newest last, oldest first": "Nota: Les m\xE9s recents al final, les m\xE9s antigues al principi",
      "Save the current conversation as a checkpoint. Usage: /chat save <tag>": "Desar la conversa actual com a punt de control. \xDAs: /chat save <etiqueta>",
      "Missing tag. Usage: /chat save <tag>": "Etiqueta absent. \xDAs: /chat save <etiqueta>",
      "Delete a conversation checkpoint. Usage: /chat delete <tag>": "Eliminar un punt de control de conversa. \xDAs: /chat delete <etiqueta>",
      "Missing tag. Usage: /chat delete <tag>": "Etiqueta absent. \xDAs: /chat delete <etiqueta>",
      "Conversation checkpoint '{{tag}}' has been deleted.": "El punt de control de conversa '{{tag}}' s'ha eliminat.",
      "Error: No checkpoint found with tag '{{tag}}'.": "Error: No s'ha trobat cap punt de control amb l'etiqueta '{{tag}}'.",
      "Resume a conversation from a checkpoint. Usage: /chat resume <tag>": "Reprendre una conversa des d'un punt de control. \xDAs: /chat resume <etiqueta>",
      "Missing tag. Usage: /chat resume <tag>": "Etiqueta absent. \xDAs: /chat resume <etiqueta>",
      "No saved checkpoint found with tag: {{tag}}.": "No s'ha trobat cap punt de control desat amb l'etiqueta: {{tag}}.",
      "A checkpoint with the tag {{tag}} already exists. Do you want to overwrite it?": "Ja existeix un punt de control amb l'etiqueta {{tag}}. Voleu sobreescriure'l?",
      "No chat client available to save conversation.": "No hi ha cap client de xat disponible per desar la conversa.",
      "Conversation checkpoint saved with tag: {{tag}}.": "Punt de control de conversa desat amb l'etiqueta: {{tag}}.",
      "No conversation found to save.": "No s'ha trobat cap conversa per desar.",
      "No chat client available to share conversation.": "No hi ha cap client de xat disponible per compartir la conversa.",
      "Invalid file format. Only .md and .json are supported.": "Format de fitxer no v\xE0lid. Nom\xE9s es suporten .md i .json.",
      "Error sharing conversation: {{error}}": "Error en compartir la conversa: {{error}}",
      "Conversation shared to {{filePath}}": "Conversa compartida a {{filePath}}",
      "No conversation found to share.": "No s'ha trobat cap conversa per compartir.",
      "Share the current conversation to a markdown or json file. Usage: /chat share <file>": "Compartir la conversa actual a un fitxer markdown o json. \xDAs: /chat share <fitxer>",
      // ============================================================================
      // Ordres - Resum
      // ============================================================================
      "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md": "Generar un resum del projecte i desar-lo a .qwen/PROJECT_SUMMARY.md",
      "No chat client available to generate summary.": "No hi ha cap client de xat disponible per generar el resum.",
      "Already generating summary, wait for previous request to complete": "Ja s'est\xE0 generant el resum, espereu que acabi la sol\xB7licitud anterior",
      "No conversation found to summarize.": "No s'ha trobat cap conversa per resumir.",
      "Failed to generate project context summary: {{error}}": "Error en generar el resum del context del projecte: {{error}}",
      "Saved project summary to {{filePathForDisplay}}.": "Resum del projecte desat a {{filePathForDisplay}}.",
      "Saving project summary...": "Desant el resum del projecte...",
      "Generating project summary...": "Generant el resum del projecte...",
      "Failed to generate summary - no text content received from LLM response": "Error en generar el resum - no s'ha rebut contingut de text de la resposta del model",
      // ============================================================================
      // Ordres - Model
      // ============================================================================
      "Switch the model for this session (--fast for suggestion model)": "Canviar el model per a aquesta sessi\xF3 (--fast per al model de suggeriments)",
      "Set a lighter model for prompt suggestions and speculative execution": "Establir un model m\xE9s lleuger per a suggeriments de missatges i execuci\xF3 especulativa",
      "Content generator configuration not available.": "Configuraci\xF3 del generador de contingut no disponible.",
      "Authentication type not available.": "Tipus d'autenticaci\xF3 no disponible.",
      "No models available for the current authentication type ({{authType}}).": "No hi ha models disponibles per al tipus d'autenticaci\xF3 actual ({{authType}}).",
      // ============================================================================
      // Ordres - Netejar
      // ============================================================================
      "Starting a new session, resetting chat, and clearing terminal.": "Iniciant una nova sessi\xF3, restablint el xat i netejant el terminal.",
      "Starting a new session and clearing.": "Iniciant una nova sessi\xF3 i netejant.",
      // ============================================================================
      // Ordres - Comprimir
      // ============================================================================
      "Already compressing, wait for previous request to complete": "Ja s'est\xE0 comprimint, espereu que acabi la sol\xB7licitud anterior",
      "Failed to compress chat history.": "Error en comprimir l'historial del xat.",
      "Failed to compress chat history: {{error}}": "Error en comprimir l'historial del xat: {{error}}",
      "Compressing chat history": "Comprimint l'historial del xat",
      "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.": "L'historial del xat s'ha comprimit de {{originalTokens}} a {{newTokens}} tokens.",
      "Compression was not beneficial for this history size.": "La compressi\xF3 no ha estat beneficiosa per a aquesta mida d'historial.",
      "Chat history compression did not reduce size. This may indicate issues with the compression prompt.": "La compressi\xF3 de l'historial del xat no ha redu\xEFt la mida. Aix\xF2 pot indicar problemes amb el missatge de compressi\xF3.",
      "Could not compress chat history due to a token counting error.": "No s'ha pogut comprimir l'historial del xat per un error de recompte de tokens.",
      "Chat history is already compressed.": "L'historial del xat ja est\xE0 comprimit.",
      // ============================================================================
      // Ordres - Directori
      // ============================================================================
      "Configuration is not available.": "Configuraci\xF3 no disponible.",
      "Please provide at least one path to add.": "Proporcioneu almenys un cam\xED per afegir.",
      "The /directory add command is not supported in restrictive sandbox profiles. Please use --include-directories when starting the session instead.": "L'ordre /directory add no \xE9s compatible en perfils d'entorn a\xEFllat restrictius. En el seu lloc, useu --include-directories en iniciar la sessi\xF3.",
      "Error adding '{{path}}': {{error}}": "Error en afegir '{{path}}': {{error}}",
      "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}": "S'han afegit correctament els fitxers QWEN.md dels directoris seg\xFCents si n'hi ha:\n- {{directories}}",
      "Error refreshing memory: {{error}}": "Error en actualitzar la mem\xF2ria: {{error}}",
      "Successfully added directories:\n- {{directories}}": "S'han afegit correctament els directoris:\n- {{directories}}",
      "Current workspace directories:\n{{directories}}": "Directoris actuals de l'espai de treball:\n{{directories}}",
      // ============================================================================
      // Ordres - Documentació
      // ============================================================================
      "Please open the following URL in your browser to view the documentation:\n{{url}}": "Obriu la URL seg\xFCent al vostre navegador per veure la documentaci\xF3:\n{{url}}",
      "Opening documentation in your browser: {{url}}": "Obrint la documentaci\xF3 al vostre navegador: {{url}}",
      // ============================================================================
      // Diàlegs - Confirmació d'eines
      // ============================================================================
      "Do you want to proceed?": "Voleu continuar?",
      "Yes, allow once": "S\xED, permetre una vegada",
      "Allow always": "Permetre sempre",
      Yes: "S\xED",
      No: "No",
      "No (esc)": "No (esc)",
      "Yes, allow always for this session": "S\xED, permetre sempre per a aquesta sessi\xF3",
      "Modify in progress:": "Modificaci\xF3 en curs:",
      "Save and close external editor to continue": "Deseu i tanqueu l'editor extern per continuar",
      "Apply this change?": "Aplicar aquest canvi?",
      "Yes, allow always": "S\xED, permetre sempre",
      "Modify with external editor": "Modificar amb editor extern",
      "No, suggest changes (esc)": "No, suggerir canvis (esc)",
      "Allow execution of: '{{command}}'?": "Permetre l'execuci\xF3 de: '{{command}}'?",
      "Yes, allow always ...": "S\xED, permetre sempre...",
      "Always allow in this project": "Permetre sempre en aquest projecte",
      "Always allow {{action}} in this project": "Permetre sempre {{action}} en aquest projecte",
      "Always allow for this user": "Permetre sempre per a aquest usuari",
      "Always allow {{action}} for this user": "Permetre sempre {{action}} per a aquest usuari",
      "Yes, restore previous mode ({{mode}})": "S\xED, restaurar el mode anterior ({{mode}})",
      "Yes, and auto-accept edits": "S\xED, i acceptar els canvis autom\xE0ticament",
      "Yes, and manually approve edits": "S\xED, i aprovar els canvis manualment",
      "No, keep planning (esc)": "No, seguir planificant (esc)",
      "URLs to fetch:": "URLs a recuperar:",
      "MCP Server: {{server}}": "Servidor MCP: {{server}}",
      "Tool: {{tool}}": "Eina: {{tool}}",
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?': `Permetre l'execuci\xF3 de l'eina MCP "{{tool}}" del servidor "{{server}}"?`,
      'Yes, always allow tool "{{tool}}" from server "{{server}}"': `S\xED, permetre sempre l'eina "{{tool}}" del servidor "{{server}}"`,
      'Yes, always allow all tools from server "{{server}}"': 'S\xED, permetre sempre totes les eines del servidor "{{server}}"',
      // ============================================================================
      // Diàlegs - Confirmació de shell
      // ============================================================================
      "Shell Command Execution": "Execuci\xF3 d'ordres shell",
      "A custom command wants to run the following shell commands:": "Una ordre personalitzada vol executar les ordres shell seg\xFCents:",
      // ============================================================================
      // Diàlegs - Quota Pro
      // ============================================================================
      "Pro quota limit reached for {{model}}.": "S'ha assolit el l\xEDmit de quota Pro per a {{model}}.",
      "Change auth (executes the /auth command)": "Canviar autenticaci\xF3 (executa l'ordre /auth)",
      "Continue with {{model}}": "Continuar amb {{model}}",
      // ============================================================================
      // Diàlegs - Benvinguda
      // ============================================================================
      "Current Plan:": "Pla actual:",
      "Progress: {{done}}/{{total}} tasks completed": "Progr\xE9s: {{done}}/{{total}} tasques completades",
      ", {{inProgress}} in progress": ", {{inProgress}} en curs",
      "Pending Tasks:": "Tasques pendents:",
      "What would you like to do?": "Qu\xE8 voleu fer?",
      "Choose how to proceed with your session:": "Trieu com voleu continuar la vostra sessi\xF3:",
      "Start new chat session": "Iniciar una nova sessi\xF3 de xat",
      "Continue previous conversation": "Continuar la conversa anterior",
      "\u{1F44B} Welcome back! (Last updated: {{timeAgo}})": "\u{1F44B} Benvingut de nou! (Darrera actualitzaci\xF3: {{timeAgo}})",
      "\u{1F3AF} Overall Goal:": "\u{1F3AF} Objectiu general:",
      // ============================================================================
      // Diàlegs - Autenticació
      // ============================================================================
      "Get started": "Comencem",
      "Select Authentication Method": "Seleccioneu el m\xE8tode d'autenticaci\xF3",
      "OpenAI API key is required to use OpenAI authentication.": "Cal una clau API d'OpenAI per usar l'autenticaci\xF3 d'OpenAI.",
      "You must select an auth method to proceed. Press Ctrl+C again to exit.": "Cal seleccionar un m\xE8tode d'autenticaci\xF3 per continuar. Premeu Ctrl+C de nou per sortir.",
      "Terms of Services and Privacy Notice": "Termes de servei i av\xEDs de privacitat",
      "Qwen OAuth": "Qwen OAuth",
      "Discontinued \u2014 switch to Coding Plan or API Key": "Descontinuat \u2014 canvieu a Coding Plan o clau API",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch provider.": "El nivell gratu\xEFt de Qwen OAuth es va descontinuar el 15-04-2026. Executeu /auth per canviar de prove\xEFdor.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead.": "El nivell gratu\xEFt de Qwen OAuth es va descontinuar el 15-04-2026. Seleccioneu Coding Plan o clau API en el seu lloc.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.": "El nivell gratu\xEFt de Qwen OAuth es va descontinuar el 15-04-2026. Seleccioneu un model d'un altre prove\xEFdor o executeu /auth per canviar.",
      "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n": "\n\u26A0 El nivell gratu\xEFt de Qwen OAuth es va descontinuar el 15-04-2026. Seleccioneu una altra opci\xF3.\n",
      "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models": "De pagament \xB7 Fins a 6.000 sol\xB7licituds/5 h \xB7 Tots els models del Coding Plan d'Alibaba Cloud",
      "Alibaba Cloud Coding Plan": "Coding Plan d'Alibaba Cloud",
      "Bring your own API key": "Porteu la vostra pr\xF2pia clau API",
      "API-KEY": "API-KEY",
      "Use coding plan credentials or your own api-keys/providers.": "Useu les credencials del coding plan o les vostres pr\xF2pies claus API/prove\xEFdors.",
      OpenAI: "OpenAI",
      "Failed to login. Message: {{message}}": "Error en iniciar sessi\xF3. Missatge: {{message}}",
      "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.": "L'autenticaci\xF3 ha de ser {{enforcedType}}, per\xF2 actualment esteu usant {{currentType}}.",
      "Qwen OAuth authentication timed out. Please try again.": "L'autenticaci\xF3 Qwen OAuth ha expirat. Torneu-ho a intentar.",
      "Qwen OAuth authentication cancelled.": "L'autenticaci\xF3 Qwen OAuth s'ha cancel\xB7lat.",
      "Qwen OAuth Authentication": "Autenticaci\xF3 Qwen OAuth",
      "Please visit this URL to authorize:": "Visiteu aquesta URL per autoritzar:",
      "Or scan the QR code below:": "O escanegeu el codi QR de sota:",
      "Waiting for authorization": "Esperant l'autoritzaci\xF3",
      "Time remaining:": "Temps restant:",
      "(Press ESC or CTRL+C to cancel)": "(Premeu ESC o CTRL+C per cancel\xB7lar)",
      "Qwen OAuth Authentication Timeout": "Temps d'espera de l'autenticaci\xF3 Qwen OAuth esgotat",
      "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.": "El token OAuth ha expirat (m\xE9s de {{seconds}} segons). Seleccioneu el m\xE8tode d'autenticaci\xF3 de nou.",
      "Press any key to return to authentication type selection.": "Premeu qualsevol tecla per tornar a la selecci\xF3 del tipus d'autenticaci\xF3.",
      "Waiting for Qwen OAuth authentication...": "Esperant l'autenticaci\xF3 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: La vostra clau API existent a settings.json no s'esborrar\xE0 en usar Qwen OAuth. Podeu tornar a l'autenticaci\xF3 d'OpenAI m\xE9s endavant si cal.",
      "Note: Your existing API key will not be cleared when using Qwen OAuth.": "Nota: La vostra clau API existent no s'esborrar\xE0 en usar Qwen OAuth.",
      "Authentication timed out. Please try again.": "L'autenticaci\xF3 ha expirat. Torneu-ho a intentar.",
      "Waiting for auth... (Press ESC or CTRL+C to cancel)": "Esperant l'autenticaci\xF3... (Premeu ESC o CTRL+C per cancel\xB7lar)",
      "Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.": "Manca la clau API per a l'autenticaci\xF3 compatible amb OpenAI. Establiu settings.security.auth.apiKey o la variable d'entorn {{envKeyHint}}.",
      "{{envKeyHint}} environment variable not found.": "La variable d'entorn {{envKeyHint}} no s'ha trobat.",
      "{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.": "La variable d'entorn {{envKeyHint}} no s'ha trobat. Establiu-la al fitxer .env o a les variables d'entorn.",
      "{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.": "La variable d'entorn {{envKeyHint}} no s'ha trobat (o establiu settings.security.auth.apiKey). Establiu-la al fitxer .env o a les variables d'entorn.",
      "Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.": "Manca la clau API per a l'autenticaci\xF3 compatible amb OpenAI. Establiu la variable d'entorn {{envKeyHint}}.",
      "Anthropic provider missing required baseUrl in modelProviders[].baseUrl.": "El prove\xEFdor Anthropic no t\xE9 la baseUrl obligat\xF2ria a modelProviders[].baseUrl.",
      "ANTHROPIC_BASE_URL environment variable not found.": "La variable d'entorn ANTHROPIC_BASE_URL no s'ha trobat.",
      "Invalid auth method selected.": "S'ha seleccionat un m\xE8tode d'autenticaci\xF3 no v\xE0lid.",
      "Failed to authenticate. Message: {{message}}": "Error en autenticar-se. Missatge: {{message}}",
      "Authenticated successfully with {{authType}} credentials.": "S'ha autenticat correctament amb les credencials {{authType}}.",
      'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}': 'Valor de QWEN_DEFAULT_AUTH_TYPE no v\xE0lid: "{{value}}". Els valors v\xE0lids s\xF3n: {{validValues}}',
      "OpenAI Configuration Required": "Configuraci\xF3 d'OpenAI necess\xE0ria",
      "Please enter your OpenAI configuration. You can get an API key from": "Introdu\xEFu la vostra configuraci\xF3 d'OpenAI. Podeu obtenir una clau API de",
      "API Key:": "Clau API:",
      "Invalid credentials: {{errorMessage}}": "Credencials no v\xE0lides: {{errorMessage}}",
      "Failed to validate credentials": "Error en validar les credencials",
      "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel": "Premeu Retorn per continuar, Tab/\u2191\u2193 per navegar, Esc per cancel\xB7lar",
      // ============================================================================
      // Diàlegs - Model
      // ============================================================================
      "Select Model": "Seleccioneu el model",
      "(Press Esc to close)": "(Premeu Esc per tancar)",
      "Current (effective) configuration": "Configuraci\xF3 actual (efectiva)",
      AuthType: "Tipus d'autenticaci\xF3",
      "API Key": "Clau API",
      unset: "no establert",
      "(default)": "(per defecte)",
      "(set)": "(establert)",
      "(not set)": "(no establert)",
      Modality: "Modalitat",
      "Context Window": "Fin. de context",
      text: "text",
      "text-only": "nom\xE9s text",
      image: "imatge",
      pdf: "pdf",
      audio: "\xE0udio",
      video: "v\xEDdeo",
      "not set": "no establert",
      none: "cap",
      unknown: "desconegut",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "Error en canviar al model '{{modelId}}'.\n\n{{error}}",
      "Qwen 3.6 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.6 Plus \u2014 model h\xEDbrid eficient amb un rendiment de codificaci\xF3 l\xEDder",
      "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)": "L'\xFAltim model de visi\xF3 Qwen d'Alibaba Cloud ModelStudio (versi\xF3: qwen3-vl-plus-2025-09-23)",
      // ============================================================================
      // Diàlegs - Permisos
      // ============================================================================
      "Manage folder trust settings": "Gestionar la configuraci\xF3 de confian\xE7a de carpetes",
      "Manage permission rules": "Gestionar les regles de permisos",
      Allow: "Permetre",
      Ask: "Preguntar",
      Deny: "Denegar",
      Workspace: "Espai de treball",
      "Qwen Code won't ask before using allowed tools.": "Qwen Code no preguntar\xE0 abans d'usar les eines permeses.",
      "Qwen Code will ask before using these tools.": "Qwen Code preguntar\xE0 abans d'usar aquestes eines.",
      "Qwen Code is not allowed to use denied tools.": "Qwen Code no t\xE9 perm\xEDs per usar les eines denegades.",
      "Manage trusted directories for this workspace.": "Gestionar els directoris de confian\xE7a d'aquest espai de treball.",
      "Any use of the {{tool}} tool": "Qualsevol \xFAs de l'eina {{tool}}",
      "{{tool}} commands matching '{{pattern}}'": "Ordres de {{tool}} que coincideixen amb '{{pattern}}'",
      "From user settings": "Des de la configuraci\xF3 d'usuari",
      "From project settings": "Des de la configuraci\xF3 del projecte",
      "From session": "Des de la sessi\xF3",
      "Project settings (local)": "Configuraci\xF3 del projecte (local)",
      "Saved in .qwen/settings.local.json": "Desat a .qwen/settings.local.json",
      "Project settings": "Configuraci\xF3 del projecte",
      "Checked in at .qwen/settings.json": "Registrat a .qwen/settings.json",
      "User settings": "Configuraci\xF3 d'usuari",
      "Saved in at ~/.qwen/settings.json": "Desat a ~/.qwen/settings.json",
      "Add a new rule\u2026": "Afegir una nova regla\u2026",
      "Add {{type}} permission rule": "Afegir una regla de perm\xEDs {{type}}",
      "Permission rules are a tool name, optionally followed by a specifier in parentheses.": "Les regles de permisos s\xF3n un nom d'eina, seguit opcionalment d'un especificador entre par\xE8ntesis.",
      "e.g.,": "p. ex.,",
      or: "o",
      "Enter permission rule\u2026": "Introdu\xEFu la regla de perm\xEDs\u2026",
      "Enter to submit \xB7 Esc to cancel": "Retorn per enviar \xB7 Esc per cancel\xB7lar",
      "Where should this rule be saved?": "On s'ha de desar aquesta regla?",
      "Enter to confirm \xB7 Esc to cancel": "Retorn per confirmar \xB7 Esc per cancel\xB7lar",
      "Delete {{type}} rule?": "Eliminar la regla {{type}}?",
      "Are you sure you want to delete this permission rule?": "Esteu segur que voleu eliminar aquesta regla de permisos?",
      "Permissions:": "Permisos:",
      "(\u2190/\u2192 or tab to cycle)": "(\u2190/\u2192 o tab per canviar)",
      "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel": "Premeu \u2191\u2193 per navegar \xB7 Retorn per seleccionar \xB7 Escriviu per cercar \xB7 Esc per cancel\xB7lar",
      "Search\u2026": "Cercar\u2026",
      "Use /trust to manage folder trust settings for this workspace.": "Useu /trust per gestionar la configuraci\xF3 de confian\xE7a de carpetes d'aquest espai de treball.",
      "Add directory\u2026": "Afegir directori\u2026",
      "Add directory to workspace": "Afegir directori a l'espai de treball",
      "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.": "Qwen Code pot llegir fitxers a l'espai de treball i fer canvis quan l'acceptaci\xF3 autom\xE0tica de canvis est\xE0 activada.",
      "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.": "Qwen Code podr\xE0 llegir fitxers en aquest directori i fer canvis quan l'acceptaci\xF3 autom\xE0tica de canvis est\xE0 activada.",
      "Enter the path to the directory:": "Introdu\xEFu el cam\xED del directori:",
      "Enter directory path\u2026": "Introdu\xEFu el cam\xED del directori\u2026",
      "Tab to complete \xB7 Enter to add \xB7 Esc to cancel": "Tab per completar \xB7 Retorn per afegir \xB7 Esc per cancel\xB7lar",
      "Remove directory?": "Eliminar el directori?",
      "Are you sure you want to remove this directory from the workspace?": "Esteu segur que voleu eliminar aquest directori de l'espai de treball?",
      "  (Original working directory)": "  (Directori de treball original)",
      "  (from settings)": "  (des de la configuraci\xF3)",
      "Directory does not exist.": "El directori no existeix.",
      "Path is not a directory.": "El cam\xED no \xE9s un directori.",
      "This directory is already in the workspace.": "Aquest directori ja \xE9s a l'espai de treball.",
      "Already covered by existing directory: {{dir}}": "Ja cobert per un directori existent: {{dir}}",
      // ============================================================================
      // Barra d'estat
      // ============================================================================
      "Using:": "En \xFAs:",
      "{{count}} open file": "{{count}} fitxer obert",
      "{{count}} open files": "{{count}} fitxers oberts",
      "(ctrl+g to view)": "(ctrl+g per veure)",
      "{{count}} {{name}} file": "{{count}} fitxer {{name}}",
      "{{count}} {{name}} files": "{{count}} fitxers {{name}}",
      "{{count}} MCP server": "{{count}} servidor MCP",
      "{{count}} MCP servers": "{{count}} servidors MCP",
      "{{count}} Blocked": "{{count}} bloquejats",
      "(ctrl+t to view)": "(ctrl+t per veure)",
      "(ctrl+t to toggle)": "(ctrl+t per canviar)",
      "Press Ctrl+C again to exit.": "Premeu Ctrl+C de nou per sortir.",
      "Press Ctrl+D again to exit.": "Premeu Ctrl+D de nou per sortir.",
      "Press Esc again to clear.": "Premeu Esc de nou per esborrar.",
      "Press \u2191 to edit queued messages": "Premeu \u2191 per editar els missatges en cua",
      // ============================================================================
      // Estat MCP
      // ============================================================================
      "No MCP servers configured.": "No hi ha servidors MCP configurats.",
      "\u23F3 MCP servers are starting up ({{count}} initializing)...": "\u23F3 Els servidors MCP s'estan iniciant ({{count}} inicialitzant)...",
      "Note: First startup may take longer. Tool availability will update automatically.": "Nota: El primer inici pot tardar m\xE9s. La disponibilitat de les eines s'actualitzar\xE0 autom\xE0ticament.",
      "Configured MCP servers:": "Servidors MCP configurats:",
      Ready: "Preparat",
      "Starting... (first startup may take longer)": "Iniciant... (el primer inici pot tardar m\xE9s)",
      Disconnected: "Desconnectat",
      "{{count}} tool": "{{count}} eina",
      "{{count}} tools": "{{count}} eines",
      "{{count}} prompt": "{{count}} missatge",
      "{{count}} prompts": "{{count}} missatges",
      "(from {{extensionName}})": "(de {{extensionName}})",
      OAuth: "OAuth",
      "OAuth expired": "OAuth expirat",
      "OAuth not authenticated": "OAuth no autenticat",
      "tools and prompts will appear when ready": "les eines i els missatges apareixeran quan estiguin a punt",
      "{{count}} tools cached": "{{count}} eines en mem\xF2ria cau",
      "Tools:": "Eines:",
      "Parameters:": "Par\xE0metres:",
      "Prompts:": "Missatges:",
      Blocked: "Bloquejat",
      "\u{1F4A1} Tips:": "\u{1F4A1} Consells:",
      Use: "Useu",
      "to show server and tool descriptions": "per mostrar les descripcions del servidor i de les eines",
      "to show tool parameter schemas": "per mostrar els esquemes de par\xE0metres de les eines",
      "to hide descriptions": "per amagar les descripcions",
      "to authenticate with OAuth-enabled servers": "per autenticar-vos amb servidors OAuth",
      Press: "Premeu",
      "to toggle tool descriptions on/off": "per activar/desactivar les descripcions de les eines",
      "Starting OAuth authentication for MCP server '{{name}}'...": "Iniciant l'autenticaci\xF3 OAuth per al servidor MCP '{{name}}'...",
      "Restarting MCP servers...": "Reiniciant els servidors MCP...",
      // ============================================================================
      // Consells d'inici
      // ============================================================================
      "Tips:": "Consells:",
      "Use /compress when the conversation gets long to summarize history and free up context.": "Useu /compress quan la conversa sigui llarga per resumir l'historial i alliberar context.",
      "Start a fresh idea with /clear or /new; the previous session stays available in history.": "Comenceu una idea nova amb /clear o /new; la sessi\xF3 anterior segueix disponible a l'historial.",
      "Use /bug to submit issues to the maintainers when something goes off.": "Useu /bug per enviar incid\xE8ncies als mantenidors quan alguna cosa vagi malament.",
      "Switch auth type quickly with /auth.": "Canvieu r\xE0pidament el tipus d'autenticaci\xF3 amb /auth.",
      "You can run any shell commands from Qwen Code using ! (e.g. !ls).": "Podeu executar qualsevol ordre shell des de Qwen Code usant ! (p. ex. !ls).",
      "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.": "Escriviu / per obrir el men\xFA emergent d'ordres; Tab completa autom\xE0ticament les ordres de barra i els missatges desats.",
      "You can resume a previous conversation by running qwen --continue or qwen --resume.": "Podeu reprendre una conversa anterior executant qwen --continue o qwen --resume.",
      "You can switch permission mode quickly with Shift+Tab or /approval-mode.": "Podeu canviar r\xE0pidament el mode de permisos amb Maj+Tab o /approval-mode.",
      "You can switch permission mode quickly with Tab or /approval-mode.": "Podeu canviar r\xE0pidament el mode de permisos amb Tab o /approval-mode.",
      "Try /insight to generate personalized insights from your chat history.": "Proveu /insight per generar idees personalitzades a partir del vostre historial de xat.",
      "Press Ctrl+O to toggle compact mode \u2014 hide tool output and thinking for a cleaner view.": "Premeu Ctrl+O per canviar el mode compacte \u2014 amagueu la sortida de les eines i el pensament per a una vista m\xE9s neta.",
      "Add a QWEN.md file to give Qwen Code persistent project context.": "Afegiu un fitxer QWEN.md per donar a Qwen Code un context persistent del projecte.",
      "Use /btw to ask a quick side question without disrupting the conversation.": "Useu /btw per fer una pregunta r\xE0pida sense interrompre la conversa.",
      "Context is almost full! Run /compress now or start /new to continue.": "El context gaireb\xE9 \xE9s ple! Executeu /compress ara o inicieu /new per continuar.",
      "Context is getting full. Use /compress to free up space.": "El context s'omple. Useu /compress per alliberar espai.",
      "Long conversation? /compress summarizes history to free context.": "Conversa llarga? /compress resumeix l'historial per alliberar context.",
      // ============================================================================
      // Pantalla de sortida / Estadístiques
      // ============================================================================
      "Agent powering down. Goodbye!": "L'agent s'apaga. Fins aviat!",
      "To continue this session, run": "Per continuar aquesta sessi\xF3, executeu",
      "Interaction Summary": "Resum de la interacci\xF3",
      "Session ID:": "ID de sessi\xF3:",
      "Tool Calls:": "Crides a eines:",
      "Success Rate:": "Taxa d'\xE8xit:",
      "User Agreement:": "Acord de l'usuari:",
      reviewed: "revisades",
      "Code Changes:": "Canvis de codi:",
      Performance: "Rendiment",
      "Wall Time:": "Temps real:",
      "Agent Active:": "Agent actiu:",
      "API Time:": "Temps de l'API:",
      "Tool Time:": "Temps d'eines:",
      "Session Stats": "Estad\xEDstiques de la sessi\xF3",
      "Model Usage": "\xDAs del model",
      Reqs: "Sol\xB7licituds",
      "Input Tokens": "Tokens d'entrada",
      "Output Tokens": "Tokens de sortida",
      "Savings Highlight:": "Estalvis destacats:",
      "of input tokens were served from the cache, reducing costs.": "dels tokens d'entrada s'han servit des de la mem\xF2ria cau, reduint els costos.",
      "Tip: For a full token breakdown, run `/stats model`.": "Consell: Per a un desglossament complet de tokens, executeu `/stats model`.",
      "Model Stats For Nerds": "Estad\xEDstiques del model per a nerds",
      "Tool Stats For Nerds": "Estad\xEDstiques d'eines per a nerds",
      Metric: "M\xE8trica",
      API: "API",
      Requests: "Sol\xB7licituds",
      Errors: "Errors",
      "Avg Latency": "Lat\xE8ncia mitjana",
      Tokens: "Tokens",
      Total: "Total",
      Prompt: "Missatge",
      Cached: "En mem\xF2ria cau",
      Thoughts: "Pensaments",
      Tool: "Eina",
      Output: "Sortida",
      "No API calls have been made in this session.": "No s'ha realitzat cap crida a l'API en aquesta sessi\xF3.",
      "Tool Name": "Nom de l'eina",
      Calls: "Crides",
      "Success Rate": "Taxa d'\xE8xit",
      "Avg Duration": "Durada mitjana",
      "User Decision Summary": "Resum de decisions de l'usuari",
      "Total Reviewed Suggestions:": "Total de suggeriments revisats:",
      " \xBB Accepted:": " \xBB Acceptats:",
      " \xBB Rejected:": " \xBB Rebutjats:",
      " \xBB Modified:": " \xBB Modificats:",
      " Overall Agreement Rate:": " Taxa d'acord global:",
      "No tool calls have been made in this session.": "No s'ha realitzat cap crida a eines en aquesta sessi\xF3.",
      "Session start time is unavailable, cannot calculate stats.": "L'hora d'inici de la sessi\xF3 no est\xE0 disponible, no es poden calcular les estad\xEDstiques.",
      // ============================================================================
      // Migració del format d'ordres
      // ============================================================================
      "Command Format Migration": "Migraci\xF3 del format d'ordres",
      "Found {{count}} TOML command file:": "S'ha trobat {{count}} fitxer d'ordres TOML:",
      "Found {{count}} TOML command files:": "S'han trobat {{count}} fitxers d'ordres TOML:",
      "Current tasks": "Tasques actuals",
      "... and {{count}} more": "... i {{count}} m\xE9s",
      "The TOML format is deprecated. Would you like to migrate them to Markdown format?": "El format TOML \xE9s obsolet. Voleu migrar-los al format Markdown?",
      "(Backups will be created and original files will be preserved)": "(Es crearan c\xF2pies de seguretat i els fitxers originals es conservaran)",
      // ============================================================================
      // Frases de càrrega
      // ============================================================================
      "Waiting for user confirmation...": "Esperant la confirmaci\xF3 de l'usuari...",
      "(esc to cancel, {{time}})": "(esc per cancel\xB7lar, {{time}})",
      // ============================================================================
      // Frases de càrrega enginyoses
      // ============================================================================
      WITTY_LOADING_PHRASES: [
        "Em sento afortunat",
        "Enviant el millor...",
        "Setze jutges d'un jutjat mengen fetge d'un penjat.",
        "Navegant pel fong mucilagin\xF3s...",
        "Consultant els esperits digitals...",
        "Desperta ferro...",
        "Escalfant els h\xE0msters de la IA...",
        "Preguntant a la petxina m\xE0gica...",
        "Generant una r\xE8plica enginyosa...",
        "Polint els algorismes...",
        "No correu la perfecci\xF3 (ni el meu codi)...",
        "Preparant bytes frescos...",
        "Comptant electrons...",
        "Activant els processadors cognitius...",
        "Buscant errors de sintaxi a l'univers...",
        "Un moment, optimitzant l'humor...",
        "Barrejant les gr\xE0cies...",
        "Desenredant les xarxes neuronals...",
        "Compilant la brillantor...",
        "Carregant gr\xE0cia.exe...",
        "Invocant el n\xFAvol de saviesa...",
        "Preparant una resposta enginyosa...",
        "Un segon, estic depurant la realitat...",
        "Donant els \xFAltims cops de...",
        "Afinant les freq\xFC\xE8ncies c\xF2smiques...",
        "Elaborant una resposta digna de la vostra paci\xE8ncia...",
        "Compilant els 1 i els 0...",
        "Resolent depend\xE8ncies... i crisis existencials...",
        "Desfragmentant records... tant de RAM com personals...",
        "Reiniciant el m\xF2dul de l'humor...",
        "Emmagatzemant en mem\xF2ria cau el necessari (principalment mems de gats)...",
        "Optimitzant per a velocitat rid\xEDcula",
        "Intercanviant bits... que no ho s\xE0piguen els bytes...",
        "Recollint brossa... torno de seguida...",
        "Assemblant les internets...",
        "Convertint caf\xE8 en codi...",
        "Actualitzant la sintaxi de la realitat...",
        "Reconnectant les sinapsis...",
        "Buscant un punt i coma mal posat...",
        "Engreixant els engranatges de la m\xE0quina...",
        "Precalfant els servidors...",
        "Calibrant el condensador de flux...",
        "Activant el motor de improbabilitat...",
        "Canalitzant la For\xE7a...",
        "Alineant les estrelles per a una resposta \xF2ptima...",
        "I tots ho diem...",
        "Carregant la propera gran idea...",
        "Un moment, estic en el meu element...",
        "Preparant-me per impressionar-vos amb brillantor...",
        "Un moment, polint el meu enginy...",
        "Aguanteu, estic creant una obra mestra...",
        "Un moment, depurant l'univers...",
        "Un moment, alineant els p\xEDxels...",
        "Un segon, optimitzant l'humor...",
        "Un moment, afinant els algorismes...",
        "Velocitat de curvatura activada...",
        "Preparant la seg\xFCent jugada mestre...",
        "No us espanteu...",
        "Seguint el conill blanc...",
        "La veritat \xE9s aqu\xED... en algun lloc...",
        "Bufant al cartutx...",
        "Carregant... Feu un gir de barril!",
        "Esperant la reaparici\xF3...",
        "Paci\xE8ncia, pensa que Rodalies encara va m\xE9s lent...",
        "El past\xEDs no \xE9s una mentida, simplement s'est\xE0 carregant...",
        "Tafanejant la pantalla de creaci\xF3 de personatge...",
        "Un moment, trobo el meme adequat...",
        "Prement 'A' per continuar...",
        "Pasturant gats digitals...",
        "Polint els p\xEDxels...",
        "Buscant un acudit per a la pantalla de c\xE0rrega...",
        "Distreu-vos amb aquesta frase enginyosa...",
        "Gaireb\xE9 a punt... probablement...",
        "Els nostres h\xE0msters treballen tan r\xE0pid com poden...",
        "Donant un copet al cap a Cloudy...",
        "Fent festes al gat...",
        "Endavant les atxes...",
        "Mai no us deixar\xE9 anar, mai no us decebr\xE9...",
        "Tocant el baix...",
        "Vaig a buscar ratafia...",
        "Vaig a tota velocitat, vaig a tota marxa...",
        "\xC9s la vida real? \xC9s sols fantasia?...",
        "Tinc bon pressentiment sobre aix\xF2...",
        "Tocant el tigre...",
        "Investigant els \xFAltims mems...",
        "Pensant com fer aix\xF2 m\xE9s enginy\xF3s...",
        "Hmm... deixeu-me pensar...",
        "Suant la cansalada...",
        "Trient el fetge per la boca...",
        "Posar fil a l'agulla...",
        "Un moment, ho tenim a tocar..",
        "Aix\xF2 \xE9s bufar i fer ampolles",
        "Qu\xE8 pots fer amb un llapis trencat? Res, no t\xE9 punta...",
        "Aplicant manteniment percussiu...",
        "Buscant l'orientaci\xF3 correcta de l'USB...",
        "Assegurant que el fum m\xE0gic quedi dins dels cables...",
        "Intentant sortir del Vim...",
        "Girant la roda del h\xE0mster...",
        "Aix\xF2 no \xE9s un error, \xE9s una caracter\xEDstica no documentada...",
        "Endavant.",
        "Tornar\xE9... amb una resposta.",
        "El meu altre proc\xE9s \xE9s una TARDIS...",
        "Posant oli als engranatges...",
        "Deixant que els pensaments macerin...",
        "Acabo de recordar on he deixat les claus...",
        "Ponderant l'orbe...",
        "He vist coses que no creur\xEDeu... com un usuari que llegeix els missatges de c\xE0rrega.",
        "Iniciant la mirada pensativa...",
        "Quin \xE9s el berenar preferit d'un computador? Xips micro.",
        "Per qu\xE8 els programadors de Java porten ulleres? Perqu\xE8 no veuen en C#.",
        "Carregant el l\xE0ser... piu piu!",
        "Dividint per zero... \xE9s broma!",
        "Buscant un supervisor adult... \xE9s a dir, processant.",
        "Fent que faci xup xup.",
        "Emmarcant... perqu\xE8 fins i tot les IA necessiten un moment.",
        "Entrella\xE7ant part\xEDcules qu\xE0ntiques per a una resposta m\xE9s r\xE0pida...",
        "Polint el crom... dels algorismes.",
        "No esteu entretinguts? (Hi estem treballant!)",
        "Invocant els follets del codi... per ajudar, \xE9s clar.",
        "Esperant que acabi el so del m\xF2dem de marcaci\xF3...",
        "Recalibrant el mesurament de l'humor.",
        "La meva altra pantalla de c\xE0rrega \xE9s fins i tot m\xE9s divertida.",
        "Estic bastant segur que hi ha un gat caminant per algun teclat...",
        "Millorant... millorant... encara carregant.",
        "No \xE9s un error, \xE9s una caracter\xEDstica... d'aquesta pantalla de c\xE0rrega.",
        "Heu provat apagar-ho i tornar-lo a encendre? (La pantalla de c\xE0rrega, no jo.)",
        "Construint pil\xF3 addicionals..."
      ],
      // ============================================================================
      // Entrada de configuració d'extensions
      // ============================================================================
      "Enter value...": "Introdu\xEFu el valor...",
      "Enter sensitive value...": "Introdu\xEFu el valor sensible...",
      "Press Enter to submit, Escape to cancel": "Premeu Retorn per enviar, Esc per cancel\xB7lar",
      // ============================================================================
      // Eina de migració d'ordres
      // ============================================================================
      "Markdown file already exists: {{filename}}": "El fitxer Markdown ja existeix: {{filename}}",
      "TOML Command Format Deprecation Notice": "Av\xEDs d'obsolesc\xE8ncia del format d'ordres TOML",
      "Found {{count}} command file(s) in TOML format:": "S'ha(n) trobat {{count}} fitxer(s) d'ordres en format TOML:",
      "The TOML format for commands is being deprecated in favor of Markdown format.": "El format TOML per a ordres s'est\xE0 fent obsolet en favor del format Markdown.",
      "Markdown format is more readable and easier to edit.": "El format Markdown \xE9s m\xE9s llegible i f\xE0cil d'editar.",
      "You can migrate these files automatically using:": "Podeu migrar aquests fitxers autom\xE0ticament usant:",
      "Or manually convert each file:": "O convertiu cada fitxer manualment:",
      'TOML: prompt = "..." / description = "..."': 'TOML: prompt = "..." / description = "..."',
      "Markdown: YAML frontmatter + content": "Markdown: cap\xE7alera YAML + contingut",
      "The migration tool will:": "L'eina de migraci\xF3 far\xE0:",
      "Convert TOML files to Markdown": "Convertir fitxers TOML a Markdown",
      "Create backups of original files": "Crear c\xF2pies de seguretat dels fitxers originals",
      "Preserve all command functionality": "Preservar tota la funcionalitat de les ordres",
      "TOML format will continue to work for now, but migration is recommended.": "El format TOML seguir\xE0 funcionant de moment, per\xF2 es recomana la migraci\xF3.",
      // ============================================================================
      // Extensions - Ordre d'explorar
      // ============================================================================
      "Open extensions page in your browser": "Obrir la p\xE0gina d'extensions al vostre navegador",
      "Unknown extensions source: {{source}}.": "Font d'extensions desconeguda: {{source}}.",
      "Would open extensions page in your browser: {{url}} (skipped in test environment)": "Obriria la p\xE0gina d'extensions al vostre navegador: {{url}} (om\xE8s en entorn de proves)",
      "View available extensions at {{url}}": "Veure les extensions disponibles a {{url}}",
      "Opening extensions page in your browser: {{url}}": "Obrint la p\xE0gina d'extensions al vostre navegador: {{url}}",
      "Failed to open browser. Check out the extensions gallery at {{url}}": "Error en obrir el navegador. Visiteu la galeria d'extensions a {{url}}",
      // ============================================================================
      // Reintents / Límit de velocitat
      // ============================================================================
      "Rate limit error: {{reason}}": "Error de l\xEDmit de velocitat: {{reason}}",
      "Retrying in {{seconds}} seconds\u2026 (attempt {{attempt}}/{{maxRetries}})": "Reintentant en {{seconds}} segons\u2026 (intent {{attempt}}/{{maxRetries}})",
      "Press Ctrl+Y to retry": "Premeu Ctrl+Y per reintentar",
      "No failed request to retry.": "No hi ha cap sol\xB7licitud fallida per reintentar.",
      "to retry last request": "per reintentar l'\xFAltima sol\xB7licitud",
      // ============================================================================
      // Autenticació del Coding Plan
      // ============================================================================
      "API key cannot be empty.": "La clau API no pot estar buida.",
      'Invalid API key. Coding Plan API keys start with "sk-sp-". Please check.': 'Clau API no v\xE0lida. Les claus API del Coding Plan comencen per "sk-sp-". Comproveu-la.',
      "You can get your Coding Plan API key here": "Podeu obtenir la vostra clau API del Coding Plan aqu\xED",
      "API key is stored in settings.env. You can migrate it to a .env file for better security.": "La clau API s'emmagatzema a settings.env. Podeu migrar-la a un fitxer .env per una millor seguretat.",
      "New model configurations are available for Alibaba Cloud Coding Plan. Update now?": "Hi ha noves configuracions de model disponibles per al Coding Plan d'Alibaba Cloud. Actualitzeu ara?",
      "Coding Plan configuration updated successfully. New models are now available.": "La configuraci\xF3 del Coding Plan s'ha actualitzat correctament. Ara hi ha nous models disponibles.",
      "Coding Plan API key not found. Please re-authenticate with Coding Plan.": "No s'ha trobat la clau API del Coding Plan. Torneu a autenticar-vos amb el Coding Plan.",
      "Failed to update Coding Plan configuration: {{message}}": "Error en actualitzar la configuraci\xF3 del Coding Plan: {{message}}",
      // ============================================================================
      // Configuració de clau API personalitzada
      // ============================================================================
      "You can configure your API key and models in settings.json": "Podeu configurar la vostra clau API i els models a settings.json",
      "Refer to the documentation for setup instructions": "Consulteu la documentaci\xF3 per a les instruccions de configuraci\xF3",
      // ============================================================================
      // Diàleg d'autenticació - Títols i etiquetes
      // ============================================================================
      "Coding Plan": "Coding Plan",
      "Paste your api key of ModelStudio Coding Plan and you're all set!": "Enganxeu la vostra clau API del Coding Plan de ModelStudio i ja esteu llest!",
      Custom: "Personalitzat",
      "More instructions about configuring `modelProviders` manually.": "M\xE9s instruccions sobre la configuraci\xF3 manual de `modelProviders`.",
      "Select API-KEY configuration mode:": "Seleccioneu el mode de configuraci\xF3 de la clau API:",
      "(Press Escape to go back)": "(Premeu Esc per tornar enrere)",
      "(Press Enter to submit, Escape to cancel)": "(Premeu Retorn per enviar, Esc per cancel\xB7lar)",
      "Select Region for Coding Plan": "Seleccioneu la regi\xF3 per al Coding Plan",
      "Choose based on where your account is registered": "Trieu en funci\xF3 d'on teniu registrat el compte",
      "Enter Coding Plan API Key": "Introdu\xEFu la clau API del Coding Plan",
      // ============================================================================
      // Actualitzacions internacionals del Coding Plan
      // ============================================================================
      "New model configurations are available for {{region}}. Update now?": "Hi ha noves configuracions de model disponibles per a {{region}}. Actualitzeu ara?",
      '{{region}} configuration updated successfully. Model switched to "{{model}}".': `La configuraci\xF3 de {{region}} s'ha actualitzat correctament. El model ha canviat a "{{model}}".`,
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up).": "S'ha autenticat correctament amb {{region}}. La clau API i les configuracions del model s'han desat a settings.json (amb c\xF2pia de seguretat).",
      // ============================================================================
      // Component d'ús del context
      // ============================================================================
      "Context Usage": "\xDAs del context",
      "% used": "% usat",
      "% context used": "% del context usat",
      "Context exceeds limit! Use /compress or /clear to reduce.": "El context supera el l\xEDmit! Useu /compress o /clear per reduir-lo.",
      "Use /compress or /clear": "Useu /compress o /clear",
      "No API response yet. Send a message to see actual usage.": "Encara no hi ha cap resposta de l'API. Envieu un missatge per veure l'\xFAs real.",
      "Estimated pre-conversation overhead": "C\xE0rrega estimada pr\xE8via a la conversa",
      "Context window": "Finestra de context",
      tokens: "tokens",
      Used: "Usat",
      Free: "Lliure",
      "Autocompact buffer": "Mem\xF2ria interm\xE8dia de compactaci\xF3 autom\xE0tica",
      "Usage by category": "\xDAs per categoria",
      "System prompt": "Missatge del sistema",
      "Built-in tools": "Eines integrades",
      "MCP tools": "Eines MCP",
      "Memory files": "Fitxers de mem\xF2ria",
      Skills: "Habilitats",
      Messages: "Missatges",
      "Show context window usage breakdown.": "Mostrar el desglossament de l'\xFAs de la finestra de context.",
      "Run /context detail for per-item breakdown.": "Executeu /context detail per a un desglossament per element.",
      'Show context window usage breakdown. Use "/context detail" for per-item breakdown.': `Mostrar el desglossament de l'\xFAs de la finestra de context. Useu "/context detail" per a un desglossament per element.`,
      "body loaded": "cos carregat",
      memory: "mem\xF2ria",
      "{{region}} configuration updated successfully.": "La configuraci\xF3 de {{region}} s'ha actualitzat correctament.",
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json.": "S'ha autenticat correctament amb {{region}}. La clau API i les configuracions del model s'han desat a settings.json.",
      "Tip: Use /model to switch between available Coding Plan models.": "Consell: Useu /model per canviar entre els models del Coding Plan disponibles.",
      // ============================================================================
      // Eina de preguntes a l'usuari
      // ============================================================================
      "Please answer the following question(s):": "Responeu la(es) pregunta(es) seg\xFCent(s):",
      "Cannot ask user questions in non-interactive mode. Please run in interactive mode to use this tool.": "No es poden fer preguntes a l'usuari en mode no interactiu. Executeu en mode interactiu per usar aquesta eina.",
      "User declined to answer the questions.": "L'usuari ha declinat respondre les preguntes.",
      "User has provided the following answers:": "L'usuari ha proporcionat les respostes seg\xFCents:",
      "Failed to process user answers:": "Error en processar les respostes de l'usuari:",
      "Type something...": "Escriviu alguna cosa...",
      Submit: "Enviar",
      "Submit answers": "Enviar respostes",
      Cancel: "Cancel\xB7lar",
      "Your answers:": "Les vostres respostes:",
      "(not answered)": "(sense resposta)",
      "Ready to submit your answers?": "Preparats per enviar les vostres respostes?",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select": "\u2191/\u2193: Navegar | \u2190/\u2192: Canviar pestanyes | Retorn: Seleccionar",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: Navegar | \u2190/\u2192: Canviar pestanyes | Espai/Retorn: Canviar | Esc: Cancel\xB7lar",
      "\u2191/\u2193: Navigate | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: Navegar | Espai/Retorn: Canviar | Esc: Cancel\xB7lar",
      "\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel": "\u2191/\u2193: Navegar | Retorn: Seleccionar | Esc: Cancel\xB7lar",
      // ============================================================================
      // Ordres - Autenticació
      // ============================================================================
      "Configure Qwen authentication information with Qwen-OAuth or Alibaba Cloud Coding Plan": "Configurar la informaci\xF3 d'autenticaci\xF3 de Qwen amb Qwen-OAuth o el Coding Plan d'Alibaba Cloud",
      "Authenticate using Qwen OAuth": "Autenticar-se usant Qwen OAuth",
      "Authenticate using Alibaba Cloud Coding Plan": "Autenticar-se usant el Coding Plan d'Alibaba Cloud",
      "Region for Coding Plan (china/global)": "Regi\xF3 per al Coding Plan (china/global)",
      "API key for Coding Plan": "Clau API per al Coding Plan",
      "Show current authentication status": "Mostrar l'estat d'autenticaci\xF3 actual",
      "Authentication completed successfully.": "L'autenticaci\xF3 s'ha completat correctament.",
      "Starting Qwen OAuth authentication...": "Iniciant l'autenticaci\xF3 Qwen OAuth...",
      "Successfully authenticated with Qwen OAuth.": "S'ha autenticat correctament amb Qwen OAuth.",
      "Failed to authenticate with Qwen OAuth: {{error}}": "Error en autenticar-se amb Qwen OAuth: {{error}}",
      "Processing Alibaba Cloud Coding Plan authentication...": "Processant l'autenticaci\xF3 del Coding Plan d'Alibaba Cloud...",
      "Successfully authenticated with Alibaba Cloud Coding Plan.": "S'ha autenticat correctament amb el Coding Plan d'Alibaba Cloud.",
      "Failed to authenticate with Coding Plan: {{error}}": "Error en autenticar-se amb el Coding Plan: {{error}}",
      "\u4E2D\u56FD (China)": "\u4E2D\u56FD (China)",
      "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)": "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)",
      Global: "Global",
      "Alibaba Cloud (alibabacloud.com)": "Alibaba Cloud (alibabacloud.com)",
      "Select region for Coding Plan:": "Seleccioneu la regi\xF3 per al Coding Plan:",
      "Enter your Coding Plan API key: ": "Introdu\xEFu la vostra clau API del Coding Plan: ",
      "Select authentication method:": "Seleccioneu el m\xE8tode d'autenticaci\xF3:",
      "\n=== Authentication Status ===\n": "\n=== Estat d'autenticaci\xF3 ===\n",
      "\u26A0\uFE0F  No authentication method configured.\n": "\u26A0\uFE0F  Cap m\xE8tode d'autenticaci\xF3 configurat.\n",
      "Run one of the following commands to get started:\n": "Executeu una de les ordres seg\xFCents per comen\xE7ar:\n",
      "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)": "  qwen auth qwen-oauth     - Autenticar-se amb Qwen OAuth (descontinuat)",
      "  qwen auth coding-plan      - Authenticate with Alibaba Cloud Coding Plan\n": "  qwen auth coding-plan      - Autenticar-se amb el Coding Plan d'Alibaba Cloud\n",
      "Or simply run:": "O simplement executeu:",
      "  qwen auth                - Interactive authentication setup\n": "  qwen auth                - Configuraci\xF3 interactiva de l'autenticaci\xF3\n",
      "\u2713 Authentication Method: Qwen OAuth": "\u2713 M\xE8tode d'autenticaci\xF3: Qwen OAuth",
      "  Type: Free tier (discontinued 2026-04-15)": "  Tipus: Nivell gratu\xEFt (descontinuat el 15-04-2026)",
      "  Limit: No longer available": "  L\xEDmit: Ja no disponible",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.": "El nivell gratu\xEFt de Qwen OAuth es va descontinuar el 15-04-2026. Executeu /auth per canviar al Coding Plan, OpenRouter, Fireworks AI o un altre prove\xEFdor.",
      "  Models: Qwen latest models\n": "  Models: \xDAltims models Qwen\n",
      "\u2713 Authentication Method: Alibaba Cloud Coding Plan": "\u2713 M\xE8tode d'autenticaci\xF3: Coding Plan d'Alibaba Cloud",
      "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC": "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC",
      "Global - Alibaba Cloud": "Global - Alibaba Cloud",
      "  Region: {{region}}": "  Regi\xF3: {{region}}",
      "  Current Model: {{model}}": "  Model actual: {{model}}",
      "  Config Version: {{version}}": "  Versi\xF3 de configuraci\xF3: {{version}}",
      "  Status: API key configured\n": "  Estat: Clau API configurada\n",
      "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)": "\u26A0\uFE0F  M\xE8tode d'autenticaci\xF3: Coding Plan d'Alibaba Cloud (Incomplet)",
      "  Issue: API key not found in environment or settings\n": "  Problema: Clau API no trobada a l'entorn o la configuraci\xF3\n",
      "  Run `qwen auth coding-plan` to re-configure.\n": "  Executeu `qwen auth coding-plan` per tornar a configurar.\n",
      "\u2713 Authentication Method: {{type}}": "\u2713 M\xE8tode d'autenticaci\xF3: {{type}}",
      "  Status: Configured\n": "  Estat: Configurat\n",
      "Failed to check authentication status: {{error}}": "Error en comprovar l'estat d'autenticaci\xF3: {{error}}",
      "Select an option:": "Seleccioneu una opci\xF3:",
      "Raw mode not available. Please run in an interactive terminal.": "El mode raw no est\xE0 disponible. Executeu en un terminal interactiu.",
      "(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n": "(Useu les fletxes \u2191 \u2193 per navegar, Retorn per seleccionar, Ctrl+C per sortir)\n",
      compact: "compacte",
      "compact mode: on (Ctrl+O off)": "mode compacte: activat (Ctrl+O per desactivar)",
      "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).": "Amagueu la sortida de les eines i el pensament per a una vista m\xE9s neta (canvieu amb Ctrl+O).",
      "Press Ctrl+O to show full tool output": "Premeu Ctrl+O per mostrar la sortida completa de les eines",
      "Switch to plan mode or exit plan mode": "Canviar al mode de planificaci\xF3 o sortir del mode de planificaci\xF3",
      "Exited plan mode. Previous approval mode restored.": "S'ha sortit del mode de planificaci\xF3. S'ha restaurat el mode d'aprovaci\xF3 anterior.",
      "Enabled plan mode. The agent will analyze and plan without executing tools.": "S'ha activat el mode de planificaci\xF3. L'agent analitzar\xE0 i planificar\xE0 sense executar eines.",
      'Already in plan mode. Use "/plan exit" to exit plan mode.': 'Ja esteu en mode de planificaci\xF3. Useu "/plan exit" per sortir del mode de planificaci\xF3.',
      'Not in plan mode. Use "/plan" to enter plan mode first.': 'No esteu en mode de planificaci\xF3. Useu "/plan" per entrar al mode de planificaci\xF3 primer.',
      "Set up Qwen Code's status line UI": "Configurar la interf\xEDcie de la barra d'estat de Qwen Code"
    };
  }
});

// packages/cli/src/i18n/locales/de.js
var de_exports = {};
__export(de_exports, {
  default: () => de_default2
});
var de_default2;
var init_de2 = __esm({
  "packages/cli/src/i18n/locales/de.js"() {
    "use strict";
    init_esbuild_shims();
    de_default2 = {
      // ============================================================================
      // 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",
      "Fast Model": "Schnelles 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]",
      "List available skills.": "Verf\xFCgbare Skills auflisten.",
      "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",
      "Enter to submit, Esc to go back": "Enter zum Absenden, 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)",
      "Auto (detect terminal theme)": "Automatisch (Terminal-Theme erkennen)",
      Auto: "Automatisch",
      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",
      "Open MCP management dialog, or authenticate with OAuth-enabled servers": "MCP-Verwaltungsdialog \xF6ffnen oder mit OAuth-f\xE4higem Server authentifizieren",
      "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",
      "Manage installed extensions": "Installierte 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).",
      // ============================================================================
      // Commands - Hooks
      // ============================================================================
      "Manage Qwen Code hooks": "Qwen Code-Hooks verwalten",
      "List all configured hooks": "Alle konfigurierten Hooks auflisten",
      "Enable a disabled hook": "Einen deaktivierten Hook aktivieren",
      "Disable an active hook": "Einen aktiven Hook deaktivieren",
      // Hooks - Dialog
      Hooks: "Hooks",
      "Loading hooks...": "Hooks werden geladen...",
      "Error loading hooks:": "Fehler beim Laden der Hooks:",
      "Press Escape to close": "Escape zum Schlie\xDFen dr\xFCcken",
      "Press Escape, Ctrl+C, or Ctrl+D to cancel": "Escape, Ctrl+C oder Ctrl+D zum Abbrechen",
      "Press Space, Enter, or Escape to dismiss": "Leertaste, Enter oder Escape zum Schlie\xDFen",
      "No hook selected": "Kein Hook ausgew\xE4hlt",
      // Hooks - List Step
      "No hook events found.": "Keine Hook-Ereignisse gefunden.",
      "{{count}} hook configured": "{{count}} Hook konfiguriert",
      "{{count}} hooks configured": "{{count}} Hooks konfiguriert",
      "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.": "Dieses Men\xFC ist schreibgesch\xFCtzt. Um Hooks hinzuzuf\xFCgen oder zu \xE4ndern, bearbeiten Sie settings.json direkt oder fragen Sie Qwen Code.",
      "Enter to select \xB7 Esc to cancel": "Enter zum Ausw\xE4hlen \xB7 Esc zum Abbrechen",
      // Hooks - Detail Step
      "Exit codes:": "Exit-Codes:",
      "Configured hooks:": "Konfigurierte Hooks:",
      "No hooks configured for this event.": "F\xFCr dieses Ereignis sind keine Hooks konfiguriert.",
      "To add hooks, edit settings.json directly or ask Qwen.": "Um Hooks hinzuzuf\xFCgen, bearbeiten Sie settings.json direkt oder fragen Sie Qwen.",
      "Enter to select \xB7 Esc to go back": "Enter zum Ausw\xE4hlen \xB7 Esc zum Zur\xFCck",
      // Hooks - Config Detail Step
      "Hook details": "Hook-Details",
      "Event:": "Ereignis:",
      "Extension:": "Erweiterung:",
      "Desc:": "Beschreibung:",
      "No hook config selected": "Keine Hook-Konfiguration ausgew\xE4hlt",
      "To modify or remove this hook, edit settings.json directly or ask Qwen to help.": "Um diesen Hook zu \xE4ndern oder zu entfernen, bearbeiten Sie settings.json direkt oder fragen Sie Qwen.",
      // Hooks - Disabled Step
      "Hook Configuration - Disabled": "Hook-Konfiguration - Deaktiviert",
      "All hooks are currently disabled. You have {{count}} that are not running.": "Alle Hooks sind derzeit deaktiviert. Sie haben {{count}} die nicht ausgef\xFChrt werden.",
      "{{count}} configured hook": "{{count}} konfigurierter Hook",
      "{{count}} configured hooks": "{{count}} konfigurierte Hooks",
      "When hooks are disabled:": "Wenn Hooks deaktiviert sind:",
      "No hook commands will execute": "Keine Hook-Befehle werden ausgef\xFChrt",
      "StatusLine will not be displayed": "StatusLine wird nicht angezeigt",
      "Tool operations will proceed without hook validation": "Tool-Operationen werden ohne Hook-Validierung fortgesetzt",
      'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.': 'Um Hooks wieder zu aktivieren, entfernen Sie "disableAllHooks" aus settings.json oder fragen Sie Qwen Code.',
      // Hooks - Source
      Project: "Projekt",
      User: "Benutzer",
      System: "System",
      Extension: "Erweiterung",
      "Local Settings": "Lokale Einstellungen",
      "User Settings": "Benutzereinstellungen",
      "System Settings": "Systemeinstellungen",
      Extensions: "Erweiterungen",
      "Session (temporary)": "Sitzung (tempor\xE4r)",
      // Hooks - Status
      "\u2713 Enabled": "\u2713 Aktiviert",
      "\u2717 Disabled": "\u2717 Deaktiviert",
      // Hooks - Event Descriptions (short)
      "Before tool execution": "Vor der Tool-Ausf\xFChrung",
      "After tool execution": "Nach der Tool-Ausf\xFChrung",
      "After tool execution fails": "Wenn die Tool-Ausf\xFChrung fehlschl\xE4gt",
      "When notifications are sent": "Wenn Benachrichtigungen gesendet werden",
      "When the user submits a prompt": "Wenn der Benutzer einen Prompt absendet",
      "When a new session is started": "Wenn eine neue Sitzung gestartet wird",
      "Right before Qwen Code concludes its response": "Direkt bevor Qwen Code seine Antwort abschlie\xDFt",
      "When a subagent (Agent tool call) is started": "Wenn ein Subagent (Agent-Tool-Aufruf) gestartet wird",
      "Right before a subagent concludes its response": "Direkt bevor ein Subagent seine Antwort abschlie\xDFt",
      "Before conversation compaction": "Vor der Gespr\xE4chskomprimierung",
      "When a session is ending": "Wenn eine Sitzung endet",
      "When a permission dialog is displayed": "Wenn ein Berechtigungsdialog angezeigt wird",
      // Hooks - Event Descriptions (detailed)
      "Input to command is JSON of tool call arguments.": "Die Eingabe an den Befehl ist JSON der Tool-Aufruf-Argumente.",
      'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': 'Die Eingabe an den Befehl ist JSON mit den Feldern "inputs" (Tool-Aufruf-Argumente) und "response" (Tool-Aufruf-Antwort).',
      "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.": "Die Eingabe an den Befehl ist JSON mit tool_name, tool_input, tool_use_id, error, error_type, is_interrupt und is_timeout.",
      "Input to command is JSON with notification message and type.": "Die Eingabe an den Befehl ist JSON mit Benachrichtigungsnachricht und -typ.",
      "Input to command is JSON with original user prompt text.": "Die Eingabe an den Befehl ist JSON mit dem urspr\xFCnglichen Benutzer-Prompt-Text.",
      "Input to command is JSON with session start source.": "Die Eingabe an den Befehl ist JSON mit der Sitzungsstart-Quelle.",
      "Input to command is JSON with session end reason.": "Die Eingabe an den Befehl ist JSON mit dem Sitzungsende-Grund.",
      "Input to command is JSON with agent_id and agent_type.": "Die Eingabe an den Befehl ist JSON mit agent_id und agent_type.",
      "Input to command is JSON with agent_id, agent_type, and agent_transcript_path.": "Die Eingabe an den Befehl ist JSON mit agent_id, agent_type und agent_transcript_path.",
      "Input to command is JSON with compaction details.": "Die Eingabe an den Befehl ist JSON mit Komprimierungsdetails.",
      "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.": "Die Eingabe an den Befehl ist JSON mit tool_name, tool_input und tool_use_id. Ausgabe ist JSON mit hookSpecificOutput, das die Entscheidung zum Zulassen oder Ablehnen enth\xE4lt.",
      // Hooks - Exit Code Descriptions
      "stdout/stderr not shown": "stdout/stderr nicht angezeigt",
      "show stderr to model and continue conversation": "stderr dem Modell anzeigen und Konversation fortsetzen",
      "show stderr to user only": "stderr nur dem Benutzer anzeigen",
      "stdout shown in transcript mode (ctrl+o)": "stdout im Transkriptmodus angezeigt (ctrl+o)",
      "show stderr to model immediately": "stderr sofort dem Modell anzeigen",
      "show stderr to user only but continue with tool call": "stderr nur dem Benutzer anzeigen, aber mit Tool-Aufruf fortfahren",
      "block processing, erase original prompt, and show stderr to user only": "Verarbeitung blockieren, urspr\xFCnglichen Prompt l\xF6schen und stderr nur dem Benutzer anzeigen",
      "stdout shown to Qwen": "stdout dem Qwen anzeigen",
      "show stderr to user only (blocking errors ignored)": "stderr nur dem Benutzer anzeigen (Blockierungsfehler ignoriert)",
      "command completes successfully": "Befehl erfolgreich abgeschlossen",
      "stdout shown to subagent": "stdout dem Subagenten anzeigen",
      "show stderr to subagent and continue having it run": "stderr dem Subagenten anzeigen und ihn weiterlaufen lassen",
      "stdout appended as custom compact instructions": "stdout als benutzerdefinierte Komprimierungsanweisungen angeh\xE4ngt",
      "block compaction": "Komprimierung blockieren",
      "show stderr to user only but continue with compaction": "stderr nur dem Benutzer anzeigen, aber mit Komprimierung fortfahren",
      "use hook decision if provided": "Hook-Entscheidung verwenden, falls bereitgestellt",
      // Hooks - Messages
      "Config not loaded.": "Konfiguration nicht geladen.",
      "Hooks are not enabled. Enable hooks in settings to use this feature.": "Hooks sind nicht aktiviert. Aktivieren Sie Hooks in den Einstellungen, um diese Funktion zu nutzen.",
      "No hooks configured. Add hooks in your settings.json file.": "Keine Hooks konfiguriert. F\xFCgen Sie Hooks in Ihrer settings.json-Datei hinzu.",
      "Configured Hooks ({{count}} total)": "Konfigurierte Hooks ({{count}} insgesamt)",
      // ============================================================================
      // Commands - Session Export
      // ============================================================================
      "Export current session message history to a file": "Den Nachrichtenverlauf der aktuellen Sitzung in eine Datei exportieren",
      "Export session to HTML format": "Sitzung in das HTML-Format exportieren",
      "Export session to JSON format": "Sitzung in das JSON-Format exportieren",
      "Export session to JSONL format (one message per line)": "Sitzung in das JSONL-Format exportieren (eine Nachricht pro Zeile)",
      "Export session to markdown format": "Sitzung in das Markdown-Format exportieren",
      // ============================================================================
      // Commands - Insights
      // ============================================================================
      "generate personalized programming insights from your chat history": "Personalisierte Programmier-Einblicke aus Ihrem Chatverlauf generieren",
      // ============================================================================
      // Commands - Session History
      // ============================================================================
      "Resume a previous session": "Eine vorherige Sitzung fortsetzen",
      "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested": "Einen Tool-Aufruf wiederherstellen. Dadurch werden Konversations- und Dateiverlauf auf den Zustand zur\xFCckgesetzt, in dem der Tool-Aufruf vorgeschlagen wurde",
      "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",
      "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}}"',
      "Open auto-memory folder": "Auto-Speicher-Ordner \xF6ffnen",
      "Auto-memory: {{status}}": "Auto-Speicher: {{status}}",
      "Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream to run": "Auto-Konsolidierung: {{status}} \xB7 {{lastDream}} \xB7 /dream zum Ausf\xFChren",
      never: "nie",
      on: "ein",
      off: "aus",
      "\u2746 dreaming": "\u2746 konsolidiert",
      "Remove matching entries from managed auto-memory.": "Passende Eintr\xE4ge aus dem verwalteten Auto-Speicher entfernen.",
      "Usage: /forget <memory text to remove>": "Verwendung: /forget <zu entfernender Erinnerungstext>",
      "No managed auto-memory entries matched: {{query}}": "Keine verwalteten Auto-Speicher-Eintr\xE4ge gefunden: {{query}}",
      "Show managed auto-memory status.": "Status des verwalteten Auto-Speichers anzeigen.",
      "Run managed auto-memory extraction for the current session.": "Verwaltete Auto-Speicher-Extraktion f\xFCr die aktuelle Sitzung ausf\xFChren.",
      "Managed auto-memory root: {{root}}": "Verwalteter Auto-Speicher-Stamm: {{root}}",
      "Managed auto-memory topics:": "Verwaltete Auto-Speicher-Themen:",
      "No extraction cursor found yet.": "Noch kein Extraktions-Cursor gefunden.",
      "Cursor: session={{sessionId}}, offset={{offset}}, updated={{updatedAt}}": "Cursor: Sitzung={{sessionId}}, Offset={{offset}}, Aktualisiert={{updatedAt}}",
      "No chat client available to extract memory.": "Kein Chat-Client verf\xFCgbar, um Erinnerungen zu extrahieren.",
      "Managed auto-memory extraction is already running.": "Verwaltete Auto-Speicher-Extraktion l\xE4uft bereits.",
      "Managed auto-memory extraction found no new durable memories.": "Verwaltete Auto-Speicher-Extraktion hat keine neuen dauerhaften Erinnerungen gefunden.",
      "Consolidate managed auto-memory topic files.": "Verwaltete Auto-Speicher-Themendateien konsolidieren.",
      "Managed auto-memory dream found nothing to improve.": "Auto-Speicher-Konsolidierung hat nichts zu verbessern gefunden.",
      "Deduplicated entries: {{count}}": "Deduplizierte Eintr\xE4ge: {{count}}",
      "Save a durable memory using the save_memory tool.": "Eine dauerhafte Erinnerung mit dem save_memory-Tool speichern.",
      "Usage: /remember [--global|--project] <text to remember>": "Verwendung: /remember [--global|--project] <zu merkender Text>",
      // ============================================================================
      // 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.",
      "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...",
      "Discovered {{count}} tool(s) from '{{name}}'.": "{{count}} Werkzeug(e) von '{{name}}' entdeckt.",
      "Authentication complete. Returning to server details...": "Authentifizierung abgeschlossen. Zur\xFCck zu den Serverdetails...",
      "Authentication successful.": "Authentifizierung erfolgreich.",
      "If the browser does not open, copy and paste this URL into your browser:": "Falls der Browser sich nicht \xF6ffnet, kopieren Sie diese URL und f\xFCgen Sie sie in Ihren Browser ein:",
      "Make sure to copy the COMPLETE URL - it may wrap across multiple lines.": "\u26A0\uFE0F  Stellen Sie sicher, dass Sie die VOLLST\xC4NDIGE URL kopieren \u2013 sie kann \xFCber mehrere Zeilen gehen.",
      // ============================================================================
      // 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 (--fast for suggestion model)": "Modell f\xFCr diese Sitzung wechseln (--fast f\xFCr Vorschlagsmodell)",
      "Set a lighter model for prompt suggestions and speculative execution": "Leichteres Modell f\xFCr Eingabevorschl\xE4ge und spekulative Ausf\xFChrung festlegen",
      "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",
      Yes: "Ja",
      No: "Nein",
      "No (esc)": "Nein (Esc)",
      "Yes, allow always for this session": "Ja, f\xFCr diese Sitzung immer erlauben",
      // MCP Management Dialog (translations for MCP UI components)
      "Manage MCP servers": "MCP-Server verwalten",
      "Server Detail": "Serverdetails",
      "Disable Server": "Server deaktivieren",
      Tools: "Werkzeuge",
      "Tool Detail": "Werkzeugdetails",
      "MCP Management": "MCP-Verwaltung",
      "Loading...": "L\xE4dt...",
      "Unknown step": "Unbekannter Schritt",
      "Esc to back": "Esc zur\xFCck",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close": "\u2191\u2193 navigieren \xB7 Enter ausw\xE4hlen \xB7 Esc schlie\xDFen",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back": "\u2191\u2193 navigieren \xB7 Enter ausw\xE4hlen \xB7 Esc zur\xFCck",
      "\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back": "\u2191\u2193 navigieren \xB7 Enter best\xE4tigen \xB7 Esc zur\xFCck",
      "User Settings (global)": "Benutzereinstellungen (global)",
      "Workspace Settings (project-specific)": "Arbeitsbereichseinstellungen (projektspezifisch)",
      "Disable server:": "Server deaktivieren:",
      "Select where to add the server to the exclude list:": "W\xE4hlen Sie, wo der Server zur Ausschlussliste hinzugef\xFCgt werden soll:",
      "Press Enter to confirm, Esc to cancel": "Enter zum Best\xE4tigen, Esc zum Abbrechen",
      Disable: "Deaktivieren",
      Enable: "Aktivieren",
      Authenticate: "Authentifizieren",
      "Re-authenticate": "Erneut authentifizieren",
      "Clear Authentication": "Authentifizierung l\xF6schen",
      disabled: "deaktiviert",
      "Server:": "Server:",
      Reconnect: "Neu verbinden",
      "View tools": "Werkzeuge anzeigen",
      "Status:": "Status:",
      "Command:": "Befehl:",
      "Working Directory:": "Arbeitsverzeichnis:",
      "Capabilities:": "F\xE4higkeiten:",
      "No server selected": "Kein Server ausgew\xE4hlt",
      "(disabled)": "(deaktiviert)",
      "Error:": "Fehler:",
      tool: "Werkzeug",
      tools: "Werkzeuge",
      connected: "verbunden",
      connecting: "verbindet",
      disconnected: "getrennt",
      error: "Fehler",
      // MCP Server List
      "User MCPs": "Benutzer-MCPs",
      "Project MCPs": "Projekt-MCPs",
      "Extension MCPs": "Erweiterungs-MCPs",
      server: "Server",
      servers: "Server",
      "Add MCP servers to your settings to get started.": "F\xFCgen Sie MCP-Server zu Ihren Einstellungen hinzu, um zu beginnen.",
      "Run qwen --debug to see error logs": "F\xFChren Sie qwen --debug aus, um Fehlerprotokolle anzuzeigen",
      // MCP OAuth Authentication
      "OAuth Authentication": "OAuth-Authentifizierung",
      "Press Enter to start authentication, Esc to go back": "Dr\xFCcken Sie Enter, um die Authentifizierung zu starten, Esc zum Zur\xFCckgehen",
      "Authenticating... Please complete the login in your browser.": "Authentifizierung l\xE4uft... Bitte schlie\xDFen Sie die Anmeldung in Ihrem Browser ab.",
      "Press Enter or Esc to go back": "Dr\xFCcken Sie Enter oder Esc zum Zur\xFCckgehen",
      // MCP Tool List
      "No tools available for this server.": "Keine Werkzeuge f\xFCr diesen Server verf\xFCgbar.",
      destructive: "destruktiv",
      "read-only": "schreibgesch\xFCtzt",
      "open-world": "offene Welt",
      idempotent: "idempotent",
      "Tools for {{name}}": "Werkzeuge f\xFCr {{name}}",
      "Tools for {{serverName}}": "Werkzeuge f\xFCr {{serverName}}",
      "{{current}}/{{total}}": "{{current}}/{{total}}",
      // MCP Tool Detail
      required: "erforderlich",
      Type: "Typ",
      Enum: "Aufz\xE4hlung",
      Parameters: "Parameter",
      "No tool selected": "Kein Werkzeug ausgew\xE4hlt",
      Annotations: "Anmerkungen",
      Title: "Titel",
      "Read Only": "Schreibgesch\xFCtzt",
      Destructive: "Destruktiv",
      Idempotent: "Idempotent",
      "Open World": "Offene Welt",
      Server: "Server",
      // Invalid tool related translations
      "{{count}} invalid tools": "{{count}} ung\xFCltige Werkzeuge",
      invalid: "ung\xFCltig",
      "invalid: {{reason}}": "ung\xFCltig: {{reason}}",
      "missing name": "Name fehlt",
      "missing description": "Beschreibung fehlt",
      "(unnamed)": "(unbenannt)",
      "Warning: This tool cannot be called by the LLM": "Warnung: Dieses Werkzeug kann nicht vom LLM aufgerufen werden",
      Reason: "Grund",
      "Tools must have both name and description to be used by the LLM.": "Werkzeuge m\xFCssen sowohl einen Namen als auch eine Beschreibung haben, um vom LLM verwendet zu werden.",
      "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 ...",
      "Always allow in this project": "In diesem Projekt immer erlauben",
      "Always allow {{action}} in this project": "{{action}} in diesem Projekt immer erlauben",
      "Always allow for this user": "F\xFCr diesen Benutzer immer erlauben",
      "Always allow {{action}} for this user": "{{action}} f\xFCr diesen Benutzer immer erlauben",
      "Yes, restore previous mode ({{mode}})": "Ja, vorherigen Modus wiederherstellen ({{mode}})",
      "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",
      "Select Authentication Method": "Authentifizierungsmethode ausw\xE4hlen",
      "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.",
      "Terms of Services and Privacy Notice": "Nutzungsbedingungen und Datenschutzhinweis",
      "Qwen OAuth": "Qwen OAuth",
      "Discontinued \u2014 switch to Coding Plan or API Key": "Eingestellt \u2014 wechseln Sie zu Coding Plan oder API Key",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch provider.": "Das kostenlose Qwen OAuth-Kontingent wurde am 2026-04-15 eingestellt. F\xFChren Sie /auth aus, um den Anbieter zu wechseln.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead.": "Das kostenlose Qwen OAuth-Kontingent wurde am 2026-04-15 eingestellt. Bitte w\xE4hlen Sie Coding Plan oder API Key.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.": "Das kostenlose Qwen OAuth-Angebot wurde am 2026-04-15 eingestellt. Bitte w\xE4hlen Sie ein Modell eines anderen Anbieter oder f\xFChren Sie /auth aus, um zu wechseln.",
      "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n": "\n\u26A0 Das kostenlose Qwen OAuth-Kontingent wurde am 2026-04-15 eingestellt. Bitte w\xE4hlen Sie eine andere Option.\n",
      "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models": "Kostenpflichtig \xB7 Bis zu 6.000 Anfragen/5 Std. \xB7 Alle Alibaba Cloud Coding Plan Modelle",
      "Alibaba Cloud Coding Plan": "Alibaba Cloud Coding Plan",
      "Bring your own API key": "Eigenen API-Schl\xFCssel verwenden",
      "Browser-based authentication with third-party providers (e.g. OpenRouter, ModelScope)": "Browserbasierte Authentifizierung mit externen Anbietern (z. B. OpenRouter, ModelScope)",
      "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.",
      "Note: Your existing API key will not be cleared when using Qwen OAuth.": "Hinweis: Ihr bestehender API-Schl\xFCssel wird bei Verwendung von Qwen OAuth nicht gel\xF6scht.",
      "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)",
      Modality: "Modalit\xE4t",
      "Context Window": "Kontextfenster",
      text: "Text",
      "text-only": "nur Text",
      image: "Bild",
      pdf: "PDF",
      audio: "Audio",
      video: "Video",
      "not set": "nicht gesetzt",
      none: "keine",
      unknown: "unbekannt",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "Modell konnte nicht auf '{{modelId}}' umgestellt werden.\n\n{{error}}",
      "Qwen 3.6 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.6 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",
      "Manage permission rules": "Berechtigungsregeln verwalten",
      Allow: "Erlauben",
      Ask: "Fragen",
      Deny: "Verweigern",
      Workspace: "Arbeitsbereich",
      "Qwen Code won't ask before using allowed tools.": "Qwen Code fragt nicht, bevor erlaubte Tools verwendet werden.",
      "Qwen Code will ask before using these tools.": "Qwen Code fragt, bevor diese Tools verwendet werden.",
      "Qwen Code is not allowed to use denied tools.": "Qwen Code darf verweigerte Tools nicht verwenden.",
      "Manage trusted directories for this workspace.": "Vertrauensw\xFCrdige Verzeichnisse f\xFCr diesen Arbeitsbereich verwalten.",
      "Any use of the {{tool}} tool": "Jede Verwendung des {{tool}}-Tools",
      "{{tool}} commands matching '{{pattern}}'": "{{tool}}-Befehle, die '{{pattern}}' entsprechen",
      "From user settings": "Aus Benutzereinstellungen",
      "From project settings": "Aus Projekteinstellungen",
      "From session": "Aus Sitzung",
      "Project settings (local)": "Projekteinstellungen (lokal)",
      "Saved in .qwen/settings.local.json": "Gespeichert in .qwen/settings.local.json",
      "Project settings": "Projekteinstellungen",
      "Checked in at .qwen/settings.json": "Eingecheckt in .qwen/settings.json",
      "User settings": "Benutzereinstellungen",
      "Saved in at ~/.qwen/settings.json": "Gespeichert in ~/.qwen/settings.json",
      "Add a new rule\u2026": "Neue Regel hinzuf\xFCgen\u2026",
      "Add {{type}} permission rule": "{{type}}-Berechtigungsregel hinzuf\xFCgen",
      "Permission rules are a tool name, optionally followed by a specifier in parentheses.": "Berechtigungsregeln sind ein Toolname, optional gefolgt von einem Bezeichner in Klammern.",
      "e.g.,": "z.B.",
      or: "oder",
      "Enter permission rule\u2026": "Berechtigungsregel eingeben\u2026",
      "Enter to submit \xB7 Esc to cancel": "Enter zum Absenden \xB7 Esc zum Abbrechen",
      "Where should this rule be saved?": "Wo soll diese Regel gespeichert werden?",
      "Enter to confirm \xB7 Esc to cancel": "Enter zum Best\xE4tigen \xB7 Esc zum Abbrechen",
      "Delete {{type}} rule?": "{{type}}-Regel l\xF6schen?",
      "Are you sure you want to delete this permission rule?": "Sind Sie sicher, dass Sie diese Berechtigungsregel l\xF6schen m\xF6chten?",
      "Permissions:": "Berechtigungen:",
      "(\u2190/\u2192 or tab to cycle)": "(\u2190/\u2192 oder Tab zum Wechseln)",
      "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel": "\u2191\u2193 navigieren \xB7 Enter ausw\xE4hlen \xB7 Tippen suchen \xB7 Esc abbrechen",
      "Search\u2026": "Suche\u2026",
      "Use /trust to manage folder trust settings for this workspace.": "Verwenden Sie /trust, um die Ordnervertrauenseinstellungen f\xFCr diesen Arbeitsbereich zu verwalten.",
      // Workspace directory management
      "Add directory\u2026": "Verzeichnis hinzuf\xFCgen\u2026",
      "Add directory to workspace": "Verzeichnis zum Arbeitsbereich hinzuf\xFCgen",
      "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.": "Qwen Code kann Dateien im Arbeitsbereich lesen und Bearbeitungen vornehmen, wenn die automatische Akzeptierung aktiviert ist.",
      "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.": "Qwen Code kann Dateien in diesem Verzeichnis lesen und Bearbeitungen vornehmen, wenn die automatische Akzeptierung aktiviert ist.",
      "Enter the path to the directory:": "Pfad zum Verzeichnis eingeben:",
      "Enter directory path\u2026": "Verzeichnispfad eingeben\u2026",
      "Tab to complete \xB7 Enter to add \xB7 Esc to cancel": "Tab zum Vervollst\xE4ndigen \xB7 Enter zum Hinzuf\xFCgen \xB7 Esc zum Abbrechen",
      "Remove directory?": "Verzeichnis entfernen?",
      "Are you sure you want to remove this directory from the workspace?": "M\xF6chten Sie dieses Verzeichnis wirklich aus dem Arbeitsbereich entfernen?",
      "  (Original working directory)": "  (Urspr\xFCngliches Arbeitsverzeichnis)",
      "  (from settings)": "  (aus Einstellungen)",
      "Directory does not exist.": "Verzeichnis existiert nicht.",
      "Path is not a directory.": "Pfad ist kein Verzeichnis.",
      "This directory is already in the workspace.": "Dieses Verzeichnis ist bereits im Arbeitsbereich.",
      "Already covered by existing directory: {{dir}}": "Bereits durch vorhandenes Verzeichnis abgedeckt: {{dir}}",
      // ============================================================================
      // 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.",
      "Press \u2191 to edit queued messages": "Dr\xFCcken Sie \u2191, um Nachrichten in der Warteschlange zu bearbeiten",
      // ============================================================================
      // 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:",
      "Current tasks": "Aktuelle Aufgaben",
      "... 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.",
      "Press Ctrl+O to toggle compact mode \u2014 hide tool output and thinking for a cleaner view.": "Strg+O dr\xFCcken, um den Kompaktmodus umzuschalten \u2014 Tool-Ausgabe und Denkprozess ausblenden.",
      "Add a QWEN.md file to give Qwen Code persistent project context.": "F\xFCgen Sie eine QWEN.md-Datei hinzu, um Qwen Code dauerhaften Projektkontext zu geben.",
      "Use /btw to ask a quick side question without disrupting the conversation.": "Verwenden Sie /btw, um eine kurze Nebenfrage zu stellen, ohne die Unterhaltung zu unterbrechen.",
      "Context is almost full! Run /compress now or start /new to continue.": "Der Kontext ist fast voll! F\xFChren Sie jetzt /compress aus oder starten Sie /new, um fortzufahren.",
      "Context is getting full. Use /compress to free up space.": "Der Kontext f\xFCllt sich. Verwenden Sie /compress, um Platz freizugeben.",
      "Long conversation? /compress summarizes history to free context.": "Lange Unterhaltung? /compress fasst den Verlauf zusammen, um Kontext freizugeben.",
      // ============================================================================
      // Custom API Key Configuration
      // ============================================================================
      "You can configure your API key and models in settings.json": "Sie k\xF6nnen Ihren API-Schl\xFCssel und Modelle in settings.json konfigurieren",
      "Refer to the documentation for setup instructions": "Einrichtungsanweisungen finden Sie in der Dokumentation",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "API key cannot be empty.": "API-Schl\xFCssel darf nicht leer sein.",
      "You can get your Coding Plan API key here": "Sie k\xF6nnen Ihren Coding-Plan-API-Schl\xFCssel hier erhalten",
      "New model configurations are available for Alibaba Cloud Coding Plan. Update now?": "Neue Modellkonfigurationen sind f\xFCr Alibaba Cloud 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",
      "Paste your api key of ModelStudio Coding Plan and you're all set!": "F\xFCgen Sie Ihren ModelStudio Coding Plan 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:",
      "Select Region for Coding Plan": "Region f\xFCr Coding Plan ausw\xE4hlen",
      "Choose based on where your account is registered": "W\xE4hlen Sie basierend auf dem Registrierungsort Ihres Kontos",
      "Enter Coding Plan API Key": "Coding-Plan-API-Schl\xFCssel eingeben",
      // ============================================================================
      // Coding Plan International Updates
      // ============================================================================
      "New model configurations are available for {{region}}. Update now?": "Neue Modellkonfigurationen sind f\xFCr {{region}} 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).",
      // ============================================================================
      // Context Usage Component
      // ============================================================================
      "Context Usage": "Kontextnutzung",
      "% used": "% verwendet",
      "% context used": "% Kontext verwendet",
      "Context exceeds limit! Use /compress or /clear to reduce.": "Kontext \xFCberschreitet Limit! Verwenden Sie /compress oder /clear zum Reduzieren.",
      "Use /compress or /clear": "Verwenden Sie /compress oder /clear",
      "No API response yet. Send a message to see actual usage.": "Noch keine API-Antwort. Senden Sie eine Nachricht, um die tats\xE4chliche Nutzung anzuzeigen.",
      "Estimated pre-conversation overhead": "Gesch\xE4tzte Vorabkosten vor der Unterhaltung",
      "Context window": "Kontextfenster",
      tokens: "Tokens",
      Used: "Verwendet",
      Free: "Frei",
      "Autocompact buffer": "Autokomprimierungs-Puffer",
      "Usage by category": "Verwendung nach Kategorie",
      "System prompt": "System-Prompt",
      "Built-in tools": "Integrierte Tools",
      "MCP tools": "MCP-Tools",
      "Memory files": "Speicherdateien",
      Skills: "F\xE4higkeiten",
      Messages: "Nachrichten",
      "Show context window usage breakdown.": "Zeigt die Aufschl\xFCsselung der Kontextfenster-Nutzung an.",
      "Run /context detail for per-item breakdown.": "F\xFChren Sie /context detail f\xFCr eine Aufschl\xFCsselung nach Elementen aus.",
      active: "aktiv",
      "body loaded": "Inhalt geladen",
      memory: "Speicher",
      "{{region}} configuration updated successfully.": "{{region}}-Konfiguration erfolgreich aktualisiert.",
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json.": "Erfolgreich mit {{region}} authentifiziert. API-Schl\xFCssel und Modellkonfigurationen wurden in settings.json gespeichert.",
      "Tip: Use /model to switch between available Coding Plan models.": "Tipp: Verwenden Sie /model, um zwischen verf\xFCgbaren Coding Plan-Modellen zu wechseln.",
      // ============================================================================
      // Ask User Question Tool
      // ============================================================================
      "Please answer the following question(s):": "Bitte beantworten Sie die folgende(n) Frage(n):",
      "Cannot ask user questions in non-interactive mode. Please run in interactive mode to use this tool.": "Benutzerfragen k\xF6nnen im nicht-interaktiven Modus nicht gestellt werden. Bitte f\xFChren Sie das Tool im interaktiven Modus aus.",
      "User declined to answer the questions.": "Benutzer hat die Beantwortung der Fragen abgelehnt.",
      "User has provided the following answers:": "Benutzer hat die folgenden Antworten bereitgestellt:",
      "Failed to process user answers:": "Fehler beim Verarbeiten der Benutzerantworten:",
      "Type something...": "Etwas eingeben...",
      Submit: "Senden",
      "Submit answers": "Antworten senden",
      Cancel: "Abbrechen",
      "Your answers:": "Ihre Antworten:",
      "(not answered)": "(nicht beantwortet)",
      "Ready to submit your answers?": "Bereit, Ihre Antworten zu senden?",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select": "\u2191/\u2193: Navigieren | \u2190/\u2192: Tabs wechseln | Enter: Ausw\xE4hlen",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: Navigieren | \u2190/\u2192: Tabs wechseln | Space/Enter: Umschalten | Esc: Abbrechen",
      "\u2191/\u2193: Navigate | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: Navigieren | Space/Enter: Umschalten | Esc: Abbrechen",
      "\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel": "\u2191/\u2193: Navigieren | Enter: Ausw\xE4hlen | Esc: Abbrechen",
      // ============================================================================
      // Commands - Auth
      // ============================================================================
      "Configure Qwen authentication information with Qwen-OAuth or Alibaba Cloud Coding Plan": "Qwen-Authentifizierung mit Qwen-OAuth oder Alibaba Cloud Coding Plan konfigurieren",
      "Authenticate using Qwen OAuth": "Mit Qwen OAuth authentifizieren",
      "Authenticate using Alibaba Cloud Coding Plan": "Mit Alibaba Cloud Coding Plan authentifizieren",
      "Region for Coding Plan (china/global)": "Region f\xFCr Coding Plan (china/global)",
      "API key for Coding Plan": "API-Schl\xFCssel f\xFCr Coding Plan",
      "Show current authentication status": "Aktuellen Authentifizierungsstatus anzeigen",
      "Authentication completed successfully.": "Authentifizierung erfolgreich abgeschlossen.",
      "Starting Qwen OAuth authentication...": "Qwen OAuth-Authentifizierung wird gestartet...",
      "Successfully authenticated with Qwen OAuth.": "Erfolgreich mit Qwen OAuth authentifiziert.",
      "Failed to authenticate with Qwen OAuth: {{error}}": "Authentifizierung mit Qwen OAuth fehlgeschlagen: {{error}}",
      "Processing Alibaba Cloud Coding Plan authentication...": "Alibaba Cloud Coding Plan-Authentifizierung wird verarbeitet...",
      "Successfully authenticated with Alibaba Cloud Coding Plan.": "Erfolgreich mit Alibaba Cloud Coding Plan authentifiziert.",
      "Failed to authenticate with Coding Plan: {{error}}": "Authentifizierung mit Coding Plan fehlgeschlagen: {{error}}",
      "\u4E2D\u56FD (China)": "\u4E2D\u56FD (China)",
      "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)": "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)",
      Global: "Global",
      "Alibaba Cloud (alibabacloud.com)": "Alibaba Cloud (alibabacloud.com)",
      "Select region for Coding Plan:": "Region f\xFCr Coding Plan ausw\xE4hlen:",
      "Enter your Coding Plan API key: ": "Geben Sie Ihren Coding Plan API-Schl\xFCssel ein: ",
      "Select authentication method:": "Authentifizierungsmethode ausw\xE4hlen:",
      "\n=== Authentication Status ===\n": "\n=== Authentifizierungsstatus ===\n",
      "\u26A0\uFE0F  No authentication method configured.\n": "\u26A0\uFE0F  Keine Authentifizierungsmethode konfiguriert.\n",
      "Run one of the following commands to get started:\n": "F\xFChren Sie einen der folgenden Befehle aus, um zu beginnen:\n",
      "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)": "  qwen auth qwen-oauth     - Mit Qwen OAuth authentifizieren (eingestellt)",
      "  qwen auth coding-plan      - Authenticate with Alibaba Cloud Coding Plan\n": "  qwen auth coding-plan      - Mit Alibaba Cloud Coding Plan authentifizieren\n",
      "Or simply run:": "Oder einfach ausf\xFChren:",
      "  qwen auth                - Interactive authentication setup\n": "  qwen auth                - Interaktive Authentifizierungseinrichtung\n",
      "\u2713 Authentication Method: Qwen OAuth": "\u2713 Authentifizierungsmethode: Qwen OAuth",
      "  Type: Free tier (discontinued 2026-04-15)": "  Typ: Kostenloses Kontingent (eingestellt 2026-04-15)",
      "  Limit: No longer available": "  Limit: Nicht mehr verf\xFCgbar",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.": "Das kostenlose Qwen OAuth-Kontingent wurde am 2026-04-15 eingestellt. F\xFChren Sie /auth aus, um zu Coding Plan, OpenRouter, Fireworks AI oder einem anderen Anbieter zu wechseln.",
      "  Models: Qwen latest models\n": "  Modelle: Qwen neueste Modelle\n",
      "\u2713 Authentication Method: Alibaba Cloud Coding Plan": "\u2713 Authentifizierungsmethode: Alibaba Cloud Coding Plan",
      "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC": "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC",
      "Global - Alibaba Cloud": "Global - Alibaba Cloud",
      "  Region: {{region}}": "  Region: {{region}}",
      "  Current Model: {{model}}": "  Aktuelles Modell: {{model}}",
      "  Config Version: {{version}}": "  Konfigurationsversion: {{version}}",
      "  Status: API key configured\n": "  Status: API-Schl\xFCssel konfiguriert\n",
      "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)": "\u26A0\uFE0F  Authentifizierungsmethode: Alibaba Cloud Coding Plan (Unvollst\xE4ndig)",
      "  Issue: API key not found in environment or settings\n": "  Problem: API-Schl\xFCssel nicht in Umgebung oder Einstellungen gefunden\n",
      "  Run `qwen auth coding-plan` to re-configure.\n": "  F\xFChren Sie `qwen auth coding-plan` aus, um neu zu konfigurieren.\n",
      "\u2713 Authentication Method: {{type}}": "\u2713 Authentifizierungsmethode: {{type}}",
      "  Status: Configured\n": "  Status: Konfiguriert\n",
      "Failed to check authentication status: {{error}}": "Authentifizierungsstatus konnte nicht \xFCberpr\xFCft werden: {{error}}",
      "Select an option:": "Option ausw\xE4hlen:",
      "Raw mode not available. Please run in an interactive terminal.": "Raw-Modus nicht verf\xFCgbar. Bitte in einem interaktiven Terminal ausf\xFChren.",
      "(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n": "(\u2191 \u2193 Pfeiltasten zum Navigieren, Enter zum Ausw\xE4hlen, Strg+C zum Beenden)\n",
      compact: "kompakt",
      "compact mode: on (Ctrl+O off)": "Kompaktmodus: ein (Strg+O aus)",
      "to toggle compact mode": "Kompaktmodus umschalten",
      "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).": "Tool-Ausgabe und Denkprozess ausblenden f\xFCr eine \xFCbersichtlichere Ansicht (mit Strg+O umschalten).",
      "Press Ctrl+O to show full tool output": "Strg+O f\xFCr vollst\xE4ndige Tool-Ausgabe dr\xFCcken",
      "Switch to plan mode or exit plan mode": "Switch to plan mode or exit plan mode",
      "Exited plan mode. Previous approval mode restored.": "Exited plan mode. Previous approval mode restored.",
      "Enabled plan mode. The agent will analyze and plan without executing tools.": "Enabled plan mode. The agent will analyze and plan without executing tools.",
      'Already in plan mode. Use "/plan exit" to exit plan mode.': 'Already in plan mode. Use "/plan exit" to exit plan mode.',
      'Not in plan mode. Use "/plan" to enter plan mode first.': 'Not in plan mode. Use "/plan" to enter plan mode first.',
      "Set up Qwen Code's status line UI": "Set up Qwen Code's status line UI"
    };
  }
});

// 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",
      "to toggle compact mode": "to toggle compact mode",
      "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",
      "Fast Model": "Fast 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]",
      "List available skills.": "List available skills.",
      "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",
      "Enter to submit, Esc to go back": "Enter to submit, 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}}",
      // ============================================================================
      // Extensions - Management Dialog
      // ============================================================================
      "Manage Extensions": "Manage Extensions",
      "Extension Details": "Extension Details",
      "View Extension": "View Extension",
      "Update Extension": "Update Extension",
      "Disable Extension": "Disable Extension",
      "Enable Extension": "Enable Extension",
      "Uninstall Extension": "Uninstall Extension",
      "Select Scope": "Select Scope",
      "User Scope": "User Scope",
      "Workspace Scope": "Workspace Scope",
      "No extensions found.": "No extensions found.",
      Active: "Active",
      Disabled: "Disabled",
      "Update available": "Update available",
      "Up to date": "Up to date",
      "Checking...": "Checking...",
      "Updating...": "Updating...",
      Unknown: "Unknown",
      Error: "Error",
      "Version:": "Version:",
      "Status:": "Status:",
      'Are you sure you want to uninstall extension "{{name}}"?': 'Are you sure you want to uninstall extension "{{name}}"?',
      "This action cannot be undone.": "This action cannot be undone.",
      'Extension "{{name}}" disabled successfully.': 'Extension "{{name}}" disabled successfully.',
      'Extension "{{name}}" enabled successfully.': 'Extension "{{name}}" enabled successfully.',
      'Extension "{{name}}" updated successfully.': 'Extension "{{name}}" updated successfully.',
      'Failed to update extension "{{name}}": {{error}}': 'Failed to update extension "{{name}}": {{error}}',
      "Select the scope for this action:": "Select the scope for this action:",
      "User - Applies to all projects": "User - Applies to all projects",
      "Workspace - Applies to current project only": "Workspace - Applies to current project only",
      // Extension dialog - missing keys
      "Name:": "Name:",
      "MCP Servers:": "MCP Servers:",
      "Settings:": "Settings:",
      active: "active",
      disabled: "disabled",
      "View Details": "View Details",
      "Update failed:": "Update failed:",
      "Updating {{name}}...": "Updating {{name}}...",
      "Update complete!": "Update complete!",
      "User (global)": "User (global)",
      "Workspace (project-specific)": "Workspace (project-specific)",
      'Disable "{{name}}" - Select Scope': 'Disable "{{name}}" - Select Scope',
      'Enable "{{name}}" - Select Scope': 'Enable "{{name}}" - Select Scope',
      "No extension selected": "No extension selected",
      "Press Y/Enter to confirm, N/Esc to cancel": "Press Y/Enter to confirm, N/Esc to cancel",
      "Y/Enter to confirm, N/Esc to cancel": "Y/Enter to confirm, N/Esc to cancel",
      "{{count}} extensions installed": "{{count}} extensions installed",
      "Use '/extensions install' to install your first extension.": "Use '/extensions install' to install your first extension.",
      // Update status values
      "up to date": "up to date",
      "update available": "update available",
      "checking...": "checking...",
      "not updatable": "not updatable",
      error: "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)",
      "Auto (detect terminal theme)": "Auto (detect terminal theme)",
      Auto: "Auto",
      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",
      "Open MCP management dialog, or authenticate with OAuth-enabled servers": "Open MCP management dialog, or authenticate with OAuth-enabled servers",
      "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",
      "Manage installed extensions": "Manage installed 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.",
      "The name of the extension to update.": "The name of the extension to update.",
      "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).",
      // ============================================================================
      // Commands - Hooks
      // ============================================================================
      "Manage Qwen Code hooks": "Manage Qwen Code hooks",
      "List all configured hooks": "List all configured hooks",
      "Enable a disabled hook": "Enable a disabled hook",
      "Disable an active hook": "Disable an active hook",
      // Hooks - Dialog
      Hooks: "Hooks",
      "Loading hooks...": "Loading hooks...",
      "Error loading hooks:": "Error loading hooks:",
      "Press Escape to close": "Press Escape to close",
      "Press Escape, Ctrl+C, or Ctrl+D to cancel": "Press Escape, Ctrl+C, or Ctrl+D to cancel",
      "Press Space, Enter, or Escape to dismiss": "Press Space, Enter, or Escape to dismiss",
      "No hook selected": "No hook selected",
      // Hooks - List Step
      "No hook events found.": "No hook events found.",
      "{{count}} hook configured": "{{count}} hook configured",
      "{{count}} hooks configured": "{{count}} hooks configured",
      "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.": "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.",
      "Enter to select \xB7 Esc to cancel": "Enter to select \xB7 Esc to cancel",
      // Hooks - Detail Step
      "Exit codes:": "Exit codes:",
      "Configured hooks:": "Configured hooks:",
      "No hooks configured for this event.": "No hooks configured for this event.",
      "To add hooks, edit settings.json directly or ask Qwen.": "To add hooks, edit settings.json directly or ask Qwen.",
      "Enter to select \xB7 Esc to go back": "Enter to select \xB7 Esc to go back",
      // Hooks - Config Detail Step
      "Hook details": "Hook details",
      "Event:": "Event:",
      "Extension:": "Extension:",
      "Desc:": "Desc:",
      "No hook config selected": "No hook config selected",
      "To modify or remove this hook, edit settings.json directly or ask Qwen to help.": "To modify or remove this hook, edit settings.json directly or ask Qwen to help.",
      // Hooks - Disabled Step
      "Hook Configuration - Disabled": "Hook Configuration - Disabled",
      "All hooks are currently disabled. You have {{count}} that are not running.": "All hooks are currently disabled. You have {{count}} that are not running.",
      "{{count}} configured hook": "{{count}} configured hook",
      "{{count}} configured hooks": "{{count}} configured hooks",
      "When hooks are disabled:": "When hooks are disabled:",
      "No hook commands will execute": "No hook commands will execute",
      "StatusLine will not be displayed": "StatusLine will not be displayed",
      "Tool operations will proceed without hook validation": "Tool operations will proceed without hook validation",
      'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.': 'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.',
      // Hooks - Source
      Project: "Project",
      User: "User",
      System: "System",
      Extension: "Extension",
      "Local Settings": "Local Settings",
      "User Settings": "User Settings",
      "System Settings": "System Settings",
      Extensions: "Extensions",
      "Session (temporary)": "Session (temporary)",
      // Hooks - Status
      "\u2713 Enabled": "\u2713 Enabled",
      "\u2717 Disabled": "\u2717 Disabled",
      // Hooks - Event Descriptions (short)
      "Before tool execution": "Before tool execution",
      "After tool execution": "After tool execution",
      "After tool execution fails": "After tool execution fails",
      "When notifications are sent": "When notifications are sent",
      "When the user submits a prompt": "When the user submits a prompt",
      "When a new session is started": "When a new session is started",
      "Right before Qwen Code concludes its response": "Right before Qwen Code concludes its response",
      "When a subagent (Agent tool call) is started": "When a subagent (Agent tool call) is started",
      "Right before a subagent concludes its response": "Right before a subagent concludes its response",
      "Before conversation compaction": "Before conversation compaction",
      "When a session is ending": "When a session is ending",
      "When a permission dialog is displayed": "When a permission dialog is displayed",
      // Hooks - Event Descriptions (detailed)
      "Input to command is JSON of tool call arguments.": "Input to command is JSON of tool call arguments.",
      'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': 'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).',
      "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.": "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.",
      "Input to command is JSON with notification message and type.": "Input to command is JSON with notification message and type.",
      "Input to command is JSON with original user prompt text.": "Input to command is JSON with original user prompt text.",
      "Input to command is JSON with session start source.": "Input to command is JSON with session start source.",
      "Input to command is JSON with session end reason.": "Input to command is JSON with session end reason.",
      "Input to command is JSON with agent_id and agent_type.": "Input to command is JSON with agent_id and agent_type.",
      "Input to command is JSON with agent_id, agent_type, and agent_transcript_path.": "Input to command is JSON with agent_id, agent_type, and agent_transcript_path.",
      "Input to command is JSON with compaction details.": "Input to command is JSON with compaction details.",
      "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.": "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.",
      // Hooks - Exit Code Descriptions
      "stdout/stderr not shown": "stdout/stderr not shown",
      "show stderr to model and continue conversation": "show stderr to model and continue conversation",
      "show stderr to user only": "show stderr to user only",
      "stdout shown in transcript mode (ctrl+o)": "stdout shown in transcript mode (ctrl+o)",
      "show stderr to model immediately": "show stderr to model immediately",
      "show stderr to user only but continue with tool call": "show stderr to user only but continue with tool call",
      "block processing, erase original prompt, and show stderr to user only": "block processing, erase original prompt, and show stderr to user only",
      "stdout shown to Qwen": "stdout shown to Qwen",
      "show stderr to user only (blocking errors ignored)": "show stderr to user only (blocking errors ignored)",
      "command completes successfully": "command completes successfully",
      "stdout shown to subagent": "stdout shown to subagent",
      "show stderr to subagent and continue having it run": "show stderr to subagent and continue having it run",
      "stdout appended as custom compact instructions": "stdout appended as custom compact instructions",
      "block compaction": "block compaction",
      "show stderr to user only but continue with compaction": "show stderr to user only but continue with compaction",
      "use hook decision if provided": "use hook decision if provided",
      // Hooks - Messages
      "Config not loaded.": "Config not loaded.",
      "Hooks are not enabled. Enable hooks in settings to use this feature.": "Hooks are not enabled. Enable hooks in settings to use this feature.",
      "No hooks configured. Add hooks in your settings.json file.": "No hooks configured. Add hooks in your settings.json file.",
      "Configured Hooks ({{count}} total)": "Configured Hooks ({{count}} total)",
      // ============================================================================
      // Commands - Session Export
      // ============================================================================
      "Export current session message history to a file": "Export current session message history to a file",
      "Export session to HTML format": "Export session to HTML format",
      "Export session to JSON format": "Export session to JSON format",
      "Export session to JSONL format (one message per line)": "Export session to JSONL format (one message per line)",
      "Export session to markdown format": "Export session to markdown format",
      // ============================================================================
      // Commands - Insights
      // ============================================================================
      "generate personalized programming insights from your chat history": "generate personalized programming insights from your chat history",
      // ============================================================================
      // Commands - Session History
      // ============================================================================
      "Resume a previous session": "Resume a previous session",
      "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested": "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested",
      "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",
      "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}}"',
      "Open auto-memory folder": "Open auto-memory folder",
      "Auto-memory: {{status}}": "Auto-memory: {{status}}",
      "Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream to run": "Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream to run",
      never: "never",
      on: "on",
      off: "off",
      "\u2726 dreaming": "\u2726 dreaming",
      "Remove matching entries from managed auto-memory.": "Remove matching entries from managed auto-memory.",
      "Usage: /forget <memory text to remove>": "Usage: /forget <memory text to remove>",
      "No managed auto-memory entries matched: {{query}}": "No managed auto-memory entries matched: {{query}}",
      "Show managed auto-memory status.": "Show managed auto-memory status.",
      "Run managed auto-memory extraction for the current session.": "Run managed auto-memory extraction for the current session.",
      "Managed auto-memory root: {{root}}": "Managed auto-memory root: {{root}}",
      "Managed auto-memory topics:": "Managed auto-memory topics:",
      "No extraction cursor found yet.": "No extraction cursor found yet.",
      "Cursor: session={{sessionId}}, offset={{offset}}, updated={{updatedAt}}": "Cursor: session={{sessionId}}, offset={{offset}}, updated={{updatedAt}}",
      "No chat client available to extract memory.": "No chat client available to extract memory.",
      "Managed auto-memory extraction is already running.": "Managed auto-memory extraction is already running.",
      "Managed auto-memory extraction found no new durable memories.": "Managed auto-memory extraction found no new durable memories.",
      "Consolidate managed auto-memory topic files.": "Consolidate managed auto-memory topic files.",
      "Managed auto-memory dream found nothing to improve.": "Managed auto-memory dream found nothing to improve.",
      "Deduplicated entries: {{count}}": "Deduplicated entries: {{count}}",
      "Save a durable memory using the save_memory tool.": "Save a durable memory using the save_memory tool.",
      "Usage: /remember [--global|--project] <text to remember>": "Usage: /remember [--global|--project] <text to remember>",
      // ============================================================================
      // 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.",
      "Open MCP management dialog": "Open MCP management dialog",
      "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}}'...",
      "Discovered {{count}} tool(s) from '{{name}}'.": "Discovered {{count}} tool(s) from '{{name}}'.",
      "Authentication complete. Returning to server details...": "Authentication complete. Returning to server details...",
      "Authentication successful.": "Authentication successful.",
      "If the browser does not open, copy and paste this URL into your browser:": "If the browser does not open, copy and paste this URL into your browser:",
      "Make sure to copy the COMPLETE URL - it may wrap across multiple lines.": "Make sure to copy the COMPLETE URL - it may wrap across multiple lines.",
      // ============================================================================
      // MCP Management Dialog
      // ============================================================================
      "Manage MCP servers": "Manage MCP servers",
      "Server Detail": "Server Detail",
      "Disable Server": "Disable Server",
      Tools: "Tools",
      "Tool Detail": "Tool Detail",
      "MCP Management": "MCP Management",
      "Loading...": "Loading...",
      "Unknown step": "Unknown step",
      "Esc to back": "Esc to back",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close": "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back": "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back",
      "\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back": "\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back",
      "User Settings (global)": "User Settings (global)",
      "Workspace Settings (project-specific)": "Workspace Settings (project-specific)",
      "Disable server:": "Disable server:",
      "Select where to add the server to the exclude list:": "Select where to add the server to the exclude list:",
      "Press Enter to confirm, Esc to cancel": "Press Enter to confirm, Esc to cancel",
      "View tools": "View tools",
      Reconnect: "Reconnect",
      Enable: "Enable",
      Disable: "Disable",
      Authenticate: "Authenticate",
      "Re-authenticate": "Re-authenticate",
      "Clear Authentication": "Clear Authentication",
      "Server:": "Server:",
      "Command:": "Command:",
      "Working Directory:": "Working Directory:",
      "Capabilities:": "Capabilities:",
      "No server selected": "No server selected",
      prompts: "prompts",
      "(disabled)": "(disabled)",
      "Error:": "Error:",
      tool: "tool",
      tools: "tools",
      connected: "connected",
      connecting: "connecting",
      disconnected: "disconnected",
      // MCP Server List
      "User MCPs": "User MCPs",
      "Project MCPs": "Project MCPs",
      "Extension MCPs": "Extension MCPs",
      server: "server",
      servers: "servers",
      "Add MCP servers to your settings to get started.": "Add MCP servers to your settings to get started.",
      "Run qwen --debug to see error logs": "Run qwen --debug to see error logs",
      // MCP OAuth Authentication
      "OAuth Authentication": "OAuth Authentication",
      "Press Enter to start authentication, Esc to go back": "Press Enter to start authentication, Esc to go back",
      "Authenticating... Please complete the login in your browser.": "Authenticating... Please complete the login in your browser.",
      "Press c to copy the authorization URL to your clipboard.": "Press c to copy the authorization URL to your clipboard.",
      "Copy request sent to your terminal. If paste is empty, copy the URL above manually.": "Copy request sent to your terminal. If paste is empty, copy the URL above manually.",
      "Cannot write to terminal \u2014 copy the URL above manually.": "Cannot write to terminal \u2014 copy the URL above manually.",
      "Press Enter or Esc to go back": "Press Enter or Esc to go back",
      // MCP Tool List
      "No tools available for this server.": "No tools available for this server.",
      destructive: "destructive",
      "read-only": "read-only",
      "open-world": "open-world",
      idempotent: "idempotent",
      "Tools for {{name}}": "Tools for {{name}}",
      "Tools for {{serverName}}": "Tools for {{serverName}}",
      "{{current}}/{{total}}": "{{current}}/{{total}}",
      // MCP Tool Detail
      required: "required",
      Type: "Type",
      Enum: "Enum",
      Parameters: "Parameters",
      "No tool selected": "No tool selected",
      Annotations: "Annotations",
      Title: "Title",
      "Read Only": "Read Only",
      Destructive: "Destructive",
      Idempotent: "Idempotent",
      "Open World": "Open World",
      Server: "Server",
      // Invalid tool related translations
      "{{count}} invalid tools": "{{count}} invalid tools",
      invalid: "invalid",
      "invalid: {{reason}}": "invalid: {{reason}}",
      "missing name": "missing name",
      "missing description": "missing description",
      "(unnamed)": "(unnamed)",
      "Warning: This tool cannot be called by the LLM": "Warning: This tool cannot be called by the LLM",
      Reason: "Reason",
      "Tools must have both name and description to be used by the LLM.": "Tools must have both name and description to be used by the LLM.",
      // ============================================================================
      // 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 (--fast for suggestion model)": "Switch the model for this session (--fast for suggestion model)",
      "Set a lighter model for prompt suggestions and speculative execution": "Set a lighter model for prompt suggestions and speculative execution",
      "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",
      Yes: "Yes",
      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 ...",
      "Always allow in this project": "Always allow in this project",
      "Always allow {{action}} in this project": "Always allow {{action}} in this project",
      "Always allow for this user": "Always allow for this user",
      "Always allow {{action}} for this user": "Always allow {{action}} for this user",
      "Yes, restore previous mode ({{mode}})": "Yes, restore previous mode ({{mode}})",
      "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",
      "Select Authentication Method": "Select Authentication Method",
      "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.",
      "Terms of Services and Privacy Notice": "Terms of Services and Privacy Notice",
      "Qwen OAuth": "Qwen OAuth",
      "Discontinued \u2014 switch to Coding Plan or API Key": "Discontinued \u2014 switch to Coding Plan or API Key",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch provider.": "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch provider.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead.": "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.": "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.",
      "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n": "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n",
      "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models": "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models",
      "Alibaba Cloud Coding Plan": "Alibaba Cloud Coding Plan",
      "Bring your own API key": "Bring your own API key",
      "Browser-based authentication with third-party providers (e.g. OpenRouter, ModelScope)": "Browser-based authentication with third-party providers (e.g. OpenRouter, ModelScope)",
      "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.",
      "Note: Your existing API key will not be cleared when using Qwen OAuth.": "Note: Your existing API key will not be cleared when using Qwen OAuth.",
      "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)",
      Modality: "Modality",
      "Context Window": "Context Window",
      text: "text",
      "text-only": "text-only",
      image: "image",
      pdf: "pdf",
      audio: "audio",
      video: "video",
      "not set": "not set",
      none: "none",
      unknown: "unknown",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "Failed to switch model to '{{modelId}}'.\n\n{{error}}",
      "Qwen 3.6 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.6 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",
      "Manage permission rules": "Manage permission rules",
      Allow: "Allow",
      Ask: "Ask",
      Deny: "Deny",
      Workspace: "Workspace",
      "Qwen Code won't ask before using allowed tools.": "Qwen Code won't ask before using allowed tools.",
      "Qwen Code will ask before using these tools.": "Qwen Code will ask before using these tools.",
      "Qwen Code is not allowed to use denied tools.": "Qwen Code is not allowed to use denied tools.",
      "Manage trusted directories for this workspace.": "Manage trusted directories for this workspace.",
      "Any use of the {{tool}} tool": "Any use of the {{tool}} tool",
      "{{tool}} commands matching '{{pattern}}'": "{{tool}} commands matching '{{pattern}}'",
      "From user settings": "From user settings",
      "From project settings": "From project settings",
      "From session": "From session",
      "Project settings (local)": "Project settings (local)",
      "Saved in .qwen/settings.local.json": "Saved in .qwen/settings.local.json",
      "Project settings": "Project settings",
      "Checked in at .qwen/settings.json": "Checked in at .qwen/settings.json",
      "User settings": "User settings",
      "Saved in at ~/.qwen/settings.json": "Saved in at ~/.qwen/settings.json",
      "Add a new rule\u2026": "Add a new rule\u2026",
      "Add {{type}} permission rule": "Add {{type}} permission rule",
      "Permission rules are a tool name, optionally followed by a specifier in parentheses.": "Permission rules are a tool name, optionally followed by a specifier in parentheses.",
      "e.g.,": "e.g.,",
      or: "or",
      "Enter permission rule\u2026": "Enter permission rule\u2026",
      "Enter to submit \xB7 Esc to cancel": "Enter to submit \xB7 Esc to cancel",
      "Where should this rule be saved?": "Where should this rule be saved?",
      "Enter to confirm \xB7 Esc to cancel": "Enter to confirm \xB7 Esc to cancel",
      "Delete {{type}} rule?": "Delete {{type}} rule?",
      "Are you sure you want to delete this permission rule?": "Are you sure you want to delete this permission rule?",
      "Permissions:": "Permissions:",
      "(\u2190/\u2192 or tab to cycle)": "(\u2190/\u2192 or tab to cycle)",
      "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel": "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel",
      "Search\u2026": "Search\u2026",
      "Use /trust to manage folder trust settings for this workspace.": "Use /trust to manage folder trust settings for this workspace.",
      // Workspace directory management
      "Add directory\u2026": "Add directory\u2026",
      "Add directory to workspace": "Add directory to workspace",
      "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.": "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.",
      "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.": "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.",
      "Enter the path to the directory:": "Enter the path to the directory:",
      "Enter directory path\u2026": "Enter directory path\u2026",
      "Tab to complete \xB7 Enter to add \xB7 Esc to cancel": "Tab to complete \xB7 Enter to add \xB7 Esc to cancel",
      "Remove directory?": "Remove directory?",
      "Are you sure you want to remove this directory from the workspace?": "Are you sure you want to remove this directory from the workspace?",
      "  (Original working directory)": "  (Original working directory)",
      "  (from settings)": "  (from settings)",
      "Directory does not exist.": "Directory does not exist.",
      "Path is not a directory.": "Path is not a directory.",
      "This directory is already in the workspace.": "This directory is already in the workspace.",
      "Already covered by existing directory: {{dir}}": "Already covered by existing directory: {{dir}}",
      // ============================================================================
      // 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.",
      "Press \u2191 to edit queued messages": "Press \u2191 to edit queued messages",
      // ============================================================================
      // 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.",
      "Press Ctrl+O to toggle compact mode \u2014 hide tool output and thinking for a cleaner view.": "Press Ctrl+O to toggle compact mode \u2014 hide tool output and thinking for a cleaner view.",
      "Add a QWEN.md file to give Qwen Code persistent project context.": "Add a QWEN.md file to give Qwen Code persistent project context.",
      "Use /btw to ask a quick side question without disrupting the conversation.": "Use /btw to ask a quick side question without disrupting the conversation.",
      "Context is almost full! Run /compress now or start /new to continue.": "Context is almost full! Run /compress now or start /new to continue.",
      "Context is getting full. Use /compress to free up space.": "Context is getting full. Use /compress to free up space.",
      "Long conversation? /compress summarizes history to free context.": "Long conversation? /compress summarizes history to free context.",
      // ============================================================================
      // 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:",
      "Current tasks": "Current tasks",
      "... 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}})",
      "Press Ctrl+Y to retry": "Press Ctrl+Y to retry",
      "No failed request to retry.": "No failed request to retry.",
      "to retry last request": "to retry last request",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "API key cannot be empty.": "API key cannot be empty.",
      'Invalid API key. Coding Plan API keys start with "sk-sp-". Please check.': 'Invalid API key. Coding Plan API keys start with "sk-sp-". Please check.',
      "You can get your Coding Plan API key here": "You can get your 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 Alibaba Cloud Coding Plan. Update now?": "New model configurations are available for Alibaba Cloud 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
      // ============================================================================
      "You can configure your API key and models in settings.json": "You can configure your API key and models in settings.json",
      "Refer to the documentation for setup instructions": "Refer to the documentation for setup instructions",
      // ============================================================================
      // Auth Dialog - View Titles and Labels
      // ============================================================================
      "Coding Plan": "Coding Plan",
      "Paste your api key of ModelStudio Coding Plan and you're all set!": "Paste your api key of ModelStudio Coding Plan 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)",
      "Select Region for Coding Plan": "Select Region for Coding Plan",
      "Choose based on where your account is registered": "Choose based on where your account is registered",
      "Enter Coding Plan API Key": "Enter Coding Plan API Key",
      // ============================================================================
      // Coding Plan International Updates
      // ============================================================================
      "New model configurations are available for {{region}}. Update now?": "New model configurations are available for {{region}}. 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).",
      // ============================================================================
      // Context Usage Component
      // ============================================================================
      "Context Usage": "Context Usage",
      "% used": "% used",
      "% context used": "% context used",
      "Context exceeds limit! Use /compress or /clear to reduce.": "Context exceeds limit! Use /compress or /clear to reduce.",
      "Use /compress or /clear": "Use /compress or /clear",
      "No API response yet. Send a message to see actual usage.": "No API response yet. Send a message to see actual usage.",
      "Estimated pre-conversation overhead": "Estimated pre-conversation overhead",
      "Context window": "Context window",
      tokens: "tokens",
      Used: "Used",
      Free: "Free",
      "Autocompact buffer": "Autocompact buffer",
      "Usage by category": "Usage by category",
      "System prompt": "System prompt",
      "Built-in tools": "Built-in tools",
      "MCP tools": "MCP tools",
      "Memory files": "Memory files",
      Skills: "Skills",
      Messages: "Messages",
      "Show context window usage breakdown.": "Show context window usage breakdown.",
      "Run /context detail for per-item breakdown.": "Run /context detail for per-item breakdown.",
      'Show context window usage breakdown. Use "/context detail" for per-item breakdown.': 'Show context window usage breakdown. Use "/context detail" for per-item breakdown.',
      "body loaded": "body loaded",
      memory: "memory",
      "{{region}} configuration updated successfully.": "{{region}} configuration updated successfully.",
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json.": "Authenticated successfully with {{region}}. API key and model configs saved to settings.json.",
      "Tip: Use /model to switch between available Coding Plan models.": "Tip: Use /model to switch between available Coding Plan models.",
      // ============================================================================
      // Ask User Question Tool
      // ============================================================================
      "Please answer the following question(s):": "Please answer the following question(s):",
      "Cannot ask user questions in non-interactive mode. Please run in interactive mode to use this tool.": "Cannot ask user questions in non-interactive mode. Please run in interactive mode to use this tool.",
      "User declined to answer the questions.": "User declined to answer the questions.",
      "User has provided the following answers:": "User has provided the following answers:",
      "Failed to process user answers:": "Failed to process user answers:",
      "Type something...": "Type something...",
      Submit: "Submit",
      "Submit answers": "Submit answers",
      Cancel: "Cancel",
      "Your answers:": "Your answers:",
      "(not answered)": "(not answered)",
      "Ready to submit your answers?": "Ready to submit your answers?",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select": "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space/Enter: Toggle | Esc: Cancel",
      "\u2191/\u2193: Navigate | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: Navigate | Space/Enter: Toggle | Esc: Cancel",
      "\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel": "\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel",
      // ============================================================================
      // Commands - Auth
      // ============================================================================
      "Configure Qwen authentication information with Qwen-OAuth or Alibaba Cloud Coding Plan": "Configure Qwen authentication information with Qwen-OAuth or Alibaba Cloud Coding Plan",
      "Authenticate using Qwen OAuth": "Authenticate using Qwen OAuth",
      "Authenticate using Alibaba Cloud Coding Plan": "Authenticate using Alibaba Cloud Coding Plan",
      "Region for Coding Plan (china/global)": "Region for Coding Plan (china/global)",
      "API key for Coding Plan": "API key for Coding Plan",
      "Show current authentication status": "Show current authentication status",
      "Authentication completed successfully.": "Authentication completed successfully.",
      "Starting Qwen OAuth authentication...": "Starting Qwen OAuth authentication...",
      "Successfully authenticated with Qwen OAuth.": "Successfully authenticated with Qwen OAuth.",
      "Failed to authenticate with Qwen OAuth: {{error}}": "Failed to authenticate with Qwen OAuth: {{error}}",
      "Processing Alibaba Cloud Coding Plan authentication...": "Processing Alibaba Cloud Coding Plan authentication...",
      "Successfully authenticated with Alibaba Cloud Coding Plan.": "Successfully authenticated with Alibaba Cloud Coding Plan.",
      "Failed to authenticate with Coding Plan: {{error}}": "Failed to authenticate with Coding Plan: {{error}}",
      "\u4E2D\u56FD (China)": "\u4E2D\u56FD (China)",
      "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)": "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)",
      Global: "Global",
      "Alibaba Cloud (alibabacloud.com)": "Alibaba Cloud (alibabacloud.com)",
      "Select region for Coding Plan:": "Select region for Coding Plan:",
      "Enter your Coding Plan API key: ": "Enter your Coding Plan API key: ",
      "Select authentication method:": "Select authentication method:",
      "\n=== Authentication Status ===\n": "\n=== Authentication Status ===\n",
      "\u26A0\uFE0F  No authentication method configured.\n": "\u26A0\uFE0F  No authentication method configured.\n",
      "Run one of the following commands to get started:\n": "Run one of the following commands to get started:\n",
      "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)": "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)",
      "  qwen auth coding-plan      - Authenticate with Alibaba Cloud Coding Plan\n": "  qwen auth coding-plan      - Authenticate with Alibaba Cloud Coding Plan\n",
      "Or simply run:": "Or simply run:",
      "  qwen auth                - Interactive authentication setup\n": "  qwen auth                - Interactive authentication setup\n",
      "\u2713 Authentication Method: Qwen OAuth": "\u2713 Authentication Method: Qwen OAuth",
      "  Type: Free tier (discontinued 2026-04-15)": "  Type: Free tier (discontinued 2026-04-15)",
      "  Limit: No longer available": "  Limit: No longer available",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.": "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.",
      "  Models: Qwen latest models\n": "  Models: Qwen latest models\n",
      "\u2713 Authentication Method: Alibaba Cloud Coding Plan": "\u2713 Authentication Method: Alibaba Cloud Coding Plan",
      "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC": "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC",
      "Global - Alibaba Cloud": "Global - Alibaba Cloud",
      "  Region: {{region}}": "  Region: {{region}}",
      "  Current Model: {{model}}": "  Current Model: {{model}}",
      "  Config Version: {{version}}": "  Config Version: {{version}}",
      "  Status: API key configured\n": "  Status: API key configured\n",
      "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)": "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)",
      "  Issue: API key not found in environment or settings\n": "  Issue: API key not found in environment or settings\n",
      "  Run `qwen auth coding-plan` to re-configure.\n": "  Run `qwen auth coding-plan` to re-configure.\n",
      "\u2713 Authentication Method: {{type}}": "\u2713 Authentication Method: {{type}}",
      "  Status: Configured\n": "  Status: Configured\n",
      "Failed to check authentication status: {{error}}": "Failed to check authentication status: {{error}}",
      "Select an option:": "Select an option:",
      "Raw mode not available. Please run in an interactive terminal.": "Raw mode not available. Please run in an interactive terminal.",
      "(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n": "(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n",
      compact: "compact",
      "compact mode: on (Ctrl+O off)": "compact mode: on (Ctrl+O off)",
      "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).": "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).",
      "Press Ctrl+O to show full tool output": "Press Ctrl+O to show full tool output",
      "Switch to plan mode or exit plan mode": "Switch to plan mode or exit plan mode",
      "Exited plan mode. Previous approval mode restored.": "Exited plan mode. Previous approval mode restored.",
      "Enabled plan mode. The agent will analyze and plan without executing tools.": "Enabled plan mode. The agent will analyze and plan without executing tools.",
      'Already in plan mode. Use "/plan exit" to exit plan mode.': 'Already in plan mode. Use "/plan exit" to exit plan mode.',
      'Not in plan mode. Use "/plan" to enter plan mode first.': 'Not in plan mode. Use "/plan" to enter plan mode first.',
      "Set up Qwen Code's status line UI": "Set up Qwen Code's status line UI"
    };
  }
});

// packages/cli/src/i18n/locales/fr.js
var fr_exports = {};
__export(fr_exports, {
  default: () => fr_default2
});
var fr_default2;
var init_fr2 = __esm({
  "packages/cli/src/i18n/locales/fr.js"() {
    "use strict";
    init_esbuild_shims();
    fr_default2 = {
      // ============================================================================
      // Aide / Composants UI
      // ============================================================================
      "\u2191 to manage attachments": "\u2191 pour g\xE9rer les pi\xE8ces jointes",
      "\u2190 \u2192 select, Delete to remove, \u2193 to exit": "\u2190 \u2192 s\xE9lectionner, Suppr pour retirer, \u2193 pour quitter",
      "Attachments: ": "Pi\xE8ces jointes : ",
      "Basics:": "Bases :",
      "Add context": "Ajouter du contexte",
      "Use {{symbol}} to specify files for context (e.g., {{example}}) to target specific files or folders.": "Utilisez {{symbol}} pour sp\xE9cifier des fichiers de contexte (ex. {{example}}) pour cibler des fichiers ou dossiers sp\xE9cifiques.",
      "@": "@",
      "@src/myFile.ts": "@src/myFile.ts",
      "Shell mode": "Mode shell",
      "YOLO mode": "Mode YOLO",
      "plan mode": "mode plan",
      "auto-accept edits": "acceptation automatique des modifications",
      "Accepting edits": "Acceptation des modifications",
      "(shift + tab to cycle)": "(maj + tab pour cycler)",
      "(tab to cycle)": "(tab pour cycler)",
      "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).": "Ex\xE9cutez des commandes shell via {{symbol}} (ex. {{example1}}) ou utilisez le langage naturel (ex. {{example2}}).",
      "!": "!",
      "!npm run start": "!npm run start",
      "start server": "d\xE9marrer le serveur",
      "Commands:": "Commandes :",
      "shell command": "commande shell",
      "Model Context Protocol command (from external servers)": "Commande Model Context Protocol (depuis des serveurs externes)",
      "Keyboard Shortcuts:": "Raccourcis clavier :",
      "Toggle this help display": "Afficher/masquer cette aide",
      "Toggle shell mode": "Basculer le mode shell",
      "Open command menu": "Ouvrir le menu des commandes",
      "Add file context": "Ajouter un contexte de fichier",
      "Accept suggestion / Autocomplete": "Accepter la suggestion / Autocompl\xE9tion",
      "Reverse search history": "Recherche invers\xE9e dans l'historique",
      "Press ? again to close": "Appuyez \xE0 nouveau sur ? pour fermer",
      "for shell mode": "pour le mode shell",
      "for commands": "pour les commandes",
      "for file paths": "pour les chemins de fichiers",
      "to clear input": "pour effacer l'entr\xE9e",
      "to cycle approvals": "pour cycler les approbations",
      "to quit": "pour quitter",
      "for newline": "pour une nouvelle ligne",
      "to clear screen": "pour effacer l'\xE9cran",
      "to search history": "pour rechercher dans l'historique",
      "to paste images": "pour coller des images",
      "for external editor": "pour un \xE9diteur externe",
      "Jump through words in the input": "Sauter de mot en mot dans l'entr\xE9e",
      "Close dialogs, cancel requests, or quit application": "Fermer les bo\xEEtes de dialogue, annuler les requ\xEAtes ou quitter l'application",
      "New line": "Nouvelle ligne",
      "New line (Alt+Enter works for certain linux distros)": "Nouvelle ligne (Alt+Entr\xE9e fonctionne sur certaines distributions Linux)",
      "Clear the screen": "Effacer l'\xE9cran",
      "Open input in external editor": "Ouvrir l'entr\xE9e dans un \xE9diteur externe",
      "Send message": "Envoyer le message",
      "Initializing...": "Initialisation...",
      "Connecting to MCP servers... ({{connected}}/{{total}})": "Connexion aux serveurs MCP... ({{connected}}/{{total}})",
      "Type your message or @path/to/file": "Tapez votre message ou @chemin/vers/fichier",
      "? for shortcuts": "? pour les raccourcis",
      "Press 'i' for INSERT mode and 'Esc' for NORMAL mode.": "Appuyez sur 'i' pour le mode INSERTION et '\xC9chap' pour le mode NORMAL.",
      "Cancel operation / Clear input (double press)": "Annuler l'op\xE9ration / Effacer l'entr\xE9e (double appui)",
      "Cycle approval modes": "Cycler les modes d'approbation",
      "Cycle through your prompt history": "Parcourir l'historique des invites",
      "For a full list of shortcuts, see {{docPath}}": "Pour la liste compl\xE8te des raccourcis, voir {{docPath}}",
      "docs/keyboard-shortcuts.md": "docs/keyboard-shortcuts.md",
      "for help on Qwen Code": "pour l'aide de Qwen Code",
      "show version info": "afficher les informations de version",
      "submit a bug report": "soumettre un rapport de bogue",
      "About Qwen Code": "\xC0 propos de Qwen Code",
      Status: "Statut",
      // ============================================================================
      // Informations système
      // ============================================================================
      "Qwen Code": "Qwen Code",
      Runtime: "Environnement",
      OS: "OS",
      Auth: "Auth",
      "CLI Version": "Version CLI",
      "Git Commit": "Commit Git",
      Model: "Mod\xE8le",
      "Fast Model": "Mod\xE8le rapide",
      Sandbox: "Bac \xE0 sable",
      "OS Platform": "Plateforme OS",
      "OS Arch": "Architecture OS",
      "OS Release": "Version OS",
      "Node.js Version": "Version Node.js",
      "NPM Version": "Version NPM",
      "Session ID": "ID de session",
      "Auth Method": "M\xE9thode d'authentification",
      "Base URL": "URL de base",
      Proxy: "Proxy",
      "Memory Usage": "Utilisation m\xE9moire",
      "IDE Client": "Client IDE",
      // ============================================================================
      // Commandes - Général
      // ============================================================================
      "Analyzes the project and creates a tailored QWEN.md file.": "Analyse le projet et cr\xE9e un fichier QWEN.md personnalis\xE9.",
      "List available Qwen Code tools. Usage: /tools [desc]": "Lister les outils Qwen Code disponibles. Utilisation : /tools [desc]",
      "List available skills.": "Lister les comp\xE9tences disponibles.",
      "Available Qwen Code CLI tools:": "Outils Qwen Code CLI disponibles :",
      "No tools available": "Aucun outil disponible",
      "View or change the approval mode for tool usage": "Voir ou modifier le mode d'approbation pour l'utilisation des outils",
      'Invalid approval mode "{{arg}}". Valid modes: {{modes}}': `Mode d'approbation invalide "{{arg}}". Modes valides : {{modes}}`,
      'Approval mode set to "{{mode}}"': `Mode d'approbation d\xE9fini sur "{{mode}}"`,
      "View or change the language setting": "Voir ou modifier le param\xE8tre de langue",
      "change the theme": "changer le th\xE8me",
      "Select Theme": "S\xE9lectionner un th\xE8me",
      Preview: "Aper\xE7u",
      "(Use Enter to select, Tab to configure scope)": "(Utilisez Entr\xE9e pour s\xE9lectionner, Tab pour configurer la port\xE9e)",
      "(Use Enter to apply scope, Tab to go back)": "(Utilisez Entr\xE9e pour appliquer la port\xE9e, Tab pour revenir)",
      "Theme configuration unavailable due to NO_COLOR env variable.": "Configuration du th\xE8me indisponible en raison de la variable d'environnement NO_COLOR.",
      'Theme "{{themeName}}" not found.': 'Th\xE8me "{{themeName}}" introuvable.',
      'Theme "{{themeName}}" not found in selected scope.': 'Th\xE8me "{{themeName}}" introuvable dans la port\xE9e s\xE9lectionn\xE9e.',
      "Clear conversation history and free up context": "Effacer l'historique de conversation et lib\xE9rer le contexte",
      "Compresses the context by replacing it with a summary.": "Compresse le contexte en le rempla\xE7ant par un r\xE9sum\xE9.",
      "open full Qwen Code documentation in your browser": "ouvrir la documentation compl\xE8te de Qwen Code dans votre navigateur",
      "Configuration not available.": "Configuration non disponible.",
      "change the auth method": "changer la m\xE9thode d'authentification",
      "Configure authentication information for login": "Configurer les informations d'authentification pour la connexion",
      "Copy the last result or code snippet to clipboard": "Copier le dernier r\xE9sultat ou extrait de code dans le presse-papiers",
      // ============================================================================
      // Commandes - Agents
      // ============================================================================
      "Manage subagents for specialized task delegation.": "G\xE9rer les sous-agents pour la d\xE9l\xE9gation de t\xE2ches sp\xE9cialis\xE9es.",
      "Manage existing subagents (view, edit, delete).": "G\xE9rer les sous-agents existants (voir, modifier, supprimer).",
      "Create a new subagent with guided setup.": "Cr\xE9er un nouveau sous-agent avec configuration guid\xE9e.",
      // ============================================================================
      // Agents - Boîte de dialogue de gestion
      // ============================================================================
      Agents: "Agents",
      "Choose Action": "Choisir une action",
      "Edit {{name}}": "Modifier {{name}}",
      "Edit Tools: {{name}}": "Modifier les outils : {{name}}",
      "Edit Color: {{name}}": "Modifier la couleur : {{name}}",
      "Delete {{name}}": "Supprimer {{name}}",
      "Unknown Step": "\xC9tape inconnue",
      "Esc to close": "\xC9chap pour fermer",
      "Enter to select, \u2191\u2193 to navigate, Esc to close": "Entr\xE9e pour s\xE9lectionner, \u2191\u2193 pour naviguer, \xC9chap pour fermer",
      "Esc to go back": "\xC9chap pour revenir",
      "Enter to confirm, Esc to cancel": "Entr\xE9e pour confirmer, \xC9chap pour annuler",
      "Enter to select, \u2191\u2193 to navigate, Esc to go back": "Entr\xE9e pour s\xE9lectionner, \u2191\u2193 pour naviguer, \xC9chap pour revenir",
      "Enter to submit, Esc to go back": "Entr\xE9e pour soumettre, \xC9chap pour revenir",
      "Invalid step: {{step}}": "\xC9tape invalide : {{step}}",
      "No subagents found.": "Aucun sous-agent trouv\xE9.",
      "Use '/agents create' to create your first subagent.": "Utilisez '/agents create' pour cr\xE9er votre premier sous-agent.",
      "(built-in)": "(int\xE9gr\xE9)",
      "(overridden by project level agent)": "(remplac\xE9 par un agent au niveau du projet)",
      "Project Level ({{path}})": "Niveau projet ({{path}})",
      "User Level ({{path}})": "Niveau utilisateur ({{path}})",
      "Built-in Agents": "Agents int\xE9gr\xE9s",
      "Extension Agents": "Agents d'extension",
      "Using: {{count}} agents": "Utilisation : {{count}} agents",
      "View Agent": "Voir l'agent",
      "Edit Agent": "Modifier l'agent",
      "Delete Agent": "Supprimer l'agent",
      Back: "Retour",
      "No agent selected": "Aucun agent s\xE9lectionn\xE9",
      "File Path: ": "Chemin du fichier : ",
      "Tools: ": "Outils : ",
      "Color: ": "Couleur : ",
      "Description:": "Description :",
      "System Prompt:": "Invite syst\xE8me :",
      "Open in editor": "Ouvrir dans l'\xE9diteur",
      "Edit tools": "Modifier les outils",
      "Edit color": "Modifier la couleur",
      "\u274C Error:": "\u274C Erreur :",
      'Are you sure you want to delete agent "{{name}}"?': `\xCAtes-vous s\xFBr de vouloir supprimer l'agent "{{name}}" ?`,
      // ============================================================================
      // Agents - Assistant de création
      // ============================================================================
      "Project Level (.qwen/agents/)": "Niveau projet (.qwen/agents/)",
      "User Level (~/.qwen/agents/)": "Niveau utilisateur (~/.qwen/agents/)",
      "\u2705 Subagent Created Successfully!": "\u2705 Sous-agent cr\xE9\xE9 avec succ\xE8s !",
      'Subagent "{{name}}" has been saved to {{level}} level.': 'Le sous-agent "{{name}}" a \xE9t\xE9 enregistr\xE9 au niveau {{level}}.',
      "Name: ": "Nom : ",
      "Location: ": "Emplacement : ",
      "\u274C Error saving subagent:": "\u274C Erreur lors de la sauvegarde du sous-agent :",
      "Warnings:": "Avertissements :",
      'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent': 'Le nom "{{name}}" existe d\xE9j\xE0 au niveau {{level}} - le sous-agent existant sera \xE9cras\xE9',
      'Name "{{name}}" exists at user level - project level will take precedence': 'Le nom "{{name}}" existe au niveau utilisateur - le niveau projet aura la priorit\xE9',
      'Name "{{name}}" exists at project level - existing subagent will take precedence': 'Le nom "{{name}}" existe au niveau projet - le sous-agent existant aura la priorit\xE9',
      "Description is over {{length}} characters": "La description d\xE9passe {{length}} caract\xE8res",
      "System prompt is over {{length}} characters": "L'invite syst\xE8me d\xE9passe {{length}} caract\xE8res",
      "Step {{n}}: Choose Location": "\xC9tape {{n}} : Choisir l'emplacement",
      "Step {{n}}: Choose Generation Method": "\xC9tape {{n}} : Choisir la m\xE9thode de g\xE9n\xE9ration",
      "Generate with Qwen Code (Recommended)": "G\xE9n\xE9rer avec Qwen Code (Recommand\xE9)",
      "Manual Creation": "Cr\xE9ation manuelle",
      "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)": "D\xE9crivez ce que ce sous-agent doit faire et quand il doit \xEAtre utilis\xE9. (Soyez complet pour de meilleurs r\xE9sultats)",
      "e.g., Expert code reviewer that reviews code based on best practices...": "ex. R\xE9viseur de code expert qui r\xE9vise le code selon les meilleures pratiques...",
      "Generating subagent configuration...": "G\xE9n\xE9ration de la configuration du sous-agent...",
      "Failed to generate subagent: {{error}}": "\xC9chec de la g\xE9n\xE9ration du sous-agent : {{error}}",
      "Step {{n}}: Describe Your Subagent": "\xC9tape {{n}} : D\xE9crire votre sous-agent",
      "Step {{n}}: Enter Subagent Name": "\xC9tape {{n}} : Entrer le nom du sous-agent",
      "Step {{n}}: Enter System Prompt": "\xC9tape {{n}} : Entrer l'invite syst\xE8me",
      "Step {{n}}: Enter Description": "\xC9tape {{n}} : Entrer la description",
      "Step {{n}}: Select Tools": "\xC9tape {{n}} : S\xE9lectionner les outils",
      "All Tools (Default)": "Tous les outils (par d\xE9faut)",
      "All Tools": "Tous les outils",
      "Read-only Tools": "Outils en lecture seule",
      "Read & Edit Tools": "Outils lecture et \xE9dition",
      "Read & Edit & Execution Tools": "Outils lecture, \xE9dition et ex\xE9cution",
      "All tools selected, including MCP tools": "Tous les outils s\xE9lectionn\xE9s, y compris les outils MCP",
      "Selected tools:": "Outils s\xE9lectionn\xE9s :",
      "Read-only tools:": "Outils en lecture seule :",
      "Edit tools:": "Outils d'\xE9dition :",
      "Execution tools:": "Outils d'ex\xE9cution :",
      "Step {{n}}: Choose Background Color": "\xC9tape {{n}} : Choisir la couleur d'arri\xE8re-plan",
      "Step {{n}}: Confirm and Save": "\xC9tape {{n}} : Confirmer et enregistrer",
      "Esc to cancel": "\xC9chap pour annuler",
      "Press Enter to save, e to save and edit, Esc to go back": "Appuyez sur Entr\xE9e pour enregistrer, e pour enregistrer et modifier, \xC9chap pour revenir",
      "Press Enter to continue, {{navigation}}Esc to {{action}}": "Appuyez sur Entr\xE9e pour continuer, {{navigation}}\xC9chap pour {{action}}",
      cancel: "annuler",
      "go back": "revenir",
      "\u2191\u2193 to navigate, ": "\u2191\u2193 pour naviguer, ",
      "Enter a clear, unique name for this subagent.": "Entrez un nom clair et unique pour ce sous-agent.",
      "e.g., Code Reviewer": "ex. R\xE9viseur de code",
      "Name cannot be empty.": "Le nom ne peut pas \xEAtre vide.",
      "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.": "R\xE9digez l'invite syst\xE8me qui d\xE9finit le comportement de ce sous-agent. Soyez complet pour de meilleurs r\xE9sultats.",
      "e.g., You are an expert code reviewer...": "ex. Vous \xEAtes un r\xE9viseur de code expert...",
      "System prompt cannot be empty.": "L'invite syst\xE8me ne peut pas \xEAtre vide.",
      "Describe when and how this subagent should be used.": "D\xE9crivez quand et comment ce sous-agent doit \xEAtre utilis\xE9.",
      "e.g., Reviews code for best practices and potential bugs.": "ex. R\xE9vise le code pour les meilleures pratiques et les bogues potentiels.",
      "Description cannot be empty.": "La description ne peut pas \xEAtre vide.",
      "Failed to launch editor: {{error}}": "\xC9chec du lancement de l'\xE9diteur : {{error}}",
      "Failed to save and edit subagent: {{error}}": "\xC9chec de la sauvegarde et modification du sous-agent : {{error}}",
      // ============================================================================
      // Extensions - Boîte de dialogue de gestion
      // ============================================================================
      "Manage Extensions": "G\xE9rer les extensions",
      "Extension Details": "D\xE9tails de l'extension",
      "View Extension": "Voir l'extension",
      "Update Extension": "Mettre \xE0 jour l'extension",
      "Disable Extension": "D\xE9sactiver l'extension",
      "Enable Extension": "Activer l'extension",
      "Uninstall Extension": "D\xE9sinstaller l'extension",
      "Select Scope": "S\xE9lectionner la port\xE9e",
      "User Scope": "Port\xE9e utilisateur",
      "Workspace Scope": "Port\xE9e espace de travail",
      "No extensions found.": "Aucune extension trouv\xE9e.",
      Active: "Actif",
      Disabled: "D\xE9sactiv\xE9",
      "Update available": "Mise \xE0 jour disponible",
      "Up to date": "\xC0 jour",
      "Checking...": "V\xE9rification...",
      "Updating...": "Mise \xE0 jour...",
      Unknown: "Inconnu",
      Error: "Erreur",
      "Version:": "Version :",
      "Status:": "Statut :",
      'Are you sure you want to uninstall extension "{{name}}"?': `\xCAtes-vous s\xFBr de vouloir d\xE9sinstaller l'extension "{{name}}" ?`,
      "This action cannot be undone.": "Cette action est irr\xE9versible.",
      'Extension "{{name}}" disabled successfully.': 'Extension "{{name}}" d\xE9sactiv\xE9e avec succ\xE8s.',
      'Extension "{{name}}" enabled successfully.': 'Extension "{{name}}" activ\xE9e avec succ\xE8s.',
      'Extension "{{name}}" updated successfully.': 'Extension "{{name}}" mise \xE0 jour avec succ\xE8s.',
      'Failed to update extension "{{name}}": {{error}}': `\xC9chec de la mise \xE0 jour de l'extension "{{name}}" : {{error}}`,
      "Select the scope for this action:": "S\xE9lectionnez la port\xE9e pour cette action :",
      "User - Applies to all projects": "Utilisateur - S'applique \xE0 tous les projets",
      "Workspace - Applies to current project only": "Espace de travail - S'applique uniquement au projet actuel",
      "Name:": "Nom :",
      "MCP Servers:": "Serveurs MCP :",
      "Settings:": "Param\xE8tres :",
      active: "actif",
      disabled: "d\xE9sactiv\xE9",
      "View Details": "Voir les d\xE9tails",
      "Update failed:": "\xC9chec de la mise \xE0 jour :",
      "Updating {{name}}...": "Mise \xE0 jour de {{name}}...",
      "Update complete!": "Mise \xE0 jour termin\xE9e !",
      "User (global)": "Utilisateur (global)",
      "Workspace (project-specific)": "Espace de travail (sp\xE9cifique au projet)",
      'Disable "{{name}}" - Select Scope': 'D\xE9sactiver "{{name}}" - S\xE9lectionner la port\xE9e',
      'Enable "{{name}}" - Select Scope': 'Activer "{{name}}" - S\xE9lectionner la port\xE9e',
      "No extension selected": "Aucune extension s\xE9lectionn\xE9e",
      "Press Y/Enter to confirm, N/Esc to cancel": "Appuyez sur O/Entr\xE9e pour confirmer, N/\xC9chap pour annuler",
      "Y/Enter to confirm, N/Esc to cancel": "O/Entr\xE9e pour confirmer, N/\xC9chap pour annuler",
      "{{count}} extensions installed": "{{count}} extensions install\xE9es",
      "Use '/extensions install' to install your first extension.": "Utilisez '/extensions install' pour installer votre premi\xE8re extension.",
      "up to date": "\xE0 jour",
      "update available": "mise \xE0 jour disponible",
      "checking...": "v\xE9rification...",
      "not updatable": "non mise \xE0 jour possible",
      error: "erreur",
      // ============================================================================
      // Commandes - Général (suite)
      // ============================================================================
      "View and edit Qwen Code settings": "Voir et modifier les param\xE8tres de Qwen Code",
      Settings: "Param\xE8tres",
      "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.": "Pour voir les changements, Qwen Code doit \xEAtre red\xE9marr\xE9. Appuyez sur r pour quitter et appliquer les changements maintenant.",
      'The command "/{{command}}" is not supported in non-interactive mode.': `La commande "/{{command}}" n'est pas prise en charge en mode non interactif.`,
      // ============================================================================
      // Étiquettes des paramètres
      // ============================================================================
      "Vim Mode": "Mode Vim",
      "Disable Auto Update": "D\xE9sactiver la mise \xE0 jour automatique",
      "Attribution: commit": "Attribution : commit",
      "Terminal Bell Notification": "Notification sonore du terminal",
      "Enable Usage Statistics": "Activer les statistiques d'utilisation",
      Theme: "Th\xE8me",
      "Preferred Editor": "\xC9diteur pr\xE9f\xE9r\xE9",
      "Auto-connect to IDE": "Connexion automatique \xE0 l'IDE",
      "Enable Prompt Completion": "Activer la compl\xE9tion d'invite",
      "Debug Keystroke Logging": "Journalisation des frappes de d\xE9bogage",
      "Language: UI": "Langue : Interface",
      "Language: Model": "Langue : Mod\xE8le",
      "Output Format": "Format de sortie",
      "Hide Window Title": "Masquer le titre de la fen\xEAtre",
      "Show Status in Title": "Afficher le statut dans le titre",
      "Hide Tips": "Masquer les conseils",
      "Show Line Numbers in Code": "Afficher les num\xE9ros de ligne dans le code",
      "Show Citations": "Afficher les citations",
      "Custom Witty Phrases": "Phrases personnalis\xE9es spirituelles",
      "Show Welcome Back Dialog": "Afficher le dialogue de bienvenue",
      "Enable User Feedback": "Activer les retours utilisateur",
      "How is Qwen doing this session? (optional)": "Comment se passe cette session avec Qwen ? (facultatif)",
      Bad: "Mauvais",
      Fine: "Correct",
      Good: "Bien",
      Dismiss: "Ignorer",
      "Not Sure Yet": "Pas encore s\xFBr",
      "Any other key": "Toute autre touche",
      "Disable Loading Phrases": "D\xE9sactiver les phrases de chargement",
      "Screen Reader Mode": "Mode lecteur d'\xE9cran",
      "IDE Mode": "Mode IDE",
      "Max Session Turns": "Nombre maximum de tours de session",
      "Skip Next Speaker Check": "Ignorer la v\xE9rification du prochain interlocuteur",
      "Skip Loop Detection": "Ignorer la d\xE9tection de boucle",
      "Skip Startup Context": "Ignorer le contexte de d\xE9marrage",
      "Enable OpenAI Logging": "Activer la journalisation OpenAI",
      "OpenAI Logging Directory": "R\xE9pertoire de journalisation OpenAI",
      Timeout: "D\xE9lai d'attente",
      "Max Retries": "Nombre maximum de tentatives",
      "Disable Cache Control": "D\xE9sactiver le contr\xF4le du cache",
      "Memory Discovery Max Dirs": "R\xE9pertoires max pour la d\xE9couverte m\xE9moire",
      "Load Memory From Include Directories": "Charger la m\xE9moire depuis les r\xE9pertoires inclus",
      "Respect .gitignore": "Respecter .gitignore",
      "Respect .qwenignore": "Respecter .qwenignore",
      "Enable Recursive File Search": "Activer la recherche r\xE9cursive de fichiers",
      "Disable Fuzzy Search": "D\xE9sactiver la recherche approximative",
      "Interactive Shell (PTY)": "Shell interactif (PTY)",
      "Show Color": "Afficher les couleurs",
      "Auto Accept": "Acceptation automatique",
      "Use Ripgrep": "Utiliser Ripgrep",
      "Use Builtin Ripgrep": "Utiliser Ripgrep int\xE9gr\xE9",
      "Enable Tool Output Truncation": "Activer la troncature de sortie des outils",
      "Tool Output Truncation Threshold": "Seuil de troncature de sortie des outils",
      "Tool Output Truncation Lines": "Lignes de troncature de sortie des outils",
      "Folder Trust": "Confiance des dossiers",
      "Vision Model Preview": "Aper\xE7u du mod\xE8le de vision",
      "Tool Schema Compliance": "Conformit\xE9 au sch\xE9ma des outils",
      "Auto (detect from system)": "Auto (d\xE9tecter depuis le syst\xE8me)",
      "Auto (detect terminal theme)": "Auto (d\xE9tecter le th\xE8me du terminal)",
      Auto: "Auto",
      Text: "Texte",
      JSON: "JSON",
      Plan: "Plan",
      Default: "Par d\xE9faut",
      "Auto Edit": "\xC9dition automatique",
      YOLO: "YOLO",
      "toggle vim mode on/off": "activer/d\xE9sactiver le mode Vim",
      "check session stats. Usage: /stats [model|tools]": "v\xE9rifier les stats de session. Utilisation : /stats [mod\xE8le|outils]",
      "Show model-specific usage statistics.": "Afficher les statistiques d'utilisation sp\xE9cifiques au mod\xE8le.",
      "Show tool-specific usage statistics.": "Afficher les statistiques d'utilisation sp\xE9cifiques aux outils.",
      "exit the cli": "quitter le CLI",
      "Open MCP management dialog, or authenticate with OAuth-enabled servers": "Ouvrir le dialogue de gestion MCP, ou authentifier avec des serveurs compatibles OAuth",
      "List configured MCP servers and tools, or authenticate with OAuth-enabled servers": "Lister les serveurs MCP et outils configur\xE9s, ou authentifier avec des serveurs compatibles OAuth",
      "Manage workspace directories": "G\xE9rer les r\xE9pertoires de l'espace de travail",
      "Add directories to the workspace. Use comma to separate multiple paths": "Ajouter des r\xE9pertoires \xE0 l'espace de travail. Utilisez une virgule pour s\xE9parer plusieurs chemins",
      "Show all directories in the workspace": "Afficher tous les r\xE9pertoires de l'espace de travail",
      "set external editor preference": "d\xE9finir la pr\xE9f\xE9rence d'\xE9diteur externe",
      "Select Editor": "S\xE9lectionner l'\xE9diteur",
      "Editor Preference": "Pr\xE9f\xE9rence d'\xE9diteur",
      "These editors are currently supported. Please note that some editors cannot be used in sandbox mode.": "Ces \xE9diteurs sont actuellement pris en charge. Notez que certains \xE9diteurs ne peuvent pas \xEAtre utilis\xE9s en mode bac \xE0 sable.",
      "Your preferred editor is:": "Votre \xE9diteur pr\xE9f\xE9r\xE9 est :",
      "Manage extensions": "G\xE9rer les extensions",
      "Manage installed extensions": "G\xE9rer les extensions install\xE9es",
      "List active extensions": "Lister les extensions actives",
      "Update extensions. Usage: update <extension-names>|--all": "Mettre \xE0 jour les extensions. Utilisation : update <noms-extensions>|--all",
      "Disable an extension": "D\xE9sactiver une extension",
      "Enable an extension": "Activer une extension",
      "Install an extension from a git repo or local path": "Installer une extension depuis un d\xE9p\xF4t git ou un chemin local",
      "Uninstall an extension": "D\xE9sinstaller une extension",
      "No extensions installed.": "Aucune extension install\xE9e.",
      "Usage: /extensions update <extension-names>|--all": "Utilisation : /extensions update <noms-extensions>|--all",
      'Extension "{{name}}" not found.': 'Extension "{{name}}" introuvable.',
      "No extensions to update.": "Aucune extension \xE0 mettre \xE0 jour.",
      "Usage: /extensions install <source>": "Utilisation : /extensions install <source>",
      'Installing extension from "{{source}}"...': `Installation de l'extension depuis "{{source}}"...`,
      'Extension "{{name}}" installed successfully.': 'Extension "{{name}}" install\xE9e avec succ\xE8s.',
      'Failed to install extension from "{{source}}": {{error}}': `\xC9chec de l'installation de l'extension depuis "{{source}}" : {{error}}`,
      "Usage: /extensions uninstall <extension-name>": "Utilisation : /extensions uninstall <nom-extension>",
      'Uninstalling extension "{{name}}"...': `D\xE9sinstallation de l'extension "{{name}}"...`,
      'Extension "{{name}}" uninstalled successfully.': 'Extension "{{name}}" d\xE9sinstall\xE9e avec succ\xE8s.',
      'Failed to uninstall extension "{{name}}": {{error}}': `\xC9chec de la d\xE9sinstallation de l'extension "{{name}}" : {{error}}`,
      "Usage: /extensions {{command}} <extension> [--scope=<user|workspace>]": "Utilisation : /extensions {{command}} <extension> [--scope=<user|workspace>]",
      'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': 'Port\xE9e non prise en charge "{{scope}}", doit \xEAtre "user" ou "workspace"',
      'Extension "{{name}}" disabled for scope "{{scope}}"': 'Extension "{{name}}" d\xE9sactiv\xE9e pour la port\xE9e "{{scope}}"',
      'Extension "{{name}}" enabled for scope "{{scope}}"': 'Extension "{{name}}" activ\xE9e pour la port\xE9e "{{scope}}"',
      "Do you want to continue? [Y/n]: ": "Voulez-vous continuer ? [O/n] : ",
      "Do you want to continue?": "Voulez-vous continuer ?",
      'Installing extension "{{name}}".': `Installation de l'extension "{{name}}".`,
      "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**": "**Les extensions peuvent introduire des comportements inattendus. Assurez-vous d'avoir examin\xE9 la source de l'extension et de faire confiance \xE0 l'auteur.**",
      "This extension will run the following MCP servers:": "Cette extension ex\xE9cutera les serveurs MCP suivants :",
      local: "local",
      remote: "distant",
      "This extension will add the following commands: {{commands}}.": "Cette extension ajoutera les commandes suivantes : {{commands}}.",
      "This extension will append info to your QWEN.md context using {{fileName}}": "Cette extension ajoutera des informations \xE0 votre contexte QWEN.md en utilisant {{fileName}}",
      "This extension will exclude the following core tools: {{tools}}": "Cette extension exclura les outils principaux suivants : {{tools}}",
      "This extension will install the following skills:": "Cette extension installera les comp\xE9tences suivantes :",
      "This extension will install the following subagents:": "Cette extension installera les sous-agents suivants :",
      'Installation cancelled for "{{name}}".': 'Installation annul\xE9e pour "{{name}}".',
      "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.": "Vous installez une extension depuis {{originSource}}. Certaines fonctionnalit\xE9s peuvent ne pas fonctionner parfaitement avec Qwen Code.",
      "--ref and --auto-update are not applicable for marketplace extensions.": "--ref et --auto-update ne sont pas applicables aux extensions du marketplace.",
      'Extension "{{name}}" installed successfully and enabled.': 'Extension "{{name}}" install\xE9e et activ\xE9e avec succ\xE8s.',
      "Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).": "Installe une extension depuis une URL de d\xE9p\xF4t git, un chemin local ou le marketplace claude (marketplace-url:nom-plugin).",
      "The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.": "L'URL GitHub, le chemin local ou la source marketplace (marketplace-url:nom-plugin) de l'extension \xE0 installer.",
      "The git ref to install from.": "La r\xE9f\xE9rence git depuis laquelle installer.",
      "Enable auto-update for this extension.": "Activer la mise \xE0 jour automatique pour cette extension.",
      "Enable pre-release versions for this extension.": "Activer les versions pr\xE9-release pour cette extension.",
      "Acknowledge the security risks of installing an extension and skip the confirmation prompt.": "Reconna\xEEtre les risques de s\xE9curit\xE9 li\xE9s \xE0 l'installation d'une extension et ignorer la confirmation.",
      "The source argument must be provided.": "L'argument source doit \xEAtre fourni.",
      'Extension "{{name}}" successfully uninstalled.': 'Extension "{{name}}" d\xE9sinstall\xE9e avec succ\xE8s.',
      "Uninstalls an extension.": "D\xE9sinstalle une extension.",
      "The name or source path of the extension to uninstall.": "Le nom ou le chemin source de l'extension \xE0 d\xE9sinstaller.",
      "Please include the name of the extension to uninstall as a positional argument.": "Veuillez inclure le nom de l'extension \xE0 d\xE9sinstaller comme argument positionnel.",
      "Enables an extension.": "Active une extension.",
      "The name of the extension to enable.": "Le nom de l'extension \xE0 activer.",
      "The scope to enable the extenison in. If not set, will be enabled in all scopes.": "La port\xE9e dans laquelle activer l'extension. Si non d\xE9finie, sera activ\xE9e dans toutes les port\xE9es.",
      'Extension "{{name}}" successfully enabled for scope "{{scope}}".': 'Extension "{{name}}" activ\xE9e avec succ\xE8s pour la port\xE9e "{{scope}}".',
      'Extension "{{name}}" successfully enabled in all scopes.': 'Extension "{{name}}" activ\xE9e avec succ\xE8s dans toutes les port\xE9es.',
      "Invalid scope: {{scope}}. Please use one of {{scopes}}.": "Port\xE9e invalide : {{scope}}. Veuillez utiliser l'une de : {{scopes}}.",
      "Disables an extension.": "D\xE9sactive une extension.",
      "The name of the extension to disable.": "Le nom de l'extension \xE0 d\xE9sactiver.",
      "The scope to disable the extenison in.": "La port\xE9e dans laquelle d\xE9sactiver l'extension.",
      'Extension "{{name}}" successfully disabled for scope "{{scope}}".': 'Extension "{{name}}" d\xE9sactiv\xE9e avec succ\xE8s pour la port\xE9e "{{scope}}".',
      'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.': 'Extension "{{name}}" mise \xE0 jour avec succ\xE8s : {{oldVersion}} \u2192 {{newVersion}}.',
      'Unable to install extension "{{name}}" due to missing install metadata': `Impossible d'installer l'extension "{{name}}" en raison de m\xE9tadonn\xE9es d'installation manquantes`,
      'Extension "{{name}}" is already up to date.': `L'extension "{{name}}" est d\xE9j\xE0 \xE0 jour.`,
      "Updates all extensions or a named extension to the latest version.": "Met \xE0 jour toutes les extensions ou une extension nomm\xE9e vers la derni\xE8re version.",
      "Update all extensions.": "Mettre \xE0 jour toutes les extensions.",
      "Either an extension name or --all must be provided": "Un nom d'extension ou --all doit \xEAtre fourni",
      "Lists installed extensions.": "Liste les extensions install\xE9es.",
      "Path:": "Chemin :",
      "Source:": "Source :",
      "Type:": "Type :",
      "Ref:": "R\xE9f :",
      "Release tag:": "Tag de version :",
      "Enabled (User):": "Activ\xE9 (Utilisateur) :",
      "Enabled (Workspace):": "Activ\xE9 (Espace de travail) :",
      "Context files:": "Fichiers de contexte :",
      "Skills:": "Comp\xE9tences :",
      "Agents:": "Agents :",
      "MCP servers:": "Serveurs MCP :",
      "Link extension failed to install.": "\xC9chec de l'installation de l'extension li\xE9e.",
      'Extension "{{name}}" linked successfully and enabled.': 'Extension "{{name}}" li\xE9e et activ\xE9e avec succ\xE8s.',
      "Links an extension from a local path. Updates made to the local path will always be reflected.": "Lie une extension depuis un chemin local. Les modifications apport\xE9es au chemin local seront toujours refl\xE9t\xE9es.",
      "The name of the extension to link.": "Le nom de l'extension \xE0 lier.",
      "Set a specific setting for an extension.": "D\xE9finir un param\xE8tre sp\xE9cifique pour une extension.",
      "Name of the extension to configure.": "Nom de l'extension \xE0 configurer.",
      "The setting to configure (name or env var).": "Le param\xE8tre \xE0 configurer (nom ou variable d'environnement).",
      "The scope to set the setting in.": "La port\xE9e dans laquelle d\xE9finir le param\xE8tre.",
      "List all settings for an extension.": "Lister tous les param\xE8tres d'une extension.",
      "Name of the extension.": "Nom de l'extension.",
      'Extension "{{name}}" has no settings to configure.': `L'extension "{{name}}" n'a aucun param\xE8tre \xE0 configurer.`,
      'Settings for "{{name}}":': 'Param\xE8tres pour "{{name}}" :',
      "(workspace)": "(espace de travail)",
      "(user)": "(utilisateur)",
      "[not set]": "[non d\xE9fini]",
      "[value stored in keychain]": "[valeur stock\xE9e dans le trousseau]",
      "Value:": "Valeur :",
      "Manage extension settings.": "G\xE9rer les param\xE8tres des extensions.",
      "You need to specify a command (set or list).": "Vous devez sp\xE9cifier une commande (set ou list).",
      // ============================================================================
      // Choix de plugin / Marketplace
      // ============================================================================
      "No plugins available in this marketplace.": "Aucun plugin disponible dans ce marketplace.",
      'Select a plugin to install from marketplace "{{name}}":': 'S\xE9lectionnez un plugin \xE0 installer depuis le marketplace "{{name}}" :',
      "Plugin selection cancelled.": "S\xE9lection de plugin annul\xE9e.",
      'Select a plugin from "{{name}}"': 'S\xE9lectionner un plugin depuis "{{name}}"',
      "Use \u2191\u2193 or j/k to navigate, Enter to select, Escape to cancel": "Utilisez \u2191\u2193 ou j/k pour naviguer, Entr\xE9e pour s\xE9lectionner, \xC9chap pour annuler",
      "{{count}} more above": "{{count}} de plus au-dessus",
      "{{count}} more below": "{{count}} de plus en dessous",
      "manage IDE integration": "g\xE9rer l'int\xE9gration IDE",
      "check status of IDE integration": "v\xE9rifier le statut de l'int\xE9gration IDE",
      "install required IDE companion for {{ideName}}": "installer le compagnon IDE requis pour {{ideName}}",
      "enable IDE integration": "activer l'int\xE9gration IDE",
      "disable IDE integration": "d\xE9sactiver l'int\xE9gration 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.": "L'int\xE9gration IDE n'est pas prise en charge dans votre environnement actuel. Pour utiliser cette fonctionnalit\xE9, ex\xE9cutez Qwen Code dans l'un des IDEs pris en charge : VS Code ou ses d\xE9riv\xE9s.",
      "Set up GitHub Actions": "Configurer GitHub Actions",
      "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)": "Configurer les raccourcis du terminal pour la saisie multiligne (VS Code, Cursor, Windsurf, Trae)",
      "Please restart your terminal for the changes to take effect.": "Veuillez red\xE9marrer votre terminal pour que les modifications prennent effet.",
      "Failed to configure terminal: {{error}}": "\xC9chec de la configuration du terminal : {{error}}",
      "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.": "Impossible de d\xE9terminer le chemin de configuration de {{terminalName}} sur Windows : la variable d'environnement APPDATA n'est pas d\xE9finie.",
      "{{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 mais n'est pas un tableau JSON valide. Veuillez corriger le fichier manuellement ou le supprimer pour permettre la configuration automatique.",
      "File: {{file}}": "Fichier : {{file}}",
      "Failed to parse {{terminalName}} keybindings.json. The file contains invalid JSON. Please fix the file manually or delete it to allow automatic configuration.": "\xC9chec de l'analyse de {{terminalName}} keybindings.json. Le fichier contient du JSON invalide. Veuillez corriger le fichier manuellement ou le supprimer pour permettre la configuration automatique.",
      "Error: {{error}}": "Erreur : {{error}}",
      "Shift+Enter binding already exists": "Le raccourci Maj+Entr\xE9e existe d\xE9j\xE0",
      "Ctrl+Enter binding already exists": "Le raccourci Ctrl+Entr\xE9e existe d\xE9j\xE0",
      "Existing keybindings detected. Will not modify to avoid conflicts.": "Raccourcis existants d\xE9tect\xE9s. Aucune modification pour \xE9viter les conflits.",
      "Please check and modify manually if needed: {{file}}": "Veuillez v\xE9rifier et modifier manuellement si n\xE9cessaire : {{file}}",
      "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.": "Raccourcis Maj+Entr\xE9e et Ctrl+Entr\xE9e ajout\xE9s \xE0 {{terminalName}}.",
      "Modified: {{file}}": "Modifi\xE9 : {{file}}",
      "{{terminalName}} keybindings already configured.": "Raccourcis {{terminalName}} d\xE9j\xE0 configur\xE9s.",
      "Failed to configure {{terminalName}}.": "\xC9chec de la configuration de {{terminalName}}.",
      "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter).": "Votre terminal est d\xE9j\xE0 configur\xE9 pour une exp\xE9rience optimale avec la saisie multiligne (Maj+Entr\xE9e et Ctrl+Entr\xE9e).",
      // ============================================================================
      // Commandes - Hooks
      // ============================================================================
      "Manage Qwen Code hooks": "G\xE9rer les hooks Qwen Code",
      "List all configured hooks": "Lister tous les hooks configur\xE9s",
      "Enable a disabled hook": "Activer un hook d\xE9sactiv\xE9",
      "Disable an active hook": "D\xE9sactiver un hook actif",
      Hooks: "Hooks",
      "Loading hooks...": "Chargement des hooks...",
      "Error loading hooks:": "Erreur lors du chargement des hooks :",
      "Press Escape to close": "Appuyez sur \xC9chap pour fermer",
      "Press Escape, Ctrl+C, or Ctrl+D to cancel": "Appuyez sur \xC9chap, Ctrl+C ou Ctrl+D pour annuler",
      "Press Space, Enter, or Escape to dismiss": "Appuyez sur Espace, Entr\xE9e ou \xC9chap pour ignorer",
      "No hook selected": "Aucun hook s\xE9lectionn\xE9",
      "No hook events found.": "Aucun \xE9v\xE9nement de hook trouv\xE9.",
      "{{count}} hook configured": "{{count}} hook configur\xE9",
      "{{count}} hooks configured": "{{count}} hooks configur\xE9s",
      "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.": "Ce menu est en lecture seule. Pour ajouter ou modifier des hooks, \xE9ditez settings.json directement ou demandez \xE0 Qwen Code.",
      "Enter to select \xB7 Esc to cancel": "Entr\xE9e pour s\xE9lectionner \xB7 \xC9chap pour annuler",
      "Exit codes:": "Codes de sortie :",
      "Configured hooks:": "Hooks configur\xE9s :",
      "No hooks configured for this event.": "Aucun hook configur\xE9 pour cet \xE9v\xE9nement.",
      "To add hooks, edit settings.json directly or ask Qwen.": "Pour ajouter des hooks, \xE9ditez settings.json directement ou demandez \xE0 Qwen.",
      "Enter to select \xB7 Esc to go back": "Entr\xE9e pour s\xE9lectionner \xB7 \xC9chap pour revenir",
      "Hook details": "D\xE9tails du hook",
      "Event:": "\xC9v\xE9nement :",
      "Extension:": "Extension :",
      "Desc:": "Description :",
      "No hook config selected": "Aucune configuration de hook s\xE9lectionn\xE9e",
      "To modify or remove this hook, edit settings.json directly or ask Qwen to help.": "Pour modifier ou supprimer ce hook, \xE9ditez settings.json directement ou demandez \xE0 Qwen.",
      "Hook Configuration - Disabled": "Configuration du hook - D\xE9sactiv\xE9",
      "All hooks are currently disabled. You have {{count}} that are not running.": "Tous les hooks sont actuellement d\xE9sactiv\xE9s. Vous en avez {{count}} qui ne s'ex\xE9cutent pas.",
      "{{count}} configured hook": "{{count}} hook configur\xE9",
      "{{count}} configured hooks": "{{count}} hooks configur\xE9s",
      "When hooks are disabled:": "Quand les hooks sont d\xE9sactiv\xE9s :",
      "No hook commands will execute": "Aucune commande de hook ne s'ex\xE9cutera",
      "StatusLine will not be displayed": "La barre de statut ne sera pas affich\xE9e",
      "Tool operations will proceed without hook validation": "Les op\xE9rations d'outils se poursuivront sans validation des hooks",
      'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.': 'Pour r\xE9activer les hooks, supprimez "disableAllHooks" de settings.json ou demandez \xE0 Qwen Code.',
      Project: "Projet",
      User: "Utilisateur",
      System: "Syst\xE8me",
      Extension: "Extension",
      "Local Settings": "Param\xE8tres locaux",
      "User Settings": "Param\xE8tres utilisateur",
      "System Settings": "Param\xE8tres syst\xE8me",
      Extensions: "Extensions",
      "\u2713 Enabled": "\u2713 Activ\xE9",
      "\u2717 Disabled": "\u2717 D\xE9sactiv\xE9",
      "Before tool execution": "Avant l'ex\xE9cution de l'outil",
      "After tool execution": "Apr\xE8s l'ex\xE9cution de l'outil",
      "After tool execution fails": "Apr\xE8s l'\xE9chec de l'ex\xE9cution de l'outil",
      "When notifications are sent": "Quand des notifications sont envoy\xE9es",
      "When the user submits a prompt": "Quand l'utilisateur soumet une invite",
      "When a new session is started": "Quand une nouvelle session est d\xE9marr\xE9e",
      "Right before Qwen Code concludes its response": "Juste avant que Qwen Code conclue sa r\xE9ponse",
      "When a subagent (Agent tool call) is started": "Quand un sous-agent (appel d'outil Agent) est d\xE9marr\xE9",
      "Right before a subagent concludes its response": "Juste avant qu'un sous-agent conclue sa r\xE9ponse",
      "Before conversation compaction": "Avant la compaction de la conversation",
      "When a session is ending": "Quand une session se termine",
      "When a permission dialog is displayed": "Quand un dialogue de permission est affich\xE9",
      "Input to command is JSON of tool call arguments.": "L'entr\xE9e de la commande est du JSON des arguments d'appel d'outil.",
      'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': `L'entr\xE9e de la commande est du JSON avec les champs "inputs" (arguments d'appel d'outil) et "response" (r\xE9ponse de l'appel d'outil).`,
      "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.": "L'entr\xE9e de la commande est du JSON avec tool_name, tool_input, tool_use_id, error, error_type, is_interrupt et is_timeout.",
      "Input to command is JSON with notification message and type.": "L'entr\xE9e de la commande est du JSON avec le message et le type de notification.",
      "Input to command is JSON with original user prompt text.": "L'entr\xE9e de la commande est du JSON avec le texte d'invite original de l'utilisateur.",
      "Input to command is JSON with session start source.": "L'entr\xE9e de la commande est du JSON avec la source de d\xE9marrage de session.",
      "Input to command is JSON with session end reason.": "L'entr\xE9e de la commande est du JSON avec la raison de fin de session.",
      "Input to command is JSON with agent_id and agent_type.": "L'entr\xE9e de la commande est du JSON avec agent_id et agent_type.",
      "Input to command is JSON with agent_id, agent_type, and agent_transcript_path.": "L'entr\xE9e de la commande est du JSON avec agent_id, agent_type et agent_transcript_path.",
      "Input to command is JSON with compaction details.": "L'entr\xE9e de la commande est du JSON avec les d\xE9tails de compaction.",
      "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.": "L'entr\xE9e de la commande est du JSON avec tool_name, tool_input et tool_use_id. Sortie JSON avec hookSpecificOutput contenant la d\xE9cision d'autoriser ou de refuser.",
      "stdout/stderr not shown": "stdout/stderr non affich\xE9",
      "show stderr to model and continue conversation": "afficher stderr au mod\xE8le et continuer la conversation",
      "show stderr to user only": "afficher stderr \xE0 l'utilisateur uniquement",
      "stdout shown in transcript mode (ctrl+o)": "stdout affich\xE9 en mode transcription (ctrl+o)",
      "show stderr to model immediately": "afficher stderr au mod\xE8le imm\xE9diatement",
      "show stderr to user only but continue with tool call": "afficher stderr \xE0 l'utilisateur uniquement mais continuer l'appel d'outil",
      "block processing, erase original prompt, and show stderr to user only": "bloquer le traitement, effacer l'invite originale et afficher stderr \xE0 l'utilisateur uniquement",
      "stdout shown to Qwen": "stdout affich\xE9 \xE0 Qwen",
      "show stderr to user only (blocking errors ignored)": "afficher stderr \xE0 l'utilisateur uniquement (erreurs bloquantes ignor\xE9es)",
      "command completes successfully": "la commande se termine avec succ\xE8s",
      "stdout shown to subagent": "stdout affich\xE9 au sous-agent",
      "show stderr to subagent and continue having it run": "afficher stderr au sous-agent et continuer son ex\xE9cution",
      "stdout appended as custom compact instructions": "stdout ajout\xE9 comme instructions compactes personnalis\xE9es",
      "block compaction": "bloquer la compaction",
      "show stderr to user only but continue with compaction": "afficher stderr \xE0 l'utilisateur uniquement mais continuer la compaction",
      "use hook decision if provided": "utiliser la d\xE9cision du hook si fournie",
      "Config not loaded.": "Configuration non charg\xE9e.",
      "Hooks are not enabled. Enable hooks in settings to use this feature.": "Les hooks ne sont pas activ\xE9s. Activez les hooks dans les param\xE8tres pour utiliser cette fonctionnalit\xE9.",
      "No hooks configured. Add hooks in your settings.json file.": "Aucun hook configur\xE9. Ajoutez des hooks dans votre fichier settings.json.",
      "Configured Hooks ({{count}} total)": "Hooks configur\xE9s ({{count}} au total)",
      // ============================================================================
      // Commandes - Export de session
      // ============================================================================
      "Export current session message history to a file": "Exporter l'historique des messages de la session actuelle vers un fichier",
      "Export session to HTML format": "Exporter la session au format HTML",
      "Export session to JSON format": "Exporter la session au format JSON",
      "Export session to JSONL format (one message per line)": "Exporter la session au format JSONL (un message par ligne)",
      "Export session to markdown format": "Exporter la session au format markdown",
      // ============================================================================
      // Commandes - Insights
      // ============================================================================
      "generate personalized programming insights from your chat history": "g\xE9n\xE9rer des insights de programmation personnalis\xE9s depuis votre historique de chat",
      // ============================================================================
      // Commandes - Historique de session
      // ============================================================================
      "Resume a previous session": "Reprendre une session pr\xE9c\xE9dente",
      "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested": "Restaurer un appel d'outil. Cela r\xE9initialisera la conversation et l'historique des fichiers \xE0 l'\xE9tat o\xF9 il se trouvait lors de la suggestion de l'appel d'outil",
      "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae.": "Impossible de d\xE9tecter le type de terminal. Terminaux pris en charge : VS Code, Cursor, Windsurf et Trae.",
      'Terminal "{{terminal}}" is not supported yet.': `Le terminal "{{terminal}}" n'est pas encore pris en charge.`,
      // ============================================================================
      // Commandes - Langue
      // ============================================================================
      "Invalid language. Available: {{options}}": "Langue invalide. Disponibles : {{options}}",
      "Language subcommands do not accept additional arguments.": "Les sous-commandes de langue n'acceptent pas d'arguments suppl\xE9mentaires.",
      "Current UI language: {{lang}}": "Langue de l'interface actuelle : {{lang}}",
      "Current LLM output language: {{lang}}": "Langue de sortie LLM actuelle : {{lang}}",
      "LLM output language not set": "Langue de sortie LLM non d\xE9finie",
      "Set UI language": "D\xE9finir la langue de l'interface",
      "Set LLM output language": "D\xE9finir la langue de sortie LLM",
      "Usage: /language ui [{{options}}]": "Utilisation : /language ui [{{options}}]",
      "Usage: /language output <language>": "Utilisation : /language output <langue>",
      "Example: /language output \u4E2D\u6587": "Exemple : /language output \u4E2D\u6587",
      "Example: /language output English": "Exemple : /language output English",
      "Example: /language output \u65E5\u672C\u8A9E": "Exemple : /language output \u65E5\u672C\u8A9E",
      "Example: /language output Portugu\xEAs": "Exemple : /language output Portugu\xEAs",
      "UI language changed to {{lang}}": "Langue de l'interface chang\xE9e en {{lang}}",
      "LLM output language set to {{lang}}": "Langue de sortie LLM d\xE9finie sur {{lang}}",
      "LLM output language rule file generated at {{path}}": "Fichier de r\xE8gle de langue de sortie LLM g\xE9n\xE9r\xE9 dans {{path}}",
      "Please restart the application for the changes to take effect.": "Veuillez red\xE9marrer l'application pour que les modifications prennent effet.",
      "Failed to generate LLM output language rule file: {{error}}": "\xC9chec de la g\xE9n\xE9ration du fichier de r\xE8gle de langue de sortie LLM : {{error}}",
      "Invalid command. Available subcommands:": "Commande invalide. Sous-commandes disponibles :",
      "Available subcommands:": "Sous-commandes disponibles :",
      "To request additional UI language packs, please open an issue on GitHub.": "Pour demander des packs de langue d'interface suppl\xE9mentaires, veuillez ouvrir un ticket sur GitHub.",
      "Available options:": "Options disponibles :",
      "Set UI language to {{name}}": "D\xE9finir la langue de l'interface sur {{name}}",
      // ============================================================================
      // Commandes - Mode d'approbation
      // ============================================================================
      "Tool Approval Mode": "Mode d'approbation des outils",
      "Current approval mode: {{mode}}": "Mode d'approbation actuel : {{mode}}",
      "Available approval modes:": "Modes d'approbation disponibles :",
      "Approval mode changed to: {{mode}}": "Mode d'approbation chang\xE9 en : {{mode}}",
      "Approval mode changed to: {{mode}} (saved to {{scope}} settings{{location}})": "Mode d'approbation chang\xE9 en : {{mode}} (enregistr\xE9 dans les param\xE8tres {{scope}}{{location}})",
      "Usage: /approval-mode <mode> [--session|--user|--project]": "Utilisation : /approval-mode <mode> [--session|--user|--project]",
      "Scope subcommands do not accept additional arguments.": "Les sous-commandes de port\xE9e n'acceptent pas d'arguments suppl\xE9mentaires.",
      "Plan mode - Analyze only, do not modify files or execute commands": "Mode plan - Analyser uniquement, ne pas modifier les fichiers ni ex\xE9cuter des commandes",
      "Default mode - Require approval for file edits or shell commands": "Mode par d\xE9faut - Demander l'approbation pour les modifications de fichiers ou les commandes shell",
      "Auto-edit mode - Automatically approve file edits": "Mode \xE9dition automatique - Approuver automatiquement les modifications de fichiers",
      "YOLO mode - Automatically approve all tools": "Mode YOLO - Approuver automatiquement tous les outils",
      "{{mode}} mode": "Mode {{mode}}",
      "Settings service is not available; unable to persist the approval mode.": "Le service de param\xE8tres n'est pas disponible ; impossible de persister le mode d'approbation.",
      "Failed to save approval mode: {{error}}": "\xC9chec de la sauvegarde du mode d'approbation : {{error}}",
      "Failed to change approval mode: {{error}}": "\xC9chec du changement du mode d'approbation : {{error}}",
      "Apply to current session only (temporary)": "Appliquer uniquement \xE0 la session actuelle (temporaire)",
      "Persist for this project/workspace": "Persister pour ce projet/espace de travail",
      "Persist for this user on this machine": "Persister pour cet utilisateur sur cette machine",
      "Analyze only, do not modify files or execute commands": "Analyser uniquement, ne pas modifier les fichiers ni ex\xE9cuter des commandes",
      "Require approval for file edits or shell commands": "Demander l'approbation pour les modifications de fichiers ou les commandes shell",
      "Automatically approve file edits": "Approuver automatiquement les modifications de fichiers",
      "Automatically approve all tools": "Approuver automatiquement tous les outils",
      "Workspace approval mode exists and takes priority. User-level change will have no effect.": "Un mode d'approbation d'espace de travail existe et a la priorit\xE9. La modification au niveau utilisateur n'aura aucun effet.",
      "Apply To": "Appliquer \xE0",
      "Workspace Settings": "Param\xE8tres de l'espace de travail",
      // ============================================================================
      // Commandes - Mémoire
      // ============================================================================
      "Commands for interacting with memory.": "Commandes pour interagir avec la m\xE9moire.",
      "Show the current memory contents.": "Afficher le contenu actuel de la m\xE9moire.",
      "Show project-level memory contents.": "Afficher le contenu de la m\xE9moire au niveau du projet.",
      "Show global memory contents.": "Afficher le contenu de la m\xE9moire globale.",
      "Add content to project-level memory.": "Ajouter du contenu \xE0 la m\xE9moire au niveau du projet.",
      "Add content to global memory.": "Ajouter du contenu \xE0 la m\xE9moire globale.",
      "Refresh the memory from the source.": "Actualiser la m\xE9moire depuis la source.",
      "Usage: /memory add --project <text to remember>": "Utilisation : /memory add --project <texte \xE0 m\xE9moriser>",
      "Usage: /memory add --global <text to remember>": "Utilisation : /memory add --global <texte \xE0 m\xE9moriser>",
      'Attempting to save to project memory: "{{text}}"': 'Tentative de sauvegarde dans la m\xE9moire du projet : "{{text}}"',
      'Attempting to save to global memory: "{{text}}"': 'Tentative de sauvegarde dans la m\xE9moire globale : "{{text}}"',
      "Current memory content from {{count}} file(s):": "Contenu actuel de la m\xE9moire depuis {{count}} fichier(s) :",
      "Memory is currently empty.": "La m\xE9moire est actuellement vide.",
      "Project memory file not found or is currently empty.": "Fichier de m\xE9moire du projet introuvable ou actuellement vide.",
      "Global memory file not found or is currently empty.": "Fichier de m\xE9moire globale introuvable ou actuellement vide.",
      "Global memory is currently empty.": "La m\xE9moire globale est actuellement vide.",
      "Global memory content:\n\n---\n{{content}}\n---": "Contenu de la m\xE9moire globale :\n\n---\n{{content}}\n---",
      "Project memory content from {{path}}:\n\n---\n{{content}}\n---": "Contenu de la m\xE9moire du projet depuis {{path}} :\n\n---\n{{content}}\n---",
      "Project memory is currently empty.": "La m\xE9moire du projet est actuellement vide.",
      "Refreshing memory from source files...": "Actualisation de la m\xE9moire depuis les fichiers sources...",
      "Add content to the memory. Use --global for global memory or --project for project memory.": "Ajouter du contenu \xE0 la m\xE9moire. Utilisez --global pour la m\xE9moire globale ou --project pour la m\xE9moire du projet.",
      "Usage: /memory add [--global|--project] <text to remember>": "Utilisation : /memory add [--global|--project] <texte \xE0 m\xE9moriser>",
      'Attempting to save to memory {{scope}}: "{{fact}}"': 'Tentative de sauvegarde dans la m\xE9moire {{scope}} : "{{fact}}"',
      // ============================================================================
      // Commandes - MCP
      // ============================================================================
      "Authenticate with an OAuth-enabled MCP server": "Authentifier avec un serveur MCP compatible OAuth",
      "List configured MCP servers and tools": "Lister les serveurs MCP et outils configur\xE9s",
      "Restarts MCP servers.": "Red\xE9marre les serveurs MCP.",
      "Open MCP management dialog": "Ouvrir le dialogue de gestion MCP",
      "Could not retrieve tool registry.": "Impossible de r\xE9cup\xE9rer le registre des outils.",
      "No MCP servers configured with OAuth authentication.": "Aucun serveur MCP configur\xE9 avec l'authentification OAuth.",
      "MCP servers with OAuth authentication:": "Serveurs MCP avec authentification OAuth :",
      "Use /mcp auth <server-name> to authenticate.": "Utilisez /mcp auth <nom-serveur> pour vous authentifier.",
      "MCP server '{{name}}' not found.": "Serveur MCP '{{name}}' introuvable.",
      "Successfully authenticated and refreshed tools for '{{name}}'.": "Authentification r\xE9ussie et outils actualis\xE9s pour '{{name}}'.",
      "Failed to authenticate with MCP server '{{name}}': {{error}}": "\xC9chec de l'authentification avec le serveur MCP '{{name}}' : {{error}}",
      "Re-discovering tools from '{{name}}'...": "Red\xE9couverte des outils depuis '{{name}}'...",
      "Discovered {{count}} tool(s) from '{{name}}'.": "{{count}} outil(s) d\xE9couvert(s) depuis '{{name}}'.",
      "Authentication complete. Returning to server details...": "Authentification termin\xE9e. Retour aux d\xE9tails du serveur...",
      "Authentication successful.": "Authentification r\xE9ussie.",
      "If the browser does not open, copy and paste this URL into your browser:": "Si le navigateur ne s'ouvre pas, copiez et collez cette URL dans votre navigateur :",
      "Make sure to copy the COMPLETE URL - it may wrap across multiple lines.": "Assurez-vous de copier l'URL COMPL\xC8TE - elle peut s'\xE9tendre sur plusieurs lignes.",
      // ============================================================================
      // Boîte de dialogue de gestion MCP
      // ============================================================================
      "Manage MCP servers": "G\xE9rer les serveurs MCP",
      "Server Detail": "D\xE9tail du serveur",
      "Disable Server": "D\xE9sactiver le serveur",
      Tools: "Outils",
      "Tool Detail": "D\xE9tail de l'outil",
      "MCP Management": "Gestion MCP",
      "Loading...": "Chargement...",
      "Unknown step": "\xC9tape inconnue",
      "Esc to back": "\xC9chap pour revenir",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close": "\u2191\u2193 pour naviguer \xB7 Entr\xE9e pour s\xE9lectionner \xB7 \xC9chap pour fermer",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back": "\u2191\u2193 pour naviguer \xB7 Entr\xE9e pour s\xE9lectionner \xB7 \xC9chap pour revenir",
      "\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back": "\u2191\u2193 pour naviguer \xB7 Entr\xE9e pour confirmer \xB7 \xC9chap pour revenir",
      "User Settings (global)": "Param\xE8tres utilisateur (global)",
      "Workspace Settings (project-specific)": "Param\xE8tres espace de travail (sp\xE9cifique au projet)",
      "Disable server:": "D\xE9sactiver le serveur :",
      "Select where to add the server to the exclude list:": "S\xE9lectionnez o\xF9 ajouter le serveur \xE0 la liste d'exclusion :",
      "Press Enter to confirm, Esc to cancel": "Appuyez sur Entr\xE9e pour confirmer, \xC9chap pour annuler",
      "View tools": "Voir les outils",
      Reconnect: "Reconnecter",
      Enable: "Activer",
      Disable: "D\xE9sactiver",
      Authenticate: "Authentifier",
      "Re-authenticate": "R\xE9authentifier",
      "Clear Authentication": "Effacer l'authentification",
      "Server:": "Serveur :",
      "Command:": "Commande :",
      "Working Directory:": "R\xE9pertoire de travail :",
      "Capabilities:": "Capacit\xE9s :",
      "No server selected": "Aucun serveur s\xE9lectionn\xE9",
      prompts: "invites",
      "(disabled)": "(d\xE9sactiv\xE9)",
      "Error:": "Erreur :",
      tool: "outil",
      tools: "outils",
      connected: "connect\xE9",
      connecting: "connexion en cours",
      disconnected: "d\xE9connect\xE9",
      "User MCPs": "MCPs utilisateur",
      "Project MCPs": "MCPs projet",
      "Extension MCPs": "MCPs d'extension",
      server: "serveur",
      servers: "serveurs",
      "Add MCP servers to your settings to get started.": "Ajoutez des serveurs MCP \xE0 vos param\xE8tres pour commencer.",
      "Run qwen --debug to see error logs": "Ex\xE9cutez qwen --debug pour voir les journaux d'erreurs",
      "OAuth Authentication": "Authentification OAuth",
      "Press Enter to start authentication, Esc to go back": "Appuyez sur Entr\xE9e pour d\xE9marrer l'authentification, \xC9chap pour revenir",
      "Authenticating... Please complete the login in your browser.": "Authentification... Veuillez compl\xE9ter la connexion dans votre navigateur.",
      "Press Enter or Esc to go back": "Appuyez sur Entr\xE9e ou \xC9chap pour revenir",
      "No tools available for this server.": "Aucun outil disponible pour ce serveur.",
      destructive: "destructif",
      "read-only": "lecture seule",
      "open-world": "monde ouvert",
      idempotent: "idempotent",
      "Tools for {{name}}": "Outils pour {{name}}",
      "Tools for {{serverName}}": "Outils pour {{serverName}}",
      "{{current}}/{{total}}": "{{current}}/{{total}}",
      required: "requis",
      Type: "Type",
      Enum: "Enum",
      Parameters: "Param\xE8tres",
      "No tool selected": "Aucun outil s\xE9lectionn\xE9",
      Annotations: "Annotations",
      Title: "Titre",
      "Read Only": "Lecture seule",
      Destructive: "Destructif",
      Idempotent: "Idempotent",
      "Open World": "Monde ouvert",
      Server: "Serveur",
      "{{count}} invalid tools": "{{count}} outils invalides",
      invalid: "invalide",
      "invalid: {{reason}}": "invalide : {{reason}}",
      "missing name": "nom manquant",
      "missing description": "description manquante",
      "(unnamed)": "(sans nom)",
      "Warning: This tool cannot be called by the LLM": "Avertissement : Cet outil ne peut pas \xEAtre appel\xE9 par le LLM",
      Reason: "Raison",
      "Tools must have both name and description to be used by the LLM.": "Les outils doivent avoir un nom et une description pour \xEAtre utilis\xE9s par le LLM.",
      // ============================================================================
      // Commandes - Chat
      // ============================================================================
      "Manage conversation history.": "G\xE9rer l'historique des conversations.",
      "List saved conversation checkpoints": "Lister les points de contr\xF4le de conversation sauvegard\xE9s",
      "No saved conversation checkpoints found.": "Aucun point de contr\xF4le de conversation sauvegard\xE9 trouv\xE9.",
      "List of saved conversations:": "Liste des conversations sauvegard\xE9es :",
      "Note: Newest last, oldest first": "Note : Du plus r\xE9cent au plus ancien en dernier, du plus ancien en premier",
      "Save the current conversation as a checkpoint. Usage: /chat save <tag>": "Sauvegarder la conversation actuelle comme point de contr\xF4le. Utilisation : /chat save <\xE9tiquette>",
      "Missing tag. Usage: /chat save <tag>": "\xC9tiquette manquante. Utilisation : /chat save <\xE9tiquette>",
      "Delete a conversation checkpoint. Usage: /chat delete <tag>": "Supprimer un point de contr\xF4le de conversation. Utilisation : /chat delete <\xE9tiquette>",
      "Missing tag. Usage: /chat delete <tag>": "\xC9tiquette manquante. Utilisation : /chat delete <\xE9tiquette>",
      "Conversation checkpoint '{{tag}}' has been deleted.": "Le point de contr\xF4le de conversation '{{tag}}' a \xE9t\xE9 supprim\xE9.",
      "Error: No checkpoint found with tag '{{tag}}'.": "Erreur : Aucun point de contr\xF4le trouv\xE9 avec l'\xE9tiquette '{{tag}}'.",
      "Resume a conversation from a checkpoint. Usage: /chat resume <tag>": "Reprendre une conversation depuis un point de contr\xF4le. Utilisation : /chat resume <\xE9tiquette>",
      "Missing tag. Usage: /chat resume <tag>": "\xC9tiquette manquante. Utilisation : /chat resume <\xE9tiquette>",
      "No saved checkpoint found with tag: {{tag}}.": "Aucun point de contr\xF4le sauvegard\xE9 trouv\xE9 avec l'\xE9tiquette : {{tag}}.",
      "A checkpoint with the tag {{tag}} already exists. Do you want to overwrite it?": "Un point de contr\xF4le avec l'\xE9tiquette {{tag}} existe d\xE9j\xE0. Voulez-vous l'\xE9craser ?",
      "No chat client available to save conversation.": "Aucun client de chat disponible pour sauvegarder la conversation.",
      "Conversation checkpoint saved with tag: {{tag}}.": "Point de contr\xF4le de conversation sauvegard\xE9 avec l'\xE9tiquette : {{tag}}.",
      "No conversation found to save.": "Aucune conversation trouv\xE9e \xE0 sauvegarder.",
      "No chat client available to share conversation.": "Aucun client de chat disponible pour partager la conversation.",
      "Invalid file format. Only .md and .json are supported.": "Format de fichier invalide. Seuls .md et .json sont pris en charge.",
      "Error sharing conversation: {{error}}": "Erreur lors du partage de la conversation : {{error}}",
      "Conversation shared to {{filePath}}": "Conversation partag\xE9e vers {{filePath}}",
      "No conversation found to share.": "Aucune conversation trouv\xE9e \xE0 partager.",
      "Share the current conversation to a markdown or json file. Usage: /chat share <file>": "Partager la conversation actuelle vers un fichier markdown ou json. Utilisation : /chat share <fichier>",
      // ============================================================================
      // Commandes - Résumé
      // ============================================================================
      "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md": "G\xE9n\xE9rer un r\xE9sum\xE9 du projet et l'enregistrer dans .qwen/PROJECT_SUMMARY.md",
      "No chat client available to generate summary.": "Aucun client de chat disponible pour g\xE9n\xE9rer le r\xE9sum\xE9.",
      "Already generating summary, wait for previous request to complete": "G\xE9n\xE9ration de r\xE9sum\xE9 d\xE9j\xE0 en cours, attendez que la demande pr\xE9c\xE9dente se termine",
      "No conversation found to summarize.": "Aucune conversation trouv\xE9e \xE0 r\xE9sumer.",
      "Failed to generate project context summary: {{error}}": "\xC9chec de la g\xE9n\xE9ration du r\xE9sum\xE9 du contexte du projet : {{error}}",
      "Saved project summary to {{filePathForDisplay}}.": "R\xE9sum\xE9 du projet enregistr\xE9 dans {{filePathForDisplay}}.",
      "Saving project summary...": "Enregistrement du r\xE9sum\xE9 du projet...",
      "Generating project summary...": "G\xE9n\xE9ration du r\xE9sum\xE9 du projet...",
      "Failed to generate summary - no text content received from LLM response": "\xC9chec de la g\xE9n\xE9ration du r\xE9sum\xE9 - aucun contenu texte re\xE7u de la r\xE9ponse LLM",
      // ============================================================================
      // Commandes - Modèle
      // ============================================================================
      "Switch the model for this session (--fast for suggestion model)": "Changer le mod\xE8le pour cette session (--fast pour le mod\xE8le de suggestion)",
      "Set a lighter model for prompt suggestions and speculative execution": "D\xE9finir un mod\xE8le plus l\xE9ger pour les suggestions d'invite et l'ex\xE9cution sp\xE9culative",
      "Content generator configuration not available.": "Configuration du g\xE9n\xE9rateur de contenu non disponible.",
      "Authentication type not available.": "Type d'authentification non disponible.",
      "No models available for the current authentication type ({{authType}}).": "Aucun mod\xE8le disponible pour le type d'authentification actuel ({{authType}}).",
      // ============================================================================
      // Commandes - Effacer
      // ============================================================================
      "Starting a new session, resetting chat, and clearing terminal.": "D\xE9marrage d'une nouvelle session, r\xE9initialisation du chat et effacement du terminal.",
      "Starting a new session and clearing.": "D\xE9marrage d'une nouvelle session et effacement.",
      // ============================================================================
      // Commandes - Compresser
      // ============================================================================
      "Already compressing, wait for previous request to complete": "Compression d\xE9j\xE0 en cours, attendez que la demande pr\xE9c\xE9dente se termine",
      "Failed to compress chat history.": "\xC9chec de la compression de l'historique du chat.",
      "Failed to compress chat history: {{error}}": "\xC9chec de la compression de l'historique du chat : {{error}}",
      "Compressing chat history": "Compression de l'historique du chat",
      "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.": "L'historique du chat a \xE9t\xE9 compress\xE9 de {{originalTokens}} \xE0 {{newTokens}} tokens.",
      "Compression was not beneficial for this history size.": "La compression n'\xE9tait pas b\xE9n\xE9fique pour cette taille d'historique.",
      "Chat history compression did not reduce size. This may indicate issues with the compression prompt.": "La compression de l'historique du chat n'a pas r\xE9duit la taille. Cela peut indiquer des probl\xE8mes avec l'invite de compression.",
      "Could not compress chat history due to a token counting error.": "Impossible de compresser l'historique du chat en raison d'une erreur de comptage de tokens.",
      "Chat history is already compressed.": "L'historique du chat est d\xE9j\xE0 compress\xE9.",
      // ============================================================================
      // Commandes - Répertoire
      // ============================================================================
      "Configuration is not available.": "Configuration non disponible.",
      "Please provide at least one path to add.": "Veuillez fournir au moins un chemin \xE0 ajouter.",
      "The /directory add command is not supported in restrictive sandbox profiles. Please use --include-directories when starting the session instead.": "La commande /directory add n'est pas prise en charge dans les profils de bac \xE0 sable restrictifs. Utilisez plut\xF4t --include-directories lors du d\xE9marrage de la session.",
      "Error adding '{{path}}': {{error}}": "Erreur lors de l'ajout de '{{path}}' : {{error}}",
      "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}": "Fichiers QWEN.md ajout\xE9s avec succ\xE8s depuis les r\xE9pertoires suivants s'ils existent :\n- {{directories}}",
      "Error refreshing memory: {{error}}": "Erreur lors de l'actualisation de la m\xE9moire : {{error}}",
      "Successfully added directories:\n- {{directories}}": "R\xE9pertoires ajout\xE9s avec succ\xE8s :\n- {{directories}}",
      "Current workspace directories:\n{{directories}}": "R\xE9pertoires actuels de l'espace de travail :\n{{directories}}",
      // ============================================================================
      // Commandes - Documentation
      // ============================================================================
      "Please open the following URL in your browser to view the documentation:\n{{url}}": "Veuillez ouvrir l'URL suivante dans votre navigateur pour voir la documentation :\n{{url}}",
      "Opening documentation in your browser: {{url}}": "Ouverture de la documentation dans votre navigateur : {{url}}",
      // ============================================================================
      // Boîtes de dialogue - Confirmation d'outil
      // ============================================================================
      "Do you want to proceed?": "Voulez-vous continuer ?",
      "Yes, allow once": "Oui, autoriser une fois",
      "Allow always": "Toujours autoriser",
      Yes: "Oui",
      No: "Non",
      "No (esc)": "Non (\xE9chap)",
      "Yes, allow always for this session": "Oui, toujours autoriser pour cette session",
      "Modify in progress:": "Modification en cours :",
      "Save and close external editor to continue": "Enregistrez et fermez l'\xE9diteur externe pour continuer",
      "Apply this change?": "Appliquer cette modification ?",
      "Yes, allow always": "Oui, toujours autoriser",
      "Modify with external editor": "Modifier avec l'\xE9diteur externe",
      "No, suggest changes (esc)": "Non, sugg\xE9rer des modifications (\xE9chap)",
      "Allow execution of: '{{command}}'?": "Autoriser l'ex\xE9cution de : '{{command}}' ?",
      "Yes, allow always ...": "Oui, toujours autoriser ...",
      "Always allow in this project": "Toujours autoriser dans ce projet",
      "Always allow {{action}} in this project": "Toujours autoriser {{action}} dans ce projet",
      "Always allow for this user": "Toujours autoriser pour cet utilisateur",
      "Always allow {{action}} for this user": "Toujours autoriser {{action}} pour cet utilisateur",
      "Yes, restore previous mode ({{mode}})": "Oui, restaurer le mode pr\xE9c\xE9dent ({{mode}})",
      "Yes, and auto-accept edits": "Oui, et accepter automatiquement les modifications",
      "Yes, and manually approve edits": "Oui, et approuver manuellement les modifications",
      "No, keep planning (esc)": "Non, continuer la planification (\xE9chap)",
      "URLs to fetch:": "URLs \xE0 r\xE9cup\xE9rer :",
      "MCP Server: {{server}}": "Serveur MCP : {{server}}",
      "Tool: {{tool}}": "Outil : {{tool}}",
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?': `Autoriser l'ex\xE9cution de l'outil MCP "{{tool}}" depuis le serveur "{{server}}" ?`,
      'Yes, always allow tool "{{tool}}" from server "{{server}}"': `Oui, toujours autoriser l'outil "{{tool}}" depuis le serveur "{{server}}"`,
      'Yes, always allow all tools from server "{{server}}"': 'Oui, toujours autoriser tous les outils depuis le serveur "{{server}}"',
      // ============================================================================
      // Boîtes de dialogue - Confirmation shell
      // ============================================================================
      "Shell Command Execution": "Ex\xE9cution de commande shell",
      "A custom command wants to run the following shell commands:": "Une commande personnalis\xE9e veut ex\xE9cuter les commandes shell suivantes :",
      // ============================================================================
      // Boîtes de dialogue - Quota Pro
      // ============================================================================
      "Pro quota limit reached for {{model}}.": "Limite de quota Pro atteinte pour {{model}}.",
      "Change auth (executes the /auth command)": "Changer l'authentification (ex\xE9cute la commande /auth)",
      "Continue with {{model}}": "Continuer avec {{model}}",
      // ============================================================================
      // Boîtes de dialogue - Bienvenue
      // ============================================================================
      "Current Plan:": "Plan actuel :",
      "Progress: {{done}}/{{total}} tasks completed": "Progression : {{done}}/{{total}} t\xE2ches termin\xE9es",
      ", {{inProgress}} in progress": ", {{inProgress}} en cours",
      "Pending Tasks:": "T\xE2ches en attente :",
      "What would you like to do?": "Que souhaitez-vous faire ?",
      "Choose how to proceed with your session:": "Choisissez comment poursuivre votre session :",
      "Start new chat session": "D\xE9marrer une nouvelle session de chat",
      "Continue previous conversation": "Continuer la conversation pr\xE9c\xE9dente",
      "\u{1F44B} Welcome back! (Last updated: {{timeAgo}})": "\u{1F44B} Bon retour ! (Derni\xE8re mise \xE0 jour : {{timeAgo}})",
      "\u{1F3AF} Overall Goal:": "\u{1F3AF} Objectif global :",
      // ============================================================================
      // Boîtes de dialogue - Authentification
      // ============================================================================
      "Get started": "Commencer",
      "Select Authentication Method": "S\xE9lectionner la m\xE9thode d'authentification",
      "OpenAI API key is required to use OpenAI authentication.": "Une cl\xE9 API OpenAI est requise pour utiliser l'authentification OpenAI.",
      "You must select an auth method to proceed. Press Ctrl+C again to exit.": "Vous devez s\xE9lectionner une m\xE9thode d'authentification pour continuer. Appuyez \xE0 nouveau sur Ctrl+C pour quitter.",
      "Terms of Services and Privacy Notice": "Conditions d'utilisation et avis de confidentialit\xE9",
      "Qwen OAuth": "Qwen OAuth",
      "Discontinued \u2014 switch to Coding Plan or API Key": "Abandonn\xE9 \u2014 passez \xE0 Coding Plan ou API Key",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch provider.": "Le niveau gratuit Qwen OAuth a \xE9t\xE9 abandonn\xE9 le 2026-04-15. Ex\xE9cutez /auth pour changer de fournisseur.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead.": "Le niveau gratuit Qwen OAuth a \xE9t\xE9 abandonn\xE9 le 2026-04-15. Veuillez s\xE9lectionner Coding Plan ou API Key.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.": "Le niveau gratuit de Qwen OAuth a \xE9t\xE9 abandonn\xE9 le 2026-04-15. Veuillez s\xE9lectionner un mod\xE8le d'un autre fournisseur ou ex\xE9cuter /auth pour changer.",
      "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n": "\n\u26A0 Le niveau gratuit Qwen OAuth a \xE9t\xE9 abandonn\xE9 le 2026-04-15. Veuillez s\xE9lectionner une autre option.\n",
      "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models": "Payant \xB7 Jusqu'\xE0 6 000 requ\xEAtes/5h \xB7 Tous les mod\xE8les Alibaba Cloud Coding Plan",
      "Alibaba Cloud Coding Plan": "Plan de codage Alibaba Cloud",
      "Bring your own API key": "Apportez votre propre cl\xE9 API",
      "Browser-based authentication with third-party providers (e.g. OpenRouter, ModelScope)": "Authentification bas\xE9e sur le navigateur avec des fournisseurs tiers (par exemple OpenRouter, ModelScope)",
      "API-KEY": "CL\xC9-API",
      "Use coding plan credentials or your own api-keys/providers.": "Utilisez les identifiants du plan de codage ou vos propres cl\xE9s API/fournisseurs.",
      OpenAI: "OpenAI",
      "Failed to login. Message: {{message}}": "\xC9chec de la connexion. Message : {{message}}",
      "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.": "L'authentification est impos\xE9e \xE0 {{enforcedType}}, mais vous utilisez actuellement {{currentType}}.",
      "Qwen OAuth authentication timed out. Please try again.": "L'authentification Qwen OAuth a expir\xE9. Veuillez r\xE9essayer.",
      "Qwen OAuth authentication cancelled.": "Authentification Qwen OAuth annul\xE9e.",
      "Qwen OAuth Authentication": "Authentification Qwen OAuth",
      "Please visit this URL to authorize:": "Veuillez visiter cette URL pour autoriser :",
      "Or scan the QR code below:": "Ou scannez le QR code ci-dessous :",
      "Waiting for authorization": "En attente d'autorisation",
      "Time remaining:": "Temps restant :",
      "(Press ESC or CTRL+C to cancel)": "(Appuyez sur \xC9CHAP ou CTRL+C pour annuler)",
      "Qwen OAuth Authentication Timeout": "D\xE9lai d'authentification Qwen OAuth",
      "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.": "Token OAuth expir\xE9 (plus de {{seconds}} secondes). Veuillez s\xE9lectionner \xE0 nouveau la m\xE9thode d'authentification.",
      "Press any key to return to authentication type selection.": "Appuyez sur n'importe quelle touche pour revenir \xE0 la s\xE9lection du type d'authentification.",
      "Waiting for Qwen OAuth authentication...": "En attente de l'authentification 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.": "Remarque : Votre cl\xE9 API existante dans settings.json ne sera pas effac\xE9e lors de l'utilisation de Qwen OAuth. Vous pouvez revenir \xE0 l'authentification OpenAI plus tard si n\xE9cessaire.",
      "Note: Your existing API key will not be cleared when using Qwen OAuth.": "Remarque : Votre cl\xE9 API existante ne sera pas effac\xE9e lors de l'utilisation de Qwen OAuth.",
      "Authentication timed out. Please try again.": "L'authentification a expir\xE9. Veuillez r\xE9essayer.",
      "Waiting for auth... (Press ESC or CTRL+C to cancel)": "En attente d'authentification... (Appuyez sur \xC9CHAP ou CTRL+C pour annuler)",
      "Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.": "Cl\xE9 API manquante pour l'authentification compatible OpenAI. D\xE9finissez settings.security.auth.apiKey ou la variable d'environnement {{envKeyHint}}.",
      "{{envKeyHint}} environment variable not found.": "Variable d'environnement {{envKeyHint}} introuvable.",
      "{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.": "Variable d'environnement {{envKeyHint}} introuvable. Veuillez la d\xE9finir dans votre fichier .env ou les variables d'environnement.",
      "{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.": "Variable d'environnement {{envKeyHint}} introuvable (ou d\xE9finissez settings.security.auth.apiKey). Veuillez la d\xE9finir dans votre fichier .env ou les variables d'environnement.",
      "Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.": "Cl\xE9 API manquante pour l'authentification compatible OpenAI. D\xE9finissez la variable d'environnement {{envKeyHint}}.",
      "Anthropic provider missing required baseUrl in modelProviders[].baseUrl.": "Le fournisseur Anthropic manque le baseUrl requis dans modelProviders[].baseUrl.",
      "ANTHROPIC_BASE_URL environment variable not found.": "Variable d'environnement ANTHROPIC_BASE_URL introuvable.",
      "Invalid auth method selected.": "M\xE9thode d'authentification invalide s\xE9lectionn\xE9e.",
      "Failed to authenticate. Message: {{message}}": "\xC9chec de l'authentification. Message : {{message}}",
      "Authenticated successfully with {{authType}} credentials.": "Authentification r\xE9ussie avec les identifiants {{authType}}.",
      'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}': 'Valeur QWEN_DEFAULT_AUTH_TYPE invalide : "{{value}}". Valeurs valides : {{validValues}}',
      "OpenAI Configuration Required": "Configuration OpenAI requise",
      "Please enter your OpenAI configuration. You can get an API key from": "Veuillez entrer votre configuration OpenAI. Vous pouvez obtenir une cl\xE9 API depuis",
      "API Key:": "Cl\xE9 API :",
      "Invalid credentials: {{errorMessage}}": "Identifiants invalides : {{errorMessage}}",
      "Failed to validate credentials": "\xC9chec de la validation des identifiants",
      "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel": "Appuyez sur Entr\xE9e pour continuer, Tab/\u2191\u2193 pour naviguer, \xC9chap pour annuler",
      // ============================================================================
      // Boîtes de dialogue - Modèle
      // ============================================================================
      "Select Model": "S\xE9lectionner un mod\xE8le",
      "(Press Esc to close)": "(Appuyez sur \xC9chap pour fermer)",
      "Current (effective) configuration": "Configuration actuelle (effective)",
      AuthType: "Type d'auth",
      "API Key": "Cl\xE9 API",
      unset: "non d\xE9fini",
      "(default)": "(par d\xE9faut)",
      "(set)": "(d\xE9fini)",
      "(not set)": "(non d\xE9fini)",
      Modality: "Modalit\xE9",
      "Context Window": "Fen\xEAtre de contexte",
      text: "texte",
      "text-only": "texte uniquement",
      image: "image",
      pdf: "pdf",
      audio: "audio",
      video: "vid\xE9o",
      "not set": "non d\xE9fini",
      none: "aucun",
      unknown: "inconnu",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "\xC9chec du changement de mod\xE8le vers '{{modelId}}'.\n\n{{error}}",
      "Qwen 3.6 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.6 Plus \u2014 mod\xE8le hybride efficace avec des performances de codage de pointe",
      "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)": "Le dernier mod\xE8le Qwen Vision d'Alibaba Cloud ModelStudio (version : qwen3-vl-plus-2025-09-23)",
      // ============================================================================
      // Boîtes de dialogue - Permissions
      // ============================================================================
      "Manage folder trust settings": "G\xE9rer les param\xE8tres de confiance des dossiers",
      "Manage permission rules": "G\xE9rer les r\xE8gles de permission",
      Allow: "Autoriser",
      Ask: "Demander",
      Deny: "Refuser",
      Workspace: "Espace de travail",
      "Qwen Code won't ask before using allowed tools.": "Qwen Code ne demandera pas avant d'utiliser les outils autoris\xE9s.",
      "Qwen Code will ask before using these tools.": "Qwen Code demandera avant d'utiliser ces outils.",
      "Qwen Code is not allowed to use denied tools.": "Qwen Code n'est pas autoris\xE9 \xE0 utiliser les outils refus\xE9s.",
      "Manage trusted directories for this workspace.": "G\xE9rer les r\xE9pertoires de confiance pour cet espace de travail.",
      "Any use of the {{tool}} tool": "Toute utilisation de l'outil {{tool}}",
      "{{tool}} commands matching '{{pattern}}'": "Commandes {{tool}} correspondant \xE0 '{{pattern}}'",
      "From user settings": "Depuis les param\xE8tres utilisateur",
      "From project settings": "Depuis les param\xE8tres du projet",
      "From session": "Depuis la session",
      "Project settings (local)": "Param\xE8tres du projet (local)",
      "Saved in .qwen/settings.local.json": "Enregistr\xE9 dans .qwen/settings.local.json",
      "Project settings": "Param\xE8tres du projet",
      "Checked in at .qwen/settings.json": "Valid\xE9 dans .qwen/settings.json",
      "User settings": "Param\xE8tres utilisateur",
      "Saved in at ~/.qwen/settings.json": "Enregistr\xE9 dans ~/.qwen/settings.json",
      "Add a new rule\u2026": "Ajouter une nouvelle r\xE8gle\u2026",
      "Add {{type}} permission rule": "Ajouter une r\xE8gle de permission {{type}}",
      "Permission rules are a tool name, optionally followed by a specifier in parentheses.": "Les r\xE8gles de permission sont un nom d'outil, suivi optionnellement d'un sp\xE9cificateur entre parenth\xE8ses.",
      "e.g.,": "ex.,",
      or: "ou",
      "Enter permission rule\u2026": "Entrer une r\xE8gle de permission\u2026",
      "Enter to submit \xB7 Esc to cancel": "Entr\xE9e pour soumettre \xB7 \xC9chap pour annuler",
      "Where should this rule be saved?": "O\xF9 cette r\xE8gle doit-elle \xEAtre enregistr\xE9e ?",
      "Enter to confirm \xB7 Esc to cancel": "Entr\xE9e pour confirmer \xB7 \xC9chap pour annuler",
      "Delete {{type}} rule?": "Supprimer la r\xE8gle {{type}} ?",
      "Are you sure you want to delete this permission rule?": "\xCAtes-vous s\xFBr de vouloir supprimer cette r\xE8gle de permission ?",
      "Permissions:": "Permissions :",
      "(\u2190/\u2192 or tab to cycle)": "(\u2190/\u2192 ou tab pour cycler)",
      "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel": "Appuyez sur \u2191\u2193 pour naviguer \xB7 Entr\xE9e pour s\xE9lectionner \xB7 Tapez pour rechercher \xB7 \xC9chap pour annuler",
      "Search\u2026": "Rechercher\u2026",
      "Use /trust to manage folder trust settings for this workspace.": "Utilisez /trust pour g\xE9rer les param\xE8tres de confiance des dossiers pour cet espace de travail.",
      "Add directory\u2026": "Ajouter un r\xE9pertoire\u2026",
      "Add directory to workspace": "Ajouter un r\xE9pertoire \xE0 l'espace de travail",
      "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.": "Qwen Code peut lire les fichiers dans l'espace de travail et effectuer des modifications lorsque l'acceptation automatique est activ\xE9e.",
      "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.": "Qwen Code pourra lire les fichiers dans ce r\xE9pertoire et effectuer des modifications lorsque l'acceptation automatique est activ\xE9e.",
      "Enter the path to the directory:": "Entrez le chemin vers le r\xE9pertoire :",
      "Enter directory path\u2026": "Entrez le chemin du r\xE9pertoire\u2026",
      "Tab to complete \xB7 Enter to add \xB7 Esc to cancel": "Tab pour compl\xE9ter \xB7 Entr\xE9e pour ajouter \xB7 \xC9chap pour annuler",
      "Remove directory?": "Supprimer le r\xE9pertoire ?",
      "Are you sure you want to remove this directory from the workspace?": "\xCAtes-vous s\xFBr de vouloir supprimer ce r\xE9pertoire de l'espace de travail ?",
      "  (Original working directory)": "  (R\xE9pertoire de travail d'origine)",
      "  (from settings)": "  (depuis les param\xE8tres)",
      "Directory does not exist.": "Le r\xE9pertoire n'existe pas.",
      "Path is not a directory.": "Le chemin n'est pas un r\xE9pertoire.",
      "This directory is already in the workspace.": "Ce r\xE9pertoire est d\xE9j\xE0 dans l'espace de travail.",
      "Already covered by existing directory: {{dir}}": "D\xE9j\xE0 couvert par le r\xE9pertoire existant : {{dir}}",
      // ============================================================================
      // Barre de statut
      // ============================================================================
      "Using:": "Utilisation :",
      "{{count}} open file": "{{count}} fichier ouvert",
      "{{count}} open files": "{{count}} fichiers ouverts",
      "(ctrl+g to view)": "(ctrl+g pour afficher)",
      "{{count}} {{name}} file": "{{count}} fichier {{name}}",
      "{{count}} {{name}} files": "{{count}} fichiers {{name}}",
      "{{count}} MCP server": "{{count}} serveur MCP",
      "{{count}} MCP servers": "{{count}} serveurs MCP",
      "{{count}} Blocked": "{{count}} bloqu\xE9(s)",
      "(ctrl+t to view)": "(ctrl+t pour afficher)",
      "(ctrl+t to toggle)": "(ctrl+t pour basculer)",
      "Press Ctrl+C again to exit.": "Appuyez \xE0 nouveau sur Ctrl+C pour quitter.",
      "Press Ctrl+D again to exit.": "Appuyez \xE0 nouveau sur Ctrl+D pour quitter.",
      "Press Esc again to clear.": "Appuyez \xE0 nouveau sur \xC9chap pour effacer.",
      // ============================================================================
      // Statut MCP
      // ============================================================================
      "No MCP servers configured.": "Aucun serveur MCP configur\xE9.",
      "\u23F3 MCP servers are starting up ({{count}} initializing)...": "\u23F3 Les serveurs MCP d\xE9marrent ({{count}} en initialisation)...",
      "Note: First startup may take longer. Tool availability will update automatically.": "Remarque : Le premier d\xE9marrage peut prendre plus de temps. La disponibilit\xE9 des outils se mettra \xE0 jour automatiquement.",
      "Configured MCP servers:": "Serveurs MCP configur\xE9s :",
      Ready: "Pr\xEAt",
      "Starting... (first startup may take longer)": "D\xE9marrage... (le premier d\xE9marrage peut prendre plus de temps)",
      Disconnected: "D\xE9connect\xE9",
      "{{count}} tool": "{{count}} outil",
      "{{count}} tools": "{{count}} outils",
      "{{count}} prompt": "{{count}} invite",
      "{{count}} prompts": "{{count}} invites",
      "(from {{extensionName}})": "(depuis {{extensionName}})",
      OAuth: "OAuth",
      "OAuth expired": "OAuth expir\xE9",
      "OAuth not authenticated": "OAuth non authentifi\xE9",
      "tools and prompts will appear when ready": "les outils et invites appara\xEEtront quand pr\xEAts",
      "{{count}} tools cached": "{{count}} outils mis en cache",
      "Tools:": "Outils :",
      "Parameters:": "Param\xE8tres :",
      "Prompts:": "Invites :",
      Blocked: "Bloqu\xE9",
      "\u{1F4A1} Tips:": "\u{1F4A1} Conseils :",
      Use: "Utilisez",
      "to show server and tool descriptions": "pour afficher les descriptions des serveurs et des outils",
      "to show tool parameter schemas": "pour afficher les sch\xE9mas de param\xE8tres des outils",
      "to hide descriptions": "pour masquer les descriptions",
      "to authenticate with OAuth-enabled servers": "pour authentifier avec des serveurs compatibles OAuth",
      Press: "Appuyez sur",
      "to toggle tool descriptions on/off": "pour activer/d\xE9sactiver les descriptions des outils",
      "Starting OAuth authentication for MCP server '{{name}}'...": "D\xE9marrage de l'authentification OAuth pour le serveur MCP '{{name}}'...",
      "Restarting MCP servers...": "Red\xE9marrage des serveurs MCP...",
      // ============================================================================
      // Conseils de démarrage
      // ============================================================================
      "Tips:": "Conseils :",
      "Use /compress when the conversation gets long to summarize history and free up context.": "Utilisez /compress quand la conversation devient longue pour r\xE9sumer l'historique et lib\xE9rer le contexte.",
      "Start a fresh idea with /clear or /new; the previous session stays available in history.": "Commencez une nouvelle id\xE9e avec /clear ou /new ; la session pr\xE9c\xE9dente reste disponible dans l'historique.",
      "Use /bug to submit issues to the maintainers when something goes off.": "Utilisez /bug pour soumettre des probl\xE8mes aux mainteneurs quand quelque chose ne va pas.",
      "Switch auth type quickly with /auth.": "Changez rapidement le type d'authentification avec /auth.",
      "You can run any shell commands from Qwen Code using ! (e.g. !ls).": "Vous pouvez ex\xE9cuter n'importe quelle commande shell depuis Qwen Code en utilisant ! (ex. !ls).",
      "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.": "Tapez / pour ouvrir le menu des commandes ; Tab autocompl\xE9te les commandes slash et les invites sauvegard\xE9es.",
      "You can resume a previous conversation by running qwen --continue or qwen --resume.": "Vous pouvez reprendre une conversation pr\xE9c\xE9dente en ex\xE9cutant qwen --continue ou qwen --resume.",
      "You can switch permission mode quickly with Shift+Tab or /approval-mode.": "Vous pouvez changer rapidement le mode de permission avec Maj+Tab ou /approval-mode.",
      "You can switch permission mode quickly with Tab or /approval-mode.": "Vous pouvez changer rapidement le mode de permission avec Tab ou /approval-mode.",
      "Try /insight to generate personalized insights from your chat history.": "Essayez /insight pour g\xE9n\xE9rer des insights personnalis\xE9s depuis votre historique de chat.",
      // ============================================================================
      // Écran de sortie / Stats
      // ============================================================================
      "Agent powering down. Goodbye!": "Agent en cours d'arr\xEAt. Au revoir !",
      "To continue this session, run": "Pour continuer cette session, ex\xE9cutez",
      "Interaction Summary": "R\xE9sum\xE9 de l'interaction",
      "Session ID:": "ID de session :",
      "Tool Calls:": "Appels d'outils :",
      "Success Rate:": "Taux de succ\xE8s :",
      "User Agreement:": "Accord de l'utilisateur :",
      reviewed: "r\xE9vis\xE9",
      "Code Changes:": "Modifications du code :",
      Performance: "Performance",
      "Wall Time:": "Temps r\xE9el :",
      "Agent Active:": "Agent actif :",
      "API Time:": "Temps API :",
      "Tool Time:": "Temps d'outil :",
      "Session Stats": "Stats de session",
      "Model Usage": "Utilisation du mod\xE8le",
      Reqs: "Req.",
      "Input Tokens": "Tokens d'entr\xE9e",
      "Output Tokens": "Tokens de sortie",
      "Savings Highlight:": "\xC9conomies notables :",
      "of input tokens were served from the cache, reducing costs.": "des tokens d'entr\xE9e ont \xE9t\xE9 servis depuis le cache, r\xE9duisant les co\xFBts.",
      "Tip: For a full token breakdown, run `/stats model`.": "Conseil : Pour une d\xE9composition compl\xE8te des tokens, ex\xE9cutez `/stats model`.",
      "Model Stats For Nerds": "Stats du mod\xE8le pour les geeks",
      "Tool Stats For Nerds": "Stats des outils pour les geeks",
      Metric: "M\xE9trique",
      API: "API",
      Requests: "Requ\xEAtes",
      Errors: "Erreurs",
      "Avg Latency": "Latence moyenne",
      Tokens: "Tokens",
      Total: "Total",
      Prompt: "Invite",
      Cached: "En cache",
      Thoughts: "R\xE9flexions",
      Tool: "Outil",
      Output: "Sortie",
      "No API calls have been made in this session.": "Aucun appel API n'a \xE9t\xE9 effectu\xE9 dans cette session.",
      "Tool Name": "Nom de l'outil",
      Calls: "Appels",
      "Success Rate": "Taux de succ\xE8s",
      "Avg Duration": "Dur\xE9e moyenne",
      "User Decision Summary": "R\xE9sum\xE9 des d\xE9cisions de l'utilisateur",
      "Total Reviewed Suggestions:": "Total des suggestions r\xE9vis\xE9es :",
      " \xBB Accepted:": " \xBB Accept\xE9es :",
      " \xBB Rejected:": " \xBB Rejet\xE9es :",
      " \xBB Modified:": " \xBB Modifi\xE9es :",
      " Overall Agreement Rate:": " Taux d'accord global :",
      "No tool calls have been made in this session.": "Aucun appel d'outil n'a \xE9t\xE9 effectu\xE9 dans cette session.",
      "Session start time is unavailable, cannot calculate stats.": "L'heure de d\xE9but de session est indisponible, impossible de calculer les stats.",
      // ============================================================================
      // Migration de format de commande
      // ============================================================================
      "Command Format Migration": "Migration du format de commande",
      "Found {{count}} TOML command file:": "Trouv\xE9 {{count}} fichier de commande TOML :",
      "Found {{count}} TOML command files:": "Trouv\xE9 {{count}} fichiers de commande TOML :",
      "Current tasks": "T\xE2ches actuelles",
      "... and {{count}} more": "... et {{count}} de plus",
      "The TOML format is deprecated. Would you like to migrate them to Markdown format?": "Le format TOML est obsol\xE8te. Souhaitez-vous les migrer vers le format Markdown ?",
      "(Backups will be created and original files will be preserved)": "(Des sauvegardes seront cr\xE9\xE9es et les fichiers originaux seront conserv\xE9s)",
      // ============================================================================
      // Phrases de chargement
      // ============================================================================
      "Waiting for user confirmation...": "En attente de la confirmation de l'utilisateur...",
      "(esc to cancel, {{time}})": "(\xE9chap pour annuler, {{time}})",
      // ============================================================================
      // Phrases de chargement amusantes
      // ============================================================================
      WITTY_LOADING_PHRASES: [
        "Je me sens chanceux",
        "Livraison d'excellence...",
        "Repeignant les empattements...",
        "Navigation dans le moisissure num\xE9rique...",
        "Consultation des esprits num\xE9riques...",
        "R\xE9ticuler les splines...",
        "R\xE9chauffement des hamsters IA...",
        "Consultation de la conque magique...",
        "G\xE9n\xE9ration d'une r\xE9plique spirituelle...",
        "Polissage des algorithmes...",
        "Ne pr\xE9cipitez pas la perfection (ni mon code)...",
        "Brassage de nouveaux octets...",
        "Comptage des \xE9lectrons...",
        "Engagement des processeurs cognitifs...",
        "V\xE9rification des erreurs de syntaxe dans l'univers...",
        "Un instant, optimisation de l'humour...",
        "M\xE9lange des chutes de r\xE9pliques...",
        "D\xE9m\xEAlage des r\xE9seaux de neurones...",
        "Compilation de la brillance...",
        "Chargement de wit.exe...",
        "Invocation du nuage de sagesse...",
        "Pr\xE9paration d'une r\xE9ponse spirituelle...",
        "Juste une seconde, je d\xE9bogue la r\xE9alit\xE9...",
        "Confusion des options...",
        "Accord des fr\xE9quences cosmiques...",
        "Cr\xE9ation d'une r\xE9ponse digne de votre patience...",
        "Compilation des 0 et des 1...",
        "R\xE9solution des d\xE9pendances... et des crises existentielles...",
        "D\xE9fragmentation des m\xE9moires... RAM et personnelles...",
        "Red\xE9marrage du module humoristique...",
        "Mise en cache de l'essentiel (surtout les m\xE8mes de chats)...",
        "Optimisation pour une vitesse ludicrous",
        "\xC9change de bits... ne le dites pas aux octets...",
        "Nettoyage de la m\xE9moire... je reviens...",
        "Assemblage des internets...",
        "Conversion de caf\xE9 en code...",
        "Mise \xE0 jour de la syntaxe de la r\xE9alit\xE9...",
        "Rec\xE2blage des synapses...",
        "Recherche d'un point-virgule \xE9gar\xE9...",
        "Graissage des rouages de la machine...",
        "Pr\xE9chauffage des serveurs...",
        "Calibrage du condensateur de flux...",
        "Engagement de l'entra\xEEnement de l'improbabilit\xE9...",
        "Canalisation de la Force...",
        "Alignement des \xE9toiles pour une r\xE9ponse optimale...",
        "Qu'il en soit ainsi pour nous tous...",
        "Chargement de la prochaine grande id\xE9e...",
        "Juste un moment, je suis dans la zone...",
        "Pr\xE9paration \xE0 vous \xE9blouir de brillance...",
        "Juste un instant, je peaufine mon esprit...",
        "Attendez, je cr\xE9e un chef-d'\u0153uvre...",
        "Juste une seconde, je d\xE9bogue l'univers...",
        "Juste un moment, j'aligne les pixels...",
        "Juste un instant, j'optimise l'humour...",
        "Juste un moment, j'accorde les algorithmes...",
        "Vitesse warp enclench\xE9e...",
        "Extraction de plus de cristaux de Dilithium...",
        "Pas de panique...",
        "Suivre le lapin blanc...",
        "La v\xE9rit\xE9 est l\xE0... quelque part...",
        "Souffler sur la cartouche...",
        "Chargement... Faites un tonneau !",
        "En attente du respawn...",
        "Finir la course de Kessel en moins de 12 parsecs...",
        "Le g\xE2teau n'est pas un mensonge, il charge juste encore...",
        "Bidouillage de l'\xE9cran de cr\xE9ation de personnage...",
        "Juste un moment, je cherche le bon m\xE8me...",
        "Appuyer sur 'A' pour continuer...",
        "Rassemblement de chats num\xE9riques...",
        "Polissage des pixels...",
        "Recherche d'un jeu de mots d'\xE9cran de chargement appropri\xE9...",
        "Vous distraire avec cette phrase spirituelle...",
        "Presque l\xE0... probablement...",
        "Nos hamsters travaillent aussi vite qu'ils peuvent...",
        "Donnant une tape dans le dos \xE0 Cloudy...",
        "Caressant le chat...",
        "Rickrolling mon patron...",
        "Je ne vais jamais vous abandonner, je ne vais jamais vous laisser tomber...",
        "Claquant la basse...",
        "Go\xFBtant les snozberries...",
        "Je vais jusqu'au bout, je vais \xE0 toute vitesse...",
        "Est-ce la vraie vie ? Est-ce juste une fantaisie ?...",
        "J'ai un bon pressentiment \xE0 ce sujet...",
        "Poking l'ours...",
        "Faire des recherches sur les derniers m\xE8mes...",
        "Trouver comment rendre \xE7a plus spirituel...",
        "Hmm... laissez-moi r\xE9fl\xE9chir...",
        "Comment appelle-t-on un poisson sans yeux ? Un posson...",
        "Pourquoi l'ordinateur est-il all\xE9 en th\xE9rapie ? Il avait trop d'octets...",
        "Pourquoi les programmeurs n'aiment pas la nature ? Elle a trop de bugs...",
        "Pourquoi les programmeurs pr\xE9f\xE8rent le mode sombre ? Parce que la lumi\xE8re attire les bugs...",
        "Pourquoi le d\xE9veloppeur est-il fauch\xE9 ? Parce qu'il a utilis\xE9 tout son cache...",
        "Que peut-on faire avec un crayon cass\xE9 ? Rien, c'est inutile...",
        "Application de la maintenance percussive...",
        "Recherche de la bonne orientation USB...",
        "S'assurer que la fum\xE9e magique reste \xE0 l'int\xE9rieur des c\xE2bles...",
        "Essai de quitter Vim...",
        "Mise en marche de la roue du hamster...",
        "Ce n'est pas un bug, c'est une fonctionnalit\xE9 non document\xE9e...",
        "Engage.",
        "Je reviendrai... avec une r\xE9ponse.",
        "Mon autre processus est un TARDIS...",
        "Communion avec l'esprit machine...",
        "Laisser les pens\xE9es mariner...",
        "Je viens de me souvenir o\xF9 j'ai mis mes cl\xE9s...",
        "Contemplation de l'orbe...",
        "J'ai vu des choses que vous ne croiriez pas... comme un utilisateur qui lit les messages de chargement.",
        "Initiation du regard pensif...",
        "Quel est le go\xFBter pr\xE9f\xE9r\xE9 d'un ordinateur ? Les microchips.",
        "Pourquoi les d\xE9veloppeurs Java portent-ils des lunettes ? Parce qu'ils ne C# pas.",
        "Chargement du laser... pew pew !",
        "Division par z\xE9ro... je plaisante !",
        "Recherche d'un superviseur... je veux dire, traitement.",
        "Faire du bip boop.",
        "Buffering... parce que m\xEAme les IAs ont besoin d'un moment.",
        "Enchev\xEAtrement de particules quantiques pour une r\xE9ponse plus rapide...",
        "Polissage du chrome... sur les algorithmes.",
        "N'\xEAtes-vous pas diverti ? (On y travaille !)",
        "Invocation des lutins de code... pour aider, bien s\xFBr.",
        "En attente de la tonalit\xE9 du modem...",
        "Recalibrage du sens de l'humour.",
        "Mon autre \xE9cran de chargement est encore plus dr\xF4le.",
        "Je suis presque s\xFBr qu'il y a un chat qui marche sur le clavier quelque part...",
        "Am\xE9lioration... Am\xE9lioration... Toujours en chargement.",
        "Ce n'est pas un bug, c'est une caract\xE9ristique... de cet \xE9cran de chargement.",
        "Avez-vous essay\xE9 de l'\xE9teindre et de le rallumer ? (L'\xE9cran de chargement, pas moi.)",
        "Construction de pyl\xF4nes suppl\xE9mentaires..."
      ],
      // ============================================================================
      // Paramètres d'extension - Saisie
      // ============================================================================
      "Enter value...": "Entrer une valeur...",
      "Enter sensitive value...": "Entrer une valeur sensible...",
      "Press Enter to submit, Escape to cancel": "Appuyez sur Entr\xE9e pour soumettre, \xC9chap pour annuler",
      // ============================================================================
      // Outil de migration de commandes
      // ============================================================================
      "Markdown file already exists: {{filename}}": "Le fichier Markdown existe d\xE9j\xE0 : {{filename}}",
      "TOML Command Format Deprecation Notice": "Avis d'obsolescence du format de commande TOML",
      "Found {{count}} command file(s) in TOML format:": "Trouv\xE9 {{count}} fichier(s) de commande au format TOML :",
      "The TOML format for commands is being deprecated in favor of Markdown format.": "Le format TOML pour les commandes est en cours d'abandon au profit du format Markdown.",
      "Markdown format is more readable and easier to edit.": "Le format Markdown est plus lisible et plus facile \xE0 modifier.",
      "You can migrate these files automatically using:": "Vous pouvez migrer ces fichiers automatiquement en utilisant :",
      "Or manually convert each file:": "Ou convertir chaque fichier manuellement :",
      'TOML: prompt = "..." / description = "..."': 'TOML : prompt = "..." / description = "..."',
      "Markdown: YAML frontmatter + content": "Markdown : YAML frontmatter + contenu",
      "The migration tool will:": "L'outil de migration va :",
      "Convert TOML files to Markdown": "Convertir les fichiers TOML en Markdown",
      "Create backups of original files": "Cr\xE9er des sauvegardes des fichiers originaux",
      "Preserve all command functionality": "Pr\xE9server toutes les fonctionnalit\xE9s des commandes",
      "TOML format will continue to work for now, but migration is recommended.": "Le format TOML continuera \xE0 fonctionner pour l'instant, mais la migration est recommand\xE9e.",
      // ============================================================================
      // Extensions - Commande Explore
      // ============================================================================
      "Open extensions page in your browser": "Ouvrir la page des extensions dans votre navigateur",
      "Unknown extensions source: {{source}}.": "Source d'extensions inconnue : {{source}}.",
      "Would open extensions page in your browser: {{url}} (skipped in test environment)": "Ouvrirait la page des extensions dans votre navigateur : {{url}} (ignor\xE9 en environnement de test)",
      "View available extensions at {{url}}": "Voir les extensions disponibles sur {{url}}",
      "Opening extensions page in your browser: {{url}}": "Ouverture de la page des extensions dans votre navigateur : {{url}}",
      "Failed to open browser. Check out the extensions gallery at {{url}}": "\xC9chec de l'ouverture du navigateur. Consultez la galerie d'extensions sur {{url}}",
      // ============================================================================
      // Réessai / Limite de débit
      // ============================================================================
      "Rate limit error: {{reason}}": "Erreur de limite de d\xE9bit : {{reason}}",
      "Retrying in {{seconds}} seconds\u2026 (attempt {{attempt}}/{{maxRetries}})": "Nouvelle tentative dans {{seconds}} secondes\u2026 (tentative {{attempt}}/{{maxRetries}})",
      "Press Ctrl+Y to retry": "Appuyez sur Ctrl+Y pour r\xE9essayer",
      "No failed request to retry.": "Aucune requ\xEAte \xE9chou\xE9e \xE0 r\xE9essayer.",
      "to retry last request": "pour r\xE9essayer la derni\xE8re requ\xEAte",
      // ============================================================================
      // Authentification du plan de codage
      // ============================================================================
      "API key cannot be empty.": "La cl\xE9 API ne peut pas \xEAtre vide.",
      "You can get your Coding Plan API key here": "Vous pouvez obtenir votre cl\xE9 API Coding Plan ici",
      "API key is stored in settings.env. You can migrate it to a .env file for better security.": "La cl\xE9 API est stock\xE9e dans settings.env. Vous pouvez la migrer vers un fichier .env pour une meilleure s\xE9curit\xE9.",
      "New model configurations are available for Alibaba Cloud Coding Plan. Update now?": "De nouvelles configurations de mod\xE8le sont disponibles pour Alibaba Cloud Coding Plan. Mettre \xE0 jour maintenant ?",
      "Coding Plan configuration updated successfully. New models are now available.": "Configuration Coding Plan mise \xE0 jour avec succ\xE8s. Les nouveaux mod\xE8les sont maintenant disponibles.",
      "Coding Plan API key not found. Please re-authenticate with Coding Plan.": "Cl\xE9 API Coding Plan introuvable. Veuillez vous r\xE9authentifier avec Coding Plan.",
      "Failed to update Coding Plan configuration: {{message}}": "\xC9chec de la mise \xE0 jour de la configuration Coding Plan : {{message}}",
      // ============================================================================
      // Configuration de clé API personnalisée
      // ============================================================================
      "You can configure your API key and models in settings.json": "Vous pouvez configurer votre cl\xE9 API et vos mod\xE8les dans settings.json",
      "Refer to the documentation for setup instructions": "Consultez la documentation pour les instructions de configuration",
      // ============================================================================
      // Boîte de dialogue Auth - Titres et étiquettes
      // ============================================================================
      "Coding Plan": "Plan de codage",
      "Paste your api key of ModelStudio Coding Plan and you're all set!": "Collez votre cl\xE9 API de ModelStudio Coding Plan et c'est parti !",
      Custom: "Personnalis\xE9",
      "More instructions about configuring `modelProviders` manually.": "Plus d'instructions sur la configuration manuelle de `modelProviders`.",
      "Select API-KEY configuration mode:": "S\xE9lectionner le mode de configuration API-KEY :",
      "(Press Escape to go back)": "(Appuyez sur \xC9chap pour revenir)",
      "(Press Enter to submit, Escape to cancel)": "(Appuyez sur Entr\xE9e pour soumettre, \xC9chap pour annuler)",
      "Select Region for Coding Plan": "S\xE9lectionner la r\xE9gion pour Coding Plan",
      "Choose based on where your account is registered": "Choisissez en fonction de l'endroit o\xF9 votre compte est enregistr\xE9",
      "Enter Coding Plan API Key": "Entrer la cl\xE9 API Coding Plan",
      // ============================================================================
      // Mises à jour internationales Coding Plan
      // ============================================================================
      "New model configurations are available for {{region}}. Update now?": "De nouvelles configurations de mod\xE8le sont disponibles pour {{region}}. Mettre \xE0 jour maintenant ?",
      '{{region}} configuration updated successfully. Model switched to "{{model}}".': 'Configuration {{region}} mise \xE0 jour avec succ\xE8s. Mod\xE8le chang\xE9 en "{{model}}".',
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up).": "Authentification r\xE9ussie avec {{region}}. Cl\xE9 API et configurations de mod\xE8le enregistr\xE9es dans settings.json (sauvegard\xE9).",
      // ============================================================================
      // Composant d'utilisation du contexte
      // ============================================================================
      "Context Usage": "Utilisation du contexte",
      "No API response yet. Send a message to see actual usage.": "Pas encore de r\xE9ponse API. Envoyez un message pour voir l'utilisation r\xE9elle.",
      "Estimated pre-conversation overhead": "Surcharge estim\xE9e avant la conversation",
      "Context window": "Fen\xEAtre de contexte",
      tokens: "tokens",
      Used: "Utilis\xE9",
      Free: "Libre",
      "Autocompact buffer": "Tampon de compaction automatique",
      "Usage by category": "Utilisation par cat\xE9gorie",
      "System prompt": "Invite syst\xE8me",
      "Built-in tools": "Outils int\xE9gr\xE9s",
      "MCP tools": "Outils MCP",
      "Memory files": "Fichiers m\xE9moire",
      Skills: "Comp\xE9tences",
      Messages: "Messages",
      "Show context window usage breakdown.": "Afficher la r\xE9partition de l'utilisation de la fen\xEAtre de contexte.",
      "Run /context detail for per-item breakdown.": "Ex\xE9cutez /context detail pour une r\xE9partition par \xE9l\xE9ment.",
      "body loaded": "corps charg\xE9",
      memory: "m\xE9moire",
      "{{region}} configuration updated successfully.": "Configuration {{region}} mise \xE0 jour avec succ\xE8s.",
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json.": "Authentification r\xE9ussie avec {{region}}. Cl\xE9 API et configurations de mod\xE8le enregistr\xE9es dans settings.json.",
      "Tip: Use /model to switch between available Coding Plan models.": "Conseil : Utilisez /model pour basculer entre les mod\xE8les Coding Plan disponibles.",
      // ============================================================================
      // Outil de question à l'utilisateur
      // ============================================================================
      "Please answer the following question(s):": "Veuillez r\xE9pondre \xE0 la (aux) question(s) suivante(s) :",
      "Cannot ask user questions in non-interactive mode. Please run in interactive mode to use this tool.": "Impossible de poser des questions \xE0 l'utilisateur en mode non interactif. Veuillez ex\xE9cuter en mode interactif pour utiliser cet outil.",
      "User declined to answer the questions.": "L'utilisateur a refus\xE9 de r\xE9pondre aux questions.",
      "User has provided the following answers:": "L'utilisateur a fourni les r\xE9ponses suivantes :",
      "Failed to process user answers:": "\xC9chec du traitement des r\xE9ponses de l'utilisateur :",
      "Type something...": "Tapez quelque chose...",
      Submit: "Soumettre",
      "Submit answers": "Soumettre les r\xE9ponses",
      Cancel: "Annuler",
      "Your answers:": "Vos r\xE9ponses :",
      "(not answered)": "(sans r\xE9ponse)",
      "Ready to submit your answers?": "Pr\xEAt \xE0 soumettre vos r\xE9ponses ?",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select": "\u2191/\u2193 : Naviguer | \u2190/\u2192 : Changer d'onglet | Entr\xE9e : S\xE9lectionner",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193 : Naviguer | \u2190/\u2192 : Changer d'onglet | Espace/Entr\xE9e : Basculer | \xC9chap : Annuler",
      "\u2191/\u2193: Navigate | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193 : Naviguer | Espace/Entr\xE9e : Basculer | \xC9chap : Annuler",
      "\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel": "\u2191/\u2193 : Naviguer | Entr\xE9e : S\xE9lectionner | \xC9chap : Annuler",
      // ============================================================================
      // Commandes - Auth
      // ============================================================================
      "Configure Qwen authentication information with Qwen-OAuth or Alibaba Cloud Coding Plan": "Configurer les informations d'authentification Qwen avec Qwen-OAuth ou Alibaba Cloud Coding Plan",
      "Authenticate using Qwen OAuth": "Authentifier avec Qwen OAuth",
      "Authenticate using Alibaba Cloud Coding Plan": "Authentifier avec Alibaba Cloud Coding Plan",
      "Region for Coding Plan (china/global)": "R\xE9gion pour Coding Plan (china/global)",
      "API key for Coding Plan": "Cl\xE9 API pour Coding Plan",
      "Show current authentication status": "Afficher le statut d'authentification actuel",
      "Authentication completed successfully.": "Authentification termin\xE9e avec succ\xE8s.",
      "Starting Qwen OAuth authentication...": "D\xE9marrage de l'authentification Qwen OAuth...",
      "Successfully authenticated with Qwen OAuth.": "Authentification r\xE9ussie avec Qwen OAuth.",
      "Failed to authenticate with Qwen OAuth: {{error}}": "\xC9chec de l'authentification avec Qwen OAuth : {{error}}",
      "Processing Alibaba Cloud Coding Plan authentication...": "Traitement de l'authentification Alibaba Cloud Coding Plan...",
      "Successfully authenticated with Alibaba Cloud Coding Plan.": "Authentification r\xE9ussie avec Alibaba Cloud Coding Plan.",
      "Failed to authenticate with Coding Plan: {{error}}": "\xC9chec de l'authentification avec Coding Plan : {{error}}",
      "\u4E2D\u56FD (China)": "\u4E2D\u56FD (Chine)",
      "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)": "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)",
      Global: "Global",
      "Alibaba Cloud (alibabacloud.com)": "Alibaba Cloud (alibabacloud.com)",
      "Select region for Coding Plan:": "S\xE9lectionner la r\xE9gion pour Coding Plan :",
      "Enter your Coding Plan API key: ": "Entrez votre cl\xE9 API Coding Plan : ",
      "Select authentication method:": "S\xE9lectionner la m\xE9thode d'authentification :",
      "\n=== Authentication Status ===\n": "\n=== Statut d'authentification ===\n",
      "\u26A0\uFE0F  No authentication method configured.\n": "\u26A0\uFE0F  Aucune m\xE9thode d'authentification configur\xE9e.\n",
      "Run one of the following commands to get started:\n": "Ex\xE9cutez l'une des commandes suivantes pour commencer :\n",
      "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)": "  qwen auth qwen-oauth     - Authentification avec Qwen OAuth (abandonn\xE9)",
      "  qwen auth coding-plan      - Authenticate with Alibaba Cloud Coding Plan\n": "  qwen auth coding-plan      - Authentifier avec Alibaba Cloud Coding Plan\n",
      "Or simply run:": "Ou simplement ex\xE9cutez :",
      "  qwen auth                - Interactive authentication setup\n": "  qwen auth                - Configuration d'authentification interactive\n",
      "\u2713 Authentication Method: Qwen OAuth": "\u2713 M\xE9thode d'authentification : Qwen OAuth",
      "  Type: Free tier (discontinued 2026-04-15)": "  Type : Niveau gratuit (abandonn\xE9 2026-04-15)",
      "  Limit: No longer available": "  Limite : Plus disponible",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.": "Le niveau gratuit Qwen OAuth a \xE9t\xE9 abandonn\xE9 le 2026-04-15. Ex\xE9cutez /auth pour passer \xE0 Coding Plan, OpenRouter, Fireworks AI ou un autre fournisseur.",
      "  Models: Qwen latest models\n": "  Mod\xE8les : Derniers mod\xE8les Qwen\n",
      "\u2713 Authentication Method: Alibaba Cloud Coding Plan": "\u2713 M\xE9thode d'authentification : Alibaba Cloud Coding Plan",
      "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC": "\u4E2D\u56FD (Chine) - \u963F\u91CC\u4E91\u767E\u70BC",
      "Global - Alibaba Cloud": "Global - Alibaba Cloud",
      "  Region: {{region}}": "  R\xE9gion : {{region}}",
      "  Current Model: {{model}}": "  Mod\xE8le actuel : {{model}}",
      "  Config Version: {{version}}": "  Version de config : {{version}}",
      "  Status: API key configured\n": "  Statut : Cl\xE9 API configur\xE9e\n",
      "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)": "\u26A0\uFE0F  M\xE9thode d'authentification : Alibaba Cloud Coding Plan (Incompl\xE8te)",
      "  Issue: API key not found in environment or settings\n": "  Probl\xE8me : Cl\xE9 API introuvable dans l'environnement ou les param\xE8tres\n",
      "  Run `qwen auth coding-plan` to re-configure.\n": "  Ex\xE9cutez `qwen auth coding-plan` pour reconfigurer.\n",
      "\u2713 Authentication Method: {{type}}": "\u2713 M\xE9thode d'authentification : {{type}}",
      "  Status: Configured\n": "  Statut : Configur\xE9\n",
      "Failed to check authentication status: {{error}}": "\xC9chec de la v\xE9rification du statut d'authentification : {{error}}",
      "Select an option:": "S\xE9lectionner une option :",
      "Raw mode not available. Please run in an interactive terminal.": "Mode brut non disponible. Veuillez ex\xE9cuter dans un terminal interactif.",
      "(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n": "(Utilisez les fl\xE8ches \u2191 \u2193 pour naviguer, Entr\xE9e pour s\xE9lectionner, Ctrl+C pour quitter)\n",
      compact: "compact",
      "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).": "Masquer la sortie des outils et la r\xE9flexion pour une vue plus nette (basculer avec Ctrl+O).",
      "Press Ctrl+O to show full tool output": "Appuyez sur Ctrl+O pour afficher la sortie compl\xE8te des outils",
      "Switch to plan mode or exit plan mode": "Passer en mode plan ou quitter le mode plan",
      "Exited plan mode. Previous approval mode restored.": "Mode plan quitt\xE9. Mode d'approbation pr\xE9c\xE9dent restaur\xE9.",
      "Enabled plan mode. The agent will analyze and plan without executing tools.": "Mode plan activ\xE9. L'agent analysera et planifiera sans ex\xE9cuter d'outils.",
      'Already in plan mode. Use "/plan exit" to exit plan mode.': 'D\xE9j\xE0 en mode plan. Utilisez "/plan exit" pour quitter le mode plan.',
      'Not in plan mode. Use "/plan" to enter plan mode first.': `Pas en mode plan. Utilisez "/plan" pour entrer en mode plan d'abord.`,
      "Set up Qwen Code's status line UI": "Configurer l'interface de la barre de statut de Qwen Code"
    };
  }
});

// packages/cli/src/i18n/locales/ja.js
var ja_exports = {};
__export(ja_exports, {
  default: () => ja_default2
});
var ja_default2;
var init_ja2 = __esm({
  "packages/cli/src/i18n/locales/ja.js"() {
    "use strict";
    init_esbuild_shims();
    ja_default2 = {
      // ============================================================================
      // 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",
      "Fast Model": "\u9AD8\u901F\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]",
      "List available skills.": "\u5229\u7528\u53EF\u80FD\u306A\u30B9\u30AD\u30EB\u3092\u4E00\u89A7\u8868\u793A\u3059\u308B\u3002",
      "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",
      "Enter to submit, Esc to go back": "Enter \u3067\u9001\u4FE1\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)",
      "Auto (detect terminal theme)": "\u81EA\u52D5\uFF08\u7AEF\u672B\u30C6\u30FC\u30DE\u3092\u691C\u51FA\uFF09",
      Auto: "\u81EA\u52D5",
      "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",
      "Open MCP management dialog, or authenticate with OAuth-enabled servers": "MCP\u7BA1\u7406\u30C0\u30A4\u30A2\u30ED\u30B0\u3092\u958B\u304F\u3001\u307E\u305F\u306FOAuth\u5BFE\u5FDC\u30B5\u30FC\u30D0\u30FC\u3067\u8A8D\u8A3C",
      "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",
      "Manage installed extensions": "\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u6E08\u307F\u306E\u62E1\u5F35\u6A5F\u80FD\u3092\u7BA1\u7406\u3059\u308B",
      "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",
      // ============================================================================
      // Commands - Hooks
      // ============================================================================
      "Manage Qwen Code hooks": "Qwen Code \u306E\u30D5\u30C3\u30AF\u3092\u7BA1\u7406\u3059\u308B",
      "List all configured hooks": "\u8A2D\u5B9A\u6E08\u307F\u306E\u30D5\u30C3\u30AF\u3092\u3059\u3079\u3066\u8868\u793A\u3059\u308B",
      "Enable a disabled hook": "\u7121\u52B9\u306A\u30D5\u30C3\u30AF\u3092\u6709\u52B9\u306B\u3059\u308B",
      "Disable an active hook": "\u6709\u52B9\u306A\u30D5\u30C3\u30AF\u3092\u7121\u52B9\u306B\u3059\u308B",
      // Hooks - Dialog
      Hooks: "\u30D5\u30C3\u30AF",
      "Loading hooks...": "\u30D5\u30C3\u30AF\u3092\u8AAD\u307F\u8FBC\u3093\u3067\u3044\u307E\u3059...",
      "Error loading hooks:": "\u30D5\u30C3\u30AF\u306E\u8AAD\u307F\u8FBC\u307F\u30A8\u30E9\u30FC\uFF1A",
      "Press Escape to close": "Escape \u30AD\u30FC\u3067\u9589\u3058\u308B",
      "Press Escape, Ctrl+C, or Ctrl+D to cancel": "Escape\u3001Ctrl+C\u3001Ctrl+D \u3067\u30AD\u30E3\u30F3\u30BB\u30EB",
      "Press Space, Enter, or Escape to dismiss": "Space\u3001Enter\u3001Escape \u3067\u9589\u3058\u308B",
      "No hook selected": "\u30D5\u30C3\u30AF\u304C\u9078\u629E\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
      // Hooks - List Step
      "No hook events found.": "\u30D5\u30C3\u30AF\u30A4\u30D9\u30F3\u30C8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002",
      "{{count}} hook configured": "{{count}} \u4EF6\u306E\u30D5\u30C3\u30AF\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059",
      "{{count}} hooks configured": "{{count}} \u4EF6\u306E\u30D5\u30C3\u30AF\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059",
      "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.": "\u3053\u306E\u30E1\u30CB\u30E5\u30FC\u306F\u8AAD\u307F\u53D6\u308A\u5C02\u7528\u3067\u3059\u3002\u30D5\u30C3\u30AF\u3092\u8FFD\u52A0\u307E\u305F\u306F\u5909\u66F4\u3059\u308B\u306B\u306F\u3001settings.json \u3092\u76F4\u63A5\u7DE8\u96C6\u3059\u308B\u304B\u3001Qwen Code \u306B\u5C0B\u306D\u3066\u304F\u3060\u3055\u3044\u3002",
      "Enter to select \xB7 Esc to cancel": "Enter \u3067\u9078\u629E \xB7 Esc \u3067\u30AD\u30E3\u30F3\u30BB\u30EB",
      // Hooks - Detail Step
      "Exit codes:": "\u7D42\u4E86\u30B3\u30FC\u30C9\uFF1A",
      "Configured hooks:": "\u8A2D\u5B9A\u6E08\u307F\u306E\u30D5\u30C3\u30AF\uFF1A",
      "No hooks configured for this event.": "\u3053\u306E\u30A4\u30D9\u30F3\u30C8\u306B\u306F\u30D5\u30C3\u30AF\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002",
      "To add hooks, edit settings.json directly or ask Qwen.": "\u30D5\u30C3\u30AF\u3092\u8FFD\u52A0\u3059\u308B\u306B\u306F\u3001settings.json \u3092\u76F4\u63A5\u7DE8\u96C6\u3059\u308B\u304B\u3001Qwen \u306B\u5C0B\u306D\u3066\u304F\u3060\u3055\u3044\u3002",
      "Enter to select \xB7 Esc to go back": "Enter \u3067\u9078\u629E \xB7 Esc \u3067\u623B\u308B",
      // Hooks - Config Detail Step
      "Hook details": "\u30D5\u30C3\u30AF\u8A73\u7D30",
      "Event:": "\u30A4\u30D9\u30F3\u30C8\uFF1A",
      "Extension:": "\u62E1\u5F35\u6A5F\u80FD\uFF1A",
      "Desc:": "\u8AAC\u660E\uFF1A",
      "No hook config selected": "\u30D5\u30C3\u30AF\u8A2D\u5B9A\u304C\u9078\u629E\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
      "To modify or remove this hook, edit settings.json directly or ask Qwen to help.": "\u3053\u306E\u30D5\u30C3\u30AF\u3092\u5909\u66F4\u307E\u305F\u306F\u524A\u9664\u3059\u308B\u306B\u306F\u3001settings.json \u3092\u76F4\u63A5\u7DE8\u96C6\u3059\u308B\u304B\u3001Qwen \u306B\u5C0B\u306D\u3066\u304F\u3060\u3055\u3044\u3002",
      // Hooks - Disabled Step
      "Hook Configuration - Disabled": "\u30D5\u30C3\u30AF\u8A2D\u5B9A - \u7121\u52B9",
      "All hooks are currently disabled. You have {{count}} that are not running.": "\u3059\u3079\u3066\u306E\u30D5\u30C3\u30AF\u306F\u73FE\u5728\u7121\u52B9\u3067\u3059\u3002{{count}} \u304C\u5B9F\u884C\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002",
      "{{count}} configured hook": "{{count}} \u500B\u306E\u8A2D\u5B9A\u3055\u308C\u305F\u30D5\u30C3\u30AF",
      "{{count}} configured hooks": "{{count}} \u500B\u306E\u8A2D\u5B9A\u3055\u308C\u305F\u30D5\u30C3\u30AF",
      "When hooks are disabled:": "\u30D5\u30C3\u30AF\u304C\u7121\u52B9\u306A\u5834\u5408\uFF1A",
      "No hook commands will execute": "\u30D5\u30C3\u30AF\u30B3\u30DE\u30F3\u30C9\u306F\u5B9F\u884C\u3055\u308C\u307E\u305B\u3093",
      "StatusLine will not be displayed": "StatusLine \u306F\u8868\u793A\u3055\u308C\u307E\u305B\u3093",
      "Tool operations will proceed without hook validation": "\u30C4\u30FC\u30EB\u64CD\u4F5C\u306F\u30D5\u30C3\u30AF\u691C\u8A3C\u306A\u3057\u3067\u7D9A\u884C\u3055\u308C\u307E\u3059",
      'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.': '\u30D5\u30C3\u30AF\u3092\u518D\u6709\u52B9\u5316\u3059\u308B\u306B\u306F\u3001settings.json \u304B\u3089 "disableAllHooks" \u3092\u524A\u9664\u3059\u308B\u304B\u3001Qwen Code \u306B\u5C0B\u306D\u3066\u304F\u3060\u3055\u3044\u3002',
      // Hooks - Source
      Project: "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8",
      User: "\u30E6\u30FC\u30B6\u30FC",
      System: "\u30B7\u30B9\u30C6\u30E0",
      Extension: "\u62E1\u5F35\u6A5F\u80FD",
      "Local Settings": "\u30ED\u30FC\u30AB\u30EB\u8A2D\u5B9A",
      "User Settings": "\u30E6\u30FC\u30B6\u30FC\u8A2D\u5B9A",
      "System Settings": "\u30B7\u30B9\u30C6\u30E0\u8A2D\u5B9A",
      Extensions: "\u62E1\u5F35\u6A5F\u80FD",
      "Session (temporary)": "\u30BB\u30C3\u30B7\u30E7\u30F3\uFF08\u4E00\u6642\uFF09",
      // Hooks - Status
      "\u2713 Enabled": "\u2713 \u6709\u52B9",
      "\u2717 Disabled": "\u2717 \u7121\u52B9",
      // Hooks - Event Descriptions (short)
      "Before tool execution": "\u30C4\u30FC\u30EB\u5B9F\u884C\u524D",
      "After tool execution": "\u30C4\u30FC\u30EB\u5B9F\u884C\u5F8C",
      "After tool execution fails": "\u30C4\u30FC\u30EB\u5B9F\u884C\u5931\u6557\u6642",
      "When notifications are sent": "\u901A\u77E5\u9001\u4FE1\u6642",
      "When the user submits a prompt": "\u30E6\u30FC\u30B6\u30FC\u304C\u30D7\u30ED\u30F3\u30D7\u30C8\u3092\u9001\u4FE1\u3057\u305F\u6642",
      "When a new session is started": "\u65B0\u3057\u3044\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u958B\u59CB\u3055\u308C\u305F\u6642",
      "Right before Qwen Code concludes its response": "Qwen Code \u304C\u5FDC\u7B54\u3092\u7D42\u4E86\u3059\u308B\u76F4\u524D",
      "When a subagent (Agent tool call) is started": "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\uFF08Agent \u30C4\u30FC\u30EB\u547C\u3073\u51FA\u3057\uFF09\u304C\u958B\u59CB\u3055\u308C\u305F\u6642",
      "Right before a subagent concludes its response": "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u304C\u5FDC\u7B54\u3092\u7D42\u4E86\u3059\u308B\u76F4\u524D",
      "Before conversation compaction": "\u4F1A\u8A71\u5727\u7E2E\u524D",
      "When a session is ending": "\u30BB\u30C3\u30B7\u30E7\u30F3\u7D42\u4E86\u6642",
      "When a permission dialog is displayed": "\u6A29\u9650\u30C0\u30A4\u30A2\u30ED\u30B0\u8868\u793A\u6642",
      // Hooks - Event Descriptions (detailed)
      "Input to command is JSON of tool call arguments.": "\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F\u30C4\u30FC\u30EB\u547C\u3073\u51FA\u3057\u5F15\u6570\u306E JSON \u3067\u3059\u3002",
      'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': '\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F "inputs"\uFF08\u30C4\u30FC\u30EB\u547C\u3073\u51FA\u3057\u5F15\u6570\uFF09\u3068 "response"\uFF08\u30C4\u30FC\u30EB\u547C\u3073\u51FA\u3057\u5FDC\u7B54\uFF09\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u6301\u3064 JSON \u3067\u3059\u3002',
      "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.": "\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F tool_name\u3001tool_input\u3001tool_use_id\u3001error\u3001error_type\u3001is_interrupt\u3001is_timeout \u3092\u6301\u3064 JSON \u3067\u3059\u3002",
      "Input to command is JSON with notification message and type.": "\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F\u901A\u77E5\u30E1\u30C3\u30BB\u30FC\u30B8\u3068\u30BF\u30A4\u30D7\u3092\u6301\u3064 JSON \u3067\u3059\u3002",
      "Input to command is JSON with original user prompt text.": "\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F\u5143\u306E\u30E6\u30FC\u30B6\u30FC\u30D7\u30ED\u30F3\u30D7\u30C8\u30C6\u30AD\u30B9\u30C8\u3092\u6301\u3064 JSON \u3067\u3059\u3002",
      "Input to command is JSON with session start source.": "\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F\u30BB\u30C3\u30B7\u30E7\u30F3\u958B\u59CB\u30BD\u30FC\u30B9\u3092\u6301\u3064 JSON \u3067\u3059\u3002",
      "Input to command is JSON with session end reason.": "\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F\u30BB\u30C3\u30B7\u30E7\u30F3\u7D42\u4E86\u7406\u7531\u3092\u6301\u3064 JSON \u3067\u3059\u3002",
      "Input to command is JSON with agent_id and agent_type.": "\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F agent_id \u3068 agent_type \u3092\u6301\u3064 JSON \u3067\u3059\u3002",
      "Input to command is JSON with agent_id, agent_type, and agent_transcript_path.": "\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F agent_id\u3001agent_type\u3001agent_transcript_path \u3092\u6301\u3064 JSON \u3067\u3059\u3002",
      "Input to command is JSON with compaction details.": "\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F\u5727\u7E2E\u8A73\u7D30\u3092\u6301\u3064 JSON \u3067\u3059\u3002",
      "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.": "\u30B3\u30DE\u30F3\u30C9\u3078\u306E\u5165\u529B\u306F tool_name\u3001tool_input\u3001tool_use_id \u3092\u6301\u3064 JSON \u3067\u3059\u3002\u8A31\u53EF\u307E\u305F\u306F\u62D2\u5426\u306E\u6C7A\u5B9A\u3092\u542B\u3080 hookSpecificOutput \u3092\u6301\u3064 JSON \u3092\u51FA\u529B\u3057\u307E\u3059\u3002",
      // Hooks - Exit Code Descriptions
      "stdout/stderr not shown": "stdout/stderr \u306F\u8868\u793A\u3055\u308C\u307E\u305B\u3093",
      "show stderr to model and continue conversation": "stderr \u3092\u30E2\u30C7\u30EB\u306B\u8868\u793A\u3057\u3001\u4F1A\u8A71\u3092\u7D9A\u3051\u308B",
      "show stderr to user only": "stderr \u3092\u30E6\u30FC\u30B6\u30FC\u306E\u307F\u306B\u8868\u793A",
      "stdout shown in transcript mode (ctrl+o)": "stdout \u306F\u30C8\u30E9\u30F3\u30B9\u30AF\u30EA\u30D7\u30C8\u30E2\u30FC\u30C9\u3067\u8868\u793A (ctrl+o)",
      "show stderr to model immediately": "stderr \u3092\u30E2\u30C7\u30EB\u306B\u5373\u5EA7\u306B\u8868\u793A",
      "show stderr to user only but continue with tool call": "stderr \u3092\u30E6\u30FC\u30B6\u30FC\u306E\u307F\u306B\u8868\u793A\u3057\u3001\u30C4\u30FC\u30EB\u547C\u3073\u51FA\u3057\u3092\u7D9A\u3051\u308B",
      "block processing, erase original prompt, and show stderr to user only": "\u51E6\u7406\u3092\u30D6\u30ED\u30C3\u30AF\u3057\u3001\u5143\u306E\u30D7\u30ED\u30F3\u30D7\u30C8\u3092\u6D88\u53BB\u3057\u3001stderr \u3092\u30E6\u30FC\u30B6\u30FC\u306E\u307F\u306B\u8868\u793A",
      "stdout shown to Qwen": "stdout \u3092\u30E2\u30C7\u30EB\u306B\u8868\u793A",
      "show stderr to user only (blocking errors ignored)": "stderr \u3092\u30E6\u30FC\u30B6\u30FC\u306E\u307F\u306B\u8868\u793A\uFF08\u30D6\u30ED\u30C3\u30AD\u30F3\u30B0\u30A8\u30E9\u30FC\u306F\u7121\u8996\uFF09",
      "command completes successfully": "\u30B3\u30DE\u30F3\u30C9\u304C\u6B63\u5E38\u306B\u5B8C\u4E86",
      "stdout shown to subagent": "stdout \u3092\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306B\u8868\u793A",
      "show stderr to subagent and continue having it run": "stderr \u3092\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306B\u8868\u793A\u3057\u3001\u5B9F\u884C\u3092\u7D9A\u3051\u308B",
      "stdout appended as custom compact instructions": "stdout \u3092\u30AB\u30B9\u30BF\u30E0\u5727\u7E2E\u6307\u793A\u3068\u3057\u3066\u8FFD\u52A0",
      "block compaction": "\u5727\u7E2E\u3092\u30D6\u30ED\u30C3\u30AF",
      "show stderr to user only but continue with compaction": "stderr \u3092\u30E6\u30FC\u30B6\u30FC\u306E\u307F\u306B\u8868\u793A\u3057\u3001\u5727\u7E2E\u3092\u7D9A\u3051\u308B",
      "use hook decision if provided": "\u63D0\u4F9B\u3055\u308C\u3066\u3044\u308B\u5834\u5408\u306F\u30D5\u30C3\u30AF\u306E\u6C7A\u5B9A\u3092\u4F7F\u7528",
      // Hooks - Messages
      "Config not loaded.": "\u8A2D\u5B9A\u304C\u8AAD\u307F\u8FBC\u307E\u308C\u3066\u3044\u307E\u305B\u3093\u3002",
      "Hooks are not enabled. Enable hooks in settings to use this feature.": "\u30D5\u30C3\u30AF\u304C\u6709\u52B9\u306B\u306A\u3063\u3066\u3044\u307E\u305B\u3093\u3002\u3053\u306E\u6A5F\u80FD\u3092\u4F7F\u7528\u3059\u308B\u306B\u306F\u8A2D\u5B9A\u3067\u30D5\u30C3\u30AF\u3092\u6709\u52B9\u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "No hooks configured. Add hooks in your settings.json file.": "\u30D5\u30C3\u30AF\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002settings.json \u30D5\u30A1\u30A4\u30EB\u306B\u30D5\u30C3\u30AF\u3092\u8FFD\u52A0\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "Configured Hooks ({{count}} total)": "\u8A2D\u5B9A\u6E08\u307F\u306E\u30D5\u30C3\u30AF\uFF08\u5408\u8A08 {{count}} \u4EF6\uFF09",
      // ============================================================================
      // Commands - Session Export
      // ============================================================================
      "Export current session message history to a file": "\u73FE\u5728\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u5C65\u6B74\u3092\u30D5\u30A1\u30A4\u30EB\u306B\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3059\u308B",
      "Export session to HTML format": "\u30BB\u30C3\u30B7\u30E7\u30F3\u3092 HTML \u5F62\u5F0F\u3067\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3059\u308B",
      "Export session to JSON format": "\u30BB\u30C3\u30B7\u30E7\u30F3\u3092 JSON \u5F62\u5F0F\u3067\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3059\u308B",
      "Export session to JSONL format (one message per line)": "\u30BB\u30C3\u30B7\u30E7\u30F3\u3092 JSONL \u5F62\u5F0F\u3067\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3059\u308B\uFF081 \u884C\u306B 1 \u30E1\u30C3\u30BB\u30FC\u30B8\uFF09",
      "Export session to markdown format": "\u30BB\u30C3\u30B7\u30E7\u30F3\u3092 Markdown \u5F62\u5F0F\u3067\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3059\u308B",
      // ============================================================================
      // Commands - Insights
      // ============================================================================
      "generate personalized programming insights from your chat history": "\u30C1\u30E3\u30C3\u30C8\u5C65\u6B74\u304B\u3089\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BA\u3055\u308C\u305F\u30D7\u30ED\u30B0\u30E9\u30DF\u30F3\u30B0\u30A4\u30F3\u30B5\u30A4\u30C8\u3092\u751F\u6210\u3059\u308B",
      // ============================================================================
      // Commands - Session History
      // ============================================================================
      "Resume a previous session": "\u524D\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u518D\u958B\u3059\u308B",
      "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested": "\u30C4\u30FC\u30EB\u547C\u3073\u51FA\u3057\u3092\u5FA9\u5143\u3057\u307E\u3059\u3002\u3053\u308C\u306B\u3088\u308A\u3001\u4F1A\u8A71\u3068\u30D5\u30A1\u30A4\u30EB\u306E\u5C65\u6B74\u306F\u305D\u306E\u30C4\u30FC\u30EB\u547C\u3073\u51FA\u3057\u304C\u63D0\u6848\u3055\u308C\u305F\u6642\u70B9\u306E\u72B6\u614B\u306B\u623B\u308A\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",
      "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}}"',
      "Open auto-memory folder": "\u81EA\u52D5\u30E1\u30E2\u30EA\u30D5\u30A9\u30EB\u30C0\u3092\u958B\u304F",
      "Auto-memory: {{status}}": "\u81EA\u52D5\u30E1\u30E2\u30EA: {{status}}",
      "Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream to run": "\u81EA\u52D5\u7D71\u5408: {{status}} \xB7 {{lastDream}} \xB7 /dream \u3067\u5B9F\u884C",
      never: "\u672A\u5B9F\u884C",
      on: "\u30AA\u30F3",
      off: "\u30AA\u30D5",
      "\u2746 dreaming": "\u2746 \u6574\u7406\u4E2D",
      "Remove matching entries from managed auto-memory.": "\u30DE\u30CD\u30FC\u30B8\u30C9\u81EA\u52D5\u30E1\u30E2\u30EA\u304B\u3089\u4E00\u81F4\u3059\u308B\u30A8\u30F3\u30C8\u30EA\u3092\u524A\u9664\u3059\u308B\u3002",
      "Usage: /forget <memory text to remove>": "\u4F7F\u3044\u65B9: /forget <\u524A\u9664\u3059\u308B\u30E1\u30E2\u30EA\u30C6\u30AD\u30B9\u30C8>",
      "No managed auto-memory entries matched: {{query}}": "\u4E00\u81F4\u3059\u308B\u30DE\u30CD\u30FC\u30B8\u30C9\u81EA\u52D5\u30E1\u30E2\u30EA\u30A8\u30F3\u30C8\u30EA\u306A\u3057: {{query}}",
      "Show managed auto-memory status.": "\u30DE\u30CD\u30FC\u30B8\u30C9\u81EA\u52D5\u30E1\u30E2\u30EA\u306E\u30B9\u30C6\u30FC\u30BF\u30B9\u3092\u8868\u793A\u3059\u308B\u3002",
      "Run managed auto-memory extraction for the current session.": "\u73FE\u5728\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u306E\u30DE\u30CD\u30FC\u30B8\u30C9\u81EA\u52D5\u30E1\u30E2\u30EA\u62BD\u51FA\u3092\u5B9F\u884C\u3059\u308B\u3002",
      "Managed auto-memory root: {{root}}": "\u30DE\u30CD\u30FC\u30B8\u30C9\u81EA\u52D5\u30E1\u30E2\u30EA\u306E\u30EB\u30FC\u30C8: {{root}}",
      "Managed auto-memory topics:": "\u30DE\u30CD\u30FC\u30B8\u30C9\u81EA\u52D5\u30E1\u30E2\u30EA\u306E\u30C8\u30D4\u30C3\u30AF:",
      "No extraction cursor found yet.": "\u307E\u3060\u62BD\u51FA\u30AB\u30FC\u30BD\u30EB\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002",
      "Cursor: session={{sessionId}}, offset={{offset}}, updated={{updatedAt}}": "\u30AB\u30FC\u30BD\u30EB: \u30BB\u30C3\u30B7\u30E7\u30F3={{sessionId}}, \u30AA\u30D5\u30BB\u30C3\u30C8={{offset}}, \u66F4\u65B0={{updatedAt}}",
      "No chat client available to extract memory.": "\u30E1\u30E2\u30EA\u3092\u62BD\u51FA\u3067\u304D\u308B\u30C1\u30E3\u30C3\u30C8\u30AF\u30E9\u30A4\u30A2\u30F3\u30C8\u304C\u3042\u308A\u307E\u305B\u3093\u3002",
      "Managed auto-memory extraction is already running.": "\u30DE\u30CD\u30FC\u30B8\u30C9\u81EA\u52D5\u30E1\u30E2\u30EA\u62BD\u51FA\u306F\u3059\u3067\u306B\u5B9F\u884C\u4E2D\u3067\u3059\u3002",
      "Managed auto-memory extraction found no new durable memories.": "\u30DE\u30CD\u30FC\u30B8\u30C9\u81EA\u52D5\u30E1\u30E2\u30EA\u62BD\u51FA\u3067\u65B0\u3057\u3044\u6C38\u7D9A\u30E1\u30E2\u30EA\u306F\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002",
      "Consolidate managed auto-memory topic files.": "\u30DE\u30CD\u30FC\u30B8\u30C9\u81EA\u52D5\u30E1\u30E2\u30EA\u30C8\u30D4\u30C3\u30AF\u30D5\u30A1\u30A4\u30EB\u3092\u7D71\u5408\u3059\u308B\u3002",
      "Managed auto-memory dream found nothing to improve.": "\u81EA\u52D5\u30E1\u30E2\u30EA\u7D71\u5408\u3067\u6539\u5584\u3059\u308B\u3082\u306E\u306F\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002",
      "Deduplicated entries: {{count}}": "\u91CD\u8907\u9664\u53BB\u3057\u305F\u30A8\u30F3\u30C8\u30EA: {{count}}",
      "Save a durable memory using the save_memory tool.": "save_memory\u30C4\u30FC\u30EB\u3092\u4F7F\u7528\u3057\u3066\u6C38\u7D9A\u30E1\u30E2\u30EA\u3092\u4FDD\u5B58\u3059\u308B\u3002",
      "Usage: /remember [--global|--project] <text to remember>": "\u4F7F\u3044\u65B9: /remember [--global|--project] <\u899A\u3048\u3066\u304A\u304F\u30C6\u30AD\u30B9\u30C8>",
      // 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",
      "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...",
      "Discovered {{count}} tool(s) from '{{name}}'.": "'{{name}}' \u304B\u3089 {{count}} \u500B\u306E\u30C4\u30FC\u30EB\u3092\u691C\u51FA\u3057\u307E\u3057\u305F\u3002",
      "Authentication complete. Returning to server details...": "\u8A8D\u8A3C\u5B8C\u4E86\u3002\u30B5\u30FC\u30D0\u30FC\u8A73\u7D30\u306B\u623B\u308A\u307E\u3059...",
      "Authentication successful.": "\u8A8D\u8A3C\u6210\u529F\u3002",
      "If the browser does not open, copy and paste this URL into your browser:": "\u30D6\u30E9\u30A6\u30B6\u304C\u958B\u304B\u306A\u3044\u5834\u5408\u306F\u3001\u3053\u306EURL\u3092\u30B3\u30D4\u30FC\u3057\u3066\u30D6\u30E9\u30A6\u30B6\u306B\u8CBC\u308A\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\uFF1A",
      "Make sure to copy the COMPLETE URL - it may wrap across multiple lines.": "\u26A0\uFE0F  URL\u5168\u4F53\u3092\u30B3\u30D4\u30FC\u3057\u3066\u304F\u3060\u3055\u3044\u2014\u2014\u8907\u6570\u884C\u306B\u307E\u305F\u304C\u308B\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002",
      "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 (--fast for suggestion model)": "\u3053\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u306E\u30E2\u30C7\u30EB\u3092\u5207\u308A\u66FF\u3048\uFF08--fast \u3067\u63D0\u6848\u30E2\u30C7\u30EB\u3092\u8A2D\u5B9A\uFF09",
      "Set a lighter model for prompt suggestions and speculative execution": "\u30D7\u30ED\u30F3\u30D7\u30C8\u63D0\u6848\u3068\u6295\u6A5F\u7684\u5B9F\u884C\u7528\u306E\u8EFD\u91CF\u30E2\u30C7\u30EB\u3092\u8A2D\u5B9A",
      "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",
      Yes: "\u306F\u3044",
      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",
      // MCP Management - Core translations
      "Manage MCP servers": "MCP\u30B5\u30FC\u30D0\u30FC\u3092\u7BA1\u7406",
      "Server Detail": "\u30B5\u30FC\u30D0\u30FC\u8A73\u7D30",
      "Disable Server": "\u30B5\u30FC\u30D0\u30FC\u3092\u7121\u52B9\u5316",
      Tools: "\u30C4\u30FC\u30EB",
      "Tool Detail": "\u30C4\u30FC\u30EB\u8A73\u7D30",
      "MCP Management": "MCP\u7BA1\u7406",
      "Loading...": "\u8AAD\u307F\u8FBC\u307F\u4E2D...",
      "Unknown step": "\u4E0D\u660E\u306A\u30B9\u30C6\u30C3\u30D7",
      "Esc to back": "Esc \u623B\u308B",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close": "\u2191\u2193 \u30CA\u30D3\u30B2\u30FC\u30C8 \xB7 Enter \u9078\u629E \xB7 Esc \u9589\u3058\u308B",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back": "\u2191\u2193 \u30CA\u30D3\u30B2\u30FC\u30C8 \xB7 Enter \u9078\u629E \xB7 Esc \u623B\u308B",
      "\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back": "\u2191\u2193 \u30CA\u30D3\u30B2\u30FC\u30C8 \xB7 Enter \u78BA\u8A8D \xB7 Esc \u623B\u308B",
      "User Settings (global)": "\u30E6\u30FC\u30B6\u30FC\u8A2D\u5B9A\uFF08\u30B0\u30ED\u30FC\u30D0\u30EB\uFF09",
      "Workspace Settings (project-specific)": "\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u8A2D\u5B9A\uFF08\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u56FA\u6709\uFF09",
      "Disable server:": "\u30B5\u30FC\u30D0\u30FC\u3092\u7121\u52B9\u5316:",
      "Select where to add the server to the exclude list:": "\u30B5\u30FC\u30D0\u30FC\u3092\u9664\u5916\u30EA\u30B9\u30C8\u306B\u8FFD\u52A0\u3059\u308B\u5834\u6240\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044:",
      "Press Enter to confirm, Esc to cancel": "Enter \u3067\u78BA\u8A8D\u3001Esc \u3067\u30AD\u30E3\u30F3\u30BB\u30EB",
      Disable: "\u7121\u52B9\u5316",
      Enable: "\u6709\u52B9\u5316",
      Authenticate: "\u8A8D\u8A3C",
      "Re-authenticate": "\u518D\u8A8D\u8A3C",
      "Clear Authentication": "\u8A8D\u8A3C\u3092\u30AF\u30EA\u30A2",
      disabled: "\u7121\u52B9",
      "Server:": "\u30B5\u30FC\u30D0\u30FC:",
      Reconnect: "\u518D\u63A5\u7D9A",
      "View tools": "\u30C4\u30FC\u30EB\u3092\u8868\u793A",
      "Status:": "\u30B9\u30C6\u30FC\u30BF\u30B9:",
      "Source:": "\u30BD\u30FC\u30B9:",
      "Command:": "\u30B3\u30DE\u30F3\u30C9:",
      "Working Directory:": "\u4F5C\u696D\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA:",
      "Capabilities:": "\u6A5F\u80FD:",
      "No server selected": "\u30B5\u30FC\u30D0\u30FC\u304C\u9078\u629E\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
      "(disabled)": "(\u7121\u52B9)",
      "Error:": "\u30A8\u30E9\u30FC:",
      tool: "\u30C4\u30FC\u30EB",
      tools: "\u30C4\u30FC\u30EB",
      connected: "\u63A5\u7D9A\u6E08\u307F",
      connecting: "\u63A5\u7D9A\u4E2D",
      disconnected: "\u5207\u65AD\u6E08\u307F",
      error: "\u30A8\u30E9\u30FC",
      // MCP Server List
      "User MCPs": "\u30E6\u30FC\u30B6\u30FCMCP",
      "Project MCPs": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8MCP",
      "Extension MCPs": "\u62E1\u5F35\u6A5F\u80FDMCP",
      server: "\u30B5\u30FC\u30D0\u30FC",
      servers: "\u30B5\u30FC\u30D0\u30FC",
      "Add MCP servers to your settings to get started.": "\u8A2D\u5B9A\u306BMCP\u30B5\u30FC\u30D0\u30FC\u3092\u8FFD\u52A0\u3057\u3066\u958B\u59CB\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "Run qwen --debug to see error logs": "qwen --debug \u3092\u5B9F\u884C\u3057\u3066\u30A8\u30E9\u30FC\u30ED\u30B0\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044",
      // MCP OAuth Authentication
      "OAuth Authentication": "OAuth \u8A8D\u8A3C",
      "Press Enter to start authentication, Esc to go back": "Enter \u3067\u8A8D\u8A3C\u958B\u59CB\u3001Esc \u3067\u623B\u308B",
      "Authenticating... Please complete the login in your browser.": "\u8A8D\u8A3C\u4E2D... \u30D6\u30E9\u30A6\u30B6\u3067\u30ED\u30B0\u30A4\u30F3\u3092\u5B8C\u4E86\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "Press Enter or Esc to go back": "Enter \u307E\u305F\u306F Esc \u3067\u623B\u308B",
      // MCP Tool List
      "No tools available for this server.": "\u3053\u306E\u30B5\u30FC\u30D0\u30FC\u306B\u306F\u4F7F\u7528\u53EF\u80FD\u306A\u30C4\u30FC\u30EB\u304C\u3042\u308A\u307E\u305B\u3093\u3002",
      destructive: "\u7834\u58CA\u7684",
      "read-only": "\u8AAD\u307F\u53D6\u308A\u5C02\u7528",
      "open-world": "\u30AA\u30FC\u30D7\u30F3\u30EF\u30FC\u30EB\u30C9",
      idempotent: "\u51AA\u7B49",
      "Tools for {{name}}": "{{name}} \u306E\u30C4\u30FC\u30EB",
      "Tools for {{serverName}}": "{{serverName}} \u306E\u30C4\u30FC\u30EB",
      "{{current}}/{{total}}": "{{current}}/{{total}}",
      // MCP Tool Detail
      required: "\u5FC5\u9808",
      Type: "\u578B",
      Enum: "\u5217\u6319",
      Parameters: "\u30D1\u30E9\u30E1\u30FC\u30BF",
      "No tool selected": "\u30C4\u30FC\u30EB\u304C\u9078\u629E\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
      Annotations: "\u6CE8\u91C8",
      Title: "\u30BF\u30A4\u30C8\u30EB",
      "Read Only": "\u8AAD\u307F\u53D6\u308A\u5C02\u7528",
      Destructive: "\u7834\u58CA\u7684",
      Idempotent: "\u51AA\u7B49",
      "Open World": "\u30AA\u30FC\u30D7\u30F3\u30EF\u30FC\u30EB\u30C9",
      Server: "\u30B5\u30FC\u30D0\u30FC",
      // Invalid tool related translations
      "{{count}} invalid tools": "{{count}} \u500B\u306E\u7121\u52B9\u306A\u30C4\u30FC\u30EB",
      invalid: "\u7121\u52B9",
      "invalid: {{reason}}": "\u7121\u52B9: {{reason}}",
      "missing name": "\u540D\u524D\u306A\u3057",
      "missing description": "\u8AAC\u660E\u306A\u3057",
      "(unnamed)": "(\u540D\u524D\u306A\u3057)",
      "Warning: This tool cannot be called by the LLM": "\u8B66\u544A: \u3053\u306E\u30C4\u30FC\u30EB\u306FLLM\u306B\u3088\u3063\u3066\u547C\u3073\u51FA\u3059\u3053\u3068\u304C\u3067\u304D\u307E\u305B\u3093",
      Reason: "\u7406\u7531",
      "Tools must have both name and description to be used by the LLM.": "\u30C4\u30FC\u30EB\u306FLLM\u306B\u3088\u3063\u3066\u4F7F\u7528\u3055\u308C\u308B\u306B\u306F\u540D\u524D\u3068\u8AAC\u660E\u306E\u4E21\u65B9\u304C\u5FC5\u8981\u3067\u3059\u3002",
      "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...",
      "Always allow in this project": "\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3067\u5E38\u306B\u8A31\u53EF",
      "Always allow {{action}} in this project": "\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3067{{action}}\u3092\u5E38\u306B\u8A31\u53EF",
      "Always allow for this user": "\u3053\u306E\u30E6\u30FC\u30B6\u30FC\u306B\u5E38\u306B\u8A31\u53EF",
      "Always allow {{action}} for this user": "\u3053\u306E\u30E6\u30FC\u30B6\u30FC\u306B{{action}}\u3092\u5E38\u306B\u8A31\u53EF",
      "Yes, restore previous mode ({{mode}})": "\u306F\u3044\u3001\u4EE5\u524D\u306E\u30E2\u30FC\u30C9\u306B\u623B\u3059 ({{mode}})",
      "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:",
      "Current tasks": "\u73FE\u5728\u306E\u30BF\u30B9\u30AF",
      "... and {{count}} more": "... \u4ED6 {{count}} \u4EF6",
      "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",
      "Select Authentication Method": "\u8A8D\u8A3C\u65B9\u6CD5\u3092\u9078\u629E",
      "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",
      "Terms of Services and Privacy Notice": "\u5229\u7528\u898F\u7D04\u3068\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC\u901A\u77E5",
      "Qwen OAuth": "Qwen OAuth",
      "Discontinued \u2014 switch to Coding Plan or API Key": "\u7D42\u4E86 \u2014 Coding Plan \u307E\u305F\u306F API Key \u306B\u5207\u308A\u66FF\u3048\u3066\u304F\u3060\u3055\u3044",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch provider.": "Qwen OAuth \u7121\u6599\u67A0\u306F 2026-04-15 \u306B\u7D42\u4E86\u3057\u307E\u3057\u305F\u3002/auth \u3092\u5B9F\u884C\u3057\u3066\u30D7\u30ED\u30D0\u30A4\u30C0\u30FC\u3092\u5207\u308A\u66FF\u3048\u3066\u304F\u3060\u3055\u3044\u3002",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead.": "Qwen OAuth \u7121\u6599\u67A0\u306F 2026-04-15 \u306B\u7D42\u4E86\u3057\u307E\u3057\u305F\u3002Coding Plan \u307E\u305F\u306F API Key \u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.": "Qwen OAuth\u7121\u6599\u30D7\u30E9\u30F3\u306F2026-04-15\u306B\u7D42\u4E86\u3057\u307E\u3057\u305F\u3002\u4ED6\u306E\u30D7\u30ED\u30D0\u30A4\u30C0\u30FC\u306E\u30E2\u30C7\u30EB\u3092\u9078\u629E\u3059\u308B\u304B\u3001/auth\u3092\u5B9F\u884C\u3057\u3066\u5207\u308A\u66FF\u3048\u3066\u304F\u3060\u3055\u3044\u3002",
      "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n": "\n\u26A0 Qwen OAuth \u7121\u6599\u67A0\u306F 2026-04-15 \u306B\u7D42\u4E86\u3057\u307E\u3057\u305F\u3002\u4ED6\u306E\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044\u3002\n",
      "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models": "\u6709\u6599 \xB7 5\u6642\u9593\u6700\u59276,000\u30EA\u30AF\u30A8\u30B9\u30C8 \xB7 \u3059\u3079\u3066\u306E Alibaba Cloud Coding Plan \u30E2\u30C7\u30EB",
      "Alibaba Cloud Coding Plan": "Alibaba Cloud Coding Plan",
      "Bring your own API key": "\u81EA\u5206\u306EAPI\u30AD\u30FC\u3092\u4F7F\u7528",
      "Browser-based authentication with third-party providers (e.g. OpenRouter, ModelScope)": "\u30B5\u30FC\u30C9\u30D1\u30FC\u30C6\u30A3\u30D7\u30ED\u30D0\u30A4\u30C0\u30FC\u306B\u3088\u308B\u30D6\u30E9\u30A6\u30B6\u30D9\u30FC\u30B9\u306E\u8A8D\u8A3C\uFF08\u4F8B\uFF1AOpenRouter\u3001ModelScope\uFF09",
      "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",
      "Note: Your existing API key will not be cleared when using Qwen OAuth.": "\u6CE8: Qwen OAuth\u3092\u4F7F\u7528\u3057\u3066\u3082\u3001\u65E2\u5B58\u306EAPI\u30AD\u30FC\u306F\u30AF\u30EA\u30A2\u3055\u308C\u307E\u305B\u3093\u3002",
      "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)",
      Modality: "\u30E2\u30C0\u30EA\u30C6\u30A3",
      "Context Window": "\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30A6\u30A3\u30F3\u30C9\u30A6",
      text: "\u30C6\u30AD\u30B9\u30C8",
      "text-only": "\u30C6\u30AD\u30B9\u30C8\u306E\u307F",
      image: "\u753B\u50CF",
      pdf: "PDF",
      audio: "\u97F3\u58F0",
      video: "\u52D5\u753B",
      "not set": "\u672A\u8A2D\u5B9A",
      none: "\u306A\u3057",
      unknown: "\u4E0D\u660E",
      "Qwen 3.6 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.6 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",
      "Manage permission rules": "\u6A29\u9650\u30EB\u30FC\u30EB\u3092\u7BA1\u7406",
      Allow: "\u8A31\u53EF",
      Ask: "\u78BA\u8A8D",
      Deny: "\u62D2\u5426",
      Workspace: "\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9",
      "Qwen Code won't ask before using allowed tools.": "Qwen Code \u306F\u8A31\u53EF\u3055\u308C\u305F\u30C4\u30FC\u30EB\u3092\u4F7F\u7528\u3059\u308B\u524D\u306B\u78BA\u8A8D\u3057\u307E\u305B\u3093\u3002",
      "Qwen Code will ask before using these tools.": "Qwen Code \u306F\u3053\u308C\u3089\u306E\u30C4\u30FC\u30EB\u3092\u4F7F\u7528\u3059\u308B\u524D\u306B\u78BA\u8A8D\u3057\u307E\u3059\u3002",
      "Qwen Code is not allowed to use denied tools.": "Qwen Code \u306F\u62D2\u5426\u3055\u308C\u305F\u30C4\u30FC\u30EB\u3092\u4F7F\u7528\u3067\u304D\u307E\u305B\u3093\u3002",
      "Manage trusted directories for this workspace.": "\u3053\u306E\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u306E\u4FE1\u983C\u6E08\u307F\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u7BA1\u7406\u3057\u307E\u3059\u3002",
      "Any use of the {{tool}} tool": "{{tool}} \u30C4\u30FC\u30EB\u306E\u3059\u3079\u3066\u306E\u4F7F\u7528",
      "{{tool}} commands matching '{{pattern}}'": "'{{pattern}}' \u306B\u4E00\u81F4\u3059\u308B {{tool}} \u30B3\u30DE\u30F3\u30C9",
      "From user settings": "\u30E6\u30FC\u30B6\u30FC\u8A2D\u5B9A\u304B\u3089",
      "From project settings": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u8A2D\u5B9A\u304B\u3089",
      "From session": "\u30BB\u30C3\u30B7\u30E7\u30F3\u304B\u3089",
      "Project settings (local)": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u8A2D\u5B9A\uFF08\u30ED\u30FC\u30AB\u30EB\uFF09",
      "Saved in .qwen/settings.local.json": ".qwen/settings.local.json \u306B\u4FDD\u5B58",
      "Project settings": "\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u8A2D\u5B9A",
      "Checked in at .qwen/settings.json": ".qwen/settings.json \u306B\u30C1\u30A7\u30C3\u30AF\u30A4\u30F3",
      "User settings": "\u30E6\u30FC\u30B6\u30FC\u8A2D\u5B9A",
      "Saved in at ~/.qwen/settings.json": "~/.qwen/settings.json \u306B\u4FDD\u5B58",
      "Add a new rule\u2026": "\u65B0\u3057\u3044\u30EB\u30FC\u30EB\u3092\u8FFD\u52A0\u2026",
      "Add {{type}} permission rule": "{{type}}\u6A29\u9650\u30EB\u30FC\u30EB\u3092\u8FFD\u52A0",
      "Permission rules are a tool name, optionally followed by a specifier in parentheses.": "\u6A29\u9650\u30EB\u30FC\u30EB\u306F\u30C4\u30FC\u30EB\u540D\u3067\u3001\u30AA\u30D7\u30B7\u30E7\u30F3\u3067\u62EC\u5F27\u5185\u306B\u6307\u5B9A\u5B50\u3092\u4ED8\u3051\u307E\u3059\u3002",
      "e.g.,": "\u4F8B\uFF1A",
      or: "\u307E\u305F\u306F",
      "Enter permission rule\u2026": "\u6A29\u9650\u30EB\u30FC\u30EB\u3092\u5165\u529B\u2026",
      "Enter to submit \xB7 Esc to cancel": "Enter \u3067\u9001\u4FE1 \xB7 Esc \u3067\u30AD\u30E3\u30F3\u30BB\u30EB",
      "Where should this rule be saved?": "\u3053\u306E\u30EB\u30FC\u30EB\u3092\u3069\u3053\u306B\u4FDD\u5B58\u3057\u307E\u3059\u304B\uFF1F",
      "Enter to confirm \xB7 Esc to cancel": "Enter \u3067\u78BA\u8A8D \xB7 Esc \u3067\u30AD\u30E3\u30F3\u30BB\u30EB",
      "Delete {{type}} rule?": "{{type}}\u30EB\u30FC\u30EB\u3092\u524A\u9664\u3057\u307E\u3059\u304B\uFF1F",
      "Are you sure you want to delete this permission rule?": "\u3053\u306E\u6A29\u9650\u30EB\u30FC\u30EB\u3092\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B\uFF1F",
      "Permissions:": "\u6A29\u9650\uFF1A",
      "(\u2190/\u2192 or tab to cycle)": "\uFF08\u2190/\u2192 \u307E\u305F\u306F Tab \u3067\u5207\u66FF\uFF09",
      "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel": "\u2191\u2193 \u3067\u30CA\u30D3\u30B2\u30FC\u30C8 \xB7 Enter \u3067\u9078\u629E \xB7 \u5165\u529B\u3067\u691C\u7D22 \xB7 Esc \u3067\u30AD\u30E3\u30F3\u30BB\u30EB",
      "Search\u2026": "\u691C\u7D22\u2026",
      "Use /trust to manage folder trust settings for this workspace.": "/trust \u3092\u4F7F\u7528\u3057\u3066\u3053\u306E\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u306E\u30D5\u30A9\u30EB\u30C0\u4FE1\u983C\u8A2D\u5B9A\u3092\u7BA1\u7406\u3057\u307E\u3059\u3002",
      // Workspace directory management
      "Add directory\u2026": "\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u8FFD\u52A0\u2026",
      "Add directory to workspace": "\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u306B\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u8FFD\u52A0",
      "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.": "Qwen Code \u306F\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u5185\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u8AAD\u307F\u53D6\u308A\u3001\u81EA\u52D5\u7DE8\u96C6\u627F\u8A8D\u304C\u6709\u52B9\u306A\u5834\u5408\u306F\u7DE8\u96C6\u3092\u884C\u3048\u307E\u3059\u3002",
      "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.": "Qwen Code \u306F\u3053\u306E\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u5185\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u8AAD\u307F\u53D6\u308A\u3001\u81EA\u52D5\u7DE8\u96C6\u627F\u8A8D\u304C\u6709\u52B9\u306A\u5834\u5408\u306F\u7DE8\u96C6\u3092\u884C\u3048\u307E\u3059\u3002",
      "Enter the path to the directory:": "\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306E\u30D1\u30B9\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044:",
      "Enter directory path\u2026": "\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u30D1\u30B9\u3092\u5165\u529B\u2026",
      "Tab to complete \xB7 Enter to add \xB7 Esc to cancel": "Tab \u3067\u88DC\u5B8C \xB7 Enter \u3067\u8FFD\u52A0 \xB7 Esc \u3067\u30AD\u30E3\u30F3\u30BB\u30EB",
      "Remove directory?": "\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u524A\u9664\u3057\u307E\u3059\u304B\uFF1F",
      "Are you sure you want to remove this directory from the workspace?": "\u3053\u306E\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u304B\u3089\u524A\u9664\u3057\u3066\u3082\u3088\u308D\u3057\u3044\u3067\u3059\u304B\uFF1F",
      "  (Original working directory)": "  \uFF08\u5143\u306E\u4F5C\u696D\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\uFF09",
      "  (from settings)": "  \uFF08\u8A2D\u5B9A\u3088\u308A\uFF09",
      "Directory does not exist.": "\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u304C\u5B58\u5728\u3057\u307E\u305B\u3093\u3002",
      "Path is not a directory.": "\u30D1\u30B9\u306F\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002",
      "This directory is already in the workspace.": "\u3053\u306E\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306F\u3059\u3067\u306B\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u306B\u542B\u307E\u308C\u3066\u3044\u307E\u3059\u3002",
      "Already covered by existing directory: {{dir}}": "\u65E2\u5B58\u306E\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u306B\u3088\u3063\u3066\u65E2\u306B\u30AB\u30D0\u30FC\u3055\u308C\u3066\u3044\u307E\u3059: {{dir}}",
      // 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",
      "Press \u2191 to edit queued messages": "\u2191 \u3092\u62BC\u3057\u3066\u30AD\u30E5\u30FC\u5185\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u7DE8\u96C6",
      // 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",
      "Press Ctrl+O to toggle compact mode \u2014 hide tool output and thinking for a cleaner view.": "Ctrl+O \u3067\u30B3\u30F3\u30D1\u30AF\u30C8\u30E2\u30FC\u30C9\u3092\u5207\u308A\u66FF\u3048 \u2014 \u30C4\u30FC\u30EB\u51FA\u529B\u3068\u601D\u8003\u3092\u975E\u8868\u793A\u306B\u3057\u3066\u3059\u3063\u304D\u308A\u8868\u793A\u3002",
      "Add a QWEN.md file to give Qwen Code persistent project context.": "QWEN.md \u30D5\u30A1\u30A4\u30EB\u3092\u8FFD\u52A0\u3059\u308B\u3068\u3001Qwen Code \u306B\u6C38\u7D9A\u7684\u306A\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u3092\u4E0E\u3048\u3089\u308C\u307E\u3059\u3002",
      "Use /btw to ask a quick side question without disrupting the conversation.": "\u4F1A\u8A71\u3092\u4E2D\u65AD\u305B\u305A\u306B /btw \u3067\u3061\u3087\u3063\u3068\u3057\u305F\u6A2A\u9053\u306E\u8CEA\u554F\u304C\u3067\u304D\u307E\u3059\u3002",
      "Context is almost full! Run /compress now or start /new to continue.": "\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u304C\u3082\u3046\u3059\u3050\u3044\u3063\u3071\u3044\u3067\u3059\uFF01\u4ECA\u3059\u3050 /compress \u3092\u5B9F\u884C\u3059\u308B\u304B\u3001/new \u3092\u958B\u59CB\u3057\u3066\u7D9A\u3051\u3066\u304F\u3060\u3055\u3044\u3002",
      "Context is getting full. Use /compress to free up space.": "\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u304C\u57CB\u307E\u308A\u3064\u3064\u3042\u308A\u307E\u3059\u3002/compress \u3092\u4F7F\u3063\u3066\u7A7A\u304D\u3092\u5897\u3084\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "Long conversation? /compress summarizes history to free context.": "\u4F1A\u8A71\u304C\u9577\u304F\u306A\u308A\u307E\u3057\u305F\u304B\uFF1F /compress \u306F\u5C65\u6B74\u3092\u8981\u7D04\u3057\u3066\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u3092\u7A7A\u3051\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
      // ============================================================================
      "You can configure your API key and models in settings.json": "settings.json \u3067 API \u30AD\u30FC\u3068\u30E2\u30C7\u30EB\u3092\u8A2D\u5B9A\u3067\u304D\u307E\u3059",
      "Refer to the documentation for setup instructions": "\u30BB\u30C3\u30C8\u30A2\u30C3\u30D7\u624B\u9806\u306F\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "API key cannot be empty.": "API\u30AD\u30FC\u306F\u7A7A\u306B\u3067\u304D\u307E\u305B\u3093\u3002",
      "You can get your Coding Plan API key here": "Coding Plan API\u30AD\u30FC\u306F\u3053\u3061\u3089\u3067\u53D6\u5F97\u3067\u304D\u307E\u3059",
      "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",
      "Paste your api key of ModelStudio Coding Plan and you're all set!": "ModelStudio Coding Plan\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",
      "Select Region for Coding Plan": "Coding Plan\u306E\u30EA\u30FC\u30B8\u30E7\u30F3\u3092\u9078\u629E",
      "Choose based on where your account is registered": "\u30A2\u30AB\u30A6\u30F3\u30C8\u306E\u767B\u9332\u5148\u306B\u5FDC\u3058\u3066\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044",
      "Enter Coding Plan API Key": "Coding Plan API\u30AD\u30FC\u3092\u5165\u529B",
      // ============================================================================
      // 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",
      '{{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",
      // ============================================================================
      // Context Usage Component
      // ============================================================================
      "Context Usage": "\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u4F7F\u7528\u91CF",
      "% used": "% \u4F7F\u7528",
      "% context used": "% \u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u4F7F\u7528",
      "Context exceeds limit! Use /compress or /clear to reduce.": "\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u304C\u5236\u9650\u3092\u8D85\u3048\u3066\u3044\u307E\u3059\uFF01/compress \u307E\u305F\u306F /clear \u3092\u4F7F\u7528\u3057\u3066\u6E1B\u3089\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "Use /compress or /clear": "/compress \u307E\u305F\u306F /clear \u3092\u4F7F\u7528",
      "No API response yet. Send a message to see actual usage.": "API\u5FDC\u7B54\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u9001\u4FE1\u3057\u3066\u5B9F\u969B\u306E\u4F7F\u7528\u91CF\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "Estimated pre-conversation overhead": "\u63A8\u5B9A\u4E8B\u524D\u4F1A\u8A71\u30AA\u30FC\u30D0\u30FC\u30D8\u30C3\u30C9",
      "Context window": "\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30A6\u30A3\u30F3\u30C9\u30A6",
      tokens: "\u30C8\u30FC\u30AF\u30F3",
      Used: "\u4F7F\u7528\u6E08\u307F",
      Free: "\u7A7A\u304D",
      "Autocompact buffer": "\u81EA\u52D5\u5727\u7E2E\u30D0\u30C3\u30D5\u30A1",
      "Usage by category": "\u30AB\u30C6\u30B4\u30EA\u5225\u306E\u4F7F\u7528\u91CF",
      "System prompt": "\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8",
      "Built-in tools": "\u7D44\u307F\u8FBC\u307F\u30C4\u30FC\u30EB",
      "MCP tools": "MCP\u30C4\u30FC\u30EB",
      "Memory files": "\u30E1\u30E2\u30EA\u30D5\u30A1\u30A4\u30EB",
      Skills: "\u30B9\u30AD\u30EB",
      Messages: "\u30E1\u30C3\u30BB\u30FC\u30B8",
      "Show context window usage breakdown.": "\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30A6\u30A3\u30F3\u30C9\u30A6\u306E\u4F7F\u7528\u72B6\u6CC1\u3092\u8868\u793A\u3057\u307E\u3059\u3002",
      "Run /context detail for per-item breakdown.": "/context detail \u3092\u5B9F\u884C\u3059\u308B\u3068\u9805\u76EE\u3054\u3068\u306E\u5185\u8A33\u3092\u8868\u793A\u3057\u307E\u3059\u3002",
      active: "\u6709\u52B9",
      "body loaded": "\u672C\u6587\u8AAD\u307F\u8FBC\u307F\u6E08\u307F",
      memory: "\u30E1\u30E2\u30EA",
      "{{region}} configuration updated successfully.": "{{region}} \u306E\u8A2D\u5B9A\u304C\u6B63\u5E38\u306B\u66F4\u65B0\u3055\u308C\u307E\u3057\u305F\u3002",
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json.": "{{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\u3002",
      "Tip: Use /model to switch between available Coding Plan models.": "\u30D2\u30F3\u30C8: /model \u3067\u5229\u7528\u53EF\u80FD\u306A Coding Plan \u30E2\u30C7\u30EB\u3092\u5207\u308A\u66FF\u3048\u3089\u308C\u307E\u3059\u3002",
      // ============================================================================
      // Ask User Question Tool
      // ============================================================================
      "Please answer the following question(s):": "\u4EE5\u4E0B\u306E\u8CEA\u554F\u306B\u7B54\u3048\u3066\u304F\u3060\u3055\u3044\uFF1A",
      "Cannot ask user questions in non-interactive mode. Please run in interactive mode to use this tool.": "\u975E\u5BFE\u8A71\u30E2\u30FC\u30C9\u3067\u306F\u30E6\u30FC\u30B6\u30FC\u306B\u8CEA\u554F\u3067\u304D\u307E\u305B\u3093\u3002\u3053\u306E\u30C4\u30FC\u30EB\u3092\u4F7F\u7528\u3059\u308B\u306B\u306F\u5BFE\u8A71\u30E2\u30FC\u30C9\u3067\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "User declined to answer the questions.": "\u30E6\u30FC\u30B6\u30FC\u306F\u8CEA\u554F\u3078\u306E\u56DE\u7B54\u3092\u62D2\u5426\u3057\u307E\u3057\u305F\u3002",
      "User has provided the following answers:": "\u30E6\u30FC\u30B6\u30FC\u306F\u4EE5\u4E0B\u306E\u56DE\u7B54\u3092\u63D0\u4F9B\u3057\u307E\u3057\u305F\uFF1A",
      "Failed to process user answers:": "\u30E6\u30FC\u30B6\u30FC\u56DE\u7B54\u306E\u51E6\u7406\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF1A",
      "Type something...": "\u4F55\u304B\u5165\u529B...",
      Submit: "\u9001\u4FE1",
      "Submit answers": "\u56DE\u7B54\u3092\u9001\u4FE1",
      Cancel: "\u30AD\u30E3\u30F3\u30BB\u30EB",
      "Your answers:": "\u3042\u306A\u305F\u306E\u56DE\u7B54\uFF1A",
      "(not answered)": "(\u672A\u56DE\u7B54)",
      "Ready to submit your answers?": "\u56DE\u7B54\u3092\u9001\u4FE1\u3057\u307E\u3059\u304B\uFF1F",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select": "\u2191/\u2193: \u30CA\u30D3\u30B2\u30FC\u30C8 | \u2190/\u2192: \u30BF\u30D6\u5207\u308A\u66FF\u3048 | Enter: \u9078\u629E",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: \u30CA\u30D3\u30B2\u30FC\u30C8 | \u2190/\u2192: \u30BF\u30D6\u5207\u308A\u66FF\u3048 | Space/Enter: \u5207\u308A\u66FF\u3048 | Esc: \u30AD\u30E3\u30F3\u30BB\u30EB",
      "\u2191/\u2193: Navigate | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: \u30CA\u30D3\u30B2\u30FC\u30C8 | Space/Enter: \u5207\u308A\u66FF\u3048 | Esc: \u30AD\u30E3\u30F3\u30BB\u30EB",
      "\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel": "\u2191/\u2193: \u30CA\u30D3\u30B2\u30FC\u30C8 | Enter: \u9078\u629E | Esc: \u30AD\u30E3\u30F3\u30BB\u30EB",
      // ============================================================================
      // Commands - Auth
      // ============================================================================
      "Configure Qwen authentication information with Qwen-OAuth or Alibaba Cloud Coding Plan": "Qwen-OAuth \u307E\u305F\u306F Alibaba Cloud Coding Plan \u3067 Qwen \u8A8D\u8A3C\u60C5\u5831\u3092\u8A2D\u5B9A\u3059\u308B",
      "Authenticate using Qwen OAuth": "Qwen OAuth \u3067\u8A8D\u8A3C\u3059\u308B",
      "Authenticate using Alibaba Cloud Coding Plan": "Alibaba Cloud Coding Plan \u3067\u8A8D\u8A3C\u3059\u308B",
      "Region for Coding Plan (china/global)": "Coding Plan \u306E\u30EA\u30FC\u30B8\u30E7\u30F3 (china/global)",
      "API key for Coding Plan": "Coding Plan \u306E API \u30AD\u30FC",
      "Show current authentication status": "\u73FE\u5728\u306E\u8A8D\u8A3C\u30B9\u30C6\u30FC\u30BF\u30B9\u3092\u8868\u793A",
      "Authentication completed successfully.": "\u8A8D\u8A3C\u304C\u6B63\u5E38\u306B\u5B8C\u4E86\u3057\u307E\u3057\u305F\u3002",
      "Starting Qwen OAuth authentication...": "Qwen OAuth \u8A8D\u8A3C\u3092\u958B\u59CB\u3057\u3066\u3044\u307E\u3059...",
      "Successfully authenticated with Qwen OAuth.": "Qwen OAuth \u3067\u306E\u8A8D\u8A3C\u306B\u6210\u529F\u3057\u307E\u3057\u305F\u3002",
      "Failed to authenticate with Qwen OAuth: {{error}}": "Qwen OAuth \u3067\u306E\u8A8D\u8A3C\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {{error}}",
      "Processing Alibaba Cloud Coding Plan authentication...": "Alibaba Cloud Coding Plan \u8A8D\u8A3C\u3092\u51E6\u7406\u3057\u3066\u3044\u307E\u3059...",
      "Successfully authenticated with Alibaba Cloud Coding Plan.": "Alibaba Cloud Coding Plan \u3067\u306E\u8A8D\u8A3C\u306B\u6210\u529F\u3057\u307E\u3057\u305F\u3002",
      "Failed to authenticate with Coding Plan: {{error}}": "Coding Plan \u3067\u306E\u8A8D\u8A3C\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {{error}}",
      "\u4E2D\u56FD (China)": "\u4E2D\u56FD (China)",
      "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)": "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)",
      Global: "\u30B0\u30ED\u30FC\u30D0\u30EB",
      "Alibaba Cloud (alibabacloud.com)": "Alibaba Cloud (alibabacloud.com)",
      "Select region for Coding Plan:": "Coding Plan \u306E\u30EA\u30FC\u30B8\u30E7\u30F3\u3092\u9078\u629E:",
      "Enter your Coding Plan API key: ": "Coding Plan \u306E API \u30AD\u30FC\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044: ",
      "Select authentication method:": "\u8A8D\u8A3C\u65B9\u6CD5\u3092\u9078\u629E:",
      "\n=== Authentication Status ===\n": "\n=== \u8A8D\u8A3C\u30B9\u30C6\u30FC\u30BF\u30B9 ===\n",
      "\u26A0\uFE0F  No authentication method configured.\n": "\u26A0\uFE0F  \u8A8D\u8A3C\u65B9\u6CD5\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\n",
      "Run one of the following commands to get started:\n": "\u4EE5\u4E0B\u306E\u30B3\u30DE\u30F3\u30C9\u306E\u3044\u305A\u308C\u304B\u3092\u5B9F\u884C\u3057\u3066\u958B\u59CB\u3057\u3066\u304F\u3060\u3055\u3044:\n",
      "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)": "  qwen auth qwen-oauth     - Qwen OAuth \u3067\u8A8D\u8A3C\uFF08\u7D42\u4E86\uFF09",
      "  qwen auth coding-plan      - Authenticate with Alibaba Cloud Coding Plan\n": "  qwen auth coding-plan      - Alibaba Cloud Coding Plan \u3067\u8A8D\u8A3C\n",
      "Or simply run:": "\u307E\u305F\u306F\u4EE5\u4E0B\u3092\u5B9F\u884C:",
      "  qwen auth                - Interactive authentication setup\n": "  qwen auth                - \u30A4\u30F3\u30BF\u30E9\u30AF\u30C6\u30A3\u30D6\u8A8D\u8A3C\u30BB\u30C3\u30C8\u30A2\u30C3\u30D7\n",
      "\u2713 Authentication Method: Qwen OAuth": "\u2713 \u8A8D\u8A3C\u65B9\u6CD5: Qwen OAuth",
      "  Type: Free tier (discontinued 2026-04-15)": "  \u30BF\u30A4\u30D7: \u7121\u6599\u67A0\uFF082026-04-15 \u7D42\u4E86\uFF09",
      "  Limit: No longer available": "  \u5236\u9650: \u5229\u7528\u4E0D\u53EF",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.": "Qwen OAuth \u7121\u6599\u67A0\u306F 2026-04-15 \u306B\u7D42\u4E86\u3057\u307E\u3057\u305F\u3002/auth \u3092\u5B9F\u884C\u3057\u3066 Coding Plan\u3001OpenRouter\u3001Fireworks AI\u3001\u307E\u305F\u306F\u4ED6\u306E\u30D7\u30ED\u30D0\u30A4\u30C0\u30FC\u306B\u5207\u308A\u66FF\u3048\u3066\u304F\u3060\u3055\u3044\u3002",
      "  Models: Qwen latest models\n": "  \u30E2\u30C7\u30EB: Qwen \u6700\u65B0\u30E2\u30C7\u30EB\n",
      "\u2713 Authentication Method: Alibaba Cloud Coding Plan": "\u2713 \u8A8D\u8A3C\u65B9\u6CD5: Alibaba Cloud Coding Plan",
      "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC": "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC",
      "Global - Alibaba Cloud": "\u30B0\u30ED\u30FC\u30D0\u30EB - Alibaba Cloud",
      "  Region: {{region}}": "  \u30EA\u30FC\u30B8\u30E7\u30F3: {{region}}",
      "  Current Model: {{model}}": "  \u73FE\u5728\u306E\u30E2\u30C7\u30EB: {{model}}",
      "  Config Version: {{version}}": "  \u8A2D\u5B9A\u30D0\u30FC\u30B8\u30E7\u30F3: {{version}}",
      "  Status: API key configured\n": "  \u30B9\u30C6\u30FC\u30BF\u30B9: API\u30AD\u30FC\u8A2D\u5B9A\u6E08\u307F\n",
      "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)": "\u26A0\uFE0F  \u8A8D\u8A3C\u65B9\u6CD5: Alibaba Cloud Coding Plan\uFF08\u4E0D\u5B8C\u5168\uFF09",
      "  Issue: API key not found in environment or settings\n": "  \u554F\u984C: \u74B0\u5883\u5909\u6570\u307E\u305F\u306F\u8A2D\u5B9A\u306BAPI\u30AD\u30FC\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\n",
      "  Run `qwen auth coding-plan` to re-configure.\n": "  `qwen auth coding-plan` \u3092\u5B9F\u884C\u3057\u3066\u518D\u8A2D\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002\n",
      "\u2713 Authentication Method: {{type}}": "\u2713 \u8A8D\u8A3C\u65B9\u6CD5: {{type}}",
      "  Status: Configured\n": "  \u30B9\u30C6\u30FC\u30BF\u30B9: \u8A2D\u5B9A\u6E08\u307F\n",
      "Failed to check authentication status: {{error}}": "\u8A8D\u8A3C\u30B9\u30C6\u30FC\u30BF\u30B9\u306E\u78BA\u8A8D\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {{error}}",
      "Select an option:": "\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u9078\u629E:",
      "Raw mode not available. Please run in an interactive terminal.": "Raw\u30E2\u30FC\u30C9\u304C\u5229\u7528\u3067\u304D\u307E\u305B\u3093\u3002\u30A4\u30F3\u30BF\u30E9\u30AF\u30C6\u30A3\u30D6\u30BF\u30FC\u30DF\u30CA\u30EB\u3067\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
      "(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n": "(\u2191 \u2193 \u77E2\u5370\u30AD\u30FC\u3067\u79FB\u52D5\u3001Enter \u3067\u9078\u629E\u3001Ctrl+C \u3067\u7D42\u4E86)\n",
      compact: "\u30B3\u30F3\u30D1\u30AF\u30C8",
      "compact mode: on (Ctrl+O off)": "\u30B3\u30F3\u30D1\u30AF\u30C8\u30E2\u30FC\u30C9: \u30AA\u30F3 (Ctrl+O \u3067\u30AA\u30D5)",
      "to toggle compact mode": "\u30B3\u30F3\u30D1\u30AF\u30C8\u30E2\u30FC\u30C9\u306E\u5207\u308A\u66FF\u3048",
      "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).": "\u30B3\u30F3\u30D1\u30AF\u30C8\u30E2\u30FC\u30C9\u3067\u30C4\u30FC\u30EB\u51FA\u529B\u3068\u601D\u8003\u3092\u975E\u8868\u793A\u306B\u3057\u307E\u3059\uFF08Ctrl+O \u3067\u5207\u308A\u66FF\u3048\uFF09\u3002",
      "Press Ctrl+O to show full tool output": "Ctrl+O \u3067\u5B8C\u5168\u306A\u30C4\u30FC\u30EB\u51FA\u529B\u3092\u8868\u793A",
      "Switch to plan mode or exit plan mode": "Switch to plan mode or exit plan mode",
      "Exited plan mode. Previous approval mode restored.": "Exited plan mode. Previous approval mode restored.",
      "Enabled plan mode. The agent will analyze and plan without executing tools.": "Enabled plan mode. The agent will analyze and plan without executing tools.",
      'Already in plan mode. Use "/plan exit" to exit plan mode.': 'Already in plan mode. Use "/plan exit" to exit plan mode.',
      'Not in plan mode. Use "/plan" to enter plan mode first.': 'Not in plan mode. Use "/plan" to enter plan mode first.',
      "Set up Qwen Code's status line UI": "Set up Qwen Code's status line UI"
    };
  }
});

// packages/cli/src/i18n/locales/pt.js
var pt_exports = {};
__export(pt_exports, {
  default: () => pt_default2
});
var pt_default2;
var init_pt2 = __esm({
  "packages/cli/src/i18n/locales/pt.js"() {
    "use strict";
    init_esbuild_shims();
    pt_default2 = {
      // ============================================================================
      // 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",
      "to toggle compact mode": "alternar modo compacto",
      "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",
      "Fast Model": "Modelo R\xE1pido",
      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]",
      "List available skills.": "Listar habilidades dispon\xEDveis.",
      "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",
      "Enter to submit, Esc to go back": "Enter para enviar, 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)",
      "Auto (detect terminal theme)": "Autom\xE1tico (detectar tema do terminal)",
      Auto: "Autom\xE1tico",
      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",
      "Open MCP management dialog, or authenticate with OAuth-enabled servers": "Abrir di\xE1logo de gerenciamento MCP ou autenticar com servidor habilitado para OAuth",
      "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",
      "Manage installed extensions": "Gerenciar extens\xF5es instaladas",
      "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).",
      // ============================================================================
      // Commands - Hooks
      // ============================================================================
      "Manage Qwen Code hooks": "Gerenciar hooks do Qwen Code",
      "List all configured hooks": "Listar todos os hooks configurados",
      "Enable a disabled hook": "Ativar um hook desativado",
      "Disable an active hook": "Desativar um hook ativo",
      // Hooks - Dialog
      Hooks: "Hooks",
      "Loading hooks...": "Carregando hooks...",
      "Error loading hooks:": "Erro ao carregar hooks:",
      "Press Escape to close": "Pressione Escape para fechar",
      "Press Escape, Ctrl+C, or Ctrl+D to cancel": "Pressione Escape, Ctrl+C ou Ctrl+D para cancelar",
      "Press Space, Enter, or Escape to dismiss": "Pressione Espa\xE7o, Enter ou Escape para dispensar",
      "No hook selected": "Nenhum hook selecionado",
      // Hooks - List Step
      "No hook events found.": "Nenhum evento de hook encontrado.",
      "{{count}} hook configured": "{{count}} hook configurado",
      "{{count}} hooks configured": "{{count}} hooks configurados",
      "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.": "Este menu \xE9 somente leitura. Para adicionar ou modificar hooks, edite settings.json diretamente ou pergunte ao Qwen Code.",
      "Enter to select \xB7 Esc to cancel": "Enter para selecionar \xB7 Esc para cancelar",
      // Hooks - Detail Step
      "Exit codes:": "C\xF3digos de sa\xEDda:",
      "Configured hooks:": "Hooks configurados:",
      "No hooks configured for this event.": "Nenhum hook configurado para este evento.",
      "To add hooks, edit settings.json directly or ask Qwen.": "Para adicionar hooks, edite settings.json diretamente ou pergunte ao Qwen.",
      "Enter to select \xB7 Esc to go back": "Enter para selecionar \xB7 Esc para voltar",
      // Hooks - Config Detail Step
      "Hook details": "Detalhes do Hook",
      "Event:": "Evento:",
      "Extension:": "Extens\xE3o:",
      "Desc:": "Descri\xE7\xE3o:",
      "No hook config selected": "Nenhuma configura\xE7\xE3o de hook selecionada",
      "To modify or remove this hook, edit settings.json directly or ask Qwen to help.": "Para modificar ou remover este hook, edite settings.json diretamente ou pergunte ao Qwen.",
      // Hooks - Disabled Step
      "Hook Configuration - Disabled": "Configura\xE7\xE3o de Hook - Desativado",
      "All hooks are currently disabled. You have {{count}} that are not running.": "Todos os hooks est\xE3o desativados. Voc\xEA tem {{count}} que n\xE3o est\xE3o em execu\xE7\xE3o.",
      "{{count}} configured hook": "{{count}} hook configurado",
      "{{count}} configured hooks": "{{count}} hooks configurados",
      "When hooks are disabled:": "Quando os hooks est\xE3o desativados:",
      "No hook commands will execute": "Nenhum comando de hook ser\xE1 executado",
      "StatusLine will not be displayed": "StatusLine n\xE3o ser\xE1 exibido",
      "Tool operations will proceed without hook validation": "As opera\xE7\xF5es de ferramentas prosseguir\xE3o sem valida\xE7\xE3o de hook",
      'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.': 'Para reativar os hooks, remova "disableAllHooks" do settings.json ou pergunte ao Qwen Code.',
      // Hooks - Source
      Project: "Projeto",
      User: "Usu\xE1rio",
      System: "Sistema",
      Extension: "Extens\xE3o",
      "Local Settings": "Configura\xE7\xF5es Locais",
      "User Settings": "Configura\xE7\xF5es do Usu\xE1rio",
      "System Settings": "Configura\xE7\xF5es do Sistema",
      Extensions: "Extens\xF5es",
      "Session (temporary)": "Sess\xE3o (tempor\xE1rio)",
      // Hooks - Status
      "\u2713 Enabled": "\u2713 Ativado",
      "\u2717 Disabled": "\u2717 Desativado",
      // Hooks - Event Descriptions (short)
      "Before tool execution": "Antes da execu\xE7\xE3o da ferramenta",
      "After tool execution": "Ap\xF3s a execu\xE7\xE3o da ferramenta",
      "After tool execution fails": "Ap\xF3s a falha da execu\xE7\xE3o da ferramenta",
      "When notifications are sent": "Quando notifica\xE7\xF5es s\xE3o enviadas",
      "When the user submits a prompt": "Quando o usu\xE1rio envia um prompt",
      "When a new session is started": "Quando uma nova sess\xE3o \xE9 iniciada",
      "Right before Qwen Code concludes its response": "Logo antes do Qwen Code concluir sua resposta",
      "When a subagent (Agent tool call) is started": "Quando um subagente (chamada de ferramenta Agent) \xE9 iniciado",
      "Right before a subagent concludes its response": "Logo antes de um subagente concluir sua resposta",
      "Before conversation compaction": "Antes da compacta\xE7\xE3o da conversa",
      "When a session is ending": "Quando uma sess\xE3o est\xE1 terminando",
      "When a permission dialog is displayed": "Quando um di\xE1logo de permiss\xE3o \xE9 exibido",
      // Hooks - Event Descriptions (detailed)
      "Input to command is JSON of tool call arguments.": "A entrada para o comando \xE9 JSON dos argumentos da chamada da ferramenta.",
      'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': 'A entrada para o comando \xE9 JSON com campos "inputs" (argumentos da chamada da ferramenta) e "response" (resposta da chamada da ferramenta).',
      "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.": "A entrada para o comando \xE9 JSON com tool_name, tool_input, tool_use_id, error, error_type, is_interrupt e is_timeout.",
      "Input to command is JSON with notification message and type.": "A entrada para o comando \xE9 JSON com mensagem e tipo de notifica\xE7\xE3o.",
      "Input to command is JSON with original user prompt text.": "A entrada para o comando \xE9 JSON com o texto original do prompt do usu\xE1rio.",
      "Input to command is JSON with session start source.": "A entrada para o comando \xE9 JSON com a fonte de in\xEDcio da sess\xE3o.",
      "Input to command is JSON with session end reason.": "A entrada para o comando \xE9 JSON com o motivo do fim da sess\xE3o.",
      "Input to command is JSON with agent_id and agent_type.": "A entrada para o comando \xE9 JSON com agent_id e agent_type.",
      "Input to command is JSON with agent_id, agent_type, and agent_transcript_path.": "A entrada para o comando \xE9 JSON com agent_id, agent_type e agent_transcript_path.",
      "Input to command is JSON with compaction details.": "A entrada para o comando \xE9 JSON com detalhes da compacta\xE7\xE3o.",
      "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.": "A entrada para o comando \xE9 JSON com tool_name, tool_input e tool_use_id. Sa\xEDda \xE9 JSON com hookSpecificOutput contendo decis\xE3o de permitir ou negar.",
      // Hooks - Exit Code Descriptions
      "stdout/stderr not shown": "stdout/stderr n\xE3o exibido",
      "show stderr to model and continue conversation": "mostrar stderr ao modelo e continuar conversa",
      "show stderr to user only": "mostrar stderr apenas ao usu\xE1rio",
      "stdout shown in transcript mode (ctrl+o)": "stdout exibido no modo transcri\xE7\xE3o (ctrl+o)",
      "show stderr to model immediately": "mostrar stderr ao modelo imediatamente",
      "show stderr to user only but continue with tool call": "mostrar stderr apenas ao usu\xE1rio mas continuar com chamada de ferramenta",
      "block processing, erase original prompt, and show stderr to user only": "bloquear processamento, apagar prompt original e mostrar stderr apenas ao usu\xE1rio",
      "stdout shown to Qwen": "stdout mostrado ao Qwen",
      "show stderr to user only (blocking errors ignored)": "mostrar stderr apenas ao usu\xE1rio (erros de bloqueio ignorados)",
      "command completes successfully": "comando conclu\xEDdo com sucesso",
      "stdout shown to subagent": "stdout mostrado ao subagente",
      "show stderr to subagent and continue having it run": "mostrar stderr ao subagente e continuar executando",
      "stdout appended as custom compact instructions": "stdout anexado como instru\xE7\xF5es de compacta\xE7\xE3o personalizadas",
      "block compaction": "bloquear compacta\xE7\xE3o",
      "show stderr to user only but continue with compaction": "mostrar stderr apenas ao usu\xE1rio mas continuar com compacta\xE7\xE3o",
      "use hook decision if provided": "usar decis\xE3o do hook se fornecida",
      // Hooks - Messages
      "Config not loaded.": "Configura\xE7\xE3o n\xE3o carregada.",
      "Hooks are not enabled. Enable hooks in settings to use this feature.": "Hooks n\xE3o est\xE3o ativados. Ative hooks nas configura\xE7\xF5es para usar este recurso.",
      "No hooks configured. Add hooks in your settings.json file.": "Nenhum hook configurado. Adicione hooks no seu arquivo settings.json.",
      "Configured Hooks ({{count}} total)": "Hooks Configurados ({{count}} total)",
      // ============================================================================
      // Commands - Session Export
      // ============================================================================
      "Export current session message history to a file": "Exportar o hist\xF3rico de mensagens da sess\xE3o atual para um arquivo",
      "Export session to HTML format": "Exportar a sess\xE3o para o formato HTML",
      "Export session to JSON format": "Exportar a sess\xE3o para o formato JSON",
      "Export session to JSONL format (one message per line)": "Exportar a sess\xE3o para o formato JSONL (uma mensagem por linha)",
      "Export session to markdown format": "Exportar a sess\xE3o para o formato Markdown",
      // ============================================================================
      // Commands - Insights
      // ============================================================================
      "generate personalized programming insights from your chat history": "Gerar insights personalizados de programa\xE7\xE3o a partir do seu hist\xF3rico de chat",
      // ============================================================================
      // Commands - Session History
      // ============================================================================
      "Resume a previous session": "Retomar uma sess\xE3o anterior",
      "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested": "Restaurar uma chamada de ferramenta. Isso redefinir\xE1 o hist\xF3rico da conversa e dos arquivos para o estado em que a chamada da ferramenta foi sugerida",
      "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",
      "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}}"',
      "Open auto-memory folder": "Abrir pasta de mem\xF3ria autom\xE1tica",
      "Auto-memory: {{status}}": "Mem\xF3ria autom\xE1tica: {{status}}",
      "Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream to run": "Consolida\xE7\xE3o autom\xE1tica: {{status}} \xB7 {{lastDream}} \xB7 /dream para executar",
      never: "nunca",
      on: "ativado",
      off: "desativado",
      "\u2746 dreaming": "\u2746 consolidando",
      "Remove matching entries from managed auto-memory.": "Remover entradas correspondentes da mem\xF3ria autom\xE1tica gerenciada.",
      "Usage: /forget <memory text to remove>": "Uso: /forget <texto de mem\xF3ria a remover>",
      "No managed auto-memory entries matched: {{query}}": "Nenhuma entrada de mem\xF3ria autom\xE1tica gerenciada correspondeu: {{query}}",
      "Show managed auto-memory status.": "Mostrar status da mem\xF3ria autom\xE1tica gerenciada.",
      "Run managed auto-memory extraction for the current session.": "Executar extra\xE7\xE3o de mem\xF3ria autom\xE1tica gerenciada para a sess\xE3o atual.",
      "Managed auto-memory root: {{root}}": "Raiz da mem\xF3ria autom\xE1tica gerenciada: {{root}}",
      "Managed auto-memory topics:": "T\xF3picos de mem\xF3ria autom\xE1tica gerenciada:",
      "No extraction cursor found yet.": "Nenhum cursor de extra\xE7\xE3o encontrado ainda.",
      "Cursor: session={{sessionId}}, offset={{offset}}, updated={{updatedAt}}": "Cursor: sess\xE3o={{sessionId}}, offset={{offset}}, atualizado={{updatedAt}}",
      "No chat client available to extract memory.": "Nenhum cliente de chat dispon\xEDvel para extrair mem\xF3ria.",
      "Managed auto-memory extraction is already running.": "A extra\xE7\xE3o de mem\xF3ria autom\xE1tica gerenciada j\xE1 est\xE1 em execu\xE7\xE3o.",
      "Managed auto-memory extraction found no new durable memories.": "A extra\xE7\xE3o de mem\xF3ria autom\xE1tica gerenciada n\xE3o encontrou novas mem\xF3rias dur\xE1veis.",
      "Consolidate managed auto-memory topic files.": "Consolidar arquivos de t\xF3picos de mem\xF3ria autom\xE1tica gerenciada.",
      "Managed auto-memory dream found nothing to improve.": "A consolida\xE7\xE3o de mem\xF3ria autom\xE1tica n\xE3o encontrou nada para melhorar.",
      "Deduplicated entries: {{count}}": "Entradas desduplicadas: {{count}}",
      "Save a durable memory using the save_memory tool.": "Salvar uma mem\xF3ria dur\xE1vel usando a ferramenta save_memory.",
      "Usage: /remember [--global|--project] <text to remember>": "Uso: /remember [--global|--project] <texto a lembrar>",
      // ============================================================================
      // 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.",
      "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}}'...",
      "Discovered {{count}} tool(s) from '{{name}}'.": "{{count}} ferramenta(s) descoberta(s) de '{{name}}'.",
      "Authentication complete. Returning to server details...": "Autentica\xE7\xE3o conclu\xEDda. Retornando aos detalhes do servidor...",
      "Authentication successful.": "Autentica\xE7\xE3o bem-sucedida.",
      "If the browser does not open, copy and paste this URL into your browser:": "Se o navegador n\xE3o abrir, copie e cole esta URL no seu navegador:",
      "Make sure to copy the COMPLETE URL - it may wrap across multiple lines.": "\u26A0\uFE0F  Certifique-se de copiar a URL COMPLETA \u2013 ela pode ocupar v\xE1rias linhas.",
      // ============================================================================
      // 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 (--fast for suggestion model)": "Trocar o modelo para esta sess\xE3o (--fast para modelo de sugest\xF5es)",
      "Set a lighter model for prompt suggestions and speculative execution": "Definir modelo mais leve para sugest\xF5es de prompt e execu\xE7\xE3o especulativa",
      "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",
      Yes: "Sim",
      No: "N\xE3o",
      "No (esc)": "N\xE3o (esc)",
      "Yes, allow always for this session": "Sim, permitir sempre para esta sess\xE3o",
      // MCP Management - Core translations
      "Manage MCP servers": "Gerenciar servidores MCP",
      "Server Detail": "Detalhes do servidor",
      "Disable Server": "Desativar servidor",
      Tools: "Ferramentas",
      "Tool Detail": "Detalhes da ferramenta",
      "MCP Management": "Gerenciamento MCP",
      "Loading...": "Carregando...",
      "Unknown step": "Etapa desconhecida",
      "Esc to back": "Esc para voltar",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close": "\u2191\u2193 navegar \xB7 Enter selecionar \xB7 Esc fechar",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back": "\u2191\u2193 navegar \xB7 Enter selecionar \xB7 Esc voltar",
      "\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back": "\u2191\u2193 navegar \xB7 Enter confirmar \xB7 Esc voltar",
      "User Settings (global)": "Configura\xE7\xF5es do usu\xE1rio (global)",
      "Workspace Settings (project-specific)": "Configura\xE7\xF5es do workspace (espec\xEDfico do projeto)",
      "Disable server:": "Desativar servidor:",
      "Select where to add the server to the exclude list:": "Selecione onde adicionar o servidor \xE0 lista de exclus\xE3o:",
      "Press Enter to confirm, Esc to cancel": "Enter para confirmar, Esc para cancelar",
      Disable: "Desativar",
      Enable: "Ativar",
      Authenticate: "Autenticar",
      "Re-authenticate": "Reautenticar",
      "Clear Authentication": "Limpar autentica\xE7\xE3o",
      disabled: "desativado",
      "Server:": "Servidor:",
      Reconnect: "Reconectar",
      "View tools": "Ver ferramentas",
      "Status:": "Status:",
      "Source:": "Fonte:",
      "Command:": "Comando:",
      "Working Directory:": "Diret\xF3rio de trabalho:",
      "Capabilities:": "Capacidades:",
      "No server selected": "Nenhum servidor selecionado",
      "(disabled)": "(desativado)",
      "Error:": "Erro:",
      tool: "ferramenta",
      tools: "ferramentas",
      connected: "conectado",
      connecting: "conectando",
      disconnected: "desconectado",
      error: "erro",
      // MCP Server List
      "User MCPs": "MCPs do usu\xE1rio",
      "Project MCPs": "MCPs do projeto",
      "Extension MCPs": "MCPs de extens\xE3o",
      server: "servidor",
      servers: "servidores",
      "Add MCP servers to your settings to get started.": "Adicione servidores MCP \xE0s suas configura\xE7\xF5es para come\xE7ar.",
      "Run qwen --debug to see error logs": "Execute qwen --debug para ver os logs de erro",
      // MCP OAuth Authentication
      "OAuth Authentication": "Autentica\xE7\xE3o OAuth",
      "Press Enter to start authentication, Esc to go back": "Pressione Enter para iniciar a autentica\xE7\xE3o, Esc para voltar",
      "Authenticating... Please complete the login in your browser.": "Autenticando... Por favor, conclua o login no seu navegador.",
      "Press Enter or Esc to go back": "Pressione Enter ou Esc para voltar",
      // MCP Tool List
      "No tools available for this server.": "Nenhuma ferramenta dispon\xEDvel para este servidor.",
      destructive: "destrutivo",
      "read-only": "somente leitura",
      "open-world": "mundo aberto",
      idempotent: "idempotente",
      "Tools for {{name}}": "Ferramentas para {{name}}",
      "Tools for {{serverName}}": "Ferramentas para {{serverName}}",
      "{{current}}/{{total}}": "{{current}}/{{total}}",
      // MCP Tool Detail
      required: "obrigat\xF3rio",
      Type: "Tipo",
      Enum: "Enumera\xE7\xE3o",
      Parameters: "Par\xE2metros",
      "No tool selected": "Nenhuma ferramenta selecionada",
      Annotations: "Anota\xE7\xF5es",
      Title: "T\xEDtulo",
      "Read Only": "Somente leitura",
      Destructive: "Destrutivo",
      Idempotent: "Idempotente",
      "Open World": "Mundo aberto",
      Server: "Servidor",
      // Invalid tool related translations
      "{{count}} invalid tools": "{{count}} ferramentas inv\xE1lidas",
      invalid: "inv\xE1lido",
      "invalid: {{reason}}": "inv\xE1lido: {{reason}}",
      "missing name": "nome ausente",
      "missing description": "descri\xE7\xE3o ausente",
      "(unnamed)": "(sem nome)",
      "Warning: This tool cannot be called by the LLM": "Aviso: Esta ferramenta n\xE3o pode ser chamada pelo LLM",
      Reason: "Motivo",
      "Tools must have both name and description to be used by the LLM.": "As ferramentas devem ter tanto nome quanto descri\xE7\xE3o para serem usadas pelo LLM.",
      "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 ...",
      "Always allow in this project": "Sempre permitir neste projeto",
      "Always allow {{action}} in this project": "Sempre permitir {{action}} neste projeto",
      "Always allow for this user": "Sempre permitir para este usu\xE1rio",
      "Always allow {{action}} for this user": "Sempre permitir {{action}} para este usu\xE1rio",
      "Yes, restore previous mode ({{mode}})": "Sim, restaurar modo anterior ({{mode}})",
      "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",
      "Select Authentication Method": "Selecionar M\xE9todo de Autentica\xE7\xE3o",
      "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.",
      "Terms of Services and Privacy Notice": "Termos de Servi\xE7o e Aviso de Privacidade",
      "Qwen OAuth": "Qwen OAuth",
      "Discontinued \u2014 switch to Coding Plan or API Key": "Descontinuado \u2014 mude para Coding Plan ou API Key",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch provider.": "O n\xEDvel gratuito do Qwen OAuth foi descontinuado em 2026-04-15. Execute /auth para trocar de provedor.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead.": "O n\xEDvel gratuito do Qwen OAuth foi descontinuado em 2026-04-15. Selecione Coding Plan ou API Key.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.": "O n\xEDvel gratuito do Qwen OAuth foi descontinuado em 2026-04-15. Por favor, selecione um modelo de outro provedor ou execute /auth para trocar.",
      "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n": "\n\u26A0 O n\xEDvel gratuito do Qwen OAuth foi descontinuado em 2026-04-15. Selecione outra op\xE7\xE3o.\n",
      "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models": "Pago \xB7 At\xE9 6.000 solicita\xE7\xF5es/5 hrs \xB7 Todos os modelos Alibaba Cloud Coding Plan",
      "Alibaba Cloud Coding Plan": "Alibaba Cloud Coding Plan",
      "Bring your own API key": "Traga sua pr\xF3pria chave API",
      "Browser-based authentication with third-party providers (e.g. OpenRouter, ModelScope)": "Autentica\xE7\xE3o baseada em navegador com provedores terceiros (por exemplo, OpenRouter, ModelScope)",
      "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.",
      "Note: Your existing API key will not be cleared when using Qwen OAuth.": "Nota: Sua chave de API existente n\xE3o ser\xE1 limpa ao usar o Qwen OAuth.",
      "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)",
      Modality: "Modalidade",
      "Context Window": "Janela de Contexto",
      text: "texto",
      "text-only": "somente texto",
      image: "imagem",
      pdf: "PDF",
      audio: "\xE1udio",
      video: "v\xEDdeo",
      "not set": "n\xE3o definido",
      none: "nenhum",
      unknown: "desconhecido",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "Falha ao trocar o modelo para '{{modelId}}'.\n\n{{error}}",
      "Qwen 3.6 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.6 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",
      "Manage permission rules": "Gerenciar regras de permiss\xE3o",
      Allow: "Permitir",
      Ask: "Perguntar",
      Deny: "Negar",
      Workspace: "\xC1rea de trabalho",
      "Qwen Code won't ask before using allowed tools.": "O Qwen Code n\xE3o perguntar\xE1 antes de usar ferramentas permitidas.",
      "Qwen Code will ask before using these tools.": "O Qwen Code perguntar\xE1 antes de usar essas ferramentas.",
      "Qwen Code is not allowed to use denied tools.": "O Qwen Code n\xE3o tem permiss\xE3o para usar ferramentas negadas.",
      "Manage trusted directories for this workspace.": "Gerenciar diret\xF3rios confi\xE1veis para esta \xE1rea de trabalho.",
      "Any use of the {{tool}} tool": "Qualquer uso da ferramenta {{tool}}",
      "{{tool}} commands matching '{{pattern}}'": "Comandos {{tool}} correspondentes a '{{pattern}}'",
      "From user settings": "Das configura\xE7\xF5es do usu\xE1rio",
      "From project settings": "Das configura\xE7\xF5es do projeto",
      "From session": "Da sess\xE3o",
      "Project settings (local)": "Configura\xE7\xF5es do projeto (local)",
      "Saved in .qwen/settings.local.json": "Salvo em .qwen/settings.local.json",
      "Project settings": "Configura\xE7\xF5es do projeto",
      "Checked in at .qwen/settings.json": "Registrado em .qwen/settings.json",
      "User settings": "Configura\xE7\xF5es do usu\xE1rio",
      "Saved in at ~/.qwen/settings.json": "Salvo em ~/.qwen/settings.json",
      "Add a new rule\u2026": "Adicionar nova regra\u2026",
      "Add {{type}} permission rule": "Adicionar regra de permiss\xE3o {{type}}",
      "Permission rules are a tool name, optionally followed by a specifier in parentheses.": "Regras de permiss\xE3o s\xE3o um nome de ferramenta, opcionalmente seguido por um especificador entre par\xEAnteses.",
      "e.g.,": "ex.",
      or: "ou",
      "Enter permission rule\u2026": "Insira a regra de permiss\xE3o\u2026",
      "Enter to submit \xB7 Esc to cancel": "Enter para enviar \xB7 Esc para cancelar",
      "Where should this rule be saved?": "Onde esta regra deve ser salva?",
      "Enter to confirm \xB7 Esc to cancel": "Enter para confirmar \xB7 Esc para cancelar",
      "Delete {{type}} rule?": "Excluir regra {{type}}?",
      "Are you sure you want to delete this permission rule?": "Tem certeza de que deseja excluir esta regra de permiss\xE3o?",
      "Permissions:": "Permiss\xF5es:",
      "(\u2190/\u2192 or tab to cycle)": "(\u2190/\u2192 ou Tab para alternar)",
      "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel": "\u2191\u2193 para navegar \xB7 Enter para selecionar \xB7 Digite para pesquisar \xB7 Esc para cancelar",
      "Search\u2026": "Pesquisar\u2026",
      "Use /trust to manage folder trust settings for this workspace.": "Use /trust para gerenciar as configura\xE7\xF5es de confian\xE7a de pasta desta \xE1rea de trabalho.",
      // Workspace directory management
      "Add directory\u2026": "Adicionar diret\xF3rio\u2026",
      "Add directory to workspace": "Adicionar diret\xF3rio \xE0 \xE1rea de trabalho",
      "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.": "O Qwen Code pode ler arquivos na \xE1rea de trabalho e fazer edi\xE7\xF5es quando a aceita\xE7\xE3o autom\xE1tica est\xE1 ativada.",
      "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.": "O Qwen Code poder\xE1 ler arquivos neste diret\xF3rio e fazer edi\xE7\xF5es quando a aceita\xE7\xE3o autom\xE1tica est\xE1 ativada.",
      "Enter the path to the directory:": "Insira o caminho do diret\xF3rio:",
      "Enter directory path\u2026": "Insira o caminho do diret\xF3rio\u2026",
      "Tab to complete \xB7 Enter to add \xB7 Esc to cancel": "Tab para completar \xB7 Enter para adicionar \xB7 Esc para cancelar",
      "Remove directory?": "Remover diret\xF3rio?",
      "Are you sure you want to remove this directory from the workspace?": "Tem certeza de que deseja remover este diret\xF3rio da \xE1rea de trabalho?",
      "  (Original working directory)": "  (Diret\xF3rio de trabalho original)",
      "  (from settings)": "  (das configura\xE7\xF5es)",
      "Directory does not exist.": "O diret\xF3rio n\xE3o existe.",
      "Path is not a directory.": "O caminho n\xE3o \xE9 um diret\xF3rio.",
      "This directory is already in the workspace.": "Este diret\xF3rio j\xE1 est\xE1 na \xE1rea de trabalho.",
      "Already covered by existing directory: {{dir}}": "J\xE1 coberto pelo diret\xF3rio existente: {{dir}}",
      // ============================================================================
      // 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.",
      "Press \u2191 to edit queued messages": "Pressione \u2191 para editar mensagens na fila",
      // ============================================================================
      // 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.",
      "Press Ctrl+O to toggle compact mode \u2014 hide tool output and thinking for a cleaner view.": "Pressione Ctrl+O para alternar o modo compacto \u2014 ocultar sa\xEDda de ferramentas e racioc\xEDnio.",
      "Add a QWEN.md file to give Qwen Code persistent project context.": "Adicione um arquivo QWEN.md para dar ao Qwen Code um contexto persistente do projeto.",
      "Use /btw to ask a quick side question without disrupting the conversation.": "Use /btw para fazer uma pergunta lateral r\xE1pida sem interromper a conversa.",
      "Context is almost full! Run /compress now or start /new to continue.": "O contexto est\xE1 quase cheio! Execute /compress agora ou inicie /new para continuar.",
      "Context is getting full. Use /compress to free up space.": "O contexto est\xE1 ficando cheio. Use /compress para liberar espa\xE7o.",
      "Long conversation? /compress summarizes history to free context.": "Conversa longa? /compress resume o hist\xF3rico para liberar contexto.",
      // ============================================================================
      // 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:",
      "Current tasks": "Tarefas atuais",
      "... 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
      // ============================================================================
      "You can configure your API key and models in settings.json": "Voc\xEA pode configurar sua chave de API e modelos em settings.json",
      "Refer to the documentation for setup instructions": "Consulte a documenta\xE7\xE3o para instru\xE7\xF5es de configura\xE7\xE3o",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "API key cannot be empty.": "A chave de API n\xE3o pode estar vazia.",
      "You can get your Coding Plan API key here": "Voc\xEA pode obter sua chave de API do Coding Plan aqui",
      "New model configurations are available for Alibaba Cloud Coding Plan. Update now?": "Novas configura\xE7\xF5es de modelo est\xE3o dispon\xEDveis para o Alibaba Cloud 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",
      "Paste your api key of ModelStudio Coding Plan and you're all set!": "Cole sua chave de API do ModelStudio Coding Plan 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:",
      "Select Region for Coding Plan": "Selecionar regi\xE3o do Coding Plan",
      "Choose based on where your account is registered": "Escolha com base em onde sua conta est\xE1 registrada",
      "Enter Coding Plan API Key": "Inserir chave de API do Coding Plan",
      // ============================================================================
      // 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?",
      '{{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).",
      // ============================================================================
      // Context Usage Component
      // ============================================================================
      "Context Usage": "Uso do Contexto",
      "% used": "% usado",
      "% context used": "% contexto usado",
      "Context exceeds limit! Use /compress or /clear to reduce.": "Contexto excede o limite! Use /compress ou /clear para reduzir.",
      "Use /compress or /clear": "Use /compress ou /clear",
      "No API response yet. Send a message to see actual usage.": "Ainda n\xE3o h\xE1 resposta da API. Envie uma mensagem para ver o uso real.",
      "Estimated pre-conversation overhead": "Sobrecarga estimada pr\xE9-conversa",
      "Context window": "Janela de Contexto",
      tokens: "tokens",
      Used: "Usado",
      Free: "Livre",
      "Autocompact buffer": "Buffer de autocompacta\xE7\xE3o",
      "Usage by category": "Uso por categoria",
      "System prompt": "Prompt do sistema",
      "Built-in tools": "Ferramentas integradas",
      "MCP tools": "Ferramentas MCP",
      "Memory files": "Arquivos de mem\xF3ria",
      Skills: "Habilidades",
      Messages: "Mensagens",
      "Show context window usage breakdown.": "Exibe a divis\xE3o de uso da janela de contexto.",
      "Run /context detail for per-item breakdown.": "Execute /context detail para detalhamento por item.",
      active: "ativo",
      "body loaded": "conte\xFAdo carregado",
      memory: "mem\xF3ria",
      "{{region}} configuration updated successfully.": "Configura\xE7\xE3o do {{region}} atualizada com sucesso.",
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json.": "Autenticado com sucesso com {{region}}. Chave de API e configura\xE7\xF5es de modelo salvas em settings.json.",
      "Tip: Use /model to switch between available Coding Plan models.": "Dica: Use /model para alternar entre os modelos dispon\xEDveis do Coding Plan.",
      // ============================================================================
      // Ask User Question Tool
      // ============================================================================
      "Please answer the following question(s):": "Por favor, responda \xE0(s) seguinte(s) pergunta(s):",
      "Cannot ask user questions in non-interactive mode. Please run in interactive mode to use this tool.": "N\xE3o \xE9 poss\xEDvel fazer perguntas ao usu\xE1rio no modo n\xE3o interativo. Por favor, execute no modo interativo para usar esta ferramenta.",
      "User declined to answer the questions.": "O usu\xE1rio recusou responder \xE0s perguntas.",
      "User has provided the following answers:": "O usu\xE1rio forneceu as seguintes respostas:",
      "Failed to process user answers:": "Falha ao processar as respostas do usu\xE1rio:",
      "Type something...": "Digite algo...",
      Submit: "Enviar",
      "Submit answers": "Enviar respostas",
      Cancel: "Cancelar",
      "Your answers:": "Suas respostas:",
      "(not answered)": "(n\xE3o respondido)",
      "Ready to submit your answers?": "Pronto para enviar suas respostas?",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select": "\u2191/\u2193: Navegar | \u2190/\u2192: Alternar abas | Enter: Selecionar",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: Navegar | \u2190/\u2192: Alternar abas | Space/Enter: Alternar | Esc: Cancelar",
      "\u2191/\u2193: Navigate | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: Navegar | Space/Enter: Alternar | Esc: Cancelar",
      "\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel": "\u2191/\u2193: Navegar | Enter: Selecionar | Esc: Cancelar",
      // ============================================================================
      // Commands - Auth
      // ============================================================================
      "Configure Qwen authentication information with Qwen-OAuth or Alibaba Cloud Coding Plan": "Configurar autentica\xE7\xE3o Qwen com Qwen-OAuth ou Alibaba Cloud Coding Plan",
      "Authenticate using Qwen OAuth": "Autenticar usando Qwen OAuth",
      "Authenticate using Alibaba Cloud Coding Plan": "Autenticar usando Alibaba Cloud Coding Plan",
      "Region for Coding Plan (china/global)": "Regi\xE3o para Coding Plan (china/global)",
      "API key for Coding Plan": "Chave de API para Coding Plan",
      "Show current authentication status": "Mostrar status atual de autentica\xE7\xE3o",
      "Authentication completed successfully.": "Autentica\xE7\xE3o conclu\xEDda com sucesso.",
      "Starting Qwen OAuth authentication...": "Iniciando autentica\xE7\xE3o Qwen OAuth...",
      "Successfully authenticated with Qwen OAuth.": "Autenticado com sucesso via Qwen OAuth.",
      "Failed to authenticate with Qwen OAuth: {{error}}": "Falha ao autenticar com Qwen OAuth: {{error}}",
      "Processing Alibaba Cloud Coding Plan authentication...": "Processando autentica\xE7\xE3o Alibaba Cloud Coding Plan...",
      "Successfully authenticated with Alibaba Cloud Coding Plan.": "Autenticado com sucesso via Alibaba Cloud Coding Plan.",
      "Failed to authenticate with Coding Plan: {{error}}": "Falha ao autenticar com Coding Plan: {{error}}",
      "\u4E2D\u56FD (China)": "\u4E2D\u56FD (China)",
      "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)": "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)",
      Global: "Global",
      "Alibaba Cloud (alibabacloud.com)": "Alibaba Cloud (alibabacloud.com)",
      "Select region for Coding Plan:": "Selecione a regi\xE3o para Coding Plan:",
      "Enter your Coding Plan API key: ": "Insira sua chave de API do Coding Plan: ",
      "Select authentication method:": "Selecione o m\xE9todo de autentica\xE7\xE3o:",
      "\n=== Authentication Status ===\n": "\n=== Status de Autentica\xE7\xE3o ===\n",
      "\u26A0\uFE0F  No authentication method configured.\n": "\u26A0\uFE0F  Nenhum m\xE9todo de autentica\xE7\xE3o configurado.\n",
      "Run one of the following commands to get started:\n": "Execute um dos seguintes comandos para come\xE7ar:\n",
      "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)": "  qwen auth qwen-oauth     - Autenticar com Qwen OAuth (descontinuado)",
      "  qwen auth coding-plan      - Authenticate with Alibaba Cloud Coding Plan\n": "  qwen auth coding-plan      - Autenticar com Alibaba Cloud Coding Plan\n",
      "Or simply run:": "Ou simplesmente execute:",
      "  qwen auth                - Interactive authentication setup\n": "  qwen auth                - Configura\xE7\xE3o interativa de autentica\xE7\xE3o\n",
      "\u2713 Authentication Method: Qwen OAuth": "\u2713 M\xE9todo de autentica\xE7\xE3o: Qwen OAuth",
      "  Type: Free tier (discontinued 2026-04-15)": "  Tipo: N\xEDvel gratuito (descontinuado 2026-04-15)",
      "  Limit: No longer available": "  Limite: N\xE3o mais dispon\xEDvel",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.": "O n\xEDvel gratuito do Qwen OAuth foi descontinuado em 2026-04-15. Execute /auth para mudar para Coding Plan, OpenRouter, Fireworks AI ou outro provedor.",
      "  Models: Qwen latest models\n": "  Modelos: Modelos Qwen mais recentes\n",
      "\u2713 Authentication Method: Alibaba Cloud Coding Plan": "\u2713 M\xE9todo de autentica\xE7\xE3o: Alibaba Cloud Coding Plan",
      "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC": "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC",
      "Global - Alibaba Cloud": "Global - Alibaba Cloud",
      "  Region: {{region}}": "  Regi\xE3o: {{region}}",
      "  Current Model: {{model}}": "  Modelo atual: {{model}}",
      "  Config Version: {{version}}": "  Vers\xE3o da configura\xE7\xE3o: {{version}}",
      "  Status: API key configured\n": "  Status: Chave de API configurada\n",
      "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)": "\u26A0\uFE0F  M\xE9todo de autentica\xE7\xE3o: Alibaba Cloud Coding Plan (Incompleto)",
      "  Issue: API key not found in environment or settings\n": "  Problema: Chave de API n\xE3o encontrada no ambiente ou configura\xE7\xF5es\n",
      "  Run `qwen auth coding-plan` to re-configure.\n": "  Execute `qwen auth coding-plan` para reconfigurar.\n",
      "\u2713 Authentication Method: {{type}}": "\u2713 M\xE9todo de autentica\xE7\xE3o: {{type}}",
      "  Status: Configured\n": "  Status: Configurado\n",
      "Failed to check authentication status: {{error}}": "Falha ao verificar status de autentica\xE7\xE3o: {{error}}",
      "Select an option:": "Selecione uma op\xE7\xE3o:",
      "Raw mode not available. Please run in an interactive terminal.": "Modo raw n\xE3o dispon\xEDvel. Execute em um terminal interativo.",
      "(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n": "(Use \u2191 \u2193 para navegar, Enter para selecionar, Ctrl+C para sair)\n",
      compact: "compacto",
      "compact mode: on (Ctrl+O off)": "modo compacto: ligado (Ctrl+O desligar)",
      "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).": "Ocultar sa\xEDda da ferramenta e racioc\xEDnio para uma visualiza\xE7\xE3o mais limpa (alternar com Ctrl+O).",
      "Press Ctrl+O to show full tool output": "Pressione Ctrl+O para exibir a sa\xEDda completa da ferramenta",
      "Switch to plan mode or exit plan mode": "Switch to plan mode or exit plan mode",
      "Exited plan mode. Previous approval mode restored.": "Exited plan mode. Previous approval mode restored.",
      "Enabled plan mode. The agent will analyze and plan without executing tools.": "Enabled plan mode. The agent will analyze and plan without executing tools.",
      'Already in plan mode. Use "/plan exit" to exit plan mode.': 'Already in plan mode. Use "/plan exit" to exit plan mode.',
      'Not in plan mode. Use "/plan" to enter plan mode first.': 'Not in plan mode. Use "/plan" to enter plan mode first.',
      "Set up Qwen Code's status line UI": "Set up Qwen Code's status line UI"
    };
  }
});

// packages/cli/src/i18n/locales/ru.js
var ru_exports = {};
__export(ru_exports, {
  default: () => ru_default2
});
var ru_default2;
var init_ru2 = __esm({
  "packages/cli/src/i18n/locales/ru.js"() {
    "use strict";
    init_esbuild_shims();
    ru_default2 = {
      // ============================================================================
      // Справка / Компоненты интерфейса
      // ============================================================================
      // 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",
      "to toggle compact mode": "\u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u043A\u043E\u043C\u043F\u0430\u043A\u0442\u043D\u044B\u0439 \u0440\u0435\u0436\u0438\u043C",
      // ============================================================================
      // Поля системной информации
      // ============================================================================
      "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",
      "Fast Model": "\u0411\u044B\u0441\u0442\u0440\u0430\u044F \u043C\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]",
      "List available skills.": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0435 \u043D\u0430\u0432\u044B\u043A\u0438.",
      "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",
      "Enter to submit, Esc to go back": "Enter \u0434\u043B\u044F \u043E\u0442\u043F\u0440\u0430\u0432\u043A\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)",
      "Auto (detect terminal theme)": "\u0410\u0432\u0442\u043E (\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0438\u0442\u044C \u0442\u0435\u043C\u0443 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430)",
      Auto: "\u0410\u0432\u0442\u043E",
      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",
      "Open MCP management dialog, or authenticate with OAuth-enabled servers": "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0434\u0438\u0430\u043B\u043E\u0433 \u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F MCP \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\u0435 \u0441 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u043E\u0439 OAuth",
      "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",
      "Manage installed extensions": "\u0423\u043F\u0440\u0430\u0432\u043B\u044F\u0442\u044C \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043D\u044B\u043C\u0438 \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).",
      // ============================================================================
      // Commands - Hooks
      // ============================================================================
      "Manage Qwen Code hooks": "\u0423\u043F\u0440\u0430\u0432\u043B\u044F\u0442\u044C \u0445\u0443\u043A\u0430\u043C\u0438 Qwen Code",
      "List all configured hooks": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0432\u0441\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0435 \u0445\u0443\u043A\u0438",
      "Enable a disabled hook": "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u043D\u044B\u0439 \u0445\u0443\u043A",
      "Disable an active hook": "\u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0430\u043A\u0442\u0438\u0432\u043D\u044B\u0439 \u0445\u0443\u043A",
      // Hooks - Dialog
      Hooks: "\u0425\u0443\u043A\u0438",
      "Loading hooks...": "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0445\u0443\u043A\u043E\u0432...",
      "Error loading hooks:": "\u041E\u0448\u0438\u0431\u043A\u0430 \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0438 \u0445\u0443\u043A\u043E\u0432:",
      "Press Escape to close": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Escape \u0434\u043B\u044F \u0437\u0430\u043A\u0440\u044B\u0442\u0438\u044F",
      "Press Escape, Ctrl+C, or Ctrl+D to cancel": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Escape, Ctrl+C \u0438\u043B\u0438 Ctrl+D \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B",
      "Press Space, Enter, or Escape to dismiss": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 \u041F\u0440\u043E\u0431\u0435\u043B, Enter \u0438\u043B\u0438 Escape \u0434\u043B\u044F \u0437\u0430\u043A\u0440\u044B\u0442\u0438\u044F",
      "No hook selected": "\u0425\u0443\u043A \u043D\u0435 \u0432\u044B\u0431\u0440\u0430\u043D",
      // Hooks - List Step
      "No hook events found.": "\u0421\u043E\u0431\u044B\u0442\u0438\u044F \u0445\u0443\u043A\u043E\u0432 \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u044B.",
      "{{count}} hook configured": "{{count}} \u0445\u0443\u043A \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D",
      "{{count}} hooks configured": "{{count}} \u0445\u0443\u043A\u043E\u0432 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043E",
      "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.": "\u042D\u0442\u043E \u043C\u0435\u043D\u044E \u0442\u043E\u043B\u044C\u043A\u043E \u0434\u043B\u044F \u0447\u0442\u0435\u043D\u0438\u044F. \u0427\u0442\u043E\u0431\u044B \u0434\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0438\u043B\u0438 \u0438\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0445\u0443\u043A\u0438, \u043E\u0442\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u0443\u0439\u0442\u0435 settings.json \u043D\u0430\u043F\u0440\u044F\u043C\u0443\u044E \u0438\u043B\u0438 \u0441\u043F\u0440\u043E\u0441\u0438\u0442\u0435 Qwen Code.",
      "Enter to select \xB7 Esc to cancel": "Enter \u0434\u043B\u044F \u0432\u044B\u0431\u043E\u0440\u0430 \xB7 Esc \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B",
      // Hooks - Detail Step
      "Exit codes:": "\u041A\u043E\u0434\u044B \u0432\u044B\u0445\u043E\u0434\u0430:",
      "Configured hooks:": "\u041D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0435 \u0445\u0443\u043A\u0438:",
      "No hooks configured for this event.": "\u0414\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0441\u043E\u0431\u044B\u0442\u0438\u044F \u043D\u0435\u0442 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0445 \u0445\u0443\u043A\u043E\u0432.",
      "To add hooks, edit settings.json directly or ask Qwen.": "\u0427\u0442\u043E\u0431\u044B \u0434\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0445\u0443\u043A\u0438, \u043E\u0442\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u0443\u0439\u0442\u0435 settings.json \u043D\u0430\u043F\u0440\u044F\u043C\u0443\u044E \u0438\u043B\u0438 \u0441\u043F\u0440\u043E\u0441\u0438\u0442\u0435 Qwen.",
      "Enter to select \xB7 Esc to go back": "Enter \u0434\u043B\u044F \u0432\u044B\u0431\u043E\u0440\u0430 \xB7 Esc \u0434\u043B\u044F \u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430",
      // Hooks - Config Detail Step
      "Hook details": "\u0414\u0435\u0442\u0430\u043B\u0438 \u0445\u0443\u043A\u0430",
      "Event:": "\u0421\u043E\u0431\u044B\u0442\u0438\u0435:",
      "Extension:": "\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435:",
      "Desc:": "\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435:",
      "No hook config selected": "\u041A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F \u0445\u0443\u043A\u0430 \u043D\u0435 \u0432\u044B\u0431\u0440\u0430\u043D\u0430",
      "To modify or remove this hook, edit settings.json directly or ask Qwen to help.": "\u0427\u0442\u043E\u0431\u044B \u0438\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0438\u043B\u0438 \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u044D\u0442\u043E\u0442 \u0445\u0443\u043A, \u043E\u0442\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u0443\u0439\u0442\u0435 settings.json \u043D\u0430\u043F\u0440\u044F\u043C\u0443\u044E \u0438\u043B\u0438 \u0441\u043F\u0440\u043E\u0441\u0438\u0442\u0435 Qwen.",
      // Hooks - Disabled Step
      "Hook Configuration - Disabled": "\u041A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F \u0445\u0443\u043A\u043E\u0432 - \u041E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u043E",
      "All hooks are currently disabled. You have {{count}} that are not running.": "\u0412\u0441\u0435 \u0445\u0443\u043A\u0438 \u0432 \u0434\u0430\u043D\u043D\u044B\u0439 \u043C\u043E\u043C\u0435\u043D\u0442 \u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u044B. \u0423 \u0432\u0430\u0441 {{count}} \u043D\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u044E\u0442\u0441\u044F.",
      "{{count}} configured hook": "{{count}} \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0439 \u0445\u0443\u043A",
      "{{count}} configured hooks": "{{count}} \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0445 \u0445\u0443\u043A\u043E\u0432",
      "When hooks are disabled:": "\u041A\u043E\u0433\u0434\u0430 \u0445\u0443\u043A\u0438 \u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u044B:",
      "No hook commands will execute": "\u041D\u0438\u043A\u0430\u043A\u0438\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0445\u0443\u043A\u043E\u0432 \u043D\u0435 \u0431\u0443\u0434\u0443\u0442 \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0442\u044C\u0441\u044F",
      "StatusLine will not be displayed": "StatusLine \u043D\u0435 \u0431\u0443\u0434\u0435\u0442 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0430\u0442\u044C\u0441\u044F",
      "Tool operations will proceed without hook validation": "\u041E\u043F\u0435\u0440\u0430\u0446\u0438\u0438 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u0431\u0443\u0434\u0443\u0442 \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0442\u044C\u0441\u044F \u0431\u0435\u0437 \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0438 \u0445\u0443\u043A\u043E\u0432",
      'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.': '\u0427\u0442\u043E\u0431\u044B \u0441\u043D\u043E\u0432\u0430 \u0432\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0445\u0443\u043A\u0438, \u0443\u0434\u0430\u043B\u0438\u0442\u0435 "disableAllHooks" \u0438\u0437 settings.json \u0438\u043B\u0438 \u0441\u043F\u0440\u043E\u0441\u0438\u0442\u0435 Qwen Code.',
      // Hooks - Source
      Project: "\u041F\u0440\u043E\u0435\u043A\u0442",
      User: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C",
      System: "\u0421\u0438\u0441\u0442\u0435\u043C\u0430",
      Extension: "\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435",
      "Local Settings": "\u041B\u043E\u043A\u0430\u043B\u044C\u043D\u044B\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438",
      "User Settings": "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438",
      "System Settings": "\u0421\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438",
      Extensions: "\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F",
      "Session (temporary)": "\u0421\u0435\u0441\u0441\u0438\u044F (\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E)",
      // Hooks - Status
      "\u2713 Enabled": "\u2713 \u0412\u043A\u043B\u044E\u0447\u0435\u043D",
      "\u2717 Disabled": "\u2717 \u041E\u0442\u043A\u043B\u044E\u0447\u0435\u043D",
      // Hooks - Event Descriptions (short)
      "Before tool execution": "\u041F\u0435\u0440\u0435\u0434 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435\u043C \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430",
      "After tool execution": "\u041F\u043E\u0441\u043B\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430",
      "After tool execution fails": "\u041F\u0440\u0438 \u043D\u0435\u0443\u0434\u0430\u0447\u043D\u043E\u043C \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0438 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430",
      "When notifications are sent": "\u041F\u0440\u0438 \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0435 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0439",
      "When the user submits a prompt": "\u041A\u043E\u0433\u0434\u0430 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u043E\u0442\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u0442 \u043F\u0440\u043E\u043C\u043F\u0442",
      "When a new session is started": "\u041F\u0440\u0438 \u0437\u0430\u043F\u0443\u0441\u043A\u0435 \u043D\u043E\u0432\u043E\u0439 \u0441\u0435\u0441\u0441\u0438\u0438",
      "Right before Qwen Code concludes its response": "\u041D\u0435\u043F\u043E\u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0435\u043D\u043D\u043E \u043F\u0435\u0440\u0435\u0434 \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u0435\u043C \u043E\u0442\u0432\u0435\u0442\u0430 Qwen Code",
      "When a subagent (Agent tool call) is started": "\u041F\u0440\u0438 \u0437\u0430\u043F\u0443\u0441\u043A\u0435 \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u0430 (\u0432\u044B\u0437\u043E\u0432 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430 Agent)",
      "Right before a subagent concludes its response": "\u041D\u0435\u043F\u043E\u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0435\u043D\u043D\u043E \u043F\u0435\u0440\u0435\u0434 \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u0435\u043C \u043E\u0442\u0432\u0435\u0442\u0430 \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u0430",
      "Before conversation compaction": "\u041F\u0435\u0440\u0435\u0434 \u0441\u0436\u0430\u0442\u0438\u0435\u043C \u0440\u0430\u0437\u0433\u043E\u0432\u043E\u0440\u0430",
      "When a session is ending": "\u041F\u0440\u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u0438 \u0441\u0435\u0441\u0441\u0438\u0438",
      "When a permission dialog is displayed": "\u041F\u0440\u0438 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0438 \u0434\u0438\u0430\u043B\u043E\u0433\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0439",
      // Hooks - Event Descriptions (detailed)
      "Input to command is JSON of tool call arguments.": "\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u0432\u044B\u0437\u043E\u0432\u0430 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430.",
      'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': '\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0441 \u043F\u043E\u043B\u044F\u043C\u0438 "inputs" (\u0430\u0440\u0433\u0443\u043C\u0435\u043D\u0442\u044B \u0432\u044B\u0437\u043E\u0432\u0430 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430) \u0438 "response" (\u043E\u0442\u0432\u0435\u0442 \u0432\u044B\u0437\u043E\u0432\u0430 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430).',
      "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.": "\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0441 tool_name, tool_input, tool_use_id, error, error_type, is_interrupt \u0438 is_timeout.",
      "Input to command is JSON with notification message and type.": "\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0441 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435\u043C \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u0438 \u0442\u0438\u043F\u043E\u043C.",
      "Input to command is JSON with original user prompt text.": "\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0441 \u0438\u0441\u0445\u043E\u0434\u043D\u044B\u043C \u0442\u0435\u043A\u0441\u0442\u043E\u043C \u043F\u0440\u043E\u043C\u043F\u0442\u0430 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F.",
      "Input to command is JSON with session start source.": "\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0441 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u043E\u043C \u0437\u0430\u043F\u0443\u0441\u043A\u0430 \u0441\u0435\u0441\u0441\u0438\u0438.",
      "Input to command is JSON with session end reason.": "\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0441 \u043F\u0440\u0438\u0447\u0438\u043D\u043E\u0439 \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F \u0441\u0435\u0441\u0441\u0438\u0438.",
      "Input to command is JSON with agent_id and agent_type.": "\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0441 agent_id \u0438 agent_type.",
      "Input to command is JSON with agent_id, agent_type, and agent_transcript_path.": "\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0441 agent_id, agent_type \u0438 agent_transcript_path.",
      "Input to command is JSON with compaction details.": "\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0441 \u0434\u0435\u0442\u0430\u043B\u044F\u043C\u0438 \u0441\u0436\u0430\u0442\u0438\u044F.",
      "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.": "\u0412\u0432\u043E\u0434 \u0432 \u043A\u043E\u043C\u0430\u043D\u0434\u0443 \u2014 \u044D\u0442\u043E JSON \u0441 tool_name, tool_input \u0438 tool_use_id. \u0412\u044B\u0432\u043E\u0434 \u2014 JSON \u0441 hookSpecificOutput, \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0449\u0438\u043C \u0440\u0435\u0448\u0435\u043D\u0438\u0435 \u043E \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0438 \u0438\u043B\u0438 \u043E\u0442\u043A\u0430\u0437\u0435.",
      // Hooks - Exit Code Descriptions
      "stdout/stderr not shown": "stdout/stderr \u043D\u0435 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0430\u044E\u0442\u0441\u044F",
      "show stderr to model and continue conversation": "\u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C stderr \u043C\u043E\u0434\u0435\u043B\u0438 \u0438 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u0440\u0430\u0437\u0433\u043E\u0432\u043E\u0440",
      "show stderr to user only": "\u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C stderr \u0442\u043E\u043B\u044C\u043A\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E",
      "stdout shown in transcript mode (ctrl+o)": "stdout \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0430\u0435\u0442\u0441\u044F \u0432 \u0440\u0435\u0436\u0438\u043C\u0435 \u0442\u0440\u0430\u043D\u0441\u043A\u0440\u0438\u043F\u0446\u0438\u0438 (ctrl+o)",
      "show stderr to model immediately": "\u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C stderr \u043C\u043E\u0434\u0435\u043B\u0438 \u043D\u0435\u043C\u0435\u0434\u043B\u0435\u043D\u043D\u043E",
      "show stderr to user only but continue with tool call": "\u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C stderr \u0442\u043E\u043B\u044C\u043A\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E, \u043D\u043E \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u0432\u044B\u0437\u043E\u0432 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430",
      "block processing, erase original prompt, and show stderr to user only": "\u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0443, \u0441\u0442\u0435\u0440\u0435\u0442\u044C \u0438\u0441\u0445\u043E\u0434\u043D\u044B\u0439 \u043F\u0440\u043E\u043C\u043F\u0442 \u0438 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C stderr \u0442\u043E\u043B\u044C\u043A\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E",
      "stdout shown to Qwen": "stdout \u043F\u043E\u043A\u0430\u0437\u0430\u043D Qwen",
      "show stderr to user only (blocking errors ignored)": "\u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C stderr \u0442\u043E\u043B\u044C\u043A\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E (\u0431\u043B\u043E\u043A\u0438\u0440\u0443\u044E\u0449\u0438\u0435 \u043E\u0448\u0438\u0431\u043A\u0438 \u0438\u0433\u043D\u043E\u0440\u0438\u0440\u0443\u044E\u0442\u0441\u044F)",
      "command completes successfully": "\u043A\u043E\u043C\u0430\u043D\u0434\u0430 \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0430",
      "stdout shown to subagent": "stdout \u043F\u043E\u043A\u0430\u0437\u0430\u043D \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u0443",
      "show stderr to subagent and continue having it run": "\u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C stderr \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u0443 \u0438 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u0435\u0433\u043E \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435",
      "stdout appended as custom compact instructions": "stdout \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D \u043A\u0430\u043A \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u0438 \u0441\u0436\u0430\u0442\u0438\u044F",
      "block compaction": "\u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0436\u0430\u0442\u0438\u0435",
      "show stderr to user only but continue with compaction": "\u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C stderr \u0442\u043E\u043B\u044C\u043A\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E, \u043D\u043E \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u0441\u0436\u0430\u0442\u0438\u0435",
      "use hook decision if provided": "\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0440\u0435\u0448\u0435\u043D\u0438\u0435 \u0445\u0443\u043A\u0430, \u0435\u0441\u043B\u0438 \u043F\u0440\u0435\u0434\u043E\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u043E",
      // Hooks - Messages
      "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.",
      "Hooks are not enabled. Enable hooks in settings to use this feature.": "\u0425\u0443\u043A\u0438 \u043D\u0435 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u044B. \u0412\u043A\u043B\u044E\u0447\u0438\u0442\u0435 \u0445\u0443\u043A\u0438 \u0432 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430\u0445, \u0447\u0442\u043E\u0431\u044B \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u044D\u0442\u0443 \u0444\u0443\u043D\u043A\u0446\u0438\u044E.",
      "No hooks configured. Add hooks in your settings.json file.": "\u0425\u0443\u043A\u0438 \u043D\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u044B. \u0414\u043E\u0431\u0430\u0432\u044C\u0442\u0435 \u0445\u0443\u043A\u0438 \u0432 \u0444\u0430\u0439\u043B settings.json.",
      "Configured Hooks ({{count}} total)": "\u041D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0435 \u0445\u0443\u043A\u0438 (\u0432\u0441\u0435\u0433\u043E {{count}})",
      // ============================================================================
      // Commands - Session Export
      // ============================================================================
      "Export current session message history to a file": "\u042D\u043A\u0441\u043F\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0438\u0441\u0442\u043E\u0440\u0438\u044E \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0441\u0435\u0441\u0441\u0438\u0438 \u0432 \u0444\u0430\u0439\u043B",
      "Export session to HTML format": "\u042D\u043A\u0441\u043F\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0435\u0441\u0441\u0438\u044E \u0432 \u0444\u043E\u0440\u043C\u0430\u0442 HTML",
      "Export session to JSON format": "\u042D\u043A\u0441\u043F\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0435\u0441\u0441\u0438\u044E \u0432 \u0444\u043E\u0440\u043C\u0430\u0442 JSON",
      "Export session to JSONL format (one message per line)": "\u042D\u043A\u0441\u043F\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0435\u0441\u0441\u0438\u044E \u0432 \u0444\u043E\u0440\u043C\u0430\u0442 JSONL (\u043E\u0434\u043D\u043E \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u043D\u0430 \u0441\u0442\u0440\u043E\u043A\u0443)",
      "Export session to markdown format": "\u042D\u043A\u0441\u043F\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0435\u0441\u0441\u0438\u044E \u0432 \u0444\u043E\u0440\u043C\u0430\u0442 Markdown",
      // ============================================================================
      // Commands - Insights
      // ============================================================================
      "generate personalized programming insights from your chat history": "\u0421\u043E\u0437\u0434\u0430\u0442\u044C \u043F\u0435\u0440\u0441\u043E\u043D\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0435 \u0438\u043D\u0441\u0430\u0439\u0442\u044B \u043F\u043E \u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044E \u043D\u0430 \u043E\u0441\u043D\u043E\u0432\u0435 \u0438\u0441\u0442\u043E\u0440\u0438\u0438 \u0447\u0430\u0442\u0430",
      // ============================================================================
      // Commands - Session History
      // ============================================================================
      "Resume a previous session": "\u041F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0443\u044E \u0441\u0435\u0441\u0441\u0438\u044E",
      "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested": "\u0412\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0432\u044B\u0437\u043E\u0432 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430. \u042D\u0442\u043E \u0432\u0435\u0440\u043D\u0435\u0442 \u0438\u0441\u0442\u043E\u0440\u0438\u044E \u0440\u0430\u0437\u0433\u043E\u0432\u043E\u0440\u0430 \u0438 \u0444\u0430\u0439\u043B\u043E\u0432 \u043A \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u044E \u043D\u0430 \u043C\u043E\u043C\u0435\u043D\u0442, \u043A\u043E\u0433\u0434\u0430 \u0431\u044B\u043B \u043F\u0440\u0435\u0434\u043B\u043E\u0436\u0435\u043D \u044D\u0442\u043E\u0442 \u0432\u044B\u0437\u043E\u0432 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430",
      "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",
      "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}}"',
      "Open auto-memory folder": "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u043F\u0430\u043F\u043A\u0443 \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438",
      "Auto-memory: {{status}}": "\u0410\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u044C: {{status}}",
      "Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream to run": "\u0410\u0432\u0442\u043E\u043A\u043E\u043D\u0441\u043E\u043B\u0438\u0434\u0430\u0446\u0438\u044F: {{status}} \xB7 {{lastDream}} \xB7 /dream \u0434\u043B\u044F \u0437\u0430\u043F\u0443\u0441\u043A\u0430",
      never: "\u043D\u0438\u043A\u043E\u0433\u0434\u0430",
      on: "\u0432\u043A\u043B",
      off: "\u0432\u044B\u043A\u043B",
      "\u2746 dreaming": "\u2746 \u043A\u043E\u043D\u0441\u043E\u043B\u0438\u0434\u0430\u0446\u0438\u044F",
      "Remove matching entries from managed auto-memory.": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u043E\u0432\u043F\u0430\u0434\u0430\u044E\u0449\u0438\u0435 \u0437\u0430\u043F\u0438\u0441\u0438 \u0438\u0437 \u0443\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0439 \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438.",
      "Usage: /forget <memory text to remove>": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /forget <\u0442\u0435\u043A\u0441\u0442 \u0432\u043E\u0441\u043F\u043E\u043C\u0438\u043D\u0430\u043D\u0438\u044F \u0434\u043B\u044F \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u044F>",
      "No managed auto-memory entries matched: {{query}}": "\u041D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E \u0441\u043E\u0432\u043F\u0430\u0434\u0430\u044E\u0449\u0438\u0445 \u0437\u0430\u043F\u0438\u0441\u0435\u0439 \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438: {{query}}",
      "Show managed auto-memory status.": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0441\u0442\u0430\u0442\u0443\u0441 \u0443\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0439 \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438.",
      "Run managed auto-memory extraction for the current session.": "\u0417\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C \u0438\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u0435 \u0443\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0439 \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438 \u0434\u043B\u044F \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0441\u0435\u0441\u0441\u0438\u0438.",
      "Managed auto-memory root: {{root}}": "\u041A\u043E\u0440\u043D\u0435\u0432\u0430\u044F \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u044F \u0443\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0439 \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438: {{root}}",
      "Managed auto-memory topics:": "\u0422\u0435\u043C\u044B \u0443\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0439 \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438:",
      "No extraction cursor found yet.": "\u041A\u0443\u0440\u0441\u043E\u0440 \u0438\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u044F \u0435\u0449\u0451 \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D.",
      "Cursor: session={{sessionId}}, offset={{offset}}, updated={{updatedAt}}": "\u041A\u0443\u0440\u0441\u043E\u0440: \u0441\u0435\u0441\u0441\u0438\u044F={{sessionId}}, \u0441\u043C\u0435\u0449\u0435\u043D\u0438\u0435={{offset}}, \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u043E={{updatedAt}}",
      "No chat client available to extract memory.": "\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 \u0438\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u044F \u043F\u0430\u043C\u044F\u0442\u0438.",
      "Managed auto-memory extraction is already running.": "\u0418\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u0435 \u0443\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0439 \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438 \u0443\u0436\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u0435\u0442\u0441\u044F.",
      "Managed auto-memory extraction found no new durable memories.": "\u0418\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u0435 \u0443\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0439 \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438 \u043D\u0435 \u043D\u0430\u0448\u043B\u043E \u043D\u043E\u0432\u044B\u0445 \u0434\u043E\u043B\u0433\u043E\u0441\u0440\u043E\u0447\u043D\u044B\u0445 \u0432\u043E\u0441\u043F\u043E\u043C\u0438\u043D\u0430\u043D\u0438\u0439.",
      "Consolidate managed auto-memory topic files.": "\u041A\u043E\u043D\u0441\u043E\u043B\u0438\u0434\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0444\u0430\u0439\u043B\u044B \u0442\u0435\u043C \u0443\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0439 \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438.",
      "Managed auto-memory dream found nothing to improve.": "\u041A\u043E\u043D\u0441\u043E\u043B\u0438\u0434\u0430\u0446\u0438\u044F \u0430\u0432\u0442\u043E\u043F\u0430\u043C\u044F\u0442\u0438 \u043D\u0435 \u043D\u0430\u0448\u043B\u0430 \u0447\u0435\u0433\u043E \u0443\u043B\u0443\u0447\u0448\u0430\u0442\u044C.",
      "Deduplicated entries: {{count}}": "\u0423\u0434\u0430\u043B\u0435\u043D\u043E \u0434\u0443\u0431\u043B\u0438\u043A\u0430\u0442\u043E\u0432: {{count}}",
      "Save a durable memory using the save_memory tool.": "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0434\u043E\u043B\u0433\u043E\u0441\u0440\u043E\u0447\u043D\u0443\u044E \u043F\u0430\u043C\u044F\u0442\u044C \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430 save_memory.",
      "Usage: /remember [--global|--project] <text to remember>": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435: /remember [--global|--project] <\u0442\u0435\u043A\u0441\u0442 \u0434\u043B\u044F \u0437\u0430\u043F\u043E\u043C\u0438\u043D\u0430\u043D\u0438\u044F>",
      // ============================================================================
      // Команды - 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.",
      "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}}'...",
      "Discovered {{count}} tool(s) from '{{name}}'.": "\u041E\u0431\u043D\u0430\u0440\u0443\u0436\u0435\u043D\u043E {{count}} \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442(\u043E\u0432) \u043E\u0442 '{{name}}'.",
      "Authentication complete. Returning to server details...": "\u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0430. \u0412\u043E\u0437\u0432\u0440\u0430\u0442 \u043A \u0434\u0435\u0442\u0430\u043B\u044F\u043C \u0441\u0435\u0440\u0432\u0435\u0440\u0430...",
      "Authentication successful.": "\u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0443\u0441\u043F\u0435\u0448\u043D\u0430.",
      "If the browser does not open, copy and paste this URL into your browser:": "\u0415\u0441\u043B\u0438 \u0431\u0440\u0430\u0443\u0437\u0435\u0440 \u043D\u0435 \u043E\u0442\u043A\u0440\u044B\u043B\u0441\u044F, \u0441\u043A\u043E\u043F\u0438\u0440\u0443\u0439\u0442\u0435 \u044D\u0442\u043E\u0442 URL \u0438 \u0432\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u0435\u0433\u043E \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440:",
      "Make sure to copy the COMPLETE URL - it may wrap across multiple lines.": "\u26A0\uFE0F  \u0423\u0431\u0435\u0434\u0438\u0442\u0435\u0441\u044C, \u0447\u0442\u043E \u0441\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u043B\u0438 \u041F\u041E\u041B\u041D\u042B\u0419 URL \u2014 \u043E\u043D \u043C\u043E\u0436\u0435\u0442 \u0437\u0430\u043D\u0438\u043C\u0430\u0442\u044C \u043D\u0435\u0441\u043A\u043E\u043B\u044C\u043A\u043E \u0441\u0442\u0440\u043E\u043A.",
      // ============================================================================
      // Команды - Чат
      // ============================================================================
      "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 (--fast for suggestion model)": "\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 (--fast \u0434\u043B\u044F \u043C\u043E\u0434\u0435\u043B\u0438 \u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043E\u043A)",
      "Set a lighter model for prompt suggestions and speculative execution": "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u043E\u0431\u043B\u0435\u0433\u0447\u0451\u043D\u043D\u0443\u044E \u043C\u043E\u0434\u0435\u043B\u044C \u0434\u043B\u044F \u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043E\u043A \u0438 \u0441\u043F\u0435\u043A\u0443\u043B\u044F\u0442\u0438\u0432\u043D\u043E\u0433\u043E \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F",
      "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",
      Yes: "\u0414\u0430",
      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",
      // MCP Management - Core translations
      Disable: "\u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C",
      Enable: "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C",
      Authenticate: "\u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F",
      "Re-authenticate": "\u041F\u043E\u0432\u0442\u043E\u0440\u043D\u0430\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F",
      "Clear Authentication": "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044E",
      disabled: "\u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D",
      "Server:": "\u0421\u0435\u0440\u0432\u0435\u0440:",
      Reconnect: "\u041F\u0435\u0440\u0435\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C",
      "View tools": "\u041F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0435\u0442\u044C \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B",
      "(disabled)": "(\u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D)",
      "Error:": "\u041E\u0448\u0438\u0431\u043A\u0430:",
      tool: "\u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442",
      connected: "\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D",
      connecting: "\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435",
      disconnected: "\u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D",
      error: "\u043E\u0448\u0438\u0431\u043A\u0430",
      // Invalid tool related translations
      "{{count}} invalid tools": "{{count}} \u043D\u0435\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0445 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      invalid: "\u043D\u0435\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0439",
      "invalid: {{reason}}": "\u043D\u0435\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043B\u044C\u043D\u043E: {{reason}}",
      "missing name": "\u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u0435\u0442 \u0438\u043C\u044F",
      "missing description": "\u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u0435\u0442 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435",
      "(unnamed)": "(\u0431\u0435\u0437 \u0438\u043C\u0435\u043D\u0438)",
      "Warning: This tool cannot be called by the LLM": "\u041F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u0435: \u042D\u0442\u043E\u0442 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442 \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0431\u044B\u0442\u044C \u0432\u044B\u0437\u0432\u0430\u043D LLM",
      Reason: "\u041F\u0440\u0438\u0447\u0438\u043D\u0430",
      "Tools must have both name and description to be used by the LLM.": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0434\u043E\u043B\u0436\u043D\u044B \u0438\u043C\u0435\u0442\u044C \u043A\u0430\u043A \u0438\u043C\u044F, \u0442\u0430\u043A \u0438 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435, \u0447\u0442\u043E\u0431\u044B \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F LLM.",
      "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 ...",
      "Always allow in this project": "\u0412\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C \u0432 \u044D\u0442\u043E\u043C \u043F\u0440\u043E\u0435\u043A\u0442\u0435",
      "Always allow {{action}} in this project": "\u0412\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C {{action}} \u0432 \u044D\u0442\u043E\u043C \u043F\u0440\u043E\u0435\u043A\u0442\u0435",
      "Always allow for this user": "\u0412\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F",
      "Always allow {{action}} for this user": "\u0412\u0441\u0435\u0433\u0434\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0430\u0442\u044C {{action}} \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F",
      "Yes, restore previous mode ({{mode}})": "\u0414\u0430, \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0438\u0439 \u0440\u0435\u0436\u0438\u043C ({{mode}})",
      "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",
      "Select Authentication Method": "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u043C\u0435\u0442\u043E\u0434 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438",
      "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.",
      "Terms of Services and Privacy Notice": "\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",
      "Qwen OAuth": "Qwen OAuth",
      "Discontinued \u2014 switch to Coding Plan or API Key": "\u041F\u0440\u0435\u043A\u0440\u0430\u0449\u0435\u043D\u043E \u2014 \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u0435\u0441\u044C \u043D\u0430 Coding Plan \u0438\u043B\u0438 API Key",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch provider.": "\u0411\u0435\u0441\u043F\u043B\u0430\u0442\u043D\u044B\u0439 \u0443\u0440\u043E\u0432\u0435\u043D\u044C Qwen OAuth \u043F\u0440\u0435\u043A\u0440\u0430\u0449\u0451\u043D 2026-04-15. \u0412\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435 /auth \u0434\u043B\u044F \u0441\u043C\u0435\u043D\u044B \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead.": "\u0411\u0435\u0441\u043F\u043B\u0430\u0442\u043D\u044B\u0439 \u0443\u0440\u043E\u0432\u0435\u043D\u044C Qwen OAuth \u043F\u0440\u0435\u043A\u0440\u0430\u0449\u0451\u043D 2026-04-15. \u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 Coding Plan \u0438\u043B\u0438 API Key.",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.": "\u0411\u0435\u0441\u043F\u043B\u0430\u0442\u043D\u044B\u0439 \u0443\u0440\u043E\u0432\u0435\u043D\u044C Qwen OAuth \u0431\u044B\u043B \u043F\u0440\u0435\u043A\u0440\u0430\u0449\u0435\u043D 2026-04-15. \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0432\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u043C\u043E\u0434\u0435\u043B\u044C \u043E\u0442 \u0434\u0440\u0443\u0433\u043E\u0433\u043E \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430 \u0438\u043B\u0438 \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435 /auth \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F.",
      "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n": "\n\u26A0 \u0411\u0435\u0441\u043F\u043B\u0430\u0442\u043D\u044B\u0439 \u0443\u0440\u043E\u0432\u0435\u043D\u044C Qwen OAuth \u043F\u0440\u0435\u043A\u0440\u0430\u0449\u0451\u043D 2026-04-15. \u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0434\u0440\u0443\u0433\u0443\u044E \u043E\u043F\u0446\u0438\u044E.\n",
      "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models": "\u041F\u043B\u0430\u0442\u043D\u043E \xB7 \u0414\u043E 6 000 \u0437\u0430\u043F\u0440\u043E\u0441\u043E\u0432/5 \u0447\u0430\u0441\u043E\u0432 \xB7 \u0412\u0441\u0435 \u043C\u043E\u0434\u0435\u043B\u0438 Alibaba Cloud Coding Plan",
      "Alibaba Cloud Coding Plan": "Alibaba Cloud Coding Plan",
      "Bring your own API key": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u0441\u0432\u043E\u0439 API-\u043A\u043B\u044E\u0447",
      "Browser-based authentication with third-party providers (e.g. OpenRouter, ModelScope)": "\u0411\u0440\u0430\u0443\u0437\u0435\u0440\u043D\u0430\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0441 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043C \u0441\u0442\u043E\u0440\u043E\u043D\u043D\u0438\u0445 \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u043E\u0432 (\u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, OpenRouter, ModelScope)",
      "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.",
      "Note: Your existing API key will not be cleared when using Qwen OAuth.": "\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 \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.",
      "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)",
      Modality: "\u041C\u043E\u0434\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u044C",
      "Context Window": "\u041A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u043D\u043E\u0435 \u043E\u043A\u043D\u043E",
      text: "\u0442\u0435\u043A\u0441\u0442",
      "text-only": "\u0442\u043E\u043B\u044C\u043A\u043E \u0442\u0435\u043A\u0441\u0442",
      image: "\u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435",
      pdf: "PDF",
      audio: "\u0430\u0443\u0434\u0438\u043E",
      video: "\u0432\u0438\u0434\u0435\u043E",
      "not set": "\u043D\u0435 \u0437\u0430\u0434\u0430\u043D\u043E",
      none: "\u043D\u0435\u0442",
      unknown: "\u043D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\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.6 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.6 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",
      "Manage permission rules": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u043F\u0440\u0430\u0432\u0438\u043B\u0430\u043C\u0438 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0439",
      Allow: "\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C",
      Ask: "\u0421\u043F\u0440\u043E\u0441\u0438\u0442\u044C",
      Deny: "\u0417\u0430\u043F\u0440\u0435\u0442\u0438\u0442\u044C",
      Workspace: "\u0420\u0430\u0431\u043E\u0447\u0430\u044F \u043E\u0431\u043B\u0430\u0441\u0442\u044C",
      "Qwen Code won't ask before using allowed tools.": "Qwen Code \u043D\u0435 \u0431\u0443\u0434\u0435\u0442 \u0441\u043F\u0440\u0430\u0448\u0438\u0432\u0430\u0442\u044C \u043F\u0435\u0440\u0435\u0434 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043C \u0440\u0430\u0437\u0440\u0435\u0448\u0451\u043D\u043D\u044B\u0445 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432.",
      "Qwen Code will ask before using these tools.": "Qwen Code \u0441\u043F\u0440\u043E\u0441\u0438\u0442 \u043F\u0435\u0440\u0435\u0434 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043C \u044D\u0442\u0438\u0445 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432.",
      "Qwen Code is not allowed to use denied tools.": "Qwen Code \u043D\u0435 \u043C\u043E\u0436\u0435\u0442 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0437\u0430\u043F\u0440\u0435\u0449\u0451\u043D\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B.",
      "Manage trusted directories for this workspace.": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0434\u043E\u0432\u0435\u0440\u0435\u043D\u043D\u044B\u043C\u0438 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430\u043C\u0438 \u0434\u043B\u044F \u044D\u0442\u043E\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u043E\u0431\u043B\u0430\u0441\u0442\u0438.",
      "Any use of the {{tool}} tool": "\u041B\u044E\u0431\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430 {{tool}}",
      "{{tool}} commands matching '{{pattern}}'": "\u041A\u043E\u043C\u0430\u043D\u0434\u044B {{tool}}, \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0435 '{{pattern}}'",
      "From user settings": "\u0418\u0437 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A",
      "From project settings": "\u0418\u0437 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u043F\u0440\u043E\u0435\u043A\u0442\u0430",
      "From session": "\u0418\u0437 \u0441\u0435\u0441\u0441\u0438\u0438",
      "Project settings (local)": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u043F\u0440\u043E\u0435\u043A\u0442\u0430 (\u043B\u043E\u043A\u0430\u043B\u044C\u043D\u044B\u0435)",
      "Saved in .qwen/settings.local.json": "\u0421\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u043E \u0432 .qwen/settings.local.json",
      "Project settings": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u043F\u0440\u043E\u0435\u043A\u0442\u0430",
      "Checked in at .qwen/settings.json": "\u0417\u0430\u0444\u0438\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u043D\u043E \u0432 .qwen/settings.json",
      "User settings": "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438",
      "Saved in at ~/.qwen/settings.json": "\u0421\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u043E \u0432 ~/.qwen/settings.json",
      "Add a new rule\u2026": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043D\u043E\u0432\u043E\u0435 \u043F\u0440\u0430\u0432\u0438\u043B\u043E\u2026",
      "Add {{type}} permission rule": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043F\u0440\u0430\u0432\u0438\u043B\u043E \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u044F {{type}}",
      "Permission rules are a tool name, optionally followed by a specifier in parentheses.": "\u041F\u0440\u0430\u0432\u0438\u043B\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0439 \u2014 \u044D\u0442\u043E \u0438\u043C\u044F \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430, \u0437\u0430 \u043A\u043E\u0442\u043E\u0440\u044B\u043C \u043C\u043E\u0436\u0435\u0442 \u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u044C \u0441\u043F\u0435\u0446\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440 \u0432 \u0441\u043A\u043E\u0431\u043A\u0430\u0445.",
      "e.g.,": "\u043D\u0430\u043F\u0440.",
      or: "\u0438\u043B\u0438",
      "Enter permission rule\u2026": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043F\u0440\u0430\u0432\u0438\u043B\u043E \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u044F\u2026",
      "Enter to submit \xB7 Esc to cancel": "Enter \u0434\u043B\u044F \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0438 \xB7 Esc \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B",
      "Where should this rule be saved?": "\u0413\u0434\u0435 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u044D\u0442\u043E \u043F\u0440\u0430\u0432\u0438\u043B\u043E?",
      "Enter to confirm \xB7 Esc to cancel": "Enter \u0434\u043B\u044F \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0438\u044F \xB7 Esc \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B",
      "Delete {{type}} rule?": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u043F\u0440\u0430\u0432\u0438\u043B\u043E {{type}}?",
      "Are you sure you want to delete this permission rule?": "\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 \u044D\u0442\u043E \u043F\u0440\u0430\u0432\u0438\u043B\u043E \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u044F?",
      "Permissions:": "\u0420\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u044F:",
      "(\u2190/\u2192 or tab to cycle)": "(\u2190/\u2192 \u0438\u043B\u0438 Tab \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F)",
      "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel": "\u2191\u2193 \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F \xB7 Enter \u0432\u044B\u0431\u043E\u0440 \xB7 \u0412\u0432\u043E\u0434 \u0434\u043B\u044F \u043F\u043E\u0438\u0441\u043A\u0430 \xB7 Esc \u043E\u0442\u043C\u0435\u043D\u0430",
      "Search\u2026": "\u041F\u043E\u0438\u0441\u043A\u2026",
      "Use /trust to manage folder trust settings for this workspace.": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /trust \u0434\u043B\u044F \u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F \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 \u044D\u0442\u043E\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u043E\u0431\u043B\u0430\u0441\u0442\u0438.",
      // Workspace directory management
      "Add directory\u2026": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u2026",
      "Add directory to workspace": "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043A\u0430\u0442\u0430\u043B\u043E\u0433 \u0432 \u0440\u0430\u0431\u043E\u0447\u0443\u044E \u043E\u0431\u043B\u0430\u0441\u0442\u044C",
      "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.": "Qwen Code \u043C\u043E\u0436\u0435\u0442 \u0447\u0438\u0442\u0430\u0442\u044C \u0444\u0430\u0439\u043B\u044B \u0432 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u043E\u0431\u043B\u0430\u0441\u0442\u0438 \u0438 \u0432\u043D\u043E\u0441\u0438\u0442\u044C \u043F\u0440\u0430\u0432\u043A\u0438, \u043A\u043E\u0433\u0434\u0430 \u0430\u0432\u0442\u043E\u043F\u0440\u0438\u0451\u043C \u043F\u0440\u0430\u0432\u043E\u043A \u0432\u043A\u043B\u044E\u0447\u0451\u043D.",
      "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.": "Qwen Code \u0441\u043C\u043E\u0436\u0435\u0442 \u0447\u0438\u0442\u0430\u0442\u044C \u0444\u0430\u0439\u043B\u044B \u0432 \u044D\u0442\u043E\u043C \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0435 \u0438 \u0432\u043D\u043E\u0441\u0438\u0442\u044C \u043F\u0440\u0430\u0432\u043A\u0438, \u043A\u043E\u0433\u0434\u0430 \u0430\u0432\u0442\u043E\u043F\u0440\u0438\u0451\u043C \u043F\u0440\u0430\u0432\u043E\u043A \u0432\u043A\u043B\u044E\u0447\u0451\u043D.",
      "Enter the path to the directory:": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043F\u0443\u0442\u044C \u043A \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0443:",
      "Enter directory path\u2026": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043F\u0443\u0442\u044C \u043A \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0443\u2026",
      "Tab to complete \xB7 Enter to add \xB7 Esc to cancel": "Tab \u0434\u043B\u044F \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F \xB7 Enter \u0434\u043B\u044F \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u0438\u044F \xB7 Esc \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B",
      "Remove directory?": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u043A\u0430\u0442\u0430\u043B\u043E\u0433?",
      "Are you sure you want to remove this directory from the workspace?": "\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 \u044D\u0442\u043E\u0442 \u043A\u0430\u0442\u0430\u043B\u043E\u0433 \u0438\u0437 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u043E\u0431\u043B\u0430\u0441\u0442\u0438?",
      "  (Original working directory)": "  (\u0418\u0441\u0445\u043E\u0434\u043D\u044B\u0439 \u0440\u0430\u0431\u043E\u0447\u0438\u0439 \u043A\u0430\u0442\u0430\u043B\u043E\u0433)",
      "  (from settings)": "  (\u0438\u0437 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A)",
      "Directory does not exist.": "\u041A\u0430\u0442\u0430\u043B\u043E\u0433 \u043D\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442.",
      "Path is not a directory.": "\u041F\u0443\u0442\u044C \u043D\u0435 \u044F\u0432\u043B\u044F\u0435\u0442\u0441\u044F \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u043E\u043C.",
      "This directory is already in the workspace.": "\u042D\u0442\u043E\u0442 \u043A\u0430\u0442\u0430\u043B\u043E\u0433 \u0443\u0436\u0435 \u0435\u0441\u0442\u044C \u0432 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u043E\u0431\u043B\u0430\u0441\u0442\u0438.",
      "Already covered by existing directory: {{dir}}": "\u0423\u0436\u0435 \u043E\u0445\u0432\u0430\u0447\u0435\u043D \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u043C \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u043E\u043C: {{dir}}",
      // ============================================================================
      // Строка состояния
      // ============================================================================
      "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.",
      "Press \u2191 to edit queued messages": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 \u2191 \u0434\u043B\u044F \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439 \u0432 \u043E\u0447\u0435\u0440\u0435\u0434\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:",
      "Current tasks": "\u0422\u0435\u043A\u0443\u0449\u0438\u0435 \u0437\u0430\u0434\u0430\u0447\u0438",
      "... 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.",
      "Press Ctrl+O to toggle compact mode \u2014 hide tool output and thinking for a cleaner view.": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Ctrl+O \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F \u043A\u043E\u043C\u043F\u0430\u043A\u0442\u043D\u043E\u0433\u043E \u0440\u0435\u0436\u0438\u043C\u0430 \u2014 \u0441\u043A\u0440\u044B\u0442\u044C \u0432\u044B\u0432\u043E\u0434 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u0438 \u0440\u0430\u0441\u0441\u0443\u0436\u0434\u0435\u043D\u0438\u044F.",
      "Add a QWEN.md file to give Qwen Code persistent project context.": "\u0414\u043E\u0431\u0430\u0432\u044C\u0442\u0435 \u0444\u0430\u0439\u043B QWEN.md, \u0447\u0442\u043E\u0431\u044B \u043F\u0440\u0435\u0434\u043E\u0441\u0442\u0430\u0432\u0438\u0442\u044C Qwen Code \u043F\u043E\u0441\u0442\u043E\u044F\u043D\u043D\u044B\u0439 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 \u043F\u0440\u043E\u0435\u043A\u0442\u0430.",
      "Use /btw to ask a quick side question without disrupting the conversation.": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /btw, \u0447\u0442\u043E\u0431\u044B \u0437\u0430\u0434\u0430\u0442\u044C \u043A\u043E\u0440\u043E\u0442\u043A\u0438\u0439 \u043F\u043E\u0431\u043E\u0447\u043D\u044B\u0439 \u0432\u043E\u043F\u0440\u043E\u0441, \u043D\u0435 \u043F\u0440\u0435\u0440\u044B\u0432\u0430\u044F \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439 \u0440\u0430\u0437\u0433\u043E\u0432\u043E\u0440.",
      "Context is almost full! Run /compress now or start /new to continue.": "\u041A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 \u043F\u043E\u0447\u0442\u0438 \u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D! \u0412\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435 /compress \u0441\u0435\u0439\u0447\u0430\u0441 \u0438\u043B\u0438 \u043D\u0430\u0447\u043D\u0438\u0442\u0435 /new, \u0447\u0442\u043E\u0431\u044B \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C.",
      "Context is getting full. Use /compress to free up space.": "\u041A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 \u0437\u0430\u043F\u043E\u043B\u043D\u044F\u0435\u0442\u0441\u044F. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /compress, \u0447\u0442\u043E\u0431\u044B \u043E\u0441\u0432\u043E\u0431\u043E\u0434\u0438\u0442\u044C \u043C\u0435\u0441\u0442\u043E.",
      "Long conversation? /compress summarizes history to free context.": "\u0414\u043E\u043B\u0433\u0438\u0439 \u0440\u0430\u0437\u0433\u043E\u0432\u043E\u0440? /compress \u043F\u043E\u0434\u0432\u0435\u0434\u0451\u0442 \u0438\u0442\u043E\u0433 \u0438\u0441\u0442\u043E\u0440\u0438\u0438, \u0447\u0442\u043E\u0431\u044B \u043E\u0441\u0432\u043E\u0431\u043E\u0434\u0438\u0442\u044C \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442.",
      // ============================================================================
      // Custom API Key Configuration
      // ============================================================================
      "You can configure your API key and models in settings.json": "\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0438\u0442\u044C API-\u043A\u043B\u044E\u0447 \u0438 \u043C\u043E\u0434\u0435\u043B\u0438 \u0432 settings.json",
      "Refer to the documentation for setup instructions": "\u0418\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u0438 \u043F\u043E \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0435 \u0441\u043C. \u0432 \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430\u0446\u0438\u0438",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "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 Coding Plan API key here": "\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C API-\u043A\u043B\u044E\u0447 Coding Plan \u0437\u0434\u0435\u0441\u044C",
      "New model configurations are available for Alibaba Cloud 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 Alibaba Cloud 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",
      "Paste your api key of ModelStudio Coding Plan and you're all set!": "\u0412\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u0432\u0430\u0448 API-\u043A\u043B\u044E\u0447 ModelStudio Coding Plan \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.:",
      "Select Region for Coding Plan": "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0440\u0435\u0433\u0438\u043E\u043D Coding Plan",
      "Choose based on where your account is registered": "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0432 \u0437\u0430\u0432\u0438\u0441\u0438\u043C\u043E\u0441\u0442\u0438 \u043E\u0442 \u043C\u0435\u0441\u0442\u0430 \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0432\u0430\u0448\u0435\u0433\u043E \u0430\u043A\u043A\u0430\u0443\u043D\u0442\u0430",
      "Enter Coding Plan API Key": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 API-\u043A\u043B\u044E\u0447 Coding Plan",
      // ============================================================================
      // 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?",
      '{{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).",
      // ============================================================================
      // Context Usage Component
      // ============================================================================
      "Context Usage": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430",
      "% used": "% \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u043E",
      "% context used": "% \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u043E",
      "Context exceeds limit! Use /compress or /clear to reduce.": "\u041A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 \u043F\u0440\u0435\u0432\u044B\u0448\u0430\u0435\u0442 \u043B\u0438\u043C\u0438\u0442! \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /compress \u0438\u043B\u0438 /clear \u0434\u043B\u044F \u0443\u043C\u0435\u043D\u044C\u0448\u0435\u043D\u0438\u044F.",
      "Use /compress or /clear": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /compress \u0438\u043B\u0438 /clear",
      "No API response yet. Send a message to see actual usage.": "\u041F\u043E\u043A\u0430 \u043D\u0435\u0442 \u043E\u0442\u0432\u0435\u0442\u0430 \u043E\u0442 API. \u041E\u0442\u043F\u0440\u0430\u0432\u044C\u0442\u0435 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435, \u0447\u0442\u043E\u0431\u044B \u0443\u0432\u0438\u0434\u0435\u0442\u044C \u0444\u0430\u043A\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435.",
      "Estimated pre-conversation overhead": "\u041E\u0446\u0435\u043D\u043E\u0447\u043D\u044B\u0435 \u043D\u0430\u043A\u043B\u0430\u0434\u043D\u044B\u0435 \u0440\u0430\u0441\u0445\u043E\u0434\u044B \u043F\u0435\u0440\u0435\u0434 \u0431\u0435\u0441\u0435\u0434\u043E\u0439",
      "Context window": "\u041A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u043D\u043E\u0435 \u043E\u043A\u043D\u043E",
      tokens: "\u0442\u043E\u043A\u0435\u043D\u043E\u0432",
      Used: "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u043E",
      Free: "\u0421\u0432\u043E\u0431\u043E\u0434\u043D\u043E",
      "Autocompact buffer": "\u0411\u0443\u0444\u0435\u0440 \u0430\u0432\u0442\u043E\u0443\u043F\u0430\u043A\u043E\u0432\u043A\u0438",
      "Usage by category": "\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u043F\u043E \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F\u043C",
      "System prompt": "\u0421\u0438\u0441\u0442\u0435\u043C\u043D\u0430\u044F \u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0430",
      "Built-in tools": "\u0412\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B",
      "MCP tools": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B MCP",
      "Memory files": "\u0424\u0430\u0439\u043B\u044B \u043F\u0430\u043C\u044F\u0442\u0438",
      Skills: "\u041D\u0430\u0432\u044B\u043A\u0438",
      Messages: "\u0421\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F",
      "Show context window usage breakdown.": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0440\u0430\u0437\u0431\u0438\u0432\u043A\u0443 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u043D\u043E\u0433\u043E \u043E\u043A\u043D\u0430.",
      "Run /context detail for per-item breakdown.": "\u0412\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435 /context detail \u0434\u043B\u044F \u0434\u0435\u0442\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u043F\u043E \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u043C.",
      active: "\u0430\u043A\u0442\u0438\u0432\u043D\u043E",
      "body loaded": "\u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u0437\u0430\u0433\u0440\u0443\u0436\u0435\u043D\u043E",
      memory: "\u043F\u0430\u043C\u044F\u0442\u044C",
      // MCP Management Dialog
      // ============================================================================
      "MCP Management": "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 MCP",
      "Server List": "\u0421\u043F\u0438\u0441\u043E\u043A \u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432",
      "Server Detail": "\u0414\u0435\u0442\u0430\u043B\u0438 \u0441\u0435\u0440\u0432\u0435\u0440\u0430",
      "Disable Server": "\u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0441\u0435\u0440\u0432\u0435\u0440",
      "Tool List": "\u0421\u043F\u0438\u0441\u043E\u043A \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "Tool Detail": "\u0414\u0435\u0442\u0430\u043B\u0438 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430",
      "Loading...": "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430...",
      "Unknown step": "\u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u044B\u0439 \u0448\u0430\u0433",
      "Esc to back": "Esc \u0434\u043B\u044F \u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close": "\u2191\u2193 \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F \xB7 Enter \u0432\u044B\u0431\u0440\u0430\u0442\u044C \xB7 Esc \u0437\u0430\u043A\u0440\u044B\u0442\u044C",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back": "\u2191\u2193 \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F \xB7 Enter \u0432\u044B\u0431\u0440\u0430\u0442\u044C \xB7 Esc \u043D\u0430\u0437\u0430\u0434",
      "\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back": "\u2191\u2193 \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F \xB7 Enter \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u044C \xB7 Esc \u043D\u0430\u0437\u0430\u0434",
      "User Settings (global)": "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F (\u0433\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u044B\u0435)",
      "Workspace Settings (project-specific)": "\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 (\u043F\u0440\u043E\u0435\u043A\u0442\u043D\u044B\u0435)",
      "Disable server:": "\u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0441\u0435\u0440\u0432\u0435\u0440:",
      "Select where to add the server to the exclude list:": "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435, \u0433\u0434\u0435 \u0434\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u0435\u0440\u0432\u0435\u0440 \u0432 \u0441\u043F\u0438\u0441\u043E\u043A \u0438\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0439:",
      "Press 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",
      "Status:": "\u0421\u0442\u0430\u0442\u0443\u0441:",
      "Command:": "\u041A\u043E\u043C\u0430\u043D\u0434\u0430:",
      "Working Directory:": "\u0420\u0430\u0431\u043E\u0447\u0438\u0439 \u043A\u0430\u0442\u0430\u043B\u043E\u0433:",
      "Capabilities:": "\u0412\u043E\u0437\u043C\u043E\u0436\u043D\u043E\u0441\u0442\u0438:",
      "No server selected": "\u0421\u0435\u0440\u0432\u0435\u0440 \u043D\u0435 \u0432\u044B\u0431\u0440\u0430\u043D",
      // MCP Server List
      "User MCPs": "MCP \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F",
      "Project MCPs": "MCP \u043F\u0440\u043E\u0435\u043A\u0442\u0430",
      "Extension MCPs": "MCP \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439",
      server: "\u0441\u0435\u0440\u0432\u0435\u0440",
      servers: "\u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432",
      "Add MCP servers to your settings to get started.": "\u0414\u043E\u0431\u0430\u0432\u044C\u0442\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u044B MCP \u0432 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438, \u0447\u0442\u043E\u0431\u044B \u043D\u0430\u0447\u0430\u0442\u044C.",
      "Run qwen --debug to see error logs": "\u0417\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435 qwen --debug \u0434\u043B\u044F \u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0430 \u0436\u0443\u0440\u043D\u0430\u043B\u043E\u0432 \u043E\u0448\u0438\u0431\u043E\u043A",
      // MCP OAuth Authentication
      "OAuth Authentication": "OAuth-\u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F",
      "Press Enter to start authentication, Esc to go back": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Enter \u0434\u043B\u044F \u043D\u0430\u0447\u0430\u043B\u0430 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438, Esc \u0434\u043B\u044F \u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430",
      "Authenticating... Please complete the login in your browser.": "\u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F... \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u0435 \u0432\u0445\u043E\u0434 \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435.",
      "Press Enter or Esc to go back": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Enter \u0438\u043B\u0438 Esc \u0434\u043B\u044F \u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430",
      // MCP Tool List
      "No tools available for this server.": "\u0414\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u043D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0445 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432.",
      destructive: "\u0434\u0435\u0441\u0442\u0440\u0443\u043A\u0442\u0438\u0432\u043D\u044B\u0439",
      "read-only": "\u0442\u043E\u043B\u044C\u043A\u043E \u0447\u0442\u0435\u043D\u0438\u0435",
      "open-world": "\u043E\u0442\u043A\u0440\u044B\u0442\u044B\u0439 \u043C\u0438\u0440",
      idempotent: "\u0438\u0434\u0435\u043C\u043F\u043E\u0442\u0435\u043D\u0442\u043D\u044B\u0439",
      "Tools for {{name}}": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0434\u043B\u044F {{name}}",
      "Tools for {{serverName}}": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B \u0434\u043B\u044F {{serverName}}",
      "{{current}}/{{total}}": "{{current}}/{{total}}",
      // MCP Tool Detail
      required: "\u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u044B\u0439",
      Type: "\u0422\u0438\u043F",
      Enum: "\u041F\u0435\u0440\u0435\u0447\u0438\u0441\u043B\u0435\u043D\u0438\u0435",
      Parameters: "\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B",
      "No tool selected": "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442 \u043D\u0435 \u0432\u044B\u0431\u0440\u0430\u043D",
      Annotations: "\u0410\u043D\u043D\u043E\u0442\u0430\u0446\u0438\u0438",
      Title: "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A",
      "Read Only": "\u0422\u043E\u043B\u044C\u043A\u043E \u0447\u0442\u0435\u043D\u0438\u0435",
      Destructive: "\u0414\u0435\u0441\u0442\u0440\u0443\u043A\u0442\u0438\u0432\u043D\u044B\u0439",
      Idempotent: "\u0418\u0434\u0435\u043C\u043F\u043E\u0442\u0435\u043D\u0442\u043D\u044B\u0439",
      "Open World": "\u041E\u0442\u043A\u0440\u044B\u0442\u044B\u0439 \u043C\u0438\u0440",
      Server: "\u0421\u0435\u0440\u0432\u0435\u0440",
      "{{region}} configuration updated successfully.": "\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.",
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json.": "\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.",
      "Tip: Use /model to switch between available Coding Plan models.": "\u0421\u043E\u0432\u0435\u0442: \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 /model \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F \u043C\u0435\u0436\u0434\u0443 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u043C\u0438 \u043C\u043E\u0434\u0435\u043B\u044F\u043C\u0438 Coding Plan.",
      // ============================================================================
      // Ask User Question Tool
      // ============================================================================
      "Please answer the following question(s):": "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u043E\u0442\u0432\u0435\u0442\u044C\u0442\u0435 \u043D\u0430 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0439(\u0438\u0435) \u0432\u043E\u043F\u0440\u043E\u0441(\u044B):",
      "Cannot ask user questions in non-interactive mode. Please run in interactive mode to use this tool.": "\u041D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u0437\u0430\u0434\u0430\u0432\u0430\u0442\u044C \u0432\u043E\u043F\u0440\u043E\u0441\u044B \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E \u0432 \u043D\u0435\u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u043E\u043C \u0440\u0435\u0436\u0438\u043C\u0435. \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435 \u0432 \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u043E\u043C \u0440\u0435\u0436\u0438\u043C\u0435 \u0434\u043B\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F \u044D\u0442\u043E\u0433\u043E \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430.",
      "User declined to answer the questions.": "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u043E\u0442\u043A\u0430\u0437\u0430\u043B\u0441\u044F \u043E\u0442\u0432\u0435\u0447\u0430\u0442\u044C \u043D\u0430 \u0432\u043E\u043F\u0440\u043E\u0441\u044B.",
      "User has provided the following answers:": "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u043F\u0440\u0435\u0434\u043E\u0441\u0442\u0430\u0432\u0438\u043B \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0435 \u043E\u0442\u0432\u0435\u0442\u044B:",
      "Failed to process user answers:": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0430\u0442\u044C \u043E\u0442\u0432\u0435\u0442\u044B \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F:",
      "Type something...": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0442\u043E-\u0442\u043E...",
      Submit: "\u041E\u0442\u043F\u0440\u0430\u0432\u0438\u0442\u044C",
      "Submit answers": "\u041E\u0442\u043F\u0440\u0430\u0432\u0438\u0442\u044C \u043E\u0442\u0432\u0435\u0442\u044B",
      Cancel: "\u041E\u0442\u043C\u0435\u043D\u0430",
      "Your answers:": "\u0412\u0430\u0448\u0438 \u043E\u0442\u0432\u0435\u0442\u044B:",
      "(not answered)": "(\u043D\u0435 \u043E\u0442\u0432\u0435\u0447\u0435\u043D\u043E)",
      "Ready to submit your answers?": "\u0413\u043E\u0442\u043E\u0432\u044B \u043E\u0442\u043F\u0440\u0430\u0432\u0438\u0442\u044C \u0441\u0432\u043E\u0438 \u043E\u0442\u0432\u0435\u0442\u044B?",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select": "\u2191/\u2193: \u041D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F | \u2190/\u2192: \u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u0432\u043A\u043B\u0430\u0434\u043E\u043A | Enter: \u0412\u044B\u0431\u043E\u0440",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: \u041D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F | \u2190/\u2192: \u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u0432\u043A\u043B\u0430\u0434\u043E\u043A | Space/Enter: \u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C | Esc: \u041E\u0442\u043C\u0435\u043D\u0430",
      "\u2191/\u2193: Navigate | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: \u041D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F | Space/Enter: \u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C | Esc: \u041E\u0442\u043C\u0435\u043D\u0430",
      "\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel": "\u2191/\u2193: \u041D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F | Enter: \u0412\u044B\u0431\u043E\u0440 | Esc: \u041E\u0442\u043C\u0435\u043D\u0430",
      // ============================================================================
      // Commands - Auth
      // ============================================================================
      "Configure Qwen authentication information with Qwen-OAuth or Alibaba Cloud Coding Plan": "\u041D\u0430\u0441\u0442\u0440\u043E\u0438\u0442\u044C \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044E Qwen \u0447\u0435\u0440\u0435\u0437 Qwen-OAuth \u0438\u043B\u0438 Alibaba Cloud Coding Plan",
      "Authenticate using Qwen OAuth": "\u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0447\u0435\u0440\u0435\u0437 Qwen OAuth",
      "Authenticate using Alibaba Cloud Coding Plan": "\u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0447\u0435\u0440\u0435\u0437 Alibaba Cloud Coding Plan",
      "Region for Coding Plan (china/global)": "\u0420\u0435\u0433\u0438\u043E\u043D \u0434\u043B\u044F Coding Plan (china/global)",
      "API key for Coding Plan": "API-\u043A\u043B\u044E\u0447 \u0434\u043B\u044F Coding Plan",
      "Show current authentication status": "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0442\u0435\u043A\u0443\u0449\u0438\u0439 \u0441\u0442\u0430\u0442\u0443\u0441 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438",
      "Authentication completed successfully.": "\u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0443\u0441\u043F\u0435\u0448\u043D\u043E \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0430.",
      "Starting Qwen OAuth authentication...": "\u0417\u0430\u043F\u0443\u0441\u043A \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438 Qwen OAuth...",
      "Successfully authenticated with Qwen OAuth.": "\u0423\u0441\u043F\u0435\u0448\u043D\u0430\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0447\u0435\u0440\u0435\u0437 Qwen OAuth.",
      "Failed to authenticate with Qwen OAuth: {{error}}": "\u041E\u0448\u0438\u0431\u043A\u0430 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438 \u0447\u0435\u0440\u0435\u0437 Qwen OAuth: {{error}}",
      "Processing Alibaba Cloud Coding Plan authentication...": "\u041E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438 Alibaba Cloud Coding Plan...",
      "Successfully authenticated with Alibaba Cloud Coding Plan.": "\u0423\u0441\u043F\u0435\u0448\u043D\u0430\u044F \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0447\u0435\u0440\u0435\u0437 Alibaba Cloud Coding Plan.",
      "Failed to authenticate with Coding Plan: {{error}}": "\u041E\u0448\u0438\u0431\u043A\u0430 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438 \u0447\u0435\u0440\u0435\u0437 Coding Plan: {{error}}",
      "\u4E2D\u56FD (China)": "\u4E2D\u56FD (China)",
      "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)": "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)",
      Global: "\u0413\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u044B\u0439",
      "Alibaba Cloud (alibabacloud.com)": "Alibaba Cloud (alibabacloud.com)",
      "Select region for Coding Plan:": "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0440\u0435\u0433\u0438\u043E\u043D \u0434\u043B\u044F Coding Plan:",
      "Enter your Coding Plan API key: ": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0432\u0430\u0448 API-\u043A\u043B\u044E\u0447 Coding Plan: ",
      "Select authentication method:": "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u043C\u0435\u0442\u043E\u0434 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438:",
      "\n=== Authentication Status ===\n": "\n=== \u0421\u0442\u0430\u0442\u0443\u0441 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438 ===\n",
      "\u26A0\uFE0F  No authentication method configured.\n": "\u26A0\uFE0F  \u041C\u0435\u0442\u043E\u0434 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438 \u043D\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D.\n",
      "Run one of the following commands to get started:\n": "\u0412\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435 \u043E\u0434\u043D\u0443 \u0438\u0437 \u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0445 \u043A\u043E\u043C\u0430\u043D\u0434 \u0434\u043B\u044F \u043D\u0430\u0447\u0430\u043B\u0430:\n",
      "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)": "  qwen auth qwen-oauth     - \u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0447\u0435\u0440\u0435\u0437 Qwen OAuth (\u043F\u0440\u0435\u043A\u0440\u0430\u0449\u0435\u043D\u043E)",
      "  qwen auth coding-plan      - Authenticate with Alibaba Cloud Coding Plan\n": "  qwen auth coding-plan      - \u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0447\u0435\u0440\u0435\u0437 Alibaba Cloud Coding Plan\n",
      "Or simply run:": "\u0418\u043B\u0438 \u043F\u0440\u043E\u0441\u0442\u043E \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435:",
      "  qwen auth                - Interactive authentication setup\n": "  qwen auth                - \u0418\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u0430\u044F \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438\n",
      "\u2713 Authentication Method: Qwen OAuth": "\u2713 \u041C\u0435\u0442\u043E\u0434 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438: Qwen OAuth",
      "  Type: Free tier (discontinued 2026-04-15)": "  \u0422\u0438\u043F: \u0411\u0435\u0441\u043F\u043B\u0430\u0442\u043D\u044B\u0439 \u0443\u0440\u043E\u0432\u0435\u043D\u044C (\u043F\u0440\u0435\u043A\u0440\u0430\u0449\u0435\u043D\u043E 2026-04-15)",
      "  Limit: No longer available": "  \u041B\u0438\u043C\u0438\u0442: \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0435 \u0434\u043E\u0441\u0442\u0443\u043F\u0435\u043D",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.": "\u0411\u0435\u0441\u043F\u043B\u0430\u0442\u043D\u044B\u0439 \u0443\u0440\u043E\u0432\u0435\u043D\u044C Qwen OAuth \u043F\u0440\u0435\u043A\u0440\u0430\u0449\u0451\u043D 2026-04-15. \u0412\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435 /auth \u0434\u043B\u044F \u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F \u043D\u0430 Coding Plan, OpenRouter, Fireworks AI \u0438\u043B\u0438 \u0434\u0440\u0443\u0433\u043E\u0433\u043E \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430.",
      "  Models: Qwen latest models\n": "  \u041C\u043E\u0434\u0435\u043B\u0438: \u041F\u043E\u0441\u043B\u0435\u0434\u043D\u0438\u0435 \u043C\u043E\u0434\u0435\u043B\u0438 Qwen\n",
      "\u2713 Authentication Method: Alibaba Cloud Coding Plan": "\u2713 \u041C\u0435\u0442\u043E\u0434 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438: Alibaba Cloud Coding Plan",
      "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC": "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC",
      "Global - Alibaba Cloud": "\u0413\u043B\u043E\u0431\u0430\u043B\u044C\u043D\u044B\u0439 - Alibaba Cloud",
      "  Region: {{region}}": "  \u0420\u0435\u0433\u0438\u043E\u043D: {{region}}",
      "  Current Model: {{model}}": "  \u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043C\u043E\u0434\u0435\u043B\u044C: {{model}}",
      "  Config Version: {{version}}": "  \u0412\u0435\u0440\u0441\u0438\u044F \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438: {{version}}",
      "  Status: API key configured\n": "  \u0421\u0442\u0430\u0442\u0443\u0441: API-\u043A\u043B\u044E\u0447 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\n",
      "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)": "\u26A0\uFE0F  \u041C\u0435\u0442\u043E\u0434 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438: Alibaba Cloud Coding Plan (\u041D\u0435 \u0437\u0430\u0432\u0435\u0440\u0448\u0451\u043D)",
      "  Issue: API key not found in environment or settings\n": "  \u041F\u0440\u043E\u0431\u043B\u0435\u043C\u0430: API-\u043A\u043B\u044E\u0447 \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D \u0432 \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u0438 \u0438\u043B\u0438 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430\u0445\n",
      "  Run `qwen auth coding-plan` to re-configure.\n": "  \u0412\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435 `qwen auth coding-plan` \u0434\u043B\u044F \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0439 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438.\n",
      "\u2713 Authentication Method: {{type}}": "\u2713 \u041C\u0435\u0442\u043E\u0434 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438: {{type}}",
      "  Status: Configured\n": "  \u0421\u0442\u0430\u0442\u0443\u0441: \u041D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u043E\n",
      "Failed to check authentication status: {{error}}": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C \u0441\u0442\u0430\u0442\u0443\u0441 \u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438: {{error}}",
      "Select an option:": "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0432\u0430\u0440\u0438\u0430\u043D\u0442:",
      "Raw mode not available. Please run in an interactive terminal.": "Raw-\u0440\u0435\u0436\u0438\u043C \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u043D. \u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435 \u0432 \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u043E\u043C \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0435.",
      "(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n": "(\u2191 \u2193 \u0441\u0442\u0440\u0435\u043B\u043A\u0438 \u0434\u043B\u044F \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u0438, Enter \u0434\u043B\u044F \u0432\u044B\u0431\u043E\u0440\u0430, Ctrl+C \u0434\u043B\u044F \u0432\u044B\u0445\u043E\u0434\u0430)\n",
      compact: "\u043A\u043E\u043C\u043F\u0430\u043A\u0442\u043D\u044B\u0439",
      "compact mode: on (Ctrl+O off)": "\u043A\u043E\u043C\u043F\u0430\u043A\u0442\u043D\u044B\u0439 \u0440\u0435\u0436\u0438\u043C: \u0432\u043A\u043B (Ctrl+O \u0432\u044B\u043A\u043B)",
      "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).": "\u0421\u043A\u0440\u044B\u0432\u0430\u0442\u044C \u0432\u044B\u0432\u043E\u0434 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u0438 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 \u0440\u0430\u0441\u0441\u0443\u0436\u0434\u0435\u043D\u0438\u0439 \u0434\u043B\u044F \u0431\u043E\u043B\u0435\u0435 \u0447\u0438\u0441\u0442\u043E\u0433\u043E \u0432\u0438\u0434\u0430 (\u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E Ctrl+O).",
      "Press Ctrl+O to show full tool output": "\u041D\u0430\u0436\u043C\u0438\u0442\u0435 Ctrl+O \u0434\u043B\u044F \u043F\u043E\u043A\u0430\u0437\u0430 \u043F\u043E\u043B\u043D\u043E\u0433\u043E \u0432\u044B\u0432\u043E\u0434\u0430 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
      "Switch to plan mode or exit plan mode": "Switch to plan mode or exit plan mode",
      "Exited plan mode. Previous approval mode restored.": "Exited plan mode. Previous approval mode restored.",
      "Enabled plan mode. The agent will analyze and plan without executing tools.": "Enabled plan mode. The agent will analyze and plan without executing tools.",
      'Already in plan mode. Use "/plan exit" to exit plan mode.': 'Already in plan mode. Use "/plan exit" to exit plan mode.',
      'Not in plan mode. Use "/plan" to enter plan mode first.': 'Not in plan mode. Use "/plan" to enter plan mode first.',
      "Set up Qwen Code's status line UI": "Set up Qwen Code's status line UI"
    };
  }
});

// packages/cli/src/i18n/locales/zh-TW.js
var zh_TW_exports = {};
__export(zh_TW_exports, {
  default: () => zh_TW_default2
});
var zh_TW_default2;
var init_zh_TW2 = __esm({
  "packages/cli/src/i18n/locales/zh-TW.js"() {
    "use strict";
    init_esbuild_shims();
    zh_TW_default2 = {
      "\u2191 to manage attachments": "\u2191 \u7BA1\u7406\u9644\u4EF6",
      "\u2190 \u2192 select, Delete to remove, \u2193 to exit": "\u2190 \u2192 \u9078\u64C7\uFF0CDelete \u522A\u9664\uFF0C\u2193 \u9000\u51FA",
      "Attachments: ": "\u9644\u4EF6\uFF1A",
      "Basics:": "\u57FA\u790E\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\u7232\u4E0A\u4E0B\u6587\uFF08\u4F8B\u5982\uFF0C{{example}}\uFF09\uFF0C\u7528\u65BC\u5B9A\u4F4D\u7279\u5B9A\u6587\u4EF6\u6216\u6587\u4EF6\u593E",
      "@": "@",
      "@src/myFile.ts": "@src/myFile.ts",
      "Shell mode": "Shell \u6A21\u5F0F",
      "YOLO mode": "YOLO \u6A21\u5F0F",
      "plan mode": "\u898F\u5283\u6A21\u5F0F",
      "auto-accept edits": "\u81EA\u52D5\u63A5\u53D7\u7DE8\u8F2F",
      "Accepting edits": "\u63A5\u53D7\u7DE8\u8F2F",
      "(shift + tab to cycle)": "(shift + tab \u5207\u63DB)",
      "(tab to cycle)": "(\u6309 tab \u5207\u63DB)",
      "Execute shell commands via {{symbol}} (e.g., {{example1}}) or use natural language (e.g., {{example2}}).": "\u901A\u904E {{symbol}} \u57F7\u884C shell \u547D\u4EE4\uFF08\u4F8B\u5982\uFF0C{{example1}}\uFF09\u6216\u4F7F\u7528\u81EA\u7136\u8A9E\u8A00\uFF08\u4F8B\u5982\uFF0C{{example2}}\uFF09",
      "!": "!",
      "!npm run start": "!npm run start",
      "start server": "start server",
      "Commands:": "\u547D\u4EE4\uFF1A",
      "shell command": "shell \u547D\u4EE4",
      "Model Context Protocol command (from external servers)": "\u6A21\u578B\u4E0A\u4E0B\u6587\u5354\u8B70\u547D\u4EE4\uFF08\u4F86\u81EA\u5916\u90E8\u670D\u52D9\u5668\uFF09",
      "Keyboard Shortcuts:": "\u9375\u76E4\u5FEB\u6377\u9375\uFF1A",
      "Toggle this help display": "\u5207\u63DB\u6B64\u5E6B\u52A9\u986F\u793A",
      "Toggle shell mode": "\u5207\u63DB\u547D\u4EE4\u884C\u6A21\u5F0F",
      "Open command menu": "\u6253\u958B\u547D\u4EE4\u83DC\u55AE",
      "Add file context": "\u6DFB\u52A0\u6587\u4EF6\u4E0A\u4E0B\u6587",
      "Accept suggestion / Autocomplete": "\u63A5\u53D7\u5EFA\u8B70 / \u81EA\u52D5\u88DC\u5168",
      "Reverse search history": "\u53CD\u5411\u641C\u7D22\u6B77\u53F2",
      "Press ? again to close": "\u518D\u6B21\u6309 ? \u95DC\u9589",
      "for shell mode": "\u547D\u4EE4\u884C\u6A21\u5F0F",
      "for commands": "\u547D\u4EE4\u83DC\u55AE",
      "for file paths": "\u6587\u4EF6\u8DEF\u5F91",
      "to clear input": "\u6E05\u7A7A\u8F38\u5165",
      "to cycle approvals": "\u5207\u63DB\u5BE9\u6279\u6A21\u5F0F",
      "to quit": "\u9000\u51FA",
      "for newline": "\u63DB\u884C",
      "to clear screen": "\u6E05\u5C4F",
      "to search history": "\u641C\u7D22\u6B77\u53F2",
      "to paste images": "\u7C98\u8CBC\u5716\u7247",
      "for external editor": "\u5916\u90E8\u7DE8\u8F2F\u5668",
      "to toggle compact mode": "\u5207\u63DB\u7DCA\u6E4A\u6A21\u5F0F",
      "Jump through words in the input": "\u5728\u8F38\u5165\u4E2D\u6309\u55AE\u8A5E\u8DF3\u8F49",
      "Close dialogs, cancel requests, or quit application": "\u95DC\u9589\u5C0D\u8A71\u6846\u3001\u53D6\u6D88\u8ACB\u6C42\u6216\u9000\u51FA\u61C9\u7528\u7A0B\u5E8F",
      "New line": "\u63DB\u884C",
      "New line (Alt+Enter works for certain linux distros)": "\u63DB\u884C\uFF08\u67D0\u4E9B Linux \u767C\u884C\u7248\u652F\u6301 Alt+Enter\uFF09",
      "Clear the screen": "\u6E05\u5C4F",
      "Open input in external editor": "\u5728\u5916\u90E8\u7DE8\u8F2F\u5668\u4E2D\u6253\u958B\u8F38\u5165",
      "Send message": "\u767C\u9001\u6D88\u606F",
      "Initializing...": "\u6B63\u5728\u521D\u59CB\u5316...",
      "Connecting to MCP servers... ({{connected}}/{{total}})": "\u6B63\u5728\u9023\u63A5\u5230 MCP \u670D\u52D9\u5668... ({{connected}}/{{total}})",
      "Type your message or @path/to/file": "\u8F38\u5165\u60A8\u7684\u6D88\u606F\u6216 @ \u6587\u4EF6\u8DEF\u5F91",
      "? for shortcuts": "\u6309 ? \u67E5\u770B\u5FEB\u6377\u9375",
      "Press 'i' for INSERT mode and 'Esc' for NORMAL mode.": "\u6309 'i' \u9032\u5165\u63D2\u5165\u6A21\u5F0F\uFF0C\u6309 'Esc' \u9032\u5165\u666E\u901A\u6A21\u5F0F",
      "Cancel operation / Clear input (double press)": "\u53D6\u6D88\u64CD\u4F5C / \u6E05\u7A7A\u8F38\u5165\uFF08\u96D9\u64CA\uFF09",
      "Cycle approval modes": "\u5FAA\u74B0\u5207\u63DB\u5BE9\u6279\u6A21\u5F0F",
      "Cycle through your prompt history": "\u5FAA\u74B0\u700F\u89BD\u63D0\u793A\u6B77\u53F2",
      "For a full list of shortcuts, see {{docPath}}": "\u5B8C\u6574\u5FEB\u6377\u9375\u5217\u8868\uFF0C\u8ACB\u53C3\u95B1 {{docPath}}",
      "docs/keyboard-shortcuts.md": "docs/keyboard-shortcuts.md",
      "for help on Qwen Code": "\u7372\u53D6 Qwen Code \u5E6B\u52A9",
      "show version info": "\u986F\u793A\u7248\u672C\u4FE1\u606F",
      "submit a bug report": "\u63D0\u4EA4\u932F\u8AA4\u5831\u544A",
      "About Qwen Code": "\u95DC\u65BC Qwen Code",
      Status: "\u72C0\u614B",
      "Qwen Code": "Qwen Code",
      Runtime: "\u904B\u884C\u74B0\u5883",
      OS: "\u64CD\u4F5C\u7CFB\u7D71",
      Auth: "\u8A8D\u8B49",
      "CLI Version": "CLI \u7248\u672C",
      "Git Commit": "Git \u63D0\u4EA4",
      Model: "\u6A21\u578B",
      "Fast Model": "\u5FEB\u901F\u6A21\u578B",
      Sandbox: "\u6C99\u7BB1",
      "OS Platform": "\u64CD\u4F5C\u7CFB\u7D71\u5E73\u81FA",
      "OS Arch": "\u64CD\u4F5C\u7CFB\u7D71\u67B6\u69CB",
      "OS Release": "\u64CD\u4F5C\u7CFB\u7D71\u7248\u672C",
      "Node.js Version": "Node.js \u7248\u672C",
      "NPM Version": "NPM \u7248\u672C",
      "Session ID": "\u6703\u8A71 ID",
      "Auth Method": "\u8A8D\u8B49\u65B9\u5F0F",
      "Base URL": "\u57FA\u790E URL",
      Proxy: "\u4EE3\u7406",
      "Memory Usage": "\u5167\u5B58\u4F7F\u7528",
      "IDE Client": "IDE \u5BA2\u6236\u7AEF",
      "Analyzes the project and creates a tailored QWEN.md file.": "\u5206\u6790\u9805\u76EE\u4E26\u5275\u5EFA\u5B9A\u88FD\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]",
      "List available skills.": "\u5217\u51FA\u53EF\u7528\u6280\u80FD\u3002",
      "Available Qwen Code CLI tools:": "\u53EF\u7528\u7684 Qwen Code CLI \u5DE5\u5177\uFF1A",
      "No tools available": "\u6C92\u6709\u53EF\u7528\u5DE5\u5177",
      "View or change the approval mode for tool usage": "\u67E5\u770B\u6216\u66F4\u6539\u5DE5\u5177\u4F7F\u7528\u7684\u5BE9\u6279\u6A21\u5F0F",
      'Invalid approval mode "{{arg}}". Valid modes: {{modes}}': '\u7121\u6548\u7684\u5BE9\u6279\u6A21\u5F0F "{{arg}}"\u3002\u6709\u6548\u6A21\u5F0F\uFF1A{{modes}}',
      'Approval mode set to "{{mode}}"': '\u5BE9\u6279\u6A21\u5F0F\u5DF2\u8A2D\u7F6E\u7232 "{{mode}}"',
      "View or change the language setting": "\u67E5\u770B\u6216\u66F4\u6539\u8A9E\u8A00\u8A2D\u7F6E",
      "change the theme": "\u66F4\u6539\u4E3B\u984C",
      "Select Theme": "\u9078\u64C7\u4E3B\u984C",
      Preview: "\u9810\u89BD",
      "(Use Enter to select, Tab to configure scope)": "\uFF08\u4F7F\u7528 Enter \u9078\u64C7\uFF0CTab \u914D\u7F6E\u4F5C\u7528\u57DF\uFF09",
      "(Use Enter to apply scope, Tab to go back)": "\uFF08\u4F7F\u7528 Enter \u61C9\u7528\u4F5C\u7528\u57DF\uFF0CTab \u8FD4\u56DE\uFF09",
      "Theme configuration unavailable due to NO_COLOR env variable.": "\u7531\u65BC NO_COLOR \u74B0\u5883\u8B8A\u91CF\uFF0C\u4E3B\u984C\u914D\u7F6E\u4E0D\u53EF\u7528\u3002",
      'Theme "{{themeName}}" not found.': '\u672A\u627E\u5230\u4E3B\u984C "{{themeName}}"\u3002',
      'Theme "{{themeName}}" not found in selected scope.': '\u5728\u6240\u9078\u4F5C\u7528\u57DF\u4E2D\u672A\u627E\u5230\u4E3B\u984C "{{themeName}}"\u3002',
      "Clear conversation history and free up context": "\u6E05\u9664\u5C0D\u8A71\u6B77\u53F2\u4E26\u91CB\u653E\u4E0A\u4E0B\u6587",
      "Compresses the context by replacing it with a summary.": "\u901A\u904E\u6458\u8981\u66FF\u63DB\u4F86\u58D3\u7E2E\u4E0A\u4E0B\u6587",
      "open full Qwen Code documentation in your browser": "\u5728\u700F\u89BD\u5668\u4E2D\u6253\u958B\u5B8C\u6574\u7684 Qwen Code \u6587\u6A94",
      "Configuration not available.": "\u914D\u7F6E\u4E0D\u53EF\u7528",
      "change the auth method": "\u66F4\u6539\u8A8D\u8B49\u65B9\u6CD5",
      "Configure authentication information for login": "\u914D\u7F6E\u767B\u9304\u8A8D\u8B49\u4FE1\u606F",
      "Copy the last result or code snippet to clipboard": "\u5C07\u6700\u5F8C\u7684\u7D50\u679C\u6216\u4EE3\u78BC\u7247\u6BB5\u8907\u88FD\u5230\u526A\u8CBC\u677F",
      "Manage subagents for specialized task delegation.": "\u7BA1\u7406\u7528\u65BC\u5C08\u9580\u4EFB\u52D9\u59D4\u6D3E\u7684\u5B50\u667A\u80FD\u9AD4",
      "Manage existing subagents (view, edit, delete).": "\u7BA1\u7406\u73FE\u6709\u5B50\u667A\u80FD\u9AD4\uFF08\u67E5\u770B\u3001\u7DE8\u8F2F\u3001\u522A\u9664\uFF09",
      "Create a new subagent with guided setup.": "\u901A\u904E\u5F15\u5C0E\u5F0F\u8A2D\u7F6E\u5275\u5EFA\u65B0\u7684\u5B50\u667A\u80FD\u9AD4",
      Agents: "\u667A\u80FD\u9AD4",
      "Choose Action": "\u9078\u64C7\u64CD\u4F5C",
      "Edit {{name}}": "\u7DE8\u8F2F {{name}}",
      "Edit Tools: {{name}}": "\u7DE8\u8F2F\u5DE5\u5177: {{name}}",
      "Edit Color: {{name}}": "\u7DE8\u8F2F\u984F\u8272: {{name}}",
      "Delete {{name}}": "\u522A\u9664 {{name}}",
      "Unknown Step": "\u672A\u77E5\u6B65\u9A5F",
      "Esc to close": "\u6309 Esc \u95DC\u9589",
      "Enter to select, \u2191\u2193 to navigate, Esc to close": "Enter \u9078\u64C7\uFF0C\u2191\u2193 \u5C0E\u822A\uFF0CEsc \u95DC\u9589",
      "Esc to go back": "\u6309 Esc \u8FD4\u56DE",
      "Enter to confirm, Esc to cancel": "Enter \u78BA\u8A8D\uFF0CEsc \u53D6\u6D88",
      "Enter to select, \u2191\u2193 to navigate, Esc to go back": "Enter \u9078\u64C7\uFF0C\u2191\u2193 \u5C0E\u822A\uFF0CEsc \u8FD4\u56DE",
      "Enter to submit, Esc to go back": "Enter \u63D0\u4EA4\uFF0CEsc \u8FD4\u56DE",
      "Invalid step: {{step}}": "\u7121\u6548\u6B65\u9A5F: {{step}}",
      "No subagents found.": "\u672A\u627E\u5230\u5B50\u667A\u80FD\u9AD4\u3002",
      "Use '/agents create' to create your first subagent.": "\u4F7F\u7528 '/agents create' \u5275\u5EFA\u60A8\u7684\u7B2C\u4E00\u500B\u5B50\u667A\u80FD\u9AD4\u3002",
      "(built-in)": "\uFF08\u5167\u7F6E\uFF09",
      "(overridden by project level agent)": "\uFF08\u5DF2\u88AB\u9805\u76EE\u7D1A\u667A\u80FD\u9AD4\u8986\u84CB\uFF09",
      "Project Level ({{path}})": "\u9805\u76EE\u7D1A ({{path}})",
      "User Level ({{path}})": "\u7528\u6236\u7D1A ({{path}})",
      "Built-in Agents": "\u5167\u7F6E\u667A\u80FD\u9AD4",
      "Extension Agents": "\u64F4\u5C55\u667A\u80FD\u9AD4",
      "Using: {{count}} agents": "\u4F7F\u7528\u4E2D: {{count}} \u500B\u667A\u80FD\u9AD4",
      "View Agent": "\u67E5\u770B\u667A\u80FD\u9AD4",
      "Edit Agent": "\u7DE8\u8F2F\u667A\u80FD\u9AD4",
      "Delete Agent": "\u522A\u9664\u667A\u80FD\u9AD4",
      Back: "\u8FD4\u56DE",
      "No agent selected": "\u672A\u9078\u64C7\u667A\u80FD\u9AD4",
      "File Path: ": "\u6587\u4EF6\u8DEF\u5F91: ",
      "Tools: ": "\u5DE5\u5177: ",
      "Color: ": "\u984F\u8272: ",
      "Description:": "\u63CF\u8FF0:",
      "System Prompt:": "\u7CFB\u7D71\u63D0\u793A:",
      "Open in editor": "\u5728\u7DE8\u8F2F\u5668\u4E2D\u6253\u958B",
      "Edit tools": "\u7DE8\u8F2F\u5DE5\u5177",
      "Edit color": "\u7DE8\u8F2F\u984F\u8272",
      "\u274C Error:": "\u274C \u932F\u8AA4:",
      'Are you sure you want to delete agent "{{name}}"?': '\u60A8\u78BA\u5B9A\u8981\u522A\u9664\u667A\u80FD\u9AD4 "{{name}}" \u55CE\uFF1F',
      "Project Level (.qwen/agents/)": "\u9805\u76EE\u7D1A (.qwen/agents/)",
      "User Level (~/.qwen/agents/)": "\u7528\u6236\u7D1A (~/.qwen/agents/)",
      "\u2705 Subagent Created Successfully!": "\u2705 \u5B50\u667A\u80FD\u9AD4\u5275\u5EFA\u6210\u529F\uFF01",
      'Subagent "{{name}}" has been saved to {{level}} level.': '\u5B50\u667A\u80FD\u9AD4 "{{name}}" \u5DF2\u4FDD\u5B58\u5230 {{level}} \u7D1A\u5225\u3002',
      "Name: ": "\u540D\u7A31: ",
      "Location: ": "\u4F4D\u7F6E: ",
      "\u274C Error saving subagent:": "\u274C \u4FDD\u5B58\u5B50\u667A\u80FD\u9AD4\u6642\u51FA\u932F:",
      "Warnings:": "\u8B66\u544A:",
      'Name "{{name}}" already exists at {{level}} level - will overwrite existing subagent': '\u540D\u7A31 "{{name}}" \u5728 {{level}} \u7D1A\u5225\u5DF2\u5B58\u5728 - \u5C07\u8986\u84CB\u73FE\u6709\u5B50\u667A\u80FD\u9AD4',
      'Name "{{name}}" exists at user level - project level will take precedence': '\u540D\u7A31 "{{name}}" \u5728\u7528\u6236\u7D1A\u5225\u5B58\u5728 - \u9805\u76EE\u7D1A\u5225\u5C07\u512A\u5148',
      'Name "{{name}}" exists at project level - existing subagent will take precedence': '\u540D\u7A31 "{{name}}" \u5728\u9805\u76EE\u7D1A\u5225\u5B58\u5728 - \u73FE\u6709\u5B50\u667A\u80FD\u9AD4\u5C07\u512A\u5148',
      "Description is over {{length}} characters": "\u63CF\u8FF0\u8D85\u904E {{length}} \u500B\u5B57\u7B26",
      "System prompt is over {{length}} characters": "\u7CFB\u7D71\u63D0\u793A\u8D85\u904E {{length}} \u500B\u5B57\u7B26",
      "Step {{n}}: Choose Location": "\u6B65\u9A5F {{n}}: \u9078\u64C7\u4F4D\u7F6E",
      "Step {{n}}: Choose Generation Method": "\u6B65\u9A5F {{n}}: \u9078\u64C7\u751F\u6210\u65B9\u5F0F",
      "Generate with Qwen Code (Recommended)": "\u4F7F\u7528 Qwen Code \u751F\u6210\uFF08\u63A8\u85A6\uFF09",
      "Manual Creation": "\u624B\u52D5\u5275\u5EFA",
      "Describe what this subagent should do and when it should be used. (Be comprehensive for best results)": "\u63CF\u8FF0\u6B64\u5B50\u667A\u80FD\u9AD4\u61C9\u8A72\u505A\u4EC0\u9EBC\u4EE5\u53CA\u4F55\u6642\u4F7F\u7528\u5B83\u3002\uFF08\u7232\u4E86\u7372\u5F97\u6700\u4F73\u6548\u679C\uFF0C\u8ACB\u5168\u9762\u63CF\u8FF0\uFF09",
      "e.g., Expert code reviewer that reviews code based on best practices...": "\u4F8B\u5982\uFF1A\u5C08\u696D\u7684\u4EE3\u78BC\u5BE9\u67E5\u54E1\uFF0C\u6839\u64DA\u6700\u4F73\u5BE6\u8E10\u5BE9\u67E5\u4EE3\u78BC...",
      "Generating subagent configuration...": "\u6B63\u5728\u751F\u6210\u5B50\u667A\u80FD\u9AD4\u914D\u7F6E...",
      "Failed to generate subagent: {{error}}": "\u751F\u6210\u5B50\u667A\u80FD\u9AD4\u5931\u6557: {{error}}",
      "Step {{n}}: Describe Your Subagent": "\u6B65\u9A5F {{n}}: \u63CF\u8FF0\u60A8\u7684\u5B50\u667A\u80FD\u9AD4",
      "Step {{n}}: Enter Subagent Name": "\u6B65\u9A5F {{n}}: \u8F38\u5165\u5B50\u667A\u80FD\u9AD4\u540D\u7A31",
      "Step {{n}}: Enter System Prompt": "\u6B65\u9A5F {{n}}: \u8F38\u5165\u7CFB\u7D71\u63D0\u793A",
      "Step {{n}}: Enter Description": "\u6B65\u9A5F {{n}}: \u8F38\u5165\u63CF\u8FF0",
      "Step {{n}}: Select Tools": "\u6B65\u9A5F {{n}}: \u9078\u64C7\u5DE5\u5177",
      "All Tools (Default)": "\u6240\u6709\u5DE5\u5177\uFF08\u9ED8\u8A8D\uFF09",
      "All Tools": "\u6240\u6709\u5DE5\u5177",
      "Read-only Tools": "\u53EA\u8B80\u5DE5\u5177",
      "Read & Edit Tools": "\u8B80\u53D6\u548C\u7DE8\u8F2F\u5DE5\u5177",
      "Read & Edit & Execution Tools": "\u8B80\u53D6\u3001\u7DE8\u8F2F\u548C\u57F7\u884C\u5DE5\u5177",
      "All tools selected, including MCP tools": "\u5DF2\u9078\u64C7\u6240\u6709\u5DE5\u5177\uFF0C\u5305\u62EC MCP \u5DE5\u5177",
      "Selected tools:": "\u5DF2\u9078\u64C7\u7684\u5DE5\u5177:",
      "Read-only tools:": "\u53EA\u8B80\u5DE5\u5177:",
      "Edit tools:": "\u7DE8\u8F2F\u5DE5\u5177:",
      "Execution tools:": "\u57F7\u884C\u5DE5\u5177:",
      "Step {{n}}: Choose Background Color": "\u6B65\u9A5F {{n}}: \u9078\u64C7\u80CC\u666F\u984F\u8272",
      "Step {{n}}: Confirm and Save": "\u6B65\u9A5F {{n}}: \u78BA\u8A8D\u4E26\u4FDD\u5B58",
      "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\u4E26\u7DE8\u8F2F\uFF0CEsc \u8FD4\u56DE",
      "Press Enter to continue, {{navigation}}Esc to {{action}}": "\u6309 Enter \u7E7C\u7E8C\uFF0C{{navigation}}Esc {{action}}",
      cancel: "\u53D6\u6D88",
      "go back": "\u8FD4\u56DE",
      "\u2191\u2193 to navigate, ": "\u2191\u2193 \u5C0E\u822A\uFF0C",
      "Enter a clear, unique name for this subagent.": "\u7232\u6B64\u5B50\u667A\u80FD\u9AD4\u8F38\u5165\u4E00\u500B\u6E05\u6670\u3001\u552F\u4E00\u7684\u540D\u7A31\u3002",
      "e.g., Code Reviewer": "\u4F8B\u5982\uFF1A\u4EE3\u78BC\u5BE9\u67E5\u54E1",
      "Name cannot be empty.": "\u540D\u7A31\u4E0D\u80FD\u7232\u7A7A\u3002",
      "Write the system prompt that defines this subagent's behavior. Be comprehensive for best results.": "\u7DE8\u5BEB\u5B9A\u7FA9\u6B64\u5B50\u667A\u80FD\u9AD4\u884C\u7232\u7684\u7CFB\u7D71\u63D0\u793A\u3002\u7232\u4E86\u7372\u5F97\u6700\u4F73\u6548\u679C\uFF0C\u8ACB\u5168\u9762\u63CF\u8FF0\u3002",
      "e.g., You are an expert code reviewer...": "\u4F8B\u5982\uFF1A\u60A8\u662F\u4E00\u4F4D\u5C08\u696D\u7684\u4EE3\u78BC\u5BE9\u67E5\u54E1...",
      "System prompt cannot be empty.": "\u7CFB\u7D71\u63D0\u793A\u4E0D\u80FD\u7232\u7A7A\u3002",
      "Describe when and how this subagent should be used.": "\u63CF\u8FF0\u4F55\u6642\u4EE5\u53CA\u5982\u4F55\u4F7F\u7528\u6B64\u5B50\u667A\u80FD\u9AD4\u3002",
      "e.g., Reviews code for best practices and potential bugs.": "\u4F8B\u5982\uFF1A\u5BE9\u67E5\u4EE3\u78BC\u4EE5\u67E5\u627E\u6700\u4F73\u5BE6\u8E10\u548C\u6F5B\u5728\u932F\u8AA4\u3002",
      "Description cannot be empty.": "\u63CF\u8FF0\u4E0D\u80FD\u7232\u7A7A\u3002",
      "Failed to launch editor: {{error}}": "\u5553\u52D5\u7DE8\u8F2F\u5668\u5931\u6557: {{error}}",
      "Failed to save and edit subagent: {{error}}": "\u4FDD\u5B58\u4E26\u7DE8\u8F2F\u5B50\u667A\u80FD\u9AD4\u5931\u6557: {{error}}",
      "Manage Extensions": "\u7BA1\u7406\u64F4\u5C55",
      "Extension Details": "\u64F4\u5C55\u8A73\u60C5",
      "View Extension": "\u67E5\u770B\u64F4\u5C55",
      "Update Extension": "\u66F4\u65B0\u64F4\u5C55",
      "Disable Extension": "\u7981\u7528\u64F4\u5C55",
      "Enable Extension": "\u5553\u7528\u64F4\u5C55",
      "Uninstall Extension": "\u5378\u8F09\u64F4\u5C55",
      "Select Scope": "\u9078\u64C7\u4F5C\u7528\u57DF",
      "User Scope": "\u7528\u6236\u4F5C\u7528\u57DF",
      "Workspace Scope": "\u5DE5\u4F5C\u5340\u4F5C\u7528\u57DF",
      "No extensions found.": "\u672A\u627E\u5230\u64F4\u5C55\u3002",
      Active: "\u5DF2\u5553\u7528",
      Disabled: "\u5DF2\u7981\u7528",
      "Update available": "\u6709\u53EF\u7528\u66F4\u65B0",
      "Up to date": "\u5DF2\u662F\u6700\u65B0",
      "Checking...": "\u6AA2\u67E5\u4E2D...",
      "Updating...": "\u66F4\u65B0\u4E2D...",
      Unknown: "\u672A\u77E5",
      Error: "\u932F\u8AA4",
      "Version:": "\u7248\u672C\uFF1A",
      "Status:": "\u72C0\u614B\uFF1A",
      'Are you sure you want to uninstall extension "{{name}}"?': '\u78BA\u5B9A\u8981\u5378\u8F09\u64F4\u5C55 "{{name}}" \u55CE\uFF1F',
      "This action cannot be undone.": "\u6B64\u64CD\u4F5C\u7121\u6CD5\u64A4\u92B7\u3002",
      'Extension "{{name}}" disabled successfully.': '\u64F4\u5C55 "{{name}}" \u7981\u7528\u6210\u529F\u3002',
      'Extension "{{name}}" enabled successfully.': '\u64F4\u5C55 "{{name}}" \u5553\u7528\u6210\u529F\u3002',
      'Extension "{{name}}" updated successfully.': '\u64F4\u5C55 "{{name}}" \u66F4\u65B0\u6210\u529F\u3002',
      'Failed to update extension "{{name}}": {{error}}': '\u66F4\u65B0\u64F4\u5C55 "{{name}}" \u5931\u6557\uFF1A{{error}}',
      "Select the scope for this action:": "\u9078\u64C7\u6B64\u64CD\u4F5C\u7684\u4F5C\u7528\u57DF\uFF1A",
      "User - Applies to all projects": "\u7528\u6236 - \u61C9\u7528\u65BC\u6240\u6709\u9805\u76EE",
      "Workspace - Applies to current project only": "\u5DE5\u4F5C\u5340 - \u50C5\u61C9\u7528\u65BC\u7576\u524D\u9805\u76EE",
      "Name:": "\u540D\u7A31\uFF1A",
      "MCP Servers:": "MCP \u670D\u52D9\u5668\uFF1A",
      "Settings:": "\u8A2D\u7F6E\uFF1A",
      active: "\u5DF2\u5553\u7528",
      disabled: "\u5DF2\u7981\u7528",
      "View Details": "\u67E5\u770B\u8A73\u60C5",
      "Update failed:": "\u66F4\u65B0\u5931\u6557\uFF1A",
      "Updating {{name}}...": "\u6B63\u5728\u66F4\u65B0 {{name}}...",
      "Update complete!": "\u66F4\u65B0\u5B8C\u6210\uFF01",
      "User (global)": "\u7528\u6236\uFF08\u5168\u5C40\uFF09",
      "Workspace (project-specific)": "\u5DE5\u4F5C\u5340\uFF08\u9805\u76EE\u7279\u5B9A\uFF09",
      'Disable "{{name}}" - Select Scope': '\u7981\u7528 "{{name}}" - \u9078\u64C7\u4F5C\u7528\u57DF',
      'Enable "{{name}}" - Select Scope': '\u5553\u7528 "{{name}}" - \u9078\u64C7\u4F5C\u7528\u57DF',
      "No extension selected": "\u672A\u9078\u64C7\u64F4\u5C55",
      "Press Y/Enter to confirm, N/Esc to cancel": "\u6309 Y/Enter \u78BA\u8A8D\uFF0CN/Esc \u53D6\u6D88",
      "Y/Enter to confirm, N/Esc to cancel": "Y/Enter \u78BA\u8A8D\uFF0CN/Esc \u53D6\u6D88",
      "{{count}} extensions installed": "\u5DF2\u5B89\u88DD {{count}} \u500B\u64F4\u5C55",
      "Use '/extensions install' to install your first extension.": "\u4F7F\u7528 '/extensions install' \u5B89\u88DD\u60A8\u7684\u7B2C\u4E00\u500B\u64F4\u5C55\u3002",
      "up to date": "\u5DF2\u662F\u6700\u65B0",
      "update available": "\u6709\u53EF\u7528\u66F4\u65B0",
      "checking...": "\u6AA2\u67E5\u4E2D...",
      "not updatable": "\u4E0D\u53EF\u66F4\u65B0",
      error: "\u932F\u8AA4",
      "View and edit Qwen Code settings": "\u67E5\u770B\u548C\u7DE8\u8F2F Qwen Code \u8A2D\u7F6E",
      Settings: "\u8A2D\u7F6E",
      "To see changes, Qwen Code must be restarted. Press r to exit and apply changes now.": "\u8981\u67E5\u770B\u66F4\u6539\uFF0C\u5FC5\u9808\u91CD\u5553 Qwen Code\u3002\u6309 r \u9000\u51FA\u4E26\u7ACB\u5373\u61C9\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',
      "Vim Mode": "Vim \u6A21\u5F0F",
      "Disable Auto Update": "\u7981\u7528\u81EA\u52D5\u66F4\u65B0",
      "Attribution: commit": "\u7F72\u540D\uFF1A\u63D0\u4EA4",
      "Terminal Bell Notification": "\u7D42\u7AEF\u97FF\u9234\u901A\u77E5",
      "Enable Usage Statistics": "\u5553\u7528\u4F7F\u7528\u7D71\u8A08",
      Theme: "\u4E3B\u984C",
      "Preferred Editor": "\u9996\u9078\u7DE8\u8F2F\u5668",
      "Auto-connect to IDE": "\u81EA\u52D5\u9023\u63A5\u5230 IDE",
      "Enable Prompt Completion": "\u5553\u7528\u63D0\u793A\u88DC\u5168",
      "Debug Keystroke Logging": "\u8ABF\u8A66\u6309\u9375\u8A18\u9304",
      "Language: UI": "\u8A9E\u8A00\uFF1A\u754C\u9762",
      "Language: Model": "\u8A9E\u8A00\uFF1A\u6A21\u578B",
      "Output Format": "\u8F38\u51FA\u683C\u5F0F",
      "Hide Window Title": "\u96B1\u85CF\u7A97\u53E3\u6A19\u984C",
      "Show Status in Title": "\u5728\u6A19\u984C\u4E2D\u986F\u793A\u72C0\u614B",
      "Hide Tips": "\u96B1\u85CF\u63D0\u793A",
      "Show Line Numbers in Code": "\u5728\u4EE3\u78BC\u4E2D\u986F\u793A\u884C\u865F",
      "Show Citations": "\u986F\u793A\u5F15\u7528",
      "Custom Witty Phrases": "\u81EA\u5B9A\u7FA9\u8A7C\u8AE7\u77ED\u8A9E",
      "Show Welcome Back Dialog": "\u986F\u793A\u6B61\u8FCE\u56DE\u4F86\u5C0D\u8A71\u6846",
      "Enable User Feedback": "\u5553\u7528\u7528\u6236\u53CD\u994B",
      "How is Qwen doing this session? (optional)": "Qwen \u9019\u6B21\u8868\u73FE\u5982\u4F55\uFF1F\uFF08\u53EF\u9078\uFF09",
      Bad: "\u4E0D\u6EFF\u610F",
      Fine: "\u9084\u884C",
      Good: "\u6EFF\u610F",
      Dismiss: "\u5FFD\u7565",
      "Not Sure Yet": "\u66AB\u4E0D\u8A55\u50F9",
      "Any other key": "\u4EFB\u610F\u5176\u4ED6\u9375",
      "Disable Loading Phrases": "\u7981\u7528\u52A0\u8F09\u77ED\u8A9E",
      "Screen Reader Mode": "\u5C4F\u5E55\u95B1\u8B80\u5668\u6A21\u5F0F",
      "IDE Mode": "IDE \u6A21\u5F0F",
      "Max Session Turns": "\u6700\u5927\u6703\u8A71\u8F2A\u6B21",
      "Skip Next Speaker Check": "\u8DF3\u904E\u4E0B\u4E00\u500B\u8AAA\u8A71\u8005\u6AA2\u67E5",
      "Skip Loop Detection": "\u8DF3\u904E\u5FAA\u74B0\u6AA2\u6E2C",
      "Skip Startup Context": "\u8DF3\u904E\u5553\u52D5\u4E0A\u4E0B\u6587",
      "Enable OpenAI Logging": "\u5553\u7528 OpenAI \u65E5\u8A8C",
      "OpenAI Logging Directory": "OpenAI \u65E5\u8A8C\u76EE\u9304",
      Timeout: "\u8D85\u6642",
      "Max Retries": "\u6700\u5927\u91CD\u8A66\u6B21\u6578",
      "Disable Cache Control": "\u7981\u7528\u7DE9\u5B58\u63A7\u5236",
      "Memory Discovery Max Dirs": "\u5167\u5B58\u767C\u73FE\u6700\u5927\u76EE\u9304\u6578",
      "Load Memory From Include Directories": "\u5F9E\u5305\u542B\u76EE\u9304\u52A0\u8F09\u5167\u5B58",
      "Respect .gitignore": "\u9075\u5B88 .gitignore",
      "Respect .qwenignore": "\u9075\u5B88 .qwenignore",
      "Enable Recursive File Search": "\u5553\u7528\u905E\u6B78\u6587\u4EF6\u641C\u7D22",
      "Disable Fuzzy Search": "\u7981\u7528\u6A21\u7CCA\u641C\u7D22",
      "Interactive Shell (PTY)": "\u4EA4\u4E92\u5F0F Shell (PTY)",
      "Show Color": "\u986F\u793A\u984F\u8272",
      "Auto Accept": "\u81EA\u52D5\u63A5\u53D7",
      "Use Ripgrep": "\u4F7F\u7528 Ripgrep",
      "Use Builtin Ripgrep": "\u4F7F\u7528\u5167\u7F6E Ripgrep",
      "Enable Tool Output Truncation": "\u5553\u7528\u5DE5\u5177\u8F38\u51FA\u622A\u65B7",
      "Tool Output Truncation Threshold": "\u5DE5\u5177\u8F38\u51FA\u622A\u65B7\u95BE\u503C",
      "Tool Output Truncation Lines": "\u5DE5\u5177\u8F38\u51FA\u622A\u65B7\u884C\u6578",
      "Folder Trust": "\u6587\u4EF6\u593E\u4FE1\u4EFB",
      "Vision Model Preview": "\u8996\u89BA\u6A21\u578B\u9810\u89BD",
      "Tool Schema Compliance": "\u5DE5\u5177 Schema \u517C\u5BB9\u6027",
      "Auto (detect from system)": "\u81EA\u52D5\uFF08\u5F9E\u7CFB\u7D71\u6AA2\u6E2C\uFF09",
      "Auto (detect terminal theme)": "\u81EA\u52D5\uFF08\u6AA2\u6E2C\u7D42\u7AEF\u4E3B\u984C\uFF09",
      Auto: "\u81EA\u52D5",
      Text: "\u6587\u672C",
      JSON: "JSON",
      Plan: "\u898F\u5283",
      Default: "\u9ED8\u8A8D",
      "Auto Edit": "\u81EA\u52D5\u7DE8\u8F2F",
      YOLO: "YOLO",
      "toggle vim mode on/off": "\u5207\u63DB vim \u6A21\u5F0F\u958B\u95DC",
      "check session stats. Usage: /stats [model|tools]": "\u6AA2\u67E5\u6703\u8A71\u7D71\u8A08\u4FE1\u606F\u3002\u7528\u6CD5\uFF1A/stats [model|tools]",
      "Show model-specific usage statistics.": "\u986F\u793A\u6A21\u578B\u76F8\u95DC\u7684\u4F7F\u7528\u7D71\u8A08\u4FE1\u606F",
      "Show tool-specific usage statistics.": "\u986F\u793A\u5DE5\u5177\u76F8\u95DC\u7684\u4F7F\u7528\u7D71\u8A08\u4FE1\u606F",
      "exit the cli": "\u9000\u51FA\u547D\u4EE4\u884C\u754C\u9762",
      "Open MCP management dialog, or authenticate with OAuth-enabled servers": "\u6253\u958B MCP \u7BA1\u7406\u5C0D\u8A71\u6846\uFF0C\u6216\u5728\u652F\u6301 OAuth \u7684\u670D\u52D9\u5668\u4E0A\u9032\u884C\u8EAB\u4EFD\u9A57\u8B49",
      "List configured MCP servers and tools, or authenticate with OAuth-enabled servers": "\u5217\u51FA\u5DF2\u914D\u7F6E\u7684 MCP \u670D\u52D9\u5668\u548C\u5DE5\u5177\uFF0C\u6216\u4F7F\u7528\u652F\u6301 OAuth \u7684\u670D\u52D9\u5668\u9032\u884C\u8EAB\u4EFD\u9A57\u8B49",
      "Manage workspace directories": "\u7BA1\u7406\u5DE5\u4F5C\u5340\u76EE\u9304",
      "Add directories to the workspace. Use comma to separate multiple paths": "\u5C07\u76EE\u9304\u6DFB\u52A0\u5230\u5DE5\u4F5C\u5340\u3002\u4F7F\u7528\u9017\u865F\u5206\u9694\u591A\u500B\u8DEF\u5F91",
      "Show all directories in the workspace": "\u986F\u793A\u5DE5\u4F5C\u5340\u4E2D\u7684\u6240\u6709\u76EE\u9304",
      "set external editor preference": "\u8A2D\u7F6E\u5916\u90E8\u7DE8\u8F2F\u5668\u9996\u9078\u9805",
      "Select Editor": "\u9078\u64C7\u7DE8\u8F2F\u5668",
      "Editor Preference": "\u7DE8\u8F2F\u5668\u9996\u9078\u9805",
      "These editors are currently supported. Please note that some editors cannot be used in sandbox mode.": "\u7576\u524D\u652F\u6301\u4EE5\u4E0B\u7DE8\u8F2F\u5668\u3002\u8ACB\u6CE8\u610F\uFF0C\u67D0\u4E9B\u7DE8\u8F2F\u5668\u7121\u6CD5\u5728\u6C99\u7BB1\u6A21\u5F0F\u4E0B\u4F7F\u7528\u3002",
      "Your preferred editor is:": "\u60A8\u7684\u9996\u9078\u7DE8\u8F2F\u5668\u662F\uFF1A",
      "Manage extensions": "\u7BA1\u7406\u64F4\u5C55",
      "Manage installed extensions": "\u7BA1\u7406\u5DF2\u5B89\u88DD\u7684\u64F4\u5C55",
      "List active extensions": "\u5217\u51FA\u6D3B\u52D5\u64F4\u5C55",
      "Update extensions. Usage: update <extension-names>|--all": "\u66F4\u65B0\u64F4\u5C55\u3002\u7528\u6CD5\uFF1Aupdate <extension-names>|--all",
      "Disable an extension": "\u7981\u7528\u64F4\u5C55",
      "Enable an extension": "\u5553\u7528\u64F4\u5C55",
      "Install an extension from a git repo or local path": "\u5F9E Git \u5009\u5EAB\u6216\u672C\u5730\u8DEF\u5F91\u5B89\u88DD\u64F4\u5C55",
      "Uninstall an extension": "\u5378\u8F09\u64F4\u5C55",
      "No extensions installed.": "\u672A\u5B89\u88DD\u64F4\u5C55\u3002",
      "Usage: /extensions update <extension-names>|--all": "\u7528\u6CD5\uFF1A/extensions update <\u64F4\u5C55\u540D>|--all",
      'Extension "{{name}}" not found.': '\u672A\u627E\u5230\u64F4\u5C55 "{{name}}"\u3002',
      "No extensions to update.": "\u6C92\u6709\u53EF\u66F4\u65B0\u7684\u64F4\u5C55\u3002",
      "Usage: /extensions install <source>": "\u7528\u6CD5\uFF1A/extensions install <\u4F86\u6E90>",
      'Installing extension from "{{source}}"...': '\u6B63\u5728\u5F9E "{{source}}" \u5B89\u88DD\u64F4\u5C55...',
      'Extension "{{name}}" installed successfully.': '\u64F4\u5C55 "{{name}}" \u5B89\u88DD\u6210\u529F\u3002',
      'Failed to install extension from "{{source}}": {{error}}': '\u5F9E "{{source}}" \u5B89\u88DD\u64F4\u5C55\u5931\u6557\uFF1A{{error}}',
      "Usage: /extensions uninstall <extension-name>": "\u7528\u6CD5\uFF1A/extensions uninstall <\u64F4\u5C55\u540D>",
      'Uninstalling extension "{{name}}"...': '\u6B63\u5728\u5378\u8F09\u64F4\u5C55 "{{name}}"...',
      'Extension "{{name}}" uninstalled successfully.': '\u64F4\u5C55 "{{name}}" \u5378\u8F09\u6210\u529F\u3002',
      'Failed to uninstall extension "{{name}}": {{error}}': '\u5378\u8F09\u64F4\u5C55 "{{name}}" \u5931\u6557\uFF1A{{error}}',
      "Usage: /extensions {{command}} <extension> [--scope=<user|workspace>]": "\u7528\u6CD5\uFF1A/extensions {{command}} <\u64F4\u5C55> [--scope=<user|workspace>]",
      'Unsupported scope "{{scope}}", should be one of "user" or "workspace"': '\u4E0D\u652F\u6301\u7684\u4F5C\u7528\u57DF "{{scope}}"\uFF0C\u61C9\u7232 "user" \u6216 "workspace"',
      'Extension "{{name}}" disabled for scope "{{scope}}"': '\u64F4\u5C55 "{{name}}" \u5DF2\u5728\u4F5C\u7528\u57DF "{{scope}}" \u4E2D\u7981\u7528',
      'Extension "{{name}}" enabled for scope "{{scope}}"': '\u64F4\u5C55 "{{name}}" \u5DF2\u5728\u4F5C\u7528\u57DF "{{scope}}" \u4E2D\u5553\u7528',
      "Do you want to continue? [Y/n]: ": "\u662F\u5426\u7E7C\u7E8C\uFF1F[Y/n]\uFF1A",
      "Do you want to continue?": "\u662F\u5426\u7E7C\u7E8C\uFF1F",
      'Installing extension "{{name}}".': '\u6B63\u5728\u5B89\u88DD\u64F4\u5C55 "{{name}}"\u3002',
      "**Extensions may introduce unexpected behavior. Ensure you have investigated the extension source and trust the author.**": "**\u64F4\u5C55\u53EF\u80FD\u6703\u5F15\u5165\u610F\u5916\u884C\u7232\u3002\u8ACB\u78BA\u4FDD\u60A8\u5DF2\u8ABF\u67E5\u904E\u64F4\u5C55\u6E90\u4E26\u4FE1\u4EFB\u4F5C\u8005\u3002**",
      "This extension will run the following MCP servers:": "\u6B64\u64F4\u5C55\u5C07\u904B\u884C\u4EE5\u4E0B MCP \u670D\u52D9\u5668\uFF1A",
      local: "\u672C\u5730",
      remote: "\u9060\u7A0B",
      "This extension will add the following commands: {{commands}}.": "\u6B64\u64F4\u5C55\u5C07\u6DFB\u52A0\u4EE5\u4E0B\u547D\u4EE4\uFF1A{{commands}}\u3002",
      "This extension will append info to your QWEN.md context using {{fileName}}": "\u6B64\u64F4\u5C55\u5C07\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\u64F4\u5C55\u5C07\u6392\u9664\u4EE5\u4E0B\u6838\u5FC3\u5DE5\u5177\uFF1A{{tools}}",
      "This extension will install the following skills:": "\u6B64\u64F4\u5C55\u5C07\u5B89\u88DD\u4EE5\u4E0B\u6280\u80FD\uFF1A",
      "This extension will install the following subagents:": "\u6B64\u64F4\u5C55\u5C07\u5B89\u88DD\u4EE5\u4E0B\u5B50\u667A\u80FD\u9AD4\uFF1A",
      'Installation cancelled for "{{name}}".': '\u5DF2\u53D6\u6D88\u5B89\u88DD "{{name}}"\u3002',
      "You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.": "\u60A8\u6B63\u5728\u5B89\u88DD\u4F86\u81EA {{originSource}} \u7684\u64F4\u5C55\u3002\u67D0\u4E9B\u529F\u80FD\u53EF\u80FD\u7121\u6CD5\u5B8C\u7F8E\u517C\u5BB9 Qwen Code\u3002",
      "--ref and --auto-update are not applicable for marketplace extensions.": "--ref \u548C --auto-update \u4E0D\u9069\u7528\u65BC\u5E02\u5834\u64F4\u5C55\u3002",
      'Extension "{{name}}" installed successfully and enabled.': '\u64F4\u5C55 "{{name}}" \u5B89\u88DD\u6210\u529F\u4E26\u5DF2\u5553\u7528\u3002',
      "Installs an extension from a git repository URL, local path, or claude marketplace (marketplace-url:plugin-name).": "\u5F9E Git \u5009\u5EAB URL\u3001\u672C\u5730\u8DEF\u5F91\u6216 Claude \u5E02\u5834\uFF08marketplace-url:plugin-name\uFF09\u5B89\u88DD\u64F4\u5C55\u3002",
      "The github URL, local path, or marketplace source (marketplace-url:plugin-name) of the extension to install.": "\u8981\u5B89\u88DD\u7684\u64F4\u5C55\u7684 GitHub URL\u3001\u672C\u5730\u8DEF\u5F91\u6216\u5E02\u5834\u6E90\uFF08marketplace-url:plugin-name\uFF09\u3002",
      "The git ref to install from.": "\u8981\u5B89\u88DD\u7684 Git \u5F15\u7528\u3002",
      "Enable auto-update for this extension.": "\u7232\u6B64\u64F4\u5C55\u5553\u7528\u81EA\u52D5\u66F4\u65B0\u3002",
      "Enable pre-release versions for this extension.": "\u7232\u6B64\u64F4\u5C55\u5553\u7528\u9810\u767C\u4F48\u7248\u672C\u3002",
      "Acknowledge the security risks of installing an extension and skip the confirmation prompt.": "\u78BA\u8A8D\u5B89\u88DD\u64F4\u5C55\u7684\u5B89\u5168\u98A8\u96AA\u4E26\u8DF3\u904E\u78BA\u8A8D\u63D0\u793A\u3002",
      "The source argument must be provided.": "\u5FC5\u9808\u63D0\u4F9B\u4F86\u6E90\u53C3\u6578\u3002",
      'Extension "{{name}}" successfully uninstalled.': '\u64F4\u5C55 "{{name}}" \u5378\u8F09\u6210\u529F\u3002',
      "Uninstalls an extension.": "\u5378\u8F09\u64F4\u5C55\u3002",
      "The name or source path of the extension to uninstall.": "\u8981\u5378\u8F09\u7684\u64F4\u5C55\u7684\u540D\u7A31\u6216\u6E90\u8DEF\u5F91\u3002",
      "Please include the name of the extension to uninstall as a positional argument.": "\u8ACB\u5C07\u8981\u5378\u8F09\u7684\u64F4\u5C55\u540D\u7A31\u4F5C\u7232\u4F4D\u7F6E\u53C3\u6578\u3002",
      "Enables an extension.": "\u5553\u7528\u64F4\u5C55\u3002",
      "The name of the extension to enable.": "\u8981\u5553\u7528\u7684\u64F4\u5C55\u540D\u7A31\u3002",
      "The scope to enable the extenison in. If not set, will be enabled in all scopes.": "\u5553\u7528\u64F4\u5C55\u7684\u4F5C\u7528\u57DF\u3002\u5982\u679C\u672A\u8A2D\u7F6E\uFF0C\u5C07\u5728\u6240\u6709\u4F5C\u7528\u57DF\u4E2D\u5553\u7528\u3002",
      'Extension "{{name}}" successfully enabled for scope "{{scope}}".': '\u64F4\u5C55 "{{name}}" \u5DF2\u5728\u4F5C\u7528\u57DF "{{scope}}" \u4E2D\u5553\u7528\u3002',
      'Extension "{{name}}" successfully enabled in all scopes.': '\u64F4\u5C55 "{{name}}" \u5DF2\u5728\u6240\u6709\u4F5C\u7528\u57DF\u4E2D\u5553\u7528\u3002',
      "Invalid scope: {{scope}}. Please use one of {{scopes}}.": "\u7121\u6548\u7684\u4F5C\u7528\u57DF\uFF1A{{scope}}\u3002\u8ACB\u4F7F\u7528 {{scopes}} \u4E4B\u4E00\u3002",
      "Disables an extension.": "\u7981\u7528\u64F4\u5C55\u3002",
      "The name of the extension to disable.": "\u8981\u7981\u7528\u7684\u64F4\u5C55\u540D\u7A31\u3002",
      "The scope to disable the extenison in.": "\u7981\u7528\u64F4\u5C55\u7684\u4F5C\u7528\u57DF\u3002",
      'Extension "{{name}}" successfully disabled for scope "{{scope}}".': '\u64F4\u5C55 "{{name}}" \u5DF2\u5728\u4F5C\u7528\u57DF "{{scope}}" \u4E2D\u7981\u7528\u3002',
      'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.': '\u64F4\u5C55 "{{name}}" \u66F4\u65B0\u6210\u529F\uFF1A{{oldVersion}} \u2192 {{newVersion}}\u3002',
      'Unable to install extension "{{name}}" due to missing install metadata': '\u7531\u65BC\u7F3A\u5C11\u5B89\u88DD\u5143\u6578\u64DA\uFF0C\u7121\u6CD5\u5B89\u88DD\u64F4\u5C55 "{{name}}"',
      'Extension "{{name}}" is already up to date.': '\u64F4\u5C55 "{{name}}" \u5DF2\u662F\u6700\u65B0\u7248\u672C\u3002',
      "Updates all extensions or a named extension to the latest version.": "\u5C07\u6240\u6709\u64F4\u5C55\u6216\u6307\u5B9A\u64F4\u5C55\u66F4\u65B0\u5230\u6700\u65B0\u7248\u672C\u3002",
      "Update all extensions.": "\u66F4\u65B0\u6240\u6709\u64F4\u5C55\u3002",
      "The name of the extension to update.": "\u8981\u66F4\u65B0\u7684\u64F4\u5C55\u540D\u7A31\u3002",
      "Either an extension name or --all must be provided": "\u5FC5\u9808\u63D0\u4F9B\u64F4\u5C55\u540D\u7A31\u6216 --all",
      "Lists installed extensions.": "\u5217\u51FA\u5DF2\u5B89\u88DD\u7684\u64F4\u5C55\u3002",
      "Path:": "\u8DEF\u5F91\uFF1A",
      "Source:": "\u4F86\u6E90\uFF1A",
      "Type:": "\u985E\u578B\uFF1A",
      "Ref:": "\u5F15\u7528\uFF1A",
      "Release tag:": "\u767C\u4F48\u6A19\u7C64\uFF1A",
      "Enabled (User):": "\u5DF2\u5553\u7528\uFF08\u7528\u6236\uFF09\uFF1A",
      "Enabled (Workspace):": "\u5DF2\u5553\u7528\uFF08\u5DE5\u4F5C\u5340\uFF09\uFF1A",
      "Context files:": "\u4E0A\u4E0B\u6587\u6587\u4EF6\uFF1A",
      "Skills:": "\u6280\u80FD\uFF1A",
      "Agents:": "\u667A\u80FD\u9AD4\uFF1A",
      "MCP servers:": "MCP \u670D\u52D9\u5668\uFF1A",
      "Link extension failed to install.": "\u93C8\u63A5\u64F4\u5C55\u5B89\u88DD\u5931\u6557\u3002",
      'Extension "{{name}}" linked successfully and enabled.': '\u64F4\u5C55 "{{name}}" \u93C8\u63A5\u6210\u529F\u4E26\u5DF2\u5553\u7528\u3002',
      "Links an extension from a local path. Updates made to the local path will always be reflected.": "\u5F9E\u672C\u5730\u8DEF\u5F91\u93C8\u63A5\u64F4\u5C55\u3002\u5C0D\u672C\u5730\u8DEF\u5F91\u7684\u66F4\u65B0\u5C07\u59CB\u7D42\u53CD\u6620\u3002",
      "The name of the extension to link.": "\u8981\u93C8\u63A5\u7684\u64F4\u5C55\u540D\u7A31\u3002",
      "Set a specific setting for an extension.": "\u7232\u64F4\u5C55\u8A2D\u7F6E\u7279\u5B9A\u914D\u7F6E\u3002",
      "Name of the extension to configure.": "\u8981\u914D\u7F6E\u7684\u64F4\u5C55\u540D\u7A31\u3002",
      "The setting to configure (name or env var).": "\u8981\u914D\u7F6E\u7684\u8A2D\u7F6E\uFF08\u540D\u7A31\u6216\u74B0\u5883\u8B8A\u91CF\uFF09\u3002",
      "The scope to set the setting in.": "\u8A2D\u7F6E\u914D\u7F6E\u7684\u4F5C\u7528\u57DF\u3002",
      "List all settings for an extension.": "\u5217\u51FA\u64F4\u5C55\u7684\u6240\u6709\u8A2D\u7F6E\u3002",
      "Name of the extension.": "\u64F4\u5C55\u540D\u7A31\u3002",
      'Extension "{{name}}" has no settings to configure.': '\u64F4\u5C55 "{{name}}" \u6C92\u6709\u53EF\u914D\u7F6E\u7684\u8A2D\u7F6E\u3002',
      'Settings for "{{name}}":': '"{{name}}" \u7684\u8A2D\u7F6E\uFF1A',
      "(workspace)": "\uFF08\u5DE5\u4F5C\u5340\uFF09",
      "(user)": "\uFF08\u7528\u6236\uFF09",
      "[not set]": "\uFF3B\u672A\u8A2D\u7F6E\uFF3D",
      "[value stored in keychain]": "\uFF3B\u503C\u5B58\u5132\u5728\u9470\u5319\u4E32\u4E2D\uFF3D",
      "Value:": "\u503C\uFF1A",
      "Manage extension settings.": "\u7BA1\u7406\u64F4\u5C55\u8A2D\u7F6E\u3002",
      "You need to specify a command (set or list).": "\u60A8\u9700\u8981\u6307\u5B9A\u547D\u4EE4\uFF08set \u6216 list\uFF09\u3002",
      "No plugins available in this marketplace.": "\u6B64\u5E02\u5834\u4E2D\u6C92\u6709\u53EF\u7528\u7684\u63D2\u4EF6\u3002",
      'Select a plugin to install from marketplace "{{name}}":': '\u5F9E\u5E02\u5834 "{{name}}" \u4E2D\u9078\u64C7\u8981\u5B89\u88DD\u7684\u63D2\u4EF6\uFF1A',
      "Plugin selection cancelled.": "\u63D2\u4EF6\u9078\u64C7\u5DF2\u53D6\u6D88\u3002",
      'Select a plugin from "{{name}}"': '\u5F9E "{{name}}" \u4E2D\u9078\u64C7\u63D2\u4EF6',
      "Use \u2191\u2193 or j/k to navigate, Enter to select, Escape to cancel": "\u4F7F\u7528 \u2191\u2193 \u6216 j/k \u5C0E\u822A\uFF0C\u56DE\u8ECA\u9078\u64C7\uFF0CEsc \u53D6\u6D88",
      "{{count}} more above": "\u4E0A\u65B9\u9084\u6709 {{count}} \u9805",
      "{{count}} more below": "\u4E0B\u65B9\u9084\u6709 {{count}} \u9805",
      "manage IDE integration": "\u7BA1\u7406 IDE \u96C6\u6210",
      "check status of IDE integration": "\u6AA2\u67E5 IDE \u96C6\u6210\u72C0\u614B",
      "install required IDE companion for {{ideName}}": "\u5B89\u88DD {{ideName}} \u6240\u9700\u7684 IDE \u914D\u5957\u5DE5\u5177",
      "enable IDE integration": "\u5553\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\u7576\u524D\u74B0\u5883\u4E0D\u652F\u6301 IDE \u96C6\u6210\u3002\u8981\u4F7F\u7528\u6B64\u529F\u80FD\uFF0C\u8ACB\u5728\u4EE5\u4E0B\u652F\u6301\u7684 IDE \u4E4B\u4E00\u4E2D\u904B\u884C Qwen Code\uFF1AVS Code \u6216 VS Code \u5206\u652F\u7248\u672C\u3002",
      "Set up GitHub Actions": "\u8A2D\u7F6E GitHub Actions",
      "Configure terminal keybindings for multiline input (VS Code, Cursor, Windsurf, Trae)": "\u914D\u7F6E\u7D42\u7AEF\u6309\u9375\u7D81\u5B9A\u4EE5\u652F\u6301\u591A\u884C\u8F38\u5165\uFF08VS Code\u3001Cursor\u3001Windsurf\u3001Trae\uFF09",
      "Please restart your terminal for the changes to take effect.": "\u8ACB\u91CD\u5553\u7D42\u7AEF\u4EE5\u4F7F\u66F4\u6539\u751F\u6548\u3002",
      "Failed to configure terminal: {{error}}": "\u914D\u7F6E\u7D42\u7AEF\u5931\u6557\uFF1A{{error}}",
      "Could not determine {{terminalName}} config path on Windows: APPDATA environment variable is not set.": "\u7121\u6CD5\u78BA\u5B9A {{terminalName}} \u5728 Windows \u4E0A\u7684\u914D\u7F6E\u8DEF\u5F91\uFF1A\u672A\u8A2D\u7F6E APPDATA \u74B0\u5883\u8B8A\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 \u6578\u7D44\u3002\u8ACB\u624B\u52D5\u4FEE\u5FA9\u6587\u4EF6\u6216\u522A\u9664\u5B83\u4EE5\u5141\u8A31\u81EA\u52D5\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\u6557\u3002\u6587\u4EF6\u5305\u542B\u7121\u6548\u7684 JSON\u3002\u8ACB\u624B\u52D5\u4FEE\u5FA9\u6587\u4EF6\u6216\u522A\u9664\u5B83\u4EE5\u5141\u8A31\u81EA\u52D5\u914D\u7F6E\u3002",
      "Error: {{error}}": "\u932F\u8AA4\uFF1A{{error}}",
      "Shift+Enter binding already exists": "Shift+Enter \u7D81\u5B9A\u5DF2\u5B58\u5728",
      "Ctrl+Enter binding already exists": "Ctrl+Enter \u7D81\u5B9A\u5DF2\u5B58\u5728",
      "Existing keybindings detected. Will not modify to avoid conflicts.": "\u6AA2\u6E2C\u5230\u73FE\u6709\u6309\u9375\u7D81\u5B9A\u3002\u7232\u907F\u514D\u885D\u7A81\uFF0C\u4E0D\u6703\u4FEE\u6539\u3002",
      "Please check and modify manually if needed: {{file}}": "\u5982\u6709\u9700\u8981\uFF0C\u8ACB\u624B\u52D5\u6AA2\u67E5\u4E26\u4FEE\u6539\uFF1A{{file}}",
      "Added Shift+Enter and Ctrl+Enter keybindings to {{terminalName}}.": "\u5DF2\u7232 {{terminalName}} \u6DFB\u52A0 Shift+Enter \u548C Ctrl+Enter \u6309\u9375\u7D81\u5B9A\u3002",
      "Modified: {{file}}": "\u5DF2\u4FEE\u6539\uFF1A{{file}}",
      "{{terminalName}} keybindings already configured.": "{{terminalName}} \u6309\u9375\u7D81\u5B9A\u5DF2\u914D\u7F6E\u3002",
      "Failed to configure {{terminalName}}.": "\u914D\u7F6E {{terminalName}} \u5931\u6557\u3002",
      "Your terminal is already configured for an optimal experience with multiline input (Shift+Enter and Ctrl+Enter).": "\u60A8\u7684\u7D42\u7AEF\u5DF2\u914D\u7F6E\u7232\u652F\u6301\u591A\u884C\u8F38\u5165\uFF08Shift+Enter \u548C Ctrl+Enter\uFF09\u7684\u6700\u4F73\u9AD4\u9A57\u3002",
      "Manage Qwen Code hooks": "\u7BA1\u7406 Qwen Code Hook",
      "List all configured hooks": "\u5217\u51FA\u6240\u6709\u5DF2\u914D\u7F6E\u7684 Hook",
      "Enable a disabled hook": "\u5553\u7528\u5DF2\u7981\u7528\u7684 Hook",
      "Disable an active hook": "\u7981\u7528\u5DF2\u5553\u7528\u7684 Hook",
      Hooks: "Hook",
      "Loading hooks...": "\u6B63\u5728\u52A0\u8F09 Hook...",
      "Error loading hooks:": "\u52A0\u8F09 Hook \u51FA\u932F\uFF1A",
      "Press Escape to close": "\u6309 Escape \u95DC\u9589",
      "Press Escape, Ctrl+C, or Ctrl+D to cancel": "\u6309 Escape\u3001Ctrl+C \u6216 Ctrl+D \u53D6\u6D88",
      "Press Space, Enter, or Escape to dismiss": "\u6309\u7A7A\u683C\u3001\u56DE\u8ECA\u6216 Escape \u95DC\u9589",
      "No hook selected": "\u672A\u9078\u64C7 Hook",
      "No hook events found.": "\u672A\u627E\u5230 Hook \u4E8B\u4EF6\u3002",
      "{{count}} hook configured": "{{count}} \u500B Hook \u5DF2\u914D\u7F6E",
      "{{count}} hooks configured": "{{count}} \u500B Hook \u5DF2\u914D\u7F6E",
      "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.": "\u6B64\u83DC\u55AE\u7232\u53EA\u8B80\u3002\u8981\u6DFB\u52A0\u6216\u4FEE\u6539 Hook\uFF0C\u8ACB\u76F4\u63A5\u7DE8\u8F2F settings.json \u6216\u8A62\u554F Qwen Code\u3002",
      "Enter to select \xB7 Esc to cancel": "Enter \u9078\u64C7 \xB7 Esc \u53D6\u6D88",
      "Exit codes:": "\u9000\u51FA\u78BC\uFF1A",
      "Configured hooks:": "\u5DF2\u914D\u7F6E\u7684 Hook\uFF1A",
      "No hooks configured for this event.": "\u6B64\u4E8B\u4EF6\u672A\u914D\u7F6E Hook\u3002",
      "To add hooks, edit settings.json directly or ask Qwen.": "\u8981\u6DFB\u52A0 Hook\uFF0C\u8ACB\u76F4\u63A5\u7DE8\u8F2F settings.json \u6216\u8A62\u554F Qwen\u3002",
      "Enter to select \xB7 Esc to go back": "Enter \u9078\u64C7 \xB7 Esc \u8FD4\u56DE",
      "Hook details": "Hook \u8A73\u60C5",
      "Event:": "\u4E8B\u4EF6\uFF1A",
      "Extension:": "\u64F4\u5C55\uFF1A",
      "Desc:": "\u63CF\u8FF0\uFF1A",
      "No hook config selected": "\u672A\u9078\u64C7 Hook \u914D\u7F6E",
      "To modify or remove this hook, edit settings.json directly or ask Qwen to help.": "\u8981\u4FEE\u6539\u6216\u522A\u9664\u6B64 Hook\uFF0C\u8ACB\u76F4\u63A5\u7DE8\u8F2F settings.json \u6216\u8A62\u554F Qwen\u3002",
      "Hook Configuration - Disabled": "Hook \u914D\u7F6E - \u5DF2\u7981\u7528",
      "All hooks are currently disabled. You have {{count}} that are not running.": "\u6240\u6709 Hook \u7576\u524D\u5DF2\u7981\u7528\u3002\u60A8\u6709 {{count}} \u672A\u904B\u884C\u3002",
      "{{count}} configured hook": "{{count}} \u500B\u5DF2\u914D\u7F6E\u7684 Hook",
      "{{count}} configured hooks": "{{count}} \u500B\u5DF2\u914D\u7F6E\u7684 Hook",
      "When hooks are disabled:": "\u7576 Hook \u88AB\u7981\u7528\u6642\uFF1A",
      "No hook commands will execute": "\u4E0D\u6703\u57F7\u884C\u4EFB\u4F55 Hook \u547D\u4EE4",
      "StatusLine will not be displayed": "\u4E0D\u6703\u986F\u793A\u72C0\u614B\u6B04",
      "Tool operations will proceed without hook validation": "\u5DE5\u5177\u64CD\u4F5C\u5C07\u5728\u6C92\u6709 Hook \u9A57\u8B49\u7684\u60C5\u6CC1\u4E0B\u7E7C\u7E8C",
      'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.': '\u8981\u91CD\u65B0\u5553\u7528 Hook\uFF0C\u8ACB\u5F9E settings.json \u4E2D\u522A\u9664 "disableAllHooks" \u6216\u8A62\u554F Qwen Code\u3002',
      Project: "\u9805\u76EE",
      User: "\u7528\u6236",
      System: "\u7CFB\u7D71",
      Extension: "\u64F4\u5C55",
      "Local Settings": "\u672C\u5730\u8A2D\u7F6E",
      "User Settings": "\u7528\u6236\u8A2D\u7F6E",
      "System Settings": "\u7CFB\u7D71\u8A2D\u7F6E",
      Extensions: "\u64F4\u5C55",
      "Session (temporary)": "\u6703\u8A71\uFF08\u81E8\u6642\uFF09",
      "\u2713 Enabled": "\u2713 \u5DF2\u5553\u7528",
      "\u2717 Disabled": "\u2717 \u5DF2\u7981\u7528",
      "Before tool execution": "\u5DE5\u5177\u57F7\u884C\u524D",
      "After tool execution": "\u5DE5\u5177\u57F7\u884C\u5F8C",
      "After tool execution fails": "\u5DE5\u5177\u57F7\u884C\u5931\u6557\u5F8C",
      "When notifications are sent": "\u767C\u9001\u901A\u77E5\u6642",
      "When the user submits a prompt": "\u7528\u6236\u63D0\u4EA4\u63D0\u793A\u6642",
      "When a new session is started": "\u65B0\u6703\u8A71\u958B\u59CB\u6642",
      "Right before Qwen Code concludes its response": "Qwen Code \u7D50\u675F\u97FF\u61C9\u4E4B\u524D",
      "When a subagent (Agent tool call) is started": "\u5B50\u667A\u80FD\u9AD4\uFF08Agent \u5DE5\u5177\u8ABF\u7528\uFF09\u5553\u52D5\u6642",
      "Right before a subagent concludes its response": "\u5B50\u667A\u80FD\u9AD4\u7D50\u675F\u97FF\u61C9\u4E4B\u524D",
      "Before conversation compaction": "\u5C0D\u8A71\u58D3\u7E2E\u524D",
      "When a session is ending": "\u6703\u8A71\u7D50\u675F\u6642",
      "When a permission dialog is displayed": "\u986F\u793A\u6B0A\u9650\u5C0D\u8A71\u6846\u6642",
      "Input to command is JSON of tool call arguments.": "\u547D\u4EE4\u8F38\u5165\u7232\u5DE5\u5177\u8ABF\u7528\u53C3\u6578\u7684 JSON\u3002",
      'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': '\u547D\u4EE4\u8F38\u5165\u7232\u5305\u542B "inputs"\uFF08\u5DE5\u5177\u8ABF\u7528\u53C3\u6578\uFF09\u548C "response"\uFF08\u5DE5\u5177\u8ABF\u7528\u97FF\u61C9\uFF09\u5B57\u6BB5\u7684 JSON\u3002',
      "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.": "\u547D\u4EE4\u8F38\u5165\u7232\u5305\u542B tool_name\u3001tool_input\u3001tool_use_id\u3001error\u3001error_type\u3001is_interrupt \u548C is_timeout \u7684 JSON\u3002",
      "Input to command is JSON with notification message and type.": "\u547D\u4EE4\u8F38\u5165\u7232\u5305\u542B\u901A\u77E5\u6D88\u606F\u548C\u985E\u578B\u7684 JSON\u3002",
      "Input to command is JSON with original user prompt text.": "\u547D\u4EE4\u8F38\u5165\u7232\u5305\u542B\u539F\u59CB\u7528\u6236\u63D0\u793A\u6587\u672C\u7684 JSON\u3002",
      "Input to command is JSON with session start source.": "\u547D\u4EE4\u8F38\u5165\u7232\u5305\u542B\u6703\u8A71\u5553\u52D5\u4F86\u6E90\u7684 JSON\u3002",
      "Input to command is JSON with session end reason.": "\u547D\u4EE4\u8F38\u5165\u7232\u5305\u542B\u6703\u8A71\u7D50\u675F\u539F\u56E0\u7684 JSON\u3002",
      "Input to command is JSON with agent_id and agent_type.": "\u547D\u4EE4\u8F38\u5165\u7232\u5305\u542B agent_id \u548C agent_type \u7684 JSON\u3002",
      "Input to command is JSON with agent_id, agent_type, and agent_transcript_path.": "\u547D\u4EE4\u8F38\u5165\u7232\u5305\u542B agent_id\u3001agent_type \u548C agent_transcript_path \u7684 JSON\u3002",
      "Input to command is JSON with compaction details.": "\u547D\u4EE4\u8F38\u5165\u7232\u5305\u542B\u58D3\u7E2E\u8A73\u60C5\u7684 JSON\u3002",
      "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.": "\u547D\u4EE4\u8F38\u5165\u7232\u5305\u542B tool_name\u3001tool_input \u548C tool_use_id \u7684 JSON\u3002\u8F38\u51FA\u5305\u542B hookSpecificOutput \u7684 JSON\uFF0C\u5176\u4E2D\u5305\u542B\u5141\u8A31\u6216\u62D2\u7D55\u7684\u6C7A\u5B9A\u3002",
      "stdout/stderr not shown": "stdout/stderr \u4E0D\u986F\u793A",
      "show stderr to model and continue conversation": "\u5411\u6A21\u578B\u986F\u793A stderr \u4E26\u7E7C\u7E8C\u5C0D\u8A71",
      "show stderr to user only": "\u50C5\u5411\u7528\u6236\u986F\u793A stderr",
      "stdout shown in transcript mode (ctrl+o)": "stdout \u4EE5\u8F49\u9304\u6A21\u5F0F\u986F\u793A (ctrl+o)",
      "show stderr to model immediately": "\u7ACB\u5373\u5411\u6A21\u578B\u986F\u793A stderr",
      "show stderr to user only but continue with tool call": "\u50C5\u5411\u7528\u6236\u986F\u793A stderr \u4F46\u7E7C\u7E8C\u5DE5\u5177\u8ABF\u7528",
      "block processing, erase original prompt, and show stderr to user only": "\u963B\u6B62\u8655\u7406\uFF0C\u64E6\u9664\u539F\u59CB\u63D0\u793A\uFF0C\u50C5\u5411\u7528\u6236\u986F\u793A stderr",
      "stdout shown to Qwen": "\u5411 Qwen \u986F\u793A stdout",
      "show stderr to user only (blocking errors ignored)": "\u50C5\u5411\u7528\u6236\u986F\u793A stderr\uFF08\u5FFD\u7565\u963B\u585E\u932F\u8AA4\uFF09",
      "command completes successfully": "\u547D\u4EE4\u6210\u529F\u5B8C\u6210",
      "stdout shown to subagent": "\u5411\u5B50\u667A\u80FD\u9AD4\u986F\u793A stdout",
      "show stderr to subagent and continue having it run": "\u5411\u5B50\u667A\u80FD\u9AD4\u986F\u793A stderr \u4E26\u7E7C\u7E8C\u904B\u884C",
      "stdout appended as custom compact instructions": "stdout \u4F5C\u7232\u81EA\u5B9A\u7FA9\u58D3\u7E2E\u6307\u4EE4\u8FFD\u52A0",
      "block compaction": "\u963B\u6B62\u58D3\u7E2E",
      "show stderr to user only but continue with compaction": "\u50C5\u5411\u7528\u6236\u986F\u793A stderr \u4F46\u7E7C\u7E8C\u58D3\u7E2E",
      "use hook decision if provided": "\u5982\u679C\u63D0\u4F9B\u5247\u4F7F\u7528 Hook \u6C7A\u5B9A",
      "Config not loaded.": "\u914D\u7F6E\u672A\u52A0\u8F09\u3002",
      "Hooks are not enabled. Enable hooks in settings to use this feature.": "Hook \u672A\u5553\u7528\u3002\u8ACB\u5728\u8A2D\u7F6E\u4E2D\u5553\u7528 Hook \u4EE5\u4F7F\u7528\u6B64\u529F\u80FD\u3002",
      "No hooks configured. Add hooks in your settings.json file.": "\u672A\u914D\u7F6E Hook\u3002\u8ACB\u5728 settings.json \u6587\u4EF6\u4E2D\u6DFB\u52A0 Hook\u3002",
      "Configured Hooks ({{count}} total)": "\u5DF2\u914D\u7F6E\u7684 Hook\uFF08\u5171 {{count}} \u500B\uFF09",
      "Export current session message history to a file": "\u5C07\u7576\u524D\u6703\u8A71\u7684\u6D88\u606F\u8A18\u9304\u5C0E\u51FA\u5230\u6587\u4EF6",
      "Export session to HTML format": "\u5C07\u6703\u8A71\u5C0E\u51FA\u7232 HTML \u6587\u4EF6",
      "Export session to JSON format": "\u5C07\u6703\u8A71\u5C0E\u51FA\u7232 JSON \u6587\u4EF6",
      "Export session to JSONL format (one message per line)": "\u5C07\u6703\u8A71\u5C0E\u51FA\u7232 JSONL \u6587\u4EF6\uFF08\u6BCF\u884C\u4E00\u689D\u6D88\u606F\uFF09",
      "Export session to markdown format": "\u5C07\u6703\u8A71\u5C0E\u51FA\u7232 Markdown \u6587\u4EF6",
      "generate personalized programming insights from your chat history": "\u6839\u64DA\u4F60\u7684\u804A\u5929\u8A18\u9304\u751F\u6210\u500B\u6027\u5316\u7DE8\u7A0B\u6D1E\u5BDF",
      "Resume a previous session": "\u6062\u5FA9\u5148\u524D\u6703\u8A71",
      "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested": "\u6062\u5FA9\u67D0\u6B21\u5DE5\u5177\u8ABF\u7528\u3002\u9019\u5C07\u628A\u5C0D\u8A71\u8207\u6587\u4EF6\u6B77\u53F2\u91CD\u7F6E\u5230\u63D0\u51FA\u8A72\u5DE5\u5177\u8ABF\u7528\u5EFA\u8B70\u6642\u7684\u72C0\u614B",
      "Could not detect terminal type. Supported terminals: VS Code, Cursor, Windsurf, and Trae.": "\u7121\u6CD5\u6AA2\u6E2C\u7D42\u7AEF\u985E\u578B\u3002\u652F\u6301\u7684\u7D42\u7AEF\uFF1AVS Code\u3001Cursor\u3001Windsurf \u548C Trae\u3002",
      'Terminal "{{terminal}}" is not supported yet.': '\u7D42\u7AEF "{{terminal}}" \u5C1A\u672A\u652F\u6301\u3002',
      "Invalid language. Available: {{options}}": "\u7121\u6548\u7684\u8A9E\u8A00\u3002\u53EF\u7528\u9078\u9805\uFF1A{{options}}",
      "Language subcommands do not accept additional arguments.": "\u8A9E\u8A00\u5B50\u547D\u4EE4\u4E0D\u63A5\u53D7\u984D\u5916\u53C3\u6578",
      "Current UI language: {{lang}}": "\u7576\u524D UI \u8A9E\u8A00\uFF1A{{lang}}",
      "Current LLM output language: {{lang}}": "\u7576\u524D LLM \u8F38\u51FA\u8A9E\u8A00\uFF1A{{lang}}",
      "LLM output language not set": "\u672A\u8A2D\u7F6E LLM \u8F38\u51FA\u8A9E\u8A00",
      "Set UI language": "\u8A2D\u7F6E UI \u8A9E\u8A00",
      "Set LLM output language": "\u8A2D\u7F6E LLM \u8F38\u51FA\u8A9E\u8A00",
      "Usage: /language ui [{{options}}]": "\u7528\u6CD5\uFF1A/language ui [{{options}}]",
      "Usage: /language output <language>": "\u7528\u6CD5\uFF1A/language output <\u8A9E\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 \u8A9E\u8A00\u5DF2\u66F4\u6539\u7232 {{lang}}",
      "LLM output language set to {{lang}}": "LLM \u8F38\u51FA\u8A9E\u8A00\u5DF2\u8A2D\u7F6E\u7232 {{lang}}",
      "LLM output language rule file generated at {{path}}": "LLM \u8F38\u51FA\u8A9E\u8A00\u898F\u5247\u6587\u4EF6\u5DF2\u751F\u6210\u65BC {{path}}",
      "Please restart the application for the changes to take effect.": "\u8ACB\u91CD\u5553\u61C9\u7528\u7A0B\u5E8F\u4EE5\u4F7F\u66F4\u6539\u751F\u6548\u3002",
      "Failed to generate LLM output language rule file: {{error}}": "\u751F\u6210 LLM \u8F38\u51FA\u8A9E\u8A00\u898F\u5247\u6587\u4EF6\u5931\u6557\uFF1A{{error}}",
      "Invalid command. Available subcommands:": "\u7121\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\u8ACB\u6C42\u5176\u4ED6 UI \u8A9E\u8A00\u5305\uFF0C\u8ACB\u5728 GitHub \u4E0A\u63D0\u4EA4 issue",
      "Available options:": "\u53EF\u7528\u9078\u9805\uFF1A",
      "Set UI language to {{name}}": "\u5C07 UI \u8A9E\u8A00\u8A2D\u7F6E\u7232 {{name}}",
      "Tool Approval Mode": "\u5DE5\u5177\u5BE9\u6279\u6A21\u5F0F",
      "Current approval mode: {{mode}}": "\u7576\u524D\u5BE9\u6279\u6A21\u5F0F\uFF1A{{mode}}",
      "Available approval modes:": "\u53EF\u7528\u7684\u5BE9\u6279\u6A21\u5F0F\uFF1A",
      "Approval mode changed to: {{mode}}": "\u5BE9\u6279\u6A21\u5F0F\u5DF2\u66F4\u6539\u7232\uFF1A{{mode}}",
      "Approval mode changed to: {{mode}} (saved to {{scope}} settings{{location}})": "\u5BE9\u6279\u6A21\u5F0F\u5DF2\u66F4\u6539\u7232\uFF1A{{mode}}\uFF08\u5DF2\u4FDD\u5B58\u5230{{scope}}\u8A2D\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\u984D\u5916\u53C3\u6578",
      "Plan mode - Analyze only, do not modify files or execute commands": "\u898F\u5283\u6A21\u5F0F - \u50C5\u5206\u6790\uFF0C\u4E0D\u4FEE\u6539\u6587\u4EF6\u6216\u57F7\u884C\u547D\u4EE4",
      "Default mode - Require approval for file edits or shell commands": "\u9ED8\u8A8D\u6A21\u5F0F - \u9700\u8981\u6279\u51C6\u6587\u4EF6\u7DE8\u8F2F\u6216 shell \u547D\u4EE4",
      "Auto-edit mode - Automatically approve file edits": "\u81EA\u52D5\u7DE8\u8F2F\u6A21\u5F0F - \u81EA\u52D5\u6279\u51C6\u6587\u4EF6\u7DE8\u8F2F",
      "YOLO mode - Automatically approve all tools": "YOLO \u6A21\u5F0F - \u81EA\u52D5\u6279\u51C6\u6240\u6709\u5DE5\u5177",
      "{{mode}} mode": "{{mode}} \u6A21\u5F0F",
      "Settings service is not available; unable to persist the approval mode.": "\u8A2D\u7F6E\u670D\u52D9\u4E0D\u53EF\u7528\uFF1B\u7121\u6CD5\u6301\u4E45\u5316\u5BE9\u6279\u6A21\u5F0F\u3002",
      "Failed to save approval mode: {{error}}": "\u4FDD\u5B58\u5BE9\u6279\u6A21\u5F0F\u5931\u6557\uFF1A{{error}}",
      "Failed to change approval mode: {{error}}": "\u66F4\u6539\u5BE9\u6279\u6A21\u5F0F\u5931\u6557\uFF1A{{error}}",
      "Apply to current session only (temporary)": "\u50C5\u61C9\u7528\u65BC\u7576\u524D\u6703\u8A71\uFF08\u81E8\u6642\uFF09",
      "Persist for this project/workspace": "\u6301\u4E45\u5316\u5230\u6B64\u9805\u76EE/\u5DE5\u4F5C\u5340",
      "Persist for this user on this machine": "\u6301\u4E45\u5316\u5230\u6B64\u6A5F\u5668\u4E0A\u7684\u6B64\u7528\u6236",
      "Analyze only, do not modify files or execute commands": "\u50C5\u5206\u6790\uFF0C\u4E0D\u4FEE\u6539\u6587\u4EF6\u6216\u57F7\u884C\u547D\u4EE4",
      "Require approval for file edits or shell commands": "\u9700\u8981\u6279\u51C6\u6587\u4EF6\u7DE8\u8F2F\u6216 shell \u547D\u4EE4",
      "Automatically approve file edits": "\u81EA\u52D5\u6279\u51C6\u6587\u4EF6\u7DE8\u8F2F",
      "Automatically approve all tools": "\u81EA\u52D5\u6279\u51C6\u6240\u6709\u5DE5\u5177",
      "Workspace approval mode exists and takes priority. User-level change will have no effect.": "\u5DE5\u4F5C\u5340\u5BE9\u6279\u6A21\u5F0F\u5DF2\u5B58\u5728\u4E26\u5177\u6709\u512A\u5148\u7D1A\u3002\u7528\u6236\u7D1A\u5225\u7684\u66F4\u6539\u5C07\u7121\u6548\u3002",
      "Apply To": "\u61C9\u7528\u65BC",
      "Workspace Settings": "\u5DE5\u4F5C\u5340\u8A2D\u7F6E",
      "Commands for interacting with memory.": "\u7528\u65BC\u8207\u8A18\u61B6\u4EA4\u4E92\u7684\u547D\u4EE4",
      "Show the current memory contents.": "\u986F\u793A\u7576\u524D\u8A18\u61B6\u5167\u5BB9",
      "Show project-level memory contents.": "\u986F\u793A\u9805\u76EE\u7D1A\u8A18\u61B6\u5167\u5BB9",
      "Show global memory contents.": "\u986F\u793A\u5168\u5C40\u8A18\u61B6\u5167\u5BB9",
      "Add content to project-level memory.": "\u6DFB\u52A0\u5167\u5BB9\u5230\u9805\u76EE\u7D1A\u8A18\u61B6",
      "Add content to global memory.": "\u6DFB\u52A0\u5167\u5BB9\u5230\u5168\u5C40\u8A18\u61B6",
      "Refresh the memory from the source.": "\u5F9E\u6E90\u5237\u65B0\u8A18\u61B6",
      "Usage: /memory add --project <text to remember>": "\u7528\u6CD5\uFF1A/memory add --project <\u8981\u8A18\u4F4F\u7684\u6587\u672C>",
      "Usage: /memory add --global <text to remember>": "\u7528\u6CD5\uFF1A/memory add --global <\u8981\u8A18\u4F4F\u7684\u6587\u672C>",
      'Attempting to save to project memory: "{{text}}"': '\u6B63\u5728\u5617\u8A66\u4FDD\u5B58\u5230\u9805\u76EE\u8A18\u61B6\uFF1A"{{text}}"',
      'Attempting to save to global memory: "{{text}}"': '\u6B63\u5728\u5617\u8A66\u4FDD\u5B58\u5230\u5168\u5C40\u8A18\u61B6\uFF1A"{{text}}"',
      "Current memory content from {{count}} file(s):": "\u4F86\u81EA {{count}} \u500B\u6587\u4EF6\u7684\u7576\u524D\u8A18\u61B6\u5167\u5BB9\uFF1A",
      "Memory is currently empty.": "\u8A18\u61B6\u7576\u524D\u7232\u7A7A",
      "Project memory file not found or is currently empty.": "\u9805\u76EE\u8A18\u61B6\u6587\u4EF6\u672A\u627E\u5230\u6216\u7576\u524D\u7232\u7A7A",
      "Global memory file not found or is currently empty.": "\u5168\u5C40\u8A18\u61B6\u6587\u4EF6\u672A\u627E\u5230\u6216\u7576\u524D\u7232\u7A7A",
      "Global memory is currently empty.": "\u5168\u5C40\u8A18\u61B6\u7576\u524D\u7232\u7A7A",
      "Global memory content:\n\n---\n{{content}}\n---": "\u5168\u5C40\u8A18\u61B6\u5167\u5BB9\uFF1A\n\n---\n{{content}}\n---",
      "Project memory content from {{path}}:\n\n---\n{{content}}\n---": "\u9805\u76EE\u8A18\u61B6\u5167\u5BB9\u4F86\u81EA {{path}}\uFF1A\n\n---\n{{content}}\n---",
      "Project memory is currently empty.": "\u9805\u76EE\u8A18\u61B6\u7576\u524D\u7232\u7A7A",
      "Refreshing memory from source files...": "\u6B63\u5728\u5F9E\u6E90\u6587\u4EF6\u5237\u65B0\u8A18\u61B6...",
      "Add content to the memory. Use --global for global memory or --project for project memory.": "\u6DFB\u52A0\u5167\u5BB9\u5230\u8A18\u61B6\u3002\u4F7F\u7528 --global \u8868\u793A\u5168\u5C40\u8A18\u61B6\uFF0C\u4F7F\u7528 --project \u8868\u793A\u9805\u76EE\u8A18\u61B6",
      "Usage: /memory add [--global|--project] <text to remember>": "\u7528\u6CD5\uFF1A/memory add [--global|--project] <\u8981\u8A18\u4F4F\u7684\u6587\u672C>",
      'Attempting to save to memory {{scope}}: "{{fact}}"': '\u6B63\u5728\u5617\u8A66\u4FDD\u5B58\u5230\u8A18\u61B6 {{scope}}\uFF1A"{{fact}}"',
      "Open auto-memory folder": "\u6253\u958B\u81EA\u52D5\u8A18\u61B6\u6587\u4EF6\u593E",
      "Auto-memory: {{status}}": "\u81EA\u52D5\u8A18\u61B6\uFF1A{{status}}",
      "Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream to run": "\u81EA\u52D5\u6574\u7406\uFF1A{{status}} \xB7 {{lastDream}} \xB7 /dream \u7ACB\u5373\u904B\u884C",
      never: "\u5F9E\u672A",
      on: "\u958B",
      off: "\u95DC",
      "\u2726 dreaming": "\u2726 \u6574\u7406\u4E2D",
      "Remove matching entries from managed auto-memory.": "\u5F9E\u8A17\u7BA1\u81EA\u52D5\u8A18\u61B6\u4E2D\u522A\u9664\u5339\u914D\u7684\u689D\u76EE\u3002",
      "Usage: /forget <memory text to remove>": "\u7528\u6CD5\uFF1A/forget <\u8981\u522A\u9664\u7684\u8A18\u61B6\u6587\u672C>",
      "No managed auto-memory entries matched: {{query}}": "\u6C92\u6709\u5339\u914D\u7684\u8A17\u7BA1\u81EA\u52D5\u8A18\u61B6\u689D\u76EE\uFF1A{{query}}",
      "Show managed auto-memory status.": "\u986F\u793A\u8A17\u7BA1\u81EA\u52D5\u8A18\u61B6\u72C0\u614B",
      "Run managed auto-memory extraction for the current session.": "\u7232\u7576\u524D\u6703\u8A71\u904B\u884C\u8A17\u7BA1\u81EA\u52D5\u8A18\u61B6\u63D0\u7149",
      "Managed auto-memory root: {{root}}": "\u8A17\u7BA1\u81EA\u52D5\u8A18\u61B6\u6839\u76EE\u9304\uFF1A{{root}}",
      "Managed auto-memory topics:": "\u8A17\u7BA1\u81EA\u52D5\u8A18\u61B6\u4E3B\u984C\uFF1A",
      "No extraction cursor found yet.": "\u5C1A\u672A\u627E\u5230\u63D0\u7149\u904A\u6A19\u3002",
      "Cursor: session={{sessionId}}, offset={{offset}}, updated={{updatedAt}}": "\u904A\u6A19\uFF1Asession={{sessionId}}\uFF0Coffset={{offset}}\uFF0Cupdated={{updatedAt}}",
      "No chat client available to extract memory.": "\u6C92\u6709\u53EF\u7528\u65BC\u63D0\u7149\u8A18\u61B6\u7684\u804A\u5929\u5BA2\u6236\u7AEF\u3002",
      "Managed auto-memory extraction is already running.": "\u8A17\u7BA1\u81EA\u52D5\u8A18\u61B6\u63D0\u7149\u5DF2\u5728\u904B\u884C\u4E2D\u3002",
      "Managed auto-memory extraction found no new durable memories.": "\u8A17\u7BA1\u81EA\u52D5\u8A18\u61B6\u63D0\u7149\u672A\u767C\u73FE\u65B0\u7684\u6301\u4E45\u8A18\u61B6\u3002",
      "Consolidate managed auto-memory topic files.": "\u6574\u7406\u8A17\u7BA1\u81EA\u52D5\u8A18\u61B6\u4E3B\u984C\u6587\u4EF6",
      "Managed auto-memory dream found nothing to improve.": "\u8A17\u7BA1\u81EA\u52D5\u8A18\u61B6 dream \u672A\u767C\u73FE\u53EF\u6539\u9032\u5167\u5BB9\u3002",
      "Deduplicated entries: {{count}}": "\u53BB\u91CD\u689D\u76EE\u6578\uFF1A{{count}}",
      "Save a durable memory using the save_memory tool.": "\u4F7F\u7528 save_memory \u5DE5\u5177\u4FDD\u5B58\u4E00\u689D\u6301\u4E45\u8A18\u61B6",
      "Usage: /remember [--global|--project] <text to remember>": "\u7528\u6CD5\uFF1A/remember [--global|--project] <\u8981\u8A18\u4F4F\u7684\u6587\u672C>",
      "Authenticate with an OAuth-enabled MCP server": "\u4F7F\u7528\u652F\u6301 OAuth \u7684 MCP \u670D\u52D9\u5668\u9032\u884C\u8A8D\u8B49",
      "List configured MCP servers and tools": "\u5217\u51FA\u5DF2\u914D\u7F6E\u7684 MCP \u670D\u52D9\u5668\u548C\u5DE5\u5177",
      "Restarts MCP servers.": "\u91CD\u5553 MCP \u670D\u52D9\u5668",
      "Open MCP management dialog": "\u6253\u958B MCP \u7BA1\u7406\u5C0D\u8A71\u6846",
      "Could not retrieve tool registry.": "\u7121\u6CD5\u6AA2\u7D22\u5DE5\u5177\u8A3B\u518A\u8868",
      "No MCP servers configured with OAuth authentication.": "\u672A\u914D\u7F6E\u652F\u6301 OAuth \u8A8D\u8B49\u7684 MCP \u670D\u52D9\u5668",
      "MCP servers with OAuth authentication:": "\u652F\u6301 OAuth \u8A8D\u8B49\u7684 MCP \u670D\u52D9\u5668\uFF1A",
      "Use /mcp auth <server-name> to authenticate.": "\u4F7F\u7528 /mcp auth <server-name> \u9032\u884C\u8A8D\u8B49",
      "MCP server '{{name}}' not found.": "\u672A\u627E\u5230 MCP \u670D\u52D9\u5668 '{{name}}'",
      "Successfully authenticated and refreshed tools for '{{name}}'.": "\u6210\u529F\u8A8D\u8B49\u4E26\u5237\u65B0\u4E86 '{{name}}' \u7684\u5DE5\u5177",
      "Failed to authenticate with MCP server '{{name}}': {{error}}": "\u8A8D\u8B49 MCP \u670D\u52D9\u5668 '{{name}}' \u5931\u6557\uFF1A{{error}}",
      "Re-discovering tools from '{{name}}'...": "\u6B63\u5728\u91CD\u65B0\u767C\u73FE '{{name}}' \u7684\u5DE5\u5177...",
      "Discovered {{count}} tool(s) from '{{name}}'.": "\u5F9E '{{name}}' \u767C\u73FE\u4E86 {{count}} \u500B\u5DE5\u5177\u3002",
      "Authentication complete. Returning to server details...": "\u8A8D\u8B49\u5B8C\u6210\uFF0C\u6B63\u5728\u8FD4\u56DE\u670D\u52D9\u5668\u8A73\u60C5...",
      "Authentication successful.": "\u8A8D\u8B49\u6210\u529F\u3002",
      "If the browser does not open, copy and paste this URL into your browser:": "\u5982\u679C\u700F\u89BD\u5668\u672A\u81EA\u52D5\u6253\u958B\uFF0C\u8ACB\u8907\u88FD\u4EE5\u4E0B URL \u4E26\u7C98\u8CBC\u5230\u700F\u89BD\u5668\u4E2D\uFF1A",
      "Make sure to copy the COMPLETE URL - it may wrap across multiple lines.": "\u26A0\uFE0F  \u8ACB\u78BA\u4FDD\u8907\u88FD\u5B8C\u6574\u7684 URL \u2014\u2014 \u5B83\u53EF\u80FD\u8DE8\u8D8A\u591A\u884C\u3002",
      "Manage MCP servers": "\u7BA1\u7406 MCP \u670D\u52D9\u5668",
      "Server Detail": "\u670D\u52D9\u5668\u8A73\u60C5",
      "Disable Server": "\u7981\u7528\u670D\u52D9\u5668",
      Tools: "\u5DE5\u5177",
      "Tool Detail": "\u5DE5\u5177\u8A73\u60C5",
      "MCP Management": "MCP \u7BA1\u7406",
      "Loading...": "\u52A0\u8F09\u4E2D...",
      "Unknown step": "\u672A\u77E5\u6B65\u9A5F",
      "Esc to back": "Esc \u8FD4\u56DE",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close": "\u2191\u2193 \u5C0E\u822A \xB7 Enter \u9078\u64C7 \xB7 Esc \u95DC\u9589",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back": "\u2191\u2193 \u5C0E\u822A \xB7 Enter \u9078\u64C7 \xB7 Esc \u8FD4\u56DE",
      "\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back": "\u2191\u2193 \u5C0E\u822A \xB7 Enter \u78BA\u8A8D \xB7 Esc \u8FD4\u56DE",
      "User Settings (global)": "\u7528\u6236\u8A2D\u7F6E\uFF08\u5168\u5C40\uFF09",
      "Workspace Settings (project-specific)": "\u5DE5\u4F5C\u5340\u8A2D\u7F6E\uFF08\u9805\u76EE\u7D1A\uFF09",
      "Disable server:": "\u7981\u7528\u670D\u52D9\u5668\uFF1A",
      "Select where to add the server to the exclude list:": "\u9078\u64C7\u5C07\u670D\u52D9\u5668\u6DFB\u52A0\u5230\u6392\u9664\u5217\u8868\u7684\u4F4D\u7F6E\uFF1A",
      "Press Enter to confirm, Esc to cancel": "\u6309 Enter \u78BA\u8A8D\uFF0CEsc \u53D6\u6D88",
      "View tools": "\u67E5\u770B\u5DE5\u5177",
      Reconnect: "\u91CD\u65B0\u9023\u63A5",
      Enable: "\u5553\u7528",
      Disable: "\u7981\u7528",
      Authenticate: "\u8A8D\u8B49",
      "Re-authenticate": "\u91CD\u65B0\u8A8D\u8B49",
      "Clear Authentication": "\u6E05\u7A7A\u8A8D\u8B49",
      "Server:": "\u670D\u52D9\u5668\uFF1A",
      "Command:": "\u547D\u4EE4\uFF1A",
      "Working Directory:": "\u5DE5\u4F5C\u76EE\u9304\uFF1A",
      "Capabilities:": "\u529F\u80FD\uFF1A",
      "No server selected": "\u672A\u9078\u64C7\u670D\u52D9\u5668",
      prompts: "\u63D0\u793A\u8A5E",
      "(disabled)": "(\u5DF2\u7981\u7528)",
      "Error:": "\u932F\u8AA4\uFF1A",
      tool: "\u5DE5\u5177",
      tools: "\u500B\u5DE5\u5177",
      connected: "\u5DF2\u9023\u63A5",
      connecting: "\u9023\u63A5\u4E2D",
      disconnected: "\u5DF2\u65B7\u958B",
      "User MCPs": "\u7528\u6236 MCP",
      "Project MCPs": "\u9805\u76EE MCP",
      "Extension MCPs": "\u64F4\u5C55 MCP",
      server: "\u500B\u670D\u52D9\u5668",
      servers: "\u500B\u670D\u52D9\u5668",
      "Add MCP servers to your settings to get started.": "\u8ACB\u5728\u8A2D\u7F6E\u4E2D\u6DFB\u52A0 MCP \u670D\u52D9\u5668\u4EE5\u958B\u59CB\u4F7F\u7528\u3002",
      "Run qwen --debug to see error logs": "\u904B\u884C qwen --debug \u67E5\u770B\u932F\u8AA4\u65E5\u8A8C",
      "OAuth Authentication": "OAuth \u8A8D\u8B49",
      "Press Enter to start authentication, Esc to go back": "\u6309 Enter \u958B\u59CB\u8A8D\u8B49\uFF0CEsc \u8FD4\u56DE",
      "Authenticating... Please complete the login in your browser.": "\u8A8D\u8B49\u4E2D... \u8ACB\u5728\u700F\u89BD\u5668\u4E2D\u5B8C\u6210\u767B\u9304\u3002",
      "Press c to copy the authorization URL to your clipboard.": "\u6309 c \u8907\u88FD\u6388\u6B0A URL \u5230\u526A\u8CBC\u677F\u3002",
      "Copy request sent to your terminal. If paste is empty, copy the URL above manually.": "\u5DF2\u5411\u7D42\u7AEF\u767C\u9001\u8907\u88FD\u8ACB\u6C42\uFF1B\u82E5\u7C98\u8CBC\u7232\u7A7A\uFF0C\u8ACB\u624B\u52D5\u8907\u88FD\u4E0A\u65B9 URL\u3002",
      "Cannot write to terminal \u2014 copy the URL above manually.": "\u7121\u6CD5\u5BEB\u5165\u7D42\u7AEF\uFF0C\u8ACB\u624B\u52D5\u8907\u88FD\u4E0A\u65B9 URL\u3002",
      "Press Enter or Esc to go back": "\u6309 Enter \u6216 Esc \u8FD4\u56DE",
      "No tools available for this server.": "\u6B64\u670D\u52D9\u5668\u6C92\u6709\u53EF\u7528\u5DE5\u5177\u3002",
      destructive: "\u7834\u58DE\u6027",
      "read-only": "\u53EA\u8B80",
      "open-world": "\u958B\u653E\u4E16\u754C",
      idempotent: "\u51AA\u7B49",
      "Tools for {{name}}": "{{name}} \u7684\u5DE5\u5177",
      "Tools for {{serverName}}": "{{serverName}} \u7684\u5DE5\u5177",
      "{{current}}/{{total}}": "{{current}}/{{total}}",
      required: "\u5FC5\u586B",
      Type: "\u985E\u578B",
      Enum: "\u679A\u8209",
      Parameters: "\u53C3\u6578",
      "No tool selected": "\u672A\u9078\u64C7\u5DE5\u5177",
      Annotations: "\u8A3B\u89E3",
      Title: "\u6A19\u984C",
      "Read Only": "\u53EA\u8B80",
      Destructive: "\u7834\u58DE\u6027",
      Idempotent: "\u51AA\u7B49",
      "Open World": "\u958B\u653E\u4E16\u754C",
      Server: "\u670D\u52D9\u5668",
      "{{count}} invalid tools": "{{count}} \u500B\u7121\u6548\u5DE5\u5177",
      invalid: "\u7121\u6548",
      "invalid: {{reason}}": "\u7121\u6548\uFF1A{{reason}}",
      "missing name": "\u7F3A\u5C11\u540D\u7A31",
      "missing description": "\u7F3A\u5C11\u63CF\u8FF0",
      "(unnamed)": "(\u672A\u547D\u540D)",
      "Warning: This tool cannot be called by the LLM": "\u8B66\u544A\uFF1A\u6B64\u5DE5\u5177\u7121\u6CD5\u88AB LLM \u8ABF\u7528",
      Reason: "\u539F\u56E0",
      "Tools must have both name and description to be used by the LLM.": "\u5DE5\u5177\u5FC5\u9808\u540C\u6642\u5177\u6709\u540D\u7A31\u548C\u63CF\u8FF0\u624D\u80FD\u88AB LLM \u4F7F\u7528\u3002",
      "Manage conversation history.": "\u7BA1\u7406\u5C0D\u8A71\u6B77\u53F2",
      "List saved conversation checkpoints": "\u5217\u51FA\u5DF2\u4FDD\u5B58\u7684\u5C0D\u8A71\u6AA2\u67E5\u9EDE",
      "No saved conversation checkpoints found.": "\u672A\u627E\u5230\u5DF2\u4FDD\u5B58\u7684\u5C0D\u8A71\u6AA2\u67E5\u9EDE",
      "List of saved conversations:": "\u5DF2\u4FDD\u5B58\u7684\u5C0D\u8A71\u5217\u8868\uFF1A",
      "Note: Newest last, oldest first": "\u6CE8\u610F\uFF1A\u6700\u65B0\u7684\u5728\u6700\u5F8C\uFF0C\u6700\u820A\u7684\u5728\u6700\u524D",
      "Save the current conversation as a checkpoint. Usage: /chat save <tag>": "\u5C07\u7576\u524D\u5C0D\u8A71\u4FDD\u5B58\u7232\u6AA2\u67E5\u9EDE\u3002\u7528\u6CD5\uFF1A/chat save <tag>",
      "Missing tag. Usage: /chat save <tag>": "\u7F3A\u5C11\u6A19\u7C64\u3002\u7528\u6CD5\uFF1A/chat save <tag>",
      "Delete a conversation checkpoint. Usage: /chat delete <tag>": "\u522A\u9664\u5C0D\u8A71\u6AA2\u67E5\u9EDE\u3002\u7528\u6CD5\uFF1A/chat delete <tag>",
      "Missing tag. Usage: /chat delete <tag>": "\u7F3A\u5C11\u6A19\u7C64\u3002\u7528\u6CD5\uFF1A/chat delete <tag>",
      "Conversation checkpoint '{{tag}}' has been deleted.": "\u5C0D\u8A71\u6AA2\u67E5\u9EDE '{{tag}}' \u5DF2\u522A\u9664",
      "Error: No checkpoint found with tag '{{tag}}'.": "\u932F\u8AA4\uFF1A\u672A\u627E\u5230\u6A19\u7C64\u7232 '{{tag}}' \u7684\u6AA2\u67E5\u9EDE",
      "Resume a conversation from a checkpoint. Usage: /chat resume <tag>": "\u5F9E\u6AA2\u67E5\u9EDE\u6062\u5FA9\u5C0D\u8A71\u3002\u7528\u6CD5\uFF1A/chat resume <tag>",
      "Missing tag. Usage: /chat resume <tag>": "\u7F3A\u5C11\u6A19\u7C64\u3002\u7528\u6CD5\uFF1A/chat resume <tag>",
      "No saved checkpoint found with tag: {{tag}}.": "\u672A\u627E\u5230\u6A19\u7C64\u7232 {{tag}} \u7684\u5DF2\u4FDD\u5B58\u6AA2\u67E5\u9EDE",
      "A checkpoint with the tag {{tag}} already exists. Do you want to overwrite it?": "\u6A19\u7C64\u7232 {{tag}} \u7684\u6AA2\u67E5\u9EDE\u5DF2\u5B58\u5728\u3002\u60A8\u8981\u8986\u84CB\u5B83\u55CE\uFF1F",
      "No chat client available to save conversation.": "\u6C92\u6709\u53EF\u7528\u7684\u804A\u5929\u5BA2\u6236\u7AEF\u4F86\u4FDD\u5B58\u5C0D\u8A71",
      "Conversation checkpoint saved with tag: {{tag}}.": "\u5C0D\u8A71\u6AA2\u67E5\u9EDE\u5DF2\u4FDD\u5B58\uFF0C\u6A19\u7C64\uFF1A{{tag}}",
      "No conversation found to save.": "\u672A\u627E\u5230\u8981\u4FDD\u5B58\u7684\u5C0D\u8A71",
      "No chat client available to share conversation.": "\u6C92\u6709\u53EF\u7528\u7684\u804A\u5929\u5BA2\u6236\u7AEF\u4F86\u5206\u4EAB\u5C0D\u8A71",
      "Invalid file format. Only .md and .json are supported.": "\u7121\u6548\u7684\u6587\u4EF6\u683C\u5F0F\u3002\u50C5\u652F\u6301 .md \u548C .json \u6587\u4EF6",
      "Error sharing conversation: {{error}}": "\u5206\u4EAB\u5C0D\u8A71\u6642\u51FA\u932F\uFF1A{{error}}",
      "Conversation shared to {{filePath}}": "\u5C0D\u8A71\u5DF2\u5206\u4EAB\u5230 {{filePath}}",
      "No conversation found to share.": "\u672A\u627E\u5230\u8981\u5206\u4EAB\u7684\u5C0D\u8A71",
      "Share the current conversation to a markdown or json file. Usage: /chat share <file>": "\u5C07\u7576\u524D\u5C0D\u8A71\u5206\u4EAB\u5230 markdown \u6216 json \u6587\u4EF6\u3002\u7528\u6CD5\uFF1A/chat share <file>",
      "Generate a project summary and save it to .qwen/PROJECT_SUMMARY.md": "\u751F\u6210\u9805\u76EE\u6458\u8981\u4E26\u4FDD\u5B58\u5230 .qwen/PROJECT_SUMMARY.md",
      "No chat client available to generate summary.": "\u6C92\u6709\u53EF\u7528\u7684\u804A\u5929\u5BA2\u6236\u7AEF\u4F86\u751F\u6210\u6458\u8981",
      "Already generating summary, wait for previous request to complete": "\u6B63\u5728\u751F\u6210\u6458\u8981\uFF0C\u8ACB\u7B49\u5F85\u4E0A\u4E00\u500B\u8ACB\u6C42\u5B8C\u6210",
      "No conversation found to summarize.": "\u672A\u627E\u5230\u8981\u7E3D\u7D50\u7684\u5C0D\u8A71",
      "Failed to generate project context summary: {{error}}": "\u751F\u6210\u9805\u76EE\u4E0A\u4E0B\u6587\u6458\u8981\u5931\u6557\uFF1A{{error}}",
      "Saved project summary to {{filePathForDisplay}}.": "\u9805\u76EE\u6458\u8981\u5DF2\u4FDD\u5B58\u5230 {{filePathForDisplay}}",
      "Saving project summary...": "\u6B63\u5728\u4FDD\u5B58\u9805\u76EE\u6458\u8981...",
      "Generating project summary...": "\u6B63\u5728\u751F\u6210\u9805\u76EE\u6458\u8981...",
      "Failed to generate summary - no text content received from LLM response": "\u751F\u6210\u6458\u8981\u5931\u6557 - \u672A\u5F9E LLM \u97FF\u61C9\u4E2D\u63A5\u6536\u5230\u6587\u672C\u5167\u5BB9",
      "Switch the model for this session (--fast for suggestion model)": "\u5207\u63DB\u6B64\u6703\u8A71\u7684\u6A21\u578B\uFF08--fast \u53EF\u8A2D\u7F6E\u5EFA\u8B70\u6A21\u578B\uFF09",
      "Set a lighter model for prompt suggestions and speculative execution": "\u8A2D\u7F6E\u7528\u65BC\u8F38\u5165\u5EFA\u8B70\u548C\u63A8\u6E2C\u57F7\u884C\u7684\u8F15\u91CF\u6A21\u578B",
      "Content generator configuration not available.": "\u5167\u5BB9\u751F\u6210\u5668\u914D\u7F6E\u4E0D\u53EF\u7528",
      "Authentication type not available.": "\u8A8D\u8B49\u985E\u578B\u4E0D\u53EF\u7528",
      "No models available for the current authentication type ({{authType}}).": "\u7576\u524D\u8A8D\u8B49\u985E\u578B ({{authType}}) \u6C92\u6709\u53EF\u7528\u7684\u6A21\u578B",
      "Starting a new session, resetting chat, and clearing terminal.": "\u6B63\u5728\u958B\u59CB\u65B0\u6703\u8A71\uFF0C\u91CD\u7F6E\u804A\u5929\u4E26\u6E05\u5C4F\u3002",
      "Starting a new session and clearing.": "\u6B63\u5728\u958B\u59CB\u65B0\u6703\u8A71\u4E26\u6E05\u5C4F\u3002",
      "Already compressing, wait for previous request to complete": "\u6B63\u5728\u58D3\u7E2E\u4E2D\uFF0C\u8ACB\u7B49\u5F85\u4E0A\u4E00\u500B\u8ACB\u6C42\u5B8C\u6210",
      "Failed to compress chat history.": "\u58D3\u7E2E\u804A\u5929\u66C6\u53F2\u5931\u6557",
      "Failed to compress chat history: {{error}}": "\u58D3\u7E2E\u804A\u5929\u66C6\u53F2\u5931\u6557\uFF1A{{error}}",
      "Compressing chat history": "\u6B63\u5728\u58D3\u7E2E\u804A\u5929\u66C6\u53F2",
      "Chat history compressed from {{originalTokens}} to {{newTokens}} tokens.": "\u804A\u5929\u66C6\u53F2\u5DF2\u5F9E {{originalTokens}} \u500B token \u58D3\u7E2E\u5230 {{newTokens}} \u500B token\u3002",
      "Compression was not beneficial for this history size.": "\u5C0D\u65BC\u6B64\u6B77\u53F2\u8A18\u9304\u5927\u5C0F\uFF0C\u58D3\u7E2E\u6C92\u6709\u76CA\u8655\u3002",
      "Chat history compression did not reduce size. This may indicate issues with the compression prompt.": "\u804A\u5929\u66C6\u53F2\u58D3\u7E2E\u672A\u80FD\u6E1B\u5C0F\u5927\u5C0F\u3002\u9019\u53EF\u80FD\u8868\u660E\u58D3\u7E2E\u63D0\u793A\u5B58\u5728\u554F\u984C\u3002",
      "Could not compress chat history due to a token counting error.": "\u7531\u65BC token \u8A08\u6578\u932F\u8AA4\uFF0C\u7121\u6CD5\u58D3\u7E2E\u804A\u5929\u66C6\u53F2\u3002",
      "Chat history is already compressed.": "\u804A\u5929\u66C6\u53F2\u5DF2\u7D93\u58D3\u7E2E\u3002",
      "Configuration is not available.": "\u914D\u7F6E\u4E0D\u53EF\u7528\u3002",
      "Please provide at least one path to add.": "\u8ACB\u63D0\u4F9B\u81F3\u5C11\u4E00\u500B\u8981\u6DFB\u52A0\u7684\u8DEF\u5F91\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\u8ACB\u6539\u7232\u5728\u5553\u52D5\u6703\u8A71\u6642\u4F7F\u7528 --include-directories\u3002",
      "Error adding '{{path}}': {{error}}": "\u6DFB\u52A0 '{{path}}' \u6642\u51FA\u932F\uFF1A{{error}}",
      "Successfully added QWEN.md files from the following directories if there are:\n- {{directories}}": "\u5982\u679C\u5B58\u5728\uFF0C\u5DF2\u6210\u529F\u5F9E\u4EE5\u4E0B\u76EE\u9304\u6DFB\u52A0 QWEN.md \u6587\u4EF6\uFF1A\n- {{directories}}",
      "Error refreshing memory: {{error}}": "\u5237\u65B0\u5167\u5B58\u6642\u51FA\u932F\uFF1A{{error}}",
      "Successfully added directories:\n- {{directories}}": "\u6210\u529F\u6DFB\u52A0\u76EE\u9304\uFF1A\n- {{directories}}",
      "Current workspace directories:\n{{directories}}": "\u7576\u524D\u5DE5\u4F5C\u5340\u76EE\u9304\uFF1A\n{{directories}}",
      "Please open the following URL in your browser to view the documentation:\n{{url}}": "\u8ACB\u5728\u700F\u89BD\u5668\u4E2D\u6253\u958B\u4EE5\u4E0B URL \u4EE5\u67E5\u770B\u6587\u6A94\uFF1A\n{{url}}",
      "Opening documentation in your browser: {{url}}": "\u6B63\u5728\u700F\u89BD\u5668\u4E2D\u6253\u958B\u6587\u6A94\uFF1A{{url}}",
      "Do you want to proceed?": "\u662F\u5426\u7E7C\u7E8C\uFF1F",
      "Yes, allow once": "\u662F\uFF0C\u5141\u8A31\u4E00\u6B21",
      "Allow always": "\u7E3D\u662F\u5141\u8A31",
      Yes: "\u662F",
      No: "\u5426",
      "No (esc)": "\u5426 (esc)",
      "Yes, allow always for this session": "\u662F\uFF0C\u672C\u6B21\u6703\u8A71\u7E3D\u662F\u5141\u8A31",
      "Modify in progress:": "\u6B63\u5728\u4FEE\u6539\uFF1A",
      "Save and close external editor to continue": "\u4FDD\u5B58\u4E26\u95DC\u9589\u5916\u90E8\u7DE8\u8F2F\u5668\u4EE5\u7E7C\u7E8C",
      "Apply this change?": "\u662F\u5426\u61C9\u7528\u6B64\u66F4\u6539\uFF1F",
      "Yes, allow always": "\u662F\uFF0C\u7E3D\u662F\u5141\u8A31",
      "Modify with external editor": "\u4F7F\u7528\u5916\u90E8\u7DE8\u8F2F\u5668\u4FEE\u6539",
      "No, suggest changes (esc)": "\u5426\uFF0C\u5EFA\u8B70\u66F4\u6539 (esc)",
      "Allow execution of: '{{command}}'?": "\u5141\u8A31\u57F7\u884C\uFF1A'{{command}}'\uFF1F",
      "Yes, allow always ...": "\u662F\uFF0C\u7E3D\u662F\u5141\u8A31 ...",
      "Always allow in this project": "\u5728\u672C\u9805\u76EE\u4E2D\u7E3D\u662F\u5141\u8A31",
      "Always allow {{action}} in this project": "\u5728\u672C\u9805\u76EE\u4E2D\u7E3D\u662F\u5141\u8A31{{action}}",
      "Always allow for this user": "\u5C0D\u8A72\u7528\u6236\u7E3D\u662F\u5141\u8A31",
      "Always allow {{action}} for this user": "\u5C0D\u8A72\u7528\u6236\u7E3D\u662F\u5141\u8A31{{action}}",
      "Yes, restore previous mode ({{mode}})": "\u662F\uFF0C\u6062\u5FA9\u4E4B\u524D\u7684\u6A21\u5F0F ({{mode}})",
      "Yes, and auto-accept edits": "\u662F\uFF0C\u4E26\u81EA\u52D5\u63A5\u53D7\u7DE8\u8F2F",
      "Yes, and manually approve edits": "\u662F\uFF0C\u4E26\u624B\u52D5\u6279\u51C6\u7DE8\u8F2F",
      "No, keep planning (esc)": "\u5426\uFF0C\u7E7C\u7E8C\u898F\u5283 (esc)",
      "URLs to fetch:": "\u8981\u7372\u53D6\u7684 URL\uFF1A",
      "MCP Server: {{server}}": "MCP \u670D\u52D9\u5668\uFF1A{{server}}",
      "Tool: {{tool}}": "\u5DE5\u5177\uFF1A{{tool}}",
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?': '\u5141\u8A31\u57F7\u884C\u4F86\u81EA\u670D\u52D9\u5668 "{{server}}" \u7684 MCP \u5DE5\u5177 "{{tool}}"\uFF1F',
      'Yes, always allow tool "{{tool}}" from server "{{server}}"': '\u662F\uFF0C\u7E3D\u662F\u5141\u8A31\u4F86\u81EA\u670D\u52D9\u5668 "{{server}}" \u7684\u5DE5\u5177 "{{tool}}"',
      'Yes, always allow all tools from server "{{server}}"': '\u662F\uFF0C\u7E3D\u662F\u5141\u8A31\u4F86\u81EA\u670D\u52D9\u5668 "{{server}}" \u7684\u6240\u6709\u5DE5\u5177',
      "Shell Command Execution": "Shell \u547D\u4EE4\u57F7\u884C",
      "A custom command wants to run the following shell commands:": "\u81EA\u5B9A\u7FA9\u547D\u4EE4\u60F3\u8981\u904B\u884C\u4EE5\u4E0B shell \u547D\u4EE4\uFF1A",
      "Pro quota limit reached for {{model}}.": "{{model}} \u7684 Pro \u914D\u984D\u5DF2\u9054\u5230\u4E0A\u9650",
      "Change auth (executes the /auth command)": "\u66F4\u6539\u8A8D\u8B49\uFF08\u57F7\u884C /auth \u547D\u4EE4\uFF09",
      "Continue with {{model}}": "\u4F7F\u7528 {{model}} \u7E7C\u7E8C",
      "Current Plan:": "\u7576\u524D\u8A08\u5283\uFF1A",
      "Progress: {{done}}/{{total}} tasks completed": "\u9032\u5EA6\uFF1A\u5DF2\u5B8C\u6210 {{done}}/{{total}} \u500B\u4EFB\u52D9",
      ", {{inProgress}} in progress": "\uFF0C{{inProgress}} \u500B\u9032\u884C\u4E2D",
      "Pending Tasks:": "\u5F85\u8655\u7406\u4EFB\u52D9\uFF1A",
      "What would you like to do?": "\u60A8\u60F3\u8981\u505A\u4EC0\u9EBC\uFF1F",
      "Choose how to proceed with your session:": "\u9078\u64C7\u5982\u4F55\u7E7C\u7E8C\u60A8\u7684\u6703\u8A71\uFF1A",
      "Start new chat session": "\u958B\u59CB\u65B0\u7684\u804A\u5929\u6703\u8A71",
      "Continue previous conversation": "\u7E7C\u7E8C\u4E4B\u524D\u7684\u5C0D\u8A71",
      "\u{1F44B} Welcome back! (Last updated: {{timeAgo}})": "\u{1F44B} \u6B61\u8FCE\u56DE\u4F86\uFF01\uFF08\u6700\u5F8C\u66F4\u65B0\uFF1A{{timeAgo}}\uFF09",
      "\u{1F3AF} Overall Goal:": "\u{1F3AF} \u7E3D\u9AD4\u76EE\u6A19\uFF1A",
      "Get started": "\u958B\u59CB\u4F7F\u7528",
      "Select Authentication Method": "\u9078\u64C7\u8A8D\u8B49\u65B9\u5F0F",
      "OpenAI API key is required to use OpenAI authentication.": "\u4F7F\u7528 OpenAI \u8A8D\u8B49\u9700\u8981 OpenAI API \u5BC6\u9470",
      "You must select an auth method to proceed. Press Ctrl+C again to exit.": "\u60A8\u5FC5\u9808\u9078\u64C7\u8A8D\u8B49\u65B9\u6CD5\u624D\u80FD\u7E7C\u7E8C\u3002\u518D\u6B21\u6309 Ctrl+C \u9000\u51FA",
      "Terms of Services and Privacy Notice": "\u670D\u52D9\u689D\u6B3E\u548C\u96B1\u79C1\u8072\u660E",
      "Qwen OAuth": "Qwen OAuth (\u514D\u8CBB)",
      "Discontinued \u2014 switch to Coding Plan or API Key": "\u5DF2\u505C\u7528 \u2014 \u8ACB\u5207\u63DB\u5230 Coding Plan \u6216 API Key",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch provider.": "Qwen OAuth \u514D\u8CBB\u984D\u5EA6\u5DF2\u65BC 2026-04-15 \u505C\u7528\u3002\u8ACB\u904B\u884C /auth \u5207\u63DB\u670D\u52D9\u5546\u3002",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead.": "Qwen OAuth \u514D\u8CBB\u984D\u5EA6\u5DF2\u65BC 2026-04-15 \u505C\u7528\u3002\u8ACB\u9078\u64C7 Coding Plan \u6216 API Key\u3002",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.": "Qwen OAuth\u514D\u8CBB\u5C64\u5DF2\u65BC2026-04-15\u505C\u6B62\u670D\u52D9\u3002\u8ACB\u9078\u64C7\u5176\u4ED6\u63D0\u4F9B\u5546\u7684\u6A21\u578B\u6216\u904B\u884C /auth \u5207\u63DB\u3002",
      "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n": "\n\u26A0 Qwen OAuth \u514D\u8CBB\u984D\u5EA6\u5DF2\u65BC 2026-04-15 \u505C\u7528\u3002\u8ACB\u9078\u64C7\u5176\u4ED6\u9078\u9805\u3002\n",
      "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models": "\u4ED8\u8CBB \xB7 \u6BCF 5 \u5C0F\u6642\u6700\u591A 6,000 \u6B21\u8ACB\u6C42 \xB7 \u652F\u6301\u963F\u91CC\u96F2\u767E\u934A Coding Plan \u5168\u90E8\u6A21\u578B",
      "Alibaba Cloud Coding Plan": "\u963F\u91CC\u96F2\u767E\u934A Coding Plan",
      "Bring your own API key": "\u4F7F\u7528\u81EA\u5DF1\u7684 API \u5BC6\u9470",
      "API-KEY": "API-KEY",
      "Browser-based authentication with third-party providers (e.g. OpenRouter, ModelScope)": "\u57FA\u65BC\u700F\u89BD\u5668\u7684\u7B2C\u4E09\u65B9\u63D0\u4F9B\u5546\u8A8D\u8B49\uFF08\u4F8B\u5982 OpenRouter\u3001ModelScope\uFF09",
      "Use coding plan credentials or your own api-keys/providers.": "\u4F7F\u7528 Coding Plan \u6191\u8B49\u6216\u60A8\u81EA\u5DF1\u7684 API \u5BC6\u9470/\u63D0\u4F9B\u5546\u3002",
      OpenAI: "OpenAI",
      "Failed to login. Message: {{message}}": "\u767B\u9304\u5931\u6557\u3002\u6D88\u606F\uFF1A{{message}}",
      "Authentication is enforced to be {{enforcedType}}, but you are currently using {{currentType}}.": "\u8A8D\u8B49\u65B9\u5F0F\u88AB\u5F37\u5236\u8A2D\u7F6E\u7232 {{enforcedType}}\uFF0C\u4F46\u60A8\u7576\u524D\u4F7F\u7528\u7684\u662F {{currentType}}",
      "Qwen OAuth authentication timed out. Please try again.": "Qwen OAuth \u8A8D\u8B49\u8D85\u6642\u3002\u8ACB\u91CD\u8A66",
      "Qwen OAuth authentication cancelled.": "Qwen OAuth \u8A8D\u8B49\u5DF2\u53D6\u6D88",
      "Qwen OAuth Authentication": "Qwen OAuth \u8A8D\u8B49",
      "Please visit this URL to authorize:": "\u8ACB\u8A2A\u554F\u6B64 URL \u9032\u884C\u6388\u6B0A\uFF1A",
      "Or scan the QR code below:": "\u6216\u6383\u63CF\u4E0B\u65B9\u7684\u4E8C\u7DAD\u78BC\uFF1A",
      "Waiting for authorization": "\u7B49\u5F85\u6388\u6B0A\u4E2D",
      "Time remaining:": "\u5269\u9918\u6642\u9593\uFF1A",
      "(Press ESC or CTRL+C to cancel)": "\uFF08\u6309 ESC \u6216 CTRL+C \u53D6\u6D88\uFF09",
      "Qwen OAuth Authentication Timeout": "Qwen OAuth \u8A8D\u8B49\u8D85\u6642",
      "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.": "OAuth \u4EE4\u724C\u5DF2\u904E\u671F\uFF08\u8D85\u904E {{seconds}} \u79D2\uFF09\u3002\u8ACB\u91CD\u65B0\u9078\u64C7\u8A8D\u8B49\u65B9\u6CD5",
      "Press any key to return to authentication type selection.": "\u6309\u4EFB\u610F\u9375\u8FD4\u56DE\u8A8D\u8B49\u985E\u578B\u9078\u64C7",
      "Waiting for Qwen OAuth authentication...": "\u6B63\u5728\u7B49\u5F85 Qwen OAuth \u8A8D\u8B49...",
      "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 \u6642\uFF0Csettings.json \u4E2D\u73FE\u6709\u7684 API \u5BC6\u9470\u4E0D\u6703\u88AB\u6E05\u9664\u3002\u5982\u679C\u9700\u8981\uFF0C\u60A8\u53EF\u4EE5\u7A0D\u5F8C\u5207\u63DB\u56DE OpenAI \u8A8D\u8B49\u3002",
      "Note: Your existing API key will not be cleared when using Qwen OAuth.": "\u6CE8\u610F\uFF1A\u4F7F\u7528 Qwen OAuth \u6642\uFF0C\u73FE\u6709\u7684 API \u5BC6\u9470\u4E0D\u6703\u88AB\u6E05\u9664\u3002",
      "Authentication timed out. Please try again.": "\u8A8D\u8B49\u8D85\u6642\u3002\u8ACB\u91CD\u8A66\u3002",
      "Waiting for auth... (Press ESC or CTRL+C to cancel)": "\u6B63\u5728\u7B49\u5F85\u8A8D\u8B49...\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\u8A8D\u8B49\u7684 API \u5BC6\u9470\u3002\u8ACB\u8A2D\u7F6E settings.security.auth.apiKey \u6216\u8A2D\u7F6E {{envKeyHint}} \u74B0\u5883\u8B8A\u91CF\u3002",
      "{{envKeyHint}} environment variable not found.": "\u672A\u627E\u5230 {{envKeyHint}} \u74B0\u5883\u8B8A\u91CF\u3002",
      "{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.": "\u672A\u627E\u5230 {{envKeyHint}} \u74B0\u5883\u8B8A\u91CF\u3002\u8ACB\u5728 .env \u6587\u4EF6\u6216\u7CFB\u7D71\u74B0\u5883\u8B8A\u91CF\u4E2D\u9032\u884C\u8A2D\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}} \u74B0\u5883\u8B8A\u91CF\uFF08\u6216\u8A2D\u7F6E settings.security.auth.apiKey\uFF09\u3002\u8ACB\u5728 .env \u6587\u4EF6\u6216\u7CFB\u7D71\u74B0\u5883\u8B8A\u91CF\u4E2D\u9032\u884C\u8A2D\u7F6E\u3002",
      "Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.": "\u7F3A\u5C11 OpenAI \u517C\u5BB9\u8A8D\u8B49\u7684 API \u5BC6\u9470\u3002\u8ACB\u8A2D\u7F6E {{envKeyHint}} \u74B0\u5883\u8B8A\u91CF\u3002",
      "Anthropic provider missing required baseUrl in modelProviders[].baseUrl.": "Anthropic \u63D0\u4F9B\u5546\u7F3A\u5C11\u5FC5\u9700\u7684 baseUrl\uFF0C\u8ACB\u5728 modelProviders[].baseUrl \u4E2D\u914D\u7F6E\u3002",
      "ANTHROPIC_BASE_URL environment variable not found.": "\u672A\u627E\u5230 ANTHROPIC_BASE_URL \u74B0\u5883\u8B8A\u91CF\u3002",
      "Invalid auth method selected.": "\u9078\u64C7\u4E86\u7121\u6548\u7684\u8A8D\u8B49\u65B9\u5F0F\u3002",
      "Failed to authenticate. Message: {{message}}": "\u8A8D\u8B49\u5931\u6557\u3002\u6D88\u606F\uFF1A{{message}}",
      "Authenticated successfully with {{authType}} credentials.": "\u4F7F\u7528 {{authType}} \u6191\u64DA\u6210\u529F\u8A8D\u8B49\u3002",
      'Invalid QWEN_DEFAULT_AUTH_TYPE value: "{{value}}". Valid values are: {{validValues}}': '\u7121\u6548\u7684 QWEN_DEFAULT_AUTH_TYPE \u503C\uFF1A"{{value}}"\u3002\u6709\u6548\u503C\u7232\uFF1A{{validValues}}',
      "OpenAI Configuration Required": "\u9700\u8981\u914D\u7F6E OpenAI",
      "Please enter your OpenAI configuration. You can get an API key from": "\u8ACB\u8F38\u5165\u60A8\u7684 OpenAI \u914D\u7F6E\u3002\u60A8\u53EF\u4EE5\u5F9E\u4EE5\u4E0B\u5730\u5740\u7372\u53D6 API \u5BC6\u9470\uFF1A",
      "API Key:": "API \u5BC6\u9470\uFF1A",
      "Invalid credentials: {{errorMessage}}": "\u6191\u64DA\u7121\u6548\uFF1A{{errorMessage}}",
      "Failed to validate credentials": "\u9A57\u8B49\u6191\u64DA\u5931\u6557",
      "Press Enter to continue, Tab/\u2191\u2193 to navigate, Esc to cancel": "\u6309 Enter \u7E7C\u7E8C\uFF0CTab/\u2191\u2193 \u5C0E\u822A\uFF0CEsc \u53D6\u6D88",
      "Select Model": "\u9078\u64C7\u6A21\u578B",
      "(Press Esc to close)": "\uFF08\u6309 Esc \u95DC\u9589\uFF09",
      "Current (effective) configuration": "\u7576\u524D\uFF08\u5BE6\u969B\u751F\u6548\uFF09\u914D\u7F6E",
      AuthType: "\u8A8D\u8B49\u65B9\u5F0F",
      "API Key": "API \u5BC6\u9470",
      unset: "\u672A\u8A2D\u7F6E",
      "(default)": "(\u9ED8\u8A8D)",
      "(set)": "(\u5DF2\u8A2D\u7F6E)",
      "(not set)": "(\u672A\u8A2D\u7F6E)",
      Modality: "\u6A21\u614B",
      "Context Window": "\u4E0A\u4E0B\u6587\u7A97\u53E3",
      text: "\u6587\u672C",
      "text-only": "\u7D14\u6587\u672C",
      image: "\u5716\u50CF",
      pdf: "PDF",
      audio: "\u97F3\u983B",
      video: "\u8996\u983B",
      "not set": "\u672A\u8A2D\u7F6E",
      none: "\u7121",
      unknown: "\u672A\u77E5",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "\u7121\u6CD5\u5207\u63DB\u5230\u6A21\u578B '{{modelId}}'.\n\n{{error}}",
      "Qwen 3.6 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.6 Plus \u2014 \u9AD8\u6548\u6DF7\u5408\u67B6\u69CB\uFF0C\u7DE8\u7A0B\u6027\u80FD\u696D\u754C\u9818\u5148",
      "The latest Qwen Vision model from Alibaba Cloud ModelStudio (version: qwen3-vl-plus-2025-09-23)": "\u4F86\u81EA\u963F\u91CC\u96F2 ModelStudio \u7684\u6700\u65B0 Qwen Vision \u6A21\u578B\uFF08\u7248\u672C\uFF1Aqwen3-vl-plus-2025-09-23\uFF09",
      "Manage folder trust settings": "\u7BA1\u7406\u6587\u4EF6\u593E\u4FE1\u4EFB\u8A2D\u7F6E",
      "Manage permission rules": "\u7BA1\u7406\u6B0A\u9650\u898F\u5247",
      Allow: "\u5141\u8A31",
      Ask: "\u8A62\u554F",
      Deny: "\u62D2\u7D55",
      Workspace: "\u5DE5\u4F5C\u5340",
      "Qwen Code won't ask before using allowed tools.": "Qwen Code \u4F7F\u7528\u5DF2\u5141\u8A31\u7684\u5DE5\u5177\u524D\u4E0D\u6703\u8A62\u554F\u3002",
      "Qwen Code will ask before using these tools.": "Qwen Code \u4F7F\u7528\u9019\u4E9B\u5DE5\u5177\u524D\u6703\u5148\u8A62\u554F\u3002",
      "Qwen Code is not allowed to use denied tools.": "Qwen Code \u4E0D\u5141\u8A31\u4F7F\u7528\u88AB\u62D2\u7D55\u7684\u5DE5\u5177\u3002",
      "Manage trusted directories for this workspace.": "\u7BA1\u7406\u6B64\u5DE5\u4F5C\u5340\u7684\u53D7\u4FE1\u4EFB\u76EE\u9304\u3002",
      "Any use of the {{tool}} tool": "{{tool}} \u5DE5\u5177\u7684\u4EFB\u4F55\u4F7F\u7528",
      "{{tool}} commands matching '{{pattern}}'": "\u5339\u914D '{{pattern}}' \u7684 {{tool}} \u547D\u4EE4",
      "From user settings": "\u4F86\u81EA\u7528\u6236\u8A2D\u7F6E",
      "From project settings": "\u4F86\u81EA\u9805\u76EE\u8A2D\u7F6E",
      "From session": "\u4F86\u81EA\u6703\u8A71",
      "Project settings (local)": "\u9805\u76EE\u8A2D\u7F6E\uFF08\u672C\u5730\uFF09",
      "Saved in .qwen/settings.local.json": "\u4FDD\u5B58\u5728 .qwen/settings.local.json",
      "Project settings": "\u9805\u76EE\u8A2D\u7F6E",
      "Checked in at .qwen/settings.json": "\u4FDD\u5B58\u5728 .qwen/settings.json",
      "User settings": "\u7528\u6236\u8A2D\u7F6E",
      "Saved in at ~/.qwen/settings.json": "\u4FDD\u5B58\u5728 ~/.qwen/settings.json",
      "Add a new rule\u2026": "\u6DFB\u52A0\u65B0\u898F\u5247\u2026",
      "Add {{type}} permission rule": "\u6DFB\u52A0{{type}}\u6B0A\u9650\u898F\u5247",
      "Permission rules are a tool name, optionally followed by a specifier in parentheses.": "\u6B0A\u9650\u898F\u5247\u662F\u4E00\u500B\u5DE5\u5177\u540D\u7A31\uFF0C\u53EF\u9078\u5730\u5F8C\u8DDF\u62EC\u865F\u4E2D\u7684\u9650\u5B9A\u7B26\u3002",
      "e.g.,": "\u4F8B\u5982",
      or: "\u6216",
      "Enter permission rule\u2026": "\u8F38\u5165\u6B0A\u9650\u898F\u5247\u2026",
      "Enter to submit \xB7 Esc to cancel": "\u56DE\u8ECA\u63D0\u4EA4 \xB7 Esc \u53D6\u6D88",
      "Where should this rule be saved?": "\u6B64\u898F\u5247\u61C9\u4FDD\u5B58\u5728\u54EA\u88CF\uFF1F",
      "Enter to confirm \xB7 Esc to cancel": "\u56DE\u8ECA\u78BA\u8A8D \xB7 Esc \u53D6\u6D88",
      "Delete {{type}} rule?": "\u522A\u9664{{type}}\u898F\u5247\uFF1F",
      "Are you sure you want to delete this permission rule?": "\u78BA\u5B9A\u8981\u522A\u9664\u6B64\u6B0A\u9650\u898F\u5247\u55CE\uFF1F",
      "Permissions:": "\u6B0A\u9650\uFF1A",
      "(\u2190/\u2192 or tab to cycle)": "\uFF08\u2190/\u2192 \u6216 tab \u5207\u63DB\uFF09",
      "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel": "\u6309 \u2191\u2193 \u5C0E\u822A \xB7 \u56DE\u8ECA\u9078\u64C7 \xB7 \u8F38\u5165\u641C\u7D22 \xB7 Esc \u53D6\u6D88",
      "Search\u2026": "\u641C\u7D22\u2026",
      "Use /trust to manage folder trust settings for this workspace.": "\u4F7F\u7528 /trust \u7BA1\u7406\u6B64\u5DE5\u4F5C\u5340\u7684\u6587\u4EF6\u593E\u4FE1\u4EFB\u8A2D\u7F6E\u3002",
      "Add directory\u2026": "\u6DFB\u52A0\u76EE\u9304\u2026",
      "Add directory to workspace": "\u6DFB\u52A0\u5DE5\u4F5C\u5340\u76EE\u9304",
      "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.": "Qwen Code \u53EF\u4EE5\u8B80\u53D6\u5DE5\u4F5C\u5340\u4E2D\u7684\u6587\u4EF6\uFF0C\u4E26\u5728\u81EA\u52D5\u63A5\u53D7\u7DE8\u8F2F\u6A21\u5F0F\u958B\u5553\u6642\u9032\u884C\u7DE8\u8F2F\u3002",
      "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.": "Qwen Code \u5C07\u80FD\u5920\u8B80\u53D6\u6B64\u76EE\u9304\u4E2D\u7684\u6587\u4EF6\uFF0C\u4E26\u5728\u81EA\u52D5\u63A5\u53D7\u7DE8\u8F2F\u6A21\u5F0F\u958B\u5553\u6642\u9032\u884C\u7DE8\u8F2F\u3002",
      "Enter the path to the directory:": "\u8F38\u5165\u76EE\u9304\u8DEF\u5F91\uFF1A",
      "Enter directory path\u2026": "\u8F38\u5165\u76EE\u9304\u8DEF\u5F91\u2026",
      "Tab to complete \xB7 Enter to add \xB7 Esc to cancel": "Tab \u88DC\u5168 \xB7 \u56DE\u8ECA\u6DFB\u52A0 \xB7 Esc \u53D6\u6D88",
      "Remove directory?": "\u522A\u9664\u76EE\u9304\uFF1F",
      "Are you sure you want to remove this directory from the workspace?": "\u78BA\u5B9A\u8981\u5C07\u6B64\u76EE\u9304\u5F9E\u5DE5\u4F5C\u5340\u4E2D\u79FB\u9664\u55CE\uFF1F",
      "  (Original working directory)": "  \uFF08\u539F\u59CB\u5DE5\u4F5C\u76EE\u9304\uFF09",
      "  (from settings)": "  \uFF08\u4F86\u81EA\u8A2D\u7F6E\uFF09",
      "Directory does not exist.": "\u76EE\u9304\u4E0D\u5B58\u5728\u3002",
      "Path is not a directory.": "\u8DEF\u5F91\u4E0D\u662F\u76EE\u9304\u3002",
      "This directory is already in the workspace.": "\u6B64\u76EE\u9304\u5DF2\u5728\u5DE5\u4F5C\u5340\u4E2D\u3002",
      "Already covered by existing directory: {{dir}}": "\u5DF2\u88AB\u73FE\u6709\u76EE\u9304\u8986\u84CB\uFF1A{{dir}}",
      "Using:": "\u5DF2\u52A0\u8F09: ",
      "{{count}} open file": "{{count}} \u500B\u6253\u958B\u7684\u6587\u4EF6",
      "{{count}} open files": "{{count}} \u500B\u6253\u958B\u7684\u6587\u4EF6",
      "(ctrl+g to view)": "\uFF08\u6309 ctrl+g \u67E5\u770B\uFF09",
      "{{count}} {{name}} file": "{{count}} \u500B {{name}} \u6587\u4EF6",
      "{{count}} {{name}} files": "{{count}} \u500B {{name}} \u6587\u4EF6",
      "{{count}} MCP server": "{{count}} \u500B MCP \u670D\u52D9\u5668",
      "{{count}} MCP servers": "{{count}} \u500B MCP \u670D\u52D9\u5668",
      "{{count}} Blocked": "{{count}} \u500B\u5DF2\u963B\u6B62",
      "(ctrl+t to view)": "\uFF08\u6309 ctrl+t \u67E5\u770B\uFF09",
      "(ctrl+t to toggle)": "\uFF08\u6309 ctrl+t \u5207\u63DB\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",
      "Press \u2191 to edit queued messages": "\u6309 \u2191 \u7DE8\u8F2F\u6392\u968A\u6D88\u606F",
      "No MCP servers configured.": "\u672A\u914D\u7F6E MCP \u670D\u52D9\u5668",
      "\u23F3 MCP servers are starting up ({{count}} initializing)...": "\u23F3 MCP \u670D\u52D9\u5668\u6B63\u5728\u5553\u52D5\uFF08{{count}} \u500B\u6B63\u5728\u521D\u59CB\u5316\uFF09...",
      "Note: First startup may take longer. Tool availability will update automatically.": "\u6CE8\u610F\uFF1A\u9996\u6B21\u5553\u52D5\u53EF\u80FD\u9700\u8981\u66F4\u9577\u6642\u9593\u3002\u5DE5\u5177\u53EF\u7528\u6027\u5C07\u81EA\u52D5\u66F4\u65B0",
      "Configured MCP servers:": "\u5DF2\u914D\u7F6E\u7684 MCP \u670D\u52D9\u5668\uFF1A",
      Ready: "\u5C31\u7DD2",
      "Starting... (first startup may take longer)": "\u6B63\u5728\u5553\u52D5...\uFF08\u9996\u6B21\u5553\u52D5\u53EF\u80FD\u9700\u8981\u66F4\u9577\u6642\u9593\uFF09",
      Disconnected: "\u5DF2\u65B7\u958B\u9023\u63A5",
      "{{count}} tool": "{{count}} \u500B\u5DE5\u5177",
      "{{count}} tools": "{{count}} \u500B\u5DE5\u5177",
      "{{count}} prompt": "{{count}} \u500B\u63D0\u793A",
      "{{count}} prompts": "{{count}} \u500B\u63D0\u793A",
      "(from {{extensionName}})": "\uFF08\u4F86\u81EA {{extensionName}}\uFF09",
      OAuth: "OAuth",
      "OAuth expired": "OAuth \u5DF2\u904E\u671F",
      "OAuth not authenticated": "OAuth \u672A\u8A8D\u8B49",
      "tools and prompts will appear when ready": "\u5DE5\u5177\u548C\u63D0\u793A\u5C07\u5728\u5C31\u7DD2\u6642\u986F\u793A",
      "{{count}} tools cached": "{{count}} \u500B\u5DE5\u5177\u5DF2\u7DE9\u5B58",
      "Tools:": "\u5DE5\u5177\uFF1A",
      "Parameters:": "\u53C3\u6578\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": "\u986F\u793A\u670D\u52D9\u5668\u548C\u5DE5\u5177\u63CF\u8FF0",
      "to show tool parameter schemas": "\u986F\u793A\u5DE5\u5177\u53C3\u6578\u67B6\u69CB",
      "to hide descriptions": "\u96B1\u85CF\u63CF\u8FF0",
      "to authenticate with OAuth-enabled servers": "\u4F7F\u7528\u652F\u6301 OAuth \u7684\u670D\u52D9\u5668\u9032\u884C\u8A8D\u8B49",
      Press: "\u6309",
      "to toggle tool descriptions on/off": "\u5207\u63DB\u5DE5\u5177\u63CF\u8FF0\u958B\u95DC",
      "Starting OAuth authentication for MCP server '{{name}}'...": "\u6B63\u5728\u7232 MCP \u670D\u52D9\u5668 '{{name}}' \u5553\u52D5 OAuth \u8A8D\u8B49...",
      "Restarting MCP servers...": "\u6B63\u5728\u91CD\u5553 MCP \u670D\u52D9\u5668...",
      "Tips:": "\u63D0\u793A\uFF1A",
      "Use /compress when the conversation gets long to summarize history and free up context.": "\u5C0D\u8A71\u8B8A\u9577\u6642\u7528 /compress\uFF0C\u7E3D\u7D50\u6B77\u53F2\u4E26\u91CB\u653E\u4E0A\u4E0B\u6587\u3002",
      "Start a fresh idea with /clear or /new; the previous session stays available in history.": "\u7528 /clear \u6216 /new \u958B\u5553\u65B0\u601D\u8DEF\uFF1B\u4E4B\u524D\u7684\u6703\u8A71\u6703\u4FDD\u7559\u5728\u6B77\u53F2\u8A18\u9304\u4E2D\u3002",
      "Use /bug to submit issues to the maintainers when something goes off.": "\u9047\u5230\u554F\u984C\u6642\uFF0C\u7528 /bug \u5C07\u554F\u984C\u63D0\u4EA4\u7D66\u7DAD\u8B77\u8005\u3002",
      "Switch auth type quickly with /auth.": "\u7528 /auth \u5FEB\u901F\u5207\u63DB\u8A8D\u8B49\u65B9\u5F0F\u3002",
      "You can run any shell commands from Qwen Code using ! (e.g. !ls).": "\u5728 Qwen Code \u4E2D\u4F7F\u7528 ! \u53EF\u904B\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.": "\u8F38\u5165 / \u6253\u958B\u547D\u4EE4\u5F48\u7A97\uFF1B\u6309 Tab \u81EA\u52D5\u88DC\u5168\u659C\u69D3\u547D\u4EE4\u548C\u4FDD\u5B58\u7684\u63D0\u793A\u8A5E\u3002",
      "You can resume a previous conversation by running qwen --continue or qwen --resume.": "\u904B\u884C qwen --continue \u6216 qwen --resume \u53EF\u7E7C\u7E8C\u4E4B\u524D\u7684\u6703\u8A71\u3002",
      "You can switch permission mode quickly with Shift+Tab or /approval-mode.": "\u6309 Shift+Tab \u6216\u8F38\u5165 /approval-mode \u53EF\u5FEB\u901F\u5207\u63DB\u6B0A\u9650\u6A21\u5F0F\u3002",
      "You can switch permission mode quickly with Tab or /approval-mode.": "\u6309 Tab \u6216\u8F38\u5165 /approval-mode \u53EF\u5FEB\u901F\u5207\u63DB\u6B0A\u9650\u6A21\u5F0F\u3002",
      "Try /insight to generate personalized insights from your chat history.": "\u8A66\u8A66 /insight\uFF0C\u5F9E\u804A\u5929\u8A18\u9304\u4E2D\u751F\u6210\u500B\u6027\u5316\u6D1E\u5BDF\u3002",
      "Press Ctrl+O to toggle compact mode \u2014 hide tool output and thinking for a cleaner view.": "\u6309 Ctrl+O \u5207\u63DB\u7DCA\u6E4A\u6A21\u5F0F \u2500\u2500 \u96B1\u85CF\u5DE5\u5177\u8F38\u51FA\u548C\u601D\u8003\u904E\u7A0B\uFF0C\u754C\u9762\u66F4\u7C21\u6F54\u3002",
      "Add a QWEN.md file to give Qwen Code persistent project context.": "\u6DFB\u52A0 QWEN.md \u6587\u4EF6\uFF0C\u7232 Qwen Code \u63D0\u4F9B\u6301\u4E45\u7684\u9805\u76EE\u4E0A\u4E0B\u6587\u3002",
      "Use /btw to ask a quick side question without disrupting the conversation.": "\u7528 /btw \u5FEB\u901F\u554F\u4E00\u500B\u5C0F\u554F\u984C\uFF0C\u4E0D\u6703\u6253\u65B7\u7576\u524D\u5C0D\u8A71\u3002",
      "Context is almost full! Run /compress now or start /new to continue.": "\u4E0A\u4E0B\u6587\u5373\u5C07\u7528\u6EFF\uFF01\u8ACB\u7ACB\u5373\u57F7\u884C /compress \u6216\u4F7F\u7528 /new \u958B\u5553\u65B0\u6703\u8A71\u3002",
      "Context is getting full. Use /compress to free up space.": "\u4E0A\u4E0B\u6587\u7A7A\u9593\u4E0D\u8DB3\uFF0C\u7528 /compress \u91CB\u653E\u7A7A\u9593\u3002",
      "Long conversation? /compress summarizes history to free context.": "\u5C0D\u8A71\u592A\u9577\uFF1F\u7528 /compress \u7E3D\u7D50\u6B77\u53F2\uFF0C\u91CB\u653E\u4E0A\u4E0B\u6587\u3002",
      "Agent powering down. Goodbye!": "Qwen Code \u6B63\u5728\u95DC\u9589\uFF0C\u518D\u898B\uFF01",
      "To continue this session, run": "\u8981\u7E7C\u7E8C\u6B64\u6703\u8A71\uFF0C\u8ACB\u904B\u884C",
      "Interaction Summary": "\u4EA4\u4E92\u6458\u8981",
      "Session ID:": "\u6703\u8A71 ID\uFF1A",
      "Tool Calls:": "\u5DE5\u5177\u8ABF\u7528\uFF1A",
      "Success Rate:": "\u6210\u529F\u7387\uFF1A",
      "User Agreement:": "\u7528\u6236\u540C\u610F\u7387\uFF1A",
      reviewed: "\u5DF2\u5BE9\u8988",
      "Code Changes:": "\u4EE3\u78BC\u8B8A\u66F4\uFF1A",
      Performance: "\u6027\u80FD",
      "Wall Time:": "\u7E3D\u8017\u6642\uFF1A",
      "Agent Active:": "\u667A\u80FD\u9AD4\u6D3B\u8E8D\u6642\u9593\uFF1A",
      "API Time:": "API \u6642\u9593\uFF1A",
      "Tool Time:": "\u5DE5\u5177\u6642\u9593\uFF1A",
      "Session Stats": "\u6703\u8A71\u7D71\u8A08",
      "Model Usage": "\u6A21\u578B\u4F7F\u7528\u60C5\u6CC1",
      Reqs: "\u8ACB\u6C42\u6578",
      "Input Tokens": "\u8F38\u5165 token \u6578",
      "Output Tokens": "\u8F38\u51FA token \u6578",
      "Savings Highlight:": "\u7BC0\u7701\u4EAE\u9EDE\uFF1A",
      "of input tokens were served from the cache, reducing costs.": "\u5F9E\u7DE9\u5B58\u8F09\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\u7D30\uFF0C\u8ACB\u904B\u884C `/stats model`",
      "Model Stats For Nerds": "\u6A21\u578B\u7D71\u8A08\uFF08\u6280\u8853\u7D30\u7BC0\uFF09",
      "Tool Stats For Nerds": "\u5DE5\u5177\u7D71\u8A08\uFF08\u6280\u8853\u7D30\u7BC0\uFF09",
      Metric: "\u6307\u6A19",
      API: "API",
      Requests: "\u8ACB\u6C42\u6578",
      Errors: "\u932F\u8AA4\u6578",
      "Avg Latency": "\u5E73\u5747\u5EF6\u9072",
      Tokens: "\u4EE4\u724C",
      Total: "\u7E3D\u8A08",
      Prompt: "\u63D0\u793A",
      Cached: "\u7DE9\u5B58",
      Thoughts: "\u601D\u8003",
      Tool: "\u5DE5\u5177",
      Output: "\u8F38\u51FA",
      "No API calls have been made in this session.": "\u672C\u6B21\u6703\u8A71\u4E2D\u672A\u9032\u884C\u4EFB\u4F55 API \u8ABF\u7528",
      "Tool Name": "\u5DE5\u5177\u540D\u7A31",
      Calls: "\u8ABF\u7528\u6B21\u6578",
      "Success Rate": "\u6210\u529F\u7387",
      "Avg Duration": "\u5E73\u5747\u8017\u6642",
      "User Decision Summary": "\u7528\u6236\u6C7A\u7B56\u6458\u8981",
      "Total Reviewed Suggestions:": "\u5DF2\u5BE9\u8988\u5EFA\u8B70\u7E3D\u6578\uFF1A",
      " \xBB Accepted:": " \xBB \u5DF2\u63A5\u53D7\uFF1A",
      " \xBB Rejected:": " \xBB \u5DF2\u62D2\u7D55\uFF1A",
      " \xBB Modified:": " \xBB \u5DF2\u4FEE\u6539\uFF1A",
      " Overall Agreement Rate:": " \u7E3D\u9AD4\u540C\u610F\u7387\uFF1A",
      "No tool calls have been made in this session.": "\u672C\u6B21\u6703\u8A71\u4E2D\u672A\u9032\u884C\u4EFB\u4F55\u5DE5\u5177\u8ABF\u7528",
      "Session start time is unavailable, cannot calculate stats.": "\u6703\u8A71\u958B\u59CB\u6642\u9593\u4E0D\u53EF\u7528\uFF0C\u7121\u6CD5\u8A08\u7B97\u7D71\u8A08\u4FE1\u606F",
      "Command Format Migration": "\u547D\u4EE4\u683C\u5F0F\u9077\u79FB",
      "Found {{count}} TOML command file:": "\u767C\u73FE {{count}} \u500B TOML \u547D\u4EE4\u6587\u4EF6\uFF1A",
      "Found {{count}} TOML command files:": "\u767C\u73FE {{count}} \u500B TOML \u547D\u4EE4\u6587\u4EF6\uFF1A",
      "Current tasks": "\u76EE\u524D\u4EFB\u52D9",
      "... and {{count}} more": "... \u4EE5\u53CA\u5176\u4ED6 {{count}} \u500B",
      "The TOML format is deprecated. Would you like to migrate them to Markdown format?": "TOML \u683C\u5F0F\u5DF2\u68C4\u7528\u3002\u662F\u5426\u5C07\u5B83\u5011\u9077\u79FB\u5230 Markdown \u683C\u5F0F\uFF1F",
      "(Backups will be created and original files will be preserved)": "\uFF08\u5C07\u5275\u5EFA\u5099\u4EFD\uFF0C\u539F\u59CB\u6587\u4EF6\u5C07\u4FDD\u7559\uFF09",
      "Waiting for user confirmation...": "\u7B49\u5F85\u7528\u6236\u78BA\u8A8D...",
      "(esc to cancel, {{time}})": "\uFF08\u6309 esc \u53D6\u6D88\uFF0C{{time}}\uFF09",
      WITTY_LOADING_PHRASES: [
        "\u6B63\u5728\u52AA\u529B\u642C\u78DA\uFF0C\u8ACB\u7A0D\u5019...",
        "\u8001\u95C6\u5728\u8EAB\u5F8C\uFF0C\u5FEB\u52A0\u8F09\u554A\uFF01",
        "\u982D\u9AEE\u6389\u5149\u524D\uFF0C\u4E00\u5B9A\u80FD\u52A0\u8F09\u5B8C...",
        "\u670D\u52D9\u5668\u6B63\u5728\u6DF1\u547C\u5438\uFF0C\u6E96\u5099\u653E\u5927\u62DB...",
        "\u6B63\u5728\u5411\u670D\u52D9\u5668\u6295\u9935\u5496\u5561...",
        "\u6B63\u5728\u8CE6\u80FD\u5168\u93C8\u8DEF\uFF0C\u5C0B\u627E\u95DC\u9375\u6293\u624B...",
        "\u6B63\u5728\u964D\u672C\u589E\u6548\uFF0C\u512A\u5316\u52A0\u8F09\u8DEF\u5F91...",
        "\u6B63\u5728\u6253\u7834\u90E8\u9580\u58C1\u58D8\uFF0C\u6C89\u6FB1\u65B9\u6CD5\u8AD6...",
        "\u6B63\u5728\u64C1\u62B1\u8B8A\u5316\uFF0C\u8FED\u4EE3\u6838\u5FC3\u50F9\u503C...",
        "\u6B63\u5728\u5C0D\u9F4A\u9846\u7C92\u5EA6\uFF0C\u6253\u78E8\u5E95\u5C64\u908F\u8F2F...",
        "\u5927\u529B\u51FA\u5947\u8DE1\uFF0C\u6B63\u5728\u5F37\u884C\u52A0\u8F09...",
        "\u53EA\u8981\u6211\u4E0D\u5BEB\u4EE3\u78BC\uFF0C\u4EE3\u78BC\u5C31\u6C92\u6709 Bug...",
        "\u6B63\u5728\u628A Bug \u8F49\u5316\u7232 Feature...",
        "\u53EA\u8981\u6211\u4E0D\u5C37\u5C2C\uFF0CBug \u5C31\u8FFD\u4E0D\u4E0A\u6211...",
        "\u6B63\u5728\u8A66\u5716\u7406\u89E3\u53BB\u5E74\u7684\u81EA\u5DF1\u5BEB\u4E86\u4EC0\u9EBC...",
        "\u6B63\u5728\u733F\u529B\u89BA\u9192\u4E2D\uFF0C\u8ACB\u8010\u5FC3\u7B49\u5F85...",
        "\u6B63\u5728\u8A62\u554F\u7522\u54C1\u7D93\u7406\uFF1A\u9019\u9700\u6C42\u662F\u771F\u7684\u55CE\uFF1F",
        "\u6B63\u5728\u7D66\u7522\u54C1\u7D93\u7406\u756B\u9905\uFF0C\u8ACB\u7A0D\u7B49...",
        "\u6BCF\u4E00\u884C\u4EE3\u78BC\uFF0C\u90FD\u5728\u52AA\u529B\u8B93\u4E16\u754C\u8B8A\u5F97\u66F4\u597D\u4E00\u9EDE\u9EDE...",
        "\u6BCF\u4E00\u500B\u5049\u5927\u7684\u60F3\u6CD5\uFF0C\u90FD\u503C\u5F97\u9019\u4EFD\u8010\u5FC3\u7684\u7B49\u5F85...",
        "\u5225\u6025\uFF0C\u7F8E\u597D\u7684\u4E8B\u7269\u7E3D\u662F\u9700\u8981\u4E00\u9EDE\u6642\u9593\u53BB\u919E\u91C0...",
        "\u9858\u4F60\u7684\u4EE3\u78BC\u6C38\u7121 Bug\uFF0C\u9858\u4F60\u7684\u5922\u60F3\u7D42\u5C07\u6210\u771F...",
        "\u54EA\u6015\u53EA\u6709 0.1% \u7684\u9032\u5EA6\uFF0C\u4E5F\u662F\u5728\u5411\u76EE\u6A19\u9760\u8FD1...",
        "\u52A0\u8F09\u7684\u662F\u5B57\u7BC0\uFF0C\u627F\u8F09\u7684\u662F\u5C0D\u6280\u8853\u7684\u71B1\u611B..."
      ],
      "Enter value...": "\u8ACB\u8F38\u5165\u503C...",
      "Enter sensitive value...": "\u8ACB\u8F38\u5165\u654F\u611F\u503C...",
      "Press Enter to submit, Escape to cancel": "\u6309 Enter \u63D0\u4EA4\uFF0CEscape \u53D6\u6D88",
      "Markdown file already exists: {{filename}}": "Markdown \u6587\u4EF6\u5DF2\u5B58\u5728\uFF1A{{filename}}",
      "TOML Command Format Deprecation Notice": "TOML \u547D\u4EE4\u683C\u5F0F\u68C4\u7528\u901A\u77E5",
      "Found {{count}} command file(s) in TOML format:": "\u767C\u73FE {{count}} \u500B 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\u68C4\u7528\uFF0C\u63A8\u85A6\u4F7F\u7528 Markdown \u683C\u5F0F\u3002",
      "Markdown format is more readable and easier to edit.": "Markdown \u683C\u5F0F\u66F4\u6613\u8B80\u3001\u66F4\u6613\u7DE8\u8F2F\u3002",
      "You can migrate these files automatically using:": "\u60A8\u53EF\u4EE5\u4F7F\u7528\u4EE5\u4E0B\u547D\u4EE4\u81EA\u52D5\u9077\u79FB\u9019\u4E9B\u6587\u4EF6\uFF1A",
      "Or manually convert each file:": "\u6216\u624B\u52D5\u8F49\u63DB\u6BCF\u500B\u6587\u4EF6\uFF1A",
      'TOML: prompt = "..." / description = "..."': 'TOML\uFF1Aprompt = "..." / description = "..."',
      "Markdown: YAML frontmatter + content": "Markdown\uFF1AYAML frontmatter + \u5167\u5BB9",
      "The migration tool will:": "\u9077\u79FB\u5DE5\u5177\u5C07\uFF1A",
      "Convert TOML files to Markdown": "\u5C07 TOML \u6587\u4EF6\u8F49\u63DB\u7232 Markdown",
      "Create backups of original files": "\u5275\u5EFA\u539F\u59CB\u6587\u4EF6\u7684\u5099\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\u8B70\u9077\u79FB\u3002",
      "Open extensions page in your browser": "\u5728\u700F\u89BD\u5668\u4E2D\u6253\u958B\u64F4\u5C55\u5E02\u5834\u9801\u9762",
      "Unknown extensions source: {{source}}.": "\u672A\u77E5\u7684\u64F4\u5C55\u4F86\u6E90\uFF1A{{source}}\u3002",
      "Would open extensions page in your browser: {{url}} (skipped in test environment)": "\u5C07\u5728\u700F\u89BD\u5668\u4E2D\u6253\u958B\u64F4\u5C55\u9801\u9762\uFF1A{{url}}\uFF08\u6E2C\u8A66\u74B0\u5883\u4E2D\u5DF2\u8DF3\u904E\uFF09",
      "View available extensions at {{url}}": "\u5728 {{url}} \u67E5\u770B\u53EF\u7528\u64F4\u5C55",
      "Opening extensions page in your browser: {{url}}": "\u6B63\u5728\u700F\u89BD\u5668\u4E2D\u6253\u958B\u64F4\u5C55\u9801\u9762\uFF1A{{url}}",
      "Failed to open browser. Check out the extensions gallery at {{url}}": "\u6253\u958B\u700F\u89BD\u5668\u5931\u6557\u3002\u8ACB\u8A2A\u554F\u64F4\u5C55\u5E02\u5834\uFF1A{{url}}",
      "Rate limit error: {{reason}}": "\u89F8\u767C\u9650\u6D41\uFF1A{{reason}}",
      "Retrying in {{seconds}} seconds\u2026 (attempt {{attempt}}/{{maxRetries}})": "\u5C07\u65BC {{seconds}} \u79D2\u5F8C\u91CD\u8A66\u2026\uFF08\u7B2C {{attempt}}/{{maxRetries}} \u6B21\uFF09",
      "Press Ctrl+Y to retry": "\u6309 Ctrl+Y \u91CD\u8A66\u3002",
      "No failed request to retry.": "\u6C92\u6709\u53EF\u91CD\u8A66\u7684\u5931\u6557\u8ACB\u6C42\u3002",
      "to retry last request": "\u91CD\u8A66\u4E0A\u4E00\u6B21\u8ACB\u6C42",
      "API key cannot be empty.": "API Key \u4E0D\u80FD\u7232\u7A7A\u3002",
      'Invalid API key. Coding Plan API keys start with "sk-sp-". Please check.': '\u7121\u6548\u7684 API Key\uFF0CCoding Plan API Key \u5747\u4EE5 "sk-sp-" \u958B\u982D\uFF0C\u8ACB\u6AA2\u67E5',
      "You can get your Coding Plan API key here": "\u60A8\u53EF\u4EE5\u5728\u9019\u88CF\u7372\u53D6 Coding Plan API Key",
      "API key is stored in settings.env. You can migrate it to a .env file for better security.": "API Key \u5DF2\u5B58\u5132\u5728 settings.env \u4E2D\u3002\u60A8\u53EF\u4EE5\u5C07\u5176\u9077\u79FB\u5230 .env \u6587\u4EF6\u4EE5\u7372\u5F97\u66F4\u597D\u7684\u5B89\u5168\u6027\u3002",
      "New model configurations are available for Alibaba Cloud Coding Plan. Update now?": "\u963F\u91CC\u96F2\u767E\u934A 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\u73FE\u5DF2\u53EF\u7528\u3002",
      "Coding Plan API key not found. Please re-authenticate with Coding Plan.": "\u672A\u627E\u5230 Coding Plan API Key\u3002\u8ACB\u91CD\u65B0\u901A\u904E Coding Plan \u8A8D\u8B49\u3002",
      "Failed to update Coding Plan configuration: {{message}}": "\u66F4\u65B0 Coding Plan \u914D\u7F6E\u5931\u6557\uFF1A{{message}}",
      "You can configure your API key and models in settings.json": "\u60A8\u53EF\u4EE5\u5728 settings.json \u4E2D\u914D\u7F6E API Key \u548C\u6A21\u578B",
      "Refer to the documentation for setup instructions": "\u8ACB\u53C3\u8003\u6587\u6A94\u77AD\u89E3\u914D\u7F6E\u8AAA\u660E",
      "Coding Plan": "Coding Plan",
      "Paste your api key of ModelStudio Coding Plan and you're all set!": "\u7C98\u8CBC\u60A8\u7684\u767E\u934A Coding Plan API Key\uFF0C\u5373\u53EF\u5B8C\u6210\u8A2D\u7F6E\uFF01",
      Custom: "\u81EA\u5B9A\u7FA9",
      "More instructions about configuring `modelProviders` manually.": "\u95DC\u65BC\u624B\u52D5\u914D\u7F6E `modelProviders` \u7684\u66F4\u591A\u8AAA\u660E\u3002",
      "Select API-KEY configuration mode:": "\u9078\u64C7 API-KEY \u914D\u7F6E\u6A21\u5F0F\uFF1A",
      "(Press Escape to go back)": "(\u6309 Escape \u9375\u8FD4\u56DE)",
      "(Press Enter to submit, Escape to cancel)": "(\u6309 Enter \u63D0\u4EA4\uFF0CEscape \u53D6\u6D88)",
      "Select Region for Coding Plan": "\u9078\u64C7 Coding Plan \u5340\u57DF",
      "Choose based on where your account is registered": "\u8ACB\u6839\u64DA\u60A8\u7684\u8CEC\u865F\u8A3B\u518A\u5730\u5340\u9078\u64C7",
      "Enter Coding Plan API Key": "\u8F38\u5165 Coding Plan API Key",
      "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",
      '{{region}} configuration updated successfully. Model switched to "{{model}}".': '{{region}} \u914D\u7F6E\u66F4\u65B0\u6210\u529F\u3002\u6A21\u578B\u5DF2\u5207\u63DB\u81F3 "{{model}}"\u3002',
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json (backed up).": "\u6210\u529F\u901A\u904E {{region}} \u8A8D\u8B49\u3002API Key \u548C\u6A21\u578B\u914D\u7F6E\u5DF2\u4FDD\u5B58\u81F3 settings.json\uFF08\u5DF2\u5099\u4EFD\uFF09\u3002",
      "Context Usage": "\u4E0A\u4E0B\u6587\u4F7F\u7528\u60C5\u6CC1",
      "% used": "% \u5DF2\u7528",
      "% context used": "% \u4E0A\u4E0B\u6587\u5DF2\u7528",
      "Context exceeds limit! Use /compress or /clear to reduce.": "\u4E0A\u4E0B\u6587\u8D85\u51FA\u9650\u5236\uFF01\u8ACB\u4F7F\u7528 /compress \u6216 /clear \u4F86\u6E1B\u5C11\u4E0A\u4E0B\u6587\u3002",
      "Use /compress or /clear": "\u4F7F\u7528 /compress \u6216 /clear",
      "No API response yet. Send a message to see actual usage.": "\u66AB\u7121 API \u97FF\u61C9\u3002\u767C\u9001\u6D88\u606F\u4EE5\u67E5\u770B\u5BE6\u969B\u4F7F\u7528\u60C5\u6CC1\u3002",
      "Estimated pre-conversation overhead": "\u9810\u4F30\u5C0D\u8A71\u524D\u958B\u92B7",
      "Context window": "\u4E0A\u4E0B\u6587\u7A97\u53E3",
      tokens: "tokens",
      Used: "\u5DF2\u7528",
      Free: "\u7A7A\u9592",
      "Autocompact buffer": "\u81EA\u52D5\u58D3\u7E2E\u7DE9\u885D\u5340",
      "Usage by category": "\u5206\u985E\u7528\u91CF",
      "System prompt": "\u7CFB\u7D71\u63D0\u793A",
      "Built-in tools": "\u5167\u7F6E\u5DE5\u5177",
      "MCP tools": "MCP \u5DE5\u5177",
      "Memory files": "\u8A18\u61B6\u6587\u4EF6",
      Skills: "\u6280\u80FD",
      Messages: "\u6D88\u606F",
      "Show context window usage breakdown.": "\u986F\u793A\u4E0A\u4E0B\u6587\u7A97\u53E3\u4F7F\u7528\u60C5\u6CC1\u5206\u89E3\u3002",
      "Run /context detail for per-item breakdown.": "\u904B\u884C /context detail \u67E5\u770B\u8A73\u7D30\u5206\u89E3\u3002",
      'Show context window usage breakdown. Use "/context detail" for per-item breakdown.': '\u986F\u793A\u4E0A\u4E0B\u6587\u7A97\u53E3\u4F7F\u7528\u60C5\u6CC1\u5206\u89E3\u3002\u8F38\u5165 "/context detail" \u67E5\u770B\u8A73\u7D30\u5206\u89E3\u3002',
      "body loaded": "\u5167\u5BB9\u5DF2\u52A0\u8F09",
      memory: "\u8A18\u61B6",
      "{{region}} configuration updated successfully.": "{{region}} \u914D\u7F6E\u66F4\u65B0\u6210\u529F\u3002",
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json.": "\u6210\u529F\u901A\u904E {{region}} \u8A8D\u8B49\u3002API Key \u548C\u6A21\u578B\u914D\u7F6E\u5DF2\u4FDD\u5B58\u81F3 settings.json\u3002",
      "Tip: Use /model to switch between available Coding Plan models.": "\u63D0\u793A\uFF1A\u4F7F\u7528 /model \u5207\u63DB\u53EF\u7528\u7684 Coding Plan \u6A21\u578B\u3002",
      "Please answer the following question(s):": "\u8ACB\u56DE\u7B54\u4EE5\u4E0B\u554F\u984C\uFF1A",
      "Cannot ask user questions in non-interactive mode. Please run in interactive mode to use this tool.": "\u7121\u6CD5\u5728\u975E\u4EA4\u4E92\u6A21\u5F0F\u4E0B\u8A62\u554F\u7528\u6236\u554F\u984C\u3002\u8ACB\u5728\u4EA4\u4E92\u6A21\u5F0F\u4E0B\u904B\u884C\u4EE5\u4F7F\u7528\u6B64\u5DE5\u5177\u3002",
      "User declined to answer the questions.": "\u7528\u6236\u62D2\u7D55\u56DE\u7B54\u554F\u984C\u3002",
      "User has provided the following answers:": "\u7528\u6236\u63D0\u4F9B\u4E86\u4EE5\u4E0B\u7B54\u6848\uFF1A",
      "Failed to process user answers:": "\u8655\u7406\u7528\u6236\u7B54\u6848\u5931\u6557\uFF1A",
      "Type something...": "\u8F38\u5165\u5167\u5BB9...",
      Submit: "\u63D0\u4EA4",
      "Submit answers": "\u63D0\u4EA4\u7B54\u6848",
      Cancel: "\u53D6\u6D88",
      "Your answers:": "\u60A8\u7684\u7B54\u6848\uFF1A",
      "(not answered)": "(\u672A\u56DE\u7B54)",
      "Ready to submit your answers?": "\u6E96\u5099\u597D\u63D0\u4EA4\u60A8\u7684\u7B54\u6848\u4E86\u55CE\uFF1F",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select": "\u2191/\u2193: \u5C0E\u822A | \u2190/\u2192: \u5207\u63DB\u6A19\u7C64\u9801 | Enter: \u9078\u64C7",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: \u5C0E\u822A | \u2190/\u2192: \u5207\u63DB\u6A19\u7C64\u9801 | Space/Enter: \u5207\u63DB | Esc: \u53D6\u6D88",
      "\u2191/\u2193: Navigate | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: \u5C0E\u822A | Space/Enter: \u5207\u63DB | Esc: \u53D6\u6D88",
      "\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel": "\u2191/\u2193: \u5C0E\u822A | Enter: \u9078\u64C7 | Esc: \u53D6\u6D88",
      "Configure Qwen authentication information with Qwen-OAuth or Alibaba Cloud Coding Plan": "\u4F7F\u7528 Qwen OAuth \u6216\u963F\u91CC\u96F2\u767E\u934A Coding Plan \u914D\u7F6E Qwen \u8A8D\u8B49\u4FE1\u606F",
      "Authenticate using Qwen OAuth": "\u4F7F\u7528 Qwen OAuth \u9032\u884C\u8A8D\u8B49",
      "Authenticate using Alibaba Cloud Coding Plan": "\u4F7F\u7528\u963F\u91CC\u96F2\u767E\u934A Coding Plan \u9032\u884C\u8A8D\u8B49",
      "Region for Coding Plan (china/global)": "Coding Plan \u5340\u57DF (china/global)",
      "API key for Coding Plan": "Coding Plan \u7684 API \u5BC6\u9470",
      "Show current authentication status": "\u986F\u793A\u7576\u524D\u8A8D\u8B49\u72C0\u614B",
      "Authentication completed successfully.": "\u8A8D\u8B49\u5B8C\u6210\u3002",
      "Starting Qwen OAuth authentication...": "\u6B63\u5728\u5553\u52D5 Qwen OAuth \u8A8D\u8B49...",
      "Successfully authenticated with Qwen OAuth.": "\u5DF2\u6210\u529F\u901A\u904E Qwen OAuth \u8A8D\u8B49\u3002",
      "Failed to authenticate with Qwen OAuth: {{error}}": "Qwen OAuth \u8A8D\u8B49\u5931\u6557\uFF1A{{error}}",
      "Processing Alibaba Cloud Coding Plan authentication...": "\u6B63\u5728\u8655\u7406\u963F\u91CC\u96F2\u767E\u934A Coding Plan \u8A8D\u8B49...",
      "Successfully authenticated with Alibaba Cloud Coding Plan.": "\u5DF2\u6210\u529F\u901A\u904E\u963F\u91CC\u96F2\u767E\u934A Coding Plan \u8A8D\u8B49\u3002",
      "Failed to authenticate with Coding Plan: {{error}}": "Coding Plan \u8A8D\u8B49\u5931\u6557\uFF1A{{error}}",
      "\u4E2D\u56FD (China)": "\u4E2D\u570B (China)",
      "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)": "\u963F\u91CC\u96F2\u767E\u934A (aliyun.com)",
      Global: "\u5168\u7403",
      "Alibaba Cloud (alibabacloud.com)": "Alibaba Cloud (alibabacloud.com)",
      "Select region for Coding Plan:": "\u9078\u64C7 Coding Plan \u5340\u57DF\uFF1A",
      "Enter your Coding Plan API key: ": "\u8ACB\u8F38\u5165\u60A8\u7684 Coding Plan API \u5BC6\u9470\uFF1A",
      "Select authentication method:": "\u9078\u64C7\u8A8D\u8B49\u65B9\u5F0F\uFF1A",
      "\n=== Authentication Status ===\n": "\n=== \u8A8D\u8B49\u72C0\u614B ===\n",
      "\u26A0\uFE0F  No authentication method configured.\n": "\u26A0\uFE0F  \u672A\u914D\u7F6E\u8A8D\u8B49\u65B9\u5F0F\u3002\n",
      "Run one of the following commands to get started:\n": "\u904B\u884C\u4EE5\u4E0B\u547D\u4EE4\u4E4B\u4E00\u958B\u59CB\u914D\u7F6E\uFF1A\n",
      "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)": "  qwen auth qwen-oauth     - \u4F7F\u7528 Qwen OAuth \u767B\u9304\uFF08\u5DF2\u505C\u7528\uFF09",
      "  qwen auth coding-plan      - Authenticate with Alibaba Cloud Coding Plan\n": "  qwen auth coding-plan      - \u4F7F\u7528\u963F\u91CC\u96F2\u767E\u934A Coding Plan \u8A8D\u8B49\n",
      "Or simply run:": "\u6216\u8005\u76F4\u63A5\u904B\u884C\uFF1A",
      "  qwen auth                - Interactive authentication setup\n": "  qwen auth                - \u4EA4\u4E92\u5F0F\u8A8D\u8B49\u914D\u7F6E\n",
      "\u2713 Authentication Method: Qwen OAuth": "\u2713 \u8A8D\u8B49\u65B9\u5F0F\uFF1AQwen OAuth",
      "  Type: Free tier (discontinued 2026-04-15)": "  \u985E\u578B\uFF1A\u514D\u8CBB\u984D\u5EA6\uFF082026-04-15 \u5DF2\u505C\u7528\uFF09",
      "  Limit: No longer available": "  \u9650\u984D\uFF1A\u5DF2\u4E0D\u53EF\u7528",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.": "Qwen OAuth \u514D\u8CBB\u984D\u5EA6\u5DF2\u65BC 2026-04-15 \u505C\u7528\u3002\u8ACB\u904B\u884C /auth \u5207\u63DB\u5230 Coding Plan\u3001OpenRouter\u3001Fireworks AI \u6216\u5176\u4ED6\u670D\u52D9\u5546\u3002",
      "  Models: Qwen latest models\n": "  \u6A21\u578B\uFF1AQwen \u6700\u65B0\u6A21\u578B\n",
      "\u2713 Authentication Method: Alibaba Cloud Coding Plan": "\u2713 \u8A8D\u8B49\u65B9\u5F0F\uFF1A\u963F\u91CC\u96F2\u767E\u934A Coding Plan",
      "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC": "\u4E2D\u570B (China) - \u963F\u91CC\u96F2\u767E\u934A",
      "Global - Alibaba Cloud": "\u5168\u7403 - Alibaba Cloud",
      "  Region: {{region}}": "  \u5340\u57DF\uFF1A{{region}}",
      "  Current Model: {{model}}": "  \u7576\u524D\u6A21\u578B\uFF1A{{model}}",
      "  Config Version: {{version}}": "  \u914D\u7F6E\u7248\u672C\uFF1A{{version}}",
      "  Status: API key configured\n": "  \u72C0\u614B\uFF1AAPI \u5BC6\u9470\u5DF2\u914D\u7F6E\n",
      "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)": "\u26A0\uFE0F  \u8A8D\u8B49\u65B9\u5F0F\uFF1A\u963F\u91CC\u96F2\u767E\u934A Coding Plan\uFF08\u4E0D\u5B8C\u6574\uFF09",
      "  Issue: API key not found in environment or settings\n": "  \u554F\u984C\uFF1A\u5728\u74B0\u5883\u8B8A\u91CF\u6216\u8A2D\u7F6E\u4E2D\u672A\u627E\u5230 API \u5BC6\u9470\n",
      "  Run `qwen auth coding-plan` to re-configure.\n": "  \u904B\u884C `qwen auth coding-plan` \u91CD\u65B0\u914D\u7F6E\u3002\n",
      "\u2713 Authentication Method: {{type}}": "\u2713 \u8A8D\u8B49\u65B9\u5F0F\uFF1A{{type}}",
      "  Status: Configured\n": "  \u72C0\u614B\uFF1A\u5DF2\u914D\u7F6E\n",
      "Failed to check authentication status: {{error}}": "\u6AA2\u67E5\u8A8D\u8B49\u72C0\u614B\u5931\u6557\uFF1A{{error}}",
      "Select an option:": "\u8ACB\u9078\u64C7\uFF1A",
      "Raw mode not available. Please run in an interactive terminal.": "\u539F\u59CB\u6A21\u5F0F\u4E0D\u53EF\u7528\u3002\u8ACB\u5728\u4EA4\u4E92\u5F0F\u7D42\u7AEF\u4E2D\u904B\u884C\u3002",
      "(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n": "(\u4F7F\u7528 \u2191 \u2193 \u7BAD\u982D\u5C0E\u822A\uFF0CEnter \u9078\u64C7\uFF0CCtrl+C \u9000\u51FA)\n",
      compact: "\u7DCA\u6E4A",
      "compact mode: on (Ctrl+O off)": "\u7DCA\u6E4A\u6A21\u5F0F\uFF1A\u958B\uFF08Ctrl+O \u95DC\u9589\uFF09",
      "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).": "\u7DCA\u6E4A\u6A21\u5F0F\u4E0B\u96B1\u85CF\u5DE5\u5177\u8F38\u51FA\u548C\u601D\u8003\u904E\u7A0B\uFF0C\u754C\u9762\u66F4\u7C21\u6F54\uFF08Ctrl+O \u5207\u63DB\uFF09\u3002",
      "Press Ctrl+O to show full tool output": "\u6309 Ctrl+O \u67E5\u770B\u8A73\u7D30\u5DE5\u5177\u8ABF\u7528\u7D50\u679C",
      "Switch to plan mode or exit plan mode": "\u5207\u63DB\u5230\u8A08\u5283\u6A21\u5F0F\u6216\u9000\u51FA\u8A08\u5283\u6A21\u5F0F",
      "Exited plan mode. Previous approval mode restored.": "\u5DF2\u9000\u51FA\u8A08\u5283\u6A21\u5F0F\uFF0C\u5DF2\u6062\u5FA9\u4E4B\u524D\u7684\u5BE9\u6279\u6A21\u5F0F\u3002",
      "Enabled plan mode. The agent will analyze and plan without executing tools.": "\u5553\u7528\u8A08\u5283\u6A21\u5F0F\u3002\u667A\u80FD\u9AD4\u5C07\u53EA\u5206\u6790\u548C\u898F\u5283\uFF0C\u800C\u4E0D\u57F7\u884C\u5DE5\u5177\u3002",
      'Already in plan mode. Use "/plan exit" to exit plan mode.': '\u5DF2\u8655\u65BC\u8A08\u5283\u6A21\u5F0F\u3002\u4F7F\u7528 "/plan exit" \u9000\u51FA\u8A08\u5283\u6A21\u5F0F\u3002',
      'Not in plan mode. Use "/plan" to enter plan mode first.': '\u672A\u8655\u65BC\u8A08\u5283\u6A21\u5F0F\u3002\u8ACB\u5148\u4F7F\u7528 "/plan" \u9032\u5165\u8A08\u5283\u6A21\u5F0F\u3002',
      "Set up Qwen Code's status line UI": "\u914D\u7F6E Qwen Code \u7684\u72C0\u614B\u6B04"
    };
  }
});

// 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\uFF1A",
      "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",
      "to toggle compact mode": "\u5207\u6362\u7D27\u51D1\u6A21\u5F0F",
      "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",
      "Fast Model": "\u5FEB\u901F\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]",
      "List available skills.": "\u5217\u51FA\u53EF\u7528\u6280\u80FD\u3002",
      "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\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",
      "Enter to submit, Esc to go back": "Enter \u63D0\u4EA4\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}}",
      // ============================================================================
      // Extensions - Management Dialog
      // ============================================================================
      "Manage Extensions": "\u7BA1\u7406\u6269\u5C55",
      "Extension Details": "\u6269\u5C55\u8BE6\u60C5",
      "View Extension": "\u67E5\u770B\u6269\u5C55",
      "Update Extension": "\u66F4\u65B0\u6269\u5C55",
      "Disable Extension": "\u7981\u7528\u6269\u5C55",
      "Enable Extension": "\u542F\u7528\u6269\u5C55",
      "Uninstall Extension": "\u5378\u8F7D\u6269\u5C55",
      "Select Scope": "\u9009\u62E9\u4F5C\u7528\u57DF",
      "User Scope": "\u7528\u6237\u4F5C\u7528\u57DF",
      "Workspace Scope": "\u5DE5\u4F5C\u533A\u4F5C\u7528\u57DF",
      "No extensions found.": "\u672A\u627E\u5230\u6269\u5C55\u3002",
      Active: "\u5DF2\u542F\u7528",
      Disabled: "\u5DF2\u7981\u7528",
      "Update available": "\u6709\u53EF\u7528\u66F4\u65B0",
      "Up to date": "\u5DF2\u662F\u6700\u65B0",
      "Checking...": "\u68C0\u67E5\u4E2D...",
      "Updating...": "\u66F4\u65B0\u4E2D...",
      Unknown: "\u672A\u77E5",
      Error: "\u9519\u8BEF",
      "Version:": "\u7248\u672C\uFF1A",
      "Status:": "\u72B6\u6001\uFF1A",
      'Are you sure you want to uninstall extension "{{name}}"?': '\u786E\u5B9A\u8981\u5378\u8F7D\u6269\u5C55 "{{name}}" \u5417\uFF1F',
      "This action cannot be undone.": "\u6B64\u64CD\u4F5C\u65E0\u6CD5\u64A4\u9500\u3002",
      'Extension "{{name}}" disabled successfully.': '\u6269\u5C55 "{{name}}" \u7981\u7528\u6210\u529F\u3002',
      'Extension "{{name}}" enabled successfully.': '\u6269\u5C55 "{{name}}" \u542F\u7528\u6210\u529F\u3002',
      'Extension "{{name}}" updated successfully.': '\u6269\u5C55 "{{name}}" \u66F4\u65B0\u6210\u529F\u3002',
      'Failed to update extension "{{name}}": {{error}}': '\u66F4\u65B0\u6269\u5C55 "{{name}}" \u5931\u8D25\uFF1A{{error}}',
      "Select the scope for this action:": "\u9009\u62E9\u6B64\u64CD\u4F5C\u7684\u4F5C\u7528\u57DF\uFF1A",
      "User - Applies to all projects": "\u7528\u6237 - \u5E94\u7528\u4E8E\u6240\u6709\u9879\u76EE",
      "Workspace - Applies to current project only": "\u5DE5\u4F5C\u533A - \u4EC5\u5E94\u7528\u4E8E\u5F53\u524D\u9879\u76EE",
      // Extension dialog - missing keys
      "Name:": "\u540D\u79F0\uFF1A",
      "MCP Servers:": "MCP \u670D\u52A1\u5668\uFF1A",
      "Settings:": "\u8BBE\u7F6E\uFF1A",
      active: "\u5DF2\u542F\u7528",
      "View Details": "\u67E5\u770B\u8BE6\u60C5",
      "Update failed:": "\u66F4\u65B0\u5931\u8D25\uFF1A",
      "Updating {{name}}...": "\u6B63\u5728\u66F4\u65B0 {{name}}...",
      "Update complete!": "\u66F4\u65B0\u5B8C\u6210\uFF01",
      "User (global)": "\u7528\u6237\uFF08\u5168\u5C40\uFF09",
      "Workspace (project-specific)": "\u5DE5\u4F5C\u533A\uFF08\u9879\u76EE\u7279\u5B9A\uFF09",
      'Disable "{{name}}" - Select Scope': '\u7981\u7528 "{{name}}" - \u9009\u62E9\u4F5C\u7528\u57DF',
      'Enable "{{name}}" - Select Scope': '\u542F\u7528 "{{name}}" - \u9009\u62E9\u4F5C\u7528\u57DF',
      "No extension selected": "\u672A\u9009\u62E9\u6269\u5C55",
      "Press Y/Enter to confirm, N/Esc to cancel": "\u6309 Y/Enter \u786E\u8BA4\uFF0CN/Esc \u53D6\u6D88",
      "Y/Enter to confirm, N/Esc to cancel": "Y/Enter \u786E\u8BA4\uFF0CN/Esc \u53D6\u6D88",
      "{{count}} extensions installed": "\u5DF2\u5B89\u88C5 {{count}} \u4E2A\u6269\u5C55",
      "Use '/extensions install' to install your first extension.": "\u4F7F\u7528 '/extensions install' \u5B89\u88C5\u60A8\u7684\u7B2C\u4E00\u4E2A\u6269\u5C55\u3002",
      // Update status values
      "up to date": "\u5DF2\u662F\u6700\u65B0",
      "update available": "\u6709\u53EF\u7528\u66F4\u65B0",
      "checking...": "\u68C0\u67E5\u4E2D...",
      "not updatable": "\u4E0D\u53EF\u66F4\u65B0",
      error: "\u9519\u8BEF",
      // ============================================================================
      // 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",
      "Auto (detect terminal theme)": "\u81EA\u52A8\uFF08\u68C0\u6D4B\u7EC8\u7AEF\u4E3B\u9898\uFF09",
      Auto: "\u81EA\u52A8",
      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",
      "Open MCP management dialog, or authenticate with OAuth-enabled servers": "\u6253\u5F00 MCP \u7BA1\u7406\u5BF9\u8BDD\u6846\uFF0C\u6216\u5728\u652F\u6301 OAuth \u7684\u670D\u52A1\u5668\u4E0A\u8FDB\u884C\u8EAB\u4EFD\u9A8C\u8BC1",
      "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",
      "Manage installed extensions": "\u7BA1\u7406\u5DF2\u5B89\u88C5\u7684\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",
      "Value:": "\u503C\uFF1A",
      "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",
      // ============================================================================
      // Commands - Hooks
      // ============================================================================
      "Manage Qwen Code hooks": "\u7BA1\u7406 Qwen Code Hook",
      "List all configured hooks": "\u5217\u51FA\u6240\u6709\u5DF2\u914D\u7F6E\u7684 Hook",
      "Enable a disabled hook": "\u542F\u7528\u5DF2\u7981\u7528\u7684 Hook",
      "Disable an active hook": "\u7981\u7528\u5DF2\u542F\u7528\u7684 Hook",
      // Hooks - Dialog
      Hooks: "Hook",
      "Loading hooks...": "\u6B63\u5728\u52A0\u8F7D Hook...",
      "Error loading hooks:": "\u52A0\u8F7D Hook \u51FA\u9519\uFF1A",
      "Press Escape to close": "\u6309 Escape \u5173\u95ED",
      "Press Escape, Ctrl+C, or Ctrl+D to cancel": "\u6309 Escape\u3001Ctrl+C \u6216 Ctrl+D \u53D6\u6D88",
      "Press Space, Enter, or Escape to dismiss": "\u6309\u7A7A\u683C\u3001\u56DE\u8F66\u6216 Escape \u5173\u95ED",
      "No hook selected": "\u672A\u9009\u62E9 Hook",
      // Hooks - List Step
      "No hook events found.": "\u672A\u627E\u5230 Hook \u4E8B\u4EF6\u3002",
      "{{count}} hook configured": "{{count}} \u4E2A Hook \u5DF2\u914D\u7F6E",
      "{{count}} hooks configured": "{{count}} \u4E2A Hook \u5DF2\u914D\u7F6E",
      "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code.": "\u6B64\u83DC\u5355\u4E3A\u53EA\u8BFB\u3002\u8981\u6DFB\u52A0\u6216\u4FEE\u6539 Hook\uFF0C\u8BF7\u76F4\u63A5\u7F16\u8F91 settings.json \u6216\u8BE2\u95EE Qwen Code\u3002",
      "Enter to select \xB7 Esc to cancel": "Enter \u9009\u62E9 \xB7 Esc \u53D6\u6D88",
      // Hooks - Detail Step
      "Exit codes:": "\u9000\u51FA\u7801\uFF1A",
      "Configured hooks:": "\u5DF2\u914D\u7F6E\u7684 Hook\uFF1A",
      "No hooks configured for this event.": "\u6B64\u4E8B\u4EF6\u672A\u914D\u7F6E Hook\u3002",
      "To add hooks, edit settings.json directly or ask Qwen.": "\u8981\u6DFB\u52A0 Hook\uFF0C\u8BF7\u76F4\u63A5\u7F16\u8F91 settings.json \u6216\u8BE2\u95EE Qwen\u3002",
      "Enter to select \xB7 Esc to go back": "Enter \u9009\u62E9 \xB7 Esc \u8FD4\u56DE",
      // Hooks - Config Detail Step
      "Hook details": "Hook \u8BE6\u60C5",
      "Event:": "\u4E8B\u4EF6\uFF1A",
      "Extension:": "\u6269\u5C55\uFF1A",
      "Desc:": "\u63CF\u8FF0\uFF1A",
      "No hook config selected": "\u672A\u9009\u62E9 Hook \u914D\u7F6E",
      "To modify or remove this hook, edit settings.json directly or ask Qwen to help.": "\u8981\u4FEE\u6539\u6216\u5220\u9664\u6B64 Hook\uFF0C\u8BF7\u76F4\u63A5\u7F16\u8F91 settings.json \u6216\u8BE2\u95EE Qwen\u3002",
      // Hooks - Disabled Step
      "Hook Configuration - Disabled": "Hook \u914D\u7F6E - \u5DF2\u7981\u7528",
      "All hooks are currently disabled. You have {{count}} that are not running.": "\u6240\u6709 Hook \u5F53\u524D\u5DF2\u7981\u7528\u3002\u60A8\u6709 {{count}} \u672A\u8FD0\u884C\u3002",
      "{{count}} configured hook": "{{count}} \u4E2A\u5DF2\u914D\u7F6E\u7684 Hook",
      "{{count}} configured hooks": "{{count}} \u4E2A\u5DF2\u914D\u7F6E\u7684 Hook",
      "When hooks are disabled:": "\u5F53 Hook \u88AB\u7981\u7528\u65F6\uFF1A",
      "No hook commands will execute": "\u4E0D\u4F1A\u6267\u884C\u4EFB\u4F55 Hook \u547D\u4EE4",
      "StatusLine will not be displayed": "\u4E0D\u4F1A\u663E\u793A\u72B6\u6001\u680F",
      "Tool operations will proceed without hook validation": "\u5DE5\u5177\u64CD\u4F5C\u5C06\u5728\u6CA1\u6709 Hook \u9A8C\u8BC1\u7684\u60C5\u51B5\u4E0B\u7EE7\u7EED",
      'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.': '\u8981\u91CD\u65B0\u542F\u7528 Hook\uFF0C\u8BF7\u4ECE settings.json \u4E2D\u5220\u9664 "disableAllHooks" \u6216\u8BE2\u95EE Qwen Code\u3002',
      // Hooks - Source
      Project: "\u9879\u76EE",
      User: "\u7528\u6237",
      System: "\u7CFB\u7EDF",
      Extension: "\u6269\u5C55",
      "Local Settings": "\u672C\u5730\u8BBE\u7F6E",
      "User Settings": "\u7528\u6237\u8BBE\u7F6E",
      "System Settings": "\u7CFB\u7EDF\u8BBE\u7F6E",
      Extensions: "\u6269\u5C55",
      "Session (temporary)": "\u4F1A\u8BDD\uFF08\u4E34\u65F6\uFF09",
      // Hooks - Status
      "\u2713 Enabled": "\u2713 \u5DF2\u542F\u7528",
      "\u2717 Disabled": "\u2717 \u5DF2\u7981\u7528",
      // Hooks - Event Descriptions (short)
      "Before tool execution": "\u5DE5\u5177\u6267\u884C\u524D",
      "After tool execution": "\u5DE5\u5177\u6267\u884C\u540E",
      "After tool execution fails": "\u5DE5\u5177\u6267\u884C\u5931\u8D25\u540E",
      "When notifications are sent": "\u53D1\u9001\u901A\u77E5\u65F6",
      "When the user submits a prompt": "\u7528\u6237\u63D0\u4EA4\u63D0\u793A\u65F6",
      "When a new session is started": "\u65B0\u4F1A\u8BDD\u5F00\u59CB\u65F6",
      "Right before Qwen Code concludes its response": "Qwen Code \u7ED3\u675F\u54CD\u5E94\u4E4B\u524D",
      "When a subagent (Agent tool call) is started": "\u5B50\u667A\u80FD\u4F53\uFF08Agent \u5DE5\u5177\u8C03\u7528\uFF09\u542F\u52A8\u65F6",
      "Right before a subagent concludes its response": "\u5B50\u667A\u80FD\u4F53\u7ED3\u675F\u54CD\u5E94\u4E4B\u524D",
      "Before conversation compaction": "\u5BF9\u8BDD\u538B\u7F29\u524D",
      "When a session is ending": "\u4F1A\u8BDD\u7ED3\u675F\u65F6",
      "When a permission dialog is displayed": "\u663E\u793A\u6743\u9650\u5BF9\u8BDD\u6846\u65F6",
      // Hooks - Event Descriptions (detailed)
      "Input to command is JSON of tool call arguments.": "\u547D\u4EE4\u8F93\u5165\u4E3A\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u7684 JSON\u3002",
      'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).': '\u547D\u4EE4\u8F93\u5165\u4E3A\u5305\u542B "inputs"\uFF08\u5DE5\u5177\u8C03\u7528\u53C2\u6570\uFF09\u548C "response"\uFF08\u5DE5\u5177\u8C03\u7528\u54CD\u5E94\uFF09\u5B57\u6BB5\u7684 JSON\u3002',
      "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout.": "\u547D\u4EE4\u8F93\u5165\u4E3A\u5305\u542B tool_name\u3001tool_input\u3001tool_use_id\u3001error\u3001error_type\u3001is_interrupt \u548C is_timeout \u7684 JSON\u3002",
      "Input to command is JSON with notification message and type.": "\u547D\u4EE4\u8F93\u5165\u4E3A\u5305\u542B\u901A\u77E5\u6D88\u606F\u548C\u7C7B\u578B\u7684 JSON\u3002",
      "Input to command is JSON with original user prompt text.": "\u547D\u4EE4\u8F93\u5165\u4E3A\u5305\u542B\u539F\u59CB\u7528\u6237\u63D0\u793A\u6587\u672C\u7684 JSON\u3002",
      "Input to command is JSON with session start source.": "\u547D\u4EE4\u8F93\u5165\u4E3A\u5305\u542B\u4F1A\u8BDD\u542F\u52A8\u6765\u6E90\u7684 JSON\u3002",
      "Input to command is JSON with session end reason.": "\u547D\u4EE4\u8F93\u5165\u4E3A\u5305\u542B\u4F1A\u8BDD\u7ED3\u675F\u539F\u56E0\u7684 JSON\u3002",
      "Input to command is JSON with agent_id and agent_type.": "\u547D\u4EE4\u8F93\u5165\u4E3A\u5305\u542B agent_id \u548C agent_type \u7684 JSON\u3002",
      "Input to command is JSON with agent_id, agent_type, and agent_transcript_path.": "\u547D\u4EE4\u8F93\u5165\u4E3A\u5305\u542B agent_id\u3001agent_type \u548C agent_transcript_path \u7684 JSON\u3002",
      "Input to command is JSON with compaction details.": "\u547D\u4EE4\u8F93\u5165\u4E3A\u5305\u542B\u538B\u7F29\u8BE6\u60C5\u7684 JSON\u3002",
      "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.": "\u547D\u4EE4\u8F93\u5165\u4E3A\u5305\u542B tool_name\u3001tool_input \u548C tool_use_id \u7684 JSON\u3002\u8F93\u51FA\u5305\u542B hookSpecificOutput \u7684 JSON\uFF0C\u5176\u4E2D\u5305\u542B\u5141\u8BB8\u6216\u62D2\u7EDD\u7684\u51B3\u5B9A\u3002",
      // Hooks - Exit Code Descriptions
      "stdout/stderr not shown": "stdout/stderr \u4E0D\u663E\u793A",
      "show stderr to model and continue conversation": "\u5411\u6A21\u578B\u663E\u793A stderr \u5E76\u7EE7\u7EED\u5BF9\u8BDD",
      "show stderr to user only": "\u4EC5\u5411\u7528\u6237\u663E\u793A stderr",
      "stdout shown in transcript mode (ctrl+o)": "stdout \u4EE5\u8F6C\u5F55\u6A21\u5F0F\u663E\u793A (ctrl+o)",
      "show stderr to model immediately": "\u7ACB\u5373\u5411\u6A21\u578B\u663E\u793A stderr",
      "show stderr to user only but continue with tool call": "\u4EC5\u5411\u7528\u6237\u663E\u793A stderr \u4F46\u7EE7\u7EED\u5DE5\u5177\u8C03\u7528",
      "block processing, erase original prompt, and show stderr to user only": "\u963B\u6B62\u5904\u7406\uFF0C\u64E6\u9664\u539F\u59CB\u63D0\u793A\uFF0C\u4EC5\u5411\u7528\u6237\u663E\u793A stderr",
      "stdout shown to Qwen": "\u5411 Qwen \u663E\u793A stdout",
      "show stderr to user only (blocking errors ignored)": "\u4EC5\u5411\u7528\u6237\u663E\u793A stderr\uFF08\u5FFD\u7565\u963B\u585E\u9519\u8BEF\uFF09",
      "command completes successfully": "\u547D\u4EE4\u6210\u529F\u5B8C\u6210",
      "stdout shown to subagent": "\u5411\u5B50\u667A\u80FD\u4F53\u663E\u793A stdout",
      "show stderr to subagent and continue having it run": "\u5411\u5B50\u667A\u80FD\u4F53\u663E\u793A stderr \u5E76\u7EE7\u7EED\u8FD0\u884C",
      "stdout appended as custom compact instructions": "stdout \u4F5C\u4E3A\u81EA\u5B9A\u4E49\u538B\u7F29\u6307\u4EE4\u8FFD\u52A0",
      "block compaction": "\u963B\u6B62\u538B\u7F29",
      "show stderr to user only but continue with compaction": "\u4EC5\u5411\u7528\u6237\u663E\u793A stderr \u4F46\u7EE7\u7EED\u538B\u7F29",
      "use hook decision if provided": "\u5982\u679C\u63D0\u4F9B\u5219\u4F7F\u7528 Hook \u51B3\u5B9A",
      // Hooks - Messages
      "Config not loaded.": "\u914D\u7F6E\u672A\u52A0\u8F7D\u3002",
      "Hooks are not enabled. Enable hooks in settings to use this feature.": "Hook \u672A\u542F\u7528\u3002\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u542F\u7528 Hook \u4EE5\u4F7F\u7528\u6B64\u529F\u80FD\u3002",
      "No hooks configured. Add hooks in your settings.json file.": "\u672A\u914D\u7F6E Hook\u3002\u8BF7\u5728 settings.json \u6587\u4EF6\u4E2D\u6DFB\u52A0 Hook\u3002",
      "Configured Hooks ({{count}} total)": "\u5DF2\u914D\u7F6E\u7684 Hook\uFF08\u5171 {{count}} \u4E2A\uFF09",
      // ============================================================================
      // Commands - Session Export
      // ============================================================================
      "Export current session message history to a file": "\u5C06\u5F53\u524D\u4F1A\u8BDD\u7684\u6D88\u606F\u8BB0\u5F55\u5BFC\u51FA\u5230\u6587\u4EF6",
      "Export session to HTML format": "\u5C06\u4F1A\u8BDD\u5BFC\u51FA\u4E3A HTML \u6587\u4EF6",
      "Export session to JSON format": "\u5C06\u4F1A\u8BDD\u5BFC\u51FA\u4E3A JSON \u6587\u4EF6",
      "Export session to JSONL format (one message per line)": "\u5C06\u4F1A\u8BDD\u5BFC\u51FA\u4E3A JSONL \u6587\u4EF6\uFF08\u6BCF\u884C\u4E00\u6761\u6D88\u606F\uFF09",
      "Export session to markdown format": "\u5C06\u4F1A\u8BDD\u5BFC\u51FA\u4E3A Markdown \u6587\u4EF6",
      // ============================================================================
      // Commands - Insights
      // ============================================================================
      "generate personalized programming insights from your chat history": "\u6839\u636E\u4F60\u7684\u804A\u5929\u8BB0\u5F55\u751F\u6210\u4E2A\u6027\u5316\u7F16\u7A0B\u6D1E\u5BDF",
      // ============================================================================
      // Commands - Session History
      // ============================================================================
      "Resume a previous session": "\u6062\u590D\u5148\u524D\u4F1A\u8BDD",
      "Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested": "\u6062\u590D\u67D0\u6B21\u5DE5\u5177\u8C03\u7528\u3002\u8FD9\u5C06\u628A\u5BF9\u8BDD\u4E0E\u6587\u4EF6\u5386\u53F2\u91CD\u7F6E\u5230\u63D0\u51FA\u8BE5\u5DE5\u5177\u8C03\u7528\u5EFA\u8BAE\u65F6\u7684\u72B6\u6001",
      "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",
      "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}}"',
      "Open auto-memory folder": "\u6253\u5F00\u81EA\u52A8\u8BB0\u5FC6\u6587\u4EF6\u5939",
      "Auto-memory: {{status}}": "\u81EA\u52A8\u8BB0\u5FC6\uFF1A{{status}}",
      "Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream to run": "\u81EA\u52A8\u6574\u7406\uFF1A{{status}} \xB7 {{lastDream}} \xB7 /dream \u7ACB\u5373\u8FD0\u884C",
      never: "\u4ECE\u672A",
      on: "\u5F00",
      off: "\u5173",
      "\u2726 dreaming": "\u2726 \u6574\u7406\u4E2D",
      "Remove matching entries from managed auto-memory.": "\u4ECE\u6258\u7BA1\u81EA\u52A8\u8BB0\u5FC6\u4E2D\u5220\u9664\u5339\u914D\u7684\u6761\u76EE\u3002",
      "Usage: /forget <memory text to remove>": "\u7528\u6CD5\uFF1A/forget <\u8981\u5220\u9664\u7684\u8BB0\u5FC6\u6587\u672C>",
      "No managed auto-memory entries matched: {{query}}": "\u6CA1\u6709\u5339\u914D\u7684\u6258\u7BA1\u81EA\u52A8\u8BB0\u5FC6\u6761\u76EE\uFF1A{{query}}",
      "Show managed auto-memory status.": "\u663E\u793A\u6258\u7BA1\u81EA\u52A8\u8BB0\u5FC6\u72B6\u6001",
      "Run managed auto-memory extraction for the current session.": "\u4E3A\u5F53\u524D\u4F1A\u8BDD\u8FD0\u884C\u6258\u7BA1\u81EA\u52A8\u8BB0\u5FC6\u63D0\u70BC",
      "Managed auto-memory root: {{root}}": "\u6258\u7BA1\u81EA\u52A8\u8BB0\u5FC6\u6839\u76EE\u5F55\uFF1A{{root}}",
      "Managed auto-memory topics:": "\u6258\u7BA1\u81EA\u52A8\u8BB0\u5FC6\u4E3B\u9898\uFF1A",
      "No extraction cursor found yet.": "\u5C1A\u672A\u627E\u5230\u63D0\u70BC\u6E38\u6807\u3002",
      "Cursor: session={{sessionId}}, offset={{offset}}, updated={{updatedAt}}": "\u6E38\u6807\uFF1Asession={{sessionId}}\uFF0Coffset={{offset}}\uFF0Cupdated={{updatedAt}}",
      "No chat client available to extract memory.": "\u6CA1\u6709\u53EF\u7528\u4E8E\u63D0\u70BC\u8BB0\u5FC6\u7684\u804A\u5929\u5BA2\u6237\u7AEF\u3002",
      "Managed auto-memory extraction is already running.": "\u6258\u7BA1\u81EA\u52A8\u8BB0\u5FC6\u63D0\u70BC\u5DF2\u5728\u8FD0\u884C\u4E2D\u3002",
      "Managed auto-memory extraction found no new durable memories.": "\u6258\u7BA1\u81EA\u52A8\u8BB0\u5FC6\u63D0\u70BC\u672A\u53D1\u73B0\u65B0\u7684\u6301\u4E45\u8BB0\u5FC6\u3002",
      "Consolidate managed auto-memory topic files.": "\u6574\u7406\u6258\u7BA1\u81EA\u52A8\u8BB0\u5FC6\u4E3B\u9898\u6587\u4EF6",
      "Managed auto-memory dream found nothing to improve.": "\u6258\u7BA1\u81EA\u52A8\u8BB0\u5FC6 dream \u672A\u53D1\u73B0\u53EF\u6539\u8FDB\u5185\u5BB9\u3002",
      "Deduplicated entries: {{count}}": "\u53BB\u91CD\u6761\u76EE\u6570\uFF1A{{count}}",
      "Save a durable memory using the save_memory tool.": "\u4F7F\u7528 save_memory \u5DE5\u5177\u4FDD\u5B58\u4E00\u6761\u6301\u4E45\u8BB0\u5FC6",
      "Usage: /remember [--global|--project] <text to remember>": "\u7528\u6CD5\uFF1A/remember [--global|--project] <\u8981\u8BB0\u4F4F\u7684\u6587\u672C>",
      // ============================================================================
      // 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",
      "Open MCP management dialog": "\u6253\u5F00 MCP \u7BA1\u7406\u5BF9\u8BDD\u6846",
      "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...",
      "Discovered {{count}} tool(s) from '{{name}}'.": "\u4ECE '{{name}}' \u53D1\u73B0\u4E86 {{count}} \u4E2A\u5DE5\u5177\u3002",
      "Authentication complete. Returning to server details...": "\u8BA4\u8BC1\u5B8C\u6210\uFF0C\u6B63\u5728\u8FD4\u56DE\u670D\u52A1\u5668\u8BE6\u60C5...",
      "Authentication successful.": "\u8BA4\u8BC1\u6210\u529F\u3002",
      "If the browser does not open, copy and paste this URL into your browser:": "\u5982\u679C\u6D4F\u89C8\u5668\u672A\u81EA\u52A8\u6253\u5F00\uFF0C\u8BF7\u590D\u5236\u4EE5\u4E0B URL \u5E76\u7C98\u8D34\u5230\u6D4F\u89C8\u5668\u4E2D\uFF1A",
      "Make sure to copy the COMPLETE URL - it may wrap across multiple lines.": "\u26A0\uFE0F  \u8BF7\u786E\u4FDD\u590D\u5236\u5B8C\u6574\u7684 URL \u2014\u2014 \u5B83\u53EF\u80FD\u8DE8\u8D8A\u591A\u884C\u3002",
      // ============================================================================
      // MCP Management Dialog
      // ============================================================================
      "Manage MCP servers": "\u7BA1\u7406 MCP \u670D\u52A1\u5668",
      "Server Detail": "\u670D\u52A1\u5668\u8BE6\u60C5",
      "Disable Server": "\u7981\u7528\u670D\u52A1\u5668",
      Tools: "\u5DE5\u5177",
      "Tool Detail": "\u5DE5\u5177\u8BE6\u60C5",
      "MCP Management": "MCP \u7BA1\u7406",
      "Loading...": "\u52A0\u8F7D\u4E2D...",
      "Unknown step": "\u672A\u77E5\u6B65\u9AA4",
      "Esc to back": "Esc \u8FD4\u56DE",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close": "\u2191\u2193 \u5BFC\u822A \xB7 Enter \u9009\u62E9 \xB7 Esc \u5173\u95ED",
      "\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back": "\u2191\u2193 \u5BFC\u822A \xB7 Enter \u9009\u62E9 \xB7 Esc \u8FD4\u56DE",
      "\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back": "\u2191\u2193 \u5BFC\u822A \xB7 Enter \u786E\u8BA4 \xB7 Esc \u8FD4\u56DE",
      "User Settings (global)": "\u7528\u6237\u8BBE\u7F6E\uFF08\u5168\u5C40\uFF09",
      "Workspace Settings (project-specific)": "\u5DE5\u4F5C\u533A\u8BBE\u7F6E\uFF08\u9879\u76EE\u7EA7\uFF09",
      "Disable server:": "\u7981\u7528\u670D\u52A1\u5668\uFF1A",
      "Select where to add the server to the exclude list:": "\u9009\u62E9\u5C06\u670D\u52A1\u5668\u6DFB\u52A0\u5230\u6392\u9664\u5217\u8868\u7684\u4F4D\u7F6E\uFF1A",
      "Press Enter to confirm, Esc to cancel": "\u6309 Enter \u786E\u8BA4\uFF0CEsc \u53D6\u6D88",
      "View tools": "\u67E5\u770B\u5DE5\u5177",
      Reconnect: "\u91CD\u65B0\u8FDE\u63A5",
      Enable: "\u542F\u7528",
      Disable: "\u7981\u7528",
      Authenticate: "\u8BA4\u8BC1",
      "Re-authenticate": "\u91CD\u65B0\u8BA4\u8BC1",
      "Clear Authentication": "\u6E05\u7A7A\u8BA4\u8BC1",
      disabled: "\u5DF2\u7981\u7528",
      "Server:": "\u670D\u52A1\u5668\uFF1A",
      "(disabled)": "(\u5DF2\u7981\u7528)",
      "Error:": "\u9519\u8BEF\uFF1A",
      tool: "\u5DE5\u5177",
      tools: "\u4E2A\u5DE5\u5177",
      connected: "\u5DF2\u8FDE\u63A5",
      connecting: "\u8FDE\u63A5\u4E2D",
      disconnected: "\u5DF2\u65AD\u5F00",
      // MCP Server List
      "User MCPs": "\u7528\u6237 MCP",
      "Project MCPs": "\u9879\u76EE MCP",
      "Extension MCPs": "\u6269\u5C55 MCP",
      server: "\u4E2A\u670D\u52A1\u5668",
      servers: "\u4E2A\u670D\u52A1\u5668",
      "Add MCP servers to your settings to get started.": "\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u6DFB\u52A0 MCP \u670D\u52A1\u5668\u4EE5\u5F00\u59CB\u4F7F\u7528\u3002",
      "Run qwen --debug to see error logs": "\u8FD0\u884C qwen --debug \u67E5\u770B\u9519\u8BEF\u65E5\u5FD7",
      // MCP OAuth Authentication
      "OAuth Authentication": "OAuth \u8BA4\u8BC1",
      "Press Enter to start authentication, Esc to go back": "\u6309 Enter \u5F00\u59CB\u8BA4\u8BC1\uFF0CEsc \u8FD4\u56DE",
      "Authenticating... Please complete the login in your browser.": "\u8BA4\u8BC1\u4E2D... \u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55\u3002",
      "Press c to copy the authorization URL to your clipboard.": "\u6309 c \u590D\u5236\u6388\u6743 URL \u5230\u526A\u8D34\u677F\u3002",
      "Copy request sent to your terminal. If paste is empty, copy the URL above manually.": "\u5DF2\u5411\u7EC8\u7AEF\u53D1\u9001\u590D\u5236\u8BF7\u6C42\uFF1B\u82E5\u7C98\u8D34\u4E3A\u7A7A\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4E0A\u65B9 URL\u3002",
      "Cannot write to terminal \u2014 copy the URL above manually.": "\u65E0\u6CD5\u5199\u5165\u7EC8\u7AEF\uFF0C\u8BF7\u624B\u52A8\u590D\u5236\u4E0A\u65B9 URL\u3002",
      "Press Enter or Esc to go back": "\u6309 Enter \u6216 Esc \u8FD4\u56DE",
      // MCP Server Detail
      "Command:": "\u547D\u4EE4\uFF1A",
      "Working Directory:": "\u5DE5\u4F5C\u76EE\u5F55\uFF1A",
      "Capabilities:": "\u529F\u80FD\uFF1A",
      "No server selected": "\u672A\u9009\u62E9\u670D\u52A1\u5668",
      prompts: "\u63D0\u793A",
      // MCP Tool List
      "No tools available for this server.": "\u6B64\u670D\u52A1\u5668\u6CA1\u6709\u53EF\u7528\u5DE5\u5177\u3002",
      destructive: "\u7834\u574F\u6027",
      "read-only": "\u53EA\u8BFB",
      "open-world": "\u5F00\u653E\u4E16\u754C",
      idempotent: "\u5E42\u7B49",
      "Tools for {{name}}": "{{name}} \u7684\u5DE5\u5177",
      "Tools for {{serverName}}": "{{serverName}} \u7684\u5DE5\u5177",
      "{{current}}/{{total}}": "{{current}}/{{total}}",
      // MCP Tool Detail
      required: "\u5FC5\u9700",
      Type: "\u7C7B\u578B",
      Enum: "\u679A\u4E3E",
      Parameters: "\u53C2\u6570",
      "No tool selected": "\u672A\u9009\u62E9\u5DE5\u5177",
      Annotations: "\u6CE8\u89E3",
      Title: "\u6807\u9898",
      "Read Only": "\u53EA\u8BFB",
      Destructive: "\u7834\u574F\u6027",
      Idempotent: "\u5E42\u7B49",
      "Open World": "\u5F00\u653E\u4E16\u754C",
      Server: "\u670D\u52A1\u5668",
      // Invalid tool related translations
      "{{count}} invalid tools": "{{count}} \u4E2A\u65E0\u6548\u5DE5\u5177",
      invalid: "\u65E0\u6548",
      "invalid: {{reason}}": "\u65E0\u6548\uFF1A{{reason}}",
      "missing name": "\u7F3A\u5C11\u540D\u79F0",
      "missing description": "\u7F3A\u5C11\u63CF\u8FF0",
      "(unnamed)": "(\u672A\u547D\u540D)",
      "Warning: This tool cannot be called by the LLM": "\u8B66\u544A\uFF1A\u6B64\u5DE5\u5177\u65E0\u6CD5\u88AB LLM \u8C03\u7528",
      Reason: "\u539F\u56E0",
      "Tools must have both name and description to be used by the LLM.": "\u5DE5\u5177\u5FC5\u987B\u540C\u65F6\u5177\u6709\u540D\u79F0\u548C\u63CF\u8FF0\u624D\u80FD\u88AB LLM \u4F7F\u7528\u3002",
      // ============================================================================
      // 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 (--fast for suggestion model)": "\u5207\u6362\u6B64\u4F1A\u8BDD\u7684\u6A21\u578B\uFF08--fast \u53EF\u8BBE\u7F6E\u5EFA\u8BAE\u6A21\u578B\uFF09",
      "Set a lighter model for prompt suggestions and speculative execution": "\u8BBE\u7F6E\u7528\u4E8E\u8F93\u5165\u5EFA\u8BAE\u548C\u63A8\u6D4B\u6267\u884C\u7684\u8F7B\u91CF\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",
      Yes: "\u662F",
      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 ...",
      "Always allow in this project": "\u5728\u672C\u9879\u76EE\u4E2D\u603B\u662F\u5141\u8BB8",
      "Always allow {{action}} in this project": "\u5728\u672C\u9879\u76EE\u4E2D\u603B\u662F\u5141\u8BB8{{action}}",
      "Always allow for this user": "\u5BF9\u8BE5\u7528\u6237\u603B\u662F\u5141\u8BB8",
      "Always allow {{action}} for this user": "\u5BF9\u8BE5\u7528\u6237\u603B\u662F\u5141\u8BB8{{action}}",
      "Yes, restore previous mode ({{mode}})": "\u662F\uFF0C\u6062\u590D\u4E4B\u524D\u7684\u6A21\u5F0F ({{mode}})",
      "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",
      "Select Authentication Method": "\u9009\u62E9\u8BA4\u8BC1\u65B9\u5F0F",
      "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",
      "Terms of Services and Privacy Notice": "\u670D\u52A1\u6761\u6B3E\u548C\u9690\u79C1\u58F0\u660E",
      "Qwen OAuth": "Qwen OAuth (\u514D\u8D39)",
      "Discontinued \u2014 switch to Coding Plan or API Key": "\u5DF2\u505C\u7528 \u2014 \u8BF7\u5207\u6362\u5230 Coding Plan \u6216 API Key",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch provider.": "Qwen OAuth \u514D\u8D39\u989D\u5EA6\u5DF2\u4E8E 2026-04-15 \u505C\u7528\u3002\u8BF7\u8FD0\u884C /auth \u5207\u6362\u670D\u52A1\u5546\u3002",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead.": "Qwen OAuth \u514D\u8D39\u989D\u5EA6\u5DF2\u4E8E 2026-04-15 \u505C\u7528\u3002\u8BF7\u9009\u62E9 Coding Plan \u6216 API Key\u3002",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch.": "Qwen OAuth\u514D\u8D39\u5C42\u5DF2\u4E8E2026-04-15\u505C\u6B62\u670D\u52A1\u3002\u8BF7\u9009\u62E9\u5176\u4ED6\u63D0\u4F9B\u5546\u7684\u6A21\u578B\u6216\u8FD0\u884C /auth \u5207\u6362\u3002",
      "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n": "\n\u26A0 Qwen OAuth \u514D\u8D39\u989D\u5EA6\u5DF2\u4E8E 2026-04-15 \u505C\u7528\u3002\u8BF7\u9009\u62E9\u5176\u4ED6\u9009\u9879\u3002\n",
      "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models": "\u4ED8\u8D39 \xB7 \u6BCF 5 \u5C0F\u65F6\u6700\u591A 6,000 \u6B21\u8BF7\u6C42 \xB7 \u652F\u6301\u963F\u91CC\u4E91\u767E\u70BC Coding Plan \u5168\u90E8\u6A21\u578B",
      "Alibaba Cloud Coding Plan": "\u963F\u91CC\u4E91\u767E\u70BC Coding Plan",
      "Bring your own API key": "\u4F7F\u7528\u81EA\u5DF1\u7684 API \u5BC6\u94A5",
      "Browser-based authentication with third-party providers (e.g. OpenRouter, ModelScope)": "\u57FA\u4E8E\u6D4F\u89C8\u5668\u7684\u7B2C\u4E09\u65B9\u63D0\u4F9B\u5546\u8BA4\u8BC1\uFF08\u4F8B\u5982 OpenRouter\u3001ModelScope\uFF09",
      "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",
      "Note: Your existing API key will not be cleared when using Qwen OAuth.": "\u6CE8\u610F\uFF1A\u4F7F\u7528 Qwen OAuth \u65F6\uFF0C\u73B0\u6709\u7684 API \u5BC6\u94A5\u4E0D\u4F1A\u88AB\u6E05\u9664\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)",
      Modality: "\u6A21\u6001",
      "Context Window": "\u4E0A\u4E0B\u6587\u7A97\u53E3",
      text: "\u6587\u672C",
      "text-only": "\u7EAF\u6587\u672C",
      image: "\u56FE\u50CF",
      pdf: "PDF",
      audio: "\u97F3\u9891",
      video: "\u89C6\u9891",
      "not set": "\u672A\u8BBE\u7F6E",
      none: "\u65E0",
      unknown: "\u672A\u77E5",
      "Failed to switch model to '{{modelId}}'.\n\n{{error}}": "\u65E0\u6CD5\u5207\u6362\u5230\u6A21\u578B '{{modelId}}'.\n\n{{error}}",
      "Qwen 3.6 Plus \u2014 efficient hybrid model with leading coding performance": "Qwen 3.6 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",
      "Manage permission rules": "\u7BA1\u7406\u6743\u9650\u89C4\u5219",
      Allow: "\u5141\u8BB8",
      Ask: "\u8BE2\u95EE",
      Deny: "\u62D2\u7EDD",
      Workspace: "\u5DE5\u4F5C\u533A",
      "Qwen Code won't ask before using allowed tools.": "Qwen Code \u4F7F\u7528\u5DF2\u5141\u8BB8\u7684\u5DE5\u5177\u524D\u4E0D\u4F1A\u8BE2\u95EE\u3002",
      "Qwen Code will ask before using these tools.": "Qwen Code \u4F7F\u7528\u8FD9\u4E9B\u5DE5\u5177\u524D\u4F1A\u5148\u8BE2\u95EE\u3002",
      "Qwen Code is not allowed to use denied tools.": "Qwen Code \u4E0D\u5141\u8BB8\u4F7F\u7528\u88AB\u62D2\u7EDD\u7684\u5DE5\u5177\u3002",
      "Manage trusted directories for this workspace.": "\u7BA1\u7406\u6B64\u5DE5\u4F5C\u533A\u7684\u53D7\u4FE1\u4EFB\u76EE\u5F55\u3002",
      "Any use of the {{tool}} tool": "{{tool}} \u5DE5\u5177\u7684\u4EFB\u4F55\u4F7F\u7528",
      "{{tool}} commands matching '{{pattern}}'": "\u5339\u914D '{{pattern}}' \u7684 {{tool}} \u547D\u4EE4",
      "From user settings": "\u6765\u81EA\u7528\u6237\u8BBE\u7F6E",
      "From project settings": "\u6765\u81EA\u9879\u76EE\u8BBE\u7F6E",
      "From session": "\u6765\u81EA\u4F1A\u8BDD",
      "Project settings (local)": "\u9879\u76EE\u8BBE\u7F6E\uFF08\u672C\u5730\uFF09",
      "Saved in .qwen/settings.local.json": "\u4FDD\u5B58\u5728 .qwen/settings.local.json",
      "Project settings": "\u9879\u76EE\u8BBE\u7F6E",
      "Checked in at .qwen/settings.json": "\u4FDD\u5B58\u5728 .qwen/settings.json",
      "User settings": "\u7528\u6237\u8BBE\u7F6E",
      "Saved in at ~/.qwen/settings.json": "\u4FDD\u5B58\u5728 ~/.qwen/settings.json",
      "Add a new rule\u2026": "\u6DFB\u52A0\u65B0\u89C4\u5219\u2026",
      "Add {{type}} permission rule": "\u6DFB\u52A0{{type}}\u6743\u9650\u89C4\u5219",
      "Permission rules are a tool name, optionally followed by a specifier in parentheses.": "\u6743\u9650\u89C4\u5219\u662F\u4E00\u4E2A\u5DE5\u5177\u540D\u79F0\uFF0C\u53EF\u9009\u5730\u540E\u8DDF\u62EC\u53F7\u4E2D\u7684\u9650\u5B9A\u7B26\u3002",
      "e.g.,": "\u4F8B\u5982",
      or: "\u6216",
      "Enter permission rule\u2026": "\u8F93\u5165\u6743\u9650\u89C4\u5219\u2026",
      "Enter to submit \xB7 Esc to cancel": "\u56DE\u8F66\u63D0\u4EA4 \xB7 Esc \u53D6\u6D88",
      "Where should this rule be saved?": "\u6B64\u89C4\u5219\u5E94\u4FDD\u5B58\u5728\u54EA\u91CC\uFF1F",
      "Enter to confirm \xB7 Esc to cancel": "\u56DE\u8F66\u786E\u8BA4 \xB7 Esc \u53D6\u6D88",
      "Delete {{type}} rule?": "\u5220\u9664{{type}}\u89C4\u5219\uFF1F",
      "Are you sure you want to delete this permission rule?": "\u786E\u5B9A\u8981\u5220\u9664\u6B64\u6743\u9650\u89C4\u5219\u5417\uFF1F",
      "Permissions:": "\u6743\u9650\uFF1A",
      "(\u2190/\u2192 or tab to cycle)": "\uFF08\u2190/\u2192 \u6216 tab \u5207\u6362\uFF09",
      "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel": "\u6309 \u2191\u2193 \u5BFC\u822A \xB7 \u56DE\u8F66\u9009\u62E9 \xB7 \u8F93\u5165\u641C\u7D22 \xB7 Esc \u53D6\u6D88",
      "Search\u2026": "\u641C\u7D22\u2026",
      "Use /trust to manage folder trust settings for this workspace.": "\u4F7F\u7528 /trust \u7BA1\u7406\u6B64\u5DE5\u4F5C\u533A\u7684\u6587\u4EF6\u5939\u4FE1\u4EFB\u8BBE\u7F6E\u3002",
      // Workspace directory management
      "Add directory\u2026": "\u6DFB\u52A0\u76EE\u5F55\u2026",
      "Add directory to workspace": "\u6DFB\u52A0\u5DE5\u4F5C\u533A\u76EE\u5F55",
      "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on.": "Qwen Code \u53EF\u4EE5\u8BFB\u53D6\u5DE5\u4F5C\u533A\u4E2D\u7684\u6587\u4EF6\uFF0C\u5E76\u5728\u81EA\u52A8\u63A5\u53D7\u7F16\u8F91\u6A21\u5F0F\u5F00\u542F\u65F6\u8FDB\u884C\u7F16\u8F91\u3002",
      "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on.": "Qwen Code \u5C06\u80FD\u591F\u8BFB\u53D6\u6B64\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\uFF0C\u5E76\u5728\u81EA\u52A8\u63A5\u53D7\u7F16\u8F91\u6A21\u5F0F\u5F00\u542F\u65F6\u8FDB\u884C\u7F16\u8F91\u3002",
      "Enter the path to the directory:": "\u8F93\u5165\u76EE\u5F55\u8DEF\u5F84\uFF1A",
      "Enter directory path\u2026": "\u8F93\u5165\u76EE\u5F55\u8DEF\u5F84\u2026",
      "Tab to complete \xB7 Enter to add \xB7 Esc to cancel": "Tab \u8865\u5168 \xB7 \u56DE\u8F66\u6DFB\u52A0 \xB7 Esc \u53D6\u6D88",
      "Remove directory?": "\u5220\u9664\u76EE\u5F55\uFF1F",
      "Are you sure you want to remove this directory from the workspace?": "\u786E\u5B9A\u8981\u5C06\u6B64\u76EE\u5F55\u4ECE\u5DE5\u4F5C\u533A\u4E2D\u79FB\u9664\u5417\uFF1F",
      "  (Original working directory)": "  \uFF08\u539F\u59CB\u5DE5\u4F5C\u76EE\u5F55\uFF09",
      "  (from settings)": "  \uFF08\u6765\u81EA\u8BBE\u7F6E\uFF09",
      "Directory does not exist.": "\u76EE\u5F55\u4E0D\u5B58\u5728\u3002",
      "Path is not a directory.": "\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55\u3002",
      "This directory is already in the workspace.": "\u6B64\u76EE\u5F55\u5DF2\u5728\u5DE5\u4F5C\u533A\u4E2D\u3002",
      "Already covered by existing directory: {{dir}}": "\u5DF2\u88AB\u73B0\u6709\u76EE\u5F55\u8986\u76D6\uFF1A{{dir}}",
      // ============================================================================
      // 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",
      "Press \u2191 to edit queued messages": "\u6309 \u2191 \u7F16\u8F91\u6392\u961F\u6D88\u606F",
      // ============================================================================
      // 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",
      "Press Ctrl+O to toggle compact mode \u2014 hide tool output and thinking for a cleaner view.": "\u6309 Ctrl+O \u5207\u6362\u7D27\u51D1\u6A21\u5F0F \u2500\u2500 \u9690\u85CF\u5DE5\u5177\u8F93\u51FA\u548C\u601D\u8003\u8FC7\u7A0B\uFF0C\u754C\u9762\u66F4\u7B80\u6D01\u3002",
      "Add a QWEN.md file to give Qwen Code persistent project context.": "\u6DFB\u52A0 QWEN.md \u6587\u4EF6\uFF0C\u4E3A Qwen Code \u63D0\u4F9B\u6301\u4E45\u7684\u9879\u76EE\u4E0A\u4E0B\u6587\u3002",
      "Use /btw to ask a quick side question without disrupting the conversation.": "\u7528 /btw \u5FEB\u901F\u95EE\u4E00\u4E2A\u5C0F\u95EE\u9898\uFF0C\u4E0D\u4F1A\u6253\u65AD\u5F53\u524D\u5BF9\u8BDD\u3002",
      "Context is almost full! Run /compress now or start /new to continue.": "\u4E0A\u4E0B\u6587\u5373\u5C06\u7528\u6EE1\uFF01\u8BF7\u7ACB\u5373\u6267\u884C /compress \u6216\u4F7F\u7528 /new \u5F00\u542F\u65B0\u4F1A\u8BDD\u3002",
      "Context is getting full. Use /compress to free up space.": "\u4E0A\u4E0B\u6587\u7A7A\u95F4\u4E0D\u8DB3\uFF0C\u7528 /compress \u91CA\u653E\u7A7A\u95F4\u3002",
      "Long conversation? /compress summarizes history to free context.": "\u5BF9\u8BDD\u592A\u957F\uFF1F\u7528 /compress \u603B\u7ED3\u5386\u53F2\uFF0C\u91CA\u653E\u4E0A\u4E0B\u6587\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",
      "Current tasks": "\u5F53\u524D\u4EFB\u52A1",
      "... 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",
      "Press Ctrl+Y to retry": "\u6309 Ctrl+Y \u91CD\u8BD5\u3002",
      "No failed request to retry.": "\u6CA1\u6709\u53EF\u91CD\u8BD5\u7684\u5931\u8D25\u8BF7\u6C42\u3002",
      "to retry last request": "\u91CD\u8BD5\u4E0A\u4E00\u6B21\u8BF7\u6C42",
      // ============================================================================
      // Coding Plan Authentication
      // ============================================================================
      "API key cannot be empty.": "API Key \u4E0D\u80FD\u4E3A\u7A7A\u3002",
      'Invalid API key. Coding Plan API keys start with "sk-sp-". Please check.': '\u65E0\u6548\u7684 API Key\uFF0CCoding Plan API Key \u5747\u4EE5 "sk-sp-" \u5F00\u5934\uFF0C\u8BF7\u68C0\u67E5',
      "You can get your Coding Plan API key here": "\u60A8\u53EF\u4EE5\u5728\u8FD9\u91CC\u83B7\u53D6 Coding Plan API Key",
      "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 Alibaba Cloud Coding Plan. Update now?": "\u963F\u91CC\u4E91\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
      // ============================================================================
      "You can configure your API key and models in settings.json": "\u60A8\u53EF\u4EE5\u5728 settings.json \u4E2D\u914D\u7F6E API Key \u548C\u6A21\u578B",
      "Refer to the documentation for setup instructions": "\u8BF7\u53C2\u8003\u6587\u6863\u4E86\u89E3\u914D\u7F6E\u8BF4\u660E",
      // ============================================================================
      // Auth Dialog - View Titles and Labels
      // ============================================================================
      "API-KEY": "API-KEY",
      "Coding Plan": "Coding Plan",
      "Paste your api key of ModelStudio 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",
      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)",
      "Select Region for Coding Plan": "\u9009\u62E9 Coding Plan \u533A\u57DF",
      "Choose based on where your account is registered": "\u8BF7\u6839\u636E\u60A8\u7684\u8D26\u53F7\u6CE8\u518C\u5730\u533A\u9009\u62E9",
      "Enter Coding Plan API Key": "\u8F93\u5165 Coding Plan API Key",
      // ============================================================================
      // 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",
      '{{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",
      // ============================================================================
      // Context Usage
      // ============================================================================
      "Context Usage": "\u4E0A\u4E0B\u6587\u4F7F\u7528\u60C5\u51B5",
      "% used": "% \u5DF2\u7528",
      "% context used": "% \u4E0A\u4E0B\u6587\u5DF2\u7528",
      "Context exceeds limit! Use /compress or /clear to reduce.": "\u4E0A\u4E0B\u6587\u8D85\u51FA\u9650\u5236\uFF01\u8BF7\u4F7F\u7528 /compress \u6216 /clear \u6765\u51CF\u5C11\u4E0A\u4E0B\u6587\u3002",
      "Use /compress or /clear": "\u4F7F\u7528 /compress \u6216 /clear",
      "Context window": "\u4E0A\u4E0B\u6587\u7A97\u53E3",
      Used: "\u5DF2\u7528",
      Free: "\u7A7A\u95F2",
      "Autocompact buffer": "\u81EA\u52A8\u538B\u7F29\u7F13\u51B2\u533A",
      "Usage by category": "\u5206\u7C7B\u7528\u91CF",
      "System prompt": "\u7CFB\u7EDF\u63D0\u793A",
      "Built-in tools": "\u5185\u7F6E\u5DE5\u5177",
      "MCP tools": "MCP \u5DE5\u5177",
      "Memory files": "\u8BB0\u5FC6\u6587\u4EF6",
      Skills: "\u6280\u80FD",
      Messages: "\u6D88\u606F",
      tokens: "tokens",
      "Estimated pre-conversation overhead": "\u9884\u4F30\u5BF9\u8BDD\u524D\u5F00\u9500",
      "No API response yet. Send a message to see actual usage.": "\u6682\u65E0 API \u54CD\u5E94\u3002\u53D1\u9001\u6D88\u606F\u4EE5\u67E5\u770B\u5B9E\u9645\u4F7F\u7528\u60C5\u51B5\u3002",
      "Show context window usage breakdown.": "\u663E\u793A\u4E0A\u4E0B\u6587\u7A97\u53E3\u4F7F\u7528\u60C5\u51B5\u5206\u89E3\u3002",
      "Run /context detail for per-item breakdown.": "\u8FD0\u884C /context detail \u67E5\u770B\u8BE6\u7EC6\u5206\u89E3\u3002",
      'Show context window usage breakdown. Use "/context detail" for per-item breakdown.': '\u663E\u793A\u4E0A\u4E0B\u6587\u7A97\u53E3\u4F7F\u7528\u60C5\u51B5\u5206\u89E3\u3002\u8F93\u5165 "/context detail" \u67E5\u770B\u8BE6\u7EC6\u5206\u89E3\u3002',
      "body loaded": "\u5185\u5BB9\u5DF2\u52A0\u8F7D",
      memory: "\u8BB0\u5FC6",
      "{{region}} configuration updated successfully.": "{{region}} \u914D\u7F6E\u66F4\u65B0\u6210\u529F\u3002",
      "Authenticated successfully with {{region}}. API key and model configs saved to settings.json.": "\u6210\u529F\u901A\u8FC7 {{region}} \u8BA4\u8BC1\u3002API Key \u548C\u6A21\u578B\u914D\u7F6E\u5DF2\u4FDD\u5B58\u81F3 settings.json\u3002",
      "Tip: Use /model to switch between available Coding Plan models.": "\u63D0\u793A\uFF1A\u4F7F\u7528 /model \u5207\u6362\u53EF\u7528\u7684 Coding Plan \u6A21\u578B\u3002",
      // ============================================================================
      // Ask User Question Tool
      // ============================================================================
      "Please answer the following question(s):": "\u8BF7\u56DE\u7B54\u4EE5\u4E0B\u95EE\u9898\uFF1A",
      "Cannot ask user questions in non-interactive mode. Please run in interactive mode to use this tool.": "\u65E0\u6CD5\u5728\u975E\u4EA4\u4E92\u6A21\u5F0F\u4E0B\u8BE2\u95EE\u7528\u6237\u95EE\u9898\u3002\u8BF7\u5728\u4EA4\u4E92\u6A21\u5F0F\u4E0B\u8FD0\u884C\u4EE5\u4F7F\u7528\u6B64\u5DE5\u5177\u3002",
      "User declined to answer the questions.": "\u7528\u6237\u62D2\u7EDD\u56DE\u7B54\u95EE\u9898\u3002",
      "User has provided the following answers:": "\u7528\u6237\u63D0\u4F9B\u4E86\u4EE5\u4E0B\u7B54\u6848\uFF1A",
      "Failed to process user answers:": "\u5904\u7406\u7528\u6237\u7B54\u6848\u5931\u8D25\uFF1A",
      "Type something...": "\u8F93\u5165\u5185\u5BB9...",
      Submit: "\u63D0\u4EA4",
      "Submit answers": "\u63D0\u4EA4\u7B54\u6848",
      Cancel: "\u53D6\u6D88",
      "Your answers:": "\u60A8\u7684\u7B54\u6848\uFF1A",
      "(not answered)": "(\u672A\u56DE\u7B54)",
      "Ready to submit your answers?": "\u51C6\u5907\u597D\u63D0\u4EA4\u60A8\u7684\u7B54\u6848\u4E86\u5417\uFF1F",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select": "\u2191/\u2193: \u5BFC\u822A | \u2190/\u2192: \u5207\u6362\u6807\u7B7E\u9875 | Enter: \u9009\u62E9",
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: \u5BFC\u822A | \u2190/\u2192: \u5207\u6362\u6807\u7B7E\u9875 | Space/Enter: \u5207\u6362 | Esc: \u53D6\u6D88",
      "\u2191/\u2193: Navigate | Space/Enter: Toggle | Esc: Cancel": "\u2191/\u2193: \u5BFC\u822A | Space/Enter: \u5207\u6362 | Esc: \u53D6\u6D88",
      "\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel": "\u2191/\u2193: \u5BFC\u822A | Enter: \u9009\u62E9 | Esc: \u53D6\u6D88",
      // ============================================================================
      // Commands - Auth
      // ============================================================================
      "Configure Qwen authentication information with Qwen-OAuth or Alibaba Cloud Coding Plan": "\u4F7F\u7528 Qwen OAuth \u6216\u963F\u91CC\u4E91\u767E\u70BC Coding Plan \u914D\u7F6E Qwen \u8BA4\u8BC1\u4FE1\u606F",
      "Authenticate using Qwen OAuth": "\u4F7F\u7528 Qwen OAuth \u8FDB\u884C\u8BA4\u8BC1",
      "Authenticate using Alibaba Cloud Coding Plan": "\u4F7F\u7528\u963F\u91CC\u4E91\u767E\u70BC Coding Plan \u8FDB\u884C\u8BA4\u8BC1",
      "Region for Coding Plan (china/global)": "Coding Plan \u533A\u57DF (china/global)",
      "API key for Coding Plan": "Coding Plan \u7684 API \u5BC6\u94A5",
      "Show current authentication status": "\u663E\u793A\u5F53\u524D\u8BA4\u8BC1\u72B6\u6001",
      "Authentication completed successfully.": "\u8BA4\u8BC1\u5B8C\u6210\u3002",
      "Starting Qwen OAuth authentication...": "\u6B63\u5728\u542F\u52A8 Qwen OAuth \u8BA4\u8BC1...",
      "Successfully authenticated with Qwen OAuth.": "\u5DF2\u6210\u529F\u901A\u8FC7 Qwen OAuth \u8BA4\u8BC1\u3002",
      "Failed to authenticate with Qwen OAuth: {{error}}": "Qwen OAuth \u8BA4\u8BC1\u5931\u8D25\uFF1A{{error}}",
      "Processing Alibaba Cloud Coding Plan authentication...": "\u6B63\u5728\u5904\u7406\u963F\u91CC\u4E91\u767E\u70BC Coding Plan \u8BA4\u8BC1...",
      "Successfully authenticated with Alibaba Cloud Coding Plan.": "\u5DF2\u6210\u529F\u901A\u8FC7\u963F\u91CC\u4E91\u767E\u70BC Coding Plan \u8BA4\u8BC1\u3002",
      "Failed to authenticate with Coding Plan: {{error}}": "Coding Plan \u8BA4\u8BC1\u5931\u8D25\uFF1A{{error}}",
      "\u4E2D\u56FD (China)": "\u4E2D\u56FD (China)",
      "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)": "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)",
      Global: "\u5168\u7403",
      "Alibaba Cloud (alibabacloud.com)": "Alibaba Cloud (alibabacloud.com)",
      "Select region for Coding Plan:": "\u9009\u62E9 Coding Plan \u533A\u57DF\uFF1A",
      "Enter your Coding Plan API key: ": "\u8BF7\u8F93\u5165\u60A8\u7684 Coding Plan API \u5BC6\u94A5\uFF1A",
      "Select authentication method:": "\u9009\u62E9\u8BA4\u8BC1\u65B9\u5F0F\uFF1A",
      "\n=== Authentication Status ===\n": "\n=== \u8BA4\u8BC1\u72B6\u6001 ===\n",
      "\u26A0\uFE0F  No authentication method configured.\n": "\u26A0\uFE0F  \u672A\u914D\u7F6E\u8BA4\u8BC1\u65B9\u5F0F\u3002\n",
      "Run one of the following commands to get started:\n": "\u8FD0\u884C\u4EE5\u4E0B\u547D\u4EE4\u4E4B\u4E00\u5F00\u59CB\u914D\u7F6E\uFF1A\n",
      "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)": "  qwen auth qwen-oauth     - \u4F7F\u7528 Qwen OAuth \u767B\u5F55\uFF08\u5DF2\u505C\u7528\uFF09",
      "  qwen auth coding-plan      - Authenticate with Alibaba Cloud Coding Plan\n": "  qwen auth coding-plan      - \u4F7F\u7528\u963F\u91CC\u4E91\u767E\u70BC Coding Plan \u8BA4\u8BC1\n",
      "Or simply run:": "\u6216\u8005\u76F4\u63A5\u8FD0\u884C\uFF1A",
      "  qwen auth                - Interactive authentication setup\n": "  qwen auth                - \u4EA4\u4E92\u5F0F\u8BA4\u8BC1\u914D\u7F6E\n",
      "\u2713 Authentication Method: Qwen OAuth": "\u2713 \u8BA4\u8BC1\u65B9\u5F0F\uFF1AQwen OAuth",
      "  Type: Free tier (discontinued 2026-04-15)": "  \u7C7B\u578B\uFF1A\u514D\u8D39\u989D\u5EA6\uFF082026-04-15 \u5DF2\u505C\u7528\uFF09",
      "  Limit: No longer available": "  \u9650\u989D\uFF1A\u5DF2\u4E0D\u53EF\u7528",
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.": "Qwen OAuth \u514D\u8D39\u989D\u5EA6\u5DF2\u4E8E 2026-04-15 \u505C\u7528\u3002\u8BF7\u8FD0\u884C /auth \u5207\u6362\u5230 Coding Plan\u3001OpenRouter\u3001Fireworks AI \u6216\u5176\u4ED6\u670D\u52A1\u5546\u3002",
      "  Models: Qwen latest models\n": "  \u6A21\u578B\uFF1AQwen \u6700\u65B0\u6A21\u578B\n",
      "\u2713 Authentication Method: Alibaba Cloud Coding Plan": "\u2713 \u8BA4\u8BC1\u65B9\u5F0F\uFF1A\u963F\u91CC\u4E91\u767E\u70BC Coding Plan",
      "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC": "\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC",
      "Global - Alibaba Cloud": "\u5168\u7403 - Alibaba Cloud",
      "  Region: {{region}}": "  \u533A\u57DF\uFF1A{{region}}",
      "  Current Model: {{model}}": "  \u5F53\u524D\u6A21\u578B\uFF1A{{model}}",
      "  Config Version: {{version}}": "  \u914D\u7F6E\u7248\u672C\uFF1A{{version}}",
      "  Status: API key configured\n": "  \u72B6\u6001\uFF1AAPI \u5BC6\u94A5\u5DF2\u914D\u7F6E\n",
      "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)": "\u26A0\uFE0F  \u8BA4\u8BC1\u65B9\u5F0F\uFF1A\u963F\u91CC\u4E91\u767E\u70BC Coding Plan\uFF08\u4E0D\u5B8C\u6574\uFF09",
      "  Issue: API key not found in environment or settings\n": "  \u95EE\u9898\uFF1A\u5728\u73AF\u5883\u53D8\u91CF\u6216\u8BBE\u7F6E\u4E2D\u672A\u627E\u5230 API \u5BC6\u94A5\n",
      "  Run `qwen auth coding-plan` to re-configure.\n": "  \u8FD0\u884C `qwen auth coding-plan` \u91CD\u65B0\u914D\u7F6E\u3002\n",
      "\u2713 Authentication Method: {{type}}": "\u2713 \u8BA4\u8BC1\u65B9\u5F0F\uFF1A{{type}}",
      "  Status: Configured\n": "  \u72B6\u6001\uFF1A\u5DF2\u914D\u7F6E\n",
      "Failed to check authentication status: {{error}}": "\u68C0\u67E5\u8BA4\u8BC1\u72B6\u6001\u5931\u8D25\uFF1A{{error}}",
      "Select an option:": "\u8BF7\u9009\u62E9\uFF1A",
      "Raw mode not available. Please run in an interactive terminal.": "\u539F\u59CB\u6A21\u5F0F\u4E0D\u53EF\u7528\u3002\u8BF7\u5728\u4EA4\u4E92\u5F0F\u7EC8\u7AEF\u4E2D\u8FD0\u884C\u3002",
      "(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n": "(\u4F7F\u7528 \u2191 \u2193 \u7BAD\u5934\u5BFC\u822A\uFF0CEnter \u9009\u62E9\uFF0CCtrl+C \u9000\u51FA)\n",
      compact: "\u7D27\u51D1",
      "compact mode: on (Ctrl+O off)": "\u7D27\u51D1\u6A21\u5F0F\uFF1A\u5F00\uFF08Ctrl+O \u5173\u95ED\uFF09",
      "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).": "\u7D27\u51D1\u6A21\u5F0F\u4E0B\u9690\u85CF\u5DE5\u5177\u8F93\u51FA\u548C\u601D\u8003\u8FC7\u7A0B\uFF0C\u754C\u9762\u66F4\u7B80\u6D01\uFF08Ctrl+O \u5207\u6362\uFF09\u3002",
      "Press Ctrl+O to show full tool output": "\u6309 Ctrl+O \u67E5\u770B\u8BE6\u7EC6\u5DE5\u5177\u8C03\u7528\u7ED3\u679C",
      "Switch to plan mode or exit plan mode": "\u5207\u6362\u5230\u8BA1\u5212\u6A21\u5F0F\u6216\u9000\u51FA\u8BA1\u5212\u6A21\u5F0F",
      "Exited plan mode. Previous approval mode restored.": "\u5DF2\u9000\u51FA\u8BA1\u5212\u6A21\u5F0F\uFF0C\u5DF2\u6062\u590D\u4E4B\u524D\u7684\u5BA1\u6279\u6A21\u5F0F\u3002",
      "Enabled plan mode. The agent will analyze and plan without executing tools.": "\u542F\u7528\u8BA1\u5212\u6A21\u5F0F\u3002\u667A\u80FD\u4F53\u5C06\u53EA\u5206\u6790\u548C\u89C4\u5212\uFF0C\u800C\u4E0D\u6267\u884C\u5DE5\u5177\u3002",
      'Already in plan mode. Use "/plan exit" to exit plan mode.': '\u5DF2\u5904\u4E8E\u8BA1\u5212\u6A21\u5F0F\u3002\u4F7F\u7528 "/plan exit" \u9000\u51FA\u8BA1\u5212\u6A21\u5F0F\u3002',
      'Not in plan mode. Use "/plan" to enter plan mode first.': '\u672A\u5904\u4E8E\u8BA1\u5212\u6A21\u5F0F\u3002\u8BF7\u5148\u4F7F\u7528 "/plan" \u8FDB\u5165\u8BA1\u5212\u6A21\u5F0F\u3002',
      "Set up Qwen Code's status line UI": "\u914D\u7F6E Qwen Code \u7684\u72B6\u6001\u680F"
    };
  }
});

// import("./locales/**/*.js") in packages/cli/src/i18n/index.ts
var globImport_locales_js;
var init_ = __esm({
  'import("./locales/**/*.js") in packages/cli/src/i18n/index.ts'() {
    globImport_locales_js = __glob({
      "./locales/ca.js": () => Promise.resolve().then(() => (init_ca2(), ca_exports)),
      "./locales/de.js": () => Promise.resolve().then(() => (init_de2(), de_exports)),
      "./locales/en.js": () => Promise.resolve().then(() => (init_en3(), en_exports)),
      "./locales/fr.js": () => Promise.resolve().then(() => (init_fr2(), fr_exports)),
      "./locales/ja.js": () => Promise.resolve().then(() => (init_ja2(), ja_exports)),
      "./locales/pt.js": () => Promise.resolve().then(() => (init_pt2(), pt_exports)),
      "./locales/ru.js": () => Promise.resolve().then(() => (init_ru2(), ru_exports)),
      "./locales/zh-TW.js": () => Promise.resolve().then(() => (init_zh_TW2(), zh_TW_exports)),
      "./locales/zh.js": () => Promise.resolve().then(() => (init_zh(), zh_exports))
    });
  }
});

// packages/cli/src/i18n/index.ts
import * as fs102 from "node:fs";
import * as path98 from "node:path";
import { fileURLToPath as fileURLToPath10, pathToFileURL as pathToFileURL6 } from "node:url";
import { homedir as homedir19 } from "node:os";
function detectSystemLanguage() {
  const envLang = process.env["QWEN_CODE_LANG"] || process.env["LANG"];
  if (envLang) {
    const normalized2 = envLang.replace(/_/g, "-").toLowerCase();
    for (const lang of SUPPORTED_LANGUAGES) {
      if (normalized2.startsWith(lang.code.toLowerCase())) return lang.code;
    }
  }
  try {
    const locale = Intl.DateTimeFormat().resolvedOptions().locale;
    const normalized2 = locale.replace(/_/g, "-").toLowerCase();
    for (const lang of SUPPORTED_LANGUAGES) {
      if (normalized2.startsWith(lang.code.toLowerCase())) return lang.code;
    }
  } catch {
  }
  return "en";
}
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 (!fs102.existsSync(dir)) {
        continue;
      }
      const jsPath = getLocalePath(lang, isUser);
      if (!fs102.existsSync(jsPath)) {
        continue;
      }
      try {
        const fileUrl = pathToFileURL6(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 (error40) {
        if (isUser) {
          writeStderrLine(
            `Failed to load translations from user directory for ${lang}: ${error40 instanceof Error ? error40.message : String(error40)}`
          );
        } else {
          writeStderrLine(
            `Failed to load JS translations for ${lang}: ${error40 instanceof Error ? error40.message : String(error40)}`
          );
        }
        continue;
      }
    }
    translationCache[lang] = {};
    return {};
  })();
  loadingPromises[lang] = loadPromise;
  loadPromise.finally(() => {
    delete loadingPromises[lang];
  });
  return loadPromise;
}
function interpolate(template, params) {
  if (!params) return template;
  return template.replace(
    /\{\{(\w+)\}\}/g,
    (match2, key) => params[key] ?? match2
  );
}
function resolveLanguage(lang) {
  return lang === "auto" ? detectSystemLanguage() : lang;
}
async function setLanguageAsync(lang) {
  currentLanguage = resolveLanguage(lang);
  translations = await loadTranslationsAsync(currentLanguage);
}
function getCurrentLanguage() {
  return currentLanguage;
}
function t4(key, params) {
  const translation = translations[key] ?? key;
  if (Array.isArray(translation)) {
    return key;
  }
  return interpolate(translation, params);
}
function ta(key) {
  const translation = translations[key];
  if (Array.isArray(translation)) {
    return translation;
  }
  return [];
}
async function initializeI18n(lang) {
  await setLanguageAsync(lang ?? "auto");
}
var currentLanguage, translations, translationCache, loadingPromises, getBuiltinLocalesDir, getUserLocalesDir, getLocalePath;
var init_i18n = __esm({
  "packages/cli/src/i18n/index.ts"() {
    "use strict";
    init_esbuild_shims();
    init_stdioHelpers();
    init_languages();
    init_();
    currentLanguage = "en";
    translations = {};
    translationCache = {};
    loadingPromises = {};
    getBuiltinLocalesDir = /* @__PURE__ */ __name(() => {
      const __filename5 = fileURLToPath10(import.meta.url);
      return path98.join(path98.dirname(__filename5), "locales");
    }, "getBuiltinLocalesDir");
    getUserLocalesDir = /* @__PURE__ */ __name(() => path98.join(homedir19(), ".qwen", "locales"), "getUserLocalesDir");
    getLocalePath = /* @__PURE__ */ __name((lang, useUserDir = false) => {
      const baseDir = useUserDir ? getUserLocalesDir() : getBuiltinLocalesDir();
      return path98.join(baseDir, `${lang}.js`);
    }, "getLocalePath");
    __name(detectSystemLanguage, "detectSystemLanguage");
    __name(loadTranslationsAsync, "loadTranslationsAsync");
    __name(interpolate, "interpolate");
    __name(resolveLanguage, "resolveLanguage");
    __name(setLanguageAsync, "setLanguageAsync");
    __name(getCurrentLanguage, "getCurrentLanguage");
    __name(t4, "t");
    __name(ta, "ta");
    __name(initializeI18n, "initializeI18n");
  }
});

// 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, factory2) {
      if (typeof exports2 === "object" && typeof module2 === "object")
        module2.exports = factory2();
      else if (typeof define === "function" && define.amd)
        define([], factory2);
      else if (typeof exports2 === "object")
        exports2["esprima"] = factory2();
      else
        root["esprima"] = factory2();
    }, "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 parse17(code2, options2, delegate) {
              var commentHandler = null;
              var proxyDelegate = /* @__PURE__ */ __name(function(node, metadata2) {
                if (delegate) {
                  delegate(node, metadata2);
                }
                if (commentHandler) {
                  commentHandler.visit(node, metadata2);
                }
              }, "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(parse17, "parse");
            exports3.parse = parse17;
            function parseModule(code2, options2, delegate) {
              var parsingOptions = options2 || {};
              parsingOptions.sourceType = "module";
              return parse17(code2, parsingOptions, delegate);
            }
            __name(parseModule, "parseModule");
            exports3.parseModule = parseModule;
            function parseScript(code2, options2, delegate) {
              var parsingOptions = options2 || {};
              parsingOptions.sourceType = "script";
              return parse17(code2, parsingOptions, delegate);
            }
            __name(parseScript, "parseScript");
            exports3.parseScript = parseScript;
            function tokenize7(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(tokenize7, "tokenize");
            exports3.tokenize = tokenize7;
            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, metadata2) {
                if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
                  var innerComments = [];
                  for (var i4 = this.leading.length - 1; i4 >= 0; --i4) {
                    var entry = this.leading[i4];
                    if (metadata2.end.offset >= entry.start) {
                      innerComments.unshift(entry.comment);
                      this.leading.splice(i4, 1);
                      this.trailing.splice(i4, 1);
                    }
                  }
                  if (innerComments.length) {
                    node.innerComments = innerComments;
                  }
                }
              };
              CommentHandler2.prototype.findTrailingComments = function(metadata2) {
                var trailingComments = [];
                if (this.trailing.length > 0) {
                  for (var i4 = this.trailing.length - 1; i4 >= 0; --i4) {
                    var entry_1 = this.trailing[i4];
                    if (entry_1.start >= metadata2.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] >= metadata2.end.offset) {
                    trailingComments = entry.node.trailingComments;
                    delete entry.node.trailingComments;
                  }
                }
                return trailingComments;
              };
              CommentHandler2.prototype.findLeadingComments = function(metadata2) {
                var leadingComments = [];
                var target;
                while (this.stack.length > 0) {
                  var entry = this.stack[this.stack.length - 1];
                  if (entry && entry.start >= metadata2.start.offset) {
                    target = entry.node;
                    this.stack.pop();
                  } else {
                    break;
                  }
                }
                if (target) {
                  var count = target.leadingComments ? target.leadingComments.length : 0;
                  for (var i4 = count - 1; i4 >= 0; --i4) {
                    var comment = target.leadingComments[i4];
                    if (comment.range[1] <= metadata2.start.offset) {
                      leadingComments.unshift(comment);
                      target.leadingComments.splice(i4, 1);
                    }
                  }
                  if (target.leadingComments && target.leadingComments.length === 0) {
                    delete target.leadingComments;
                  }
                  return leadingComments;
                }
                for (var i4 = this.leading.length - 1; i4 >= 0; --i4) {
                  var entry = this.leading[i4];
                  if (entry.start <= metadata2.start.offset) {
                    leadingComments.unshift(entry.comment);
                    this.leading.splice(i4, 1);
                  }
                }
                return leadingComments;
              };
              CommentHandler2.prototype.visitNode = function(node, metadata2) {
                if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
                  return;
                }
                this.insertInnerComments(node, metadata2);
                var trailingComments = this.findTrailingComments(metadata2);
                var leadingComments = this.findLeadingComments(metadata2);
                if (leadingComments.length > 0) {
                  node.leadingComments = leadingComments;
                }
                if (trailingComments.length > 0) {
                  node.trailingComments = trailingComments;
                }
                this.stack.push({
                  node,
                  start: metadata2.start.offset
                });
              };
              CommentHandler2.prototype.visitComment = function(node, metadata2) {
                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: [metadata2.start.offset, metadata2.end.offset]
                    },
                    start: metadata2.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, metadata2) {
                if (node.type === "LineComment") {
                  this.visitComment(node, metadata2);
                } else if (node.type === "BlockComment") {
                  this.visitComment(node, metadata2);
                } else if (this.attach) {
                  this.visitNode(node, metadata2);
                }
              };
              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 start2 = 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: start2,
                    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 start2 = this.scanner.index;
                  this.scanner.index += value.length;
                  return {
                    type: 7,
                    value,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start: start2,
                    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 start2 = 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(start2, this.scanner.index);
                  return {
                    type: 100,
                    value: id,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start: start2,
                    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 start2 = 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: start2,
                  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 name4 = this.parseJSXAttributeName();
                var value = null;
                if (this.matchJSX("=")) {
                  this.expectJSX("=");
                  value = this.parseJSXAttributeValue();
                }
                return this.finalize(node, new JSXNode.JSXAttribute(name4, 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 name4 = this.parseJSXElementName();
                var attributes = this.parseJSXAttributes();
                var selfClosing = this.matchJSX("/");
                if (selfClosing) {
                  this.expectJSX("/");
                }
                this.expectJSX(">");
                return this.finalize(node, new JSXNode.JSXOpeningElement(name4, 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 name4 = this.parseJSXElementName();
                var attributes = this.parseJSXAttributes();
                var selfClosing = this.matchJSX("/");
                if (selfClosing) {
                  this.expectJSX("/");
                }
                this.expectJSX(">");
                return this.finalize(node, new JSXNode.JSXOpeningElement(name4, 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(name4) {
                this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
                this.name = name4;
              }
              __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(name4) {
                this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
                this.name = name4;
              }
              __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(name4, value) {
                this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
                this.name = name4;
                this.value = value;
              }
              __name(JSXAttribute2, "JSXAttribute");
              return JSXAttribute2;
            }();
            exports3.JSXAttribute = JSXAttribute;
            var JSXNamespacedName = /* @__PURE__ */ function() {
              function JSXNamespacedName2(namespace, name4) {
                this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
                this.namespace = namespace;
                this.name = name4;
              }
              __name(JSXNamespacedName2, "JSXNamespacedName");
              return JSXNamespacedName2;
            }();
            exports3.JSXNamespacedName = JSXNamespacedName;
            var JSXOpeningElement = /* @__PURE__ */ function() {
              function JSXOpeningElement2(name4, selfClosing, attributes) {
                this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
                this.name = name4;
                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, body2, expression) {
                this.type = syntax_1.Syntax.ArrowFunctionExpression;
                this.id = null;
                this.params = params;
                this.body = body2;
                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, body2, expression) {
                this.type = syntax_1.Syntax.ArrowFunctionExpression;
                this.id = null;
                this.params = params;
                this.body = body2;
                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, body2) {
                this.type = syntax_1.Syntax.FunctionDeclaration;
                this.id = id;
                this.params = params;
                this.body = body2;
                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, body2) {
                this.type = syntax_1.Syntax.FunctionExpression;
                this.id = id;
                this.params = params;
                this.body = body2;
                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(body2) {
                this.type = syntax_1.Syntax.BlockStatement;
                this.body = body2;
              }
              __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, args2) {
                this.type = syntax_1.Syntax.CallExpression;
                this.callee = callee;
                this.arguments = args2;
              }
              __name(CallExpression2, "CallExpression");
              return CallExpression2;
            }();
            exports3.CallExpression = CallExpression;
            var CatchClause = /* @__PURE__ */ function() {
              function CatchClause2(param, body2) {
                this.type = syntax_1.Syntax.CatchClause;
                this.param = param;
                this.body = body2;
              }
              __name(CatchClause2, "CatchClause");
              return CatchClause2;
            }();
            exports3.CatchClause = CatchClause;
            var ClassBody = /* @__PURE__ */ function() {
              function ClassBody2(body2) {
                this.type = syntax_1.Syntax.ClassBody;
                this.body = body2;
              }
              __name(ClassBody2, "ClassBody");
              return ClassBody2;
            }();
            exports3.ClassBody = ClassBody;
            var ClassDeclaration = /* @__PURE__ */ function() {
              function ClassDeclaration2(id, superClass, body2) {
                this.type = syntax_1.Syntax.ClassDeclaration;
                this.id = id;
                this.superClass = superClass;
                this.body = body2;
              }
              __name(ClassDeclaration2, "ClassDeclaration");
              return ClassDeclaration2;
            }();
            exports3.ClassDeclaration = ClassDeclaration;
            var ClassExpression = /* @__PURE__ */ function() {
              function ClassExpression2(id, superClass, body2) {
                this.type = syntax_1.Syntax.ClassExpression;
                this.id = id;
                this.superClass = superClass;
                this.body = body2;
              }
              __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(test2, consequent, alternate) {
                this.type = syntax_1.Syntax.ConditionalExpression;
                this.test = test2;
                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(body2, test2) {
                this.type = syntax_1.Syntax.DoWhileStatement;
                this.body = body2;
                this.test = test2;
              }
              __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, body2) {
                this.type = syntax_1.Syntax.ForInStatement;
                this.left = left3;
                this.right = right3;
                this.body = body2;
                this.each = false;
              }
              __name(ForInStatement2, "ForInStatement");
              return ForInStatement2;
            }();
            exports3.ForInStatement = ForInStatement;
            var ForOfStatement = /* @__PURE__ */ function() {
              function ForOfStatement2(left3, right3, body2) {
                this.type = syntax_1.Syntax.ForOfStatement;
                this.left = left3;
                this.right = right3;
                this.body = body2;
              }
              __name(ForOfStatement2, "ForOfStatement");
              return ForOfStatement2;
            }();
            exports3.ForOfStatement = ForOfStatement;
            var ForStatement = /* @__PURE__ */ function() {
              function ForStatement2(init2, test2, update2, body2) {
                this.type = syntax_1.Syntax.ForStatement;
                this.init = init2;
                this.test = test2;
                this.update = update2;
                this.body = body2;
              }
              __name(ForStatement2, "ForStatement");
              return ForStatement2;
            }();
            exports3.ForStatement = ForStatement;
            var FunctionDeclaration = /* @__PURE__ */ function() {
              function FunctionDeclaration2(id, params, body2, generator) {
                this.type = syntax_1.Syntax.FunctionDeclaration;
                this.id = id;
                this.params = params;
                this.body = body2;
                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, body2, generator) {
                this.type = syntax_1.Syntax.FunctionExpression;
                this.id = id;
                this.params = params;
                this.body = body2;
                this.generator = generator;
                this.expression = false;
                this.async = false;
              }
              __name(FunctionExpression2, "FunctionExpression");
              return FunctionExpression2;
            }();
            exports3.FunctionExpression = FunctionExpression;
            var Identifier = /* @__PURE__ */ function() {
              function Identifier2(name4) {
                this.type = syntax_1.Syntax.Identifier;
                this.name = name4;
              }
              __name(Identifier2, "Identifier");
              return Identifier2;
            }();
            exports3.Identifier = Identifier;
            var IfStatement = /* @__PURE__ */ function() {
              function IfStatement2(test2, consequent, alternate) {
                this.type = syntax_1.Syntax.IfStatement;
                this.test = test2;
                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, body2) {
                this.type = syntax_1.Syntax.LabeledStatement;
                this.label = label;
                this.body = body2;
              }
              __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 Module2 = /* @__PURE__ */ function() {
              function Module3(body2) {
                this.type = syntax_1.Syntax.Program;
                this.body = body2;
                this.sourceType = "module";
              }
              __name(Module3, "Module");
              return Module3;
            }();
            exports3.Module = Module2;
            var NewExpression = /* @__PURE__ */ function() {
              function NewExpression2(callee, args2) {
                this.type = syntax_1.Syntax.NewExpression;
                this.callee = callee;
                this.arguments = args2;
              }
              __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, flags2) {
                this.type = syntax_1.Syntax.Literal;
                this.value = value;
                this.raw = raw2;
                this.regex = { pattern, flags: flags2 };
              }
              __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(body2) {
                this.type = syntax_1.Syntax.Program;
                this.body = body2;
                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(test2, consequent) {
                this.type = syntax_1.Syntax.SwitchCase;
                this.test = test2;
                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, init2) {
                this.type = syntax_1.Syntax.VariableDeclarator;
                this.id = id;
                this.init = init2;
              }
              __name(VariableDeclarator2, "VariableDeclarator");
              return VariableDeclarator2;
            }();
            exports3.VariableDeclarator = VariableDeclarator;
            var WhileStatement = /* @__PURE__ */ function() {
              function WhileStatement2(test2, body2) {
                this.type = syntax_1.Syntax.WhileStatement;
                this.test = test2;
                this.body = body2;
              }
              __name(WhileStatement2, "WhileStatement");
              return WhileStatement2;
            }();
            exports3.WhileStatement = WhileStatement;
            var WithStatement = /* @__PURE__ */ function() {
              function WithStatement2(object3, body2) {
                this.type = syntax_1.Syntax.WithStatement;
                this.object = object3;
                this.body = body2;
              }
              __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 Parser6 = function() {
              function Parser7(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(Parser7, "Parser");
              Parser7.prototype.throwError = function(messageFormat) {
                var values = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                  values[_i - 1] = arguments[_i];
                }
                var args2 = Array.prototype.slice.call(arguments, 1);
                var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) {
                  assert_1.assert(idx < args2.length, "Message reference must be in range");
                  return args2[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);
              };
              Parser7.prototype.tolerateError = function(messageFormat) {
                var values = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                  values[_i - 1] = arguments[_i];
                }
                var args2 = Array.prototype.slice.call(arguments, 1);
                var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) {
                  assert_1.assert(idx < args2.length, "Message reference must be in range");
                  return args2[idx];
                });
                var index = this.lastMarker.index;
                var line = this.scanner.lineNumber;
                var column = this.lastMarker.column + 1;
                this.errorHandler.tolerateError(index, line, column, msg);
              };
              Parser7.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);
                }
              };
              Parser7.prototype.throwUnexpectedToken = function(token2, message) {
                throw this.unexpectedTokenError(token2, message);
              };
              Parser7.prototype.tolerateUnexpectedToken = function(token2, message) {
                this.errorHandler.tolerate(this.unexpectedTokenError(token2, message));
              };
              Parser7.prototype.collectComments = function() {
                if (!this.config.comment) {
                  this.scanner.scanComments();
                } else {
                  var comments = this.scanner.scanComments();
                  if (comments.length > 0 && this.delegate) {
                    for (var i4 = 0; i4 < comments.length; ++i4) {
                      var e4 = comments[i4];
                      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 metadata2 = {
                        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, metadata2);
                    }
                  }
                }
              };
              Parser7.prototype.getTokenRaw = function(token2) {
                return this.scanner.source.slice(token2.start, token2.end);
              };
              Parser7.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 flags2 = token2.flags;
                  t5.regex = { pattern, flags: flags2 };
                }
                return t5;
              };
              Parser7.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;
              };
              Parser7.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;
              };
              Parser7.prototype.createNode = function() {
                return {
                  index: this.startMarker.index,
                  line: this.startMarker.line,
                  column: this.startMarker.column
                };
              };
              Parser7.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
                };
              };
              Parser7.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 metadata2 = {
                    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, metadata2);
                }
                return node;
              };
              Parser7.prototype.expect = function(value) {
                var token2 = this.nextToken();
                if (token2.type !== 7 || token2.value !== value) {
                  this.throwUnexpectedToken(token2);
                }
              };
              Parser7.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(",");
                }
              };
              Parser7.prototype.expectKeyword = function(keyword) {
                var token2 = this.nextToken();
                if (token2.type !== 4 || token2.value !== keyword) {
                  this.throwUnexpectedToken(token2);
                }
              };
              Parser7.prototype.match = function(value) {
                return this.lookahead.type === 7 && this.lookahead.value === value;
              };
              Parser7.prototype.matchKeyword = function(keyword) {
                return this.lookahead.type === 4 && this.lookahead.value === keyword;
              };
              Parser7.prototype.matchContextualKeyword = function(keyword) {
                return this.lookahead.type === 3 && this.lookahead.value === keyword;
              };
              Parser7.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 === "|=";
              };
              Parser7.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;
              };
              Parser7.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;
              };
              Parser7.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;
                }
              };
              Parser7.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;
              };
              Parser7.prototype.parseSpreadElement = function() {
                var node = this.createNode();
                this.expect("...");
                var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
                return this.finalize(node, new Node5.SpreadElement(arg));
              };
              Parser7.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));
              };
              Parser7.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 body2 = 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 body2;
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.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;
              };
              Parser7.prototype.isPropertyKey = function(key, value) {
                return key.type === syntax_1.Syntax.Identifier && key.name === value || key.type === syntax_1.Syntax.Literal && key.value === value;
              };
              Parser7.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 init2 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      value = this.finalize(node, new Node5.AssignmentPattern(id, init2));
                    } else {
                      shorthand = true;
                      value = id;
                    }
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                }
                return this.finalize(node, new Node5.Property(kind2, key, computed, value, method, shorthand));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.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 i4 = 0; i4 < expr.elements.length; i4++) {
                      if (expr.elements[i4] !== null) {
                        this.reinterpretExpressionAsPattern(expr.elements[i4]);
                      }
                    }
                    break;
                  case syntax_1.Syntax.ObjectExpression:
                    expr.type = syntax_1.Syntax.ObjectPattern;
                    for (var i4 = 0; i4 < expr.properties.length; i4++) {
                      this.reinterpretExpressionAsPattern(expr.properties[i4].value);
                    }
                    break;
                  case syntax_1.Syntax.AssignmentExpression:
                    expr.type = syntax_1.Syntax.AssignmentPattern;
                    delete expr.operator;
                    this.reinterpretExpressionAsPattern(expr.left);
                    break;
                  default:
                    break;
                }
              };
              Parser7.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 i4 = 0; i4 < expressions.length; i4++) {
                            this.reinterpretExpressionAsPattern(expressions[i4]);
                          }
                          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 i4 = 0; i4 < expressions.length; i4++) {
                            this.reinterpretExpressionAsPattern(expressions[i4]);
                          }
                          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 i4 = 0; i4 < expr.expressions.length; i4++) {
                              this.reinterpretExpressionAsPattern(expr.expressions[i4]);
                            }
                          } 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;
              };
              Parser7.prototype.parseArguments = function() {
                this.expect("(");
                var args2 = [];
                if (!this.match(")")) {
                  while (true) {
                    var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAssignmentExpression);
                    args2.push(expr);
                    if (this.match(")")) {
                      break;
                    }
                    this.expectCommaSeparator();
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return args2;
              };
              Parser7.prototype.isIdentifierName = function(token2) {
                return token2.type === 3 || token2.type === 4 || token2.type === 1 || token2.type === 5;
              };
              Parser7.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));
              };
              Parser7.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 args2 = this.match("(") ? this.parseArguments() : [];
                  expr = new Node5.NewExpression(callee, args2);
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return this.finalize(node, expr);
              };
              Parser7.prototype.parseAsyncArgument = function() {
                var arg = this.parseAssignmentExpression();
                this.context.firstCoverInitializedNameError = null;
                return arg;
              };
              Parser7.prototype.parseAsyncArguments = function() {
                this.expect("(");
                var args2 = [];
                if (!this.match(")")) {
                  while (true) {
                    var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAsyncArgument);
                    args2.push(expr);
                    if (this.match(")")) {
                      break;
                    }
                    this.expectCommaSeparator();
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return args2;
              };
              Parser7.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 args2 = asyncArrow ? this.parseAsyncArguments() : this.parseArguments();
                    expr = this.finalize(this.startNode(startToken), new Node5.CallExpression(expr, args2));
                    if (asyncArrow && this.match("=>")) {
                      for (var i4 = 0; i4 < args2.length; ++i4) {
                        this.reinterpretExpressionAsPattern(args2[i4]);
                      }
                      expr = {
                        type: ArrowParameterPlaceHolder,
                        params: args2,
                        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;
              };
              Parser7.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());
              };
              Parser7.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;
              };
              Parser7.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;
              };
              Parser7.prototype.parseAwaitExpression = function() {
                var node = this.createNode();
                this.nextToken();
                var argument = this.parseUnaryExpression();
                return this.finalize(node, new Node5.AwaitExpression(argument));
              };
              Parser7.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;
              };
              Parser7.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;
              };
              Parser7.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;
              };
              Parser7.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 i4 = stack.length - 1;
                  expr = stack[i4];
                  var lastMarker = markers.pop();
                  while (i4 > 1) {
                    var marker = markers.pop();
                    var lastLineStart = lastMarker && lastMarker.lineStart;
                    var node = this.startNode(marker, lastLineStart);
                    var operator2 = stack[i4 - 1];
                    expr = this.finalize(node, new Node5.BinaryExpression(operator2, stack[i4 - 2], expr));
                    i4 -= 2;
                    lastMarker = marker;
                  }
                }
                return expr;
              };
              Parser7.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;
              };
              Parser7.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 i4 = 0; i4 < param.elements.length; i4++) {
                      if (param.elements[i4] !== null) {
                        this.checkPatternParam(options2, param.elements[i4]);
                      }
                    }
                    break;
                  case syntax_1.Syntax.ObjectPattern:
                    for (var i4 = 0; i4 < param.properties.length; i4++) {
                      this.checkPatternParam(options2, param.properties[i4].value);
                    }
                    break;
                  default:
                    break;
                }
                options2.simple = options2.simple && param instanceof Node5.Identifier;
              };
              Parser7.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 i4 = 0; i4 < params.length; ++i4) {
                  var param = params[i4];
                  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[i4] = param;
                }
                if (this.context.strict || !this.context.allowYield) {
                  for (var i4 = 0; i4 < params.length; ++i4) {
                    var param = params[i4];
                    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
                };
              };
              Parser7.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 body2 = void 0;
                      if (this.match("{")) {
                        var previousAllowIn = this.context.allowIn;
                        this.context.allowIn = true;
                        body2 = this.parseFunctionSourceElements();
                        this.context.allowIn = previousAllowIn;
                      } else {
                        body2 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      }
                      var expression = body2.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, body2, expression)) : this.finalize(node, new Node5.ArrowFunctionExpression(list3.params, body2, 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;
              };
              Parser7.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;
              };
              Parser7.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;
              };
              Parser7.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));
              };
              Parser7.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 init2 = null;
                if (kind2 === "const") {
                  if (!this.matchKeyword("in") && !this.matchContextualKeyword("of")) {
                    if (this.match("=")) {
                      this.nextToken();
                      init2 = 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("=");
                  init2 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                }
                return this.finalize(node, new Node5.VariableDeclarator(id, init2));
              };
              Parser7.prototype.parseBindingList = function(kind2, options2) {
                var list3 = [this.parseLexicalBinding(kind2, options2)];
                while (this.match(",")) {
                  this.nextToken();
                  list3.push(this.parseLexicalBinding(kind2, options2));
                }
                return list3;
              };
              Parser7.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";
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.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 init2 = 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(init2, expr));
                  } else if (!this.match(":")) {
                    params.push(keyToken);
                    shorthand = true;
                    value = init2;
                  } 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));
              };
              Parser7.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));
              };
              Parser7.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;
              };
              Parser7.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;
              };
              Parser7.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));
              };
              Parser7.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 init2 = null;
                if (this.match("=")) {
                  this.nextToken();
                  init2 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                } else if (id.type !== syntax_1.Syntax.Identifier && !options2.inFor) {
                  this.expect("=");
                }
                return this.finalize(node, new Node5.VariableDeclarator(id, init2));
              };
              Parser7.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;
              };
              Parser7.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"));
              };
              Parser7.prototype.parseEmptyStatement = function() {
                var node = this.createNode();
                this.expect(";");
                return this.finalize(node, new Node5.EmptyStatement());
              };
              Parser7.prototype.parseExpressionStatement = function() {
                var node = this.createNode();
                var expr = this.parseExpression();
                this.consumeSemicolon();
                return this.finalize(node, new Node5.ExpressionStatement(expr));
              };
              Parser7.prototype.parseIfClause = function() {
                if (this.context.strict && this.matchKeyword("function")) {
                  this.tolerateError(messages_1.Messages.StrictFunction);
                }
                return this.parseStatement();
              };
              Parser7.prototype.parseIfStatement = function() {
                var node = this.createNode();
                var consequent;
                var alternate = null;
                this.expectKeyword("if");
                this.expect("(");
                var test2 = 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(test2, consequent, alternate));
              };
              Parser7.prototype.parseDoWhileStatement = function() {
                var node = this.createNode();
                this.expectKeyword("do");
                var previousInIteration = this.context.inIteration;
                this.context.inIteration = true;
                var body2 = this.parseStatement();
                this.context.inIteration = previousInIteration;
                this.expectKeyword("while");
                this.expect("(");
                var test2 = 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(body2, test2));
              };
              Parser7.prototype.parseWhileStatement = function() {
                var node = this.createNode();
                var body2;
                this.expectKeyword("while");
                this.expect("(");
                var test2 = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body2 = this.finalize(this.createNode(), new Node5.EmptyStatement());
                } else {
                  this.expect(")");
                  var previousInIteration = this.context.inIteration;
                  this.context.inIteration = true;
                  body2 = this.parseStatement();
                  this.context.inIteration = previousInIteration;
                }
                return this.finalize(node, new Node5.WhileStatement(test2, body2));
              };
              Parser7.prototype.parseForStatement = function() {
                var init2 = null;
                var test2 = 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")) {
                    init2 = 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");
                      }
                      init2 = this.finalize(init2, new Node5.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left3 = init2;
                      right3 = this.parseExpression();
                      init2 = null;
                    } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                      init2 = this.finalize(init2, new Node5.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left3 = init2;
                      right3 = this.parseAssignmentExpression();
                      init2 = null;
                      forIn = false;
                    } else {
                      init2 = this.finalize(init2, new Node5.VariableDeclaration(declarations, "var"));
                      this.expect(";");
                    }
                  } else if (this.matchKeyword("const") || this.matchKeyword("let")) {
                    init2 = this.createNode();
                    var kind2 = this.nextToken().value;
                    if (!this.context.strict && this.lookahead.value === "in") {
                      init2 = this.finalize(init2, new Node5.Identifier(kind2));
                      this.nextToken();
                      left3 = init2;
                      right3 = this.parseExpression();
                      init2 = 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")) {
                        init2 = this.finalize(init2, new Node5.VariableDeclaration(declarations, kind2));
                        this.nextToken();
                        left3 = init2;
                        right3 = this.parseExpression();
                        init2 = null;
                      } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                        init2 = this.finalize(init2, new Node5.VariableDeclaration(declarations, kind2));
                        this.nextToken();
                        left3 = init2;
                        right3 = this.parseAssignmentExpression();
                        init2 = null;
                        forIn = false;
                      } else {
                        this.consumeSemicolon();
                        init2 = this.finalize(init2, new Node5.VariableDeclaration(declarations, kind2));
                      }
                    }
                  } else {
                    var initStartToken = this.lookahead;
                    var previousAllowIn = this.context.allowIn;
                    this.context.allowIn = false;
                    init2 = this.inheritCoverGrammar(this.parseAssignmentExpression);
                    this.context.allowIn = previousAllowIn;
                    if (this.matchKeyword("in")) {
                      if (!this.context.isAssignmentTarget || init2.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init2);
                      left3 = init2;
                      right3 = this.parseExpression();
                      init2 = null;
                    } else if (this.matchContextualKeyword("of")) {
                      if (!this.context.isAssignmentTarget || init2.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init2);
                      left3 = init2;
                      right3 = this.parseAssignmentExpression();
                      init2 = null;
                      forIn = false;
                    } else {
                      if (this.match(",")) {
                        var initSeq = [init2];
                        while (this.match(",")) {
                          this.nextToken();
                          initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
                        }
                        init2 = this.finalize(this.startNode(initStartToken), new Node5.SequenceExpression(initSeq));
                      }
                      this.expect(";");
                    }
                  }
                }
                if (typeof left3 === "undefined") {
                  if (!this.match(";")) {
                    test2 = this.parseExpression();
                  }
                  this.expect(";");
                  if (!this.match(")")) {
                    update2 = this.parseExpression();
                  }
                }
                var body2;
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body2 = this.finalize(this.createNode(), new Node5.EmptyStatement());
                } else {
                  this.expect(")");
                  var previousInIteration = this.context.inIteration;
                  this.context.inIteration = true;
                  body2 = this.isolateCoverGrammar(this.parseStatement);
                  this.context.inIteration = previousInIteration;
                }
                return typeof left3 === "undefined" ? this.finalize(node, new Node5.ForStatement(init2, test2, update2, body2)) : forIn ? this.finalize(node, new Node5.ForInStatement(left3, right3, body2)) : this.finalize(node, new Node5.ForOfStatement(left3, right3, body2));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.prototype.parseWithStatement = function() {
                if (this.context.strict) {
                  this.tolerateError(messages_1.Messages.StrictModeWith);
                }
                var node = this.createNode();
                var body2;
                this.expectKeyword("with");
                this.expect("(");
                var object3 = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body2 = this.finalize(this.createNode(), new Node5.EmptyStatement());
                } else {
                  this.expect(")");
                  body2 = this.parseStatement();
                }
                return this.finalize(node, new Node5.WithStatement(object3, body2));
              };
              Parser7.prototype.parseSwitchCase = function() {
                var node = this.createNode();
                var test2;
                if (this.matchKeyword("default")) {
                  this.nextToken();
                  test2 = null;
                } else {
                  this.expectKeyword("case");
                  test2 = 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(test2, consequent));
              };
              Parser7.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));
              };
              Parser7.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 body2 = void 0;
                  if (this.matchKeyword("class")) {
                    this.tolerateUnexpectedToken(this.lookahead);
                    body2 = 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);
                    }
                    body2 = declaration;
                  } else {
                    body2 = this.parseStatement();
                  }
                  delete this.context.labelSet[key];
                  statement = new Node5.LabeledStatement(id, body2);
                } else {
                  this.consumeSemicolon();
                  statement = new Node5.ExpressionStatement(expr);
                }
                return this.finalize(node, statement);
              };
              Parser7.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));
              };
              Parser7.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 i4 = 0; i4 < params.length; i4++) {
                  var key = "$" + params[i4].value;
                  if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
                    this.tolerateError(messages_1.Messages.DuplicateBinding, params[i4].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 body2 = this.parseBlock();
                return this.finalize(node, new Node5.CatchClause(param, body2));
              };
              Parser7.prototype.parseFinallyClause = function() {
                this.expectKeyword("finally");
                return this.parseBlock();
              };
              Parser7.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));
              };
              Parser7.prototype.parseDebuggerStatement = function() {
                var node = this.createNode();
                this.expectKeyword("debugger");
                this.consumeSemicolon();
                return this.finalize(node, new Node5.DebuggerStatement());
              };
              Parser7.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;
              };
              Parser7.prototype.parseFunctionSourceElements = function() {
                var node = this.createNode();
                this.expect("{");
                var body2 = 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;
                  }
                  body2.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(body2));
              };
              Parser7.prototype.validateParam = function(options2, param, name4) {
                var key = "$" + name4;
                if (this.context.strict) {
                  if (this.scanner.isRestrictedWord(name4)) {
                    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(name4)) {
                    options2.firstRestricted = param;
                    options2.message = messages_1.Messages.StrictParamName;
                  } else if (this.scanner.isStrictModeReservedWord(name4)) {
                    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;
                }
              };
              Parser7.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));
              };
              Parser7.prototype.parseFormalParameter = function(options2) {
                var params = [];
                var param = this.match("...") ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
                for (var i4 = 0; i4 < params.length; i4++) {
                  this.validateParam(options2, params[i4], params[i4].value);
                }
                options2.simple = options2.simple && param instanceof Node5.Identifier;
                options2.params.push(param);
              };
              Parser7.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
                };
              };
              Parser7.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;
              };
              Parser7.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 body2 = 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, body2)) : this.finalize(node, new Node5.FunctionDeclaration(id, params, body2, isGenerator));
              };
              Parser7.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 body2 = 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, body2)) : this.finalize(node, new Node5.FunctionExpression(id, params, body2, isGenerator));
              };
              Parser7.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));
              };
              Parser7.prototype.parseDirectivePrologues = function() {
                var firstRestricted = null;
                var body2 = [];
                while (true) {
                  var token2 = this.lookahead;
                  if (token2.type !== 8) {
                    break;
                  }
                  var statement = this.parseDirective();
                  body2.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 body2;
              };
              Parser7.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;
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.prototype.isStartOfExpression = function() {
                var start2 = true;
                var value = this.lookahead.value;
                switch (this.lookahead.type) {
                  case 7:
                    start2 = value === "[" || value === "(" || value === "{" || value === "+" || value === "-" || value === "!" || value === "~" || value === "++" || value === "--" || value === "/" || value === "/=";
                    break;
                  case 4:
                    start2 = value === "class" || value === "delete" || value === "function" || value === "let" || value === "new" || value === "super" || value === "this" || value === "typeof" || value === "void" || value === "yield";
                    break;
                  default:
                    break;
                }
                return start2;
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.prototype.parseClassElementList = function() {
                var body2 = [];
                var hasConstructor = { value: false };
                this.expect("{");
                while (!this.match("}")) {
                  if (this.match(";")) {
                    this.nextToken();
                  } else {
                    body2.push(this.parseClassElement(hasConstructor));
                  }
                }
                this.expect("}");
                return body2;
              };
              Parser7.prototype.parseClassBody = function() {
                var node = this.createNode();
                var elementList = this.parseClassElementList();
                return this.finalize(node, new Node5.ClassBody(elementList));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.prototype.parseModule = function() {
                this.context.strict = true;
                this.context.isModule = true;
                this.scanner.isModule = true;
                var node = this.createNode();
                var body2 = this.parseDirectivePrologues();
                while (this.lookahead.type !== 2) {
                  body2.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node5.Module(body2));
              };
              Parser7.prototype.parseScript = function() {
                var node = this.createNode();
                var body2 = this.parseDirectivePrologues();
                while (this.lookahead.type !== 2) {
                  body2.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node5.Script(body2));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.prototype.parseNamedImports = function() {
                this.expect("{");
                var specifiers = [];
                while (!this.match("}")) {
                  specifiers.push(this.parseImportSpecifier());
                  if (!this.match("}")) {
                    this.expect(",");
                  }
                }
                this.expect("}");
                return specifiers;
              };
              Parser7.prototype.parseImportDefaultSpecifier = function() {
                var node = this.createNode();
                var local = this.parseIdentifierName();
                return this.finalize(node, new Node5.ImportDefaultSpecifier(local));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.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));
              };
              Parser7.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 Parser7;
            }();
            exports3.Parser = Parser6;
          },
          /* 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(error40) {
                this.errors.push(error40);
              };
              ErrorHandler2.prototype.tolerate = function(error40) {
                if (this.tolerant) {
                  this.recordError(error40);
                } else {
                  throw error40;
                }
              };
              ErrorHandler2.prototype.constructError = function(msg, column) {
                var error40 = new Error(msg);
                try {
                  throw error40;
                } catch (base) {
                  if (Object.create && Object.defineProperty) {
                    error40 = Object.create(base);
                    Object.defineProperty(error40, "column", { value: column });
                  }
                }
                return error40;
              };
              ErrorHandler2.prototype.createError = function(index, line, col, description) {
                var msg = "Line " + line + ": " + description;
                var error40 = this.constructError(msg, col);
                error40.index = index;
                error40.lineNumber = line;
                error40.description = description;
                return error40;
              };
              ErrorHandler2.prototype.throwError = function(index, line, col, description) {
                throw this.createError(index, line, col, description);
              };
              ErrorHandler2.prototype.tolerateError = function(index, line, col, description) {
                var error40 = this.createError(index, line, col, description);
                if (this.tolerant) {
                  this.recordError(error40);
                } else {
                  throw error40;
                }
              };
              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 start2, loc;
                if (this.trackComment) {
                  comments = [];
                  start2 = 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: [start2 + offset, this.index - 1],
                        range: [start2, 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: [start2 + offset, this.index],
                    range: [start2, this.index],
                    loc
                  };
                  comments.push(entry);
                }
                return comments;
              };
              Scanner2.prototype.skipMultiLineComment = function() {
                var comments = [];
                var start2, loc;
                if (this.trackComment) {
                  comments = [];
                  start2 = 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: [start2 + 2, this.index - 2],
                          range: [start2, 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: [start2 + 2, this.index],
                    range: [start2, this.index],
                    loc
                  };
                  comments.push(entry);
                }
                this.tolerateUnexpectedToken();
                return comments;
              };
              Scanner2.prototype.scanComments = function() {
                var comments;
                if (this.trackComment) {
                  comments = [];
                }
                var start2 = 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;
                    start2 = 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);
                      }
                      start2 = true;
                    } else if (ch === 42) {
                      this.index += 2;
                      var comment = this.skipMultiLineComment();
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else if (start2 && 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(i4) {
                var cp3 = this.source.charCodeAt(i4);
                if (cp3 >= 55296 && cp3 <= 56319) {
                  var second = this.source.charCodeAt(i4 + 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 i4 = 0; i4 < len; ++i4) {
                  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 start2 = this.index++;
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (ch === 92) {
                    this.index = start2;
                    return this.getComplexIdentifier();
                  } else if (ch >= 55296 && ch < 57343) {
                    this.index = start2;
                    return this.getComplexIdentifier();
                  }
                  if (character_1.Character.isIdentifierPart(ch)) {
                    ++this.index;
                  } else {
                    break;
                  }
                }
                return this.source.slice(start2, 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 start2 = this.index;
                var id = this.source.charCodeAt(start2) === 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 && start2 + id.length !== this.index) {
                  var restore = this.index;
                  this.index = start2;
                  this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
                  this.index = restore;
                }
                return {
                  type,
                  value: id,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start: start2,
                  end: this.index
                };
              };
              Scanner2.prototype.scanPunctuator = function() {
                var start2 = 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 === start2) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 7,
                  value: str2,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start: start2,
                  end: this.index
                };
              };
              Scanner2.prototype.scanHexLiteral = function(start2) {
                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: start2,
                  end: this.index
                };
              };
              Scanner2.prototype.scanBinaryLiteral = function(start2) {
                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: start2,
                  end: this.index
                };
              };
              Scanner2.prototype.scanOctalLiteral = function(prefix, start2) {
                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: start2,
                  end: this.index
                };
              };
              Scanner2.prototype.isImplicitOctalLiteral = function() {
                for (var i4 = this.index + 1; i4 < this.length; ++i4) {
                  var ch = this.source[i4];
                  if (ch === "8" || ch === "9") {
                    return false;
                  }
                  if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                    return true;
                  }
                }
                return true;
              };
              Scanner2.prototype.scanNumericLiteral = function() {
                var start2 = this.index;
                var ch = this.source[start2];
                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(start2);
                    }
                    if (ch === "b" || ch === "B") {
                      ++this.index;
                      return this.scanBinaryLiteral(start2);
                    }
                    if (ch === "o" || ch === "O") {
                      return this.scanOctalLiteral(ch, start2);
                    }
                    if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                      if (this.isImplicitOctalLiteral()) {
                        return this.scanOctalLiteral(ch, start2);
                      }
                    }
                  }
                  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: start2,
                  end: this.index
                };
              };
              Scanner2.prototype.scanStringLiteral = function() {
                var start2 = this.index;
                var quote3 = this.source[start2];
                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 = start2;
                  this.throwUnexpectedToken();
                }
                return {
                  type: 8,
                  value: str2,
                  octal,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start: start2,
                  end: this.index
                };
              };
              Scanner2.prototype.scanTemplate = function() {
                var cooked = "";
                var terminated = false;
                var start2 = this.index;
                var head = this.source[start2] === "`";
                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(start2 + 1, this.index - rawOffset),
                  cooked,
                  head,
                  tail,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start: start2,
                  end: this.index
                };
              };
              Scanner2.prototype.testRegExp = function(pattern, flags2) {
                var astralSubstitute = "\uFFFF";
                var tmp = pattern;
                var self2 = this;
                if (flags2.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, flags2);
                } 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 flags2 = "";
                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) {
                        flags2 += char;
                        for (str2 += "\\u"; restore < this.index; ++restore) {
                          str2 += this.source[restore];
                        }
                      } else {
                        this.index = restore;
                        flags2 += "u";
                        str2 += "\\u";
                      }
                      this.tolerateUnexpectedToken();
                    } else {
                      str2 += "\\";
                      this.tolerateUnexpectedToken();
                    }
                  } else {
                    flags2 += ch;
                    str2 += ch;
                  }
                }
                return flags2;
              };
              Scanner2.prototype.scanRegExp = function() {
                var start2 = this.index;
                var pattern = this.scanRegExpBody();
                var flags2 = this.scanRegExpFlags();
                var value = this.testRegExp(pattern, flags2);
                return {
                  type: 9,
                  value: "",
                  pattern,
                  flags: flags2,
                  regex: value,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start: start2,
                  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 i4 = 0; i4 < comments.length; ++i4) {
                      var e4 = comments[i4];
                      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 flags2 = token2.flags;
                      entry.regex = { pattern, flags: flags2 };
                    }
                    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 isArray3(arg) {
      if (Array.isArray) {
        return Array.isArray(arg);
      }
      return objectToString2(arg) === "[object Array]";
    }
    __name(isArray3, "isArray");
    exports2.isArray = isArray3;
    function isBoolean3(arg) {
      return typeof arg === "boolean";
    }
    __name(isBoolean3, "isBoolean");
    exports2.isBoolean = isBoolean3;
    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 isNumber4(arg) {
      return typeof arg === "number";
    }
    __name(isNumber4, "isNumber");
    exports2.isNumber = isNumber4;
    function isString3(arg) {
      return typeof arg === "string";
    }
    __name(isString3, "isString");
    exports2.isString = isString3;
    function isSymbol(arg) {
      return typeof arg === "symbol";
    }
    __name(isSymbol, "isSymbol");
    exports2.isSymbol = isSymbol;
    function isUndefined3(arg) {
      return arg === void 0;
    }
    __name(isUndefined3, "isUndefined");
    exports2.isUndefined = isUndefined3;
    function isRegExp2(re3) {
      return objectToString2(re3) === "[object RegExp]";
    }
    __name(isRegExp2, "isRegExp");
    exports2.isRegExp = isRegExp2;
    function isObject5(arg) {
      return typeof arg === "object" && arg !== null;
    }
    __name(isObject5, "isObject");
    exports2.isObject = isObject5;
    function isDate2(d2) {
      return objectToString2(d2) === "[object Date]";
    }
    __name(isDate2, "isDate");
    exports2.isDate = isDate2;
    function isError(e4) {
      return objectToString2(e4) === "[object Error]" || e4 instanceof Error;
    }
    __name(isError, "isError");
    exports2.isError = isError;
    function isFunction7(arg) {
      return typeof arg === "function";
    }
    __name(isFunction7, "isFunction");
    exports2.isFunction = isFunction7;
    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, start2, compare) {
      if (start2 === lo) {
        start2++;
      }
      for (; start2 < hi; start2++) {
        const pivot = array2[start2];
        const pivotIndex = results[start2];
        let left3 = lo;
        let right3 = start2;
        while (left3 < right3) {
          const mid = left3 + right3 >>> 1;
          if (compare(pivot, array2[mid]) < 0) {
            right3 = mid;
          } else {
            left3 = mid + 1;
          }
        }
        let n3 = start2 - 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, start2, length, hint, compare) {
      let lastOffset = 0;
      let maxOffset = 0;
      let offset = 1;
      if (compare(value, array2[start2 + hint]) > 0) {
        maxOffset = length - hint;
        while (offset < maxOffset && compare(value, array2[start2 + 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[start2 + 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[start2 + m3]) > 0) {
          lastOffset = m3 + 1;
        } else {
          offset = m3;
        }
      }
      return offset;
    }
    __name(gallopLeft, "gallopLeft");
    function gallopRight(value, array2, start2, length, hint, compare) {
      let lastOffset = 0;
      let maxOffset = 0;
      let offset = 1;
      if (compare(value, array2[start2 + hint]) < 0) {
        maxOffset = hint + 1;
        while (offset < maxOffset && compare(value, array2[start2 + 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[start2 + 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[start2 + 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(i4) {
        const { compare } = this;
        const { array: array2 } = this;
        let start1 = this.runStart[i4];
        let length1 = this.runLength[i4];
        const start2 = this.runStart[i4 + 1];
        let length2 = this.runLength[i4 + 1];
        this.runLength[i4] = length1 + length2;
        if (i4 === this.stackSize - 3) {
          this.runStart[i4 + 1] = this.runStart[i4 + 2];
          this.runLength[i4 + 1] = this.runLength[i4 + 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 i4 = 0;
        for (i4 = 0; i4 < length1; i4++) {
          tmp[i4] = array2[start1 + i4];
          tmpIndex[i4] = results[start1 + i4];
        }
        let cursor1 = 0;
        let cursor2 = start2;
        let dest = start1;
        array2[dest] = array2[cursor2];
        results[dest] = results[cursor2];
        dest++;
        cursor2++;
        if (--length2 === 0) {
          for (i4 = 0; i4 < length1; i4++) {
            array2[dest + i4] = tmp[cursor1 + i4];
            results[dest + i4] = tmpIndex[cursor1 + i4];
          }
          return;
        }
        if (length1 === 1) {
          for (i4 = 0; i4 < length2; i4++) {
            array2[dest + i4] = array2[cursor2 + i4];
            results[dest + i4] = results[cursor2 + i4];
          }
          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 (i4 = 0; i4 < count1; i4++) {
                array2[dest + i4] = tmp[cursor1 + i4];
                results[dest + i4] = tmpIndex[cursor1 + i4];
              }
              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 (i4 = 0; i4 < count2; i4++) {
                array2[dest + i4] = array2[cursor2 + i4];
                results[dest + i4] = results[cursor2 + i4];
              }
              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 (i4 = 0; i4 < length2; i4++) {
            array2[dest + i4] = array2[cursor2 + i4];
            results[dest + i4] = results[cursor2 + i4];
          }
          array2[dest + length2] = tmp[cursor1];
          results[dest + length2] = tmpIndex[cursor1];
        } else if (length1 === 0) {
          throw new Error("mergeLow preconditions were not respected");
        } else {
          for (i4 = 0; i4 < length1; i4++) {
            array2[dest + i4] = tmp[cursor1 + i4];
            results[dest + i4] = tmpIndex[cursor1 + i4];
          }
        }
      }
      /**
       * 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 i4 = 0;
        for (i4 = 0; i4 < length2; i4++) {
          tmp[i4] = array2[start2 + i4];
          tmpIndex[i4] = results[start2 + i4];
        }
        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 (i4 = 0; i4 < length2; i4++) {
            array2[customCursor + i4] = tmp[i4];
            results[customCursor + i4] = tmpIndex[i4];
          }
          return;
        }
        if (length2 === 1) {
          dest -= length1;
          cursor1 -= length1;
          customDest = dest + 1;
          customCursor = cursor1 + 1;
          for (i4 = length1 - 1; i4 >= 0; i4--) {
            array2[customDest + i4] = array2[customCursor + i4];
            results[customDest + i4] = results[customCursor + i4];
          }
          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 (i4 = count1 - 1; i4 >= 0; i4--) {
                array2[customDest + i4] = array2[customCursor + i4];
                results[customDest + i4] = results[customCursor + i4];
              }
              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 (i4 = 0; i4 < count2; i4++) {
                array2[customDest + i4] = tmp[customCursor + i4];
                results[customDest + i4] = tmpIndex[customCursor + i4];
              }
              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 (i4 = length1 - 1; i4 >= 0; i4--) {
            array2[customDest + i4] = array2[customCursor + i4];
            results[customDest + i4] = results[customCursor + i4];
          }
          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 (i4 = 0; i4 < length2; i4++) {
            array2[customCursor + i4] = tmp[i4];
            results[customCursor + i4] = tmpIndex[i4];
          }
        }
      }
    };
    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 i4 = 0;
      while (i4 < length) {
        results[i4] = i4++;
      }
      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 hasOwnProperty3 = require_has_own_prop();
    var {
      isObject: isObject5,
      isArray: isArray3,
      isString: isString3,
      isNumber: isNumber4
    } = 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 EMPTY3 = "";
    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 symbol2 = /* @__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 = symbol2(prefix, source_key);
      if (!hasOwnProperty3(source2, source_prop)) {
        return;
      }
      const target_prop = target_key === source_key ? source_prop : symbol2(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 = symbol2(prefix, to);
        if (!hasOwnProperty3(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, symbol2(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 (!isString3(key) && !isNumber4(key)) {
          return;
        }
        if (!hasOwnProperty3(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: EMPTY3,
      UNDEFINED,
      symbol: symbol2,
      define: define2,
      copy_comments,
      swap_comments,
      assign_non_prop_comments,
      assign(target, source2, keys) {
        if (!isObject5(target)) {
          throw new TypeError("Cannot convert undefined or null to object");
        }
        if (!isObject5(source2)) {
          return target;
        }
        if (keys === UNDEFINED) {
          keys = Object.keys(source2);
          assign_non_prop_comments(target, source2);
        } else if (!isArray3(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: isArray3 } = require_util19();
    var { sort } = require_src38();
    var {
      SYMBOL_PREFIXES,
      UNDEFINED,
      symbol: symbol2,
      copy_comments,
      swap_comments
    } = require_common5();
    var reverse_comments = /* @__PURE__ */ __name((array2) => {
      const { length } = array2;
      let i4 = 0;
      const max = length / 2;
      for (; i4 < max; i4++) {
        swap_comments(array2, i4, length - i4 - 1);
      }
    }, "reverse_comments");
    var move_comment = /* @__PURE__ */ __name((target, source2, i4, offset, remove2) => {
      copy_comments(target, source2, i4 + offset, i4, remove2);
    }, "move_comment");
    var move_comments = /* @__PURE__ */ __name((target, source2, start2, count, offset, remove2) => {
      if (offset > 0) {
        let i5 = count;
        while (i5-- > 0) {
          move_comment(target, source2, start2 + i5, offset, remove2);
        }
        return;
      }
      let i4 = 0;
      while (i4 < count) {
        const ii = i4++;
        move_comment(target, source2, start2 + ii, offset, remove2);
      }
    }, "move_comments");
    var remove_comments = /* @__PURE__ */ __name((array2, key) => {
      SYMBOL_PREFIXES.forEach((prefix) => {
        const prop = symbol2(prefix, key);
        delete array2[prop];
      });
    }, "remove_comments");
    var get_mapped = /* @__PURE__ */ __name((map3, key) => {
      let mapped = key;
      while (mapped in map3) {
        mapped = map3[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(...args2) {
        const { length } = this;
        const ret = super.splice(...args2);
        let [begin, deleteCount, ...items] = args2;
        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 start2 = begin + deleteCount;
        const count = length - start2;
        move_comments(this, this, start2, count, offset, true);
        return ret;
      }
      slice(...args2) {
        const { length } = this;
        const array2 = super.slice(...args2);
        if (!array2.length) {
          return new _CommentArray();
        }
        let [begin, before] = args2;
        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 += isArray3(item) ? item.length : 1;
          if (!(item instanceof _CommentArray)) {
            return;
          }
          move_comments(ret, item, 0, item.length, prev);
        });
        return ret;
      }
      sort(...args2) {
        const result = sort(
          this,
          ...args2.slice(0, 1)
        );
        const map3 = /* @__PURE__ */ Object.create(null);
        result.forEach((source_index, index) => {
          if (source_index === index) {
            return;
          }
          const real_source_index = get_mapped(map3, source_index);
          if (real_source_index === index) {
            return;
          }
          map3[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: EMPTY3,
      UNDEFINED,
      define: define2,
      assign_non_prop_comments
    } = require_common5();
    var tokenize7 = /* @__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 error40 = new SyntaxError(`Unexpected token ${current.value.slice(0, 1)}`);
      Object.assign(error40, current.loc.start);
      throw error40;
    }, "unexpected");
    var unexpected_end = /* @__PURE__ */ __name(() => {
      const error40 = new SyntaxError("Unexpected end of JSON input");
      Object.assign(error40, last2 ? last2.loc.end : {
        line: 1,
        column: 0
      });
      throw error40;
    }, "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 name4;
      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");
        name4 = JSON.parse(current.value);
        set_prop(name4);
        assign_comments(PREFIX_BEFORE);
        next();
        parse_comments(PREFIX_AFTER_PROP);
        expect(COLON3);
        next();
        parse_comments(PREFIX_AFTER_COLON);
        obj[name4] = transform2(name4, 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 i4 = 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(i4);
        assign_comments(PREFIX_BEFORE);
        array2[i4] = transform2(i4, walk());
        i4++;
        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 = EMPTY3;
      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 isObject5 = /* @__PURE__ */ __name((subject) => Object(subject) === subject, "isObject");
    var parse17 = /* @__PURE__ */ __name((code2, rev, no_comments) => {
      clean();
      tokens = tokenize7(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 (!isObject5(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: parse17,
      tokenize: tokenize7
    };
  }
});

// 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_stringify4 = __commonJS({
  "node_modules/comment-json/src/stringify.js"(exports2, module2) {
    init_esbuild_shims();
    var {
      isArray: isArray3,
      isObject: isObject5,
      isFunction: isFunction7,
      isNumber: isNumber4,
      isString: isString3
    } = 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: EMPTY3,
      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 EMPTY3;
      }
      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);
      }, EMPTY3);
      return display_block || is_line_comment ? str2 + LF3 + deeper_gap : str2;
    }, "process_comments");
    var replacer = null;
    var indent = EMPTY3;
    var clean = /* @__PURE__ */ __name(() => {
      replacer = null;
      indent = EMPTY3;
    }, "clean");
    var join71 = /* @__PURE__ */ __name((one, two, gap) => one ? two ? one + two.trim() + LF3 + gap : one.trimRight() + LF3 + gap : two ? two.trimRight() + LF3 + gap : EMPTY3, "join");
    var join_content = /* @__PURE__ */ __name((inside, value, gap) => {
      const comment = process_comments(value, PREFIX_BEFORE, gap + indent, true);
      return join71(comment, inside, gap);
    }, "join_content");
    var array_stringify = /* @__PURE__ */ __name((value, gap) => {
      const deeper_gap = gap + indent;
      const { length } = value;
      let inside = EMPTY3;
      let after_comma = EMPTY3;
      for (let i4 = 0; i4 < length; i4++) {
        if (i4 !== 0) {
          inside += COMMA;
        }
        const before = join71(
          after_comma,
          process_comments(value, BEFORE(i4), deeper_gap),
          deeper_gap
        );
        inside += before || LF3 + deeper_gap;
        inside += stringify4(i4, value, deeper_gap) || STR_NULL;
        inside += process_comments(value, AFTER_VALUE(i4), deeper_gap);
        after_comma = process_comments(value, AFTER(i4), deeper_gap);
      }
      inside += join71(
        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 = EMPTY3;
      let after_comma = EMPTY3;
      let first2 = true;
      const keys = isArray3(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 = join71(
          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 += join71(
        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 (isObject5(value) && isFunction7(value.toJSON)) {
        value = value.toJSON(key);
      }
      if (isFunction7(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 isArray3(value) ? array_stringify(value, gap) : object_stringify(value, gap);
        // undefined
        default:
      }
    }
    __name(stringify4, "stringify");
    var get_indent = /* @__PURE__ */ __name((space) => isString3(space) ? space : isNumber4(space) ? repeat(SPACE3, space) : EMPTY3, "get_indent");
    var { toString: toString3 } = 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 = toString3.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 (!isFunction7(replacer_) && !isArray3(replacer_)) {
        replacer_ = null;
      }
      replacer = replacer_;
      indent = indent_;
      const str2 = is_primitive_object(value) ? JSON.stringify(value) : stringify4("", { "": value }, EMPTY3);
      clean();
      return isObject5(value) ? process_comments(value, PREFIX_BEFORE_ALL, EMPTY3).trimLeft() + str2 + process_comments(value, PREFIX_AFTER_ALL, EMPTY3).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: parse17, tokenize: tokenize7 } = require_parse8();
    var stringify4 = require_stringify4();
    var { CommentArray } = require_array();
    var { assign } = require_common5();
    module2.exports = {
      parse: parse17,
      stringify: stringify4,
      tokenize: tokenize7,
      CommentArray,
      assign
    };
  }
});

// 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 i4 = 0; i4 < 3; i4++) {
        t32 = h3 + 1 / 3 * -(i4 - 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[i4] = 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 i4 = Math.floor(6 * h3);
      const v2 = 1 - bl;
      f5 = 6 * h3 - i4;
      if ((i4 & 1) !== 0) {
        f5 = 1 - f5;
      }
      const n3 = wh + f5 * (v2 - wh);
      let r5;
      let g2;
      let b2;
      switch (i4) {
        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(args2, saturation = null) {
      const [r5, g2, b2] = args2;
      let value = saturation === null ? convert2.rgb.hsv(args2)[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(args2) {
      return convert2.rgb.ansi16(convert2.hsv.rgb(args2), args2[2]);
    };
    convert2.rgb.ansi256 = function(args2) {
      const r5 = args2[0];
      const g2 = args2[1];
      const b2 = args2[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(args2) {
      let color = args2 % 10;
      if (color === 0 || color === 7) {
        if (args2 > 50) {
          color += 3.5;
        }
        color = color / 10.5 * 255;
        return [color, color, color];
      }
      const mult = (~~(args2 > 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(args2) {
      if (args2 >= 232) {
        const c4 = (args2 - 232) * 10 + 8;
        return [c4, c4, c4];
      }
      args2 -= 16;
      let rem;
      const r5 = Math.floor(args2 / 36) / 5 * 255;
      const g2 = Math.floor((rem = args2 % 36) / 6) / 5 * 255;
      const b2 = rem % 6 / 5 * 255;
      return [r5, g2, b2];
    };
    convert2.rgb.hex = function(args2) {
      const integer2 = ((Math.round(args2[0]) & 255) << 16) + ((Math.round(args2[1]) & 255) << 8) + (Math.round(args2[2]) & 255);
      const string4 = integer2.toString(16).toUpperCase();
      return "000000".substring(string4.length) + string4;
    };
    convert2.hex.rgb = function(args2) {
      const match2 = args2.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(args2) {
      return [args2[0] / 100 * 255, args2[0] / 100 * 255, args2[0] / 100 * 255];
    };
    convert2.gray.hsl = function(args2) {
      return [0, 0, args2[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, i4 = 0; i4 < len; i4++) {
        graph[models[i4]] = {
          // 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, i4 = 0; i4 < len; i4++) {
          const adjacent = adjacents[i4];
          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(args2) {
        return to(from(args2));
      };
    }
    __name(link3, "link");
    function wrapConversion(toModel, graph) {
      const path150 = [graph[toModel].parent, toModel];
      let fn = conversions[graph[toModel].parent][toModel];
      let cur = graph[toModel].parent;
      while (graph[cur].parent) {
        path150.unshift(graph[cur].parent);
        fn = link3(conversions[graph[cur].parent][cur], fn);
        cur = graph[cur].parent;
      }
      fn.conversion = path150;
      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, i4 = 0; i4 < len; i4++) {
        const toModel = models[i4];
        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(...args2) {
        const arg0 = args2[0];
        if (arg0 === void 0 || arg0 === null) {
          return arg0;
        }
        if (arg0.length > 1) {
          args2 = arg0;
        }
        return fn(args2);
      }, "wrappedFn");
      if ("conversion" in fn) {
        wrappedFn.conversion = fn.conversion;
      }
      return wrappedFn;
    }
    __name(wrapRaw, "wrapRaw");
    function wrapRounded(fn) {
      const wrappedFn = /* @__PURE__ */ __name(function(...args2) {
        const arg0 = args2[0];
        if (arg0 === void 0 || arg0 === null) {
          return arg0;
        }
        if (arg0.length > 1) {
          args2 = arg0;
        }
        const result = fn(args2);
        if (typeof result === "object") {
          for (let len = result.length, i4 = 0; i4 < len; i4++) {
            result[i4] = Math.round(result[i4]);
          }
        }
        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) => (...args2) => {
      const code2 = fn(...args2);
      return `\x1B[${code2 + offset}m`;
    }, "wrapAnsi16");
    var wrapAnsi2567 = /* @__PURE__ */ __name((fn, offset) => (...args2) => {
      const code2 = fn(...args2);
      return `\x1B[${38 + offset};5;${code2}m`;
    }, "wrapAnsi256");
    var wrapAnsi16m7 = /* @__PURE__ */ __name((fn, offset) => (...args2) => {
      const rgb = fn(...args2);
      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 name4 = sourceSpace === "ansi16" ? "ansi" : sourceSpace;
        if (sourceSpace === targetSpace) {
          styles10[name4] = wrap2(identity, offset);
        } else if (typeof suite === "object") {
          styles10[name4] = 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 os59 = __require("os");
    var tty3 = __require("tty");
    var hasFlag3 = require_has_flag2();
    var { env: env6 } = 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 env6) {
      if (env6.FORCE_COLOR === "true") {
        forceColor = 1;
      } else if (env6.FORCE_COLOR === "false") {
        forceColor = 0;
      } else {
        forceColor = env6.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env6.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 (env6.TERM === "dumb") {
        return min;
      }
      if (process.platform === "win32") {
        const osRelease = os59.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 (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].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 ("TERM_PROGRAM" in env6) {
        const version2 = 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(supportsColor3, "supportsColor");
    function getSupportLevel(stream5) {
      const level = supportsColor3(stream5, stream5 && stream5.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(name4, arguments_2) {
      const results = [];
      const chunks = arguments_2.trim().split(/\s*,\s*/g);
      let matches2;
      for (const chunk of chunks) {
        const number4 = Number(chunk);
        if (!Number.isNaN(number4)) {
          results.push(number4);
        } else if (matches2 = chunk.match(STRING_REGEX)) {
          results.push(matches2[2].replace(ESCAPE_REGEX, (m3, escape7, character) => escape7 ? unescape4(escape7) : character));
        } else {
          throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name4}')`);
        }
      }
      return results;
    }
    __name(parseArguments2, "parseArguments");
    function parseStyle(style) {
      STYLE_REGEX.lastIndex = 0;
      const results = [];
      let matches2;
      while ((matches2 = STYLE_REGEX.exec(style)) !== null) {
        const name4 = matches2[1];
        if (matches2[2]) {
          const args2 = parseArguments2(name4, matches2[2]);
          results.push([name4].concat(args2));
        } else {
          results.push([name4]);
        }
      }
      return results;
    }
    __name(parseStyle, "parseStyle");
    function buildStyle(chalk10, styles10) {
      const enabled2 = {};
      for (const layer2 of styles10) {
        for (const style of layer2.styles) {
          enabled2[style[0]] = layer2.inverse ? null : style.slice(1);
        }
      }
      let current = chalk10;
      for (const [styleName, styles11] of Object.entries(enabled2)) {
        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 = (chalk10, 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(chalk10, 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(chalk10, 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: isArray3 } = 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 chalk11 = {};
      applyOptions3(chalk11, options2);
      chalk11.template = (...arguments_2) => chalkTag(chalk11.template, ...arguments_2);
      Object.setPrototypeOf(chalk11, Chalk.prototype);
      Object.setPrototypeOf(chalk11.template, chalk11);
      chalk11.template.constructor = () => {
        throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.");
      };
      chalk11.template.Instance = ChalkClass;
      return chalk11.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_2) {
            const styler = createStyler3(ansiStyles7.color[levelMapping3[level]][model](...arguments_2), 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_2) {
            const styler = createStyler3(ansiStyles7.bgColor[levelMapping3[level]][model](...arguments_2), 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_2) => {
        if (isArray3(arguments_2[0]) && isArray3(arguments_2[0].raw)) {
          return applyStyle3(builder, chalkTag(builder, ...arguments_2));
        }
        return applyStyle3(builder, arguments_2.length === 1 ? "" + arguments_2[0] : arguments_2.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((chalk11, ...strings) => {
      const [firstString] = strings;
      if (!isArray3(firstString) || !isArray3(firstString.raw)) {
        return strings.join(" ");
      }
      const arguments_2 = strings.slice(1);
      const parts2 = [firstString.raw[0]];
      for (let i4 = 1; i4 < firstString.length; i4++) {
        parts2.push(
          String(arguments_2[i4 - 1]).replace(/[{}\\]/g, "\\$&"),
          String(firstString.raw[i4])
        );
      }
      if (template === void 0) {
        template = require_templates();
      }
      return template(chalk11, parts2.join(""));
    }, "chalkTag");
    Object.defineProperties(Chalk.prototype, styles10);
    var chalk10 = Chalk();
    chalk10.supportsColor = stdoutColor3;
    chalk10.stderr = Chalk({ level: stderrColor3 ? stderrColor3.level : 0 });
    chalk10.stderr.supportsColor = stderrColor3;
    module2.exports = chalk10;
  }
});

// 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 env6 = p2.env || {};
    var isColorSupported = !(!!env6.NO_COLOR || argv.includes("--no-color")) && (!!env6.FORCE_COLOR || argv.includes("--color") || p2.platform === "win32" || (p2.stdout || {}).isTTY && env6.TERM !== "dumb" || !!env6.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((enabled2 = isColorSupported) => {
      let f5 = enabled2 ? formatter : () => String;
      return {
        isColorSupported: enabled2,
        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, set2) {
      let pos2 = 65536;
      for (let i4 = 0, length = set2.length; i4 < length; i4 += 2) {
        pos2 += set2[i4];
        if (pos2 > code2) return false;
        pos2 += set2[i4 + 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(name4) {
      let isFirst = true;
      for (let i4 = 0; i4 < name4.length; i4++) {
        let cp3 = name4.charCodeAt(i4);
        if ((cp3 & 64512) === 55296 && i4 + 1 < name4.length) {
          const trail = name4.charCodeAt(++i4);
          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_lib6 = __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_lib7 = __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_lib6();
    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(enabled2) {
      return enabled2 ? 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 tokenize7;
    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");
    tokenize7 = /* @__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 tokenize7(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 start2 = Math.max(startLine - (linesAbove + 1), 0);
      let end = Math.min(source2.length, endLine + linesBelow);
      if (startLine === -1) {
        start2 = 0;
      }
      if (endLine === -1) {
        end = source2.length;
      }
      const lineDiff2 = endLine - startLine;
      const markerLines = {};
      if (lineDiff2) {
        for (let i4 = 0; i4 <= lineDiff2; i4++) {
          const lineNumber = i4 + startLine;
          if (!startColumn) {
            markerLines[lineNumber] = true;
          } else if (i4 === 0) {
            const sourceLength = source2[lineNumber - 1].length;
            markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
          } else if (i4 === lineDiff2) {
            markerLines[lineNumber] = [0, endColumn];
          } else {
            const sourceLength = source2[lineNumber - i4].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: start2,
        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: start2,
        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(start2, end).map((line, index2) => {
        const number4 = start2 + 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) ? (...args2) => console.error("SEMVER", ...args2) : () => {
    };
    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_LENGTH2 = 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_LENGTH2 - 6;
    var RELEASE_TYPES = [
      "major",
      "premajor",
      "minor",
      "preminor",
      "patch",
      "prepatch",
      "prerelease"
    ];
    module2.exports = {
      MAX_LENGTH: MAX_LENGTH2,
      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: MAX_LENGTH2
    } = 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_LENGTH2],
      [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((name4, value, isGlobal) => {
      const safe = makeSafeRegex(value);
      const index = R2++;
      debug3(name4, index, value);
      t5[name4] = 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_LENGTH2, 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_LENGTH2) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH2} 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 i4 = 0;
        do {
          const a2 = this.prerelease[i4];
          const b2 = other2.prerelease[i4];
          debug3("prerelease compare", i4, 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 (++i4);
      }
      compareBuild(other2) {
        if (!(other2 instanceof _SemVer)) {
          other2 = new _SemVer(other2, this.options);
        }
        let i4 = 0;
        do {
          const a2 = this.build[i4];
          const b2 = other2.build[i4];
          debug3("build compare", i4, 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 (++i4);
      }
      // 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 i4 = this.prerelease.length;
              while (--i4 >= 0) {
                if (typeof this.prerelease[i4] === "number") {
                  this.prerelease[i4]++;
                  i4 = -2;
                }
              }
              if (i4 === -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 parse17 = /* @__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 = parse17;
  }
});

// node_modules/semver/functions/valid.js
var require_valid = __commonJS({
  "node_modules/semver/functions/valid.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var parse17 = require_parse9();
    var valid = /* @__PURE__ */ __name((version2, options2) => {
      const v2 = parse17(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 parse17 = require_parse9();
    var clean = /* @__PURE__ */ __name((version2, options2) => {
      const s5 = parse17(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 i4 = 0; i4 < possibilities.length; i4++) {
          string4 = read3(possibilities[i4]);
          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 parse17 = require_parse10();
    module2.exports = function(source2) {
      return parse17(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 parse17 = require_spdx_expression_parse();
    var spdxLicenseIds = require_spdx_license_ids();
    function valid(string4) {
      try {
        parse17(string4);
        return true;
      } catch (error40) {
        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 i4 = 0; i4 < transforms.length; i4++) {
        var transformed = transforms[i4](identifier2).trim();
        if (transformed !== identifier2 && valid(transformed)) {
          return transformed;
        }
      }
      return null;
    }, "validTransformation");
    var validLastResort = /* @__PURE__ */ __name(function(identifier2) {
      var upperCased = identifier2.toUpperCase();
      for (var i4 = 0; i4 < lastResorts.length; i4++) {
        var lastResort = lastResorts[i4];
        if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) {
          return lastResort[IDENTIFIER2];
        }
      }
      return null;
    }, "validLastResort");
    var anyCorrection = /* @__PURE__ */ __name(function(identifier2, check2) {
      for (var i4 = 0; i4 < transpositions.length; i4++) {
        var transposition = transpositions[i4];
        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 parse17 = 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 = parse17(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, start2 = perf2.now()) => {
          starts[index] = ttl !== 0 ? start2 : 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 start2 = starts[index];
            if (!ttl || !start2)
              return;
            status.ttl = ttl;
            status.start = start2;
            status.now = cachedNow || getNow();
            const age = status.now - start2;
            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 start2 = starts[index];
          if (!ttl || !start2) {
            return Infinity;
          }
          const age = (cachedNow || getNow()) - start2;
          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 i4 = this.#tail; true; ) {
            if (!this.#isValidIndex(i4)) {
              break;
            }
            if (allowStale || !this.#isStale(i4)) {
              yield i4;
            }
            if (i4 === this.#head) {
              break;
            } else {
              i4 = this.#prev[i4];
            }
          }
        }
      }
      *#rindexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
          for (let i4 = this.#head; true; ) {
            if (!this.#isValidIndex(i4)) {
              break;
            }
            if (allowStale || !this.#isStale(i4)) {
              yield i4;
            }
            if (i4 === this.#tail) {
              break;
            } else {
              i4 = this.#next[i4];
            }
          }
        }
      }
      #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 i4 of this.#indexes()) {
          if (this.#valList[i4] !== void 0 && this.#keyList[i4] !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            yield [this.#keyList[i4], this.#valList[i4]];
          }
        }
      }
      /**
       * 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 i4 of this.#rindexes()) {
          if (this.#valList[i4] !== void 0 && this.#keyList[i4] !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            yield [this.#keyList[i4], this.#valList[i4]];
          }
        }
      }
      /**
       * Return a generator yielding the keys in the cache,
       * in order from most recently used to least recently used.
       */
      *keys() {
        for (const i4 of this.#indexes()) {
          const k2 = this.#keyList[i4];
          if (k2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            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 i4 of this.#rindexes()) {
          const k2 = this.#keyList[i4];
          if (k2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            yield k2;
          }
        }
      }
      /**
       * Return a generator yielding the values in the cache,
       * in order from most recently used to least recently used.
       */
      *values() {
        for (const i4 of this.#indexes()) {
          const v2 = this.#valList[i4];
          if (v2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            yield this.#valList[i4];
          }
        }
      }
      /**
       * 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 i4 of this.#rindexes()) {
          const v2 = this.#valList[i4];
          if (v2 !== void 0 && !this.#isBackgroundFetch(this.#valList[i4])) {
            yield this.#valList[i4];
          }
        }
      }
      /**
       * 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 i4 of this.#indexes()) {
          const v2 = this.#valList[i4];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          if (fn(value, this.#keyList[i4], this)) {
            return this.get(this.#keyList[i4], 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 i4 of this.#indexes()) {
          const v2 = this.#valList[i4];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i4], 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 i4 of this.#rindexes()) {
          const v2 = this.#valList[i4];
          const value = this.#isBackgroundFetch(v2) ? v2.__staleWhileFetching : v2;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i4], this);
        }
      }
      /**
       * Delete any stale entries. Returns true if anything was removed,
       * false otherwise.
       */
      purgeStale() {
        let deleted = false;
        for (const i4 of this.#rindexes({ allowStale: true })) {
          if (this.#isStale(i4)) {
            this.#delete(this.#keyList[i4], "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 i4 = this.#keyMap.get(key);
        if (i4 === void 0)
          return void 0;
        const v2 = this.#valList[i4];
        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[i4];
          const start2 = this.#starts[i4];
          if (ttl && start2) {
            const remain = ttl - (perf2.now() - start2);
            entry.ttl = remain;
            entry.start = Date.now();
          }
        }
        if (this.#sizes) {
          entry.size = this.#sizes[i4];
        }
        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 i4 of this.#indexes({ allowStale: true })) {
          const key = this.#keyList[i4];
          const v2 = this.#valList[i4];
          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[i4];
            const age = perf2.now() - this.#starts[i4];
            entry.start = Math.floor(Date.now() - age);
          }
          if (this.#sizes) {
            entry.size = this.#sizes[i4];
          }
          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: start2, 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, start2);
          }
          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((...args2) => args2.every((arg) => arg) ? args2.join("") : "", "maybeJoin");
    var maybeEncode = /* @__PURE__ */ __name((arg) => arg ? encodeURIComponent(arg) : "", "maybeEncode");
    var formatHashFragment = /* @__PURE__ */ __name((f5) => f5.toLowerCase().replace(/^\W+/g, "").replace(/(?<!\W)\W+$/, "").replace(/\//g, "").replace(/\W+/g, "-"), "formatHashFragment");
    var defaults4 = {
      sshtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `git@${domain2}:${user}/${project}.git${maybeJoin("#", committish)}`, "sshtemplate"),
      sshurltemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `git+ssh://git@${domain2}/${user}/${project}.git${maybeJoin("#", committish)}`, "sshurltemplate"),
      edittemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, editpath, path: path150 }) => `https://${domain2}/${user}/${project}${maybeJoin("/", editpath, "/", maybeEncode(committish || "HEAD"), "/", path150)}`, "edittemplate"),
      browsetemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, treepath }) => `https://${domain2}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish))}`, "browsetemplate"),
      browsetreetemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, treepath, path: path150, fragment, hashformat }) => `https://${domain2}/${user}/${project}/${treepath}/${maybeEncode(committish || "HEAD")}/${path150}${maybeJoin("#", hashformat(fragment || ""))}`, "browsetreetemplate"),
      browseblobtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, blobpath, path: path150, fragment, hashformat }) => `https://${domain2}/${user}/${project}/${blobpath}/${maybeEncode(committish || "HEAD")}/${path150}${maybeJoin("#", hashformat(fragment || ""))}`, "browseblobtemplate"),
      docstemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, treepath, committish }) => `https://${domain2}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish))}#readme`, "docstemplate"),
      httpstemplate: /* @__PURE__ */ __name(({ auth: auth2, domain: domain2, user, project, committish }) => `git+https://${maybeJoin(auth2, "@")}${domain2}/${user}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      filetemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, path: path150 }) => `https://${domain2}/${user}/${project}/raw/${maybeEncode(committish || "HEAD")}/${path150}`, "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: domain2, user, project }) => `https://${domain2}/${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: path150 }) => `https://${maybeJoin(auth2, "@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish || "HEAD")}/${path150}`, "filetemplate"),
      gittemplate: /* @__PURE__ */ __name(({ auth: auth2, domain: domain2, user, project, committish }) => `git://${maybeJoin(auth2, "@")}${domain2}/${user}/${project}.git${maybeJoin("#", committish)}`, "gittemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `https://codeload.${domain2}/${user}/${project}/tar.gz/${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url3) => {
        let [, user, project, type, committish] = url3.pathname.split("/", 5);
        if (type && type !== "tree") {
          return;
        }
        if (!type) {
          committish = url3.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: domain2, user, project, committish, treepath, path: path150, editpath }) => `https://${domain2}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish || "HEAD"), "/", path150, editpath)}`, "edittemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `https://${domain2}/${user}/${project}/get/${maybeEncode(committish || "HEAD")}.tar.gz`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url3) => {
        let [, user, project, aux] = url3.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: url3.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: domain2, user, project, committish }) => `git+https://${maybeJoin(auth2, "@")}${domain2}/${user}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `https://${domain2}/${user}/${project}/repository/archive.tar.gz?ref=${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url3) => {
        const path150 = url3.pathname.slice(1);
        if (path150.includes("/-/") || path150.includes("/archive.tar.gz")) {
          return;
        }
        const segments = path150.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: url3.hash.slice(1) };
      }, "extract")
    };
    hosts.gist = {
      protocols: ["git:", "git+ssh:", "git+https:", "ssh:", "https:"],
      domain: "gist.github.com",
      editpath: "edit",
      sshtemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `git@${domain2}:${project}.git${maybeJoin("#", committish)}`, "sshtemplate"),
      sshurltemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `git+ssh://git@${domain2}/${project}.git${maybeJoin("#", committish)}`, "sshurltemplate"),
      edittemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, editpath }) => `https://${domain2}/${user}/${project}${maybeJoin("/", maybeEncode(committish))}/${editpath}`, "edittemplate"),
      browsetemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `https://${domain2}/${project}${maybeJoin("/", maybeEncode(committish))}`, "browsetemplate"),
      browsetreetemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish, path: path150, hashformat }) => `https://${domain2}/${project}${maybeJoin("/", maybeEncode(committish))}${maybeJoin("#", hashformat(path150))}`, "browsetreetemplate"),
      browseblobtemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish, path: path150, hashformat }) => `https://${domain2}/${project}${maybeJoin("/", maybeEncode(committish))}${maybeJoin("#", hashformat(path150))}`, "browseblobtemplate"),
      docstemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `https://${domain2}/${project}${maybeJoin("/", maybeEncode(committish))}`, "docstemplate"),
      httpstemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `git+https://${domain2}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      filetemplate: /* @__PURE__ */ __name(({ user, project, committish, path: path150 }) => `https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/", maybeEncode(committish))}/${path150}`, "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: domain2, project }) => `https://${domain2}/${project}`, "bugstemplate"),
      gittemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `git://${domain2}/${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((url3) => {
        let [, user, project, aux] = url3.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: url3.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: domain2, user, project, committish, path: path150 }) => `https://${domain2}/${user}/${project}/blob/${maybeEncode(committish) || "HEAD"}/${path150}`, "filetemplate"),
      httpstemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `https://${domain2}/${user}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `https://${domain2}/${user}/${project}/archive/${maybeEncode(committish) || "HEAD"}.tar.gz`, "tarballtemplate"),
      bugstemplate: /* @__PURE__ */ __name(() => null, "bugstemplate"),
      extract: /* @__PURE__ */ __name((url3) => {
        let [, user, project, aux] = url3.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: url3.hash.slice(1) };
      }, "extract")
    };
    for (const [name4, host] of Object.entries(hosts)) {
      hosts[name4] = Object.assign({}, defaults4, 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 url3 = __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 url3.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 (err2) {
        if (err2 instanceof URIError) {
          return;
        } else {
          throw err2;
        }
      }
      return [gitHostName, user, auth2, project, committish, defaultRepresentation, opts];
    };
  }
});

// node_modules/hosted-git-info/lib/index.js
var require_lib8 = __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 });
    function unknownHostedUrl(url3) {
      try {
        const {
          protocol,
          hostname: hostname4,
          pathname
        } = new URL(url3);
        if (!hostname4) {
          return null;
        }
        const proto3 = /(?:git\+)http:$/.test(protocol) ? "http:" : "https:";
        const path150 = pathname.replace(/\.git$/, "");
        return `${proto3}//${hostname4}${path150}`;
      } catch {
        return null;
      }
    }
    __name(unknownHostedUrl, "unknownHostedUrl");
    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(name4, host) {
        _GitHost.#gitHosts[name4] = host;
        _GitHost.#gitHosts.byDomain[host.domain] = name4;
        _GitHost.#gitHosts.byShortcut[`${name4}:`] = name4;
        _GitHost.#protocols[`${name4}:`] = { name: name4 };
      }
      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 fromManifest(manifest, opts = {}) {
        if (!manifest || typeof manifest !== "object") {
          return;
        }
        const r5 = manifest.repository;
        const rurl = r5 && (typeof r5 === "string" ? r5 : typeof r5 === "object" && typeof r5.url === "string" ? r5.url : null);
        if (!rurl) {
          throw new Error("no repository");
        }
        const info2 = rurl && _GitHost.fromUrl(rurl.replace(/^git\+/, ""), opts) || null;
        if (info2) {
          return info2;
        }
        const unk = unknownHostedUrl(rurl);
        return _GitHost.fromUrl(unk, opts) || unk;
      }
      static parseUrl(url3) {
        return parseUrl(url3);
      }
      #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(path150, ...args2) {
        if (typeof path150 !== "string") {
          return this.#fill(this.browsetemplate, path150);
        }
        if (typeof args2[0] !== "string") {
          return this.#fill(this.browsetreetemplate, { ...args2[0], path: path150 });
        }
        return this.#fill(this.browsetreetemplate, { ...args2[1], fragment: args2[0], path: path150 });
      }
      // 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(path150, ...args2) {
        if (typeof args2[0] !== "string") {
          return this.#fill(this.browseblobtemplate, { ...args2[0], path: path150 });
        }
        return this.#fill(this.browseblobtemplate, { ...args2[1], fragment: args2[0], path: path150 });
      }
      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(path150, opts) {
        return this.#fill(this.filetemplate, { ...opts, path: path150 });
      }
      edit(path150, opts) {
        return this.#fill(this.edittemplate, { ...opts, path: path150 });
      }
      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 [name4, host] of Object.entries(hosts)) {
      GitHost.addHost(name4, 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 { URL: URL5 } = __require("node:url");
    var isValidSemver = require_valid();
    var cleanSemver = require_clean();
    var validateLicense = require_validate_npm_package_license();
    var hostedGitInfo = require_lib8();
    var { isBuiltin } = __require("node:module");
    var depTypes = ["dependencies", "devDependencies", "optionalDependencies"];
    var extractDescription = require_extract_description();
    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(file2) {
            if (!file2 || typeof file2 !== "string") {
              this.warn("invalidFilename", file2);
              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 (isBuiltin(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 (URL5.canParse(data.bugs)) {
              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 (URL5.canParse(oldBugs.url)) {
                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 (!URL5.canParse(data.homepage)) {
          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(name4, strict, allowLegacyCase) {
      if (name4.charAt(0) === "." || !(isValidScopedPackageName(name4) || isCorrectlyEncodedName(name4)) || strict && !allowLegacyCase && name4 !== name4.toLowerCase() || name4.toLowerCase() === "node_modules" || name4.toLowerCase() === "favicon.ico") {
        throw new Error("Invalid name: " + JSON.stringify(name4));
      }
    }
    __name(ensureValidName, "ensureValidName");
    function modifyPeople(data, fn) {
      if (data.author) {
        data.author = fn(data.author);
      }
      ["maintainers", "contributors"].forEach(function(set2) {
        if (!Array.isArray(data[set2])) {
          return;
        }
        data[set2] = data[set2].map(fn);
      });
      return data;
    }
    __name(modifyPeople, "modifyPeople");
    function unParsePerson(person) {
      if (typeof person === "string") {
        return person;
      }
      var name4 = person.name || "";
      var u2 = person.url || person.web;
      var wrappedUrl = u2 ? " (" + u2 + ")" : "";
      var e4 = person.email || person.mail;
      var wrappedEmail = e4 ? " <" + e4 + ">" : "";
      return name4 + 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 util5 = __require("util");
    var messages = require_warning_messages();
    module2.exports = function() {
      var args2 = Array.prototype.slice.call(arguments, 0);
      var warningName = args2.shift();
      if (warningName === "typo") {
        return makeTypoWarning.apply(null, args2);
      } else {
        var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'";
        args2.unshift(msgTemplate);
        return util5.format.apply(null, args2);
      }
    };
    function makeTypoWarning(providedName, probableName, field) {
      if (field) {
        providedName = field + "['" + providedName + "']";
        probableName = field + "['" + probableName + "']";
      }
      return util5.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 = normalize13;
    var fixer = require_fixer();
    normalize13.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 normalize13(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(normalize13, "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 exec6 = __require("child_process").exec;
    var execSync11 = __require("child_process").execSync;
    var fs142 = __require("fs");
    var path150 = __require("path");
    var access10 = fs142.access;
    var accessSync2 = fs142.accessSync;
    var constants5 = fs142.constants || fs142;
    var isUsingWindows = process.platform == "win32";
    var fileNotExists = /* @__PURE__ */ __name(function(commandName, callback) {
      access10(
        commandName,
        constants5.F_OK,
        function(err2) {
          callback(!err2);
        }
      );
    }, "fileNotExists");
    var fileNotExistsSync = /* @__PURE__ */ __name(function(commandName) {
      try {
        accessSync2(commandName, constants5.F_OK);
        return false;
      } catch (e4) {
        return true;
      }
    }, "fileNotExistsSync");
    var localExecutable = /* @__PURE__ */ __name(function(commandName, callback) {
      access10(
        commandName,
        constants5.F_OK | constants5.X_OK,
        function(err2) {
          callback(null, !err2);
        }
      );
    }, "localExecutable");
    var localExecutableSync = /* @__PURE__ */ __name(function(commandName) {
      try {
        accessSync2(commandName, constants5.F_OK | constants5.X_OK);
        return true;
      } catch (e4) {
        return false;
      }
    }, "localExecutableSync");
    var commandExistsUnix = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
      fileNotExists(commandName, function(isFile4) {
        if (!isFile4) {
          var child = exec6(
            "command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }",
            function(error40, stdout2, stderr) {
              callback(null, !!stdout2);
            }
          );
          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 = exec6(
        "where " + cleanedCommandName,
        function(error40) {
          if (error40 !== null) {
            callback(null, false);
          } else {
            callback(null, true);
          }
        }
      );
    }, "commandExistsWindows");
    var commandExistsUnixSync = /* @__PURE__ */ __name(function(commandName, cleanedCommandName) {
      if (fileNotExistsSync(commandName)) {
        try {
          var stdout2 = execSync11(
            "command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }"
          );
          return !!stdout2;
        } catch (error40) {
          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 stdout2 = execSync11("where " + cleanedCommandName, { stdio: [] });
        return !!stdout2;
      } catch (error40) {
        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 dirname37 = '"' + path150.dirname(s5) + '"';
          var basename34 = '"' + path150.basename(s5) + '"';
          return dirname37 + ":" + basename34;
        }
        return '"' + s5 + '"';
      }, "cleanInput");
    }
    module2.exports = /* @__PURE__ */ __name(function commandExists3(commandName, callback) {
      var cleanedCommandName = cleanInput(commandName);
      if (!callback && typeof Promise !== "undefined") {
        return new Promise(function(resolve42, reject) {
          commandExists3(commandName, function(error40, output) {
            if (output) {
              resolve42(commandName);
            } else {
              reject(error40);
            }
          });
        });
      }
      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, ...args2) {
      const code2 = [strs[0]];
      let i4 = 0;
      while (i4 < args2.length) {
        addCodeArg(code2, args2[i4]);
        code2.push(strs[++i4]);
      }
      return new _Code(code2);
    }
    __name(_2, "_");
    exports2._ = _2;
    var plus = new _Code("+");
    function str2(strs, ...args2) {
      const expr = [safeStringify(strs[0])];
      let i4 = 0;
      while (i4 < args2.length) {
        expr.push(plus);
        addCodeArg(expr, args2[i4]);
        expr.push(plus, safeStringify(strs[++i4]));
      }
      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 i4 = 1;
      while (i4 < expr.length - 1) {
        if (expr[i4] === plus) {
          const res = mergeExprItems(expr[i4 - 1], expr[i4 + 1]);
          if (res !== void 0) {
            expr.splice(i4 - 1, 3, res);
            continue;
          }
          expr[i4++] = "+";
        }
        i4++;
      }
    }
    __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(name4) {
        super(`CodeGen: "code" for ${name4} not defined`);
        this.value = name4.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 name4 = this.toName(nameOrPrefix);
        const { prefix } = name4;
        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, name4);
        const s5 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s5.length;
        s5[itemIndex] = value.ref;
        name4.setValue(value, { property: prefix, itemIndex });
        return name4;
      }
      getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
          return;
        return vs.get(keyOrRef);
      }
      scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name4) => {
          if (name4.scopePath === void 0)
            throw new Error(`CodeGen: name "${name4}" has no value`);
          return (0, code_1._)`${scopeName}${name4.scopePath}`;
        });
      }
      scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name4) => {
          if (name4.value === void 0)
            throw new Error(`CodeGen: name "${name4}" has no value`);
          return name4.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((name4) => {
            if (nameSet.has(name4))
              return;
            nameSet.set(name4, UsedValueState.Started);
            let c4 = valueCode(name4);
            if (c4) {
              const def2 = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const;
              code2 = (0, code_1._)`${code2}${def2} ${name4} = ${c4};${this.opts._n}`;
            } else if (c4 = getCode === null || getCode === void 0 ? void 0 : getCode(name4)) {
              code2 = (0, code_1._)`${code2}${c4}${this.opts._n}`;
            } else {
              throw new ValueError(name4);
            }
            nameSet.set(name4, 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, name4, rhs) {
        super();
        this.varKind = varKind;
        this.name = name4;
        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, constants5) {
        if (!names[this.name.str])
          return;
        if (this.rhs)
          this.rhs = optimizeExpr(this.rhs, names, constants5);
        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, constants5) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
          return;
        this.rhs = optimizeExpr(this.rhs, names, constants5);
        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(error40) {
        super();
        this.error = error40;
      }
      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, constants5) {
        this.code = optimizeExpr(this.code, names, constants5);
        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 i4 = nodes.length;
        while (i4--) {
          const n3 = nodes[i4].optimizeNodes();
          if (Array.isArray(n3))
            nodes.splice(i4, 1, ...n3);
          else if (n3)
            nodes[i4] = n3;
          else
            nodes.splice(i4, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants5) {
        const { nodes } = this;
        let i4 = nodes.length;
        while (i4--) {
          const n3 = nodes[i4];
          if (n3.optimizeNames(names, constants5))
            continue;
          subtractNames(names, n3.names);
          nodes.splice(i4, 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, constants5) {
        var _a7;
        this.else = (_a7 = this.else) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names, constants5);
        if (!(super.optimizeNames(names, constants5) || this.else))
          return;
        this.condition = optimizeExpr(this.condition, names, constants5);
        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, constants5) {
        if (!super.optimizeNames(names, constants5))
          return;
        this.iteration = optimizeExpr(this.iteration, names, constants5);
        return this;
      }
      get names() {
        return addNames(super.names, this.iteration.names);
      }
    };
    var ForRange = class extends For {
      static {
        __name(this, "ForRange");
      }
      constructor(varKind, name4, from, to) {
        super();
        this.varKind = varKind;
        this.name = name4;
        this.from = from;
        this.to = to;
      }
      render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name: name4, from, to } = this;
        return `for(${varKind} ${name4}=${from}; ${name4}<${to}; ${name4}++)` + 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, name4, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name4;
        this.iterable = iterable;
      }
      render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
      }
      optimizeNames(names, constants5) {
        if (!super.optimizeNames(names, constants5))
          return;
        this.iterable = optimizeExpr(this.iterable, names, constants5);
        return this;
      }
      get names() {
        return addNames(super.names, this.iterable.names);
      }
    };
    var Func = class extends BlockNode {
      static {
        __name(this, "Func");
      }
      constructor(name4, args2, async) {
        super();
        this.name = name4;
        this.args = args2;
        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, constants5) {
        var _a7, _b2;
        super.optimizeNames(names, constants5);
        (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names, constants5);
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNames(names, constants5);
        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(error40) {
        super();
        this.error = error40;
      }
      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 name4 = this._extScope.value(prefixOrName, value);
        const vs = this._values[name4.prefix] || (this._values[name4.prefix] = /* @__PURE__ */ new Set());
        vs.add(name4);
        return name4;
      }
      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 name4 = this._scope.toName(nameOrPrefix);
        if (rhs !== void 0 && constant)
          this._constants[name4.str] = rhs;
        this._leafNode(new Def(varKind, name4, rhs));
        return name4;
      }
      // `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 name4 = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name4, from, to), () => forBody(name4));
      }
      // `for-of` statement (in es5 mode replace with a normal for loop)
      forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name4 = 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`, (i4) => {
            this.var(name4, (0, code_1._)`${arr}[${i4}]`);
            forBody(name4);
          });
        }
        return this._for(new ForIter("of", varKind, name4, iterable), () => forBody(name4));
      }
      // `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 name4 = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name4, obj), () => forBody(name4));
      }
      // 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 error40 = this.name("e");
          this._currNode = node.catch = new Catch(error40);
          catchCode(error40);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error40) {
        return this._leafNode(new Throw(error40));
      }
      // start self-balancing block
      block(body2, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body2)
          this.code(body2).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(name4, args2 = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name4, args2, 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, constants5) {
      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 = constants5[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 && constants5[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(...args2) {
      return args2.reduce(andCode);
    }
    __name(and, "and");
    exports2.and = and;
    var orCode = mappend(exports2.operators.OR);
    function or2(...args2) {
      return args2.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(it3, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it3, schema);
      return !schemaHasRules(schema, it3.self.RULES.all);
    }
    __name(alwaysValidSchema, "alwaysValidSchema");
    exports2.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it3, schema = it3.schema) {
      const { opts, self: self2 } = it3;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules[key])
          checkStrictMode(it3, `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 isNumber4 = dataPropType === Type3.Num;
        return jsPropertySyntax ? isNumber4 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber4 ? (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(it3, msg, mode = it3.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it3.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_errors5 = __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, error40 = exports2.keywordError, errorPaths, overrideAllErrors) {
      const { it: it3 } = cxt;
      const { gen, compositeRule, allErrors } = it3;
      const errObj = errorObjectCode(cxt, error40, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it3, (0, codegen_1._)`[${errObj}]`);
      }
    }
    __name(reportError3, "reportError");
    exports2.reportError = reportError3;
    function reportExtraError(cxt, error40 = exports2.keywordError, errorPaths) {
      const { it: it3 } = cxt;
      const { gen, compositeRule, allErrors } = it3;
      const errObj = errorObjectCode(cxt, error40, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it3, 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: it3 }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err2 = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i4) => {
        gen.const(err2, (0, codegen_1._)`${names_1.default.vErrors}[${i4}]`);
        gen.if((0, codegen_1._)`${err2}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err2}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it3.errorPath)));
        gen.assign((0, codegen_1._)`${err2}.schemaPath`, (0, codegen_1.str)`${it3.errSchemaPath}/${keyword}`);
        if (it3.opts.verbose) {
          gen.assign((0, codegen_1._)`${err2}.schema`, schemaValue);
          gen.assign((0, codegen_1._)`${err2}.data`, data);
        }
      });
    }
    __name(extendErrors, "extendErrors");
    exports2.extendErrors = extendErrors;
    function addError(gen, errObj) {
      const err2 = gen.const("err", errObj);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err2}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err2})`);
      gen.code((0, codegen_1._)`${names_1.default.errors}++`);
    }
    __name(addError, "addError");
    function returnErrors(it3, errs) {
      const { gen, validateName: validateName2, schemaEnv } = it3;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it3.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, error40, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error40, errorPaths);
    }
    __name(errorObjectCode, "errorObjectCode");
    function errorObject(cxt, error40, errorPaths = {}) {
      const { gen, it: it3 } = cxt;
      const keyValues = [
        errorInstancePath(it3, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error40, 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: it3 } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it3;
      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_errors5();
    var codegen_1 = require_codegen4();
    var names_1 = require_names3();
    var boolError = {
      message: "boolean schema is false"
    };
    function topBoolOrEmptySchema(it3) {
      const { gen, schema, validateName: validateName2 } = it3;
      if (schema === false) {
        falseSchemaError(it3, 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(it3, valid) {
      const { gen, schema } = it3;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it3);
      } else {
        gen.var(valid, true);
      }
    }
    __name(boolOrEmptySchema, "boolOrEmptySchema");
    exports2.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it3, overrideAllErrors) {
      const { gen, data } = it3;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it: it3
      };
      (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_errors5();
    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(it3, types7) {
      const { gen, data, opts } = it3;
      const coerceTo = coerceToTypes(types7, opts.coerceTypes);
      const checkTypes = types7.length > 0 && !(coerceTo.length === 0 && types7.length === 1 && (0, applicability_1.schemaHasRulesForType)(it3, types7[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types7, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it3, types7, coerceTo);
          else
            reportTypeError(it3);
        });
      }
      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(it3, types7, coerceTo) {
      const { gen, data, opts } = it3;
      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(it3);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it3, 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(it3) {
      const cxt = getTypeErrorContext(it3);
      (0, errors_1.reportError)(cxt, typeError);
    }
    __name(reportTypeError, "reportTypeError");
    exports2.reportTypeError = reportTypeError;
    function getTypeErrorContext(it3) {
      const { gen, data, schema } = it3;
      const schemaCode = (0, util_1.schemaRefOrVal)(it3, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it: it3
      };
    }
    __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(it3, ty) {
      const { properties, items } = it3.schema;
      if (ty === "object" && properties) {
        for (const key in properties) {
          assignDefault(it3, key, properties[key].default);
        }
      } else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i4) => assignDefault(it3, i4, sch.default));
      }
    }
    __name(assignDefaults, "assignDefaults");
    exports2.assignDefaults = assignDefaults;
    function assignDefault(it3, prop, defaultValue) {
      const { gen, compositeRule, data, opts } = it3;
      if (defaultValue === void 0)
        return;
      const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
      if (compositeRule) {
        (0, util_1.checkStrictMode)(it3, `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: it3 } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it3.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(it3, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it3, schemaMap[p2]));
    }
    __name(schemaProperties, "schemaProperties");
    exports2.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it: it3 }, func2, 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, it3.parentData],
        [names_1.default.parentDataProperty, it3.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it3.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args2 = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return context2 !== codegen_1.nil ? (0, codegen_1._)`${func2}.call(${context2}, ${args2})` : (0, codegen_1._)`${func2}(${args2})`;
    }
    __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: it3 } = cxt;
      const valid = gen.name("valid");
      if (it3.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, (i4) => {
          cxt.subschema({
            keyword,
            dataProp: i4,
            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: it3 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it3, sch));
      if (alwaysValid && !it3.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i4) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i4,
          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_errors5();
    function macroKeywordCode(cxt, def2) {
      const { gen, keyword, schema, parentSchema, it: it3 } = cxt;
      const macroSchema = def2.macro.call(it3.self, schema, parentSchema, it3);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it3.opts.validateSchema !== false)
        it3.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it3.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: it3 } = cxt;
      checkAsyncKeyword(it3, def2);
      const validate3 = !$data && def2.compile ? def2.compile.call(it3.self, schema, parentSchema, it3) : 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 ${it3.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 = it3.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: it3 } = cxt;
      gen.if(it3.parentData, () => gen.assign(data, (0, codegen_1._)`${it3.parentData}[${it3.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(it3, { 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 = it3.schema[keyword];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it3.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
          errSchemaPath: `${it3.errSchemaPath}/${keyword}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it3.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it3.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, it3, { 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 } = it3;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it3;
        const nextData = gen.let("data", (0, codegen_1._)`${it3.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 = it3.dataLevel + 1;
        subschema.dataTypes = [];
        it3.definedProperties = /* @__PURE__ */ new Set();
        subschema.parentData = it3.data;
        subschema.dataNames = [...it3.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 post2 = cb.post || function() {
      };
      _traverse(opts, pre, post2, 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, post2, 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 i4 = 0; i4 < sch.length; i4++)
                _traverse(opts, pre, post2, sch[i4], jsonPtr + "/" + key + "/" + i4, rootSchema, jsonPtr, key, schema, i4);
            }
          } else if (key in traverse.propsKeywords) {
            if (sch && typeof sch == "object") {
              for (var prop in sch)
                _traverse(opts, pre, post2, 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, post2, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
          }
        }
        post2(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 = "", normalize13) {
      if (normalize13 !== 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_errors5();
    function validateFunctionCode(it3) {
      if (isSchemaObj(it3)) {
        checkKeywords(it3);
        if (schemaCxtHasRules(it3)) {
          topSchemaObjCode(it3);
          return;
        }
      }
      validateFunction(it3, () => (0, boolSchema_1.topBoolOrEmptySchema)(it3));
    }
    __name(validateFunctionCode, "validateFunctionCode");
    exports2.validateFunctionCode = validateFunctionCode;
    function validateFunction({ gen, validateName: validateName2, schema, schemaEnv, opts }, body2) {
      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(body2);
        });
      } else {
        gen.func(validateName2, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body2));
      }
    }
    __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(it3) {
      const { schema, opts, gen } = it3;
      validateFunction(it3, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it3);
        checkNoDefault(it3);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it3);
        typeAndKeywords(it3);
        returnResults(it3);
      });
      return;
    }
    __name(topSchemaObjCode, "topSchemaObjCode");
    function resetEvaluated(it3) {
      const { gen, validateName: validateName2 } = it3;
      it3.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName2}.evaluated`);
      gen.if((0, codegen_1._)`${it3.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it3.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it3.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it3.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(it3, valid) {
      if (isSchemaObj(it3)) {
        checkKeywords(it3);
        if (schemaCxtHasRules(it3)) {
          subSchemaObjCode(it3, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it3, 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(it3) {
      return typeof it3.schema != "boolean";
    }
    __name(isSchemaObj, "isSchemaObj");
    function subSchemaObjCode(it3, valid) {
      const { schema, gen, opts } = it3;
      if (opts.$comment && schema.$comment)
        commentKeyword(it3);
      updateContext(it3);
      checkAsyncSchema(it3);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it3, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    __name(subSchemaObjCode, "subSchemaObjCode");
    function checkKeywords(it3) {
      (0, util_1.checkUnknownRules)(it3);
      checkRefsAndKeywords(it3);
    }
    __name(checkKeywords, "checkKeywords");
    function typeAndKeywords(it3, errsCount) {
      if (it3.opts.jtd)
        return schemaKeywords(it3, [], false, errsCount);
      const types7 = (0, dataType_1.getSchemaTypes)(it3.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it3, types7);
      schemaKeywords(it3, types7, !checkedTypes, errsCount);
    }
    __name(typeAndKeywords, "typeAndKeywords");
    function checkRefsAndKeywords(it3) {
      const { schema, errSchemaPath, opts, self: self2 } = it3;
      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(it3) {
      const { schema, opts } = it3;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it3, "default is ignored in the schema root");
      }
    }
    __name(checkNoDefault, "checkNoDefault");
    function updateContext(it3) {
      const schId = it3.schema[it3.opts.schemaId];
      if (schId)
        it3.baseId = (0, resolve_1.resolveUrl)(it3.opts.uriResolver, it3.baseId, schId);
    }
    __name(updateContext, "updateContext");
    function checkAsyncSchema(it3) {
      if (it3.schema.$async && !it3.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(it3) {
      const { gen, schemaEnv, validateName: validateName2, ValidationError, opts } = it3;
      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(it3);
        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(it3, types7, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it3;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it3, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it3, 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(it3, group);
          if (types7.length === 1 && types7[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it3);
          }
          gen.endIf();
        } else {
          iterateKeywords(it3, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
      __name(groupKeywords, "groupKeywords");
    }
    __name(schemaKeywords, "schemaKeywords");
    function iterateKeywords(it3, group) {
      const { gen, schema, opts: { useDefaults } } = it3;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it3, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it3, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    __name(iterateKeywords, "iterateKeywords");
    function checkStrictTypes(it3, types7) {
      if (it3.schemaEnv.meta || !it3.opts.strictTypes)
        return;
      checkContextTypes(it3, types7);
      if (!it3.opts.allowUnionTypes)
        checkMultipleTypes(it3, types7);
      checkKeywordTypes(it3, it3.dataTypes);
    }
    __name(checkStrictTypes, "checkStrictTypes");
    function checkContextTypes(it3, types7) {
      if (!types7.length)
        return;
      if (!it3.dataTypes.length) {
        it3.dataTypes = types7;
        return;
      }
      types7.forEach((t5) => {
        if (!includesType(it3.dataTypes, t5)) {
          strictTypesError(it3, `type "${t5}" not allowed by context "${it3.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it3, types7);
    }
    __name(checkContextTypes, "checkContextTypes");
    function checkMultipleTypes(it3, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it3, "use allowUnionTypes to allow union type keyword");
      }
    }
    __name(checkMultipleTypes, "checkMultipleTypes");
    function checkKeywordTypes(it3, ts) {
      const rules = it3.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it3.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t5) => hasApplicableType(ts, t5))) {
            strictTypesError(it3, `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(it3, withTypes) {
      const ts = [];
      for (const t5 of it3.dataTypes) {
        if (includesType(withTypes, t5))
          ts.push(t5);
        else if (withTypes.includes("integer") && t5 === "number")
          ts.push("integer");
      }
      it3.dataTypes = ts;
    }
    __name(narrowSchemaTypes, "narrowSchemaTypes");
    function strictTypesError(it3, msg) {
      const schemaPath = it3.schemaEnv.baseId + it3.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it3, msg, it3.opts.strictTypes);
    }
    __name(strictTypesError, "strictTypesError");
    var KeywordCxt = class {
      static {
        __name(this, "KeywordCxt");
      }
      constructor(it3, def2, keyword) {
        (0, keyword_1.validateKeywordUsage)(it3, def2, keyword);
        this.gen = it3.gen;
        this.allErrors = it3.allErrors;
        this.keyword = keyword;
        this.data = it3.data;
        this.schema = it3.schema[keyword];
        this.$data = def2.$data && it3.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it3, this.schema, keyword, this.$data);
        this.schemaType = def2.schemaType;
        this.parentSchema = it3.schema;
        this.params = {};
        this.it = it3;
        this.def = def2;
        if (this.$data) {
          this.schemaCode = it3.gen.const("vSchema", getData(this.$data, it3));
        } 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 = it3.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(append3, errorParams, errorPaths) {
        if (errorParams) {
          this.setParams(errorParams);
          this._error(append3, errorPaths);
          this.setParams({});
          return;
        }
        this._error(append3, errorPaths);
      }
      _error(append3, errorPaths) {
        ;
        (append3 ? 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: it3 } = 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, it3.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: it3, gen } = this;
        if (!it3.opts.unevaluated)
          return;
        if (it3.props !== true && schemaCxt.props !== void 0) {
          it3.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it3.props, toName);
        }
        if (it3.items !== true && schemaCxt.items !== void 0) {
          it3.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it3.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it: it3, gen } = this;
        if (it3.opts.unevaluated && (it3.props !== true || it3.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports2.KeywordCxt = KeywordCxt;
    function keywordCode(it3, keyword, def2, ruleType) {
      const cxt = new KeywordCxt(it3, 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 matches2 = RELATIVE_JSON_POINTER.exec($data);
        if (!matches2)
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches2[1];
        jsonPointer = matches2[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(env6) {
        var _a7;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env6.schema == "object")
          schema = env6.schema;
        this.schema = env6.schema;
        this.schemaId = env6.schemaId;
        this.root = env6.root || this;
        this.baseId = (_a7 = env6.baseId) !== null && _a7 !== void 0 ? _a7 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env6.schemaId || "$id"]);
        this.schemaPath = env6.schemaPath;
        this.localRefs = env6.localRefs;
        this.meta = env6.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 = resolve42.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 resolve42(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    __name(resolve42, "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 env6;
      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);
        env6 = resolveSchema.call(this, root, $ref);
      }
      const { schemaId } = this.opts;
      env6 = env6 || new SchemaEnv({ schema, schemaId, root, baseId });
      if (env6.schema !== env6.root.schema)
        return env6;
      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, flags2) => new RegExp(str2, flags2), "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 i4 = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i4 >= 0)
            group.rules.splice(i4, 1);
        }
        return this;
      }
      // Add format
      addFormat(name4, format4) {
        if (typeof format4 == "string")
          format4 = new RegExp(format4);
        this.formats[name4] = 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 name4 in this.opts.formats) {
        const format4 = this.opts.formats[name4];
        if (format4)
          this.addFormat(name4, 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 post2 = definition === null || definition === void 0 ? void 0 : definition.post;
      if (dataType && post2)
        throw new Error('keyword with "post" flag cannot have "type"');
      const { RULES } = this;
      let ruleGroup = post2 ? 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 i4 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i4 >= 0) {
        ruleGroup.rules.splice(i4, 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: it3 } = cxt;
        const { baseId, schemaEnv: env6, validateName: validateName2, opts, self: self2 } = it3;
        const { root } = env6;
        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(it3.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
          return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
          if (env6 === root)
            return callRef(cxt, validateName2, env6, env6.$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: it3 } = cxt;
      const { allErrors, schemaEnv: env6, opts } = it3;
      const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
      if ($async)
        callAsyncRef();
      else
        callSyncRef();
      function callAsyncRef() {
        if (!env6.$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 ${it3.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 (!it3.opts.unevaluated)
          return;
        const schEvaluated = (_a7 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a7 === void 0 ? void 0 : _a7.evaluated;
        if (it3.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it3.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it3.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source2}.evaluated.props`);
            it3.props = util_1.mergeEvaluated.props(gen, props, it3.props, codegen_1.Name);
          }
        }
        if (it3.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it3.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it3.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source2}.evaluated.items`);
            it3.items = util_1.mergeEvaluated.items(gen, items, it3.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 error40 = {
      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: error40,
      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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, data, schemaCode, it: it3 } = cxt;
        const prec = it3.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 error40 = {
      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: error40,
      code(cxt) {
        const { keyword, data, schemaCode, it: it3 } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it3.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 error40 = {
      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: error40,
      code(cxt) {
        const { data, $data, schema, schemaCode, it: it3 } = cxt;
        const u2 = it3.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 error40 = {
      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: error40,
      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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it: it3 } = cxt;
        const { opts } = it3;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it3.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 = it3.schemaEnv.baseId + it3.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it3, msg, it3.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 error40 = {
      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: error40,
      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 error40 = {
      message: /* @__PURE__ */ __name(({ params: { i: i4, j: j2 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j2} and ${i4} are identical)`, "message"),
      params: /* @__PURE__ */ __name(({ params: { i: i4, j: j2 } }) => (0, codegen_1._)`{i: ${i4}, j: ${j2}}`, "params")
    };
    var def2 = {
      keyword: "uniqueItems",
      type: "array",
      schemaType: "boolean",
      $data: true,
      error: error40,
      code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it: it3 } = 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 i4 = gen.let("i", (0, codegen_1._)`${data}.length`);
          const j2 = gen.let("j");
          cxt.setParams({ i: i4, j: j2 });
          gen.assign(valid, true);
          gen.if((0, codegen_1._)`${i4} > 1`, () => (canOptimize() ? loopN : loopN2)(i4, j2));
        }
        __name(validateUniqueItems, "validateUniqueItems");
        function canOptimize() {
          return itemTypes.length > 0 && !itemTypes.some((t5) => t5 === "object" || t5 === "array");
        }
        __name(canOptimize, "canOptimize");
        function loopN(i4, j2) {
          const item = gen.name("item");
          const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it3.opts.strictNumbers, dataType_1.DataType.Wrong);
          const indices = gen.const("indices", (0, codegen_1._)`{}`);
          gen.for((0, codegen_1._)`;${i4}--;`, () => {
            gen.let(item, (0, codegen_1._)`${data}[${i4}]`);
            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}] = ${i4}`);
          });
        }
        __name(loopN, "loopN");
        function loopN2(i4, j2) {
          const eql = (0, util_1.useFunc)(gen, equal_1.default);
          const outer = gen.name("outer");
          gen.label(outer).for((0, codegen_1._)`;${i4}--;`, () => gen.for((0, codegen_1._)`${j2} = ${i4}; ${j2}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i4}], ${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 error40 = {
      message: "must be equal to constant",
      params: /* @__PURE__ */ __name(({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`, "params")
    };
    var def2 = {
      keyword: "const",
      $data: true,
      error: error40,
      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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it: it3 } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it3.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, i4) => equalCode(vSchema, i4)));
        }
        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, i4) {
          const sch = schema[i4];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i4}])` : (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 error40 = {
      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: error40,
      code(cxt) {
        const { parentSchema, it: it3 } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
          (0, util_1.checkStrictMode)(it3, '"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: it3 } = cxt;
      it3.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)(it3, 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, (i4) => {
          cxt.subschema({ keyword, dataProp: i4, dataPropType: util_1.Type.Num }, valid);
          if (!it3.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: it3 } = cxt;
        if (Array.isArray(schema))
          return validateTuple(cxt, "additionalItems", schema);
        it3.items = true;
        if ((0, util_1.alwaysValidSchema)(it3, schema))
          return;
        cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    function validateTuple(cxt, extraItems, schArr = cxt.schema) {
      const { gen, parentSchema, data, keyword, it: it3 } = cxt;
      checkStrictTuple(parentSchema);
      if (it3.opts.unevaluated && schArr.length && it3.items !== true) {
        it3.items = util_1.mergeEvaluated.items(gen, schArr.length, it3.items);
      }
      const valid = gen.name("valid");
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      schArr.forEach((sch, i4) => {
        if ((0, util_1.alwaysValidSchema)(it3, sch))
          return;
        gen.if((0, codegen_1._)`${len} > ${i4}`, () => cxt.subschema({
          keyword,
          schemaProp: i4,
          dataProp: i4
        }, valid));
        cxt.ok(valid);
      });
      function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it3;
        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)(it3, 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 error40 = {
      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: error40,
      code(cxt) {
        const { schema, parentSchema, it: it3 } = cxt;
        const { prefixItems } = parentSchema;
        it3.items = true;
        if ((0, util_1.alwaysValidSchema)(it3, 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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it3 } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it3.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)(it3, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it3, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it3, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it3.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, (i4) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i4,
              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: it3 } = 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, it3.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it3.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: it3 } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it3, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it3.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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, data, it: it3 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it3, 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 (!it3.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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it: it3 } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it3;
        it3.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it3, 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)(it3, 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)(it3, 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: it3 } = cxt;
        if (it3.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
          additionalProperties_1.default.code(new validate_1.KeywordCxt(it3, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
          it3.definedProperties.add(prop);
        }
        if (it3.opts.unevaluated && allProps.length && it3.props !== true) {
          it3.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it3.props);
        }
        const properties = allProps.filter((p2) => !(0, util_1.alwaysValidSchema)(it3, 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, it3.opts.ownProperties));
            applyPropertySchema(prop);
            if (!it3.allErrors)
              gen.else().var(valid, true);
            gen.endIf();
          }
          cxt.it.definedProperties.add(prop);
          cxt.ok(valid);
        }
        function hasDefault(prop) {
          return it3.opts.useDefaults && !it3.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: it3 } = cxt;
        const { opts } = it3;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p2) => (0, util_1.alwaysValidSchema)(it3, schema[p2]));
        if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it3.opts.unevaluated || it3.props === true)) {
          return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it3.props !== true && !(it3.props instanceof codegen_1.Name)) {
          it3.props = (0, util_2.evaluatedPropsToName)(gen, it3.props);
        }
        const { props } = it3;
        validatePatternProperties();
        function validatePatternProperties() {
          for (const pat of patterns) {
            if (checkProperties)
              checkMatchingProperties(pat);
            if (it3.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)(it3, `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 (it3.opts.unevaluated && props !== true) {
                gen.assign((0, codegen_1._)`${props}[${key}]`, true);
              } else if (!alwaysValid && !it3.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: it3 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it3, 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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, schema, parentSchema, it: it3 } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        if (it3.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, i4) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it3, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i4,
                compositeRule: true
              }, schValid);
            }
            if (i4 > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i4}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i4);
              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: it3 } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i4) => {
          if ((0, util_1.alwaysValidSchema)(it3, sch))
            return;
          const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i4 }, 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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, parentSchema, it: it3 } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it3, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it3, "then");
        const hasElse = hasSchema(it3, "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(it3, keyword) {
      const schema = it3.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it3, 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: it3 }) {
        if (parentSchema.if === void 0)
          (0, util_1.checkStrictMode)(it3, `"${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 error40 = {
      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: error40,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it: it3 } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it3;
        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 error40 = {
      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: error40,
      code(cxt) {
        const { gen, data, schema, parentSchema, it: it3 } = cxt;
        const { oneOf } = parentSchema;
        if (!it3.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 i4 = 0; i4 < oneOf.length; i4++) {
            let sch = oneOf[i4];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it3.self.RULES)) {
              const ref = sch.$ref;
              sch = compile_1.resolveRef.call(it3.self, it3.schemaEnv.root, it3.baseId, ref);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it3.opts.uriResolver, it3.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, i4);
          }
          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, i4) {
            if (sch.const) {
              addMapping(sch.const, i4);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i4);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          __name(addMappings, "addMappings");
          function addMapping(tagValue, i4) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i4;
          }
          __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_errors6 = __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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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, body2) {
        super(message);
        this.name = "ResponseStatusCodeError";
        this.message = message || "Response Status Code Error";
        this.code = "UND_ERR_RESPONSE_STATUS_CODE";
        this.body = body2;
        this.status = statusCode;
        this.statusCode = statusCode;
        this.headers = headers;
      }
      static [Symbol.hasInstance](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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](instance2) {
        return instance2 && instance2[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 i4 = 0; i4 < wellknownHeaderNames.length; ++i4) {
      const key = wellknownHeaderNames[i4];
      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 i4 = 0; i4 < wellknownHeaderNames.length; ++i4) {
      const key = headerNameLowerCasedRecord[wellknownHeaderNames[i4]];
      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 stream5 = __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_errors6();
    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(body2) {
        this[kBody] = body2;
        this[kBodyUsed] = false;
      }
      async *[Symbol.asyncIterator]() {
        assert4(!this[kBodyUsed], "disturbed");
        this[kBodyUsed] = true;
        yield* this[kBody];
      }
    };
    function wrapRequestBody(body2) {
      if (isStream3(body2)) {
        if (bodyLength(body2) === 0) {
          body2.on("data", function() {
            assert4(false);
          });
        }
        if (typeof body2.readableDidRead !== "boolean") {
          body2[kBodyUsed] = false;
          EE3.prototype.on.call(body2, "data", function() {
            this[kBodyUsed] = true;
          });
        }
        return body2;
      } else if (body2 && typeof body2.pipeTo === "function") {
        return new BodyAsyncIterable(body2);
      } else if (body2 && typeof body2 !== "string" && !ArrayBuffer.isView(body2) && isIterable2(body2)) {
        return new BodyAsyncIterable(body2);
      } else {
        return body2;
      }
    }
    __name(wrapRequestBody, "wrapRequestBody");
    function nop() {
    }
    __name(nop, "nop");
    function isStream3(obj) {
      return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
    }
    __name(isStream3, "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 buildURL2(url3, queryParams) {
      if (url3.includes("?") || url3.includes("#")) {
        throw new Error('Query params cannot be passed when url already contains "?" or "#".');
      }
      const stringified = stringify4(queryParams);
      if (stringified) {
        url3 += "?" + stringified;
      }
      return url3;
    }
    __name(buildURL2, "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(url3) {
      if (typeof url3 === "string") {
        url3 = new URL(url3);
        if (!isHttpOrHttpsPrefixed(url3.origin || url3.protocol)) {
          throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
        }
        return url3;
      }
      if (!url3 || typeof url3 !== "object") {
        throw new InvalidArgumentError("Invalid URL: The URL argument must be a non-null object.");
      }
      if (!(url3 instanceof URL)) {
        if (url3.port != null && url3.port !== "" && isValidPort(url3.port) === false) {
          throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer.");
        }
        if (url3.path != null && typeof url3.path !== "string") {
          throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined.");
        }
        if (url3.pathname != null && typeof url3.pathname !== "string") {
          throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined.");
        }
        if (url3.hostname != null && typeof url3.hostname !== "string") {
          throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined.");
        }
        if (url3.origin != null && typeof url3.origin !== "string") {
          throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined.");
        }
        if (!isHttpOrHttpsPrefixed(url3.origin || url3.protocol)) {
          throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
        }
        const port = url3.port != null ? url3.port : url3.protocol === "https:" ? 443 : 80;
        let origin2 = url3.origin != null ? url3.origin : `${url3.protocol || ""}//${url3.hostname || ""}:${port}`;
        let path150 = url3.path != null ? url3.path : `${url3.pathname || ""}${url3.search || ""}`;
        if (origin2[origin2.length - 1] === "/") {
          origin2 = origin2.slice(0, origin2.length - 1);
        }
        if (path150 && path150[0] !== "/") {
          path150 = `/${path150}`;
        }
        return new URL(`${origin2}${path150}`);
      }
      if (!isHttpOrHttpsPrefixed(url3.origin || url3.protocol)) {
        throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
      }
      return url3;
    }
    __name(parseURL, "parseURL");
    function parseOrigin(url3) {
      url3 = parseURL(url3);
      if (url3.pathname !== "/" || url3.search || url3.hash) {
        throw new InvalidArgumentError("invalid url");
      }
      return url3;
    }
    __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 isIterable2(obj) {
      return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
    }
    __name(isIterable2, "isIterable");
    function bodyLength(body2) {
      if (body2 == null) {
        return 0;
      } else if (isStream3(body2)) {
        const state = body2._readableState;
        return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null;
      } else if (isBlobLike3(body2)) {
        return body2.size != null ? body2.size : null;
      } else if (isBuffer2(body2)) {
        return body2.byteLength;
      }
      return null;
    }
    __name(bodyLength, "bodyLength");
    function isDestroyed(body2) {
      return body2 && !!(body2.destroyed || body2[kDestroyed] || stream5.isDestroyed?.(body2));
    }
    __name(isDestroyed, "isDestroyed");
    function destroy(stream6, err2) {
      if (stream6 == null || !isStream3(stream6) || isDestroyed(stream6)) {
        return;
      }
      if (typeof stream6.destroy === "function") {
        if (Object.getPrototypeOf(stream6).constructor === IncomingMessage) {
          stream6.socket = null;
        }
        stream6.destroy(err2);
      } else if (err2) {
        queueMicrotask(() => {
          stream6.emit("error", err2);
        });
      }
      if (stream6.destroyed !== true) {
        stream6[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 i4 = 0; i4 < headers.length; i4 += 2) {
        const key = headerNameToString(headers[i4]);
        let val = obj[key];
        if (val) {
          if (typeof val === "string") {
            val = [val];
            obj[key] = val;
          }
          val.push(headers[i4 + 1].toString("utf8"));
        } else {
          const headersValue = headers[i4 + 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 isBuffer2(buffer) {
      return buffer instanceof Uint8Array || Buffer.isBuffer(buffer);
    }
    __name(isBuffer2, "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(body2) {
      return !!(body2 && (stream5.isDisturbed(body2) || body2[kBodyUsed]));
    }
    __name(isDisturbed, "isDisturbed");
    function isErrored(body2) {
      return !!(body2 && stream5.isErrored(body2));
    }
    __name(isErrored, "isErrored");
    function isReadable2(body2) {
      return !!(body2 && stream5.isReadable(body2));
    }
    __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 iterator2;
      return new ReadableStream(
        {
          async start() {
            iterator2 = iterable[Symbol.asyncIterator]();
          },
          async pull(controller) {
            const { done, value } = await iterator2.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 iterator2.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 i4 = 0; i4 < characters.length; ++i4) {
        if (!isTokenCharCode(characters.charCodeAt(i4))) {
          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, name4, listener) {
      const listeners = obj[kListeners] ??= [];
      listeners.push([name4, listener]);
      obj.on(name4, listener);
      return obj;
    }
    __name(addListener, "addListener");
    function removeAllListeners(obj) {
      for (const [name4, listener] of obj[kListeners] ?? []) {
        obj.removeListener(name4, listener);
      }
      obj[kListeners] = null;
    }
    __name(removeAllListeners, "removeAllListeners");
    function errorRequest(client, request4, err2) {
      try {
        request4.onError(err2);
        assert4(request4.aborted);
      } catch (err3) {
        client.emit("error", err3);
      }
    }
    __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: isStream3,
      isIterable: isIterable2,
      isAsyncIterable: isAsyncIterable2,
      isDestroyed,
      headerNameToString,
      bufferToLowerCasedHeaderName,
      addListener,
      removeAllListeners,
      errorRequest,
      parseRawHeaders,
      parseHeaders,
      parseKeepAliveTimeout,
      destroy,
      bodyLength,
      deepClone,
      ReadableStreamFrom: ReadableStreamFrom2,
      isBuffer: isBuffer2,
      validateHandler,
      getSocketInfo,
      isFormDataLike,
      buildURL: buildURL2,
      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 util5 = __require("node:util");
    var undiciDebugLog = util5.debuglog("undici");
    var fetchDebuglog = util5.debuglog("fetch");
    var websocketDebuglog = util5.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: error40
        } = evt;
        debuglog(
          "connection to %s using %s%s errored - %s",
          `${host}${port ? `:${port}` : ""}`,
          protocol,
          version2,
          error40.message
        );
      });
      diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => {
        const {
          request: { method, path: path150, origin: origin2 }
        } = evt;
        debuglog("sending request to %s %s/%s", method, origin2, path150);
      });
      diagnosticsChannel.channel("undici:request:headers").subscribe((evt) => {
        const {
          request: { method, path: path150, origin: origin2 },
          response: { statusCode }
        } = evt;
        debuglog(
          "received response to %s %s/%s - HTTP %d",
          method,
          origin2,
          path150,
          statusCode
        );
      });
      diagnosticsChannel.channel("undici:request:trailers").subscribe((evt) => {
        const {
          request: { method, path: path150, origin: origin2 }
        } = evt;
        debuglog("trailers received from %s %s/%s", method, origin2, path150);
      });
      diagnosticsChannel.channel("undici:request:error").subscribe((evt) => {
        const {
          request: { method, path: path150, origin: origin2 },
          error: error40
        } = evt;
        debuglog(
          "request to %s %s/%s errored - %s",
          method,
          origin2,
          path150,
          error40.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: error40
          } = evt;
          debuglog(
            "connection to %s%s using %s%s errored - %s",
            host,
            port ? `:${port}` : "",
            protocol,
            version2,
            error40.message
          );
        });
        diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => {
          const {
            request: { method, path: path150, origin: origin2 }
          } = evt;
          debuglog("sending request to %s %s/%s", method, origin2, path150);
        });
      }
      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((err2) => {
        websocketDebuglog("connection errored - %s", err2.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_errors6();
    var assert4 = __require("node:assert");
    var {
      isValidHTTPToken,
      isValidHeaderValue,
      isStream: isStream3,
      destroy,
      isBuffer: isBuffer2,
      isFormDataLike,
      isIterable: isIterable2,
      isBlobLike: isBlobLike3,
      buildURL: buildURL2,
      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(origin2, {
        path: path150,
        method,
        body: body2,
        headers,
        query,
        idempotent,
        blocking,
        upgrade,
        headersTimeout,
        bodyTimeout,
        reset,
        throwOnError,
        expectContinue,
        servername
      }, handler) {
        if (typeof path150 !== "string") {
          throw new InvalidArgumentError("path must be a string");
        } else if (path150[0] !== "/" && !(path150.startsWith("http://") || path150.startsWith("https://")) && method !== "CONNECT") {
          throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
        } else if (invalidPathRegex.test(path150)) {
          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 (body2 == null) {
          this.body = null;
        } else if (isStream3(body2)) {
          this.body = body2;
          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 = (err2) => {
            if (this.abort) {
              this.abort(err2);
            } else {
              this.error = err2;
            }
          };
          this.body.on("error", this.errorHandler);
        } else if (isBuffer2(body2)) {
          this.body = body2.byteLength ? body2 : null;
        } else if (ArrayBuffer.isView(body2)) {
          this.body = body2.buffer.byteLength ? Buffer.from(body2.buffer, body2.byteOffset, body2.byteLength) : null;
        } else if (body2 instanceof ArrayBuffer) {
          this.body = body2.byteLength ? Buffer.from(body2) : null;
        } else if (typeof body2 === "string") {
          this.body = body2.length ? Buffer.from(body2) : null;
        } else if (isFormDataLike(body2) || isIterable2(body2) || isBlobLike3(body2)) {
          this.body = body2;
        } 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 ? buildURL2(path150, query) : path150;
        this.origin = origin2;
        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 i4 = 0; i4 < headers.length; i4 += 2) {
            processHeader(this, headers[i4], headers[i4 + 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 i4 = 0; i4 < keys.length; ++i4) {
              processHeader(this, keys[i4], headers[keys[i4]]);
            }
          }
        } 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 (err2) {
            this.abort(err2);
          }
        }
      }
      onRequestSent() {
        if (channels.bodySent.hasSubscribers) {
          channels.bodySent.publish({ request: this });
        }
        if (this[kHandler].onRequestSent) {
          try {
            return this[kHandler].onRequestSent();
          } catch (err2) {
            this.abort(err2);
          }
        }
      }
      onConnect(abort2) {
        assert4(!this.aborted);
        assert4(!this.completed);
        if (this.error) {
          abort2(this.error);
        } else {
          this.abort = abort2;
          return this[kHandler].onConnect(abort2);
        }
      }
      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 (err2) {
          this.abort(err2);
        }
      }
      onData(chunk) {
        assert4(!this.aborted);
        assert4(!this.completed);
        try {
          return this[kHandler].onData(chunk);
        } catch (err2) {
          this.abort(err2);
          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 (err2) {
          this.onError(err2);
        }
      }
      onError(error40) {
        this.onFinally();
        if (channels.error.hasSubscribers) {
          channels.error.publish({ request: this, error: error40 });
        }
        if (this.aborted) {
          return;
        }
        this.aborted = true;
        return this[kHandler].onError(error40);
      }
      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 i4 = 0; i4 < val.length; i4++) {
          if (typeof val[i4] === "string") {
            if (!isValidHeaderValue(val[i4])) {
              throw new InvalidArgumentError(`invalid ${key} header`);
            }
            arr.push(val[i4]);
          } else if (val[i4] === null) {
            arr.push("");
          } else if (typeof val[i4] === "object") {
            throw new InvalidArgumentError(`invalid ${key} header`);
          } else {
            arr.push(`${val[i4]}`);
          }
        }
        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 EventEmitter16 = __require("node:events");
    var Dispatcher = class extends EventEmitter16 {
      static {
        __name(this, "Dispatcher");
      }
      dispatch() {
        throw new Error("not implemented");
      }
      close() {
        throw new Error("not implemented");
      }
      destroy() {
        throw new Error("not implemented");
      }
      compose(...args2) {
        const interceptors = Array.isArray(args2[0]) ? args2[0] : args2;
        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(...args2) {
        this.#dispatch(...args2);
      }
      close(...args2) {
        return this.#dispatcher.close(...args2);
      }
      destroy(...args2) {
        return this.#dispatcher.destroy(...args2);
      }
    };
    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_errors6();
    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 i4 = newInterceptors.length - 1; i4 >= 0; i4--) {
            const interceptor = this[kInterceptors][i4];
            if (typeof interceptor !== "function") {
              throw new InvalidArgumentError("interceptor must be an function");
            }
          }
        }
        this[kInterceptors] = newInterceptors;
      }
      close(callback) {
        if (callback === void 0) {
          return new Promise((resolve42, reject) => {
            this.close((err2, data) => {
              return err2 ? reject(err2) : resolve42(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 i4 = 0; i4 < callbacks.length; i4++) {
            callbacks[i4](null, null);
          }
        }, "onClosed");
        this[kClose]().then(() => this.destroy()).then(() => {
          queueMicrotask(onClosed);
        });
      }
      destroy(err2, callback) {
        if (typeof err2 === "function") {
          callback = err2;
          err2 = null;
        }
        if (callback === void 0) {
          return new Promise((resolve42, reject) => {
            this.destroy(err2, (err3, data) => {
              return err3 ? (
                /* istanbul ignore next: should never error */
                reject(err3)
              ) : resolve42(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 (!err2) {
          err2 = 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 i4 = 0; i4 < callbacks.length; i4++) {
            callbacks[i4](null, null);
          }
        }, "onDestroyed");
        this[kDestroy](err2).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 i4 = this[kInterceptors].length - 1; i4 >= 0; i4--) {
          dispatch = this[kInterceptors][i4](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 (err2) {
          if (typeof handler.onError !== "function") {
            throw new InvalidArgumentError("invalid onError method");
          }
          handler.onError(err2);
          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, delay5, arg) {
        this._onTimeout = callback;
        this._idleTimeout = delay5;
        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, delay5, arg) {
        return delay5 <= RESOLUTION_MS ? setTimeout(callback, delay5, arg) : new FastTimer(callback, delay5, 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, delay5, arg) {
        return new FastTimer(callback, delay5, 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(delay5 = 0) {
        fastNow += delay5 - 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 util5 = require_util22();
    var { InvalidArgumentError, ConnectTimeoutError } = require_errors6();
    var timers = require_timers2();
    function noop11() {
    }
    __name(noop11, "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 || util5.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(err2) {
          queueMicrotask(clearConnectTimeout);
          if (callback) {
            const cb = callback;
            callback = null;
            cb(err2);
          }
        });
        return socket;
      }, "connect");
    }
    __name(buildConnector, "buildConnector");
    var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop11;
      }
      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 noop11;
      }
      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)`;
      util5.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 i4 = "A".charCodeAt(0); i4 <= "Z".charCodeAt(0); i4++) {
      exports2.ALPHA.push(String.fromCharCode(i4));
      exports2.ALPHA.push(String.fromCharCode(i4 + 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 i4 = 128; i4 <= 255; i4++) {
      exports2.URL_CHAR.push(i4);
    }
    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 i4 = 32; i4 <= 255; i4++) {
      if (i4 !== 127) {
        exports2.HEADER_CHARS.push(i4);
      }
    }
    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 body2 = stringPercentDecode(encodedBody);
      if (/;(\u0020){0,}base64$/i.test(mimeType)) {
        const stringBody = isomorphicDecode(body2);
        body2 = forgivingBase64(stringBody);
        if (body2 === "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: body2 };
    }
    __name(dataURLProcessor, "dataURLProcessor");
    function URLSerializer(url3, excludeFragment = false) {
      if (!excludeFragment) {
        return url3.href;
      }
      const href = url3.href;
      const hashLength = url3.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 start2 = position.position;
      if (idx === -1) {
        position.position = input.length;
        return input.slice(start2);
      }
      position.position = idx;
      return input.slice(start2, 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 i4 = 0; i4 < length; ++i4) {
        const byte = input[i4];
        if (byte !== 37) {
          output[j2++] = byte;
        } else if (byte === 37 && !(isHexCharByte(input[i4 + 1]) && isHexCharByte(input[i4 + 2]))) {
          output[j2++] = 37;
        } else {
          output[j2++] = hexByteToNumber(input[i4 + 1]) << 4 | hexByteToNumber(input[i4 + 2]);
          i4 += 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 [name4, value] of parameters.entries()) {
        serialization += ";";
        serialization += name4;
        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 i4 = 0;
      let addition = (2 << 15) - 1;
      while (i4 < length) {
        if (i4 + addition > length) {
          addition = length - i4;
        }
        result += String.fromCharCode.apply(null, input.subarray(i4, i4 += 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 err2 = new TypeError("Illegal invocation");
          err2.code = "ERR_INVALID_THIS";
          throw err2;
        }
      } else {
        if (V3?.[Symbol.toStringTag] !== I3.prototype[Symbol.toStringTag]) {
          const err2 = new TypeError("Illegal invocation");
          err2.code = "ERR_INVALID_THIS";
          throw err2;
        }
      }
    };
    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(i4) {
      return (V3, prefix, argument, opts) => {
        if (opts?.strict !== false && !(V3 instanceof i4)) {
          throw webidl.errors.exception({
            header: prefix,
            message: `Expected ${argument} ("${webidl.util.Stringify(V3)}") to be an instance of ${i4.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, name4, opts) {
      if (webidl.util.Type(V3) !== "Object" || !types7.isTypedArray(V3) || V3.constructor.name !== T2.name) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${name4} ("${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, name4, opts) {
      if (webidl.util.Type(V3) !== "Object" || !types7.isDataView(V3)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${name4} 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, name4, opts) {
      if (types7.isAnyArrayBuffer(V3)) {
        return webidl.converters.ArrayBuffer(V3, prefix, name4, { ...opts, allowShared: false });
      }
      if (types7.isTypedArray(V3)) {
        return webidl.converters.TypedArray(V3, V3.constructor, prefix, name4, { ...opts, allowShared: false });
      }
      if (types7.isDataView(V3)) {
        return webidl.converters.DataView(V3, prefix, name4, { ...opts, allowShared: false });
      }
      throw webidl.errors.conversionFailed({
        prefix,
        argument: `${name4} ("${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 zlib5 = __require("node:zlib");
    var { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require_constants16();
    var { getGlobalOrigin } = require_global3();
    var { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require_data_url2();
    var { performance: performance3 } = __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 crypto18;
    try {
      crypto18 = __require("node:crypto");
      const possibleRelevantHashes = ["sha256", "sha384", "sha512"];
      supportedHashes = crypto18.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(url3) {
      for (let i4 = 0; i4 < url3.length; ++i4) {
        const code2 = url3.charCodeAt(i4);
        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 url3 = requestCurrentURL(request4);
      if (urlIsHttpHttpsScheme(url3) && badPortsSet.has(url3.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 i4 = 0; i4 < statusText.length; ++i4) {
        const c4 = statusText.charCodeAt(i4);
        if (!(c4 === 9 || // HTAB
        c4 >= 32 && c4 <= 126 || // SP / VCHAR
        c4 >= 128 && c4 <= 255)) {
          return false;
        }
      }
      return true;
    }
    __name(isValidReasonPhrase, "isValidReasonPhrase");
    var isValidHeaderName2 = 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 i4 = policyHeader.length; i4 !== 0; i4--) {
          const token2 = policyHeader[i4 - 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(performance3.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(url3, originOnly) {
      assert4(url3 instanceof URL);
      url3 = new URL(url3);
      if (url3.protocol === "file:" || url3.protocol === "about:" || url3.protocol === "blank:") {
        return "no-referrer";
      }
      url3.username = "";
      url3.password = "";
      url3.hash = "";
      if (originOnly) {
        url3.pathname = "";
        url3.search = "";
      }
      return url3;
    }
    __name(stripURLForReferrer, "stripURLForReferrer");
    function isURLPotentiallyTrustworthy(url3) {
      if (!(url3 instanceof URL)) {
        return false;
      }
      if (url3.href === "about:blank" || url3.href === "about:srcdoc") {
        return true;
      }
      if (url3.protocol === "data:") return true;
      if (url3.protocol === "file:") return true;
      return isOriginPotentiallyTrustworthy3(url3.origin);
      function isOriginPotentiallyTrustworthy3(origin2) {
        if (origin2 == null || origin2 === "null") return false;
        const originAsURL = new URL(origin2);
        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 (crypto18 === 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 metadata2 = filterMetadataListByAlgorithm(parsedMetadata, strongest);
      for (const item of metadata2) {
        const algorithm = item.algo;
        const expectedValue = item.hash;
        let actualValue = crypto18.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(metadata2) {
      const result = [];
      let empty = true;
      for (const token2 of metadata2.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 i4 = 1; i4 < metadataList.length; ++i4) {
        const metadata2 = metadataList[i4];
        if (metadata2.algo[3] === "5") {
          algorithm = "sha512";
          break;
        } else if (algorithm[3] === "3") {
          continue;
        } else if (metadata2.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 i4 = 0; i4 < metadataList.length; ++i4) {
        if (metadataList[i4].algo === algorithm) {
          metadataList[pos2++] = metadataList[i4];
        }
      }
      metadataList.length = pos2;
      return metadataList;
    }
    __name(filterMetadataListByAlgorithm, "filterMetadataListByAlgorithm");
    function compareBase64Mixed(actualValue, expectedValue) {
      if (actualValue.length !== expectedValue.length) {
        return false;
      }
      for (let i4 = 0; i4 < actualValue.length; ++i4) {
        if (actualValue[i4] !== expectedValue[i4]) {
          if (actualValue[i4] === "+" && expectedValue[i4] === "-" || actualValue[i4] === "/" && expectedValue[i4] === "_") {
            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 promise2 = new Promise((resolve42, reject) => {
        res = resolve42;
        rej = reject;
      });
      return { promise: promise2, 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(name4, 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 ${name4} 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: `${name4} Iterator`
        },
        next: { writable: true, enumerable: true, configurable: true }
      });
      return function(target, kind2) {
        return new FastIterableIterator(target, kind2);
      };
    }
    __name(createIterator, "createIterator");
    function iteratorMixin(name4, object3, kInternalIterator, keyIndex = 0, valueIndex = 1) {
      const makeIterator = createIterator(name4, 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 forEach3(callbackfn, thisArg = globalThis) {
            webidl.brandCheck(this, object3);
            webidl.argumentLengthCheck(arguments, 1, `${name4}.forEach`);
            if (typeof callbackfn !== "function") {
              throw new TypeError(
                `Failed to execute 'forEach' on '${name4}': 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(body2, processBody, processBodyError) {
      const successSteps = processBody;
      const errorSteps = processBodyError;
      let reader;
      try {
        reader = body2.stream.getReader();
      } catch (e4) {
        errorSteps(e4);
        return;
      }
      try {
        successSteps(await readAllBytes(reader));
      } catch (e4) {
        errorSteps(e4);
      }
    }
    __name(fullyReadBody, "fullyReadBody");
    function isReadableStreamLike(stream5) {
      return stream5 instanceof ReadableStream || stream5[Symbol.toStringTag] === "ReadableStream" && typeof stream5.tee === "function";
    }
    __name(isReadableStreamLike, "isReadableStreamLike");
    function readableStreamClose(controller) {
      try {
        controller.close();
        controller.byobRequest?.respond(0);
      } catch (err2) {
        if (!err2.message.includes("Controller is already closed") && !err2.message.includes("ReadableStream is already closed")) {
          throw err2;
        }
      }
    }
    __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(url3) {
      assert4("protocol" in url3);
      const protocol = url3.protocol;
      return protocol === "about:" || protocol === "blob:" || protocol === "data:";
    }
    __name(urlIsLocal, "urlIsLocal");
    function urlHasHttpsScheme(url3) {
      return typeof url3 === "string" && url3[5] === ":" && url3[0] === "h" && url3[1] === "t" && url3[2] === "t" && url3[3] === "p" && url3[4] === "s" || url3.protocol === "https:";
    }
    __name(urlHasHttpsScheme, "urlHasHttpsScheme");
    function urlIsHttpHttpsScheme(url3) {
      assert4("protocol" in url3);
      const protocol = url3.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(zlibOptions2) {
        super();
        this.#zlibOptions = zlibOptions2;
      }
      _transform(chunk, encoding, callback) {
        if (!this._inflateStream) {
          if (chunk.length === 0) {
            callback();
            return;
          }
          this._inflateStream = (chunk[0] & 15) === 8 ? zlib5.createInflate(this.#zlibOptions) : zlib5.createInflateRaw(this.#zlibOptions);
          this._inflateStream.on("data", this.push.bind(this));
          this._inflateStream.on("end", () => this.push(null));
          this._inflateStream.on("error", (err2) => this.destroy(err2));
        }
        this._inflateStream.write(chunk, encoding, callback);
      }
      _final(callback) {
        if (this._inflateStream) {
          this._inflateStream.end();
          this._inflateStream = null;
        }
        callback();
      }
    };
    function createInflate(zlibOptions2) {
      return new InflateStream(zlibOptions2);
    }
    __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(name4, list3) {
      const value = list3.get(name4, 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: isValidHeaderName2,
      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(...args2) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.stream(...args2);
      }
      arrayBuffer(...args2) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.arrayBuffer(...args2);
      }
      slice(...args2) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.slice(...args2);
      }
      text(...args2) {
        webidl.brandCheck(this, _FileLike);
        return this[kState].blobLike.text(...args2);
      }
      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 FormData7 = 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(name4, 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'"
          );
        }
        name4 = webidl.converters.USVString(name4, 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(name4, value, filename);
        this[kState].push(entry);
      }
      delete(name4) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.delete";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name4 = webidl.converters.USVString(name4, prefix, "name");
        this[kState] = this[kState].filter((entry) => entry.name !== name4);
      }
      get(name4) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.get";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name4 = webidl.converters.USVString(name4, prefix, "name");
        const idx = this[kState].findIndex((entry) => entry.name === name4);
        if (idx === -1) {
          return null;
        }
        return this[kState][idx].value;
      }
      getAll(name4) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.getAll";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name4 = webidl.converters.USVString(name4, prefix, "name");
        return this[kState].filter((entry) => entry.name === name4).map((entry) => entry.value);
      }
      has(name4) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.has";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name4 = webidl.converters.USVString(name4, prefix, "name");
        return this[kState].findIndex((entry) => entry.name === name4) !== -1;
      }
      set(name4, 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'"
          );
        }
        name4 = webidl.converters.USVString(name4, 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(name4, value, filename);
        const idx = this[kState].findIndex((entry2) => entry2.name === name4);
        if (idx !== -1) {
          this[kState] = [
            ...this[kState].slice(0, idx),
            entry,
            ...this[kState].slice(idx + 1).filter((entry2) => entry2.name !== name4)
          ];
        } 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", FormData7, kState, "name", "value");
    Object.defineProperties(FormData7.prototype, {
      append: kEnumerableProperty,
      delete: kEnumerableProperty,
      get: kEnumerableProperty,
      getAll: kEnumerableProperty,
      has: kEnumerableProperty,
      set: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "FormData",
        configurable: true
      }
    });
    function makeEntry(name4, 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: name4, value };
    }
    __name(makeEntry, "makeEntry");
    module2.exports = { FormData: FormData7, 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 i4 = 0; i4 < chars.length; ++i4) {
        if ((chars.charCodeAt(i4) & ~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 i4 = 0; i4 < length; ++i4) {
        const cp3 = boundary.charCodeAt(i4);
        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: name4, filename, contentType, encoding } = result;
        position.position += 2;
        let body2;
        {
          const boundaryIndex = input.indexOf(boundary.subarray(2), position.position);
          if (boundaryIndex === -1) {
            return "failure";
          }
          body2 = input.subarray(position.position, boundaryIndex - 4);
          position.position += body2.length;
          if (encoding === "base64") {
            body2 = Buffer.from(body2.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([body2], filename, { type: contentType });
        } else {
          value = utf8DecodeBytes(Buffer.from(body2));
        }
        assert4(isUSVString(name4));
        assert4(typeof value === "string" && isUSVString(value) || isFileLike4(value));
        entryList.push(makeEntry(name4, value, filename));
      }
    }
    __name(multipartFormDataParser, "multipartFormDataParser");
    function parseMultipartFormDataHeaders(input, position) {
      let name4 = null;
      let filename = null;
      let contentType = null;
      let encoding = null;
      while (true) {
        if (input[position.position] === 13 && input[position.position + 1] === 10) {
          if (name4 === null) {
            return "failure";
          }
          return { name: name4, 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": {
            name4 = filename = null;
            if (!bufferStartsWith(input, formDataNameBuffer, position)) {
              return "failure";
            }
            position.position += 17;
            name4 = parseMultipartFormDataName(input, position);
            if (name4 === 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 name4 = collectASequenceOfBytes(
        (char) => char !== 10 && char !== 13 && char !== 34,
        input,
        position
      );
      if (input[position.position] !== 34) {
        return null;
      } else {
        position.position++;
      }
      name4 = new TextDecoder().decode(name4).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"');
      return name4;
    }
    __name(parseMultipartFormDataName, "parseMultipartFormDataName");
    function collectASequenceOfBytes(condition, input, position) {
      let start2 = position.position;
      while (start2 < input.length && condition(input[start2])) {
        ++start2;
      }
      return input.subarray(position.position, position.position = start2);
    }
    __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, start2, position) {
      if (buffer.length < start2.length) {
        return false;
      }
      for (let i4 = 0; i4 < start2.length; i4++) {
        if (start2[i4] !== buffer[position.position + i4]) {
          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 util5 = require_util22();
    var {
      ReadableStreamFrom: ReadableStreamFrom2,
      isBlobLike: isBlobLike3,
      isReadableStreamLike,
      readableStreamClose,
      createDeferredPromise,
      fullyReadBody,
      extractMimeType,
      utf8DecodeBytes
    } = require_util23();
    var { FormData: FormData7 } = 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: isArrayBuffer2 } = __require("node:util/types");
    var { serializeAMimeType } = require_data_url2();
    var { multipartFormDataParser } = require_formdata_parser2();
    var random2;
    try {
      const crypto18 = __require("node:crypto");
      random2 = /* @__PURE__ */ __name((max) => crypto18.randomInt(0, max), "random");
    } catch {
      random2 = /* @__PURE__ */ __name((max) => Math.floor(Math.random(max)), "random");
    }
    var textEncoder2 = new TextEncoder();
    function noop11() {
    }
    __name(noop11, "noop");
    var hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf("v18") !== 0;
    var streamRegistry;
    if (hasFinalizationRegistry) {
      streamRegistry = new FinalizationRegistry((weakRef) => {
        const stream5 = weakRef.deref();
        if (stream5 && !stream5.locked && !isDisturbed(stream5) && !isErrored(stream5)) {
          stream5.cancel("Response object has been garbage collected").catch(noop11);
        }
      });
    }
    function extractBody(object3, keepalive = false) {
      let stream5 = null;
      if (object3 instanceof ReadableStream) {
        stream5 = object3;
      } else if (isBlobLike3(object3)) {
        stream5 = object3.stream();
      } else {
        stream5 = new ReadableStream({
          async pull(controller) {
            const buffer = typeof source2 === "string" ? textEncoder2.encode(source2) : source2;
            if (buffer.byteLength) {
              controller.enqueue(buffer);
            }
            queueMicrotask(() => readableStreamClose(controller));
          },
          start() {
          },
          type: "bytes"
        });
      }
      assert4(isReadableStreamLike(stream5));
      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 (isArrayBuffer2(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 (util5.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 [name4, value] of object3) {
          if (typeof value === "string") {
            const chunk2 = textEncoder2.encode(prefix + `; name="${escape7(normalizeLinefeeds(name4))}"\r
\r
${normalizeLinefeeds(value)}\r
`);
            blobParts.push(chunk2);
            length += chunk2.byteLength;
          } else {
            const chunk2 = textEncoder2.encode(`${prefix}; name="${escape7(normalizeLinefeeds(name4))}"` + (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 = textEncoder2.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 (util5.isDisturbed(object3) || object3.locked) {
          throw new TypeError(
            "Response body object should not be disturbed or locked"
          );
        }
        stream5 = object3 instanceof ReadableStream ? object3 : ReadableStreamFrom2(object3);
      }
      if (typeof source2 === "string" || util5.isBuffer(source2)) {
        length = Buffer.byteLength(source2);
      }
      if (action != null) {
        let iterator2;
        stream5 = new ReadableStream({
          async start() {
            iterator2 = action(object3)[Symbol.asyncIterator]();
          },
          async pull(controller) {
            const { value, done } = await iterator2.next();
            if (done) {
              queueMicrotask(() => {
                controller.close();
                controller.byobRequest?.respond(0);
              });
            } else {
              if (!isErrored(stream5)) {
                const buffer = new Uint8Array(value);
                if (buffer.byteLength) {
                  controller.enqueue(buffer);
                }
              }
            }
            return controller.desiredSize > 0;
          },
          async cancel(reason) {
            await iterator2.return();
          },
          type: "bytes"
        });
      }
      const body2 = { stream: stream5, source: source2, length };
      return [body2, type];
    }
    __name(extractBody, "extractBody");
    function safelyExtractBody(object3, keepalive = false) {
      if (object3 instanceof ReadableStream) {
        assert4(!util5.isDisturbed(object3), "The body has already been consumed.");
        assert4(!object3.locked, "The stream is locked.");
      }
      return extractBody(object3, keepalive);
    }
    __name(safelyExtractBody, "safelyExtractBody");
    function cloneBody(instance2, body2) {
      const [out1, out2] = body2.stream.tee();
      body2.stream = out1;
      return {
        stream: out2,
        length: body2.length,
        source: body2.source
      };
    }
    __name(cloneBody, "cloneBody");
    function throwIfAborted(state) {
      if (state.aborted) {
        throw new DOMException("The operation was aborted.", "AbortError");
      }
    }
    __name(throwIfAborted, "throwIfAborted");
    function bodyMixinMethods(instance2) {
      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 });
          }, instance2);
        },
        arrayBuffer() {
          return consumeBody3(this, (bytes) => {
            return new Uint8Array(bytes).buffer;
          }, instance2);
        },
        text() {
          return consumeBody3(this, utf8DecodeBytes, instance2);
        },
        json() {
          return consumeBody3(this, parseJSONFromBytes, instance2);
        },
        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 FormData7();
                  fd[kState] = parsed;
                  return fd;
                }
                case "application/x-www-form-urlencoded": {
                  const entries = new URLSearchParams(value.toString());
                  const fd = new FormData7();
                  for (const [name4, value2] of entries) {
                    fd.append(name4, value2);
                  }
                  return fd;
                }
              }
            }
            throw new TypeError(
              'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
            );
          }, instance2);
        },
        bytes() {
          return consumeBody3(this, (bytes) => {
            return new Uint8Array(bytes);
          }, instance2);
        }
      };
      return methods;
    }
    __name(bodyMixinMethods, "bodyMixinMethods");
    function mixinBody(prototype2) {
      Object.assign(prototype2.prototype, bodyMixinMethods(prototype2));
    }
    __name(mixinBody, "mixinBody");
    async function consumeBody3(object3, convertBytesToJSValue, instance2) {
      webidl.brandCheck(object3, instance2);
      if (bodyUnusable(object3)) {
        throw new TypeError("Body is unusable: Body has already been read");
      }
      throwIfAborted(object3[kState]);
      const promise2 = createDeferredPromise();
      const errorSteps = /* @__PURE__ */ __name((error40) => promise2.reject(error40), "errorSteps");
      const successSteps = /* @__PURE__ */ __name((data) => {
        try {
          promise2.resolve(convertBytesToJSValue(data));
        } catch (e4) {
          errorSteps(e4);
        }
      }, "successSteps");
      if (object3[kState].body == null) {
        successSteps(Buffer.allocUnsafe(0));
        return promise2.promise;
      }
      await fullyReadBody(object3[kState].body, successSteps, errorSteps);
      return promise2.promise;
    }
    __name(consumeBody3, "consumeBody");
    function bodyUnusable(object3) {
      const body2 = object3[kState].body;
      return body2 != null && (body2.stream.locked || util5.isDisturbed(body2.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 util5 = require_util22();
    var { channels } = require_diagnostics2();
    var timers = require_timers2();
    var {
      RequestContentLengthMismatchError,
      ResponseContentLengthMismatchError,
      RequestAbortedError,
      HeadersTimeoutError,
      HeadersOverflowError,
      SocketError,
      InformationalError,
      BodyTimeoutError,
      HTTPParserError,
      ResponseExceededMaxSizeError
    } = require_errors6();
    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 constants5 = require_constants15();
    var EMPTY_BUF = Buffer.alloc(0);
    var FastBuffer = Buffer[Symbol.species];
    var addListener = util5.addListener;
    var removeAllListeners = util5.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 start2 = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start2, 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 start2 = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start2, len)) || 0;
          }, "wasm_on_header_field"),
          wasm_on_header_value: /* @__PURE__ */ __name((p2, at2, len) => {
            assert4(currentParser.ptr === p2);
            const start2 = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start2, 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 start2 = at2 - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start2, 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 Parser6 = 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(constants5.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(delay5, type) {
        if (delay5 !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
          if (this.timeout) {
            timers.clearTimeout(this.timeout);
            this.timeout = null;
          }
          if (delay5) {
            if (type & USE_FAST_TIMER) {
              this.timeout = timers.setFastTimeout(onParserTimeout, delay5, new WeakRef(this));
            } else {
              this.timeout = setTimeout(onParserTimeout, delay5, new WeakRef(this));
              this.timeout.unref();
            }
          }
          this.timeoutValue = delay5;
        } 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 (err2) {
            throw err2;
          } finally {
            currentParser = null;
            currentBufferRef = null;
          }
          const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr;
          if (ret === constants5.ERROR.PAUSED_UPGRADE) {
            this.onUpgrade(data.slice(offset));
          } else if (ret === constants5.ERROR.PAUSED) {
            this.paused = true;
            socket.unshift(data.slice(offset));
          } else if (ret !== constants5.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, constants5.ERROR[ret], data.slice(offset));
          }
        } catch (err2) {
          util5.destroy(socket, err2);
        }
      }
      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 = util5.bufferToLowerCasedHeaderName(key);
          if (headerName === "keep-alive") {
            this.keepAlive += buf.toString();
          } else if (headerName === "connection") {
            this.connection += buf.toString();
          }
        } else if (key.length === 14 && util5.bufferToLowerCasedHeaderName(key) === "content-length") {
          this.contentLength += buf.toString();
        }
        this.trackHeader(buf.length);
      }
      trackHeader(len) {
        this.headersSize += len;
        if (this.headersSize >= this.headersMaxSize) {
          util5.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 (err2) {
          util5.destroy(socket, err2);
        }
        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) {
          util5.destroy(socket, new SocketError("bad response", util5.getSocketInfo(socket)));
          return -1;
        }
        if (upgrade && !request4.upgrade) {
          util5.destroy(socket, new SocketError("bad upgrade", util5.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 ? util5.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 ? constants5.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) {
          util5.destroy(socket, new ResponseExceededMaxSizeError());
          return -1;
        }
        this.bytesRead += buf.length;
        if (request4.onData(buf) === false) {
          return constants5.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)) {
          util5.destroy(socket, new ResponseContentLengthMismatchError());
          return -1;
        }
        request4.onComplete(headers);
        client[kQueue][client[kRunningIdx]++] = null;
        if (socket[kWriting]) {
          assert4(client[kRunning] === 0);
          util5.destroy(socket, new InformationalError("reset"));
          return constants5.ERROR.PAUSED;
        } else if (!shouldKeepAlive) {
          util5.destroy(socket, new InformationalError("reset"));
          return constants5.ERROR.PAUSED;
        } else if (socket[kReset2] && client[kRunning] === 0) {
          util5.destroy(socket, new InformationalError("reset"));
          return constants5.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");
          util5.destroy(socket, new HeadersTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_BODY) {
        if (!paused) {
          util5.destroy(socket, new BodyTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
        assert4(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]);
        util5.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 Parser6(client, socket, llhttpInstance);
      addListener(socket, "error", function(err2) {
        assert4(err2.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
        const parser6 = this[kParser];
        if (err2.code === "ECONNRESET" && parser6.statusCode && !parser6.shouldKeepAlive) {
          parser6.onMessageComplete();
          return;
        }
        this[kError] = err2;
        this[kClient][kOnError](err2);
      });
      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;
        }
        util5.destroy(this, new SocketError("other side closed", util5.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 err2 = this[kError] || new SocketError("closed", util5.getSocketInfo(this));
        client2[kSocket] = null;
        client2[kHTTPContext] = null;
        if (client2.destroyed) {
          assert4(client2[kPending] === 0);
          const requests = client2[kQueue].splice(client2[kRunningIdx]);
          for (let i4 = 0; i4 < requests.length; i4++) {
            const request4 = requests[i4];
            util5.errorRequest(client2, request4, err2);
          }
        } else if (client2[kRunning] > 0 && err2.code !== "UND_ERR_INFO") {
          const request4 = client2[kQueue][client2[kRunningIdx]];
          client2[kQueue][client2[kRunningIdx]++] = null;
          util5.errorRequest(client2, request4, err2);
        }
        client2[kPendingIdx] = client2[kRunningIdx];
        assert4(client2[kRunning] === 0);
        client2.emit("disconnect", client2[kUrl], [client2], err2);
        client2[kResume]();
      });
      let closed = false;
      socket.on("close", () => {
        closed = true;
      });
      return {
        version: "h1",
        defaultPipelining: 1,
        write(...args2) {
          return writeH1(client, ...args2);
        },
        resume() {
          resumeH1(client);
        },
        destroy(err2, callback) {
          if (closed) {
            queueMicrotask(callback);
          } else {
            socket.destroy(err2).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 && util5.bodyLength(request4.body) !== 0 && (util5.isStream(request4.body) || util5.isAsyncIterable(request4.body) || util5.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: path150, host, upgrade, blocking, reset } = request4;
      let { body: body2, headers, contentLength } = request4;
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
      if (util5.isFormDataLike(body2)) {
        if (!extractBody) {
          extractBody = require_body2().extractBody;
        }
        const [bodyStream, contentType] = extractBody(body2);
        if (request4.contentType == null) {
          headers.push("content-type", contentType);
        }
        body2 = bodyStream.stream;
        contentLength = bodyStream.length;
      } else if (util5.isBlobLike(body2) && request4.contentType == null && body2.type) {
        headers.push("content-type", body2.type);
      }
      if (body2 && typeof body2.read === "function") {
        body2.read(0);
      }
      const bodyLength = util5.bodyLength(body2);
      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]) {
          util5.errorRequest(client, request4, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      const socket = client[kSocket];
      const abort2 = /* @__PURE__ */ __name((err2) => {
        if (request4.aborted || request4.completed) {
          return;
        }
        util5.errorRequest(client, request4, err2 || new RequestAbortedError());
        util5.destroy(body2);
        util5.destroy(socket, new InformationalError("aborted"));
      }, "abort");
      try {
        request4.onConnect(abort2);
      } catch (err2) {
        util5.errorRequest(client, request4, err2);
      }
      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} ${path150} 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 i4 = 0; i4 < val.length; i4++) {
              header += `${key}: ${val[i4]}\r
`;
            }
          } else {
            header += `${key}: ${val}\r
`;
          }
        }
      }
      if (channels.sendHeaders.hasSubscribers) {
        channels.sendHeaders.publish({ request: request4, headers: header, socket });
      }
      if (!body2 || bodyLength === 0) {
        writeBuffer(abort2, null, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util5.isBuffer(body2)) {
        writeBuffer(abort2, body2, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util5.isBlobLike(body2)) {
        if (typeof body2.stream === "function") {
          writeIterable(abort2, body2.stream(), client, request4, socket, contentLength, header, expectsPayload);
        } else {
          writeBlob(abort2, body2, client, request4, socket, contentLength, header, expectsPayload);
        }
      } else if (util5.isStream(body2)) {
        writeStream(abort2, body2, client, request4, socket, contentLength, header, expectsPayload);
      } else if (util5.isIterable(body2)) {
        writeIterable(abort2, body2, client, request4, socket, contentLength, header, expectsPayload);
      } else {
        assert4(false);
      }
      return true;
    }
    __name(writeH1, "writeH1");
    function writeStream(abort2, body2, 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: abort2, 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 (err2) {
          util5.destroy(this, err2);
        }
      }, "onData");
      const onDrain = /* @__PURE__ */ __name(function() {
        if (finished2) {
          return;
        }
        if (body2.resume) {
          body2.resume();
        }
      }, "onDrain");
      const onClose = /* @__PURE__ */ __name(function() {
        queueMicrotask(() => {
          body2.removeListener("error", onFinished);
        });
        if (!finished2) {
          const err2 = new RequestAbortedError();
          queueMicrotask(() => onFinished(err2));
        }
      }, "onClose");
      const onFinished = /* @__PURE__ */ __name(function(err2) {
        if (finished2) {
          return;
        }
        finished2 = true;
        assert4(socket.destroyed || socket[kWriting] && client[kRunning] <= 1);
        socket.off("drain", onDrain).off("error", onFinished);
        body2.removeListener("data", onData).removeListener("end", onFinished).removeListener("close", onClose);
        if (!err2) {
          try {
            writer.end();
          } catch (er2) {
            err2 = er2;
          }
        }
        writer.destroy(err2);
        if (err2 && (err2.code !== "UND_ERR_INFO" || err2.message !== "reset")) {
          util5.destroy(body2, err2);
        } else {
          util5.destroy(body2);
        }
      }, "onFinished");
      body2.on("data", onData).on("end", onFinished).on("error", onFinished).on("close", onClose);
      if (body2.resume) {
        body2.resume();
      }
      socket.on("drain", onDrain).on("error", onFinished);
      if (body2.errorEmitted ?? body2.errored) {
        setImmediate(() => onFinished(body2.errored));
      } else if (body2.endEmitted ?? body2.readableEnded) {
        setImmediate(() => onFinished(null));
      }
      if (body2.closeEmitted ?? body2.closed) {
        setImmediate(onClose);
      }
    }
    __name(writeStream, "writeStream");
    function writeBuffer(abort2, body2, client, request4, socket, contentLength, header, expectsPayload) {
      try {
        if (!body2) {
          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 (util5.isBuffer(body2)) {
          assert4(contentLength === body2.byteLength, "buffer body must have content length");
          socket.cork();
          socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
          socket.write(body2);
          socket.uncork();
          request4.onBodySent(body2);
          if (!expectsPayload && request4.reset !== false) {
            socket[kReset2] = true;
          }
        }
        request4.onRequestSent();
        client[kResume]();
      } catch (err2) {
        abort2(err2);
      }
    }
    __name(writeBuffer, "writeBuffer");
    async function writeBlob(abort2, body2, client, request4, socket, contentLength, header, expectsPayload) {
      assert4(contentLength === body2.size, "blob body must have content length");
      try {
        if (contentLength != null && contentLength !== body2.size) {
          throw new RequestContentLengthMismatchError();
        }
        const buffer = Buffer.from(await body2.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 (err2) {
        abort2(err2);
      }
    }
    __name(writeBlob, "writeBlob");
    async function writeIterable(abort2, body2, 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((resolve42, reject) => {
        assert4(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve42;
        }
      }), "waitForDrain");
      socket.on("close", onDrain).on("drain", onDrain);
      const writer = new AsyncWriter({ abort: abort2, socket, request: request4, contentLength, client, expectsPayload, header });
      try {
        for await (const chunk of body2) {
          if (socket[kError]) {
            throw socket[kError];
          }
          if (!writer.write(chunk)) {
            await waitForDrain();
          }
        }
        writer.end();
      } catch (err2) {
        writer.destroy(err2);
      } finally {
        socket.off("close", onDrain).off("drain", onDrain);
      }
    }
    __name(writeIterable, "writeIterable");
    var AsyncWriter = class {
      static {
        __name(this, "AsyncWriter");
      }
      constructor({ abort: abort2, 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 = abort2;
        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(err2) {
        const { socket, client, abort: abort2 } = this;
        socket[kWriting] = false;
        if (err2) {
          assert4(client[kRunning] <= 1, "pipeline should only contain this request");
          abort2(err2);
        }
      }
    };
    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 util5 = require_util22();
    var {
      RequestContentLengthMismatchError,
      RequestAbortedError,
      SocketError,
      InformationalError
    } = require_errors6();
    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 http23;
    try {
      http23 = __require("node:http2");
    } catch {
      http23 = { 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
      }
    } = http23;
    function parseH2Headers(headers) {
      const result = [];
      for (const [name4, value] of Object.entries(headers)) {
        if (Array.isArray(value)) {
          for (const subvalue of value) {
            result.push(Buffer.from(name4), Buffer.from(subvalue));
          }
        } else {
          result.push(Buffer.from(name4), 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 = http23.connect(client[kUrl], {
        createConnection: /* @__PURE__ */ __name(() => socket, "createConnection"),
        peerMaxConcurrentStreams: client[kMaxConcurrentStreams]
      });
      session[kOpenStreams] = 0;
      session[kClient] = client;
      session[kSocket] = socket;
      util5.addListener(session, "error", onHttp2SessionError);
      util5.addListener(session, "frameError", onHttp2FrameError);
      util5.addListener(session, "end", onHttp2SessionEnd);
      util5.addListener(session, "goaway", onHTTP2GoAway);
      util5.addListener(session, "close", function() {
        const { [kClient]: client2 } = this;
        const { [kSocket]: socket2 } = client2;
        const err2 = this[kSocket][kError] || this[kError] || new SocketError("closed", util5.getSocketInfo(socket2));
        client2[kHTTP2Session] = null;
        if (client2.destroyed) {
          assert4(client2[kPending] === 0);
          const requests = client2[kQueue].splice(client2[kRunningIdx]);
          for (let i4 = 0; i4 < requests.length; i4++) {
            const request4 = requests[i4];
            util5.errorRequest(client2, request4, err2);
          }
        }
      });
      session.unref();
      client[kHTTP2Session] = session;
      socket[kHTTP2Session] = session;
      util5.addListener(socket, "error", function(err2) {
        assert4(err2.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
        this[kError] = err2;
        this[kClient][kOnError](err2);
      });
      util5.addListener(socket, "end", function() {
        util5.destroy(this, new SocketError("other side closed", util5.getSocketInfo(this)));
      });
      util5.addListener(socket, "close", function() {
        const err2 = this[kError] || new SocketError("closed", util5.getSocketInfo(this));
        client[kSocket] = null;
        if (this[kHTTP2Session] != null) {
          this[kHTTP2Session].destroy(err2);
        }
        client[kPendingIdx] = client[kRunningIdx];
        assert4(client[kRunning] === 0);
        client.emit("disconnect", client[kUrl], [client], err2);
        client[kResume]();
      });
      let closed = false;
      socket.on("close", () => {
        closed = true;
      });
      return {
        version: "h2",
        defaultPipelining: Infinity,
        write(...args2) {
          return writeH2(client, ...args2);
        },
        resume() {
          resumeH2(client);
        },
        destroy(err2, callback) {
          if (closed) {
            queueMicrotask(callback);
          } else {
            socket.destroy(err2).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(err2) {
      assert4(err2.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
      this[kSocket][kError] = err2;
      this[kClient][kOnError](err2);
    }
    __name(onHttp2SessionError, "onHttp2SessionError");
    function onHttp2FrameError(type, code2, id) {
      if (id === 0) {
        const err2 = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code2}`);
        this[kSocket][kError] = err2;
        this[kClient][kOnError](err2);
      }
    }
    __name(onHttp2FrameError, "onHttp2FrameError");
    function onHttp2SessionEnd() {
      const err2 = new SocketError("other side closed", util5.getSocketInfo(this[kSocket]));
      this.destroy(err2);
      util5.destroy(this[kSocket], err2);
    }
    __name(onHttp2SessionEnd, "onHttp2SessionEnd");
    function onHTTP2GoAway(code2) {
      const err2 = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code2}`, util5.getSocketInfo(this));
      const client = this[kClient];
      client[kSocket] = null;
      client[kHTTPContext] = null;
      if (this[kHTTP2Session] != null) {
        this[kHTTP2Session].destroy(err2);
        this[kHTTP2Session] = null;
      }
      util5.destroy(this[kSocket], err2);
      if (client[kRunningIdx] < client[kQueue].length) {
        const request4 = client[kQueue][client[kRunningIdx]];
        client[kQueue][client[kRunningIdx]++] = null;
        util5.errorRequest(client, request4, err2);
        client[kPendingIdx] = client[kRunningIdx];
      }
      assert4(client[kRunning] === 0);
      client.emit("disconnect", client[kUrl], [client], err2);
      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: path150, host, upgrade, expectContinue, signal, headers: reqHeaders } = request4;
      let { body: body2 } = request4;
      if (upgrade) {
        util5.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 i4 = 0; i4 < val.length; i4++) {
            if (headers[key]) {
              headers[key] += `,${val[i4]}`;
            } else {
              headers[key] = val[i4];
            }
          }
        } else {
          headers[key] = val;
        }
      }
      let stream5;
      const { hostname: hostname4, port } = client[kUrl];
      headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname4}${port ? `:${port}` : ""}`;
      headers[HTTP2_HEADER_METHOD] = method;
      const abort2 = /* @__PURE__ */ __name((err2) => {
        if (request4.aborted || request4.completed) {
          return;
        }
        err2 = err2 || new RequestAbortedError();
        util5.errorRequest(client, request4, err2);
        if (stream5 != null) {
          util5.destroy(stream5, err2);
        }
        util5.destroy(body2, err2);
        client[kQueue][client[kRunningIdx]++] = null;
        client[kResume]();
      }, "abort");
      try {
        request4.onConnect(abort2);
      } catch (err2) {
        util5.errorRequest(client, request4, err2);
      }
      if (request4.aborted) {
        return false;
      }
      if (method === "CONNECT") {
        session.ref();
        stream5 = session.request(headers, { endStream: false, signal });
        if (stream5.id && !stream5.pending) {
          request4.onUpgrade(null, null, stream5);
          ++session[kOpenStreams];
          client[kQueue][client[kRunningIdx]++] = null;
        } else {
          stream5.once("ready", () => {
            request4.onUpgrade(null, null, stream5);
            ++session[kOpenStreams];
            client[kQueue][client[kRunningIdx]++] = null;
          });
        }
        stream5.once("close", () => {
          session[kOpenStreams] -= 1;
          if (session[kOpenStreams] === 0) session.unref();
        });
        return true;
      }
      headers[HTTP2_HEADER_PATH] = path150;
      headers[HTTP2_HEADER_SCHEME] = "https";
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
      if (body2 && typeof body2.read === "function") {
        body2.read(0);
      }
      let contentLength = util5.bodyLength(body2);
      if (util5.isFormDataLike(body2)) {
        extractBody ??= require_body2().extractBody;
        const [bodyStream, contentType] = extractBody(body2);
        headers["content-type"] = contentType;
        body2 = 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]) {
          util5.errorRequest(client, request4, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      if (contentLength != null) {
        assert4(body2, "no body must not have content length");
        headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
      }
      session.ref();
      const shouldEndStream = method === "GET" || method === "HEAD" || body2 === null;
      if (expectContinue) {
        headers[HTTP2_HEADER_EXPECT] = "100-continue";
        stream5 = session.request(headers, { endStream: shouldEndStream, signal });
        stream5.once("continue", writeBodyH2);
      } else {
        stream5 = session.request(headers, {
          endStream: shouldEndStream,
          signal
        });
        writeBodyH2();
      }
      ++session[kOpenStreams];
      stream5.once("response", (headers2) => {
        const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
        request4.onResponseStarted();
        if (request4.aborted) {
          const err2 = new RequestAbortedError();
          util5.errorRequest(client, request4, err2);
          util5.destroy(stream5, err2);
          return;
        }
        if (request4.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream5.resume.bind(stream5), "") === false) {
          stream5.pause();
        }
        stream5.on("data", (chunk) => {
          if (request4.onData(chunk) === false) {
            stream5.pause();
          }
        });
      });
      stream5.once("end", () => {
        if (stream5.state?.state == null || stream5.state.state < 6) {
          request4.onComplete([]);
        }
        if (session[kOpenStreams] === 0) {
          session.unref();
        }
        abort2(new InformationalError("HTTP/2: stream half-closed (remote)"));
        client[kQueue][client[kRunningIdx]++] = null;
        client[kPendingIdx] = client[kRunningIdx];
        client[kResume]();
      });
      stream5.once("close", () => {
        session[kOpenStreams] -= 1;
        if (session[kOpenStreams] === 0) {
          session.unref();
        }
      });
      stream5.once("error", function(err2) {
        abort2(err2);
      });
      stream5.once("frameError", (type, code2) => {
        abort2(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code2}`));
      });
      return true;
      function writeBodyH2() {
        if (!body2 || contentLength === 0) {
          writeBuffer(
            abort2,
            stream5,
            null,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util5.isBuffer(body2)) {
          writeBuffer(
            abort2,
            stream5,
            body2,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util5.isBlobLike(body2)) {
          if (typeof body2.stream === "function") {
            writeIterable(
              abort2,
              stream5,
              body2.stream(),
              client,
              request4,
              client[kSocket],
              contentLength,
              expectsPayload
            );
          } else {
            writeBlob(
              abort2,
              stream5,
              body2,
              client,
              request4,
              client[kSocket],
              contentLength,
              expectsPayload
            );
          }
        } else if (util5.isStream(body2)) {
          writeStream(
            abort2,
            client[kSocket],
            expectsPayload,
            stream5,
            body2,
            client,
            request4,
            contentLength
          );
        } else if (util5.isIterable(body2)) {
          writeIterable(
            abort2,
            stream5,
            body2,
            client,
            request4,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else {
          assert4(false);
        }
      }
      __name(writeBodyH2, "writeBodyH2");
    }
    __name(writeH2, "writeH2");
    function writeBuffer(abort2, h2stream, body2, client, request4, socket, contentLength, expectsPayload) {
      try {
        if (body2 != null && util5.isBuffer(body2)) {
          assert4(contentLength === body2.byteLength, "buffer body must have content length");
          h2stream.cork();
          h2stream.write(body2);
          h2stream.uncork();
          h2stream.end();
          request4.onBodySent(body2);
        }
        if (!expectsPayload) {
          socket[kReset2] = true;
        }
        request4.onRequestSent();
        client[kResume]();
      } catch (error40) {
        abort2(error40);
      }
    }
    __name(writeBuffer, "writeBuffer");
    function writeStream(abort2, socket, expectsPayload, h2stream, body2, client, request4, contentLength) {
      assert4(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      const pipe2 = pipeline3(
        body2,
        h2stream,
        (err2) => {
          if (err2) {
            util5.destroy(pipe2, err2);
            abort2(err2);
          } else {
            util5.removeAllListeners(pipe2);
            request4.onRequestSent();
            if (!expectsPayload) {
              socket[kReset2] = true;
            }
            client[kResume]();
          }
        }
      );
      util5.addListener(pipe2, "data", onPipeData);
      function onPipeData(chunk) {
        request4.onBodySent(chunk);
      }
      __name(onPipeData, "onPipeData");
    }
    __name(writeStream, "writeStream");
    async function writeBlob(abort2, h2stream, body2, client, request4, socket, contentLength, expectsPayload) {
      assert4(contentLength === body2.size, "blob body must have content length");
      try {
        if (contentLength != null && contentLength !== body2.size) {
          throw new RequestContentLengthMismatchError();
        }
        const buffer = Buffer.from(await body2.arrayBuffer());
        h2stream.cork();
        h2stream.write(buffer);
        h2stream.uncork();
        h2stream.end();
        request4.onBodySent(buffer);
        request4.onRequestSent();
        if (!expectsPayload) {
          socket[kReset2] = true;
        }
        client[kResume]();
      } catch (err2) {
        abort2(err2);
      }
    }
    __name(writeBlob, "writeBlob");
    async function writeIterable(abort2, h2stream, body2, 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((resolve42, reject) => {
        assert4(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve42;
        }
      }), "waitForDrain");
      h2stream.on("close", onDrain).on("drain", onDrain);
      try {
        for await (const chunk of body2) {
          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 (err2) {
        abort2(err2);
      } 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 util5 = require_util22();
    var { kBodyUsed } = require_symbols6();
    var assert4 = __require("node:assert");
    var { InvalidArgumentError } = require_errors6();
    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(body2) {
        this[kBody] = body2;
        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");
        }
        util5.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 (util5.isStream(this.opts.body)) {
          if (util5.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) && util5.isIterable(this.opts.body)) {
          this.opts.body = new BodyAsyncIterable(this.opts.body);
        }
      }
      onConnect(abort2) {
        this.abort = abort2;
        this.handler.onConnect(abort2, { history: this.history });
      }
      onUpgrade(statusCode, headers, socket) {
        this.handler.onUpgrade(statusCode, headers, socket);
      }
      onError(error40) {
        this.handler.onError(error40);
      }
      onHeaders(statusCode, headers, resume, statusText) {
        this.location = this.history.length >= this.maxRedirections || util5.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: origin2, pathname, search } = util5.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
        const path150 = search ? `${pathname}${search}` : pathname;
        this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin2);
        this.opts.path = path150;
        this.opts.origin = origin2;
        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 i4 = 0; i4 < headers.length; i4 += 2) {
        if (headers[i4].length === 8 && util5.headerNameToString(headers[i4]) === "location") {
          return headers[i4 + 1];
        }
      }
    }
    __name(parseLocation, "parseLocation");
    function shouldRemoveHeader(header, removeContent, unknownOrigin) {
      if (header.length === 4) {
        return util5.headerNameToString(header) === "host";
      }
      if (removeContent && util5.headerNameToString(header).startsWith("content-")) {
        return true;
      }
      if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
        const name4 = util5.headerNameToString(header);
        return name4 === "authorization" || name4 === "cookie" || name4 === "proxy-authorization";
      }
      return false;
    }
    __name(shouldRemoveHeader, "shouldRemoveHeader");
    function cleanRequestHeaders(headers, removeContent, unknownOrigin) {
      const ret = [];
      if (Array.isArray(headers)) {
        for (let i4 = 0; i4 < headers.length; i4 += 2) {
          if (!shouldRemoveHeader(headers[i4], removeContent, unknownOrigin)) {
            ret.push(headers[i4], headers[i4 + 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 http9 = __require("node:http");
    var util5 = require_util22();
    var { channels } = require_diagnostics2();
    var Request6 = require_request3();
    var DispatcherBase = require_dispatcher_base2();
    var {
      InvalidArgumentError,
      InformationalError,
      ClientDestroyedError
    } = require_errors6();
    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 noop11 = /* @__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(url3, {
        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] = util5.parseOrigin(url3);
        this[kConnector] = connect2;
        this[kPipelining] = pipelining != null ? pipelining : 1;
        this[kMaxHeadersSize] = maxHeaderSize || http9.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] = (err2) => onError2(this, err2);
      }
      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 origin2 = opts.origin || this[kUrl].origin;
        const request4 = new Request6(origin2, opts, handler);
        this[kQueue].push(request4);
        if (this[kResuming]) {
        } else if (util5.bodyLength(request4.body) == null && util5.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((resolve42) => {
          if (this[kSize]) {
            this[kClosedResolve] = resolve42;
          } else {
            resolve42(null);
          }
        });
      }
      async [kDestroy](err2) {
        return new Promise((resolve42) => {
          const requests = this[kQueue].splice(this[kPendingIdx]);
          for (let i4 = 0; i4 < requests.length; i4++) {
            const request4 = requests[i4];
            util5.errorRequest(this, request4, err2);
          }
          const callback = /* @__PURE__ */ __name(() => {
            if (this[kClosedResolve]) {
              this[kClosedResolve]();
              this[kClosedResolve] = null;
            }
            resolve42(null);
          }, "callback");
          if (this[kHTTPContext]) {
            this[kHTTPContext].destroy(err2, callback);
            this[kHTTPContext] = null;
          } else {
            queueMicrotask(callback);
          }
          this[kResume]();
        });
      }
    };
    var createRedirectInterceptor = require_redirect_interceptor2();
    function onError2(client, err2) {
      if (client[kRunning] === 0 && err2.code !== "UND_ERR_INFO" && err2.code !== "UND_ERR_SOCKET") {
        assert4(client[kPendingIdx] === client[kRunningIdx]);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i4 = 0; i4 < requests.length; i4++) {
          const request4 = requests[i4];
          util5.errorRequest(client, request4, err2);
        }
        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((resolve42, reject) => {
          client[kConnector]({
            host,
            hostname: hostname4,
            protocol,
            port,
            servername: client[kServerName],
            localAddress: client[kLocalAddress]
          }, (err2, socket2) => {
            if (err2) {
              reject(err2);
            } else {
              resolve42(socket2);
            }
          });
        });
        if (client.destroyed) {
          util5.destroy(socket.on("error", noop11), new ClientDestroyedError());
          return;
        }
        assert4(socket);
        try {
          client[kHTTPContext] = socket.alpnProtocol === "h2" ? await connectH2(client, socket) : await connectH1(client, socket);
        } catch (err2) {
          socket.destroy().on("error", noop11);
          throw err2;
        }
        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 (err2) {
        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: err2
          });
        }
        if (err2.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]++];
            util5.errorRequest(client, request4, err2);
          }
        } else {
          onError2(client, err2);
        }
        client.emit("connectionError", client[kUrl], [client], err2);
      }
      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(origin2, 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", origin2, [pool, ...targets]);
          }
          if (pool[kClosedResolve] && queue.isEmpty()) {
            Promise.all(pool[kClients].map((c4) => c4.close())).then(pool[kClosedResolve]);
          }
        }, "onDrain");
        this[kOnConnect] = (origin2, targets) => {
          pool.emit("connect", origin2, [pool, ...targets]);
        };
        this[kOnDisconnect] = (origin2, targets, err2) => {
          pool.emit("disconnect", origin2, [pool, ...targets], err2);
        };
        this[kOnConnectionError] = (origin2, targets, err2) => {
          pool.emit("connectionError", origin2, [pool, ...targets], err2);
        };
        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((resolve42) => {
            this[kClosedResolve] = resolve42;
          });
        }
      }
      async [kDestroy](err2) {
        while (true) {
          const item = this[kQueue].shift();
          if (!item) {
            break;
          }
          item.handler.onError(err2);
        }
        await Promise.all(this[kClients].map((c4) => c4.destroy(err2)));
      }
      [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_errors6();
    var util5 = 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(origin2, opts) {
      return new Client3(origin2, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var Pool = class extends PoolBase {
      static {
        __name(this, "Pool");
      }
      constructor(origin2, {
        connections,
        factory: factory2 = 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 factory2 !== "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] = util5.parseOrigin(origin2);
        this[kOptions] = { ...util5.deepClone(options2), connect, allowH2 };
        this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
        this[kFactory] = factory2;
        this.on("connectionError", (origin3, targets, error40) => {
          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_errors6();
    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(origin2, opts) {
      return new Pool(origin2, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var BalancedPool = class extends PoolBase {
      static {
        __name(this, "BalancedPool");
      }
      constructor(upstreams = [], { factory: factory2 = 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 factory2 !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) ? opts.interceptors.BalancedPool : [];
        this[kFactory] = factory2;
        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", (...args2) => {
          const err2 = args2[2];
          if (err2 && err2.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 i4 = 0; i4 < this[kClients].length; i4++) {
          result = getGreatestCommonDivisor(this[kClients][i4][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_errors6();
    var { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require_symbols6();
    var DispatcherBase = require_dispatcher_base2();
    var Pool = require_pool3();
    var Client3 = require_client3();
    var util5 = 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(origin2, opts) {
      return opts && opts.connections === 1 ? new Client3(origin2, opts) : new Pool(origin2, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var Agent4 = class extends DispatcherBase {
      static {
        __name(this, "Agent");
      }
      constructor({ factory: factory2 = defaultFactory, maxRedirections = 0, connect, ...options2 } = {}) {
        super();
        if (typeof factory2 !== "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] = { ...util5.deepClone(options2), connect };
        this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
        this[kMaxRedirections] = maxRedirections;
        this[kFactory] = factory2;
        this[kClients] = /* @__PURE__ */ new Map();
        this[kOnDrain] = (origin2, targets) => {
          this.emit("drain", origin2, [this, ...targets]);
        };
        this[kOnConnect] = (origin2, targets) => {
          this.emit("connect", origin2, [this, ...targets]);
        };
        this[kOnDisconnect] = (origin2, targets, err2) => {
          this.emit("disconnect", origin2, [this, ...targets], err2);
        };
        this[kOnConnectionError] = (origin2, targets, err2) => {
          this.emit("connectionError", origin2, [this, ...targets], err2);
        };
      }
      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](err2) {
        const destroyPromises = [];
        for (const client of this[kClients].values()) {
          destroyPromises.push(client.destroy(err2));
        }
        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_errors6();
    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(origin2, opts) {
      return new Pool(origin2, opts);
    }
    __name(defaultFactory, "defaultFactory");
    var noop11 = /* @__PURE__ */ __name(() => {
    }, "noop");
    function defaultAgentFactory(origin2, opts) {
      if (opts.connections === 1) {
        return new Client3(origin2, opts);
      }
      return new Pool(origin2, opts);
    }
    __name(defaultAgentFactory, "defaultAgentFactory");
    var Http1ProxyWrapper = class extends DispatcherBase {
      static {
        __name(this, "Http1ProxyWrapper");
      }
      #client;
      constructor(proxyUrl, { headers = {}, connect, factory: factory2 }) {
        super();
        if (!proxyUrl) {
          throw new InvalidArgumentError("Proxy URL is mandatory");
        }
        this[kProxyHeaders] = headers;
        if (factory2) {
          this.#client = factory2(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: origin2,
          path: path150 = "/",
          headers = {}
        } = opts;
        opts.path = origin2 + path150;
        if (!("host" in headers) && !("Host" in headers)) {
          const { host } = new URL5(origin2);
          headers.host = host;
        }
        opts.headers = { ...this[kProxyHeaders], ...headers };
        return this.#client[kDispatch](opts, handler);
      }
      async [kClose]() {
        return this.#client.close();
      }
      async [kDestroy](err2) {
        return this.#client.destroy(err2);
      }
    };
    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 url3 = this.#getUrl(opts);
        const { href, origin: origin2, port, protocol, username, password, hostname: proxyHostname } = url3;
        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 factory2 = /* @__PURE__ */ __name((origin3, options2) => {
          const { protocol: protocol2 } = new URL5(origin3);
          if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
            return new Http1ProxyWrapper(this[kProxy].uri, {
              headers: this[kProxyHeaders],
              connect,
              factory: agentFactory
            });
          }
          return agentFactory(origin3, options2);
        }, "factory");
        this[kClient] = clientFactory(url3, { connect });
        this[kAgent] = new Agent4({
          ...opts,
          factory: factory2,
          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: origin2,
                port,
                path: requestedPath,
                signal: opts2.signal,
                headers: {
                  ...this[kProxyHeaders],
                  host: opts2.host
                },
                servername: this[kProxyTls]?.servername || proxyHostname
              });
              if (statusCode !== 200) {
                socket.on("error", noop11).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 (err2) {
              if (err2.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
                callback(new SecureProxyConnectionError(err2));
              } else {
                callback(err2);
              }
            }
          }, "connect")
        });
      }
      dispatch(opts, handler) {
        const headers = buildHeaders3(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 buildHeaders3(headers) {
      if (Array.isArray(headers)) {
        const headersPair = {};
        for (let i4 = 0; i4 < headers.length; i4 += 2) {
          headersPair[headers[i4]] = headers[i4 + 1];
        }
        return headersPair;
      }
      return headers;
    }
    __name(buildHeaders3, "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 url3 = new URL(opts.origin);
        const agent = this.#getProxyAgentForUrl(url3);
        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](err2) {
        await this[kNoProxyAgent].destroy(err2);
        if (!this[kHttpProxyAgent][kDestroyed]) {
          await this[kHttpProxyAgent].destroy(err2);
        }
        if (!this[kHttpsProxyAgent][kDestroyed]) {
          await this[kHttpsProxyAgent].destroy(err2);
        }
      }
      #getProxyAgentForUrl(url3) {
        let { protocol, host: hostname4, port } = url3;
        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 i4 = 0; i4 < this.#noProxyEntries.length; i4++) {
          const entry = this.#noProxyEntries[i4];
          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 i4 = 0; i4 < noProxySplit.length; i4++) {
          const entry = noProxySplit[i4];
          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_errors6();
    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(abort2) {
        if (this.aborted) {
          abort2(this.reason);
        } else {
          this.abort = abort2;
        }
      }
      onBodySent(chunk) {
        if (this.handler.onBodySent) return this.handler.onBodySent(chunk);
      }
      static [kRetryHandlerDefaultRetry](err2, { state, opts }, cb) {
        const { statusCode, code: code2, headers } = err2;
        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(err2);
          return;
        }
        if (Array.isArray(methods) && !methods.includes(method)) {
          cb(err2);
          return;
        }
        if (statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode)) {
          cb(err2);
          return;
        }
        if (counter > maxRetries) {
          cb(err2);
          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: start2, size, end = size - 1 } = contentRange;
          assert4(this.start === start2, "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: start2, size, end = size - 1 } = range;
            assert4(
              start2 != null && Number.isFinite(start2),
              "content-range mismatch"
            );
            assert4(end != null && Number.isFinite(end), "invalid content-length");
            this.start = start2;
            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 err2 = new RequestRetryError("Request failed", statusCode, {
          headers,
          data: { count: this.retryCount }
        });
        this.abort(err2);
        return false;
      }
      onData(chunk) {
        this.start += chunk.length;
        return this.handler.onData(chunk);
      }
      onComplete(rawTrailers) {
        this.retryCount = 0;
        return this.handler.onComplete(rawTrailers);
      }
      onError(err2) {
        if (this.aborted || isDisturbed(this.opts.body)) {
          return this.handler.onError(err2);
        }
        if (this.retryCount - this.retryCountCheckpoint > 0) {
          this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint);
        } else {
          this.retryCount += 1;
        }
        this.retryOpts.retry(
          err2,
          {
            state: { counter: this.retryCount },
            opts: { retryOptions: this.retryOpts, ...this.opts }
          },
          onRetry.bind(this)
        );
        function onRetry(err3) {
          if (err3 != null || this.aborted || isDisturbed(this.opts.body)) {
            return this.handler.onError(err3);
          }
          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 (err4) {
            this.handler.onError(err4);
          }
        }
        __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: Readable8 } = __require("node:stream");
    var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError: AbortError4 } = require_errors6();
    var util5 = 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 noop11 = /* @__PURE__ */ __name(() => {
    }, "noop");
    var BodyReadable = class extends Readable8 {
      static {
        __name(this, "BodyReadable");
      }
      constructor({
        resume,
        abort: abort2,
        contentType = "",
        contentLength,
        highWaterMark = 64 * 1024
        // Same as nodejs fs streams.
      }) {
        super({
          autoDestroy: true,
          read: resume,
          highWaterMark
        });
        this._readableState.dataEmitted = false;
        this[kAbort] = abort2;
        this[kConsume] = null;
        this[kBody] = null;
        this[kContentType] = contentType;
        this[kContentLength] = contentLength;
        this[kReading] = false;
      }
      destroy(err2) {
        if (!err2 && !this._readableState.endEmitted) {
          err2 = new RequestAbortedError();
        }
        if (err2) {
          this[kAbort]();
        }
        return super.destroy(err2);
      }
      _destroy(err2, callback) {
        if (!this[kReading]) {
          setImmediate(() => {
            callback(err2);
          });
        } else {
          callback(err2);
        }
      }
      on(ev, ...args2) {
        if (ev === "data" || ev === "readable") {
          this[kReading] = true;
        }
        return super.on(ev, ...args2);
      }
      addListener(ev, ...args2) {
        return this.on(ev, ...args2);
      }
      off(ev, ...args2) {
        const ret = super.off(ev, ...args2);
        if (ev === "data" || ev === "readable") {
          this[kReading] = this.listenerCount("data") > 0 || this.listenerCount("readable") > 0;
        }
        return ret;
      }
      removeListener(ev, ...args2) {
        return this.off(ev, ...args2);
      }
      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 util5.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((resolve42, 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 {
              resolve42(null);
            }
          }).on("error", noop11).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 util5.isDisturbed(self2) || isLocked(self2);
    }
    __name(isUnusable, "isUnusable");
    async function consume(stream5, type) {
      assert4(!stream5[kConsume]);
      return new Promise((resolve42, reject) => {
        if (isUnusable(stream5)) {
          const rState = stream5._readableState;
          if (rState.destroyed && rState.closeEmitted === false) {
            stream5.on("error", (err2) => {
              reject(err2);
            }).on("close", () => {
              reject(new TypeError("unusable"));
            });
          } else {
            reject(rState.errored ?? new TypeError("unusable"));
          }
        } else {
          queueMicrotask(() => {
            stream5[kConsume] = {
              type,
              stream: stream5,
              resolve: resolve42,
              reject,
              length: 0,
              body: []
            };
            stream5.on("error", function(err2) {
              consumeFinish(this[kConsume], err2);
            }).on("close", function() {
              if (this[kConsume].body !== null) {
                consumeFinish(this[kConsume], new RequestAbortedError());
              }
            });
            consumeStart(stream5[kConsume]);
          });
        }
      });
    }
    __name(consume, "consume");
    function consumeStart(consume2) {
      if (consume2.body === null) {
        return;
      }
      const { _readableState: state } = consume2.stream;
      if (state.bufferIndex) {
        const start2 = state.bufferIndex;
        const end = state.buffer.length;
        for (let n3 = start2; 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 start2 = bufferLength > 2 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191 ? 3 : 0;
      return buffer.utf8Slice(start2, 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 i4 = 0; i4 < chunks.length; ++i4) {
        const chunk = chunks[i4];
        buffer.set(chunk, offset);
        offset += chunk.length;
      }
      return buffer;
    }
    __name(chunksConcat, "chunksConcat");
    function consumeEnd(consume2) {
      const { type, body: body2, resolve: resolve42, stream: stream5, length } = consume2;
      try {
        if (type === "text") {
          resolve42(chunksDecode(body2, length));
        } else if (type === "json") {
          resolve42(JSON.parse(chunksDecode(body2, length)));
        } else if (type === "arrayBuffer") {
          resolve42(chunksConcat(body2, length).buffer);
        } else if (type === "blob") {
          resolve42(new Blob(body2, { type: stream5[kContentType] }));
        } else if (type === "bytes") {
          resolve42(chunksConcat(body2, length));
        }
        consumeFinish(consume2);
      } catch (err2) {
        stream5.destroy(err2);
      }
    }
    __name(consumeEnd, "consumeEnd");
    function consumePush(consume2, chunk) {
      consume2.length += chunk.length;
      consume2.body.push(chunk);
    }
    __name(consumePush, "consumePush");
    function consumeFinish(consume2, err2) {
      if (consume2.body === null) {
        return;
      }
      if (err2) {
        consume2.reject(err2);
      } 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_errors6();
    var { chunksDecode } = require_readable2();
    var CHUNK_LIMIT2 = 128 * 1024;
    async function getResolveErrorBodyCallback({ callback, body: body2, contentType, statusCode, statusMessage, headers }) {
      assert4(body2);
      let chunks = [];
      let length = 0;
      try {
        for await (const chunk of body2) {
          chunks.push(chunk);
          length += chunk.length;
          if (length > CHUNK_LIMIT2) {
            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: Readable8 } = require_readable2();
    var { InvalidArgumentError, RequestAbortedError } = require_errors6();
    var util5 = 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: body2, 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 (err2) {
          if (util5.isStream(body2)) {
            util5.destroy(body2.on("error", util5.nop), err2);
          }
          throw err2;
        }
        this.method = method;
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.callback = callback;
        this.res = null;
        this.abort = null;
        this.body = body2;
        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 (util5.isStream(body2)) {
          body2.on("error", (err2) => {
            this.onError(err2);
          });
        }
        if (this.signal) {
          if (this.signal.aborted) {
            this.reason = this.signal.reason ?? new RequestAbortedError();
          } else {
            this.removeAbortListener = util5.addAbortListener(this.signal, () => {
              this.reason = this.signal.reason ?? new RequestAbortedError();
              if (this.res) {
                util5.destroy(this.res.on("error", util5.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(abort2, context2) {
        if (this.reason) {
          abort2(this.reason);
          return;
        }
        assert4(this.callback);
        this.abort = abort2;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const { callback, opaque, abort: abort2, context: context2, responseHeaders, highWaterMark } = this;
        const headers = responseHeaders === "raw" ? util5.parseRawHeaders(rawHeaders) : util5.parseHeaders(rawHeaders);
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        const parsedHeaders = responseHeaders === "raw" ? util5.parseHeaders(rawHeaders) : headers;
        const contentType = parsedHeaders["content-type"];
        const contentLength = parsedHeaders["content-length"];
        const res = new Readable8({
          resume,
          abort: abort2,
          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) {
        util5.parseHeaders(trailers, this.trailers);
        this.res.push(null);
      }
      onError(err2) {
        const { res, callback, body: body2, opaque } = this;
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err2, { opaque });
          });
        }
        if (res) {
          this.res = null;
          queueMicrotask(() => {
            util5.destroy(res, err2);
          });
        }
        if (body2) {
          this.body = null;
          util5.destroy(body2, err2);
        }
        if (this.removeAbortListener) {
          res?.off("close", this.removeAbortListener);
          this.removeAbortListener();
          this.removeAbortListener = null;
        }
      }
    };
    function request4(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve42, reject) => {
          request4.call(this, opts, (err2, data) => {
            return err2 ? reject(err2) : resolve42(data);
          });
        });
      }
      try {
        this.dispatch(opts, new RequestHandler(opts, callback));
      } catch (err2) {
        if (typeof callback !== "function") {
          throw err2;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err2, { 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_errors6();
    var kListener = Symbol("kListener");
    var kSignal = Symbol("kSignal");
    function abort2(self2) {
      if (self2.abort) {
        self2.abort(self2[kSignal]?.reason);
      } else {
        self2.reason = self2[kSignal]?.reason ?? new RequestAbortedError();
      }
      removeSignal(self2);
    }
    __name(abort2, "abort");
    function addSignal(self2, signal) {
      self2.reason = null;
      self2[kSignal] = null;
      self2[kListener] = null;
      if (!signal) {
        return;
      }
      if (signal.aborted) {
        abort2(self2);
        return;
      }
      self2[kSignal] = signal;
      self2[kListener] = () => {
        abort2(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_errors6();
    var util5 = 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, factory2, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        const { signal, method, opaque, body: body2, onInfo, responseHeaders, throwOnError } = opts;
        try {
          if (typeof callback !== "function") {
            throw new InvalidArgumentError("invalid callback");
          }
          if (typeof factory2 !== "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 (err2) {
          if (util5.isStream(body2)) {
            util5.destroy(body2.on("error", util5.nop), err2);
          }
          throw err2;
        }
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.factory = factory2;
        this.callback = callback;
        this.res = null;
        this.abort = null;
        this.context = null;
        this.trailers = null;
        this.body = body2;
        this.onInfo = onInfo || null;
        this.throwOnError = throwOnError || false;
        if (util5.isStream(body2)) {
          body2.on("error", (err2) => {
            this.onError(err2);
          });
        }
        addSignal(this, signal);
      }
      onConnect(abort2, context2) {
        if (this.reason) {
          abort2(this.reason);
          return;
        }
        assert4(this.callback);
        this.abort = abort2;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume, statusMessage) {
        const { factory: factory2, opaque, context: context2, callback, responseHeaders } = this;
        const headers = responseHeaders === "raw" ? util5.parseRawHeaders(rawHeaders) : util5.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" ? util5.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 (factory2 === null) {
            return;
          }
          res = this.runInAsyncScope(factory2, 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 }, (err2) => {
            const { callback: callback2, res: res2, opaque: opaque2, trailers, abort: abort2 } = this;
            this.res = null;
            if (err2 || !res2.readable) {
              util5.destroy(res2, err2);
            }
            this.callback = null;
            this.runInAsyncScope(callback2, null, err2 || null, { opaque: opaque2, trailers });
            if (err2) {
              abort2();
            }
          });
        }
        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 = util5.parseHeaders(trailers);
        res.end();
      }
      onError(err2) {
        const { res, callback, opaque, body: body2 } = this;
        removeSignal(this);
        this.factory = null;
        if (res) {
          this.res = null;
          util5.destroy(res, err2);
        } else if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err2, { opaque });
          });
        }
        if (body2) {
          this.body = null;
          util5.destroy(body2, err2);
        }
      }
    };
    function stream5(opts, factory2, callback) {
      if (callback === void 0) {
        return new Promise((resolve42, reject) => {
          stream5.call(this, opts, factory2, (err2, data) => {
            return err2 ? reject(err2) : resolve42(data);
          });
        });
      }
      try {
        this.dispatch(opts, new StreamHandler(opts, factory2, callback));
      } catch (err2) {
        if (typeof callback !== "function") {
          throw err2;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err2, { opaque }));
      }
    }
    __name(stream5, "stream");
    module2.exports = stream5;
  }
});

// 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: Readable8,
      Duplex,
      PassThrough: PassThrough8
    } = __require("node:stream");
    var {
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError
    } = require_errors6();
    var util5 = 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 Readable8 {
      static {
        __name(this, "PipelineRequest");
      }
      constructor() {
        super({ autoDestroy: true });
        this[kResume] = null;
      }
      _read() {
        const { [kResume]: resume } = this;
        if (resume) {
          this[kResume] = null;
          resume();
        }
      }
      _destroy(err2, callback) {
        this._read();
        callback(err2);
      }
    };
    var PipelineResponse = class extends Readable8 {
      static {
        __name(this, "PipelineResponse");
      }
      constructor(resume) {
        super({ autoDestroy: true });
        this[kResume] = resume;
      }
      _read() {
        this[kResume]();
      }
      _destroy(err2, callback) {
        if (!err2 && !this._readableState.endEmitted) {
          err2 = new RequestAbortedError();
        }
        callback(err2);
      }
    };
    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", util5.nop);
        this.ret = new Duplex({
          readableObjectMode: opts.objectMode,
          autoDestroy: true,
          read: /* @__PURE__ */ __name(() => {
            const { body: body2 } = this;
            if (body2?.resume) {
              body2.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((err2, callback) => {
            const { body: body2, req, res, ret, abort: abort2 } = this;
            if (!err2 && !ret._readableState.endEmitted) {
              err2 = new RequestAbortedError();
            }
            if (abort2 && err2) {
              abort2();
            }
            util5.destroy(body2, err2);
            util5.destroy(req, err2);
            util5.destroy(res, err2);
            removeSignal(this);
            callback(err2);
          }, "destroy")
        }).on("prefinish", () => {
          const { req } = this;
          req.push(null);
        });
        this.res = null;
        addSignal(this, signal);
      }
      onConnect(abort2, context2) {
        const { ret, res } = this;
        if (this.reason) {
          abort2(this.reason);
          return;
        }
        assert4(!res, "pipeline cannot be retried");
        assert4(!ret.destroyed);
        this.abort = abort2;
        this.context = context2;
      }
      onHeaders(statusCode, rawHeaders, resume) {
        const { opaque, handler, context: context2 } = this;
        if (statusCode < 200) {
          if (this.onInfo) {
            const headers = this.responseHeaders === "raw" ? util5.parseRawHeaders(rawHeaders) : util5.parseHeaders(rawHeaders);
            this.onInfo({ statusCode, headers });
          }
          return;
        }
        this.res = new PipelineResponse(resume);
        let body2;
        try {
          this.handler = null;
          const headers = this.responseHeaders === "raw" ? util5.parseRawHeaders(rawHeaders) : util5.parseHeaders(rawHeaders);
          body2 = this.runInAsyncScope(handler, null, {
            statusCode,
            headers,
            opaque,
            body: this.res,
            context: context2
          });
        } catch (err2) {
          this.res.on("error", util5.nop);
          throw err2;
        }
        if (!body2 || typeof body2.on !== "function") {
          throw new InvalidReturnValueError("expected Readable");
        }
        body2.on("data", (chunk) => {
          const { ret, body: body3 } = this;
          if (!ret.push(chunk) && body3.pause) {
            body3.pause();
          }
        }).on("error", (err2) => {
          const { ret } = this;
          util5.destroy(ret, err2);
        }).on("end", () => {
          const { ret } = this;
          ret.push(null);
        }).on("close", () => {
          const { ret } = this;
          if (!ret._readableState.ended) {
            util5.destroy(ret, new RequestAbortedError());
          }
        });
        this.body = body2;
      }
      onData(chunk) {
        const { res } = this;
        return res.push(chunk);
      }
      onComplete(trailers) {
        const { res } = this;
        res.push(null);
      }
      onError(err2) {
        const { ret } = this;
        this.handler = null;
        util5.destroy(ret, err2);
      }
    };
    function pipeline3(opts, handler) {
      try {
        const pipelineHandler = new PipelineHandler(opts, handler);
        this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
        return pipelineHandler.ret;
      } catch (err2) {
        return new PassThrough8().destroy(err2);
      }
    }
    __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_errors6();
    var { AsyncResource } = __require("node:async_hooks");
    var util5 = 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(abort2, context2) {
        if (this.reason) {
          abort2(this.reason);
          return;
        }
        assert4(this.callback);
        this.abort = abort2;
        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" ? util5.parseRawHeaders(rawHeaders) : util5.parseHeaders(rawHeaders);
        this.runInAsyncScope(callback, null, null, {
          headers,
          socket,
          opaque,
          context: context2
        });
      }
      onError(err2) {
        const { callback, opaque } = this;
        removeSignal(this);
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err2, { opaque });
          });
        }
      }
    };
    function upgrade(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve42, reject) => {
          upgrade.call(this, opts, (err2, data) => {
            return err2 ? reject(err2) : resolve42(data);
          });
        });
      }
      try {
        const upgradeHandler = new UpgradeHandler(opts, callback);
        this.dispatch({
          ...opts,
          method: opts.method || "GET",
          upgrade: opts.protocol || "Websocket"
        }, upgradeHandler);
      } catch (err2) {
        if (typeof callback !== "function") {
          throw err2;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err2, { 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_errors6();
    var util5 = 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(abort2, context2) {
        if (this.reason) {
          abort2(this.reason);
          return;
        }
        assert4(this.callback);
        this.abort = abort2;
        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" ? util5.parseRawHeaders(rawHeaders) : util5.parseHeaders(rawHeaders);
        }
        this.runInAsyncScope(callback, null, null, {
          statusCode,
          headers,
          socket,
          opaque,
          context: context2
        });
      }
      onError(err2) {
        const { callback, opaque } = this;
        removeSignal(this);
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err2, { opaque });
          });
        }
      }
    };
    function connect(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve42, reject) => {
          connect.call(this, opts, (err2, data) => {
            return err2 ? reject(err2) : resolve42(data);
          });
        });
      }
      try {
        const connectHandler = new ConnectHandler(opts, callback);
        this.dispatch({ ...opts, method: "CONNECT" }, connectHandler);
      } catch (err2) {
        if (typeof callback !== "function") {
          throw err2;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err2, { 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_errors6();
    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](instance2) {
        return instance2 && instance2[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: buildURL2 } = 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 i4 = 0; i4 < headers.length; i4 += 2) {
          if (headers[i4].toLocaleLowerCase() === key.toLocaleLowerCase()) {
            return headers[i4 + 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, matchHeaderValue2] of Object.entries(mockDispatch2.headers)) {
        const headerValue = getHeaderByName(headers, matchHeaderName);
        if (!matchValue(matchHeaderValue2, headerValue)) {
          return false;
        }
      }
      return true;
    }
    __name(matchHeaders, "matchHeaders");
    function safeUrl(path150) {
      if (typeof path150 !== "string") {
        return path150;
      }
      const pathSegments = path150.split("?");
      if (pathSegments.length !== 2) {
        return path150;
      }
      const qp = new URLSearchParams(pathSegments.pop());
      qp.sort();
      return [...pathSegments, qp.toString()].join("?");
    }
    __name(safeUrl, "safeUrl");
    function matchKey(mockDispatch2, { path: path150, method, body: body2, headers }) {
      const pathMatch = matchValue(mockDispatch2.path, path150);
      const methodMatch = matchValue(mockDispatch2.method, method);
      const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body2) : 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 ? buildURL2(key.path, key.query) : key.path;
      const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
      let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path150 }) => matchValue(safeUrl(path150), 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: body2 }) => typeof body2 !== "undefined" ? matchValue(body2, 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: path150, method, body: body2, headers, query } = opts;
      return {
        path: path150,
        method,
        body: body2,
        headers,
        query
      };
    }
    __name(buildKey, "buildKey");
    function generateKeyValues(data) {
      const keys = Object.keys(data);
      const result = [];
      for (let i4 = 0; i4 < keys.length; ++i4) {
        const key = keys[i4];
        const value = data[key];
        const name4 = Buffer.from(`${key}`);
        if (Array.isArray(value)) {
          for (let j2 = 0; j2 < value.length; ++j2) {
            result.push(name4, Buffer.from(`${value[j2]}`));
          }
        } else {
          result.push(name4, Buffer.from(`${value}`));
        }
      }
      return result;
    }
    __name(generateKeyValues, "generateKeyValues");
    function getStatusText2(statusCode) {
      return STATUS_CODES[statusCode] || "unknown";
    }
    __name(getStatusText2, "getStatusText");
    async function getResponse(body2) {
      const buffers = [];
      for await (const data of body2) {
        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: error40 }, delay: delay5, persist } = mockDispatch2;
      const { timesInvoked, times } = mockDispatch2;
      mockDispatch2.consumed = !persist && timesInvoked >= times;
      mockDispatch2.pending = timesInvoked < times;
      if (error40 !== null) {
        deleteMockDispatch(this[kDispatches], key);
        handler.onError(error40);
        return true;
      }
      if (typeof delay5 === "number" && delay5 > 0) {
        setTimeout(() => {
          handleReply(this[kDispatches]);
        }, delay5);
      } else {
        handleReply(this[kDispatches]);
      }
      function handleReply(mockDispatches, _data = data) {
        const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
        const body2 = typeof _data === "function" ? _data({ ...opts, headers: optsHeaders }) : _data;
        if (isPromise2(body2)) {
          body2.then((newData) => handleReply(mockDispatches, newData));
          return;
        }
        const responseData = getResponseData(body2);
        const responseHeaders = generateKeyValues(headers);
        const responseTrailers = generateKeyValues(trailers);
        handler.onConnect?.((err2) => handler.onError(err2), 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 origin2 = this[kOrigin];
      const originalDispatch = this[kOriginalDispatch];
      return /* @__PURE__ */ __name(function dispatch(opts, handler) {
        if (agent.isMockActive) {
          try {
            mockDispatch.call(this, opts, handler);
          } catch (error40) {
            if (error40 instanceof MockNotMatchedError) {
              const netConnect = agent[kGetNetConnect]();
              if (netConnect === false) {
                throw new MockNotMatchedError(`${error40.message}: subsequent request to origin ${origin2} was not allowed (net.connect disabled)`);
              }
              if (checkNetConnect(netConnect, origin2)) {
                originalDispatch.call(this, opts, handler);
              } else {
                throw new MockNotMatchedError(`${error40.message}: subsequent request to origin ${origin2} was not allowed (net.connect is not enabled for this origin)`);
              }
            } else {
              throw error40;
            }
          }
        } else {
          originalDispatch.call(this, opts, handler);
        }
      }, "dispatch");
    }
    __name(buildMockDispatch, "buildMockDispatch");
    function checkNetConnect(netConnect, origin2) {
      const url3 = new URL(origin2);
      if (netConnect === true) {
        return true;
      } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url3.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_errors6();
    var { buildURL: buildURL2 } = 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 = buildURL2(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(error40) {
        if (typeof error40 === "undefined") {
          throw new InvalidArgumentError("error must be defined");
        }
        const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error: error40 });
        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_errors6();
    var MockClient = class extends Client3 {
      static {
        __name(this, "MockClient");
      }
      constructor(origin2, opts) {
        super(origin2, 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] = origin2;
        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_errors6();
    var MockPool = class extends Pool {
      static {
        __name(this, "MockPool");
      }
      constructor(origin2, opts) {
        super(origin2, 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] = origin2;
        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: path150, data: { statusCode }, persist, times, timesInvoked, origin: origin2 }) => ({
            Method: method,
            Origin: origin2,
            Path: path150,
            "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_errors6();
    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(origin2) {
        let dispatcher = this[kMockAgentGet](origin2);
        if (!dispatcher) {
          dispatcher = this[kFactory](origin2);
          this[kMockAgentSet](origin2, 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](origin2, dispatcher) {
        this[kClients].set(origin2, dispatcher);
      }
      [kFactory](origin2) {
        const mockOptions = Object.assign({ agent: this }, this[kOptions]);
        return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin2, mockOptions) : new MockPool(origin2, mockOptions);
      }
      [kMockAgentGet](origin2) {
        const client = this[kClients].get(origin2);
        if (client) {
          return client;
        }
        if (typeof origin2 !== "string") {
          const dispatcher = this[kFactory]("http://localhost:9999");
          this[kMockAgentSet](origin2, dispatcher);
          return dispatcher;
        }
        for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) {
          if (nonExplicitDispatcher && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin2)) {
            const dispatcher = this[kFactory](origin2);
            this[kMockAgentSet](origin2, dispatcher);
            dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches];
            return dispatcher;
          }
        }
      }
      [kGetNetConnect]() {
        return this[kNetConnect];
      }
      pendingInterceptors() {
        const mockAgentClients = this[kClients];
        return Array.from(mockAgentClients.entries()).flatMap(([origin2, scope]) => scope[kDispatches].map((dispatch) => ({ ...dispatch, origin: origin2 }))).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_errors6();
    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(...args2) {
        return this.#handler.onConnect?.(...args2);
      }
      onError(...args2) {
        return this.#handler.onError?.(...args2);
      }
      onUpgrade(...args2) {
        return this.#handler.onUpgrade?.(...args2);
      }
      onResponseStarted(...args2) {
        return this.#handler.onResponseStarted?.(...args2);
      }
      onHeaders(...args2) {
        return this.#handler.onHeaders?.(...args2);
      }
      onData(...args2) {
        return this.#handler.onData?.(...args2);
      }
      onComplete(...args2) {
        return this.#handler.onComplete?.(...args2);
      }
      onBodySent(...args2) {
        return this.#handler.onBodySent?.(...args2);
      }
    };
  }
});

// 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 util5 = require_util22();
    var { InvalidArgumentError, RequestAbortedError } = require_errors6();
    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(abort2) {
        this.#abort = abort2;
        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 = util5.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(err2) {
        if (this.#dumped) {
          return;
        }
        err2 = this.#reason ?? err2;
        this.#handler.onError(err2);
      }
      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: isIP4 } = __require("node:net");
    var { lookup: lookup2 } = __require("node:dns");
    var DecoratorHandler = require_decorator_handler2();
    var { InvalidArgumentError, InformationalError } = require_errors6();
    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(origin2, opts, cb) {
        const ips = this.#records.get(origin2.hostname);
        if (ips == null && this.full) {
          cb(null, origin2.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(origin2, newOpts, (err2, addresses) => {
            if (err2 || addresses == null || addresses.length === 0) {
              cb(err2 ?? new InformationalError("No DNS entries found"));
              return;
            }
            this.setRecords(origin2, addresses);
            const records = this.#records.get(origin2.hostname);
            const ip = this.pick(
              origin2,
              records,
              newOpts.affinity
            );
            let port;
            if (typeof ip.port === "number") {
              port = `:${ip.port}`;
            } else if (origin2.port !== "") {
              port = `:${origin2.port}`;
            } else {
              port = "";
            }
            cb(
              null,
              `${origin2.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`
            );
          });
        } else {
          const ip = this.pick(
            origin2,
            ips,
            newOpts.affinity
          );
          if (ip == null) {
            this.#records.delete(origin2.hostname);
            this.runLookup(origin2, opts, cb);
            return;
          }
          let port;
          if (typeof ip.port === "number") {
            port = `:${ip.port}`;
          } else if (origin2.port !== "") {
            port = `:${origin2.port}`;
          } else {
            port = "";
          }
          cb(
            null,
            `${origin2.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`
          );
        }
      }
      #defaultLookup(origin2, opts, cb) {
        lookup2(
          origin2.hostname,
          {
            all: true,
            family: this.dualStack === false ? this.affinity : 0,
            order: "ipv4first"
          },
          (err2, addresses) => {
            if (err2) {
              return cb(err2);
            }
            const results = /* @__PURE__ */ new Map();
            for (const addr2 of addresses) {
              results.set(`${addr2.address}:${addr2.family}`, addr2);
            }
            cb(null, results.values());
          }
        );
      }
      #defaultPick(origin2, 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(origin2, hostnameRecords, affinity);
        }
        return ip;
      }
      setRecords(origin2, 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(origin2.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: origin2, handler, dispatch }, opts) {
        super(handler);
        this.#origin = origin2;
        this.#handler = handler;
        this.#opts = { ...opts };
        this.#state = state;
        this.#dispatch = dispatch;
      }
      onError(err2) {
        switch (err2.code) {
          case "ETIMEDOUT":
          case "ECONNREFUSED": {
            if (this.#state.dualStack) {
              this.#state.runLookup(this.#origin, this.#opts, (err3, newOrigin) => {
                if (err3) {
                  return this.#handler.onError(err3);
                }
                const dispatchOpts = {
                  ...this.#opts,
                  origin: newOrigin
                };
                this.#dispatch(dispatchOpts, this);
              });
              return;
            }
            this.#handler.onError(err2);
            return;
          }
          case "ENOTFOUND":
            this.#state.deleteRecord(this.#origin);
          // eslint-disable-next-line no-fallthrough
          default:
            this.#handler.onError(err2);
            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 instance2 = new DNSInstance(opts);
      return (dispatch) => {
        return /* @__PURE__ */ __name(function dnsInterceptor(origDispatchOpts, handler) {
          const origin2 = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
          if (isIP4(origin2.hostname) !== 0) {
            return dispatch(origDispatchOpts, handler);
          }
          instance2.runLookup(origin2, origDispatchOpts, (err2, newOrigin) => {
            if (err2) {
              return handler.onError(err2);
            }
            let dispatchOpts = null;
            dispatchOpts = {
              ...origDispatchOpts,
              servername: origin2.hostname,
              // For SNI on TLS
              origin: newOrigin,
              headers: {
                host: origin2.hostname,
                ...origDispatchOpts.headers
              }
            };
            dispatch(
              dispatchOpts,
              instance2.getHandler({ origin: origin2, 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: isValidHeaderName2,
      isValidHeaderValue
    } = require_util23();
    var { webidl } = require_webidl2();
    var assert4 = __require("node:assert");
    var util5 = __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 i4 = 0;
      let j2 = potentialValue.length;
      while (j2 > i4 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j2 - 1))) --j2;
      while (j2 > i4 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i4))) ++i4;
      return i4 === 0 && j2 === potentialValue.length ? potentialValue : potentialValue.substring(i4, j2);
    }
    __name(headerValueNormalize, "headerValueNormalize");
    function fill(headers, object3) {
      if (Array.isArray(object3)) {
        for (let i4 = 0; i4 < object3.length; ++i4) {
          const header = object3[i4];
          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 i4 = 0; i4 < keys.length; ++i4) {
          appendHeader(headers, keys[i4], object3[keys[i4]]);
        }
      } else {
        throw webidl.errors.conversionFailed({
          prefix: "Headers constructor",
          argument: "Argument 1",
          types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
        });
      }
    }
    __name(fill, "fill");
    function appendHeader(headers, name4, value) {
      value = headerValueNormalize(value);
      if (!isValidHeaderName2(name4)) {
        throw webidl.errors.invalidArgument({
          prefix: "Headers.append",
          value: name4,
          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(name4, 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(init2) {
        if (init2 instanceof _HeadersList) {
          this[kHeadersMap] = new Map(init2[kHeadersMap]);
          this[kHeadersSortedMap] = init2[kHeadersSortedMap];
          this.cookies = init2.cookies === null ? null : [...init2.cookies];
        } else {
          this[kHeadersMap] = new Map(init2);
          this[kHeadersSortedMap] = null;
        }
      }
      /**
       * @see https://fetch.spec.whatwg.org/#header-list-contains
       * @param {string} name
       * @param {boolean} isLowerCase
       */
      contains(name4, isLowerCase) {
        return this[kHeadersMap].has(isLowerCase ? name4 : name4.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(name4, value, isLowerCase) {
        this[kHeadersSortedMap] = null;
        const lowercaseName = isLowerCase ? name4 : name4.toLowerCase();
        const exists3 = this[kHeadersMap].get(lowercaseName);
        if (exists3) {
          const delimiter2 = lowercaseName === "cookie" ? "; " : ", ";
          this[kHeadersMap].set(lowercaseName, {
            name: exists3.name,
            value: `${exists3.value}${delimiter2}${value}`
          });
        } else {
          this[kHeadersMap].set(lowercaseName, { name: name4, 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(name4, value, isLowerCase) {
        this[kHeadersSortedMap] = null;
        const lowercaseName = isLowerCase ? name4 : name4.toLowerCase();
        if (lowercaseName === "set-cookie") {
          this.cookies = [value];
        }
        this[kHeadersMap].set(lowercaseName, { name: name4, value });
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-delete
       * @param {string} name
       * @param {boolean} isLowerCase
       */
      delete(name4, isLowerCase) {
        this[kHeadersSortedMap] = null;
        if (!isLowerCase) name4 = name4.toLowerCase();
        if (name4 === "set-cookie") {
          this.cookies = null;
        }
        this[kHeadersMap].delete(name4);
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-get
       * @param {string} name
       * @param {boolean} isLowerCase
       * @returns {string | null}
       */
      get(name4, isLowerCase) {
        return this[kHeadersMap].get(isLowerCase ? name4 : name4.toLowerCase())?.value ?? null;
      }
      *[Symbol.iterator]() {
        for (const { 0: name4, 1: { value } } of this[kHeadersMap]) {
          yield [name4, value];
        }
      }
      get entries() {
        const headers = {};
        if (this[kHeadersMap].size !== 0) {
          for (const { name: name4, value } of this[kHeadersMap].values()) {
            headers[name4] = value;
          }
        }
        return headers;
      }
      rawValues() {
        return this[kHeadersMap].values();
      }
      get entriesList() {
        const headers = [];
        if (this[kHeadersMap].size !== 0) {
          for (const { 0: lowerName, 1: { name: name4, value } } of this[kHeadersMap]) {
            if (lowerName === "set-cookie") {
              for (const cookie of this.cookies) {
                headers.push([name4, cookie]);
              }
            } else {
              headers.push([name4, 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 iterator2 = this[kHeadersMap][Symbol.iterator]();
          const firstValue = iterator2.next().value;
          array2[0] = [firstValue[0], firstValue[1].value];
          assert4(firstValue[1].value !== null);
          for (let i4 = 1, j2 = 0, right3 = 0, left3 = 0, pivot = 0, x3, value; i4 < size; ++i4) {
            value = iterator2.next().value;
            x3 = array2[i4] = [value[0], value[1].value];
            assert4(x3[1] !== null);
            left3 = 0;
            right3 = i4;
            while (left3 < right3) {
              pivot = left3 + (right3 - left3 >> 1);
              if (array2[pivot][0] <= x3[0]) {
                left3 = pivot + 1;
              } else {
                right3 = pivot;
              }
            }
            if (i4 !== pivot) {
              j2 = i4;
              while (j2 > left3) {
                array2[j2] = array2[--j2];
              }
              array2[left3] = x3;
            }
          }
          if (!iterator2.next().done) {
            throw new TypeError("Unreachable");
          }
          return array2;
        } else {
          let i4 = 0;
          for (const { 0: name4, 1: { value } } of this[kHeadersMap]) {
            array2[i4++] = [name4, value];
            assert4(value !== null);
          }
          return array2.sort(compareHeaderName);
        }
      }
    };
    var Headers6 = class _Headers {
      static {
        __name(this, "Headers");
      }
      #guard;
      #headersList;
      constructor(init2 = void 0) {
        webidl.util.markAsUncloneable(this);
        if (init2 === kConstruct) {
          return;
        }
        this.#headersList = new HeadersList();
        this.#guard = "none";
        if (init2 !== void 0) {
          init2 = webidl.converters.HeadersInit(init2, "Headers contructor", "init");
          fill(this, init2);
        }
      }
      // https://fetch.spec.whatwg.org/#dom-headers-append
      append(name4, value) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 2, "Headers.append");
        const prefix = "Headers.append";
        name4 = webidl.converters.ByteString(name4, prefix, "name");
        value = webidl.converters.ByteString(value, prefix, "value");
        return appendHeader(this, name4, value);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-delete
      delete(name4) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.delete");
        const prefix = "Headers.delete";
        name4 = webidl.converters.ByteString(name4, prefix, "name");
        if (!isValidHeaderName2(name4)) {
          throw webidl.errors.invalidArgument({
            prefix: "Headers.delete",
            value: name4,
            type: "header name"
          });
        }
        if (this.#guard === "immutable") {
          throw new TypeError("immutable");
        }
        if (!this.#headersList.contains(name4, false)) {
          return;
        }
        this.#headersList.delete(name4, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-get
      get(name4) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.get");
        const prefix = "Headers.get";
        name4 = webidl.converters.ByteString(name4, prefix, "name");
        if (!isValidHeaderName2(name4)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name4,
            type: "header name"
          });
        }
        return this.#headersList.get(name4, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-has
      has(name4) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.has");
        const prefix = "Headers.has";
        name4 = webidl.converters.ByteString(name4, prefix, "name");
        if (!isValidHeaderName2(name4)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name4,
            type: "header name"
          });
        }
        return this.#headersList.contains(name4, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-set
      set(name4, value) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 2, "Headers.set");
        const prefix = "Headers.set";
        name4 = webidl.converters.ByteString(name4, prefix, "name");
        value = webidl.converters.ByteString(value, prefix, "value");
        value = headerValueNormalize(value);
        if (!isValidHeaderName2(name4)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name4,
            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(name4, 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 i4 = 0; i4 < names.length; ++i4) {
          const { 0: name4, 1: value } = names[i4];
          if (name4 === "set-cookie") {
            for (let j2 = 0; j2 < cookies.length; ++j2) {
              headers.push([name4, cookies[j2]]);
            }
          } else {
            headers.push([name4, value]);
          }
        }
        return this.#headersList[kHeadersSortedMap] = headers;
      }
      [util5.inspect.custom](depth, options2) {
        options2.depth ??= depth;
        return `Headers ${util5.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
      },
      [util5.inspect.custom]: {
        enumerable: false
      }
    });
    webidl.converters.HeadersInit = function(V3, prefix, argument) {
      if (webidl.util.Type(V3) === "Object") {
        const iterator2 = Reflect.get(V3, Symbol.iterator);
        if (!util5.types.isProxy(V3) && iterator2 === Headers6.prototype.entries) {
          try {
            return getHeadersList(V3).entriesList;
          } catch {
          }
        }
        if (typeof iterator2 === "function") {
          return webidl.converters["sequence<sequence<ByteString>>"](V3, prefix, argument, iterator2.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 util5 = require_util22();
    var nodeUtil = __require("node:util");
    var { kEnumerableProperty } = util5;
    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: FormData7 } = require_formdata2();
    var { URLSerializer } = require_data_url2();
    var { kConstruct } = require_symbols6();
    var assert4 = __require("node:assert");
    var { types: types7 } = __require("node:util");
    var textEncoder2 = 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, init2 = {}) {
        webidl.argumentLengthCheck(arguments, 1, "Response.json");
        if (init2 !== null) {
          init2 = webidl.converters.ResponseInit(init2);
        }
        const bytes = textEncoder2.encode(
          serializeJavascriptValueToJSONString(data)
        );
        const body2 = extractBody(bytes);
        const responseObject = fromInnerResponse(makeResponse({}), "response");
        initializeResponse(responseObject, init2, { body: body2[0], type: "application/json" });
        return responseObject;
      }
      // Creates a redirect Response that redirects to url with status status.
      static redirect(url3, status = 302) {
        webidl.argumentLengthCheck(arguments, 1, "Response.redirect");
        url3 = webidl.converters.USVString(url3);
        status = webidl.converters["unsigned short"](status);
        let parsedURL;
        try {
          parsedURL = new URL(url3, relevantRealm.settingsObject.baseUrl);
        } catch (err2) {
          throw new TypeError(`Failed to parse URL from ${url3}`, { cause: err2 });
        }
        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(body2 = null, init2 = {}) {
        webidl.util.markAsUncloneable(this);
        if (body2 === kConstruct) {
          return;
        }
        if (body2 !== null) {
          body2 = webidl.converters.BodyInit(body2);
        }
        init2 = webidl.converters.ResponseInit(init2);
        this[kState] = makeResponse({});
        this[kHeaders] = new Headers6(kConstruct);
        setHeadersGuard(this[kHeaders], "response");
        setHeadersList(this[kHeaders], this[kState].headersList);
        let bodyWithType = null;
        if (body2 != null) {
          const [extractedBody, type] = extractBody(body2);
          bodyWithType = { body: extractedBody, type };
        }
        initializeResponse(this, init2, 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 url3 = urlList[urlList.length - 1] ?? null;
        if (url3 === null) {
          return "";
        }
        return URLSerializer(url3, 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 && util5.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(init2) {
      return {
        aborted: false,
        rangeRequested: false,
        timingAllowPassed: false,
        requestIncludesCredentials: false,
        type: "default",
        status: 200,
        timingInfo: null,
        cacheState: "",
        statusText: "",
        ...init2,
        headersList: init2?.headersList ? new HeadersList(init2?.headersList) : new HeadersList(),
        urlList: init2?.urlList ? [...init2.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, err2 = null) {
      assert4(isCancelled(fetchParams));
      return isAborted2(fetchParams) ? makeNetworkError(Object.assign(new DOMException("The operation was aborted.", "AbortError"), { cause: err2 })) : makeNetworkError(Object.assign(new DOMException("Request was cancelled."), { cause: err2 }));
    }
    __name(makeAppropriateNetworkError, "makeAppropriateNetworkError");
    function initializeResponse(response, init2, body2) {
      if (init2.status !== null && (init2.status < 200 || init2.status > 599)) {
        throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');
      }
      if ("statusText" in init2 && init2.statusText != null) {
        if (!isValidReasonPhrase(String(init2.statusText))) {
          throw new TypeError("Invalid statusText");
        }
      }
      if ("status" in init2 && init2.status != null) {
        response[kState].status = init2.status;
      }
      if ("statusText" in init2 && init2.statusText != null) {
        response[kState].statusText = init2.statusText;
      }
      if ("headers" in init2 && init2.headers != null) {
        fill(response[kHeaders], init2.headers);
      }
      if (body2) {
        if (nullBodyStatus.includes(response.status)) {
          throw webidl.errors.exception({
            header: "Response constructor",
            message: `Invalid response status code ${response.status}`
          });
        }
        response[kState].body = body2.body;
        if (body2.type != null && !response[kState].headersList.contains("content-type", true)) {
          response[kState].headersList.append("content-type", body2.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(
      FormData7
    );
    webidl.converters.URLSearchParams = webidl.interfaceConverter(
      URLSearchParams
    );
    webidl.converters.XMLHttpRequestBodyInit = function(V3, prefix, name4) {
      if (typeof V3 === "string") {
        return webidl.converters.USVString(V3, prefix, name4);
      }
      if (isBlobLike3(V3)) {
        return webidl.converters.Blob(V3, prefix, name4, { strict: false });
      }
      if (ArrayBuffer.isView(V3) || types7.isArrayBuffer(V3)) {
        return webidl.converters.BufferSource(V3, prefix, name4);
      }
      if (util5.isFormDataLike(V3)) {
        return webidl.converters.FormData(V3, prefix, name4, { strict: false });
      }
      if (V3 instanceof URLSearchParams) {
        return webidl.converters.URLSearchParams(V3, prefix, name4);
      }
      return webidl.converters.DOMString(V3, prefix, name4);
    };
    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 util5 = 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 } = util5;
    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: setMaxListeners2, getEventListeners, defaultMaxListeners } = __require("node:events");
    var kAbortController = Symbol("abortController");
    var requestFinalizer = new FinalizationRegistry2(({ signal, abort: abort2 }) => {
      signal.removeEventListener("abort", abort2);
    });
    var dependentControllerMap = /* @__PURE__ */ new WeakMap();
    function buildAbort(acRef) {
      return abort2;
      function abort2() {
        const ac = acRef.deref();
        if (ac !== void 0) {
          requestFinalizer.unregister(abort2);
          this.removeEventListener("abort", abort2);
          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(abort2, "abort");
    }
    __name(buildAbort, "buildAbort");
    var patchMethodWarning = false;
    var Request6 = class _Request {
      static {
        __name(this, "Request");
      }
      // https://fetch.spec.whatwg.org/#dom-request
      constructor(input, init2 = {}) {
        webidl.util.markAsUncloneable(this);
        if (input === kConstruct) {
          return;
        }
        const prefix = "Request constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        input = webidl.converters.RequestInfo(input, prefix, "input");
        init2 = webidl.converters.RequestInit(init2, prefix, "init");
        let request4 = null;
        let fallbackMode = null;
        const baseUrl = environmentSettingsObject.settingsObject.baseUrl;
        let signal = null;
        if (typeof input === "string") {
          this[kDispatcher] = init2.dispatcher;
          let parsedURL;
          try {
            parsedURL = new URL(input, baseUrl);
          } catch (err2) {
            throw new TypeError("Failed to parse URL from " + input, { cause: err2 });
          }
          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] = init2.dispatcher || input[kDispatcher];
          assert4(input instanceof _Request);
          request4 = input[kState];
          signal = input[kSignal];
        }
        const origin2 = environmentSettingsObject.settingsObject.origin;
        let window2 = "client";
        if (request4.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin(request4.window, origin2)) {
          window2 = request4.window;
        }
        if (init2.window != null) {
          throw new TypeError(`'window' option '${window2}' must be null`);
        }
        if ("window" in init2) {
          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(init2).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 (init2.referrer !== void 0) {
          const referrer = init2.referrer;
          if (referrer === "") {
            request4.referrer = "no-referrer";
          } else {
            let parsedReferrer;
            try {
              parsedReferrer = new URL(referrer, baseUrl);
            } catch (err2) {
              throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err2 });
            }
            if (parsedReferrer.protocol === "about:" && parsedReferrer.hostname === "client" || origin2 && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) {
              request4.referrer = "client";
            } else {
              request4.referrer = parsedReferrer;
            }
          }
        }
        if (init2.referrerPolicy !== void 0) {
          request4.referrerPolicy = init2.referrerPolicy;
        }
        let mode;
        if (init2.mode !== void 0) {
          mode = init2.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 (init2.credentials !== void 0) {
          request4.credentials = init2.credentials;
        }
        if (init2.cache !== void 0) {
          request4.cache = init2.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 (init2.redirect !== void 0) {
          request4.redirect = init2.redirect;
        }
        if (init2.integrity != null) {
          request4.integrity = String(init2.integrity);
        }
        if (init2.keepalive !== void 0) {
          request4.keepalive = Boolean(init2.keepalive);
        }
        if (init2.method !== void 0) {
          let method = init2.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 (init2.signal !== void 0) {
          signal = init2.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 abort2 = buildAbort(acRef);
            try {
              if (typeof getMaxListeners === "function" && getMaxListeners(signal) === defaultMaxListeners) {
                setMaxListeners2(1500, signal);
              } else if (getEventListeners(signal, "abort").length >= defaultMaxListeners) {
                setMaxListeners2(1500, signal);
              }
            } catch {
            }
            util5.addAbortListener(signal, abort2);
            requestFinalizer.register(ac, { signal, abort: abort2 }, abort2);
          }
        }
        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 = init2.headers !== void 0 ? init2.headers : new HeadersList(headersList);
          headersList.clear();
          if (headers instanceof HeadersList) {
            for (const { name: name4, value } of headers.rawValues()) {
              headersList.append(name4, value, false);
            }
            headersList.cookies = headers.cookies;
          } else {
            fillHeaders(this[kHeaders], headers);
          }
        }
        const inputBody = input instanceof _Request ? input[kState].body : null;
        if ((init2.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 (init2.body != null) {
          const [extractedBody, contentType] = extractBody(
            init2.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 && init2.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 && util5.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);
          util5.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(init2) {
      return {
        method: init2.method ?? "GET",
        localURLsOnly: init2.localURLsOnly ?? false,
        unsafeRequest: init2.unsafeRequest ?? false,
        body: init2.body ?? null,
        client: init2.client ?? null,
        reservedClient: init2.reservedClient ?? null,
        replacesClientId: init2.replacesClientId ?? "",
        window: init2.window ?? "client",
        keepalive: init2.keepalive ?? false,
        serviceWorkers: init2.serviceWorkers ?? "all",
        initiator: init2.initiator ?? "",
        destination: init2.destination ?? "",
        priority: init2.priority ?? null,
        origin: init2.origin ?? "client",
        policyContainer: init2.policyContainer ?? "client",
        referrer: init2.referrer ?? "client",
        referrerPolicy: init2.referrerPolicy ?? "",
        mode: init2.mode ?? "no-cors",
        useCORSPreflightFlag: init2.useCORSPreflightFlag ?? false,
        credentials: init2.credentials ?? "same-origin",
        useCredentials: init2.useCredentials ?? false,
        cache: init2.cache ?? "default",
        redirect: init2.redirect ?? "follow",
        integrity: init2.integrity ?? "",
        cryptoGraphicsNonceMetadata: init2.cryptoGraphicsNonceMetadata ?? "",
        parserMetadata: init2.parserMetadata ?? "",
        reloadNavigation: init2.reloadNavigation ?? false,
        historyNavigation: init2.historyNavigation ?? false,
        userActivation: init2.userActivation ?? false,
        taintedOrigin: init2.taintedOrigin ?? false,
        redirectCount: init2.redirectCount ?? 0,
        responseTainting: init2.responseTainting ?? "basic",
        preventNoCacheCacheControlHeaderModification: init2.preventNoCacheCacheControlHeaderModification ?? false,
        done: init2.done ?? false,
        timingAllowFailed: init2.timingAllowFailed ?? false,
        urlList: init2.urlList,
        url: init2.urlList[0],
        headersList: init2.headersList ? new HeadersList(init2.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 zlib5 = __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: Readable8, 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(error40) {
        if (this.state !== "ongoing") {
          return;
        }
        this.state = "aborted";
        if (!error40) {
          error40 = new DOMException("The operation was aborted.", "AbortError");
        }
        this.serializedAbortReason = error40;
        this.connection?.destroy(error40);
        this.emit("terminated", error40);
      }
    };
    function handleFetchDone(response) {
      finalizeAndReportTiming(response, "fetch");
    }
    __name(handleFetchDone, "handleFetchDone");
    function fetch5(input, init2 = void 0) {
      webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch");
      let p2 = createDeferredPromise();
      let requestObject;
      try {
        requestObject = new Request6(input, init2);
      } 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, error40) {
      if (p2) {
        p2.reject(error40);
      }
      if (request4.body != null && isReadable2(request4.body?.stream)) {
        request4.body.stream.cancel(error40).catch((err2) => {
          if (err2.code === "ERR_INVALID_STATE") {
            return;
          }
          throw err2;
        });
      }
      if (responseObject == null) {
        return;
      }
      const response = responseObject[kState];
      if (response.body != null && isReadable2(response.body?.stream)) {
        response.body.stream.cancel(error40).catch((err2) => {
          if (err2.code === "ERR_INVALID_STATE") {
            return;
          }
          throw err2;
        });
      }
    }
    __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((err2) => {
        fetchParams.controller.terminate(err2);
      });
      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((err2) => makeNetworkError(err2));
        }
        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 (err2) {
        return Promise.resolve(makeNetworkError(err2));
      }
      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(err2, abort2 = true) {
          if (!this.destroyed) {
            this.destroyed = true;
            if (abort2) {
              this.abort?.(err2 ?? 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 (err2) {
            processBodyError(err2);
          }
        }();
      }
      try {
        const { body: body2, status, statusText, headersList, socket } = await dispatch({ body: requestBody });
        if (socket) {
          response = makeResponse({ status, statusText, headersList, socket });
        } else {
          const iterator2 = body2[Symbol.asyncIterator]();
          fetchParams.controller.next = () => iterator2.next();
          response = makeResponse({ status, statusText, headersList });
        }
      } catch (err2) {
        if (err2.name === "AbortError") {
          fetchParams.controller.connection.destroy();
          return makeAppropriateNetworkError(fetchParams, err2);
        }
        return makeNetworkError(err2);
      }
      const pullAlgorithm = /* @__PURE__ */ __name(async () => {
        await fetchParams.controller.resume();
      }, "pullAlgorithm");
      const cancelAlgorithm = /* @__PURE__ */ __name((reason) => {
        if (!isCancelled(fetchParams)) {
          fetchParams.controller.abort(reason);
        }
      }, "cancelAlgorithm");
      const stream5 = 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: stream5, 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 (err2) {
            if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
              bytes = void 0;
            } else {
              bytes = err2;
              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(stream5)) {
            fetchParams.controller.terminate();
            return;
          }
          if (fetchParams.controller.controller.desiredSize <= 0) {
            return;
          }
        }
      };
      function onAborted(reason) {
        if (isAborted2(fetchParams)) {
          response.aborted = true;
          if (isReadable2(stream5)) {
            fetchParams.controller.controller.error(
              fetchParams.controller.serializedAbortReason
            );
          }
        } else {
          if (isReadable2(stream5)) {
            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: body2 }) {
        const url3 = requestCurrentURL(request4);
        const agent = fetchParams.controller.dispatcher;
        return new Promise((resolve42, reject) => agent.dispatch(
          {
            path: url3.pathname + url3.search,
            origin: url3.origin,
            method: request4.method,
            body: agent.isMockActive ? request4.body && (request4.body.source || request4.body.stream) : body2,
            headers: request4.headersList.entries,
            maxRedirections: 0,
            upgrade: request4.mode === "websocket" ? "websocket" : void 0
          },
          {
            body: null,
            abort: null,
            onConnect(abort2) {
              const { connection } = fetchParams.controller;
              timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability);
              if (connection.destroyed) {
                abort2(new DOMException("The operation was aborted.", "AbortError"));
              } else {
                fetchParams.controller.on("terminated", abort2);
                this.abort = connection.abort = abort2;
              }
              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 i4 = 0; i4 < rawHeaders.length; i4 += 2) {
                headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i4]), rawHeaders[i4 + 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 Readable8({ 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 i4 = codings.length - 1; i4 >= 0; --i4) {
                  const coding = codings[i4];
                  if (coding === "x-gzip" || coding === "gzip") {
                    decoders.push(zlib5.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: zlib5.constants.Z_SYNC_FLUSH,
                      finishFlush: zlib5.constants.Z_SYNC_FLUSH
                    }));
                  } else if (coding === "deflate") {
                    decoders.push(createInflate({
                      flush: zlib5.constants.Z_SYNC_FLUSH,
                      finishFlush: zlib5.constants.Z_SYNC_FLUSH
                    }));
                  } else if (coding === "br") {
                    decoders.push(zlib5.createBrotliDecompress({
                      flush: zlib5.constants.BROTLI_OPERATION_FLUSH,
                      finishFlush: zlib5.constants.BROTLI_OPERATION_FLUSH
                    }));
                  } else {
                    decoders.length = 0;
                    break;
                  }
                }
              }
              const onError2 = this.onError.bind(this);
              resolve42({
                status,
                statusText,
                headersList,
                body: decoders.length ? pipeline3(this.body, ...decoders, (err2) => {
                  if (err2) {
                    this.onError(err2);
                  }
                }).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(error40) {
              if (this.abort) {
                fetchParams.controller.off("terminated", this.abort);
              }
              this.body?.destroy(error40);
              fetchParams.controller.terminate(error40);
              reject(error40);
            },
            onUpgrade(status, rawHeaders, socket) {
              if (status !== 101) {
                return;
              }
              const headersList = new HeadersList();
              for (let i4 = 0; i4 < rawHeaders.length; i4 += 2) {
                headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i4]), rawHeaders[i4 + 1].toString("latin1"), true);
              }
              resolve42({
                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 stream5 = blob.stream();
      const reader = stream5.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 (error40) {
                  fr2[kError] = error40;
                  fireAProgressEvent("error", fr2);
                }
                if (fr2[kState] !== "loading") {
                  fireAProgressEvent("loadend", fr2);
                }
              });
              break;
            }
          } catch (error40) {
            if (fr2[kAborted]) {
              return;
            }
            queueMicrotask(() => {
              fr2[kState] = "done";
              fr2[kError] = error40;
              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: isValidHeaderName2 } = 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 (isValidHeaderName2(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 stream5 = innerResponse.body.stream;
          const reader = stream5.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 promise2 = 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);
          }
          promise2.resolve(Object.freeze(requestList));
        });
        return promise2.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 i4 = 0; i4 < value.length; ++i4) {
        const code2 = value.charCodeAt(i4);
        if (code2 >= 0 && code2 <= 8 || code2 >= 10 && code2 <= 31 || code2 === 127) {
          return true;
        }
      }
      return false;
    }
    __name(isCTLExcludingHtab, "isCTLExcludingHtab");
    function validateCookieName(name4) {
      for (let i4 = 0; i4 < name4.length; ++i4) {
        const code2 = name4.charCodeAt(i4);
        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 i4 = 0;
      if (value[0] === '"') {
        if (len === 1 || value[len - 1] !== '"') {
          throw new Error("Invalid cookie value");
        }
        --len;
        ++i4;
      }
      while (i4 < len) {
        const code2 = value.charCodeAt(i4++);
        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(path150) {
      for (let i4 = 0; i4 < path150.length; ++i4) {
        const code2 = path150.charCodeAt(i4);
        if (code2 < 32 || // exclude CTLs (0-31)
        code2 === 127 || // DEL
        code2 === 59) {
          throw new Error("Invalid cookie path");
        }
      }
    }
    __name(validateCookiePath, "validateCookiePath");
    function validateCookieDomain(domain2) {
      if (domain2.startsWith("-") || domain2.endsWith(".") || domain2.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, i4) => i4.toString().padStart(2, "0"));
    function toIMFDate(date5) {
      if (typeof date5 === "number") {
        date5 = new Date(date5);
      }
      return `${IMFDays[date5.getUTCDay()]}, ${IMFPaddedNumbers[date5.getUTCDate()]} ${IMFMonths[date5.getUTCMonth()]} ${date5.getUTCFullYear()} ${IMFPaddedNumbers[date5.getUTCHours()]}:${IMFPaddedNumbers[date5.getUTCMinutes()]}:${IMFPaddedNumbers[date5.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 out2 = [`${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) {
        out2.push("Secure");
      }
      if (cookie.httpOnly) {
        out2.push("HttpOnly");
      }
      if (typeof cookie.maxAge === "number") {
        validateCookieMaxAge(cookie.maxAge);
        out2.push(`Max-Age=${cookie.maxAge}`);
      }
      if (cookie.domain) {
        validateCookieDomain(cookie.domain);
        out2.push(`Domain=${cookie.domain}`);
      }
      if (cookie.path) {
        validateCookiePath(cookie.path);
        out2.push(`Path=${cookie.path}`);
      }
      if (cookie.expires && cookie.expires.toString() !== "Invalid Date") {
        out2.push(`Expires=${toIMFDate(cookie.expires)}`);
      }
      if (cookie.sameSite) {
        out2.push(`SameSite=${cookie.sameSite}`);
      }
      for (const part of cookie.unparsed) {
        if (!part.includes("=")) {
          throw new Error("Invalid unparsed");
        }
        const [key, ...value] = part.split("=");
        out2.push(`${key.trim()}=${value.join("=")}`);
      }
      return out2.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 name4 = "";
      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 };
        name4 = collectASequenceOfCodePointsFast(
          "=",
          nameValuePair,
          position
        );
        value = nameValuePair.slice(position.position + 1);
      }
      name4 = name4.trim();
      value = value.trim();
      if (name4.length + value.length > maxNameValuePairSize) {
        return null;
      }
      return {
        name: name4,
        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 out2 = {};
      if (!cookie) {
        return out2;
      }
      for (const piece of cookie.split(";")) {
        const [name4, ...value] = piece.split("=");
        out2[name4.trim()] = value.join("=");
      }
      return out2;
    }
    __name(getCookies, "getCookies");
    function deleteCookie(headers, name4, attributes) {
      webidl.brandCheck(headers, Headers6, { strict: false });
      const prefix = "deleteCookie";
      webidl.argumentLengthCheck(arguments, 2, prefix);
      name4 = webidl.converters.DOMString(name4, prefix, "name");
      attributes = webidl.converters.DeleteCookieAttributes(attributes);
      setCookie(headers, {
        name: name4,
        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, origin2 = "", lastEventId = "", source2 = null, ports2 = []) {
        webidl.brandCheck(this, _MessageEvent);
        webidl.argumentLengthCheck(arguments, 1, "MessageEvent.initMessageEvent");
        return new _MessageEvent(type, {
          bubbles,
          cancelable,
          data,
          origin: origin2,
          lastEventId,
          source: source2,
          ports: ports2
        });
      }
      static createFastMessageEvent(type, init2) {
        const messageEvent = new _MessageEvent(kConstruct, type, init2);
        messageEvent.#eventInit = init2;
        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: isUtf82 } = __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, init2) => new Event(type, init2), 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 i4 = 0; i4 < protocol.length; ++i4) {
        const code2 = protocol.charCodeAt(i4);
        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, init2) => new ErrorEvent2(type, init2), {
          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 [name4, value = ""] = pair.split("=");
        extensionList.set(
          removeHTTPWhitespace(name4, true, false),
          removeHTTPWhitespace(value, false, true)
        );
        position.position++;
      }
      return extensionList;
    }
    __name(parseExtensions, "parseExtensions");
    function isValidClientWindowBits(value) {
      for (let i4 = 0; i4 < value.length; i4++) {
        const byte = value.charCodeAt(i4);
        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 (isUtf82(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 crypto18;
    var buffer = null;
    var bufIdx = BUFFER_SIZE;
    try {
      crypto18 = __require("node:crypto");
    } catch {
      crypto18 = {
        // not full compatibility, but minimum.
        randomFillSync: /* @__PURE__ */ __name(function randomFillSync(buffer2, _offset, _size3) {
          for (let i4 = 0; i4 < buffer2.length; ++i4) {
            buffer2[i4] = Math.random() * 255 | 0;
          }
          return buffer2;
        }, "randomFillSync")
      };
    }
    function generateMask() {
      if (bufIdx === BUFFER_SIZE) {
        bufIdx = 0;
        crypto18.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 i4 = 0; i4 < bodyLength; ++i4) {
          buffer2[offset + i4] = frameData[i4] ^ maskKey[i4 & 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 crypto18;
    try {
      crypto18 = __require("node:crypto");
    } catch {
    }
    function establishWebSocketConnection(url3, protocols, client, ws2, onEstablish, options2) {
      const requestURL = url3;
      requestURL.protocol = url3.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 = crypto18.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 = crypto18.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, init2) => new CloseEvent(type, init2), {
        wasClean,
        code: code2,
        reason
      });
      if (channels.close.hasSubscribers) {
        channels.close.publish({
          websocket: ws2,
          code: code2,
          reason
        });
      }
    }
    __name(onSocketClose, "onSocketClose");
    function onSocketError(error40) {
      const { ws: ws2 } = this;
      ws2[kReadyState] = states.CLOSING;
      if (channels.socketError.hasSubscribers) {
        channels.socketError.publish(error40);
      }
      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", (err2) => {
            this.#inflate = null;
            callback(err2);
          });
        }
        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: Writable4 } = __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 Writable4 {
      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 body2 = this.consume(this.#info.payloadLength);
            if (isControlFrame(this.#info.opcode)) {
              this.#loop = this.parseControlFrame(body2);
              this.#state = parserStates.INFO;
            } else {
              if (!this.#info.compressed) {
                this.#fragments.push(body2);
                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(body2, this.#info.fin, (error40, data) => {
                  if (error40) {
                    closeWebSocketConnection(this.ws, 1007, error40.message, error40.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(body2) {
        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(body2);
          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 body3 = emptyBuffer;
            if (this.#info.closeInfo.code) {
              body3 = Buffer.allocUnsafe(2);
              body3.writeUInt16BE(this.#info.closeInfo.code, 0);
            }
            const closeFrame = new WebsocketFrameSend(body3);
            this.ws[kResponse].socket.write(
              closeFrame.createFrame(opcodes.CLOSE),
              (err2) => {
                if (!err2) {
                  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(body2);
            this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG));
            if (channels.ping.hasSubscribers) {
              channels.ping.publish({
                payload: body2
              });
            }
          }
        } else if (opcode === opcodes.PONG) {
          if (channels.pong.hasSubscribers) {
            channels.pong.publish({
              payload: body2
            });
          }
        }
        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(url3, 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");
        url3 = webidl.converters.USVString(url3, prefix, "url");
        protocols = options2.protocols;
        const baseURL = environmentSettingsObject.settingsObject.baseUrl;
        let urlRecord;
        try {
          urlRecord = new URL(url3, 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(err2) {
      let message;
      let code2;
      if (err2 instanceof CloseEvent) {
        message = err2.reason;
        code2 = err2.code;
      } else {
        message = err2.message;
      }
      fireEvent("error", this, () => new ErrorEvent2("error", { error: err2, 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 i4 = 0; i4 < value.length; i4++) {
        if (value.charCodeAt(i4) < 48 || value.charCodeAt(i4) > 57) return false;
      }
      return true;
    }
    __name(isASCIINumber, "isASCIINumber");
    function delay5(ms) {
      return new Promise((resolve42) => {
        setTimeout(resolve42, ms).unref();
      });
    }
    __name(delay5, "delay");
    module2.exports = {
      isValidLastEventId,
      isASCIINumber,
      delay: delay5
    };
  }
});

// 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: delay5 } = 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(url3, 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"
          });
        }
        url3 = webidl.converters.USVString(url3, 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(url3, 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,
            (error40) => {
              if (error40?.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 delay5(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_errors6();
    var util5 = 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: util5.parseHeaders,
      headerNameToString: util5.headerNameToString
    };
    function makeDispatcher(fn) {
      return (url3, opts, handler) => {
        if (typeof opts === "function") {
          handler = opts;
          opts = null;
        }
        if (!url3 || typeof url3 !== "string" && typeof url3 !== "object" && !(url3 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 path150 = opts.path;
          if (!opts.path.startsWith("/")) {
            path150 = `/${path150}`;
          }
          url3 = new URL(util5.parseOrigin(url3).origin + path150);
        } else {
          if (!opts) {
            opts = typeof url3 === "object" ? url3 : {};
          }
          url3 = util5.parseURL(url3);
        }
        const { agent, dispatcher = getGlobalDispatcher() } = opts;
        if (agent) {
          throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?");
        }
        return fn.call(dispatcher, {
          ...opts,
          origin: url3.origin,
          path: url3.search ? `${url3.pathname}${url3.search}` : url3.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(init2, options2 = void 0) {
      try {
        return await fetchImpl(init2, options2);
      } catch (err2) {
        if (err2 && typeof err2 === "object") {
          Error.captureStackTrace(err2);
        }
        throw err2;
      }
    }, "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/@agentclientprotocol/sdk/dist/schema/index.js
var AGENT_METHODS, CLIENT_METHODS, PROTOCOL_VERSION;
var init_schema = __esm({
  "node_modules/@agentclientprotocol/sdk/dist/schema/index.js"() {
    init_esbuild_shims();
    AGENT_METHODS = {
      authenticate: "authenticate",
      initialize: "initialize",
      session_cancel: "session/cancel",
      session_fork: "session/fork",
      session_list: "session/list",
      session_load: "session/load",
      session_new: "session/new",
      session_prompt: "session/prompt",
      session_resume: "session/resume",
      session_set_config_option: "session/set_config_option",
      session_set_mode: "session/set_mode",
      session_set_model: "session/set_model"
    };
    CLIENT_METHODS = {
      fs_read_text_file: "fs/read_text_file",
      fs_write_text_file: "fs/write_text_file",
      session_request_permission: "session/request_permission",
      session_update: "session/update",
      terminal_create: "terminal/create",
      terminal_kill: "terminal/kill",
      terminal_output: "terminal/output",
      terminal_release: "terminal/release",
      terminal_wait_for_exit: "terminal/wait_for_exit"
    };
    PROTOCOL_VERSION = 1;
  }
});

// node_modules/@agentclientprotocol/sdk/dist/schema/zod.gen.js
var zAuthMethod, zAuthenticateRequest, zAuthenticateResponse, zBlobResourceContents, zCost, zCreateTerminalResponse, zDiff, zEnvVariable, zErrorCode, zError, zExtNotification, zExtRequest, zExtResponse, zFileSystemCapability, zClientCapabilities, zHttpHeader, zImplementation, zKillTerminalCommandResponse, zListSessionsRequest, zMcpCapabilities, zMcpServerHttp, zMcpServerSse, zMcpServerStdio, zMcpServer, zModelId, zModelInfo, zNewSessionRequest, zPermissionOptionId, zPermissionOptionKind, zPermissionOption, zPlanEntryPriority, zPlanEntryStatus, zPlanEntry, zPlan, zPromptCapabilities, zProtocolVersion, zInitializeRequest, zReadTextFileResponse, zReleaseTerminalResponse, zRequestId, zCancelRequestNotification, zRole, zAnnotations, zAudioContent, zImageContent, zResourceLink, zSelectedPermissionOutcome, zRequestPermissionOutcome, zRequestPermissionResponse, zSessionConfigGroupId, zSessionConfigId, zSessionConfigOptionCategory, zSessionConfigValueId, zSessionConfigSelectOption, zSessionConfigSelectGroup, zSessionConfigSelectOptions, zSessionConfigSelect, zSessionConfigOption, zConfigOptionUpdate, zSessionForkCapabilities, zSessionId, zCancelNotification, zClientNotification, zCreateTerminalRequest, zForkSessionRequest, zKillTerminalCommandRequest, zLoadSessionRequest, zReadTextFileRequest, zReleaseTerminalRequest, zResumeSessionRequest, zSessionInfo, zListSessionsResponse, zSessionInfoUpdate, zSessionListCapabilities, zSessionModeId, zCurrentModeUpdate, zSessionMode, zSessionModeState, zSessionModelState, zForkSessionResponse, zLoadSessionResponse, zNewSessionResponse, zResumeSessionResponse, zSessionResumeCapabilities, zSessionCapabilities, zAgentCapabilities, zInitializeResponse, zSetSessionConfigOptionRequest, zSetSessionConfigOptionResponse, zSetSessionModeRequest, zSetSessionModeResponse, zSetSessionModelRequest, zSetSessionModelResponse, zStopReason, zTerminal, zTerminalExitStatus, zTerminalOutputRequest, zTerminalOutputResponse, zTextContent, zTextResourceContents, zEmbeddedResourceResource, zEmbeddedResource, zContentBlock, zContent, zContentChunk, zPromptRequest, zClientRequest, zToolCallContent, zToolCallId, zToolCallLocation, zToolCallStatus, zToolKind, zToolCall, zToolCallUpdate, zRequestPermissionRequest, zUnstructuredCommandInput, zAvailableCommandInput, zAvailableCommand, zAvailableCommandsUpdate, zUsage, zPromptResponse, zAgentResponse, zUsageUpdate, zSessionUpdate, zSessionNotification, zAgentNotification, zWaitForTerminalExitRequest, zWaitForTerminalExitResponse, zWriteTextFileRequest, zAgentRequest, zWriteTextFileResponse, zClientResponse;
var init_zod_gen = __esm({
  "node_modules/@agentclientprotocol/sdk/dist/schema/zod.gen.js"() {
    init_esbuild_shims();
    init_v42();
    zAuthMethod = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      description: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      id: external_exports2.string(),
      name: external_exports2.string()
    });
    zAuthenticateRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      methodId: external_exports2.string()
    });
    zAuthenticateResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional()
    });
    zBlobResourceContents = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      blob: external_exports2.string(),
      mimeType: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      uri: external_exports2.string()
    });
    zCost = external_exports2.object({
      amount: external_exports2.number(),
      currency: external_exports2.string()
    });
    zCreateTerminalResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      terminalId: external_exports2.string()
    });
    zDiff = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      newText: external_exports2.string(),
      oldText: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      path: external_exports2.string()
    });
    zEnvVariable = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      name: external_exports2.string(),
      value: external_exports2.string()
    });
    zErrorCode = external_exports2.union([
      external_exports2.literal(-32700),
      external_exports2.literal(-32600),
      external_exports2.literal(-32601),
      external_exports2.literal(-32602),
      external_exports2.literal(-32603),
      external_exports2.literal(-32800),
      external_exports2.literal(-32e3),
      external_exports2.literal(-32002),
      external_exports2.number().int().min(-2147483648, {
        message: "Invalid value: Expected int32 to be >= -2147483648"
      }).max(2147483647, {
        message: "Invalid value: Expected int32 to be <= 2147483647"
      })
    ]);
    zError = external_exports2.object({
      code: zErrorCode,
      data: external_exports2.unknown().optional(),
      message: external_exports2.string()
    });
    zExtNotification = external_exports2.unknown();
    zExtRequest = external_exports2.unknown();
    zExtResponse = external_exports2.unknown();
    zFileSystemCapability = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      readTextFile: external_exports2.boolean().optional().default(false),
      writeTextFile: external_exports2.boolean().optional().default(false)
    });
    zClientCapabilities = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      fs: zFileSystemCapability.optional().default({ readTextFile: false, writeTextFile: false }),
      terminal: external_exports2.boolean().optional().default(false)
    });
    zHttpHeader = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      name: external_exports2.string(),
      value: external_exports2.string()
    });
    zImplementation = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      name: external_exports2.string(),
      title: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      version: external_exports2.string()
    });
    zKillTerminalCommandResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional()
    });
    zListSessionsRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      cursor: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      cwd: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional()
    });
    zMcpCapabilities = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      http: external_exports2.boolean().optional().default(false),
      sse: external_exports2.boolean().optional().default(false)
    });
    zMcpServerHttp = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      headers: external_exports2.array(zHttpHeader),
      name: external_exports2.string(),
      url: external_exports2.string()
    });
    zMcpServerSse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      headers: external_exports2.array(zHttpHeader),
      name: external_exports2.string(),
      url: external_exports2.string()
    });
    zMcpServerStdio = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      args: external_exports2.array(external_exports2.string()),
      command: external_exports2.string(),
      env: external_exports2.array(zEnvVariable),
      name: external_exports2.string()
    });
    zMcpServer = external_exports2.union([
      zMcpServerHttp.and(external_exports2.object({
        type: external_exports2.literal("http")
      })),
      zMcpServerSse.and(external_exports2.object({
        type: external_exports2.literal("sse")
      })),
      zMcpServerStdio
    ]);
    zModelId = external_exports2.string();
    zModelInfo = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      description: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      modelId: zModelId,
      name: external_exports2.string()
    });
    zNewSessionRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      cwd: external_exports2.string(),
      mcpServers: external_exports2.array(zMcpServer)
    });
    zPermissionOptionId = external_exports2.string();
    zPermissionOptionKind = external_exports2.union([
      external_exports2.literal("allow_once"),
      external_exports2.literal("allow_always"),
      external_exports2.literal("reject_once"),
      external_exports2.literal("reject_always")
    ]);
    zPermissionOption = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      kind: zPermissionOptionKind,
      name: external_exports2.string(),
      optionId: zPermissionOptionId
    });
    zPlanEntryPriority = external_exports2.union([
      external_exports2.literal("high"),
      external_exports2.literal("medium"),
      external_exports2.literal("low")
    ]);
    zPlanEntryStatus = external_exports2.union([
      external_exports2.literal("pending"),
      external_exports2.literal("in_progress"),
      external_exports2.literal("completed")
    ]);
    zPlanEntry = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      content: external_exports2.string(),
      priority: zPlanEntryPriority,
      status: zPlanEntryStatus
    });
    zPlan = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      entries: external_exports2.array(zPlanEntry)
    });
    zPromptCapabilities = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      audio: external_exports2.boolean().optional().default(false),
      embeddedContext: external_exports2.boolean().optional().default(false),
      image: external_exports2.boolean().optional().default(false)
    });
    zProtocolVersion = external_exports2.number().int().gte(0).lte(65535);
    zInitializeRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      clientCapabilities: zClientCapabilities.optional().default({
        fs: { readTextFile: false, writeTextFile: false },
        terminal: false
      }),
      clientInfo: external_exports2.union([zImplementation, external_exports2.null()]).optional(),
      protocolVersion: zProtocolVersion
    });
    zReadTextFileResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      content: external_exports2.string()
    });
    zReleaseTerminalResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional()
    });
    zRequestId = external_exports2.union([external_exports2.null(), external_exports2.number(), external_exports2.string()]);
    zCancelRequestNotification = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      requestId: zRequestId
    });
    zRole = external_exports2.enum(["assistant", "user"]);
    zAnnotations = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      audience: external_exports2.union([external_exports2.array(zRole), external_exports2.null()]).optional(),
      lastModified: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      priority: external_exports2.union([external_exports2.number(), external_exports2.null()]).optional()
    });
    zAudioContent = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      annotations: external_exports2.union([zAnnotations, external_exports2.null()]).optional(),
      data: external_exports2.string(),
      mimeType: external_exports2.string()
    });
    zImageContent = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      annotations: external_exports2.union([zAnnotations, external_exports2.null()]).optional(),
      data: external_exports2.string(),
      mimeType: external_exports2.string(),
      uri: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional()
    });
    zResourceLink = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      annotations: external_exports2.union([zAnnotations, external_exports2.null()]).optional(),
      description: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      mimeType: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      name: external_exports2.string(),
      size: external_exports2.union([external_exports2.number(), external_exports2.null()]).optional(),
      title: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      uri: external_exports2.string()
    });
    zSelectedPermissionOutcome = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      optionId: zPermissionOptionId
    });
    zRequestPermissionOutcome = external_exports2.union([
      external_exports2.object({
        outcome: external_exports2.literal("cancelled")
      }),
      zSelectedPermissionOutcome.and(external_exports2.object({
        outcome: external_exports2.literal("selected")
      }))
    ]);
    zRequestPermissionResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      outcome: zRequestPermissionOutcome
    });
    zSessionConfigGroupId = external_exports2.string();
    zSessionConfigId = external_exports2.string();
    zSessionConfigOptionCategory = external_exports2.union([
      external_exports2.literal("mode"),
      external_exports2.literal("model"),
      external_exports2.literal("thought_level"),
      external_exports2.string()
    ]);
    zSessionConfigValueId = external_exports2.string();
    zSessionConfigSelectOption = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      description: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      name: external_exports2.string(),
      value: zSessionConfigValueId
    });
    zSessionConfigSelectGroup = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      group: zSessionConfigGroupId,
      name: external_exports2.string(),
      options: external_exports2.array(zSessionConfigSelectOption)
    });
    zSessionConfigSelectOptions = external_exports2.union([
      external_exports2.array(zSessionConfigSelectOption),
      external_exports2.array(zSessionConfigSelectGroup)
    ]);
    zSessionConfigSelect = external_exports2.object({
      currentValue: zSessionConfigValueId,
      options: zSessionConfigSelectOptions
    });
    zSessionConfigOption = zSessionConfigSelect.and(external_exports2.object({
      type: external_exports2.literal("select")
    })).and(external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      category: external_exports2.union([zSessionConfigOptionCategory, external_exports2.null()]).optional(),
      description: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      id: zSessionConfigId,
      name: external_exports2.string()
    }));
    zConfigOptionUpdate = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      configOptions: external_exports2.array(zSessionConfigOption)
    });
    zSessionForkCapabilities = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional()
    });
    zSessionId = external_exports2.string();
    zCancelNotification = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      sessionId: zSessionId
    });
    zClientNotification = external_exports2.object({
      method: external_exports2.string(),
      params: external_exports2.union([external_exports2.union([zCancelNotification, zExtNotification]), external_exports2.null()]).optional()
    });
    zCreateTerminalRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      args: external_exports2.array(external_exports2.string()).optional(),
      command: external_exports2.string(),
      cwd: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      env: external_exports2.array(zEnvVariable).optional(),
      outputByteLimit: external_exports2.union([external_exports2.number(), external_exports2.null()]).optional(),
      sessionId: zSessionId
    });
    zForkSessionRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      cwd: external_exports2.string(),
      mcpServers: external_exports2.array(zMcpServer).optional(),
      sessionId: zSessionId
    });
    zKillTerminalCommandRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      sessionId: zSessionId,
      terminalId: external_exports2.string()
    });
    zLoadSessionRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      cwd: external_exports2.string(),
      mcpServers: external_exports2.array(zMcpServer),
      sessionId: zSessionId
    });
    zReadTextFileRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      limit: external_exports2.union([
        external_exports2.number().int().gte(0).max(4294967295, {
          message: "Invalid value: Expected uint32 to be <= 4294967295"
        }),
        external_exports2.null()
      ]).optional(),
      line: external_exports2.union([
        external_exports2.number().int().gte(0).max(4294967295, {
          message: "Invalid value: Expected uint32 to be <= 4294967295"
        }),
        external_exports2.null()
      ]).optional(),
      path: external_exports2.string(),
      sessionId: zSessionId
    });
    zReleaseTerminalRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      sessionId: zSessionId,
      terminalId: external_exports2.string()
    });
    zResumeSessionRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      cwd: external_exports2.string(),
      mcpServers: external_exports2.array(zMcpServer).optional(),
      sessionId: zSessionId
    });
    zSessionInfo = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      cwd: external_exports2.string(),
      sessionId: zSessionId,
      title: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      updatedAt: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional()
    });
    zListSessionsResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      nextCursor: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      sessions: external_exports2.array(zSessionInfo)
    });
    zSessionInfoUpdate = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      title: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      updatedAt: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional()
    });
    zSessionListCapabilities = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional()
    });
    zSessionModeId = external_exports2.string();
    zCurrentModeUpdate = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      currentModeId: zSessionModeId
    });
    zSessionMode = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      description: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      id: zSessionModeId,
      name: external_exports2.string()
    });
    zSessionModeState = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      availableModes: external_exports2.array(zSessionMode),
      currentModeId: zSessionModeId
    });
    zSessionModelState = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      availableModels: external_exports2.array(zModelInfo),
      currentModelId: zModelId
    });
    zForkSessionResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      configOptions: external_exports2.union([external_exports2.array(zSessionConfigOption), external_exports2.null()]).optional(),
      models: external_exports2.union([zSessionModelState, external_exports2.null()]).optional(),
      modes: external_exports2.union([zSessionModeState, external_exports2.null()]).optional(),
      sessionId: zSessionId
    });
    zLoadSessionResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      configOptions: external_exports2.union([external_exports2.array(zSessionConfigOption), external_exports2.null()]).optional(),
      models: external_exports2.union([zSessionModelState, external_exports2.null()]).optional(),
      modes: external_exports2.union([zSessionModeState, external_exports2.null()]).optional()
    });
    zNewSessionResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      configOptions: external_exports2.union([external_exports2.array(zSessionConfigOption), external_exports2.null()]).optional(),
      models: external_exports2.union([zSessionModelState, external_exports2.null()]).optional(),
      modes: external_exports2.union([zSessionModeState, external_exports2.null()]).optional(),
      sessionId: zSessionId
    });
    zResumeSessionResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      configOptions: external_exports2.union([external_exports2.array(zSessionConfigOption), external_exports2.null()]).optional(),
      models: external_exports2.union([zSessionModelState, external_exports2.null()]).optional(),
      modes: external_exports2.union([zSessionModeState, external_exports2.null()]).optional()
    });
    zSessionResumeCapabilities = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional()
    });
    zSessionCapabilities = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      fork: external_exports2.union([zSessionForkCapabilities, external_exports2.null()]).optional(),
      list: external_exports2.union([zSessionListCapabilities, external_exports2.null()]).optional(),
      resume: external_exports2.union([zSessionResumeCapabilities, external_exports2.null()]).optional()
    });
    zAgentCapabilities = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      loadSession: external_exports2.boolean().optional().default(false),
      mcpCapabilities: zMcpCapabilities.optional().default({ http: false, sse: false }),
      promptCapabilities: zPromptCapabilities.optional().default({
        audio: false,
        embeddedContext: false,
        image: false
      }),
      sessionCapabilities: zSessionCapabilities.optional().default({})
    });
    zInitializeResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      agentCapabilities: zAgentCapabilities.optional().default({
        loadSession: false,
        mcpCapabilities: { http: false, sse: false },
        promptCapabilities: {
          audio: false,
          embeddedContext: false,
          image: false
        },
        sessionCapabilities: {}
      }),
      agentInfo: external_exports2.union([zImplementation, external_exports2.null()]).optional(),
      authMethods: external_exports2.array(zAuthMethod).optional().default([]),
      protocolVersion: zProtocolVersion
    });
    zSetSessionConfigOptionRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      configId: zSessionConfigId,
      sessionId: zSessionId,
      value: zSessionConfigValueId
    });
    zSetSessionConfigOptionResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      configOptions: external_exports2.array(zSessionConfigOption)
    });
    zSetSessionModeRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      modeId: zSessionModeId,
      sessionId: zSessionId
    });
    zSetSessionModeResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional()
    });
    zSetSessionModelRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      modelId: zModelId,
      sessionId: zSessionId
    });
    zSetSessionModelResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional()
    });
    zStopReason = external_exports2.union([
      external_exports2.literal("end_turn"),
      external_exports2.literal("max_tokens"),
      external_exports2.literal("max_turn_requests"),
      external_exports2.literal("refusal"),
      external_exports2.literal("cancelled")
    ]);
    zTerminal = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      terminalId: external_exports2.string()
    });
    zTerminalExitStatus = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      exitCode: external_exports2.union([
        external_exports2.number().int().gte(0).max(4294967295, {
          message: "Invalid value: Expected uint32 to be <= 4294967295"
        }),
        external_exports2.null()
      ]).optional(),
      signal: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional()
    });
    zTerminalOutputRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      sessionId: zSessionId,
      terminalId: external_exports2.string()
    });
    zTerminalOutputResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      exitStatus: external_exports2.union([zTerminalExitStatus, external_exports2.null()]).optional(),
      output: external_exports2.string(),
      truncated: external_exports2.boolean()
    });
    zTextContent = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      annotations: external_exports2.union([zAnnotations, external_exports2.null()]).optional(),
      text: external_exports2.string()
    });
    zTextResourceContents = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      mimeType: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      text: external_exports2.string(),
      uri: external_exports2.string()
    });
    zEmbeddedResourceResource = external_exports2.union([
      zTextResourceContents,
      zBlobResourceContents
    ]);
    zEmbeddedResource = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      annotations: external_exports2.union([zAnnotations, external_exports2.null()]).optional(),
      resource: zEmbeddedResourceResource
    });
    zContentBlock = external_exports2.union([
      zTextContent.and(external_exports2.object({
        type: external_exports2.literal("text")
      })),
      zImageContent.and(external_exports2.object({
        type: external_exports2.literal("image")
      })),
      zAudioContent.and(external_exports2.object({
        type: external_exports2.literal("audio")
      })),
      zResourceLink.and(external_exports2.object({
        type: external_exports2.literal("resource_link")
      })),
      zEmbeddedResource.and(external_exports2.object({
        type: external_exports2.literal("resource")
      }))
    ]);
    zContent = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      content: zContentBlock
    });
    zContentChunk = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      content: zContentBlock
    });
    zPromptRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      prompt: external_exports2.array(zContentBlock),
      sessionId: zSessionId
    });
    zClientRequest = external_exports2.object({
      id: zRequestId,
      method: external_exports2.string(),
      params: external_exports2.union([
        external_exports2.union([
          zInitializeRequest,
          zAuthenticateRequest,
          zNewSessionRequest,
          zLoadSessionRequest,
          zListSessionsRequest,
          zForkSessionRequest,
          zResumeSessionRequest,
          zSetSessionModeRequest,
          zSetSessionConfigOptionRequest,
          zPromptRequest,
          zSetSessionModelRequest,
          zExtRequest
        ]),
        external_exports2.null()
      ]).optional()
    });
    zToolCallContent = external_exports2.union([
      zContent.and(external_exports2.object({
        type: external_exports2.literal("content")
      })),
      zDiff.and(external_exports2.object({
        type: external_exports2.literal("diff")
      })),
      zTerminal.and(external_exports2.object({
        type: external_exports2.literal("terminal")
      }))
    ]);
    zToolCallId = external_exports2.string();
    zToolCallLocation = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      line: external_exports2.union([
        external_exports2.number().int().gte(0).max(4294967295, {
          message: "Invalid value: Expected uint32 to be <= 4294967295"
        }),
        external_exports2.null()
      ]).optional(),
      path: external_exports2.string()
    });
    zToolCallStatus = external_exports2.union([
      external_exports2.literal("pending"),
      external_exports2.literal("in_progress"),
      external_exports2.literal("completed"),
      external_exports2.literal("failed")
    ]);
    zToolKind = external_exports2.union([
      external_exports2.literal("read"),
      external_exports2.literal("edit"),
      external_exports2.literal("delete"),
      external_exports2.literal("move"),
      external_exports2.literal("search"),
      external_exports2.literal("execute"),
      external_exports2.literal("think"),
      external_exports2.literal("fetch"),
      external_exports2.literal("switch_mode"),
      external_exports2.literal("other")
    ]);
    zToolCall = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      content: external_exports2.array(zToolCallContent).optional(),
      kind: zToolKind.optional(),
      locations: external_exports2.array(zToolCallLocation).optional(),
      rawInput: external_exports2.unknown().optional(),
      rawOutput: external_exports2.unknown().optional(),
      status: zToolCallStatus.optional(),
      title: external_exports2.string(),
      toolCallId: zToolCallId
    });
    zToolCallUpdate = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      content: external_exports2.union([external_exports2.array(zToolCallContent), external_exports2.null()]).optional(),
      kind: external_exports2.union([zToolKind, external_exports2.null()]).optional(),
      locations: external_exports2.union([external_exports2.array(zToolCallLocation), external_exports2.null()]).optional(),
      rawInput: external_exports2.unknown().optional(),
      rawOutput: external_exports2.unknown().optional(),
      status: external_exports2.union([zToolCallStatus, external_exports2.null()]).optional(),
      title: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional(),
      toolCallId: zToolCallId
    });
    zRequestPermissionRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      options: external_exports2.array(zPermissionOption),
      sessionId: zSessionId,
      toolCall: zToolCallUpdate
    });
    zUnstructuredCommandInput = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      hint: external_exports2.string()
    });
    zAvailableCommandInput = zUnstructuredCommandInput;
    zAvailableCommand = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      description: external_exports2.string(),
      input: external_exports2.union([zAvailableCommandInput, external_exports2.null()]).optional(),
      name: external_exports2.string()
    });
    zAvailableCommandsUpdate = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      availableCommands: external_exports2.array(zAvailableCommand)
    });
    zUsage = external_exports2.object({
      cachedReadTokens: external_exports2.union([external_exports2.number(), external_exports2.null()]).optional(),
      cachedWriteTokens: external_exports2.union([external_exports2.number(), external_exports2.null()]).optional(),
      inputTokens: external_exports2.number(),
      outputTokens: external_exports2.number(),
      thoughtTokens: external_exports2.union([external_exports2.number(), external_exports2.null()]).optional(),
      totalTokens: external_exports2.number()
    });
    zPromptResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      stopReason: zStopReason,
      usage: external_exports2.union([zUsage, external_exports2.null()]).optional()
    });
    zAgentResponse = external_exports2.union([
      external_exports2.object({
        id: zRequestId,
        result: external_exports2.union([
          zInitializeResponse,
          zAuthenticateResponse,
          zNewSessionResponse,
          zLoadSessionResponse,
          zListSessionsResponse,
          zForkSessionResponse,
          zResumeSessionResponse,
          zSetSessionModeResponse,
          zSetSessionConfigOptionResponse,
          zPromptResponse,
          zSetSessionModelResponse,
          zExtResponse
        ])
      }),
      external_exports2.object({
        error: zError,
        id: zRequestId
      })
    ]);
    zUsageUpdate = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      cost: external_exports2.union([zCost, external_exports2.null()]).optional(),
      size: external_exports2.number(),
      used: external_exports2.number()
    });
    zSessionUpdate = external_exports2.union([
      zContentChunk.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("user_message_chunk")
      })),
      zContentChunk.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("agent_message_chunk")
      })),
      zContentChunk.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("agent_thought_chunk")
      })),
      zToolCall.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("tool_call")
      })),
      zToolCallUpdate.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("tool_call_update")
      })),
      zPlan.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("plan")
      })),
      zAvailableCommandsUpdate.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("available_commands_update")
      })),
      zCurrentModeUpdate.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("current_mode_update")
      })),
      zConfigOptionUpdate.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("config_option_update")
      })),
      zSessionInfoUpdate.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("session_info_update")
      })),
      zUsageUpdate.and(external_exports2.object({
        sessionUpdate: external_exports2.literal("usage_update")
      }))
    ]);
    zSessionNotification = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      sessionId: zSessionId,
      update: zSessionUpdate
    });
    zAgentNotification = external_exports2.object({
      method: external_exports2.string(),
      params: external_exports2.union([external_exports2.union([zSessionNotification, zExtNotification]), external_exports2.null()]).optional()
    });
    zWaitForTerminalExitRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      sessionId: zSessionId,
      terminalId: external_exports2.string()
    });
    zWaitForTerminalExitResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      exitCode: external_exports2.union([
        external_exports2.number().int().gte(0).max(4294967295, {
          message: "Invalid value: Expected uint32 to be <= 4294967295"
        }),
        external_exports2.null()
      ]).optional(),
      signal: external_exports2.union([external_exports2.string(), external_exports2.null()]).optional()
    });
    zWriteTextFileRequest = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional(),
      content: external_exports2.string(),
      path: external_exports2.string(),
      sessionId: zSessionId
    });
    zAgentRequest = external_exports2.object({
      id: zRequestId,
      method: external_exports2.string(),
      params: external_exports2.union([
        external_exports2.union([
          zWriteTextFileRequest,
          zReadTextFileRequest,
          zRequestPermissionRequest,
          zCreateTerminalRequest,
          zTerminalOutputRequest,
          zReleaseTerminalRequest,
          zWaitForTerminalExitRequest,
          zKillTerminalCommandRequest,
          zExtRequest
        ]),
        external_exports2.null()
      ]).optional()
    });
    zWriteTextFileResponse = external_exports2.object({
      _meta: external_exports2.union([external_exports2.record(external_exports2.string(), external_exports2.unknown()), external_exports2.null()]).optional()
    });
    zClientResponse = external_exports2.union([
      external_exports2.object({
        id: zRequestId,
        result: external_exports2.union([
          zWriteTextFileResponse,
          zReadTextFileResponse,
          zRequestPermissionResponse,
          zCreateTerminalResponse,
          zTerminalOutputResponse,
          zReleaseTerminalResponse,
          zWaitForTerminalExitResponse,
          zKillTerminalCommandResponse,
          zExtResponse
        ])
      }),
      external_exports2.object({
        error: zError,
        id: zRequestId
      })
    ]);
  }
});

// node_modules/@agentclientprotocol/sdk/dist/stream.js
function ndJsonStream(output, input) {
  const textEncoder2 = new TextEncoder();
  const textDecoder = new TextDecoder();
  const readable = new ReadableStream({
    async start(controller) {
      let content = "";
      const reader = input.getReader();
      try {
        while (true) {
          const { value, done } = await reader.read();
          if (done) {
            break;
          }
          if (!value) {
            continue;
          }
          content += textDecoder.decode(value, { 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);
                controller.enqueue(message);
              } catch (err2) {
                console.error("Failed to parse JSON message:", trimmedLine, err2);
              }
            }
          }
        }
      } finally {
        reader.releaseLock();
        controller.close();
      }
    }
  });
  const writable = new WritableStream({
    async write(message) {
      const content = JSON.stringify(message) + "\n";
      const writer = output.getWriter();
      try {
        await writer.write(textEncoder2.encode(content));
      } finally {
        writer.releaseLock();
      }
    }
  });
  return { readable, writable };
}
var init_stream2 = __esm({
  "node_modules/@agentclientprotocol/sdk/dist/stream.js"() {
    init_esbuild_shims();
    __name(ndJsonStream, "ndJsonStream");
  }
});

// node_modules/@agentclientprotocol/sdk/dist/acp.js
var AgentSideConnection, TerminalHandle, ClientSideConnection, Connection, RequestError;
var init_acp = __esm({
  "node_modules/@agentclientprotocol/sdk/dist/acp.js"() {
    init_esbuild_shims();
    init_zod();
    init_schema();
    init_zod_gen();
    init_schema();
    init_stream2();
    AgentSideConnection = class {
      static {
        __name(this, "AgentSideConnection");
      }
      #connection;
      /**
       * Creates a new agent-side connection to a client.
       *
       * This establishes the communication channel from the agent's perspective
       * following the ACP specification.
       *
       * @param toAgent - A function that creates an Agent handler to process incoming client requests
       * @param stream - The bidirectional message stream for communication. Typically created using
       *                 {@link ndJsonStream} for stdio-based connections.
       *
       * See protocol docs: [Communication Model](https://agentclientprotocol.com/protocol/overview#communication-model)
       */
      constructor(toAgent, stream5) {
        const agent = toAgent(this);
        const requestHandler = /* @__PURE__ */ __name(async (method, params) => {
          switch (method) {
            case AGENT_METHODS.initialize: {
              const validatedParams = zInitializeRequest.parse(params);
              return agent.initialize(validatedParams);
            }
            case AGENT_METHODS.session_new: {
              const validatedParams = zNewSessionRequest.parse(params);
              return agent.newSession(validatedParams);
            }
            case AGENT_METHODS.session_load: {
              if (!agent.loadSession) {
                throw RequestError.methodNotFound(method);
              }
              const validatedParams = zLoadSessionRequest.parse(params);
              return agent.loadSession(validatedParams);
            }
            case AGENT_METHODS.session_list: {
              if (!agent.unstable_listSessions) {
                throw RequestError.methodNotFound(method);
              }
              const validatedParams = zListSessionsRequest.parse(params);
              return agent.unstable_listSessions(validatedParams);
            }
            case AGENT_METHODS.session_fork: {
              if (!agent.unstable_forkSession) {
                throw RequestError.methodNotFound(method);
              }
              const validatedParams = zForkSessionRequest.parse(params);
              return agent.unstable_forkSession(validatedParams);
            }
            case AGENT_METHODS.session_resume: {
              if (!agent.unstable_resumeSession) {
                throw RequestError.methodNotFound(method);
              }
              const validatedParams = zResumeSessionRequest.parse(params);
              return agent.unstable_resumeSession(validatedParams);
            }
            case AGENT_METHODS.session_set_mode: {
              if (!agent.setSessionMode) {
                throw RequestError.methodNotFound(method);
              }
              const validatedParams = zSetSessionModeRequest.parse(params);
              const result = await agent.setSessionMode(validatedParams);
              return result ?? {};
            }
            case AGENT_METHODS.authenticate: {
              const validatedParams = zAuthenticateRequest.parse(params);
              const result = await agent.authenticate(validatedParams);
              return result ?? {};
            }
            case AGENT_METHODS.session_prompt: {
              const validatedParams = zPromptRequest.parse(params);
              return agent.prompt(validatedParams);
            }
            case AGENT_METHODS.session_set_model: {
              if (!agent.unstable_setSessionModel) {
                throw RequestError.methodNotFound(method);
              }
              const validatedParams = zSetSessionModelRequest.parse(params);
              const result = await agent.unstable_setSessionModel(validatedParams);
              return result ?? {};
            }
            case AGENT_METHODS.session_set_config_option: {
              if (!agent.setSessionConfigOption) {
                throw RequestError.methodNotFound(method);
              }
              const validatedParams = zSetSessionConfigOptionRequest.parse(params);
              return agent.setSessionConfigOption(validatedParams);
            }
            default:
              if (agent.extMethod) {
                return agent.extMethod(method, params);
              }
              throw RequestError.methodNotFound(method);
          }
        }, "requestHandler");
        const notificationHandler = /* @__PURE__ */ __name(async (method, params) => {
          switch (method) {
            case AGENT_METHODS.session_cancel: {
              const validatedParams = zCancelNotification.parse(params);
              return agent.cancel(validatedParams);
            }
            default:
              if (agent.extNotification) {
                return agent.extNotification(method, params);
              }
              throw RequestError.methodNotFound(method);
          }
        }, "notificationHandler");
        this.#connection = new Connection(requestHandler, notificationHandler, stream5);
      }
      /**
       * Handles session update notifications from the agent.
       *
       * This is a notification endpoint (no response expected) that sends
       * real-time updates about session progress, including message chunks,
       * tool calls, and execution plans.
       *
       * Note: Clients SHOULD continue accepting tool call updates even after
       * sending a `session/cancel` notification, as the agent may send final
       * updates before responding with the cancelled stop reason.
       *
       * See protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)
       */
      async sessionUpdate(params) {
        return await this.#connection.sendNotification(CLIENT_METHODS.session_update, params);
      }
      /**
       * Requests permission from the user for a tool call operation.
       *
       * Called by the agent when it needs user authorization before executing
       * a potentially sensitive operation. The client should present the options
       * to the user and return their decision.
       *
       * If the client cancels the prompt turn via `session/cancel`, it MUST
       * respond to this request with `RequestPermissionOutcome::Cancelled`.
       *
       * See protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/tool-calls#requesting-permission)
       */
      async requestPermission(params) {
        return await this.#connection.sendRequest(CLIENT_METHODS.session_request_permission, params);
      }
      /**
       * Reads content from a text file in the client's file system.
       *
       * Only available if the client advertises the `fs.readTextFile` capability.
       * Allows the agent to access file contents within the client's environment.
       *
       * See protocol docs: [Client](https://agentclientprotocol.com/protocol/overview#client)
       */
      async readTextFile(params) {
        return await this.#connection.sendRequest(CLIENT_METHODS.fs_read_text_file, params);
      }
      /**
       * Writes content to a text file in the client's file system.
       *
       * Only available if the client advertises the `fs.writeTextFile` capability.
       * Allows the agent to create or modify files within the client's environment.
       *
       * See protocol docs: [Client](https://agentclientprotocol.com/protocol/overview#client)
       */
      async writeTextFile(params) {
        return await this.#connection.sendRequest(CLIENT_METHODS.fs_write_text_file, params) ?? {};
      }
      /**
       * Executes a command in a new terminal.
       *
       * Returns a `TerminalHandle` that can be used to get output, wait for exit,
       * kill the command, or release the terminal.
       *
       * The terminal can also be embedded in tool calls by using its ID in
       * `ToolCallContent` with type "terminal".
       *
       * @param params - The terminal creation parameters
       * @returns A handle to control and monitor the terminal
       */
      async createTerminal(params) {
        const response = await this.#connection.sendRequest(CLIENT_METHODS.terminal_create, params);
        return new TerminalHandle(response.terminalId, params.sessionId, this.#connection);
      }
      /**
       * Extension method
       *
       * Allows the Agent to send an arbitrary request that is not part of the ACP spec.
       */
      async extMethod(method, params) {
        return await this.#connection.sendRequest(method, params);
      }
      /**
       * Extension notification
       *
       * Allows the Agent to send an arbitrary notification that is not part of the ACP spec.
       */
      async extNotification(method, params) {
        return await this.#connection.sendNotification(method, params);
      }
      /**
       * AbortSignal that aborts when the connection closes.
       *
       * This signal can be used to:
       * - Listen for connection closure: `connection.signal.addEventListener('abort', () => {...})`
       * - Check connection status synchronously: `if (connection.signal.aborted) {...}`
       * - Pass to other APIs (fetch, setTimeout) for automatic cancellation
       *
       * The connection closes when the underlying stream ends, either normally or due to an error.
       *
       * @example
       * ```typescript
       * const connection = new AgentSideConnection(agent, stream);
       *
       * // Listen for closure
       * connection.signal.addEventListener('abort', () => {
       *   console.log('Connection closed - performing cleanup');
       * });
       *
       * // Check status
       * if (connection.signal.aborted) {
       *   console.log('Connection is already closed');
       * }
       *
       * // Pass to other APIs
       * fetch(url, { signal: connection.signal });
       * ```
       */
      get signal() {
        return this.#connection.signal;
      }
      /**
       * Promise that resolves when the connection closes.
       *
       * The connection closes when the underlying stream ends, either normally or due to an error.
       * Once closed, the connection cannot send or receive any more messages.
       *
       * This is useful for async/await style cleanup:
       *
       * @example
       * ```typescript
       * const connection = new AgentSideConnection(agent, stream);
       * await connection.closed;
       * console.log('Connection closed - performing cleanup');
       * ```
       */
      get closed() {
        return this.#connection.closed;
      }
    };
    TerminalHandle = class {
      static {
        __name(this, "TerminalHandle");
      }
      id;
      #sessionId;
      #connection;
      constructor(id, sessionId, conn) {
        this.id = id;
        this.#sessionId = sessionId;
        this.#connection = conn;
      }
      /**
       * Gets the current terminal output without waiting for the command to exit.
       */
      async currentOutput() {
        return await this.#connection.sendRequest(CLIENT_METHODS.terminal_output, {
          sessionId: this.#sessionId,
          terminalId: this.id
        });
      }
      /**
       * Waits for the terminal command to complete and returns its exit status.
       */
      async waitForExit() {
        return await this.#connection.sendRequest(CLIENT_METHODS.terminal_wait_for_exit, {
          sessionId: this.#sessionId,
          terminalId: this.id
        });
      }
      /**
       * Kills the terminal command without releasing the terminal.
       *
       * The terminal remains valid after killing, allowing you to:
       * - Get the final output with `currentOutput()`
       * - Check the exit status
       * - Release the terminal when done
       *
       * Useful for implementing timeouts or cancellation.
       */
      async kill() {
        return await this.#connection.sendRequest(CLIENT_METHODS.terminal_kill, {
          sessionId: this.#sessionId,
          terminalId: this.id
        }) ?? {};
      }
      /**
       * Releases the terminal and frees all associated resources.
       *
       * If the command is still running, it will be killed.
       * After release, the terminal ID becomes invalid and cannot be used
       * with other terminal methods.
       *
       * Tool calls that already reference this terminal will continue to
       * display its output.
       *
       * **Important:** Always call this method when done with the terminal.
       */
      async release() {
        return await this.#connection.sendRequest(CLIENT_METHODS.terminal_release, {
          sessionId: this.#sessionId,
          terminalId: this.id
        }) ?? {};
      }
      async [Symbol.asyncDispose]() {
        await this.release();
      }
    };
    ClientSideConnection = class {
      static {
        __name(this, "ClientSideConnection");
      }
      #connection;
      /**
       * Creates a new client-side connection to an agent.
       *
       * This establishes the communication channel between a client and agent
       * following the ACP specification.
       *
       * @param toClient - A function that creates a Client handler to process incoming agent requests
       * @param stream - The bidirectional message stream for communication. Typically created using
       *                 {@link ndJsonStream} for stdio-based connections.
       *
       * See protocol docs: [Communication Model](https://agentclientprotocol.com/protocol/overview#communication-model)
       */
      constructor(toClient, stream5) {
        const client = toClient(this);
        const requestHandler = /* @__PURE__ */ __name(async (method, params) => {
          switch (method) {
            case CLIENT_METHODS.fs_write_text_file: {
              const validatedParams = zWriteTextFileRequest.parse(params);
              return client.writeTextFile?.(validatedParams);
            }
            case CLIENT_METHODS.fs_read_text_file: {
              const validatedParams = zReadTextFileRequest.parse(params);
              return client.readTextFile?.(validatedParams);
            }
            case CLIENT_METHODS.session_request_permission: {
              const validatedParams = zRequestPermissionRequest.parse(params);
              return client.requestPermission(validatedParams);
            }
            case CLIENT_METHODS.terminal_create: {
              const validatedParams = zCreateTerminalRequest.parse(params);
              return client.createTerminal?.(validatedParams);
            }
            case CLIENT_METHODS.terminal_output: {
              const validatedParams = zTerminalOutputRequest.parse(params);
              return client.terminalOutput?.(validatedParams);
            }
            case CLIENT_METHODS.terminal_release: {
              const validatedParams = zReleaseTerminalRequest.parse(params);
              const result = await client.releaseTerminal?.(validatedParams);
              return result ?? {};
            }
            case CLIENT_METHODS.terminal_wait_for_exit: {
              const validatedParams = zWaitForTerminalExitRequest.parse(params);
              return client.waitForTerminalExit?.(validatedParams);
            }
            case CLIENT_METHODS.terminal_kill: {
              const validatedParams = zKillTerminalCommandRequest.parse(params);
              const result = await client.killTerminal?.(validatedParams);
              return result ?? {};
            }
            default:
              if (client.extMethod) {
                return client.extMethod(method, params);
              }
              throw RequestError.methodNotFound(method);
          }
        }, "requestHandler");
        const notificationHandler = /* @__PURE__ */ __name(async (method, params) => {
          switch (method) {
            case CLIENT_METHODS.session_update: {
              const validatedParams = zSessionNotification.parse(params);
              return client.sessionUpdate(validatedParams);
            }
            default:
              if (client.extNotification) {
                return client.extNotification(method, params);
              }
              throw RequestError.methodNotFound(method);
          }
        }, "notificationHandler");
        this.#connection = new Connection(requestHandler, notificationHandler, stream5);
      }
      /**
       * Establishes the connection with a client and negotiates protocol capabilities.
       *
       * This method is called once at the beginning of the connection to:
       * - Negotiate the protocol version to use
       * - Exchange capability information between client and agent
       * - Determine available authentication methods
       *
       * The agent should respond with its supported protocol version and capabilities.
       *
       * See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
       */
      async initialize(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.initialize, params);
      }
      /**
       * Creates a new conversation session with the agent.
       *
       * Sessions represent independent conversation contexts with their own history and state.
       *
       * The agent should:
       * - Create a new session context
       * - Connect to any specified MCP servers
       * - Return a unique session ID for future requests
       *
       * May return an `auth_required` error if the agent requires authentication.
       *
       * See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/session-setup)
       */
      async newSession(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.session_new, params);
      }
      /**
       * Loads an existing session to resume a previous conversation.
       *
       * This method is only available if the agent advertises the `loadSession` capability.
       *
       * The agent should:
       * - Restore the session context and conversation history
       * - Connect to the specified MCP servers
       * - Stream the entire conversation history back to the client via notifications
       *
       * See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)
       */
      async loadSession(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.session_load, params) ?? {};
      }
      /**
       * **UNSTABLE**
       *
       * This capability is not part of the spec yet, and may be removed or changed at any point.
       *
       * Forks an existing session to create a new independent session.
       *
       * Creates a new session based on the context of an existing one, allowing
       * operations like generating summaries without affecting the original session's history.
       *
       * This method is only available if the agent advertises the `session.fork` capability.
       *
       * @experimental
       */
      async unstable_forkSession(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.session_fork, params);
      }
      /**
       * **UNSTABLE**
       *
       * This capability is not part of the spec yet, and may be removed or changed at any point.
       *
       * Lists existing sessions from the agent.
       *
       * This method is only available if the agent advertises the `listSessions` capability.
       *
       * Returns a list of sessions with metadata like session ID, working directory,
       * title, and last update time. Supports filtering by working directory and
       * cursor-based pagination.
       *
       * @experimental
       */
      async unstable_listSessions(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.session_list, params);
      }
      /**
       * **UNSTABLE**
       *
       * This capability is not part of the spec yet, and may be removed or changed at any point.
       *
       * Resumes an existing session without returning previous messages.
       *
       * This method is only available if the agent advertises the `session.resume` capability.
       *
       * The agent should resume the session context, allowing the conversation to continue
       * without replaying the message history (unlike `session/load`).
       *
       * @experimental
       */
      async unstable_resumeSession(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.session_resume, params);
      }
      /**
       * Sets the operational mode for a session.
       *
       * Allows switching between different agent modes (e.g., "ask", "architect", "code")
       * that affect system prompts, tool availability, and permission behaviors.
       *
       * The mode must be one of the modes advertised in `availableModes` during session
       * creation or loading. Agents may also change modes autonomously and notify the
       * client via `current_mode_update` notifications.
       *
       * This method can be called at any time during a session, whether the Agent is
       * idle or actively generating a turn.
       *
       * See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
       */
      async setSessionMode(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.session_set_mode, params) ?? {};
      }
      /**
       * **UNSTABLE**
       *
       * This capability is not part of the spec yet, and may be removed or changed at any point.
       *
       * Select a model for a given session.
       *
       * @experimental
       */
      async unstable_setSessionModel(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.session_set_model, params) ?? {};
      }
      /**
       * Set a configuration option for a given session.
       *
       * The response contains the full set of configuration options and their current values,
       * as changing one option may affect the available values or state of other options.
       */
      async setSessionConfigOption(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.session_set_config_option, params);
      }
      /**
       * Authenticates the client using the specified authentication method.
       *
       * Called when the agent requires authentication before allowing session creation.
       * The client provides the authentication method ID that was advertised during initialization.
       *
       * After successful authentication, the client can proceed to create sessions with
       * `newSession` without receiving an `auth_required` error.
       *
       * See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
       */
      async authenticate(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.authenticate, params) ?? {};
      }
      /**
       * Processes a user prompt within a session.
       *
       * This method handles the whole lifecycle of a prompt:
       * - Receives user messages with optional context (files, images, etc.)
       * - Processes the prompt using language models
       * - Reports language model content and tool calls to the Clients
       * - Requests permission to run tools
       * - Executes any requested tool calls
       * - Returns when the turn is complete with a stop reason
       *
       * See protocol docs: [Prompt Turn](https://agentclientprotocol.com/protocol/prompt-turn)
       */
      async prompt(params) {
        return await this.#connection.sendRequest(AGENT_METHODS.session_prompt, params);
      }
      /**
       * Cancels ongoing operations for a session.
       *
       * This is a notification sent by the client to cancel an ongoing prompt turn.
       *
       * Upon receiving this notification, the Agent SHOULD:
       * - Stop all language model requests as soon as possible
       * - Abort all tool call invocations in progress
       * - Send any pending `session/update` notifications
       * - Respond to the original `session/prompt` request with `StopReason::Cancelled`
       *
       * See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)
       */
      async cancel(params) {
        return await this.#connection.sendNotification(AGENT_METHODS.session_cancel, params);
      }
      /**
       * Extension method
       *
       * Allows the Client to send an arbitrary request that is not part of the ACP spec.
       */
      async extMethod(method, params) {
        return await this.#connection.sendRequest(method, params);
      }
      /**
       * Extension notification
       *
       * Allows the Client to send an arbitrary notification that is not part of the ACP spec.
       */
      async extNotification(method, params) {
        return await this.#connection.sendNotification(method, params);
      }
      /**
       * AbortSignal that aborts when the connection closes.
       *
       * This signal can be used to:
       * - Listen for connection closure: `connection.signal.addEventListener('abort', () => {...})`
       * - Check connection status synchronously: `if (connection.signal.aborted) {...}`
       * - Pass to other APIs (fetch, setTimeout) for automatic cancellation
       *
       * The connection closes when the underlying stream ends, either normally or due to an error.
       *
       * @example
       * ```typescript
       * const connection = new ClientSideConnection(client, stream);
       *
       * // Listen for closure
       * connection.signal.addEventListener('abort', () => {
       *   console.log('Connection closed - performing cleanup');
       * });
       *
       * // Check status
       * if (connection.signal.aborted) {
       *   console.log('Connection is already closed');
       * }
       *
       * // Pass to other APIs
       * fetch(url, { signal: connection.signal });
       * ```
       */
      get signal() {
        return this.#connection.signal;
      }
      /**
       * Promise that resolves when the connection closes.
       *
       * The connection closes when the underlying stream ends, either normally or due to an error.
       * Once closed, the connection cannot send or receive any more messages.
       *
       * This is useful for async/await style cleanup:
       *
       * @example
       * ```typescript
       * const connection = new ClientSideConnection(client, stream);
       * await connection.closed;
       * console.log('Connection closed - performing cleanup');
       * ```
       */
      get closed() {
        return this.#connection.closed;
      }
    };
    Connection = class {
      static {
        __name(this, "Connection");
      }
      #pendingResponses = /* @__PURE__ */ new Map();
      #nextRequestId = 0;
      #requestHandler;
      #notificationHandler;
      #stream;
      #writeQueue = Promise.resolve();
      #abortController = new AbortController();
      #closedPromise;
      constructor(requestHandler, notificationHandler, stream5) {
        this.#requestHandler = requestHandler;
        this.#notificationHandler = notificationHandler;
        this.#stream = stream5;
        this.#closedPromise = new Promise((resolve42) => {
          this.#abortController.signal.addEventListener("abort", () => resolve42());
        });
        this.#receive();
      }
      /**
       * AbortSignal that aborts when the connection closes.
       *
       * This signal can be used to:
       * - Listen for connection closure via event listeners
       * - Check connection status synchronously with `signal.aborted`
       * - Pass to other APIs (fetch, setTimeout) for automatic cancellation
       */
      get signal() {
        return this.#abortController.signal;
      }
      /**
       * Promise that resolves when the connection closes.
       *
       * The connection closes when the underlying stream ends, either normally
       * or due to an error. Once closed, the connection cannot send or receive
       * any more messages.
       *
       * @example
       * ```typescript
       * const connection = new ClientSideConnection(client, stream);
       * await connection.closed;
       * console.log('Connection closed - performing cleanup');
       * ```
       */
      get closed() {
        return this.#closedPromise;
      }
      async #receive() {
        const reader = this.#stream.readable.getReader();
        try {
          while (true) {
            const { value: message, done } = await reader.read();
            if (done) {
              break;
            }
            if (!message) {
              continue;
            }
            try {
              this.#processMessage(message);
            } catch (err2) {
              console.error("Unexpected error during message processing:", message, err2);
              if ("id" in message && message.id !== void 0) {
                this.#sendMessage({
                  jsonrpc: "2.0",
                  id: message.id,
                  error: {
                    code: -32700,
                    message: "Parse error"
                  }
                });
              }
            }
          }
        } finally {
          reader.releaseLock();
          this.#abortController.abort();
        }
      }
      async #processMessage(message) {
        if ("method" in message && "id" in message) {
          const response = await this.#tryCallRequestHandler(message.method, message.params);
          if ("error" in response) {
            console.error("Error handling request", message, response.error);
          }
          await this.#sendMessage({
            jsonrpc: "2.0",
            id: message.id,
            ...response
          });
        } else if ("method" in message) {
          const response = await this.#tryCallNotificationHandler(message.method, message.params);
          if ("error" in response) {
            console.error("Error handling notification", message, response.error);
          }
        } else if ("id" in message) {
          this.#handleResponse(message);
        } else {
          console.error("Invalid message", { message });
        }
      }
      async #tryCallRequestHandler(method, params) {
        try {
          const result = await this.#requestHandler(method, params);
          return { result: result ?? null };
        } catch (error40) {
          if (error40 instanceof RequestError) {
            return error40.toResult();
          }
          if (error40 instanceof external_exports.ZodError) {
            return RequestError.invalidParams(error40.format()).toResult();
          }
          let details;
          if (error40 instanceof Error) {
            details = error40.message;
          } else if (typeof error40 === "object" && error40 != null && "message" in error40 && typeof error40.message === "string") {
            details = error40.message;
          }
          try {
            return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
          } catch {
            return RequestError.internalError({ details }).toResult();
          }
        }
      }
      async #tryCallNotificationHandler(method, params) {
        try {
          await this.#notificationHandler(method, params);
          return { result: null };
        } catch (error40) {
          if (error40 instanceof RequestError) {
            return error40.toResult();
          }
          if (error40 instanceof external_exports.ZodError) {
            return RequestError.invalidParams(error40.format()).toResult();
          }
          let details;
          if (error40 instanceof Error) {
            details = error40.message;
          } else if (typeof error40 === "object" && error40 != null && "message" in error40 && typeof error40.message === "string") {
            details = error40.message;
          }
          try {
            return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
          } catch {
            return RequestError.internalError({ details }).toResult();
          }
        }
      }
      #handleResponse(response) {
        const pendingResponse = this.#pendingResponses.get(response.id);
        if (pendingResponse) {
          if ("result" in response) {
            pendingResponse.resolve(response.result);
          } else if ("error" in response) {
            pendingResponse.reject(response.error);
          }
          this.#pendingResponses.delete(response.id);
        } else {
          console.error("Got response to unknown request", response.id);
        }
      }
      async sendRequest(method, params) {
        const id = this.#nextRequestId++;
        const responsePromise = new Promise((resolve42, reject) => {
          this.#pendingResponses.set(id, { resolve: resolve42, 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(message) {
        this.#writeQueue = this.#writeQueue.then(async () => {
          const writer = this.#stream.writable.getWriter();
          try {
            await writer.write(message);
          } finally {
            writer.releaseLock();
          }
        }).catch((error40) => {
          console.error("ACP write error:", error40);
        });
        return this.#writeQueue;
      }
    };
    RequestError = class _RequestError extends Error {
      static {
        __name(this, "RequestError");
      }
      code;
      data;
      constructor(code2, message, data) {
        super(message);
        this.code = code2;
        this.name = "RequestError";
        this.data = data;
      }
      /**
       * Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
       */
      static parseError(data, additionalMessage) {
        return new _RequestError(-32700, `Parse error${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
      }
      /**
       * The JSON sent is not a valid Request object.
       */
      static invalidRequest(data, additionalMessage) {
        return new _RequestError(-32600, `Invalid request${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
      }
      /**
       * The method does not exist / is not available.
       */
      static methodNotFound(method) {
        return new _RequestError(-32601, `"Method not found": ${method}`, {
          method
        });
      }
      /**
       * Invalid method parameter(s).
       */
      static invalidParams(data, additionalMessage) {
        return new _RequestError(-32602, `Invalid params${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
      }
      /**
       * Internal JSON-RPC error.
       */
      static internalError(data, additionalMessage) {
        return new _RequestError(-32603, `Internal error${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
      }
      /**
       * Authentication required.
       */
      static authRequired(data, additionalMessage) {
        return new _RequestError(-32e3, `Authentication required${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
      }
      /**
       * Resource, such as a file, was not found
       */
      static resourceNotFound(uri) {
        return new _RequestError(-32002, `Resource not found${uri ? `: ${uri}` : ""}`, uri && { uri });
      }
      toResult() {
        return {
          error: {
            code: this.code,
            message: this.message,
            data: this.data
          }
        };
      }
      toErrorResponse() {
        return {
          code: this.code,
          message: this.message,
          data: this.data
        };
      }
    };
  }
});

// packages/channels/base/dist/AcpBridge.js
import { spawn as spawn9 } from "node:child_process";
import { Readable as Readable5, Writable } from "node:stream";
import { EventEmitter as EventEmitter12 } from "node:events";
var AcpBridge;
var init_AcpBridge = __esm({
  "packages/channels/base/dist/AcpBridge.js"() {
    "use strict";
    init_esbuild_shims();
    init_acp();
    AcpBridge = class extends EventEmitter12 {
      static {
        __name(this, "AcpBridge");
      }
      child = null;
      connection = null;
      options;
      _availableCommands = [];
      constructor(options2) {
        super();
        this.options = options2;
      }
      get availableCommands() {
        return this._availableCommands;
      }
      async start() {
        const { cliEntryPath, cwd: cwd6 } = this.options;
        const args2 = [cliEntryPath, "--acp"];
        if (this.options.model) {
          args2.push("--model", this.options.model);
        }
        this.child = spawn9(process.execPath, args2, {
          cwd: cwd6,
          stdio: ["pipe", "pipe", "pipe"],
          env: { ...process.env },
          shell: false
        });
        this.child.stderr?.on("data", (data) => {
          const msg = data.toString().trim();
          if (msg) {
            process.stderr.write(`[AcpBridge] ${msg}
`);
          }
        });
        this.child.on("exit", (code2, signal) => {
          process.stderr.write(`[AcpBridge] Process exited (code=${code2}, signal=${signal})
`);
          this.connection = null;
          this.child = null;
          this.emit("disconnected", code2, signal);
        });
        await new Promise((resolve42) => setTimeout(resolve42, 1e3));
        if (!this.child || this.child.killed) {
          throw new Error("ACP process failed to start");
        }
        const stdout2 = Readable5.toWeb(this.child.stdout);
        const stdin2 = Writable.toWeb(this.child.stdin);
        const stream5 = ndJsonStream(stdin2, stdout2);
        this.connection = new ClientSideConnection(() => ({
          sessionUpdate: /* @__PURE__ */ __name((params) => {
            this.handleSessionUpdate(params);
            return Promise.resolve();
          }, "sessionUpdate"),
          requestPermission: /* @__PURE__ */ __name(async (params) => {
            const options2 = Array.isArray(params.options) ? params.options : [];
            const optionId = options2.find((o3) => o3.optionId === "proceed_once")?.optionId || options2[0]?.optionId || "proceed_once";
            return { outcome: { outcome: "selected", optionId } };
          }, "requestPermission"),
          extNotification: /* @__PURE__ */ __name(async () => {
          }, "extNotification")
        }), stream5);
        await this.connection.initialize({
          protocolVersion: PROTOCOL_VERSION,
          clientCapabilities: {}
        });
      }
      async newSession(cwd6) {
        const conn = this.ensureConnection();
        const response = await conn.newSession({ cwd: cwd6, mcpServers: [] });
        return response.sessionId;
      }
      async loadSession(sessionId, cwd6) {
        const conn = this.ensureConnection();
        const response = await conn.loadSession({
          sessionId,
          cwd: cwd6,
          mcpServers: []
        });
        return response.sessionId;
      }
      async prompt(sessionId, text, options2) {
        const conn = this.ensureConnection();
        const chunks = [];
        const onChunk = /* @__PURE__ */ __name((sid, chunk) => {
          if (sid === sessionId)
            chunks.push(chunk);
        }, "onChunk");
        this.on("textChunk", onChunk);
        const prompt = [];
        if (options2?.imageBase64 && options2.imageMimeType) {
          prompt.push({
            type: "image",
            data: options2.imageBase64,
            mimeType: options2.imageMimeType
          });
        }
        prompt.push({ type: "text", text });
        try {
          await conn.prompt({
            sessionId,
            prompt
          });
        } finally {
          this.off("textChunk", onChunk);
        }
        return chunks.join("");
      }
      async cancelSession(sessionId) {
        const conn = this.ensureConnection();
        await conn.cancel({ sessionId });
      }
      stop() {
        if (this.child) {
          this.child.kill();
          this.child = null;
        }
        this.connection = null;
      }
      get isConnected() {
        return this.child !== null && !this.child.killed && this.child.exitCode === null;
      }
      handleSessionUpdate(params) {
        const { sessionId } = params;
        const update2 = params["update"];
        if (!update2)
          return;
        const type = update2["sessionUpdate"];
        switch (type) {
          case "agent_message_chunk": {
            const content = update2["content"];
            if (content?.type === "text" && content.text) {
              this.emit("textChunk", sessionId, content.text);
            }
            break;
          }
          case "tool_call": {
            const event = {
              sessionId,
              toolCallId: update2["toolCallId"],
              kind: update2["kind"] || "",
              title: update2["title"] || "",
              status: update2["status"] || "pending",
              rawInput: update2["rawInput"]
            };
            this.emit("toolCall", event);
            break;
          }
          case "available_commands_update": {
            if (Array.isArray(update2["availableCommands"])) {
              this._availableCommands = update2["availableCommands"];
            }
            break;
          }
          default:
            break;
        }
        this.emit("sessionUpdate", params);
      }
      ensureConnection() {
        if (!this.connection || !this.isConnected) {
          throw new Error("Not connected to ACP agent");
        }
        return this.connection;
      }
    };
  }
});

// packages/channels/base/dist/BlockStreamer.js
var BlockStreamer;
var init_BlockStreamer = __esm({
  "packages/channels/base/dist/BlockStreamer.js"() {
    "use strict";
    init_esbuild_shims();
    BlockStreamer = class {
      static {
        __name(this, "BlockStreamer");
      }
      buffer = "";
      idleTimer = null;
      sending = Promise.resolve();
      opts;
      /** Number of blocks emitted so far. */
      blockCount = 0;
      constructor(opts) {
        this.opts = opts;
      }
      /** Feed a new text chunk from the agent stream. */
      push(chunk) {
        this.buffer += chunk;
        this.clearIdleTimer();
        this.checkEmit();
        if (this.buffer.length > 0 && this.opts.idleMs > 0) {
          this.idleTimer = setTimeout(() => this.onIdle(), this.opts.idleMs);
        }
      }
      /** Flush all remaining buffered text. Awaits all pending sends. */
      async flush() {
        this.clearIdleTimer();
        if (this.buffer.length > 0) {
          this.emitBlock(this.buffer);
          this.buffer = "";
        }
        await this.sending;
      }
      // ---------------------------------------------------------------------------
      // Internal
      // ---------------------------------------------------------------------------
      checkEmit() {
        while (this.buffer.length >= this.opts.maxChars) {
          const bp = this.findBreakPoint(this.buffer, this.opts.maxChars);
          this.emitBlock(this.buffer.slice(0, bp));
          this.buffer = this.buffer.slice(bp);
        }
        if (this.buffer.length >= this.opts.minChars) {
          const bp = this.findBlockBoundary(this.buffer);
          if (bp > 0) {
            this.emitBlock(this.buffer.slice(0, bp));
            this.buffer = this.buffer.slice(bp);
          }
        }
      }
      onIdle() {
        this.idleTimer = null;
        if (this.buffer.length >= this.opts.minChars) {
          this.emitBlock(this.buffer);
          this.buffer = "";
        }
      }
      emitBlock(text) {
        const trimmed2 = text.trim();
        if (!trimmed2)
          return;
        this.blockCount++;
        this.sending = this.sending.then(() => this.opts.send(trimmed2)).catch(() => {
        });
      }
      /**
       * Find the last paragraph boundary (\n\n) in the buffer.
       * Returns the position after the boundary, or -1 if no suitable boundary
       * exists at or after minChars.
       */
      findBlockBoundary(text) {
        const last2 = text.lastIndexOf("\n\n");
        if (last2 < 0 || last2 < this.opts.minChars)
          return -1;
        return last2 + 2;
      }
      /**
       * Find the best break point at or before maxPos.
       * Prefers paragraph break > newline > space > maxPos.
       */
      findBreakPoint(text, maxPos) {
        const sub = text.slice(0, maxPos);
        const para = sub.lastIndexOf("\n\n");
        if (para > 0)
          return para + 2;
        const nl2 = sub.lastIndexOf("\n");
        if (nl2 > 0)
          return nl2 + 1;
        const sp = sub.lastIndexOf(" ");
        if (sp > 0)
          return sp + 1;
        return maxPos;
      }
      clearIdleTimer() {
        if (this.idleTimer !== null) {
          clearTimeout(this.idleTimer);
          this.idleTimer = null;
        }
      }
    };
  }
});

// packages/channels/base/dist/GroupGate.js
var GroupGate;
var init_GroupGate = __esm({
  "packages/channels/base/dist/GroupGate.js"() {
    "use strict";
    init_esbuild_shims();
    GroupGate = class {
      static {
        __name(this, "GroupGate");
      }
      policy;
      groups;
      constructor(policy = "disabled", groups = {}) {
        this.policy = policy;
        this.groups = groups;
      }
      /**
       * Full group check: policy + allowlist + mention gating.
       * Evaluation order:
       *   1. groupPolicy (disabled → drop)
       *   2. group allowlist (allowlist mode, no match → drop)
       *   3. mention gating (requireMention + not mentioned → drop silently)
       *
       * Mention gating runs before sender gate so that unmentioned messages
       * in groups don't trigger pairing flows.
       */
      check(envelope) {
        if (!envelope.isGroup) {
          return { allowed: true };
        }
        if (this.policy === "disabled") {
          return { allowed: false, reason: "disabled" };
        }
        if (this.policy === "allowlist") {
          if (!this.groups[envelope.chatId]) {
            return { allowed: false, reason: "not_allowlisted" };
          }
        }
        const groupConfig = this.groups[envelope.chatId] || this.groups["*"] || {};
        const requireMention = groupConfig.requireMention ?? true;
        if (requireMention && !envelope.isMentioned && !envelope.isReplyToBot) {
          return { allowed: false, reason: "mention_required" };
        }
        return { allowed: true };
      }
    };
  }
});

// packages/channels/base/dist/SenderGate.js
var SenderGate;
var init_SenderGate = __esm({
  "packages/channels/base/dist/SenderGate.js"() {
    "use strict";
    init_esbuild_shims();
    SenderGate = class {
      static {
        __name(this, "SenderGate");
      }
      policy;
      allowedUsers;
      pairingStore;
      constructor(policy, allowedUsers = [], pairingStore) {
        this.policy = policy;
        this.allowedUsers = new Set(allowedUsers);
        this.pairingStore = pairingStore || null;
      }
      check(senderId, senderName) {
        switch (this.policy) {
          case "open":
            return { allowed: true };
          case "allowlist":
            return { allowed: this.allowedUsers.has(senderId) };
          case "pairing": {
            if (this.allowedUsers.has(senderId)) {
              return { allowed: true };
            }
            if (this.pairingStore?.isApproved(senderId)) {
              return { allowed: true };
            }
            const code2 = this.pairingStore?.createRequest(senderId, senderName || senderId);
            return { allowed: false, pairingCode: code2 ?? null };
          }
          default:
            throw new Error(`Unknown sender policy: ${this.policy}`);
        }
      }
    };
  }
});

// packages/channels/base/dist/PairingStore.js
import * as crypto14 from "node:crypto";
import * as fs109 from "node:fs";
import * as path106 from "node:path";
import * as os36 from "node:os";
function generateCode() {
  let code2 = "";
  for (let i4 = 0; i4 < CODE_LENGTH; i4++) {
    code2 += SAFE_ALPHABET[crypto14.randomInt(SAFE_ALPHABET.length)];
  }
  return code2;
}
var SAFE_ALPHABET, CODE_LENGTH, EXPIRY_MS, MAX_PENDING, PairingStore;
var init_PairingStore = __esm({
  "packages/channels/base/dist/PairingStore.js"() {
    "use strict";
    init_esbuild_shims();
    SAFE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    CODE_LENGTH = 8;
    EXPIRY_MS = 60 * 60 * 1e3;
    MAX_PENDING = 3;
    PairingStore = class {
      static {
        __name(this, "PairingStore");
      }
      dir;
      pendingPath;
      allowlistPath;
      constructor(channelName) {
        this.dir = path106.join(os36.homedir(), ".qwen", "channels");
        this.pendingPath = path106.join(this.dir, `${channelName}-pairing.json`);
        this.allowlistPath = path106.join(this.dir, `${channelName}-allowlist.json`);
      }
      isApproved(senderId) {
        const list3 = this.readAllowlist();
        return list3.includes(senderId);
      }
      /**
       * Create a pairing request for an unknown sender.
       * Returns the code if created, or null if the pending cap is reached.
       * If the sender already has a non-expired pending request, returns that code.
       */
      createRequest(senderId, senderName) {
        const pending = this.readPending();
        const now = Date.now();
        const active = pending.filter((r5) => now - r5.createdAt < EXPIRY_MS);
        const existing = active.find((r5) => r5.senderId === senderId);
        if (existing) {
          return existing.code;
        }
        if (active.length >= MAX_PENDING) {
          return null;
        }
        const code2 = generateCode();
        active.push({ senderId, senderName, code: code2, createdAt: now });
        this.writePending(active);
        return code2;
      }
      /**
       * Approve a pairing request by code.
       * Returns the sender ID if found, or null if not found / expired.
       */
      approve(code2) {
        const pending = this.readPending();
        const now = Date.now();
        const idx = pending.findIndex((r5) => r5.code === code2.toUpperCase() && now - r5.createdAt < EXPIRY_MS);
        if (idx === -1)
          return null;
        const request4 = pending[idx];
        pending.splice(idx, 1);
        this.writePending(pending);
        const list3 = this.readAllowlist();
        if (!list3.includes(request4.senderId)) {
          list3.push(request4.senderId);
          this.writeAllowlist(list3);
        }
        return request4;
      }
      listPending() {
        const pending = this.readPending();
        const now = Date.now();
        return pending.filter((r5) => now - r5.createdAt < EXPIRY_MS);
      }
      getAllowlist() {
        return this.readAllowlist();
      }
      ensureDir() {
        if (!fs109.existsSync(this.dir)) {
          fs109.mkdirSync(this.dir, { recursive: true });
        }
      }
      readPending() {
        try {
          const data = fs109.readFileSync(this.pendingPath, "utf-8");
          return JSON.parse(data);
        } catch {
          return [];
        }
      }
      writePending(requests) {
        this.ensureDir();
        fs109.writeFileSync(this.pendingPath, JSON.stringify(requests, null, 2));
      }
      readAllowlist() {
        try {
          const data = fs109.readFileSync(this.allowlistPath, "utf-8");
          return JSON.parse(data);
        } catch {
          return [];
        }
      }
      writeAllowlist(list3) {
        this.ensureDir();
        fs109.writeFileSync(this.allowlistPath, JSON.stringify(list3, null, 2));
      }
    };
    __name(generateCode, "generateCode");
  }
});

// packages/channels/base/dist/SessionRouter.js
import { existsSync as existsSync31, readFileSync as readFileSync24, writeFileSync as writeFileSync16, unlinkSync as unlinkSync4 } from "node:fs";
var SessionRouter;
var init_SessionRouter = __esm({
  "packages/channels/base/dist/SessionRouter.js"() {
    "use strict";
    init_esbuild_shims();
    SessionRouter = class {
      static {
        __name(this, "SessionRouter");
      }
      toSession = /* @__PURE__ */ new Map();
      // routing key → session ID
      toTarget = /* @__PURE__ */ new Map();
      // session ID → target
      toCwd = /* @__PURE__ */ new Map();
      // session ID → cwd
      bridge;
      defaultCwd;
      defaultScope;
      channelScopes = /* @__PURE__ */ new Map();
      persistPath;
      constructor(bridge, defaultCwd, scope = "user", persistPath) {
        this.bridge = bridge;
        this.defaultCwd = defaultCwd;
        this.defaultScope = scope;
        this.persistPath = persistPath;
      }
      /** Replace the bridge instance (used after crash recovery restart). */
      setBridge(bridge) {
        this.bridge = bridge;
      }
      /** Set scope override for a specific channel. */
      setChannelScope(channelName, scope) {
        this.channelScopes.set(channelName, scope);
      }
      routingKey(channelName, senderId, chatId, threadId) {
        const scope = this.channelScopes.get(channelName) || this.defaultScope;
        switch (scope) {
          case "thread":
            return `${channelName}:${threadId || chatId}`;
          case "single":
            return `${channelName}:__single__`;
          case "user":
          default:
            return `${channelName}:${senderId}:${chatId}`;
        }
      }
      async resolve(channelName, senderId, chatId, threadId, cwd6) {
        const key = this.routingKey(channelName, senderId, chatId, threadId);
        const existing = this.toSession.get(key);
        if (existing) {
          return existing;
        }
        const sessionCwd = cwd6 || this.defaultCwd;
        const sessionId = await this.bridge.newSession(sessionCwd);
        this.toSession.set(key, sessionId);
        this.toTarget.set(sessionId, { channelName, senderId, chatId, threadId });
        this.toCwd.set(sessionId, sessionCwd);
        this.persist();
        return sessionId;
      }
      getTarget(sessionId) {
        return this.toTarget.get(sessionId);
      }
      hasSession(channelName, senderId, chatId) {
        const key = chatId ? this.routingKey(channelName, senderId, chatId) : `${channelName}:${senderId}`;
        if (chatId)
          return this.toSession.has(key);
        for (const k2 of this.toSession.keys()) {
          if (k2.startsWith(`${channelName}:${senderId}`))
            return true;
        }
        return false;
      }
      /**
       * Remove session(s) for the given sender. Returns the removed session IDs.
       */
      removeSession(channelName, senderId, chatId) {
        const removedIds = [];
        if (chatId) {
          const key = this.routingKey(channelName, senderId, chatId);
          const sessionId = this.deleteByKey(key);
          if (sessionId)
            removedIds.push(sessionId);
        } else {
          const prefix = `${channelName}:${senderId}`;
          for (const k2 of [...this.toSession.keys()]) {
            if (k2.startsWith(prefix)) {
              const sessionId = this.deleteByKey(k2);
              if (sessionId)
                removedIds.push(sessionId);
            }
          }
        }
        if (removedIds.length > 0)
          this.persist();
        return removedIds;
      }
      deleteByKey(key) {
        const sessionId = this.toSession.get(key);
        if (!sessionId)
          return null;
        this.toSession.delete(key);
        this.toTarget.delete(sessionId);
        this.toCwd.delete(sessionId);
        return sessionId;
      }
      /** Get all session entries for crash recovery. */
      getAll() {
        const entries = [];
        for (const [key, sessionId] of this.toSession) {
          const target = this.toTarget.get(sessionId);
          if (target) {
            entries.push({ key, sessionId, target });
          }
        }
        return entries;
      }
      /**
       * Restore session mappings from a previous bridge.
       * Called after bridge restart — attempts loadSession for each saved mapping.
       * Failed loads are silently dropped (new session on next message).
       */
      async restoreSessions() {
        if (!this.persistPath || !existsSync31(this.persistPath)) {
          return { restored: 0, failed: 0 };
        }
        let entries;
        try {
          entries = JSON.parse(readFileSync24(this.persistPath, "utf-8"));
        } catch {
          return { restored: 0, failed: 0 };
        }
        let restored = 0;
        let failed = 0;
        for (const [key, entry] of Object.entries(entries)) {
          try {
            const sessionId = await this.bridge.loadSession(entry.sessionId, entry.cwd);
            this.toSession.set(key, sessionId);
            this.toTarget.set(sessionId, entry.target);
            this.toCwd.set(sessionId, entry.cwd);
            restored++;
          } catch {
            failed++;
          }
        }
        if (failed > 0) {
          this.persist();
        }
        return { restored, failed };
      }
      /** Clear in-memory state and delete persist file. Used on clean shutdown. */
      clearAll() {
        this.toSession.clear();
        this.toTarget.clear();
        this.toCwd.clear();
        if (this.persistPath && existsSync31(this.persistPath)) {
          try {
            unlinkSync4(this.persistPath);
          } catch {
          }
        }
      }
      persist() {
        if (!this.persistPath)
          return;
        const data = {};
        for (const [key, sessionId] of this.toSession) {
          const target = this.toTarget.get(sessionId);
          if (target) {
            data[key] = {
              sessionId,
              target,
              cwd: this.toCwd.get(sessionId) || this.defaultCwd
            };
          }
        }
        try {
          writeFileSync16(this.persistPath, JSON.stringify(data, null, 2), "utf-8");
        } catch {
        }
      }
    };
  }
});

// packages/channels/base/dist/ChannelBase.js
var ChannelBase;
var init_ChannelBase = __esm({
  "packages/channels/base/dist/ChannelBase.js"() {
    "use strict";
    init_esbuild_shims();
    init_BlockStreamer();
    init_GroupGate();
    init_SenderGate();
    init_PairingStore();
    init_SessionRouter();
    ChannelBase = class {
      static {
        __name(this, "ChannelBase");
      }
      config;
      bridge;
      groupGate;
      gate;
      router;
      name;
      /** Resolved proxy URL, available to subclasses for adapter-specific clients. */
      proxy;
      instructedSessions = /* @__PURE__ */ new Set();
      commands = /* @__PURE__ */ new Map();
      /** Per-session promise chain to serialize prompt + send (followup mode). */
      sessionQueues = /* @__PURE__ */ new Map();
      /** Per-session active prompt tracking for dispatch modes. */
      activePrompts = /* @__PURE__ */ new Map();
      /** Per-session message buffer for collect mode. */
      collectBuffers = /* @__PURE__ */ new Map();
      constructor(name4, config2, bridge, options2) {
        this.name = name4;
        this.config = config2;
        this.bridge = bridge;
        this.proxy = options2?.proxy;
        this.groupGate = new GroupGate(config2.groupPolicy, config2.groups);
        const pairingStore = config2.senderPolicy === "pairing" ? new PairingStore(name4) : void 0;
        this.gate = new SenderGate(config2.senderPolicy, config2.allowedUsers, pairingStore);
        this.router = options2?.router || new SessionRouter(bridge, config2.cwd, config2.sessionScope);
        this.registerSharedCommands();
        if (!options2?.router) {
          bridge.on("toolCall", (event) => {
            const target = this.router.getTarget(event.sessionId);
            if (target) {
              this.onToolCall(target.chatId, event);
            }
          });
        }
      }
      /** Replace the bridge instance (used after crash recovery restart). */
      setBridge(bridge) {
        this.bridge = bridge;
      }
      onToolCall(_chatId, _event) {
      }
      /**
       * Called when a prompt actually begins processing (inside the session queue).
       * Override to show a platform-specific working indicator (e.g., typing, reaction).
       * Not called for buffered messages (collect mode) or gated/blocked messages.
       */
      onPromptStart(_chatId, _sessionId, _messageId) {
      }
      /**
       * Called when a prompt finishes (response sent or cancelled).
       * Override to hide the working indicator.
       */
      onPromptEnd(_chatId, _sessionId, _messageId) {
      }
      /**
       * Called for each text chunk as the agent streams its response.
       * Override to implement progressive display (e.g., updating an AI card in-place).
       * Default: no-op (chunks are collected internally and delivered via onResponseComplete).
       */
      onResponseChunk(_chatId, _chunk, _sessionId) {
      }
      /**
       * Called when the agent's full response is ready.
       * Override to customize delivery (e.g., finalize an AI card).
       * Default: calls sendMessage() with the full response text.
       */
      async onResponseComplete(chatId, fullText, _sessionId) {
        await this.sendMessage(chatId, fullText);
      }
      /**
       * Register a slash command handler. Subclasses can call this to add
       * platform-specific commands (e.g., /start for Telegram).
       * Overrides shared commands if the same name is registered.
       */
      registerCommand(name4, handler) {
        this.commands.set(name4.toLowerCase(), handler);
      }
      /** Register shared slash commands. Called from constructor. */
      registerSharedCommands() {
        const clearHandler = /* @__PURE__ */ __name(async (envelope) => {
          const removedIds = this.router.removeSession(this.name, envelope.senderId, envelope.chatId);
          if (removedIds.length > 0) {
            for (const id of removedIds) {
              this.instructedSessions.delete(id);
            }
            await this.sendMessage(envelope.chatId, "Session cleared. Your next message will start a fresh conversation.");
          } else {
            await this.sendMessage(envelope.chatId, "No active session to clear.");
          }
          return true;
        }, "clearHandler");
        this.registerCommand("clear", clearHandler);
        this.registerCommand("reset", clearHandler);
        this.registerCommand("new", clearHandler);
        this.registerCommand("help", async (envelope) => {
          const lines = [
            "Commands:",
            "/help \u2014 Show this help",
            "/clear \u2014 Clear your session (aliases: /reset, /new)",
            "/status \u2014 Show session info"
          ];
          const sharedCmds = /* @__PURE__ */ new Set(["help", "clear", "reset", "new", "status"]);
          const platformCmds = [...this.commands.keys()].filter((c4) => !sharedCmds.has(c4));
          if (platformCmds.length > 0) {
            for (const cmd of platformCmds) {
              lines.push(`/${cmd}`);
            }
          }
          const agentCommands = this.bridge.availableCommands;
          if (agentCommands.length > 0) {
            lines.push("", "Agent commands (forwarded to Qwen Code):");
            for (const cmd of agentCommands) {
              lines.push(`/${cmd.name} \u2014 ${cmd.description}`);
            }
          }
          lines.push("", "Send any text to chat with the agent.");
          await this.sendMessage(envelope.chatId, lines.join("\n"));
          return true;
        });
        this.registerCommand("status", async (envelope) => {
          const hasSession = this.router.hasSession(this.name, envelope.senderId, envelope.chatId);
          const policy = this.config.senderPolicy;
          const lines = [
            `Session: ${hasSession ? "active" : "none"}`,
            `Access: ${policy}`,
            `Channel: ${this.name}`
          ];
          await this.sendMessage(envelope.chatId, lines.join("\n"));
          return true;
        });
      }
      /** Check if a message text matches a registered local command. */
      isLocalCommand(text) {
        const parsed = this.parseCommand(text);
        return parsed !== null && this.commands.has(parsed.command);
      }
      /**
       * Parse a slash command from message text.
       * Returns { command, args } or null if not a slash command.
       */
      parseCommand(text) {
        if (!text.startsWith("/"))
          return null;
        const match2 = text.match(/^\/([a-zA-Z0-9_]+)(?:@\S+)?\s*(.*)/s);
        if (!match2)
          return null;
        return { command: match2[1].toLowerCase(), args: match2[2].trim() };
      }
      async handleInbound(envelope) {
        const groupResult = this.groupGate.check(envelope);
        if (!groupResult.allowed) {
          return;
        }
        const result = this.gate.check(envelope.senderId, envelope.senderName);
        if (!result.allowed) {
          if (result.pairingCode !== void 0) {
            await this.onPairingRequired(envelope.chatId, result.pairingCode);
          }
          return;
        }
        const parsed = this.parseCommand(envelope.text);
        if (parsed) {
          const handler = this.commands.get(parsed.command);
          if (handler) {
            const handled = await handler(envelope, parsed.args);
            if (handled)
              return;
          }
        }
        const sessionId = await this.router.resolve(this.name, envelope.senderId, envelope.chatId, envelope.threadId, this.config.cwd);
        let promptText = envelope.text;
        if (envelope.referencedText) {
          promptText = `[Replying to: "${envelope.referencedText}"]

${promptText}`;
        }
        let imageBase64 = envelope.imageBase64;
        let imageMimeType = envelope.imageMimeType;
        if (envelope.attachments?.length) {
          const filePaths = [];
          for (const att of envelope.attachments) {
            if (att.type === "image" && att.data && !imageBase64) {
              imageBase64 = att.data;
              imageMimeType = att.mimeType;
            } else if (att.filePath) {
              const label = att.type === "file" ? "file" : att.type;
              const name4 = att.fileName ? ` "${att.fileName}"` : "";
              filePaths.push(`User sent a ${label}${name4}. It has been saved to: ${att.filePath}`);
            }
          }
          if (filePaths.length > 0) {
            promptText = promptText + "\n\n" + filePaths.join("\n");
          }
        }
        if (this.config.instructions && !this.instructedSessions.has(sessionId)) {
          promptText = `${this.config.instructions}

${promptText}`;
          this.instructedSessions.add(sessionId);
        }
        const groupCfg = envelope.isGroup ? this.config.groups[envelope.chatId] || this.config.groups["*"] : void 0;
        const mode = groupCfg?.dispatchMode || this.config.dispatchMode || "steer";
        const active = this.activePrompts.get(sessionId);
        if (active) {
          switch (mode) {
            case "collect": {
              let buffer = this.collectBuffers.get(sessionId);
              if (!buffer) {
                buffer = [];
                this.collectBuffers.set(sessionId, buffer);
              }
              buffer.push({ text: promptText, envelope });
              return;
            }
            case "steer": {
              active.cancelled = true;
              await this.bridge.cancelSession(sessionId).catch(() => {
              });
              await active.done;
              promptText = `[The user sent a new message while you were working. Their previous request has been cancelled.]

${promptText}`;
              break;
            }
            case "followup": {
              break;
            }
            default: {
              const _exhaustive = mode;
              throw new Error(`Unknown dispatch mode: ${_exhaustive}`);
            }
          }
        }
        const prev = this.sessionQueues.get(sessionId) ?? Promise.resolve();
        const useBlockStreaming = this.config.blockStreaming === "on";
        const current = prev.then(async () => {
          let doneResolve = /* @__PURE__ */ __name(() => {
          }, "doneResolve");
          const done = new Promise((r5) => {
            doneResolve = r5;
          });
          const promptState = { cancelled: false, done, resolve: doneResolve };
          this.activePrompts.set(sessionId, promptState);
          this.onPromptStart(envelope.chatId, sessionId, envelope.messageId);
          const streamer = useBlockStreaming ? new BlockStreamer({
            minChars: this.config.blockStreamingChunk?.minChars ?? 400,
            maxChars: this.config.blockStreamingChunk?.maxChars ?? 1e3,
            idleMs: this.config.blockStreamingCoalesce?.idleMs ?? 1500,
            send: /* @__PURE__ */ __name((text) => this.sendMessage(envelope.chatId, text), "send")
          }) : null;
          const onChunk = /* @__PURE__ */ __name((sid, chunk) => {
            if (sid === sessionId) {
              this.onResponseChunk(envelope.chatId, chunk, sessionId);
              streamer?.push(chunk);
            }
          }, "onChunk");
          this.bridge.on("textChunk", onChunk);
          try {
            const response = await this.bridge.prompt(sessionId, promptText, {
              imageBase64,
              imageMimeType
            });
            if (!promptState.cancelled && response) {
              if (streamer) {
                await streamer.flush();
              } else {
                await this.onResponseComplete(envelope.chatId, response, sessionId);
              }
            }
          } finally {
            this.bridge.off("textChunk", onChunk);
            this.onPromptEnd(envelope.chatId, sessionId, envelope.messageId);
            this.activePrompts.delete(sessionId);
            promptState.resolve();
            const buffer = this.collectBuffers.get(sessionId);
            if (buffer && buffer.length > 0) {
              this.collectBuffers.delete(sessionId);
              const coalesced = buffer.map((b2) => b2.text).join("\n\n");
              const lastEnvelope = buffer[buffer.length - 1].envelope;
              const syntheticEnvelope = {
                ...lastEnvelope,
                text: coalesced,
                // Clear attachments/references — already resolved in original text
                referencedText: void 0,
                attachments: void 0,
                imageBase64: void 0,
                imageMimeType: void 0
              };
              this.handleInbound(syntheticEnvelope).catch(() => {
              });
            }
          }
        });
        this.sessionQueues.set(sessionId, current.catch(() => {
        }));
        await current;
      }
      async onPairingRequired(chatId, code2) {
        if (code2) {
          await this.sendMessage(chatId, `Your pairing code is: ${code2}

Ask the bot operator to approve you with:
  qwen channel pairing approve ${this.name} ${code2}`);
        } else {
          await this.sendMessage(chatId, "Too many pending pairing requests. Please try again later.");
        }
      }
    };
  }
});

// packages/channels/base/dist/index.js
var init_dist5 = __esm({
  "packages/channels/base/dist/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_AcpBridge();
    init_BlockStreamer();
    init_ChannelBase();
    init_PairingStore();
    init_GroupGate();
    init_SenderGate();
    init_SessionRouter();
  }
});

// node_modules/grammy/out/filter.js
var require_filter2 = __commonJS({
  "node_modules/grammy/out/filter.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.matchFilter = matchFilter;
    exports2.parse = parse17;
    exports2.preprocess = preprocess3;
    var filterQueryCache = /* @__PURE__ */ new Map();
    function matchFilter(filter5) {
      var _a7;
      const queries = Array.isArray(filter5) ? filter5 : [filter5];
      const key = queries.join(",");
      const predicate = (_a7 = filterQueryCache.get(key)) !== null && _a7 !== void 0 ? _a7 : (() => {
        const parsed = parse17(queries);
        const pred = compile2(parsed);
        filterQueryCache.set(key, pred);
        return pred;
      })();
      return (ctx) => predicate(ctx);
    }
    __name(matchFilter, "matchFilter");
    function parse17(filter5) {
      return Array.isArray(filter5) ? filter5.map((q2) => q2.split(":")) : [filter5.split(":")];
    }
    __name(parse17, "parse");
    function compile2(parsed) {
      const preprocessed = parsed.flatMap((q2) => check2(q2, preprocess3(q2)));
      const ltree = treeify(preprocessed);
      const predicate = arborist(ltree);
      return (ctx) => !!predicate(ctx.update, ctx);
    }
    __name(compile2, "compile");
    function preprocess3(filter5) {
      const valid = UPDATE_KEYS;
      const expanded = [filter5].flatMap((q2) => {
        const [l1, l22, l3] = q2;
        if (!(l1 in L1_SHORTCUTS))
          return [q2];
        if (!l1 && !l22 && !l3)
          return [q2];
        const targets = L1_SHORTCUTS[l1];
        const expanded2 = targets.map((s5) => [s5, l22, l3]);
        if (l22 === void 0)
          return expanded2;
        if (l22 in L2_SHORTCUTS && (l22 || l3))
          return expanded2;
        return expanded2.filter(([s5]) => {
          var _a7;
          return !!((_a7 = valid[s5]) === null || _a7 === void 0 ? void 0 : _a7[l22]);
        });
      }).flatMap((q2) => {
        const [l1, l22, l3] = q2;
        if (!(l22 in L2_SHORTCUTS))
          return [q2];
        if (!l22 && !l3)
          return [q2];
        const targets = L2_SHORTCUTS[l22];
        const expanded2 = targets.map((s5) => [l1, s5, l3]);
        if (l3 === void 0)
          return expanded2;
        return expanded2.filter(([, s5]) => {
          var _a7, _b2;
          return !!((_b2 = (_a7 = valid[l1]) === null || _a7 === void 0 ? void 0 : _a7[s5]) === null || _b2 === void 0 ? void 0 : _b2[l3]);
        });
      });
      if (expanded.length === 0) {
        throw new Error(`Shortcuts in '${filter5.join(":")}' do not expand to any valid filter query`);
      }
      return expanded;
    }
    __name(preprocess3, "preprocess");
    function check2(original, preprocessed) {
      if (preprocessed.length === 0)
        throw new Error("Empty filter query given");
      const errors = preprocessed.map(checkOne).filter((r5) => r5 !== true);
      if (errors.length === 0)
        return preprocessed;
      else if (errors.length === 1)
        throw new Error(errors[0]);
      else {
        throw new Error(`Invalid filter query '${original.join(":")}'. There are ${errors.length} errors after expanding the contained shortcuts: ${errors.join("; ")}`);
      }
    }
    __name(check2, "check");
    function checkOne(filter5) {
      const [l1, l22, l3, ...n3] = filter5;
      if (l1 === void 0)
        return "Empty filter query given";
      if (!(l1 in UPDATE_KEYS)) {
        const permitted = Object.keys(UPDATE_KEYS);
        return `Invalid L1 filter '${l1}' given in '${filter5.join(":")}'. Permitted values are: ${permitted.map((k2) => `'${k2}'`).join(", ")}.`;
      }
      if (l22 === void 0)
        return true;
      const l1Obj = UPDATE_KEYS[l1];
      if (!(l22 in l1Obj)) {
        const permitted = Object.keys(l1Obj);
        return `Invalid L2 filter '${l22}' given in '${filter5.join(":")}'. Permitted values are: ${permitted.map((k2) => `'${k2}'`).join(", ")}.`;
      }
      if (l3 === void 0)
        return true;
      const l2Obj = l1Obj[l22];
      if (!(l3 in l2Obj)) {
        const permitted = Object.keys(l2Obj);
        return `Invalid L3 filter '${l3}' given in '${filter5.join(":")}'. ${permitted.length === 0 ? `No further filtering is possible after '${l1}:${l22}'.` : `Permitted values are: ${permitted.map((k2) => `'${k2}'`).join(", ")}.`}`;
      }
      if (n3.length === 0)
        return true;
      return `Cannot filter further than three levels, ':${n3.join(":")}' is invalid!`;
    }
    __name(checkOne, "checkOne");
    function treeify(paths) {
      var _a7, _b2;
      const tree = {};
      for (const [l1, l22, l3] of paths) {
        const subtree = (_a7 = tree[l1]) !== null && _a7 !== void 0 ? _a7 : tree[l1] = {};
        if (l22 !== void 0) {
          const set2 = (_b2 = subtree[l22]) !== null && _b2 !== void 0 ? _b2 : subtree[l22] = /* @__PURE__ */ new Set();
          if (l3 !== void 0)
            set2.add(l3);
        }
      }
      return tree;
    }
    __name(treeify, "treeify");
    function or2(left3, right3) {
      return (obj, ctx) => left3(obj, ctx) || right3(obj, ctx);
    }
    __name(or2, "or");
    function concat2(get4, test2) {
      return (obj, ctx) => {
        const nextObj = get4(obj, ctx);
        return nextObj && test2(nextObj, ctx);
      };
    }
    __name(concat2, "concat");
    function leaf(pred) {
      return (obj, ctx) => pred(obj, ctx) != null;
    }
    __name(leaf, "leaf");
    function arborist(tree) {
      const l1Predicates = Object.entries(tree).map(([l1, subtree]) => {
        const l1Pred = /* @__PURE__ */ __name((obj) => obj[l1], "l1Pred");
        const l2Predicates = Object.entries(subtree).map(([l22, set2]) => {
          const l2Pred = /* @__PURE__ */ __name((obj) => obj[l22], "l2Pred");
          const l3Predicates = Array.from(set2).map((l3) => {
            const l3Pred = l3 === "me" ? (obj, ctx) => {
              const me2 = ctx.me.id;
              return testMaybeArray(obj, (u2) => u2.id === me2);
            } : (obj) => testMaybeArray(obj, (e4) => e4[l3] || e4.type === l3);
            return l3Pred;
          });
          return l3Predicates.length === 0 ? leaf(l2Pred) : concat2(l2Pred, l3Predicates.reduce(or2));
        });
        return l2Predicates.length === 0 ? leaf(l1Pred) : concat2(l1Pred, l2Predicates.reduce(or2));
      });
      if (l1Predicates.length === 0) {
        throw new Error("Cannot create filter function for empty query");
      }
      return l1Predicates.reduce(or2);
    }
    __name(arborist, "arborist");
    function testMaybeArray(t5, pred) {
      const p2 = /* @__PURE__ */ __name((x3) => x3 != null && pred(x3), "p");
      return Array.isArray(t5) ? t5.some(p2) : p2(t5);
    }
    __name(testMaybeArray, "testMaybeArray");
    var ENTITY_KEYS = {
      mention: {},
      hashtag: {},
      cashtag: {},
      bot_command: {},
      url: {},
      email: {},
      phone_number: {},
      bold: {},
      italic: {},
      underline: {},
      strikethrough: {},
      spoiler: {},
      blockquote: {},
      expandable_blockquote: {},
      code: {},
      pre: {},
      text_link: {},
      text_mention: {},
      custom_emoji: {}
    };
    var USER_KEYS = {
      me: {},
      is_bot: {},
      is_premium: {},
      added_to_attachment_menu: {}
    };
    var FORWARD_ORIGIN_KEYS = {
      user: {},
      hidden_user: {},
      chat: {},
      channel: {}
    };
    var STICKER_KEYS = {
      is_video: {},
      is_animated: {},
      premium_animation: {}
    };
    var REACTION_KEYS = {
      emoji: {},
      custom_emoji: {},
      paid: {}
    };
    var GIFT_INFO_KEYS = {
      can_be_upgraded: {},
      is_upgrade_separate: {},
      is_private: {}
    };
    var COMMON_MESSAGE_KEYS = {
      forward_origin: FORWARD_ORIGIN_KEYS,
      is_topic_message: {},
      is_automatic_forward: {},
      business_connection_id: {},
      text: {},
      animation: {},
      audio: {},
      document: {},
      paid_media: {},
      photo: {},
      sticker: STICKER_KEYS,
      story: {},
      video: {},
      video_note: {},
      voice: {},
      contact: {},
      dice: {},
      game: {},
      poll: {},
      venue: {},
      location: {},
      entities: ENTITY_KEYS,
      caption_entities: ENTITY_KEYS,
      caption: {},
      link_preview_options: {
        url: {},
        prefer_small_media: {},
        prefer_large_media: {},
        show_above_text: {}
      },
      effect_id: {},
      paid_star_count: {},
      has_media_spoiler: {},
      new_chat_title: {},
      new_chat_photo: {},
      delete_chat_photo: {},
      message_auto_delete_timer_changed: {},
      pinned_message: {},
      invoice: {},
      proximity_alert_triggered: {},
      chat_background_set: {},
      giveaway_created: {},
      giveaway: { only_new_members: {}, has_public_winners: {} },
      giveaway_winners: { only_new_members: {}, was_refunded: {} },
      giveaway_completed: {},
      gift: GIFT_INFO_KEYS,
      gift_upgrade_sent: GIFT_INFO_KEYS,
      unique_gift: { transfer_star_count: {} },
      paid_message_price_changed: {},
      video_chat_scheduled: {},
      video_chat_started: {},
      video_chat_ended: {},
      video_chat_participants_invited: {},
      web_app_data: {}
    };
    var MESSAGE_KEYS = {
      ...COMMON_MESSAGE_KEYS,
      direct_messages_topic: {},
      chat_owner_left: { new_owner: {} },
      chat_owner_changd: {},
      new_chat_members: USER_KEYS,
      left_chat_member: USER_KEYS,
      group_chat_created: {},
      supergroup_chat_created: {},
      migrate_to_chat_id: {},
      migrate_from_chat_id: {},
      successful_payment: {},
      refunded_payment: {},
      users_shared: {},
      chat_shared: {},
      connected_website: {},
      write_access_allowed: {},
      passport_data: {},
      boost_added: {},
      forum_topic_created: { is_name_implicit: {} },
      forum_topic_edited: { name: {}, icon_custom_emoji_id: {} },
      forum_topic_closed: {},
      forum_topic_reopened: {},
      general_forum_topic_hidden: {},
      general_forum_topic_unhidden: {},
      checklist: { others_can_add_tasks: {}, others_can_mark_tasks_as_done: {} },
      checklist_tasks_done: {},
      checklist_tasks_added: {},
      suggested_post_info: {},
      suggested_post_approved: {},
      suggested_post_approval_failed: {},
      suggested_post_declined: {},
      suggested_post_paid: {},
      suggested_post_refunded: {},
      sender_boost_count: {}
    };
    var CHANNEL_POST_KEYS = {
      ...COMMON_MESSAGE_KEYS,
      channel_chat_created: {},
      direct_message_price_changed: {},
      is_paid_post: {}
    };
    var BUSINESS_CONNECTION_KEYS = {
      can_reply: {},
      is_enabled: {}
    };
    var MESSAGE_REACTION_KEYS = {
      old_reaction: REACTION_KEYS,
      new_reaction: REACTION_KEYS
    };
    var MESSAGE_REACTION_COUNT_UPDATED_KEYS = {
      reactions: REACTION_KEYS
    };
    var CALLBACK_QUERY_KEYS = { data: {}, game_short_name: {} };
    var CHAT_MEMBER_UPDATED_KEYS = { from: USER_KEYS };
    var UPDATE_KEYS = {
      message: MESSAGE_KEYS,
      edited_message: MESSAGE_KEYS,
      channel_post: CHANNEL_POST_KEYS,
      edited_channel_post: CHANNEL_POST_KEYS,
      business_connection: BUSINESS_CONNECTION_KEYS,
      business_message: MESSAGE_KEYS,
      edited_business_message: MESSAGE_KEYS,
      deleted_business_messages: {},
      inline_query: {},
      chosen_inline_result: {},
      callback_query: CALLBACK_QUERY_KEYS,
      shipping_query: {},
      pre_checkout_query: {},
      poll: {},
      poll_answer: {},
      my_chat_member: CHAT_MEMBER_UPDATED_KEYS,
      chat_member: CHAT_MEMBER_UPDATED_KEYS,
      chat_join_request: {},
      message_reaction: MESSAGE_REACTION_KEYS,
      message_reaction_count: MESSAGE_REACTION_COUNT_UPDATED_KEYS,
      chat_boost: {},
      removed_chat_boost: {},
      purchased_paid_media: {}
    };
    var L1_SHORTCUTS = {
      "": ["message", "channel_post"],
      msg: ["message", "channel_post"],
      edit: ["edited_message", "edited_channel_post"]
    };
    var L2_SHORTCUTS = {
      "": ["entities", "caption_entities"],
      media: ["photo", "video"],
      file: [
        "photo",
        "animation",
        "audio",
        "document",
        "video",
        "video_note",
        "voice",
        "sticker"
      ]
    };
  }
});

// node_modules/grammy/out/context.js
var require_context = __commonJS({
  "node_modules/grammy/out/context.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Context = void 0;
    var filter_js_1 = require_filter2();
    var checker = {
      filterQuery(filter5) {
        const pred = (0, filter_js_1.matchFilter)(filter5);
        return (ctx) => pred(ctx);
      },
      text(trigger) {
        const hasText = checker.filterQuery([":text", ":caption"]);
        const trg = triggerFn(trigger);
        return (ctx) => {
          var _a7, _b2;
          if (!hasText(ctx))
            return false;
          const msg = (_a7 = ctx.message) !== null && _a7 !== void 0 ? _a7 : ctx.channelPost;
          const txt = (_b2 = msg.text) !== null && _b2 !== void 0 ? _b2 : msg.caption;
          return match2(ctx, txt, trg);
        };
      },
      command(command2) {
        const hasEntities = checker.filterQuery(":entities:bot_command");
        const atCommands = /* @__PURE__ */ new Set();
        const noAtCommands = /* @__PURE__ */ new Set();
        toArray2(command2).forEach((cmd) => {
          if (cmd.startsWith("/")) {
            throw new Error(`Do not include '/' when registering command handlers (use '${cmd.substring(1)}' not '${cmd}')`);
          }
          const set2 = cmd.includes("@") ? atCommands : noAtCommands;
          set2.add(cmd);
        });
        return (ctx) => {
          var _a7, _b2;
          if (!hasEntities(ctx))
            return false;
          const msg = (_a7 = ctx.message) !== null && _a7 !== void 0 ? _a7 : ctx.channelPost;
          const txt = (_b2 = msg.text) !== null && _b2 !== void 0 ? _b2 : msg.caption;
          return msg.entities.some((e4) => {
            if (e4.type !== "bot_command")
              return false;
            if (e4.offset !== 0)
              return false;
            const cmd = txt.substring(1, e4.length);
            if (noAtCommands.has(cmd) || atCommands.has(cmd)) {
              ctx.match = txt.substring(cmd.length + 1).trimStart();
              return true;
            }
            const index = cmd.indexOf("@");
            if (index === -1)
              return false;
            const atTarget = cmd.substring(index + 1).toLowerCase();
            const username = ctx.me.username.toLowerCase();
            if (atTarget !== username)
              return false;
            const atCommand = cmd.substring(0, index);
            if (noAtCommands.has(atCommand)) {
              ctx.match = txt.substring(cmd.length + 1).trimStart();
              return true;
            }
            return false;
          });
        };
      },
      reaction(reaction) {
        const hasMessageReaction = checker.filterQuery("message_reaction");
        const normalized2 = typeof reaction === "string" ? [{ type: "emoji", emoji: reaction }] : (Array.isArray(reaction) ? reaction : [reaction]).map((emoji4) => typeof emoji4 === "string" ? { type: "emoji", emoji: emoji4 } : emoji4);
        const emoji3 = new Set(normalized2.filter((r5) => r5.type === "emoji").map((r5) => r5.emoji));
        const customEmoji = new Set(normalized2.filter((r5) => r5.type === "custom_emoji").map((r5) => r5.custom_emoji_id));
        const paid = normalized2.some((r5) => r5.type === "paid");
        return (ctx) => {
          if (!hasMessageReaction(ctx))
            return false;
          const { old_reaction, new_reaction } = ctx.messageReaction;
          for (const reaction2 of new_reaction) {
            let isOld = false;
            if (reaction2.type === "emoji") {
              for (const old of old_reaction) {
                if (old.type !== "emoji")
                  continue;
                if (old.emoji === reaction2.emoji) {
                  isOld = true;
                  break;
                }
              }
            } else if (reaction2.type === "custom_emoji") {
              for (const old of old_reaction) {
                if (old.type !== "custom_emoji")
                  continue;
                if (old.custom_emoji_id === reaction2.custom_emoji_id) {
                  isOld = true;
                  break;
                }
              }
            } else if (reaction2.type === "paid") {
              for (const old of old_reaction) {
                if (old.type !== "paid")
                  continue;
                isOld = true;
                break;
              }
            } else {
            }
            if (isOld)
              continue;
            if (reaction2.type === "emoji") {
              if (emoji3.has(reaction2.emoji))
                return true;
            } else if (reaction2.type === "custom_emoji") {
              if (customEmoji.has(reaction2.custom_emoji_id))
                return true;
            } else if (reaction2.type === "paid") {
              if (paid)
                return true;
            } else {
              return true;
            }
          }
          return false;
        };
      },
      chatType(chatType) {
        const set2 = new Set(toArray2(chatType));
        return (ctx) => {
          var _a7;
          return ((_a7 = ctx.chat) === null || _a7 === void 0 ? void 0 : _a7.type) !== void 0 && set2.has(ctx.chat.type);
        };
      },
      callbackQuery(trigger) {
        const hasCallbackQuery = checker.filterQuery("callback_query:data");
        const trg = triggerFn(trigger);
        return (ctx) => hasCallbackQuery(ctx) && match2(ctx, ctx.callbackQuery.data, trg);
      },
      gameQuery(trigger) {
        const hasGameQuery = checker.filterQuery("callback_query:game_short_name");
        const trg = triggerFn(trigger);
        return (ctx) => hasGameQuery(ctx) && match2(ctx, ctx.callbackQuery.game_short_name, trg);
      },
      inlineQuery(trigger) {
        const hasInlineQuery = checker.filterQuery("inline_query");
        const trg = triggerFn(trigger);
        return (ctx) => hasInlineQuery(ctx) && match2(ctx, ctx.inlineQuery.query, trg);
      },
      chosenInlineResult(trigger) {
        const hasChosenInlineResult = checker.filterQuery("chosen_inline_result");
        const trg = triggerFn(trigger);
        return (ctx) => hasChosenInlineResult(ctx) && match2(ctx, ctx.chosenInlineResult.result_id, trg);
      },
      preCheckoutQuery(trigger) {
        const hasPreCheckoutQuery = checker.filterQuery("pre_checkout_query");
        const trg = triggerFn(trigger);
        return (ctx) => hasPreCheckoutQuery(ctx) && match2(ctx, ctx.preCheckoutQuery.invoice_payload, trg);
      },
      shippingQuery(trigger) {
        const hasShippingQuery = checker.filterQuery("shipping_query");
        const trg = triggerFn(trigger);
        return (ctx) => hasShippingQuery(ctx) && match2(ctx, ctx.shippingQuery.invoice_payload, trg);
      }
    };
    var Context = class _Context {
      static {
        __name(this, "Context");
      }
      constructor(update2, api, me2) {
        this.update = update2;
        this.api = api;
        this.me = me2;
      }
      // UPDATE SHORTCUTS
      // Keep in sync with types in `filter.ts`.
      /** Alias for `ctx.update.message` */
      get message() {
        return this.update.message;
      }
      /** Alias for `ctx.update.edited_message` */
      get editedMessage() {
        return this.update.edited_message;
      }
      /** Alias for `ctx.update.channel_post` */
      get channelPost() {
        return this.update.channel_post;
      }
      /** Alias for `ctx.update.edited_channel_post` */
      get editedChannelPost() {
        return this.update.edited_channel_post;
      }
      /** Alias for `ctx.update.business_connection` */
      get businessConnection() {
        return this.update.business_connection;
      }
      /** Alias for `ctx.update.business_message` */
      get businessMessage() {
        return this.update.business_message;
      }
      /** Alias for `ctx.update.edited_business_message` */
      get editedBusinessMessage() {
        return this.update.edited_business_message;
      }
      /** Alias for `ctx.update.deleted_business_messages` */
      get deletedBusinessMessages() {
        return this.update.deleted_business_messages;
      }
      /** Alias for `ctx.update.message_reaction` */
      get messageReaction() {
        return this.update.message_reaction;
      }
      /** Alias for `ctx.update.message_reaction_count` */
      get messageReactionCount() {
        return this.update.message_reaction_count;
      }
      /** Alias for `ctx.update.inline_query` */
      get inlineQuery() {
        return this.update.inline_query;
      }
      /** Alias for `ctx.update.chosen_inline_result` */
      get chosenInlineResult() {
        return this.update.chosen_inline_result;
      }
      /** Alias for `ctx.update.callback_query` */
      get callbackQuery() {
        return this.update.callback_query;
      }
      /** Alias for `ctx.update.shipping_query` */
      get shippingQuery() {
        return this.update.shipping_query;
      }
      /** Alias for `ctx.update.pre_checkout_query` */
      get preCheckoutQuery() {
        return this.update.pre_checkout_query;
      }
      /** Alias for `ctx.update.poll` */
      get poll() {
        return this.update.poll;
      }
      /** Alias for `ctx.update.poll_answer` */
      get pollAnswer() {
        return this.update.poll_answer;
      }
      /** Alias for `ctx.update.my_chat_member` */
      get myChatMember() {
        return this.update.my_chat_member;
      }
      /** Alias for `ctx.update.chat_member` */
      get chatMember() {
        return this.update.chat_member;
      }
      /** Alias for `ctx.update.chat_join_request` */
      get chatJoinRequest() {
        return this.update.chat_join_request;
      }
      /** Alias for `ctx.update.chat_boost` */
      get chatBoost() {
        return this.update.chat_boost;
      }
      /** Alias for `ctx.update.removed_chat_boost` */
      get removedChatBoost() {
        return this.update.removed_chat_boost;
      }
      /** Alias for `ctx.update.purchased_paid_media` */
      get purchasedPaidMedia() {
        return this.update.purchased_paid_media;
      }
      // AGGREGATION SHORTCUTS
      /**
       * Get the message object from wherever possible. Alias for `this.message ??
       * this.editedMessage ?? this.channelPost ?? this.editedChannelPost ??
       * this.businessMessage ?? this.editedBusinessMessage ??
       * this.callbackQuery?.message`.
       */
      get msg() {
        var _a7, _b2, _c2, _d, _e2, _f, _g;
        return (_f = (_e2 = (_d = (_c2 = (_b2 = (_a7 = this.message) !== null && _a7 !== void 0 ? _a7 : this.editedMessage) !== null && _b2 !== void 0 ? _b2 : this.channelPost) !== null && _c2 !== void 0 ? _c2 : this.editedChannelPost) !== null && _d !== void 0 ? _d : this.businessMessage) !== null && _e2 !== void 0 ? _e2 : this.editedBusinessMessage) !== null && _f !== void 0 ? _f : (_g = this.callbackQuery) === null || _g === void 0 ? void 0 : _g.message;
      }
      /**
       * Get the chat object from wherever possible. Alias for `(this.msg ??
       * this.deletedBusinessMessages ?? this.messageReaction ??
       * this.messageReactionCount ?? this.myChatMember ??  this.chatMember ??
       * this.chatJoinRequest ?? this.chatBoost ??  this.removedChatBoost)?.chat`.
       */
      get chat() {
        var _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j;
        return (_j = (_h = (_g = (_f = (_e2 = (_d = (_c2 = (_b2 = (_a7 = this.msg) !== null && _a7 !== void 0 ? _a7 : this.deletedBusinessMessages) !== null && _b2 !== void 0 ? _b2 : this.messageReaction) !== null && _c2 !== void 0 ? _c2 : this.messageReactionCount) !== null && _d !== void 0 ? _d : this.myChatMember) !== null && _e2 !== void 0 ? _e2 : this.chatMember) !== null && _f !== void 0 ? _f : this.chatJoinRequest) !== null && _g !== void 0 ? _g : this.chatBoost) !== null && _h !== void 0 ? _h : this.removedChatBoost) === null || _j === void 0 ? void 0 : _j.chat;
      }
      /**
       * Get the sender chat object from wherever possible. Alias for
       * `ctx.msg?.sender_chat`.
       */
      get senderChat() {
        var _a7;
        return (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.sender_chat;
      }
      /**
       * Get the user object from wherever possible. Alias for
       * `(this.businessConnection ?? this.messageReaction ??
       * (this.chatBoost?.boost ?? this.removedChatBoost)?.source)?.user ??
       * (this.callbackQuery ?? this.msg ?? this.inlineQuery ??
       * this.chosenInlineResult ?? this.shippingQuery ?? this.preCheckoutQuery ??
       * this.myChatMember ?? this.chatMember ?? this.chatJoinRequest ??
       * this.purchasedPaidMedia)?.from`.
       */
      get from() {
        var _a7, _b2, _c2, _d, _e2, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r2, _s;
        return (_g = (_f = (_b2 = (_a7 = this.businessConnection) !== null && _a7 !== void 0 ? _a7 : this.messageReaction) !== null && _b2 !== void 0 ? _b2 : (_e2 = (_d = (_c2 = this.chatBoost) === null || _c2 === void 0 ? void 0 : _c2.boost) !== null && _d !== void 0 ? _d : this.removedChatBoost) === null || _e2 === void 0 ? void 0 : _e2.source) === null || _f === void 0 ? void 0 : _f.user) !== null && _g !== void 0 ? _g : (_s = (_r2 = (_q = (_p = (_o = (_m = (_l = (_k = (_j = (_h = this.callbackQuery) !== null && _h !== void 0 ? _h : this.msg) !== null && _j !== void 0 ? _j : this.inlineQuery) !== null && _k !== void 0 ? _k : this.chosenInlineResult) !== null && _l !== void 0 ? _l : this.shippingQuery) !== null && _m !== void 0 ? _m : this.preCheckoutQuery) !== null && _o !== void 0 ? _o : this.myChatMember) !== null && _p !== void 0 ? _p : this.chatMember) !== null && _q !== void 0 ? _q : this.chatJoinRequest) !== null && _r2 !== void 0 ? _r2 : this.purchasedPaidMedia) === null || _s === void 0 ? void 0 : _s.from;
      }
      /**
       * Get the message identifier from wherever possible. Alias for
       * `this.msg?.message_id ?? this.messageReaction?.message_id ??
       * this.messageReactionCount?.message_id`.
       */
      get msgId() {
        var _a7, _b2, _c2, _d, _e2;
        return (_d = (_b2 = (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.message_id) !== null && _b2 !== void 0 ? _b2 : (_c2 = this.messageReaction) === null || _c2 === void 0 ? void 0 : _c2.message_id) !== null && _d !== void 0 ? _d : (_e2 = this.messageReactionCount) === null || _e2 === void 0 ? void 0 : _e2.message_id;
      }
      /**
       * Gets the chat identifier from wherever possible. Alias for `this.chat?.id
       * ?? this.businessConnection?.user_chat_id`.
       */
      get chatId() {
        var _a7, _b2, _c2;
        return (_b2 = (_a7 = this.chat) === null || _a7 === void 0 ? void 0 : _a7.id) !== null && _b2 !== void 0 ? _b2 : (_c2 = this.businessConnection) === null || _c2 === void 0 ? void 0 : _c2.user_chat_id;
      }
      /**
       * Get the inline message identifier from wherever possible. Alias for
       * `(ctx.callbackQuery ?? ctx.chosenInlineResult)?.inline_message_id`.
       */
      get inlineMessageId() {
        var _a7, _b2, _c2;
        return (_b2 = (_a7 = this.callbackQuery) === null || _a7 === void 0 ? void 0 : _a7.inline_message_id) !== null && _b2 !== void 0 ? _b2 : (_c2 = this.chosenInlineResult) === null || _c2 === void 0 ? void 0 : _c2.inline_message_id;
      }
      /**
       * Get the business connection identifier from wherever possible. Alias for
       * `this.msg?.business_connection_id ?? this.businessConnection?.id ??
       * this.deletedBusinessMessages?.business_connection_id`.
       */
      get businessConnectionId() {
        var _a7, _b2, _c2, _d, _e2;
        return (_d = (_b2 = (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.business_connection_id) !== null && _b2 !== void 0 ? _b2 : (_c2 = this.businessConnection) === null || _c2 === void 0 ? void 0 : _c2.id) !== null && _d !== void 0 ? _d : (_e2 = this.deletedBusinessMessages) === null || _e2 === void 0 ? void 0 : _e2.business_connection_id;
      }
      entities(types7) {
        var _a7, _b2;
        const message = this.msg;
        if (message === void 0)
          return [];
        const text = (_a7 = message.text) !== null && _a7 !== void 0 ? _a7 : message.caption;
        if (text === void 0)
          return [];
        let entities = (_b2 = message.entities) !== null && _b2 !== void 0 ? _b2 : message.caption_entities;
        if (entities === void 0)
          return [];
        if (types7 !== void 0) {
          const filters = new Set(toArray2(types7));
          entities = entities.filter((entity) => filters.has(entity.type));
        }
        return entities.map((entity) => ({
          ...entity,
          text: text.substring(entity.offset, entity.offset + entity.length)
        }));
      }
      /**
       * Find out which reactions were added and removed in a `message_reaction`
       * update. This method looks at `ctx.messageReaction` and computes the
       * difference between the old reaction and the new reaction. It also groups
       * the reactions by emoji reactions and custom emoji reactions. For example,
       * the resulting object could look like this:
       * ```ts
       * {
       *   emoji: ['👍', '🎉']
       *   emojiAdded: ['🎉'],
       *   emojiKept: ['👍'],
       *   emojiRemoved: [],
       *   customEmoji: [],
       *   customEmojiAdded: [],
       *   customEmojiKept: [],
       *   customEmojiRemoved: ['id0123'],
       *   paid: true,
       *   paidAdded: false,
       *   paidRemoved: false,
       * }
       * ```
       * In the above example, a tada reaction was added by the user, and a custom
       * emoji reaction with the custom emoji 'id0123' was removed in the same
       * update. The user had already reacted with a thumbs up reaction and a paid
       * star reaction, which they left both unchanged. As a result, the current
       * reaction by the user is thumbs up, tada, and a paid reaction. Note that
       * the current reaction (all emoji reactions regardless of type in one list)
       * can also be obtained from `ctx.messageReaction.new_reaction`.
       *
       * Remember that reaction updates only include information about the
       * reaction of a specific user. The respective message may have many more
       * reactions by other people which will not be included in this update.
       *
       * @returns An object containing information about the reaction update
       */
      reactions() {
        const emoji3 = [];
        const emojiAdded = [];
        const emojiKept = [];
        const emojiRemoved = [];
        const customEmoji = [];
        const customEmojiAdded = [];
        const customEmojiKept = [];
        const customEmojiRemoved = [];
        let paid = false;
        let paidAdded = false;
        const r5 = this.messageReaction;
        if (r5 !== void 0) {
          const { old_reaction, new_reaction } = r5;
          for (const reaction of new_reaction) {
            if (reaction.type === "emoji") {
              emoji3.push(reaction.emoji);
            } else if (reaction.type === "custom_emoji") {
              customEmoji.push(reaction.custom_emoji_id);
            } else if (reaction.type === "paid") {
              paid = paidAdded = true;
            }
          }
          for (const reaction of old_reaction) {
            if (reaction.type === "emoji") {
              emojiRemoved.push(reaction.emoji);
            } else if (reaction.type === "custom_emoji") {
              customEmojiRemoved.push(reaction.custom_emoji_id);
            } else if (reaction.type === "paid") {
              paidAdded = false;
            }
          }
          emojiAdded.push(...emoji3);
          customEmojiAdded.push(...customEmoji);
          for (let i4 = 0; i4 < emojiRemoved.length; i4++) {
            const len = emojiAdded.length;
            if (len === 0)
              break;
            const rem = emojiRemoved[i4];
            for (let j2 = 0; j2 < len; j2++) {
              if (rem === emojiAdded[j2]) {
                emojiKept.push(rem);
                emojiRemoved.splice(i4, 1);
                emojiAdded.splice(j2, 1);
                i4--;
                break;
              }
            }
          }
          for (let i4 = 0; i4 < customEmojiRemoved.length; i4++) {
            const len = customEmojiAdded.length;
            if (len === 0)
              break;
            const rem = customEmojiRemoved[i4];
            for (let j2 = 0; j2 < len; j2++) {
              if (rem === customEmojiAdded[j2]) {
                customEmojiKept.push(rem);
                customEmojiRemoved.splice(i4, 1);
                customEmojiAdded.splice(j2, 1);
                i4--;
                break;
              }
            }
          }
        }
        return {
          emoji: emoji3,
          emojiAdded,
          emojiKept,
          emojiRemoved,
          customEmoji,
          customEmojiAdded,
          customEmojiKept,
          customEmojiRemoved,
          paid,
          paidAdded
        };
      }
      /**
       * Returns `true` if this context object matches the given filter query, and
       * `false` otherwise. This uses the same logic as `bot.on`.
       *
       * @param filter The filter query to check
       */
      has(filter5) {
        return _Context.has.filterQuery(filter5)(this);
      }
      /**
       * Returns `true` if this context object contains the given text, or if it
       * contains text that matches the given regular expression. It returns
       * `false` otherwise. This uses the same logic as `bot.hears`.
       *
       * @param trigger The string or regex to match
       */
      hasText(trigger) {
        return _Context.has.text(trigger)(this);
      }
      /**
       * Returns `true` if this context object contains the given command, and
       * `false` otherwise. This uses the same logic as `bot.command`.
       *
       * @param command The command to match
       */
      hasCommand(command2) {
        return _Context.has.command(command2)(this);
      }
      hasReaction(reaction) {
        return _Context.has.reaction(reaction)(this);
      }
      /**
       * Returns `true` if this context object belongs to a chat with the given
       * chat type, and `false` otherwise. This uses the same logic as
       * `bot.chatType`.
       *
       * @param chatType The chat type to match
       */
      hasChatType(chatType) {
        return _Context.has.chatType(chatType)(this);
      }
      /**
       * Returns `true` if this context object contains the given callback query,
       * or if the contained callback query data matches the given regular
       * expression. It returns `false` otherwise. This uses the same logic as
       * `bot.callbackQuery`.
       *
       * @param trigger The string or regex to match
       */
      hasCallbackQuery(trigger) {
        return _Context.has.callbackQuery(trigger)(this);
      }
      /**
       * Returns `true` if this context object contains the given game query, or
       * if the contained game query matches the given regular expression. It
       * returns `false` otherwise. This uses the same logic as `bot.gameQuery`.
       *
       * @param trigger The string or regex to match
       */
      hasGameQuery(trigger) {
        return _Context.has.gameQuery(trigger)(this);
      }
      /**
       * Returns `true` if this context object contains the given inline query, or
       * if the contained inline query matches the given regular expression. It
       * returns `false` otherwise. This uses the same logic as `bot.inlineQuery`.
       *
       * @param trigger The string or regex to match
       */
      hasInlineQuery(trigger) {
        return _Context.has.inlineQuery(trigger)(this);
      }
      /**
       * Returns `true` if this context object contains the chosen inline result,
       * or if the contained chosen inline result matches the given regular
       * expression. It returns `false` otherwise. This uses the same logic as
       * `bot.chosenInlineResult`.
       *
       * @param trigger The string or regex to match
       */
      hasChosenInlineResult(trigger) {
        return _Context.has.chosenInlineResult(trigger)(this);
      }
      /**
       * Returns `true` if this context object contains the given pre-checkout
       * query, or if the contained pre-checkout query matches the given regular
       * expression. It returns `false` otherwise. This uses the same logic as
       * `bot.preCheckoutQuery`.
       *
       * @param trigger The string or regex to match
       */
      hasPreCheckoutQuery(trigger) {
        return _Context.has.preCheckoutQuery(trigger)(this);
      }
      /**
       * Returns `true` if this context object contains the given shipping query,
       * or if the contained shipping query matches the given regular expression.
       * It returns `false` otherwise. This uses the same logic as
       * `bot.shippingQuery`.
       *
       * @param trigger The string or regex to match
       */
      hasShippingQuery(trigger) {
        return _Context.has.shippingQuery(trigger)(this);
      }
      // API
      /**
       * Context-aware alias for `api.sendMessage`. Use this method to send text messages. On success, the sent Message is returned.
       *
       * @param text Text of the message to be sent, 1-4096 characters after entities parsing
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendmessage
       */
      reply(text, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendMessage(orThrow(this.chatId, "sendMessage"), text, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendMessageDraft`. Use this method to stream a partial message to a user while the message is being generated. Returns True on success.
       *
       * @param text Text of the message to be sent, 1-4096 characters after entities parsing
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendmessagedraft
       */
      replyWithDraft(text, other2, signal) {
        const msg = this.msg;
        return this.api.sendMessageDraft(orThrow(this.chatId, "sendMessageDraft"), this.update.update_id, text, {
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg === null || msg === void 0 ? void 0 : msg.message_thread_id } : {},
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.forwardMessage`. Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#forwardmessage
       */
      forwardMessage(chat_id, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.forwardMessage(chat_id, orThrow(this.chatId, "forwardMessage"), orThrow(this.msgId, "forwardMessage"), {
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.forwardMessages`. Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_ids A list of 1-100 identifiers of messages in the current chat to forward. The identifiers must be specified in a strictly increasing order.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#forwardmessages
       */
      forwardMessages(chat_id, message_ids, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.forwardMessages(chat_id, orThrow(this.chatId, "forwardMessages"), message_ids, {
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.copyMessage`. Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#copymessage
       */
      copyMessage(chat_id, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.copyMessage(chat_id, orThrow(this.chatId, "copyMessage"), orThrow(this.msgId, "copyMessage"), {
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.copyMessages`. Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_ids A list of 1-100 identifiers of messages in the current chat to copy. The identifiers must be specified in a strictly increasing order.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#copymessages
       */
      copyMessages(chat_id, message_ids, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.copyMessages(chat_id, orThrow(this.chatId, "copyMessages"), message_ids, {
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendPhoto`. Use this method to send photos. On success, the sent Message is returned.
       *
       * @param photo Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendphoto
       */
      replyWithPhoto(photo, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendPhoto(orThrow(this.chatId, "sendPhoto"), photo, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendAudio`. Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
       *
       * For sending voice messages, use the sendVoice method instead.
       *
       * @param audio Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendaudio
       */
      replyWithAudio(audio, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendAudio(orThrow(this.chatId, "sendAudio"), audio, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendDocument`. Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
       *
       * @param document File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#senddocument
       */
      replyWithDocument(document2, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendDocument(orThrow(this.chatId, "sendDocument"), document2, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendVideo`. Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
       *
       * @param video Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendvideo
       */
      replyWithVideo(video, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendVideo(orThrow(this.chatId, "sendVideo"), video, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendAnimation`. Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
       *
       * @param animation Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendanimation
       */
      replyWithAnimation(animation, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendAnimation(orThrow(this.chatId, "sendAnimation"), animation, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendVoice`. Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
       *
       * @param voice Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendvoice
       */
      replyWithVoice(voice, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendVoice(orThrow(this.chatId, "sendVoice"), voice, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendVideoNote`. Use this method to send video messages. On success, the sent Message is returned.
       * As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long.
       *
       * @param video_note Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data.. Sending video notes by a URL is currently unsupported
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendvideonote
       */
      replyWithVideoNote(video_note, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendVideoNote(orThrow(this.chatId, "sendVideoNote"), video_note, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendMediaGroup`. Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned.
       *
       * @param media An array describing messages to be sent, must include 2-10 items
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendmediagroup
       */
      replyWithMediaGroup(media, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendMediaGroup(orThrow(this.chatId, "sendMediaGroup"), media, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendLocation`. Use this method to send point on the map. On success, the sent Message is returned.
       *
       * @param latitude Latitude of the location
       * @param longitude Longitude of the location
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendlocation
       */
      replyWithLocation(latitude, longitude, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendLocation(orThrow(this.chatId, "sendLocation"), latitude, longitude, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.editMessageLiveLocation`. Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
       *
       * @param latitude Latitude of new location
       * @param longitude Longitude of new location
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagelivelocation
       */
      editMessageLiveLocation(latitude, longitude, other2, signal) {
        const inlineId = this.inlineMessageId;
        return inlineId !== void 0 ? this.api.editMessageLiveLocationInline(inlineId, latitude, longitude, { business_connection_id: this.businessConnectionId, ...other2 }, signal) : this.api.editMessageLiveLocation(orThrow(this.chatId, "editMessageLiveLocation"), orThrow(this.msgId, "editMessageLiveLocation"), latitude, longitude, { business_connection_id: this.businessConnectionId, ...other2 }, signal);
      }
      /**
       * Context-aware alias for `api.stopMessageLiveLocation`. Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#stopmessagelivelocation
       */
      stopMessageLiveLocation(other2, signal) {
        const inlineId = this.inlineMessageId;
        return inlineId !== void 0 ? this.api.stopMessageLiveLocationInline(inlineId, { business_connection_id: this.businessConnectionId, ...other2 }, signal) : this.api.stopMessageLiveLocation(orThrow(this.chatId, "stopMessageLiveLocation"), orThrow(this.msgId, "stopMessageLiveLocation"), { business_connection_id: this.businessConnectionId, ...other2 }, signal);
      }
      /**
       * Context-aware alias for `api.sendPaidMedia`. Use this method to send paid media. On success, the sent Message is returned.
       *
       * @param star_count The number of Telegram Stars that must be paid to buy access to the media
       * @param media An array describing the media to be sent; up to 10 items
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendpaidmedia
       */
      sendPaidMedia(star_count, media, other2, signal) {
        var _a7, _b2;
        const msg = this.msg;
        return this.api.sendPaidMedia(orThrow(this.chatId, "sendPaidMedia"), star_count, media, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_b2 = (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.direct_messages_topic) === null || _b2 === void 0 ? void 0 : _b2.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendVenue`. Use this method to send information about a venue. On success, the sent Message is returned.
       *
       * @param latitude Latitude of the venue
       * @param longitude Longitude of the venue
       * @param title Name of the venue
       * @param address Address of the venue
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendvenue
       */
      replyWithVenue(latitude, longitude, title, address, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendVenue(orThrow(this.chatId, "sendVenue"), latitude, longitude, title, address, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendContact`. Use this method to send phone contacts. On success, the sent Message is returned.
       *
       * @param phone_number Contact's phone number
       * @param first_name Contact's first name
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendcontact
       */
      replyWithContact(phone_number, first_name, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendContact(orThrow(this.chatId, "sendContact"), phone_number, first_name, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendPoll`. Use this method to send a native poll. On success, the sent Message is returned.
       *
       * @param question Poll question, 1-300 characters
       * @param options A list of answer options, 2-12 strings 1-100 characters each
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendpoll
       */
      replyWithPoll(question, options2, other2, signal) {
        const msg = this.msg;
        return this.api.sendPoll(orThrow(this.chatId, "sendPoll"), question, options2, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendChecklist`. Use this method to send a checklist on behalf of a connected business account. On success, the sent Message is returned.
       *
       * @param checklist An object for the checklist to send
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendchecklist
       */
      replyWithChecklist(checklist, other2, signal) {
        return this.api.sendChecklist(orThrow(this.businessConnectionId, "sendChecklist"), orThrow(this.chatId, "sendChecklist"), checklist, other2, signal);
      }
      /**
       * Context-aware alias for `api.editMessageChecklist`. Use this method to edit a checklist on behalf of a connected business account. On success, the edited Message is returned.
       *
       * @param checklist An object for the new checklist
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagechecklist
       */
      editMessageChecklist(checklist, other2, signal) {
        var _a7, _b2, _c2, _d;
        const msg = orThrow(this.msg, "editMessageChecklist");
        const target = (_d = (_b2 = (_a7 = msg.checklist_tasks_done) === null || _a7 === void 0 ? void 0 : _a7.checklist_message) !== null && _b2 !== void 0 ? _b2 : (_c2 = msg.checklist_tasks_added) === null || _c2 === void 0 ? void 0 : _c2.checklist_message) !== null && _d !== void 0 ? _d : msg;
        return this.api.editMessageChecklist(orThrow(this.businessConnectionId, "editMessageChecklist"), orThrow(target.chat.id, "editMessageChecklist"), orThrow(target.message_id, "editMessageChecklist"), checklist, other2, signal);
      }
      /**
       * Context-aware alias for `api.sendDice`. Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.
       *
       * @param emoji Emoji on which the dice throw animation is based. Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”. Dice can have values 1-6 for “🎲”, “🎯” and “🎳”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”. Defaults to “🎲”
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#senddice
       */
      replyWithDice(emoji3, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendDice(orThrow(this.chatId, "sendDice"), emoji3, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.sendChatAction`. Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
       *
       * Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.
       *
       * We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.
       *
       * @param action Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendchataction
       */
      replyWithChatAction(action, other2, signal) {
        const msg = this.msg;
        return this.api.sendChatAction(orThrow(this.chatId, "sendChatAction"), action, {
          business_connection_id: this.businessConnectionId,
          message_thread_id: msg === null || msg === void 0 ? void 0 : msg.message_thread_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.setMessageReaction`. Use this method to change the chosen reactions on a message. Service messages of some types can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns True on success.
       *
       * @param reaction A list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can't be used by bots.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setmessagereaction
       */
      react(reaction, other2, signal) {
        return this.api.setMessageReaction(orThrow(this.chatId, "setMessageReaction"), orThrow(this.msgId, "setMessageReaction"), typeof reaction === "string" ? [{ type: "emoji", emoji: reaction }] : (Array.isArray(reaction) ? reaction : [reaction]).map((emoji3) => typeof emoji3 === "string" ? { type: "emoji", emoji: emoji3 } : emoji3), other2, signal);
      }
      /**
       * Context-aware alias for `api.getUserProfilePhotos`. Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getuserprofilephotos
       */
      getUserProfilePhotos(other2, signal) {
        return this.api.getUserProfilePhotos(orThrow(this.from, "getUserProfilePhotos").id, other2, signal);
      }
      /**
       * Context-aware alias for `api.getUserProfileAudios`. Use this method to get a list of profile audios for a user. Returns a UserProfileAudios object.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getuserprofileaudios
       */
      getUserProfileAudios(other2, signal) {
        return this.api.getUserProfileAudios(orThrow(this.from, "getUserProfileAudios").id, other2, signal);
      }
      /**
       * Context-aware alias for `api.serUserEmojiStatus`. Changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App method requestEmojiStatusAccess. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setuseremojistatus
       */
      setUserEmojiStatus(other2, signal) {
        return this.api.setUserEmojiStatus(orThrow(this.from, "setUserEmojiStatus").id, other2, signal);
      }
      /**
       * Context-aware alias for `api.getUserChatBoosts`. Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object.
       *
       * @param chat_id Unique identifier for the chat or username of the channel (in the format @channelusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getuserchatboosts
       */
      getUserChatBoosts(chat_id, signal) {
        return this.api.getUserChatBoosts(chat_id !== null && chat_id !== void 0 ? chat_id : orThrow(this.chatId, "getUserChatBoosts"), orThrow(this.from, "getUserChatBoosts").id, signal);
      }
      /**
       * Context-aware alias for `api.getUserGifts`. Returns the gifts owned and hosted by a user. Returns OwnedGifts on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getusergifts
       */
      getUserGifts(other2, signal) {
        return this.api.getUserGifts(orThrow(this.from, "getUserGifts").id, other2, signal);
      }
      /**
       * Context-aware alias for `api.getChatGifts`. Returns the gifts owned by a chat. Returns OwnedGifts on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatgifts
       */
      getChatGifts(other2, signal) {
        return this.api.getChatGifts(orThrow(this.chatId, "getChatGifts"), other2, signal);
      }
      /**
       * Context-aware alias for `api.getBusinessConnection`. Use this method to get information about the connection of the bot with a business account. Returns a BusinessConnection object on success.
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getbusinessconnection
       */
      getBusinessConnection(signal) {
        return this.api.getBusinessConnection(orThrow(this.businessConnectionId, "getBusinessConnection"), signal);
      }
      /**
       * Context-aware alias for `api.getFile`. Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
       *
       * Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getfile
       */
      getFile(signal) {
        var _a7, _b2, _c2, _d, _e2, _f;
        const m3 = orThrow(this.msg, "getFile");
        const file2 = m3.photo !== void 0 ? m3.photo[m3.photo.length - 1] : (_f = (_e2 = (_d = (_c2 = (_b2 = (_a7 = m3.animation) !== null && _a7 !== void 0 ? _a7 : m3.audio) !== null && _b2 !== void 0 ? _b2 : m3.document) !== null && _c2 !== void 0 ? _c2 : m3.video) !== null && _d !== void 0 ? _d : m3.video_note) !== null && _e2 !== void 0 ? _e2 : m3.voice) !== null && _f !== void 0 ? _f : m3.sticker;
        return this.api.getFile(orThrow(file2, "getFile").file_id, signal);
      }
      /** @deprecated Use `banAuthor` instead. */
      kickAuthor(...args2) {
        return this.banAuthor(...args2);
      }
      /**
       * Context-aware alias for `api.banChatMember`. Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#banchatmember
       */
      banAuthor(other2, signal) {
        return this.api.banChatMember(orThrow(this.chatId, "banAuthor"), orThrow(this.from, "banAuthor").id, other2, signal);
      }
      /** @deprecated Use `banChatMember` instead. */
      kickChatMember(...args2) {
        return this.banChatMember(...args2);
      }
      /**
       * Context-aware alias for `api.banChatMember`. Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#banchatmember
       */
      banChatMember(user_id, other2, signal) {
        return this.api.banChatMember(orThrow(this.chatId, "banChatMember"), user_id, other2, signal);
      }
      /**
       * Context-aware alias for `api.unbanChatMember`. Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unbanchatmember
       */
      unbanChatMember(user_id, other2, signal) {
        return this.api.unbanChatMember(orThrow(this.chatId, "unbanChatMember"), user_id, other2, signal);
      }
      /**
       * Context-aware alias for `api.restrictChatMember`. Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.
       *
       * @param permissions An object for new user permissions
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#restrictchatmember
       */
      restrictAuthor(permissions, other2, signal) {
        return this.api.restrictChatMember(orThrow(this.chatId, "restrictAuthor"), orThrow(this.from, "restrictAuthor").id, permissions, other2, signal);
      }
      /**
       * Context-aware alias for `api.restrictChatMember`. Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param permissions An object for new user permissions
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#restrictchatmember
       */
      restrictChatMember(user_id, permissions, other2, signal) {
        return this.api.restrictChatMember(orThrow(this.chatId, "restrictChatMember"), user_id, permissions, other2, signal);
      }
      /**
       * Context-aware alias for `api.promoteChatMember`. Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#promotechatmember
       */
      promoteAuthor(other2, signal) {
        return this.api.promoteChatMember(orThrow(this.chatId, "promoteAuthor"), orThrow(this.from, "promoteAuthor").id, other2, signal);
      }
      /**
       * Context-aware alias for `api.promoteChatMember`. Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#promotechatmember
       */
      promoteChatMember(user_id, other2, signal) {
        return this.api.promoteChatMember(orThrow(this.chatId, "promoteChatMember"), user_id, other2, signal);
      }
      /**
       * Context-aware alias for `api.setChatAdministratorCustomTitle`. Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.
       *
       * @param custom_title New custom title for the administrator; 0-16 characters, emoji are not allowed
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatadministratorcustomtitle
       */
      setChatAdministratorAuthorCustomTitle(custom_title, signal) {
        return this.api.setChatAdministratorCustomTitle(orThrow(this.chatId, "setChatAdministratorAuthorCustomTitle"), orThrow(this.from, "setChatAdministratorAuthorCustomTitle").id, custom_title, signal);
      }
      /**
       * Context-aware alias for `api.setChatAdministratorCustomTitle`. Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param custom_title New custom title for the administrator; 0-16 characters, emoji are not allowed
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatadministratorcustomtitle
       */
      setChatAdministratorCustomTitle(user_id, custom_title, signal) {
        return this.api.setChatAdministratorCustomTitle(orThrow(this.chatId, "setChatAdministratorCustomTitle"), user_id, custom_title, signal);
      }
      /**
       * Context-aware alias for `api.setChatMemberTag`. Use this method to set a tag for a regular member in a group or a supergroup. The bot must be an administrator in the chat for this to work and must have the “can_manage_tags” administrator right. Returns True on success.
       *
       * @param tag New tag for the member; 0-16 characters, emoji are not allowed
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setChatMemberTag
       */
      setAuthorTag(tag2, signal) {
        return this.api.setChatMemberTag(orThrow(this.chatId, "setChatMemberTag"), orThrow(this.from, "setChatMemberTag").id, tag2, signal);
      }
      /**
       * Context-aware alias for `api.setChatMemberTag`. Use this method to set a tag for a regular member in a group or a supergroup. The bot must be an administrator in the chat for this to work and must have the “can_manage_tags” administrator right. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param tag New tag for the member; 0-16 characters, emoji are not allowed
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setChatMemberTag
       */
      setChatMemberTag(user_id, tag2, signal) {
        return this.api.setChatMemberTag(orThrow(this.chatId, "setChatMemberTag"), user_id, tag2, signal);
      }
      /**
       * Context-aware alias for `api.banChatSenderChat`. Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param sender_chat_id Unique identifier of the target sender chat
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#banchatsenderchat
       */
      banChatSenderChat(sender_chat_id, signal) {
        return this.api.banChatSenderChat(orThrow(this.chatId, "banChatSenderChat"), sender_chat_id, signal);
      }
      /**
       * Context-aware alias for `api.unbanChatSenderChat`. Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param sender_chat_id Unique identifier of the target sender chat
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unbanchatsenderchat
       */
      unbanChatSenderChat(sender_chat_id, signal) {
        return this.api.unbanChatSenderChat(orThrow(this.chatId, "unbanChatSenderChat"), sender_chat_id, signal);
      }
      /**
       * Context-aware alias for `api.setChatPermissions`. Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success.
       *
       * @param permissions New default chat permissions
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatpermissions
       */
      setChatPermissions(permissions, other2, signal) {
        return this.api.setChatPermissions(orThrow(this.chatId, "setChatPermissions"), permissions, other2, signal);
      }
      /**
       * Context-aware alias for `api.exportChatInviteLink`. Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success.
       *
       * Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method. If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#exportchatinvitelink
       */
      exportChatInviteLink(signal) {
        return this.api.exportChatInviteLink(orThrow(this.chatId, "exportChatInviteLink"), signal);
      }
      /**
       * Context-aware alias for `api.createChatInviteLink`. Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#createchatinvitelink
       */
      createChatInviteLink(other2, signal) {
        return this.api.createChatInviteLink(orThrow(this.chatId, "createChatInviteLink"), other2, signal);
      }
      /**
       * Context-aware alias for `api.editChatInviteLink`. Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object.
       *
       * @param invite_link The invite link to edit
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editchatinvitelink
       */
      editChatInviteLink(invite_link, other2, signal) {
        return this.api.editChatInviteLink(orThrow(this.chatId, "editChatInviteLink"), invite_link, other2, signal);
      }
      /**
       * Context-aware alias for `api.createChatSubscriptionInviteLink`. Use this method to create a subscription invite link for a channel chat. The bot must have the can_invite_users administrator rights. The link can be edited using the method editChatSubscriptionInviteLink or revoked using the method revokeChatInviteLink. Returns the new invite link as a ChatInviteLink object.
       *
       * @param subscription_period The number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days).
       * @param subscription_price The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; 1-2500
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#createchatsubscriptioninvitelink
       */
      createChatSubscriptionInviteLink(subscription_period, subscription_price, other2, signal) {
        return this.api.createChatSubscriptionInviteLink(orThrow(this.chatId, "createChatSubscriptionInviteLink"), subscription_period, subscription_price, other2, signal);
      }
      /**
       * Context-aware alias for `api.editChatSubscriptionInviteLink`. Use this method to edit a subscription invite link created by the bot. The bot must have the can_invite_users administrator rights. Returns the edited invite link as a ChatInviteLink object.
       *
       * @param invite_link The invite link to edit
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editchatsubscriptioninvitelink
       */
      editChatSubscriptionInviteLink(invite_link, other2, signal) {
        return this.api.editChatSubscriptionInviteLink(orThrow(this.chatId, "editChatSubscriptionInviteLink"), invite_link, other2, signal);
      }
      /**
       * Context-aware alias for `api.revokeChatInviteLink`. Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object.
       *
       * @param invite_link The invite link to revoke
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#revokechatinvitelink
       */
      revokeChatInviteLink(invite_link, signal) {
        return this.api.revokeChatInviteLink(orThrow(this.chatId, "editChatInviteLink"), invite_link, signal);
      }
      /**
       * Context-aware alias for `api.approveChatJoinRequest`. Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#approvechatjoinrequest
       */
      approveChatJoinRequest(user_id, signal) {
        return this.api.approveChatJoinRequest(orThrow(this.chatId, "approveChatJoinRequest"), user_id, signal);
      }
      /**
       * Context-aware alias for `api.declineChatJoinRequest`. Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#declinechatjoinrequest
       */
      declineChatJoinRequest(user_id, signal) {
        return this.api.declineChatJoinRequest(orThrow(this.chatId, "declineChatJoinRequest"), user_id, signal);
      }
      /**
       * Context-aware alias for `api.approveSuggestedPost`. Use this method to approve a suggested post in a direct messages chat. The bot must have the 'can_post_messages' administrator right in the corresponding channel chat.  Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#approvesuggestedpost
       */
      approveSuggestedPost(other2, signal) {
        return this.api.approveSuggestedPost(orThrow(this.chatId, "approveSuggestedPost"), orThrow(this.msgId, "approveSuggestedPost"), other2, signal);
      }
      /**
       * Context-aware alias for `api.declineSuggestedPost`. Use this method to decline a suggested post in a direct messages chat. The bot must have the 'can_manage_direct_messages' administrator right in the corresponding channel chat. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#declinesuggestedpost
       */
      declineSuggestedPost(other2, signal) {
        return this.api.declineSuggestedPost(orThrow(this.chatId, "declineSuggestedPost"), orThrow(this.msgId, "declineSuggestedPost"), other2, signal);
      }
      /**
       * Context-aware alias for `api.setChatPhoto`. Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param photo New chat photo, uploaded using multipart/form-data
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatphoto
       */
      setChatPhoto(photo, signal) {
        return this.api.setChatPhoto(orThrow(this.chatId, "setChatPhoto"), photo, signal);
      }
      /**
       * Context-aware alias for `api.deleteChatPhoto`. Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletechatphoto
       */
      deleteChatPhoto(signal) {
        return this.api.deleteChatPhoto(orThrow(this.chatId, "deleteChatPhoto"), signal);
      }
      /**
       * Context-aware alias for `api.setChatTitle`. Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param title New chat title, 1-255 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchattitle
       */
      setChatTitle(title, signal) {
        return this.api.setChatTitle(orThrow(this.chatId, "setChatTitle"), title, signal);
      }
      /**
       * Context-aware alias for `api.setChatDescription`. Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param description New chat description, 0-255 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatdescription
       */
      setChatDescription(description, signal) {
        return this.api.setChatDescription(orThrow(this.chatId, "setChatDescription"), description, signal);
      }
      /**
       * Context-aware alias for `api.pinChatMessage`. Use this method to add a message to the list of pinned messages in a chat. In private chats and channel direct messages chats, all non-service messages can be pinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to pin messages in groups and channels respectively. Returns True on success.
       *
       * @param message_id Identifier of a message to pin
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#pinchatmessage
       */
      pinChatMessage(message_id, other2, signal) {
        return this.api.pinChatMessage(orThrow(this.chatId, "pinChatMessage"), message_id, { business_connection_id: this.businessConnectionId, ...other2 }, signal);
      }
      /**
       * Context-aware alias for `api.unpinChatMessage`. Use this method to remove a message from the list of pinned messages in a chat. In private chats and channel direct messages chats, all messages can be unpinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin messages in groups and channels respectively. Returns True on success.
       *
       * @param message_id Identifier of a message to unpin. If not specified, the most recent pinned message (by sending date) will be unpinned.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unpinchatmessage
       */
      unpinChatMessage(message_id, other2, signal) {
        return this.api.unpinChatMessage(orThrow(this.chatId, "unpinChatMessage"), message_id, { business_connection_id: this.businessConnectionId, ...other2 }, signal);
      }
      /**
       * Context-aware alias for `api.unpinAllChatMessages`. Use this method to clear the list of pinned messages in a chat. In private chats and channel direct messages chats, no additional rights are required to unpin all pinned messages. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin all pinned messages in groups and channels respectively. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unpinallchatmessages
       */
      unpinAllChatMessages(signal) {
        return this.api.unpinAllChatMessages(orThrow(this.chatId, "unpinAllChatMessages"), signal);
      }
      /**
       * Context-aware alias for `api.leaveChat`. Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#leavechat
       */
      leaveChat(signal) {
        return this.api.leaveChat(orThrow(this.chatId, "leaveChat"), signal);
      }
      /**
       * Context-aware alias for `api.getChat`. Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchat
       */
      getChat(signal) {
        return this.api.getChat(orThrow(this.chatId, "getChat"), signal);
      }
      /**
       * Context-aware alias for `api.getChatAdministrators`. Use this method to get a list of administrators in a chat, which aren't bots. Returns an Array of ChatMember objects.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatadministrators
       */
      getChatAdministrators(signal) {
        return this.api.getChatAdministrators(orThrow(this.chatId, "getChatAdministrators"), signal);
      }
      /** @deprecated Use `getChatMemberCount` instead. */
      getChatMembersCount(...args2) {
        return this.getChatMemberCount(...args2);
      }
      /**
       * Context-aware alias for `api.getChatMemberCount`. Use this method to get the number of members in a chat. Returns Int on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatmembercount
       */
      getChatMemberCount(signal) {
        return this.api.getChatMemberCount(orThrow(this.chatId, "getChatMemberCount"), signal);
      }
      /**
       * Context-aware alias for `api.getChatMember`. Use this method to get information about a member of a chat. The method is guaranteed to work only if the bot is an administrator in the chat. Returns a ChatMember object on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatmember
       */
      getAuthor(signal) {
        return this.api.getChatMember(orThrow(this.chatId, "getAuthor"), orThrow(this.from, "getAuthor").id, signal);
      }
      /**
       * Context-aware alias for `api.getChatMember`. Use this method to get information about a member of a chat. The method is guaranteed to work only if the bot is an administrator in the chat. Returns a ChatMember object on success.
       *
       * @param user_id Unique identifier of the target user
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatmember
       */
      getChatMember(user_id, signal) {
        return this.api.getChatMember(orThrow(this.chatId, "getChatMember"), user_id, signal);
      }
      /**
       * Context-aware alias for `api.setChatStickerSet`. Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set ly returned in getChat requests to check if the bot can use this method. Returns True on success.
       *
       * @param sticker_set_name Name of the sticker set to be set as the group sticker set
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatstickerset
       */
      setChatStickerSet(sticker_set_name, signal) {
        return this.api.setChatStickerSet(orThrow(this.chatId, "setChatStickerSet"), sticker_set_name, signal);
      }
      /**
       * Context-aware alias for `api.deleteChatStickerSet`. Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set ly returned in getChat requests to check if the bot can use this method. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletechatstickerset
       */
      deleteChatStickerSet(signal) {
        return this.api.deleteChatStickerSet(orThrow(this.chatId, "deleteChatStickerSet"), signal);
      }
      /**
       * Context-aware alias for `api.createForumTopic`. Use this method to create a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator right. Returns information about the created topic as a ForumTopic object.
       *
       * @param name Topic name, 1-128 characters
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#createforumtopic
       */
      createForumTopic(name4, other2, signal) {
        return this.api.createForumTopic(orThrow(this.chatId, "createForumTopic"), name4, other2, signal);
      }
      /**
       * Context-aware alias for `api.editForumTopic`. Use this method to edit name and icon of a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editforumtopic
       */
      editForumTopic(other2, signal) {
        const message = orThrow(this.msg, "editForumTopic");
        const thread = orThrow(message.message_thread_id, "editForumTopic");
        return this.api.editForumTopic(message.chat.id, thread, other2, signal);
      }
      /**
       * Context-aware alias for `api.closeForumTopic`. Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#closeforumtopic
       */
      closeForumTopic(signal) {
        const message = orThrow(this.msg, "closeForumTopic");
        const thread = orThrow(message.message_thread_id, "closeForumTopic");
        return this.api.closeForumTopic(message.chat.id, thread, signal);
      }
      /**
       * Context-aware alias for `api.reopenForumTopic`. Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#reopenforumtopic
       */
      reopenForumTopic(signal) {
        const message = orThrow(this.msg, "reopenForumTopic");
        const thread = orThrow(message.message_thread_id, "reopenForumTopic");
        return this.api.reopenForumTopic(message.chat.id, thread, signal);
      }
      /**
       * Context-aware alias for `api.deleteForumTopic`. Use this method to delete a forum topic along with all its messages in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deleteforumtopic
       */
      deleteForumTopic(signal) {
        const message = orThrow(this.msg, "deleteForumTopic");
        const thread = orThrow(message.message_thread_id, "deleteForumTopic");
        return this.api.deleteForumTopic(message.chat.id, thread, signal);
      }
      /**
       * Context-aware alias for `api.unpinAllForumTopicMessages`. Use this method to clear the list of pinned messages in a forum topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unpinallforumtopicmessages
       */
      unpinAllForumTopicMessages(signal) {
        const message = orThrow(this.msg, "unpinAllForumTopicMessages");
        const thread = orThrow(message.message_thread_id, "unpinAllForumTopicMessages");
        return this.api.unpinAllForumTopicMessages(message.chat.id, thread, signal);
      }
      /**
       * Context-aware alias for `api.editGeneralForumTopic`. Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
       *
       * @param name New topic name, 1-128 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editgeneralforumtopic
       */
      editGeneralForumTopic(name4, signal) {
        return this.api.editGeneralForumTopic(orThrow(this.chatId, "editGeneralForumTopic"), name4, signal);
      }
      /**
       * Context-aware alias for `api.closeGeneralForumTopic`. Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#closegeneralforumtopic
       */
      closeGeneralForumTopic(signal) {
        return this.api.closeGeneralForumTopic(orThrow(this.chatId, "closeGeneralForumTopic"), signal);
      }
      /**
       * Context-aware alias for `api.reopenGeneralForumTopic`. Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success.     *
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#reopengeneralforumtopic
       */
      reopenGeneralForumTopic(signal) {
        return this.api.reopenGeneralForumTopic(orThrow(this.chatId, "reopenGeneralForumTopic"), signal);
      }
      /**
       * Context-aware alias for `api.hideGeneralForumTopic`. Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#hidegeneralforumtopic
       */
      hideGeneralForumTopic(signal) {
        return this.api.hideGeneralForumTopic(orThrow(this.chatId, "hideGeneralForumTopic"), signal);
      }
      /**
       * Context-aware alias for `api.unhideGeneralForumTopic`. Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unhidegeneralforumtopic
       */
      unhideGeneralForumTopic(signal) {
        return this.api.unhideGeneralForumTopic(orThrow(this.chatId, "unhideGeneralForumTopic"), signal);
      }
      /**
       * Context-aware alias for `api.unpinAllGeneralForumTopicMessages`. Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages
       */
      unpinAllGeneralForumTopicMessages(signal) {
        return this.api.unpinAllGeneralForumTopicMessages(orThrow(this.chatId, "unpinAllGeneralForumTopicMessages"), signal);
      }
      /**
       * Context-aware alias for `api.answerCallbackQuery`. Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
       *
       * Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#answercallbackquery
       */
      answerCallbackQuery(other2, signal) {
        return this.api.answerCallbackQuery(orThrow(this.callbackQuery, "answerCallbackQuery").id, typeof other2 === "string" ? { text: other2 } : other2, signal);
      }
      /**
       * Context-aware alias for `api.setChatMenuButton`. Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatmenubutton
       */
      setChatMenuButton(other2, signal) {
        return this.api.setChatMenuButton(other2, signal);
      }
      /**
       * Context-aware alias for `api.getChatMenuButton`. Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatmenubutton
       */
      getChatMenuButton(other2, signal) {
        return this.api.getChatMenuButton(other2, signal);
      }
      /**
       * Context-aware alias for `api.setMyDefaultAdministratorRights`. Use this method to the change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setmydefaultadministratorrights
       */
      setMyDefaultAdministratorRights(other2, signal) {
        return this.api.setMyDefaultAdministratorRights(other2, signal);
      }
      /**
       * Context-aware alias for `api.getMyDefaultAdministratorRights`. Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       */
      getMyDefaultAdministratorRights(other2, signal) {
        return this.api.getMyDefaultAdministratorRights(other2, signal);
      }
      /**
       * Context-aware alias for `api.editMessageText`. Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param text New text of the message, 1-4096 characters after entities parsing
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagetext
       */
      editMessageText(text, other2, signal) {
        var _a7, _b2, _c2, _d, _e2;
        const inlineId = this.inlineMessageId;
        return inlineId !== void 0 ? this.api.editMessageTextInline(inlineId, text, { business_connection_id: this.businessConnectionId, ...other2 }, signal) : this.api.editMessageText(orThrow(this.chatId, "editMessageText"), orThrow((_d = (_b2 = (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.message_id) !== null && _b2 !== void 0 ? _b2 : (_c2 = this.messageReaction) === null || _c2 === void 0 ? void 0 : _c2.message_id) !== null && _d !== void 0 ? _d : (_e2 = this.messageReactionCount) === null || _e2 === void 0 ? void 0 : _e2.message_id, "editMessageText"), text, { business_connection_id: this.businessConnectionId, ...other2 }, signal);
      }
      /**
       * Context-aware alias for `api.editMessageCaption`. Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagecaption
       */
      editMessageCaption(other2, signal) {
        var _a7, _b2, _c2, _d, _e2;
        const inlineId = this.inlineMessageId;
        return inlineId !== void 0 ? this.api.editMessageCaptionInline(inlineId, { business_connection_id: this.businessConnectionId, ...other2 }, signal) : this.api.editMessageCaption(orThrow(this.chatId, "editMessageCaption"), orThrow((_d = (_b2 = (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.message_id) !== null && _b2 !== void 0 ? _b2 : (_c2 = this.messageReaction) === null || _c2 === void 0 ? void 0 : _c2.message_id) !== null && _d !== void 0 ? _d : (_e2 = this.messageReactionCount) === null || _e2 === void 0 ? void 0 : _e2.message_id, "editMessageCaption"), { business_connection_id: this.businessConnectionId, ...other2 }, signal);
      }
      /**
       * Context-aware alias for `api.editMessageMedia`. Use this method to edit animation, audio, document, photo, or video messages, or to add media to text messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param media An object for a new media content of the message
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagemedia
       */
      editMessageMedia(media, other2, signal) {
        var _a7, _b2, _c2, _d, _e2;
        const inlineId = this.inlineMessageId;
        return inlineId !== void 0 ? this.api.editMessageMediaInline(inlineId, media, { business_connection_id: this.businessConnectionId, ...other2 }, signal) : this.api.editMessageMedia(orThrow(this.chatId, "editMessageMedia"), orThrow((_d = (_b2 = (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.message_id) !== null && _b2 !== void 0 ? _b2 : (_c2 = this.messageReaction) === null || _c2 === void 0 ? void 0 : _c2.message_id) !== null && _d !== void 0 ? _d : (_e2 = this.messageReactionCount) === null || _e2 === void 0 ? void 0 : _e2.message_id, "editMessageMedia"), media, { business_connection_id: this.businessConnectionId, ...other2 }, signal);
      }
      /**
       * Context-aware alias for `api.editMessageReplyMarkup`. Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagereplymarkup
       */
      editMessageReplyMarkup(other2, signal) {
        var _a7, _b2, _c2, _d, _e2;
        const inlineId = this.inlineMessageId;
        return inlineId !== void 0 ? this.api.editMessageReplyMarkupInline(inlineId, { business_connection_id: this.businessConnectionId, ...other2 }, signal) : this.api.editMessageReplyMarkup(orThrow(this.chatId, "editMessageReplyMarkup"), orThrow((_d = (_b2 = (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.message_id) !== null && _b2 !== void 0 ? _b2 : (_c2 = this.messageReaction) === null || _c2 === void 0 ? void 0 : _c2.message_id) !== null && _d !== void 0 ? _d : (_e2 = this.messageReactionCount) === null || _e2 === void 0 ? void 0 : _e2.message_id, "editMessageReplyMarkup"), { business_connection_id: this.businessConnectionId, ...other2 }, signal);
      }
      /**
       * Context-aware alias for `api.stopPoll`. Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#stoppoll
       */
      stopPoll(other2, signal) {
        var _a7, _b2, _c2, _d, _e2;
        return this.api.stopPoll(orThrow(this.chatId, "stopPoll"), orThrow((_d = (_b2 = (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.message_id) !== null && _b2 !== void 0 ? _b2 : (_c2 = this.messageReaction) === null || _c2 === void 0 ? void 0 : _c2.message_id) !== null && _d !== void 0 ? _d : (_e2 = this.messageReactionCount) === null || _e2 === void 0 ? void 0 : _e2.message_id, "stopPoll"), { business_connection_id: this.businessConnectionId, ...other2 }, signal);
      }
      /**
       * Context-aware alias for `api.deleteMessage`. Use this method to delete a message, including service messages, with the following limitations:
       * - A message can only be deleted if it was sent less than 48 hours ago.
       * - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.
       * - Bots can delete outgoing messages in private chats, groups, and supergroups.
       * - Bots can delete incoming messages in private chats.
       * - Bots granted can_post_messages permissions can delete outgoing messages in channels.
       * - If the bot is an administrator of a group, it can delete any message there.
       * - If the bot has can_delete_messages administrator right in a supergroup or a channel, it can delete any message there.
       * - If the bot has can_manage_direct_messages administrator right in a channel, it can delete any message in the corresponding direct messages chat.
       * Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletemessage
       */
      deleteMessage(signal) {
        var _a7, _b2, _c2, _d, _e2;
        return this.api.deleteMessage(orThrow(this.chatId, "deleteMessage"), orThrow((_d = (_b2 = (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.message_id) !== null && _b2 !== void 0 ? _b2 : (_c2 = this.messageReaction) === null || _c2 === void 0 ? void 0 : _c2.message_id) !== null && _d !== void 0 ? _d : (_e2 = this.messageReactionCount) === null || _e2 === void 0 ? void 0 : _e2.message_id, "deleteMessage"), signal);
      }
      /**
       * Context-aware alias for `api.deleteMessages`. Use this method to delete multiple messages simultaneously. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_ids A list of 1-100 identifiers of messages to delete. See deleteMessage for limitations on which messages can be deleted
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletemessages
       */
      deleteMessages(message_ids, signal) {
        return this.api.deleteMessages(orThrow(this.chatId, "deleteMessages"), message_ids, signal);
      }
      /**
       * Context-aware alias for `api.deleteBusinessMessages`. Delete messages on behalf of a business account. Requires the can_delete_outgoing_messages business bot right to delete messages sent by the bot itself, or the can_delete_all_messages business bot right to delete any message. Returns True on success.
       *
       * @param message_ids A list of 1-100 identifiers of messages to delete. All messages must be from the same chat. See deleteMessage for limitations on which messages can be deleted
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletebusinessmessages
       */
      deleteBusinessMessages(message_ids, signal) {
        return this.api.deleteBusinessMessages(orThrow(this.businessConnectionId, "deleteBusinessMessages"), message_ids, signal);
      }
      /**
       * Context-aware alias for `api.setBusinessAccountName`. Changes the first and last name of a managed business account. Requires the can_change_name business bot right. Returns True on success.
       *
       * @param first_name The new value of the first name for the business account; 1-64 characters
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setbusinessaccountname
       */
      setBusinessAccountName(first_name, other2, signal) {
        return this.api.setBusinessAccountName(orThrow(this.businessConnectionId, "setBusinessAccountName"), first_name, other2, signal);
      }
      /**
       * Context-aware alias for `api.setBusinessAccountUsername`. Changes the username of a managed business account. Requires the can_change_username business bot right. Returns True on success.
       *
       * @param username The new value of the username for the business account; 0-32 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setbusinessaccountusername
       */
      setBusinessAccountUsername(username, signal) {
        return this.api.setBusinessAccountUsername(orThrow(this.businessConnectionId, "setBusinessAccountUsername"), username, signal);
      }
      /**
       * Context-aware alias for `api.setBusinessAccountBio`. Changes the bio of a managed business account. Requires the can_change_bio business bot right. Returns True on success.
       *
       * @param bio The new value of the bio for the business account; 0-140 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setbusinessaccountbio
       */
      setBusinessAccountBio(bio, signal) {
        return this.api.setBusinessAccountBio(orThrow(this.businessConnectionId, "setBusinessAccountBio"), bio, signal);
      }
      /**
       * Context-aware alias for `api.setBusinessAccountProfilePhoto`. CsetBusinessAccountProfilePhotohanges the profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success.
       *
       * @param photo The new profile photo to set
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setbusinessaccountprofilephoto
       */
      setBusinessAccountProfilePhoto(photo, other2, signal) {
        return this.api.setBusinessAccountProfilePhoto(orThrow(this.businessConnectionId, "setBusinessAccountProfilePhoto"), photo, other2, signal);
      }
      /**
       * Context-aware alias for `api.removeBusinessAccountProfilePhoto`. Removes the current profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#removebusinessaccountprofilephoto
       */
      removeBusinessAccountProfilePhoto(other2, signal) {
        return this.api.removeBusinessAccountProfilePhoto(orThrow(this.businessConnectionId, "removeBusinessAccountProfilePhoto"), other2, signal);
      }
      /**
       * Context-aware alias for `api.setBusinessAccountGiftSettings`. Changes the privacy settings pertaining to incoming gifts in a managed business account. Requires the can_change_gift_settings business bot right. Returns True on success.
       *
       * @param show_gift_button Pass True, if a button for sending a gift to the user or by the business account must always be shown in the input field
       * @param accepted_gift_types Types of gifts accepted by the business account
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setbusinessaccountgiftsettings
       */
      setBusinessAccountGiftSettings(show_gift_button, accepted_gift_types, signal) {
        return this.api.setBusinessAccountGiftSettings(orThrow(this.businessConnectionId, "setBusinessAccountGiftSettings"), show_gift_button, accepted_gift_types, signal);
      }
      /**
       * Context-aware alias for `api.getBusinessAccountStarBalance`. Returns the amount of Telegram Stars owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns StarAmount on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getbusinessaccountstarbalance
       */
      getBusinessAccountStarBalance(signal) {
        return this.api.getBusinessAccountStarBalance(orThrow(this.businessConnectionId, "getBusinessAccountStarBalance"), signal);
      }
      /**
       * Context-aware alias for `api.transferBusinessAccountStars`. Transfers Telegram Stars from the business account balance to the bot's balance. Requires the can_transfer_stars business bot right. Returns True on success.
       *
       * @param star_count Number of Telegram Stars to transfer; 1-10000
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#transferbusinessaccountstars
       */
      transferBusinessAccountStars(star_count, signal) {
        return this.api.transferBusinessAccountStars(orThrow(this.businessConnectionId, "transferBusinessAccountStars"), star_count, signal);
      }
      /**
       * Context-aware alias for `api.getBusinessAccountGifts`. Returns the gifts received and owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns OwnedGifts on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getbusinessaccountgifts
       */
      getBusinessAccountGifts(other2, signal) {
        return this.api.getBusinessAccountGifts(orThrow(this.businessConnectionId, "getBusinessAccountGifts"), other2, signal);
      }
      /**
       * Context-aware alias for `api.convertGiftToStars`. Converts a given regular gift to Telegram Stars. Requires the can_convert_gifts_to_stars business bot right. Returns True on success.
       *
       * @param owned_gift_id Unique identifier of the regular gift that should be converted to Telegram Stars
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#convertgifttostars
       */
      convertGiftToStars(owned_gift_id, signal) {
        return this.api.convertGiftToStars(orThrow(this.businessConnectionId, "convertGiftToStars"), owned_gift_id, signal);
      }
      /**
       * Context-aware alias for `api.upgradeGift`. Upgrades a given regular gift to a unique gift. Requires the can_transfer_and_upgrade_gifts business bot right. Additionally requires the can_transfer_stars business bot right if the upgrade is paid. Returns True on success.
       *
       * @param owned_gift_id Unique identifier of the regular gift that should be upgraded to a unique one
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#upgradegift
       */
      upgradeGift(owned_gift_id, other2, signal) {
        return this.api.upgradeGift(orThrow(this.businessConnectionId, "upgradeGift"), owned_gift_id, other2, signal);
      }
      /**
       * Context-aware alias for `api.transferGift`. Transfers an owned unique gift to another user. Requires the can_transfer_and_upgrade_gifts business bot right. Requires can_transfer_stars business bot right if the transfer is paid. Returns True on success.
       *
       * @param owned_gift_id Unique identifier of the regular gift that should be transferred
       * @param new_owner_chat_id Unique identifier of the chat which will own the gift. The chat must be active in the last 24 hours.
       * @param star_count The amount of Telegram Stars that will be paid for the transfer from the business account balance. If positive, then the can_transfer_stars business bot right is required.
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#transfergift
       */
      transferGift(owned_gift_id, new_owner_chat_id, star_count, signal) {
        return this.api.transferGift(orThrow(this.businessConnectionId, "transferGift"), owned_gift_id, new_owner_chat_id, star_count, signal);
      }
      /**
       * Context-aware alias for `api.postStory`. Posts a story on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success.
       *
       * @param content Content of the story
       * @param active_period Period after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#poststory
       */
      postStory(content, active_period, other2, signal) {
        return this.api.postStory(orThrow(this.businessConnectionId, "postStory"), content, active_period, other2, signal);
      }
      /**
       * Context-aware alias for `api.repostStory`. Reposts a story on behalf of a business account from another business account. Both business accounts must be managed by the same bot, and the story on the source account must have been posted (or reposted) by the bot. Requires the can_manage_stories business bot right for both business accounts. Returns Story on success.
       *
       * @param active_period Period after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#repoststory
       */
      repostStory(active_period, other2, signal) {
        var _a7;
        const story = orThrow((_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.story, "repostStory");
        return this.api.repostStory(orThrow(this.businessConnectionId, "repostStory"), story.chat.id, story.id, active_period, other2, signal);
      }
      /**
       * Context-aware alias for `api.editStory`. Edits a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success.
       *
       * @param story_id Unique identifier of the story to edit
       * @param content Content of the story
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editstory
       */
      editStory(story_id, content, other2, signal) {
        return this.api.editStory(orThrow(this.businessConnectionId, "editStory"), story_id, content, other2, signal);
      }
      /**
       * Context-aware alias for `api.deleteStory`. Deletes a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns True on success.
       *
       * @param story_id Unique identifier of the story to delete
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletestory
       */
      deleteStory(story_id, signal) {
        return this.api.deleteStory(orThrow(this.businessConnectionId, "deleteStory"), story_id, signal);
      }
      /**
       * Context-aware alias for `api.sendSticker`. Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.
       *
       * @param sticker Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. Video and animated stickers can't be sent via an HTTP URL.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendsticker
       */
      replyWithSticker(sticker, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendSticker(orThrow(this.chatId, "sendSticker"), sticker, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.
       *
       * @param custom_emoji_ids A list of custom emoji identifiers
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getcustomemojistickers
       */
      getCustomEmojiStickers(signal) {
        var _a7, _b2;
        return this.api.getCustomEmojiStickers(((_b2 = (_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.entities) !== null && _b2 !== void 0 ? _b2 : []).filter((e4) => e4.type === "custom_emoji").map((e4) => e4.custom_emoji_id), signal);
      }
      /**
       * Context-aware alias for `api.sendGift`. Sends a gift to the given user. The gift can't be converted to Telegram Stars by the receiver. Returns True on success.
       *
       * @param gift_id Identifier of the gift
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendgift
       */
      replyWithGift(gift_id, other2, signal) {
        return this.api.sendGift(orThrow(this.from, "sendGift").id, gift_id, other2, signal);
      }
      /**
       * Context-aware alias for `api.giftPremiumSubscription`. Gifts a Telegram Premium subscription to the given user. Returns True on success.
       *
       * @param month_count Number of months the Telegram Premium subscription will be active for the user; must be one of 3, 6, or 12
       * @param star_count Number of Telegram Stars to pay for the Telegram Premium subscription; must be 1000 for 3 months, 1500 for 6 months, and 2500 for 12 months
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#giftpremiumsubscription
       */
      giftPremiumSubscription(month_count, star_count, other2, signal) {
        return this.api.giftPremiumSubscription(orThrow(this.from, "giftPremiumSubscription").id, month_count, star_count, other2, signal);
      }
      /**
       * Context-aware alias for `api.sendGift`. Sends a gift to the given channel chat. The gift can't be converted to Telegram Stars by the receiver. Returns True on success.
       *
       * @param gift_id Identifier of the gift
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendgift
       */
      replyWithGiftToChannel(gift_id, other2, signal) {
        return this.api.sendGiftToChannel(orThrow(this.chat, "sendGift").id, gift_id, other2, signal);
      }
      /**
       * Context-aware alias for `api.answerInlineQuery`. Use this method to send answers to an inline query. On success, True is returned.
       * No more than 50 results per query are allowed.
       *
       * Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities.
       *
       * @param results An array of results for the inline query
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#answerinlinequery
       */
      answerInlineQuery(results, other2, signal) {
        return this.api.answerInlineQuery(orThrow(this.inlineQuery, "answerInlineQuery").id, results, other2, signal);
      }
      /**
       * Context-aware alias for `api.savePreparedInlineMessage`. Stores a message that can be sent by a user of a Mini App. Returns a PreparedInlineMessage object.
       *
       * @param result An object describing the message to be sent
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#savepreparedinlinemessage
       */
      savePreparedInlineMessage(result, other2, signal) {
        return this.api.savePreparedInlineMessage(orThrow(this.from, "savePreparedInlineMessage").id, result, other2, signal);
      }
      /**
       * Context-aware alias for `api.sendInvoice`. Use this method to send invoices. On success, the sent Message is returned.
       *
       * @param title Product name, 1-32 characters
       * @param description Product description, 1-255 characters
       * @param payload Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
       * @param currency Three-letter ISO 4217 currency code, see more on currencies
       * @param prices Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendinvoice
       */
      replyWithInvoice(title, description, payload, currency, prices, other2, signal) {
        var _a7;
        const msg = this.msg;
        return this.api.sendInvoice(orThrow(this.chatId, "sendInvoice"), title, description, payload, currency, prices, {
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          direct_messages_topic_id: (_a7 = msg === null || msg === void 0 ? void 0 : msg.direct_messages_topic) === null || _a7 === void 0 ? void 0 : _a7.topic_id,
          ...other2
        }, signal);
      }
      /**
       * Context-aware alias for `api.answerShippingQuery`. If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
       *
       * @param shipping_query_id Unique identifier for the query to be answered
       * @param ok Pass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#answershippingquery
       */
      answerShippingQuery(ok2, other2, signal) {
        return this.api.answerShippingQuery(orThrow(this.shippingQuery, "answerShippingQuery").id, ok2, other2, signal);
      }
      /**
       * Context-aware alias for `api.answerPreCheckoutQuery`. Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
       *
       * @param ok Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#answerprecheckoutquery
       */
      answerPreCheckoutQuery(ok2, other2, signal) {
        return this.api.answerPreCheckoutQuery(orThrow(this.preCheckoutQuery, "answerPreCheckoutQuery").id, ok2, typeof other2 === "string" ? { error_message: other2 } : other2, signal);
      }
      /**
       * Context-aware alias for `api.refundStarPayment`. Refunds a successful payment in Telegram Stars.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#refundstarpayment
       */
      refundStarPayment(signal) {
        var _a7;
        return this.api.refundStarPayment(orThrow(this.from, "refundStarPayment").id, orThrow((_a7 = this.msg) === null || _a7 === void 0 ? void 0 : _a7.successful_payment, "refundStarPayment").telegram_payment_charge_id, signal);
      }
      /**
       * Context-aware alias for `api.editUserStarSubscription`. Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars. Returns True on success.
       *
       * @param telegram_payment_charge_id Telegram payment identifier for the subscription
       * @param is_canceled Pass True to cancel extension of the user subscription; the subscription must be active up to the end of the current subscription period. Pass False to allow the user to re-enable a subscription that was previously canceled by the bot.
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#edituserstarsubscription
       */
      editUserStarSubscription(telegram_payment_charge_id, is_canceled, signal) {
        return this.api.editUserStarSubscription(orThrow(this.from, "editUserStarSubscription").id, telegram_payment_charge_id, is_canceled, signal);
      }
      /**
       * Context-aware alias for `api.verifyUser`. Verifies a user on behalf of the organization which is represented by the bot. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#verifyuser
       */
      verifyUser(other2, signal) {
        return this.api.verifyUser(orThrow(this.from, "verifyUser").id, other2, signal);
      }
      /**
       * Context-aware alias for `api.verifyChat`. Verifies a chat on behalf of the organization which is represented by the bot. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#verifychat
       */
      verifyChat(other2, signal) {
        return this.api.verifyChat(orThrow(this.chatId, "verifyChat"), other2, signal);
      }
      /**
       * Context-aware alias for `api.removeUserVerification`. Removes verification from a user who is currently verified on behalf of the organization represented by the bot. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#removeuserverification
       */
      removeUserVerification(signal) {
        return this.api.removeUserVerification(orThrow(this.from, "removeUserVerification").id, signal);
      }
      /**
       * Context-aware alias for `api.removeChatVerification`. Removes verification from a chat that is currently verified on behalf of the organization represented by the bot. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#removechatverification
       */
      removeChatVerification(signal) {
        return this.api.removeChatVerification(orThrow(this.chatId, "removeChatVerification"), signal);
      }
      /**
       * Context-aware alias for `api.readBusinessMessage`. Marks incoming message as read on behalf of a business account. Requires the can_read_messages business bot right. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#readbusinessmessage
       */
      readBusinessMessage(signal) {
        return this.api.readBusinessMessage(orThrow(this.businessConnectionId, "readBusinessMessage"), orThrow(this.chatId, "readBusinessMessage"), orThrow(this.msgId, "readBusinessMessage"), signal);
      }
      /**
       * Context-aware alias for `api.setPassportDataErrors`. Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.
       *
       * Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
       *
       * @param errors An array describing the errors
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setpassportdataerrors
       */
      setPassportDataErrors(errors, signal) {
        return this.api.setPassportDataErrors(orThrow(this.from, "setPassportDataErrors").id, errors, signal);
      }
      /**
       * Context-aware alias for `api.sendGame`. Use this method to send a game. On success, the sent Message is returned.
       *
       * @param game_short_name Short name of the game, serves as the unique identifier for the game. Set up your games via BotFather.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendgame
       */
      replyWithGame(game_short_name, other2, signal) {
        const msg = this.msg;
        return this.api.sendGame(orThrow(this.chatId, "sendGame"), game_short_name, {
          business_connection_id: this.businessConnectionId,
          ...(msg === null || msg === void 0 ? void 0 : msg.is_topic_message) ? { message_thread_id: msg.message_thread_id } : {},
          ...other2
        }, signal);
      }
    };
    exports2.Context = Context;
    Context.has = checker;
    function orThrow(value, method) {
      if (value === void 0) {
        throw new Error(`Missing information for API call to ${method}`);
      }
      return value;
    }
    __name(orThrow, "orThrow");
    function triggerFn(trigger) {
      return toArray2(trigger).map((t5) => typeof t5 === "string" ? (txt) => txt === t5 ? t5 : null : (txt) => txt.match(t5));
    }
    __name(triggerFn, "triggerFn");
    function match2(ctx, content, triggers) {
      for (const t5 of triggers) {
        const res = t5(content);
        if (res) {
          ctx.match = res;
          return true;
        }
      }
      return false;
    }
    __name(match2, "match");
    function toArray2(e4) {
      return Array.isArray(e4) ? e4 : [e4];
    }
    __name(toArray2, "toArray");
  }
});

// node_modules/grammy/out/composer.js
var require_composer2 = __commonJS({
  "node_modules/grammy/out/composer.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Composer = exports2.BotError = void 0;
    exports2.run = run2;
    var context_js_1 = require_context();
    var BotError = class extends Error {
      static {
        __name(this, "BotError");
      }
      constructor(error40, ctx) {
        super(generateBotErrorMessage(error40));
        this.error = error40;
        this.ctx = ctx;
        this.name = "BotError";
        if (error40 instanceof Error)
          this.stack = error40.stack;
      }
    };
    exports2.BotError = BotError;
    function generateBotErrorMessage(error40) {
      let msg;
      if (error40 instanceof Error) {
        msg = `${error40.name} in middleware: ${error40.message}`;
      } else {
        const type = typeof error40;
        msg = `Non-error value of type ${type} thrown in middleware`;
        switch (type) {
          case "bigint":
          case "boolean":
          case "number":
          case "symbol":
            msg += `: ${error40}`;
            break;
          case "string":
            msg += `: ${String(error40).substring(0, 50)}`;
            break;
          default:
            msg += "!";
            break;
        }
      }
      return msg;
    }
    __name(generateBotErrorMessage, "generateBotErrorMessage");
    function flatten2(mw) {
      return typeof mw === "function" ? mw : (ctx, next) => mw.middleware()(ctx, next);
    }
    __name(flatten2, "flatten");
    function concat2(first2, andThen) {
      return async (ctx, next) => {
        let nextCalled = false;
        await first2(ctx, async () => {
          if (nextCalled)
            throw new Error("`next` already called before!");
          else
            nextCalled = true;
          await andThen(ctx, next);
        });
      };
    }
    __name(concat2, "concat");
    function pass(_ctx, next) {
      return next();
    }
    __name(pass, "pass");
    var leaf = /* @__PURE__ */ __name(() => Promise.resolve(), "leaf");
    async function run2(middleware, ctx) {
      await middleware(ctx, leaf);
    }
    __name(run2, "run");
    var Composer2 = class _Composer {
      static {
        __name(this, "Composer");
      }
      /**
       * Constructs a new composer based on the provided middleware. If no
       * middleware is given, the composer instance will simply make all context
       * objects pass through without touching them.
       *
       * @param middleware The middleware to compose
       */
      constructor(...middleware) {
        this.handler = middleware.length === 0 ? pass : middleware.map(flatten2).reduce(concat2);
      }
      middleware() {
        return this.handler;
      }
      /**
       * Registers some middleware that receives all updates. It is installed by
       * concatenating it to the end of all previously installed middleware.
       *
       * Often, this method is used to install middleware that behaves like a
       * plugin, for example session middleware.
       * ```ts
       * bot.use(session())
       * ```
       *
       * This method returns a new instance of composer. The returned instance can
       * be further extended, and all changes will be regarded here. Confer the
       * [documentation](https://grammy.dev/advanced/middleware) on the
       * website if you want to know more about how the middleware system in
       * grammY works, especially when it comes to chaining the method calls
       * (`use( ... ).use( ... ).use( ... )`).
       *
       * @param middleware The middleware to register
       */
      use(...middleware) {
        const composer = new _Composer(...middleware);
        this.handler = concat2(this.handler, flatten2(composer));
        return composer;
      }
      /**
       * Registers some middleware that will only be executed for some specific
       * updates, namely those matching the provided filter query. Filter queries
       * are a concise way to specify which updates you are interested in.
       *
       * Here are some examples of valid filter queries:
       * ```ts
       * // All kinds of message updates
       * bot.on('message', ctx => { ... })
       *
       * // Only text messages
       * bot.on('message:text', ctx => { ... })
       *
       * // Only text messages with URL
       * bot.on('message:entities:url', ctx => { ... })
       *
       * // Text messages and text channel posts
       * bot.on(':text', ctx => { ... })
       *
       * // Messages with URL in text or caption (i.e. entities or caption entities)
       * bot.on('message::url', ctx => { ... })
       *
       * // Messages or channel posts with URL in text or caption
       * bot.on('::url', ctx => { ... })
       * ```
       *
       * You can use autocomplete in VS Code to see all available filter queries.
       * Check out the
       * [documentation](https://grammy.dev/guide/filter-queries) on the
       * website to learn more about filter queries in grammY.
       *
       * It is possible to pass multiple filter queries in an array, i.e.
       * ```ts
       * // Matches all text messages and edited text messages that contain a URL
       * bot.on(['message:entities:url', 'edited_message:entities:url'], ctx => { ... })
       * ```
       *
       * Your middleware will be executed if _any of the provided filter queries_
       * matches (logical OR).
       *
       * If you instead want to match _all of the provided filter queries_
       * (logical AND), you can chain the `.on` calls:
       * ```ts
       * // Matches all messages and channel posts that both a) contain a URL and b) are forwards
       * bot.on('::url').on(':forward_origin', ctx => { ... })
       * ```
       *
       * @param filter The filter query to use, may also be an array of queries
       * @param middleware The middleware to register behind the given filter
       */
      on(filter5, ...middleware) {
        return this.filter(context_js_1.Context.has.filterQuery(filter5), ...middleware);
      }
      /**
       * Registers some middleware that will only be executed when the message
       * contains some text. Is it possible to pass a regular expression to match:
       * ```ts
       * // Match some text (exact match)
       * bot.hears('I love grammY', ctx => ctx.reply('And grammY loves you! <3'))
       * // Match a regular expression
       * bot.hears(/\/echo (.+)/, ctx => ctx.reply(ctx.match[1]))
       * ```
       * Note how `ctx.match` will contain the result of the regular expression.
       * Here it is a `RegExpMatchArray` object, so `ctx.match[1]` refers to the
       * part of the regex that was matched by `(.+)`, i.e. the text that comes
       * after “/echo”.
       *
       * You can pass an array of triggers. Your middleware will be executed if at
       * least one of them matches.
       *
       * Both text and captions of the received messages will be scanned. For
       * example, when a photo is sent to the chat and its caption matches the
       * trigger, your middleware will be executed.
       *
       * If you only want to match text messages and not captions, you can do
       * this:
       * ```ts
       * // Only matches text messages (and channel posts) for the regex
       * bot.on(':text').hears(/\/echo (.+)/, ctx => { ... })
       * ```
       *
       * @param trigger The text to look for
       * @param middleware The middleware to register
       */
      hears(trigger, ...middleware) {
        return this.filter(context_js_1.Context.has.text(trigger), ...middleware);
      }
      /**
       * Registers some middleware that will only be executed when a certain
       * command is found.
       * ```ts
       * // Reacts to /start commands
       * bot.command('start', ctx => { ... })
       * // Reacts to /help commands
       * bot.command('help', ctx => { ... })
       * ```
       *
       * The rest of the message (excluding the command, and trimmed) is provided
       * via `ctx.match`.
       *
       * > **Did you know?** You can use deep linking
       * > (https://core.telegram.org/bots/features#deep-linking) to let users
       * > start your bot with a custom payload. As an example, send someone the
       * > link https://t.me/name-of-your-bot?start=custom-payload and register a
       * > start command handler on your bot with grammY. As soon as the user
       * > starts your bot, you will receive `custom-payload` in the `ctx.match`
       * > property!
       * > ```ts
       * > bot.command('start', ctx => {
       * >   const payload = ctx.match // will be 'custom-payload'
       * > })
       * > ```
       *
       * Note that commands are not matched in captions or in the middle of the
       * text.
       * ```ts
       * bot.command('start', ctx => { ... })
       * // ... does not match:
       * // A message saying: “some text /start some more text”
       * // A photo message with the caption “/start”
       * ```
       *
       * By default, commands are detected in channel posts, too. This means that
       * `ctx.message` is potentially `undefined`, so you should use `ctx.msg`
       * instead to grab both messages and channel posts. Alternatively, if you
       * want to limit your bot to finding commands only in private and group
       * chats, you can use `bot.on('message').command('start', ctx => { ... })`,
       * or even store a message-only version of your bot in a variable like so:
       * ```ts
       * const m = bot.on('message')
       *
       * m.command('start', ctx => { ... })
       * m.command('help', ctx => { ... })
       * // etc
       * ```
       *
       * If you need more freedom matching your commands, check out the `commands`
       * plugin.
       *
       * @param command The command to look for
       * @param middleware The middleware to register
       */
      command(command2, ...middleware) {
        return this.filter(context_js_1.Context.has.command(command2), ...middleware);
      }
      /**
       * Registers some middleware that will only be added when a new reaction of
       * the given type is added to a message.
       * ```ts
       * // Reacts to new '👍' reactions
       * bot.reaction('👍', ctx => { ... })
       * // Reacts to new '👍' or '👎' reactions
       * bot.reaction(['👍', '👎'], ctx => { ... })
       * ```
       *
       * > Note that you have to enable `message_reaction` updates in
       * `allowed_updates` if you want your bot to receive updates about message
       * reactions.
       *
       * `bot.reaction` will trigger if:
       * - a new emoji reaction is added to a message
       * - a new custom emoji reaction is added a message
       *
       * `bot.reaction` will not trigger if:
       * - a reaction is removed
       * - an anonymous reaction count is updated, such as on channel posts
       * - `message_reaction` updates are not enabled for your bot
       *
       * @param reaction The reaction to look for
       * @param middleware The middleware to register
       */
      reaction(reaction, ...middleware) {
        return this.filter(context_js_1.Context.has.reaction(reaction), ...middleware);
      }
      /**
       * Registers some middleware for certain chat types only. For example, you
       * can use this method to only receive updates from private chats. The four
       * chat types are `"channel"`, `"supergroup"`, `"group"`, and `"private"`.
       * This is especially useful when combined with other filtering logic. For
       * example, this is how can you respond to `/start` commands only from
       * private chats:
       * ```ts
       * bot.chatType("private").command("start", ctx => { ... })
       * ```
       *
       * Naturally, you can also use this method on its own.
       * ```ts
       * // Private chats only
       * bot.chatType("private", ctx => { ... });
       * // Channels only
       * bot.chatType("channel", ctx => { ... });
       * ```
       *
       * You can pass an array of chat types if you want your middleware to run
       * for any of several provided chat types.
       * ```ts
       * // Groups and supergroups only
       * bot.chatType(["group", "supergroup"], ctx => { ... });
       * ```
       * [Remember](https://grammy.dev/guide/context#shortcuts) also that you
       * can access the chat type via `ctx.chat.type`.
       *
       * @param chatType The chat type
       * @param middleware The middleware to register
       */
      chatType(chatType, ...middleware) {
        return this.filter(context_js_1.Context.has.chatType(chatType), ...middleware);
      }
      /**
       * Registers some middleware for callback queries, i.e. the updates that
       * Telegram delivers to your bot when a user clicks an inline button (that
       * is a button under a message).
       *
       * This method is essentially the same as calling
       * ```ts
       * bot.on('callback_query:data', ctx => { ... })
       * ```
       * but it also allows you to match the query data against a given text or
       * regular expression.
       *
       * ```ts
       * // Create an inline keyboard
       * const keyboard = new InlineKeyboard().text('Go!', 'button-payload')
       * // Send a message with the keyboard
       * await bot.api.sendMessage(chat_id, 'Press a button!', {
       *   reply_markup: keyboard
       * })
       * // Listen to users pressing buttons with that specific payload
       * bot.callbackQuery('button-payload', ctx => { ... })
       *
       * // Listen to users pressing any button your bot ever sent
       * bot.on('callback_query:data', ctx => { ... })
       * ```
       *
       * Always remember to call `answerCallbackQuery`—even if you don't perform
       * any action: https://core.telegram.org/bots/api#answercallbackquery
       * ```ts
       * bot.on('callback_query:data', async ctx => {
       *   await ctx.answerCallbackQuery()
       * })
       * ```
       *
       * You can pass an array of triggers. Your middleware will be executed if at
       * least one of them matches.
       *
       * @param trigger The string to look for in the payload
       * @param middleware The middleware to register
       */
      callbackQuery(trigger, ...middleware) {
        return this.filter(context_js_1.Context.has.callbackQuery(trigger), ...middleware);
      }
      /**
       * Registers some middleware for game queries, i.e. the updates that
       * Telegram delivers to your bot when a user clicks an inline button for the
       * HTML5 games platform on Telegram.
       *
       * This method is essentially the same as calling
       * ```ts
       * bot.on('callback_query:game_short_name', ctx => { ... })
       * ```
       * but it also allows you to match the query data against a given text or
       * regular expression.
       *
       * You can pass an array of triggers. Your middleware will be executed if at
       * least one of them matches.
       *
       * @param trigger The string to look for in the payload
       * @param middleware The middleware to register
       */
      gameQuery(trigger, ...middleware) {
        return this.filter(context_js_1.Context.has.gameQuery(trigger), ...middleware);
      }
      /**
       * Registers middleware for inline queries. Telegram sends an inline query
       * to your bot whenever a user types “@your_bot_name ...” into a text field
       * in Telegram. You bot will then receive the entered search query and can
       * respond with a number of results (text, images, etc) that the user can
       * pick from to send a message _via_ your bot to the respective chat. Check
       * out https://core.telegram.org/bots/inline to read more about inline bots.
       *
       * > Note that you have to enable inline mode for you bot by contacting
       * > @BotFather first.
       *
       * ```ts
       * // Listen for users typing “@your_bot_name query”
       * bot.inlineQuery('query', async ctx => {
       *   // Answer the inline query, confer https://core.telegram.org/bots/api#answerinlinequery
       *   await ctx.answerInlineQuery( ... )
       * })
       * ```
       *
       * @param trigger The inline query text to match
       * @param middleware The middleware to register
       */
      inlineQuery(trigger, ...middleware) {
        return this.filter(context_js_1.Context.has.inlineQuery(trigger), ...middleware);
      }
      /**
       * Registers middleware for the ChosenInlineResult by the given id or ids.
       * ChosenInlineResult represents a result of an inline query that was chosen
       * by the user and sent to their chat partner. Check out
       * https://core.telegram.org/bots/api#choseninlineresult to read more about
       * chosen inline results.
       *
       * ```ts
       * bot.chosenInlineResult('id', async ctx => {
       *   const id = ctx.result_id;
       *   // Your code
       * })
       * ```
       *
       * @param resultId An id or array of ids
       * @param middleware The middleware to register
       */
      chosenInlineResult(resultId, ...middleware) {
        return this.filter(context_js_1.Context.has.chosenInlineResult(resultId), ...middleware);
      }
      /**
       * Registers middleware for pre-checkout queries. Telegram sends a
       * pre-checkout query to your bot whenever a user has confirmed their
       * payment and shipping details. You bot will then receive all information
       * about the order and has to respond within 10 seconds with a confirmation
       * of whether everything is alright (goods are available, etc.) and the bot
       * is ready to proceed with the order. Check out
       * https://core.telegram.org/bots/api#precheckoutquery to read more about
       * pre-checkout queries.
       *
       * ```ts
       * bot.preCheckoutQuery('invoice_payload', async ctx => {
       *   // Answer the pre-checkout query, confer https://core.telegram.org/bots/api#answerprecheckoutquery
       *   await ctx.answerPreCheckoutQuery( ... )
       * })
       * ```
       *
       * @param trigger The string to look for in the invoice payload
       * @param middleware The middleware to register
       */
      preCheckoutQuery(trigger, ...middleware) {
        return this.filter(context_js_1.Context.has.preCheckoutQuery(trigger), ...middleware);
      }
      /**
       * Registers middleware for shipping queries. If you sent an invoice
       * requesting a shipping address and the parameter _is_flexible_ was
       * specified, Telegram will send a shipping query to your bot whenever a
       * user has confirmed their shipping details. You bot will then receive the
       * shipping information and can respond with a confirmation of whether
       * delivery to the specified address is possible. Check out
       * https://core.telegram.org/bots/api#shippingquery to read more about
       * shipping queries.
       *
       * ```ts
       * bot.shippingQuery('invoice_payload', async ctx => {
       *   // Answer the shipping query, confer https://core.telegram.org/bots/api#answershippingquery
       *   await ctx.answerShippingQuery( ... )
       * })
       * ```
       *
       * @param trigger The string to look for in the invoice payload
       * @param middleware The middleware to register
       */
      shippingQuery(trigger, ...middleware) {
        return this.filter(context_js_1.Context.has.shippingQuery(trigger), ...middleware);
      }
      filter(predicate, ...middleware) {
        const composer = new _Composer(...middleware);
        this.branch(predicate, composer, pass);
        return composer;
      }
      /**
       * > This is an advanced method of grammY.
       *
       * Registers middleware behind a custom filter function that operates on the
       * context object and decides whether or not to execute the middleware. In
       * other words, the middleware will only be executed if the given predicate
       * returns `false` for the given context object. Otherwise, it will be
       * skipped and the next middleware will be executed. Note that the predicate
       * may be asynchronous, i.e. it can return a Promise of a boolean.
       *
       * This method is the same using `filter` (normal usage) with a negated
       * predicate.
       *
       * @param predicate The predicate to check
       * @param middleware The middleware to register
       */
      drop(predicate, ...middleware) {
        return this.filter(async (ctx) => !await predicate(ctx), ...middleware);
      }
      /**
       * > This is an advanced method of grammY.
       *
       * Registers some middleware that runs concurrently to the executing
       * middleware stack.
       * ```ts
       * bot.use( ... ) // will run first
       * bot.fork( ... ) // will be started second, but run concurrently
       * bot.use( ... ) // will also be run second
       * ```
       * In the first middleware, as soon as `next`'s Promise resolves, both forks
       * have completed.
       *
       * Both the fork and the downstream middleware are awaited with
       * `Promise.all`, so you will only be able to catch at most one error (the
       * one that is thrown first).
       *
       * In contrast to the other middleware methods on composer, `fork` does not
       * simply return the composer connected to the main middleware stack.
       * Instead, it returns the created composer _of the fork_ connected to the
       * middleware stack. This allows for the following pattern.
       * ```ts
       * // Middleware will be run concurrently!
       * bot.fork().on('message', ctx => { ... })
       * ```
       *
       * @param middleware The middleware to run concurrently
       */
      fork(...middleware) {
        const composer = new _Composer(...middleware);
        const fork = flatten2(composer);
        this.use((ctx, next) => Promise.all([next(), run2(fork, ctx)]));
        return composer;
      }
      /**
       * > This is an advanced method of grammY.
       *
       * Executes some middleware that can be generated on the fly for each
       * context. Pass a factory function that creates some middleware (or a
       * middleware array even). The factory function will be called once per
       * context, and its result will be executed with the context object.
       * ```ts
       * // The middleware returned by `createMyMiddleware` will be used only once
       * bot.lazy(ctx => createMyMiddleware(ctx))
       * ```
       *
       * You may generate this middleware in an `async` fashion.
       *
       * You can decide to return an empty array (`[]`) if you don't want to run
       * any middleware for a given context object. This is equivalent to
       * returning an empty instance of `Composer`.
       *
       * @param middlewareFactory The factory function creating the middleware
       */
      lazy(middlewareFactory) {
        return this.use(async (ctx, next) => {
          const middleware = await middlewareFactory(ctx);
          const arr = Array.isArray(middleware) ? middleware : [middleware];
          await flatten2(new _Composer(...arr))(ctx, next);
        });
      }
      /**
       * > This is an advanced method of grammY.
       *
       * _Not to be confused with the `router` plugin._
       *
       * This method is an alternative to the `router` plugin. It allows you to
       * branch between different middleware per context object. You can pass two
       * things to it:
       * 1. A routing function
       * 2. Different middleware identified by key
       *
       * The routing function decides based on the context object which middleware
       * to run. Each middleware is identified by a key, so the routing function
       * simply returns the key of that middleware.
       * ```ts
       * // Define different route handlers
       * const routeHandlers = {
       *   evenUpdates: (ctx: Context) => { ... }
       *   oddUpdates: (ctx: Context) => { ... }
       * }
       * // Decide for a context object which one to pick
       * const router = (ctx: Context) => ctx.update.update_id % 2 === 0
       *   ? 'evenUpdates'
       *   : 'oddUpdates'
       * // Route it!
       * bot.route(router, routeHandlers)
       * ```
       *
       * Optionally, you can pass a third option that is used as fallback
       * middleware if your route function returns `undefined`, or if the key
       * returned by your router has no middleware associated with it.
       *
       * This method may need less setup than first instantiating a `Router`, but
       * for more complex setups, having a `Router` may be more readable.
       *
       * @param router The routing function to use
       * @param routeHandlers Handlers for every route
       * @param fallback Optional fallback middleware if no route matches
       */
      route(router, routeHandlers, fallback = pass) {
        return this.lazy(async (ctx) => {
          var _a7;
          const route = await router(ctx);
          return (_a7 = route === void 0 || !routeHandlers[route] ? fallback : routeHandlers[route]) !== null && _a7 !== void 0 ? _a7 : [];
        });
      }
      /**
       * > This is an advanced method of grammY.
       *
       * Allows you to branch between two cases for a given context object.
       *
       * This method takes a predicate function that is tested once per context
       * object. If it returns `true`, the first supplied middleware is executed.
       * If it returns `false`, the second supplied middleware is executed. Note
       * that the predicate may be asynchronous, i.e. it can return a Promise of a
       * boolean.
       *
       * @param predicate The predicate to check
       * @param trueMiddleware The middleware for the `true` case
       * @param falseMiddleware The middleware for the `false` case
       */
      branch(predicate, trueMiddleware, falseMiddleware) {
        return this.lazy(async (ctx) => await predicate(ctx) ? trueMiddleware : falseMiddleware);
      }
      /**
       * > This is an advanced function of grammY.
       *
       * Installs an error boundary that catches errors that happen only inside
       * the given middleware. This allows you to install custom error handlers
       * that protect some parts of your bot. Errors will not be able to bubble
       * out of this part of your middleware system, unless the supplied error
       * handler rethrows them, in which case the next surrounding error boundary
       * will catch the error.
       *
       * Example usage:
       * ```ts
       * function errHandler(err: BotError) {
       *   console.error('Error boundary caught error!', err)
       * }
       *
       * const safe =
       *   // All passed middleware will be protected by the error boundary.
       *   bot.errorBoundary(errHandler, middleware0, middleware1, middleware2)
       *
       * // Those will also be protected!
       * safe.on('message', middleware3)
       *
       * // No error from `middleware4` will reach the `errHandler` from above,
       * // as errors are suppressed.
       *
       * // do nothing on error (suppress error), and run outside middleware
       * const suppress = (_err: BotError, next: NextFunction) => { return next() }
       * safe.errorBoundary(suppress).on('edited_message', middleware4)
       * ```
       *
       * Check out the
       * [documentation](https://grammy.dev/guide/errors#error-boundaries) on
       * the website to learn more about error boundaries.
       *
       * @param errorHandler The error handler to use
       * @param middleware The middleware to protect
       */
      errorBoundary(errorHandler, ...middleware) {
        const composer = new _Composer(...middleware);
        const bound = flatten2(composer);
        this.use(async (ctx, next) => {
          let nextCalled = false;
          const cont = /* @__PURE__ */ __name(() => (nextCalled = true, Promise.resolve()), "cont");
          try {
            await bound(ctx, cont);
          } catch (err2) {
            nextCalled = false;
            await errorHandler(new BotError(err2, ctx), cont);
          }
          if (nextCalled)
            await next();
        });
        return composer;
      }
    };
    exports2.Composer = Composer2;
  }
});

// node_modules/grammy/out/platform.node.js
var require_platform_node = __commonJS({
  "node_modules/grammy/out/platform.node.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.defaultAdapter = exports2.itrToStream = exports2.debug = void 0;
    exports2.baseFetchConfig = baseFetchConfig;
    var http_1 = __require("http");
    var https_1 = __require("https");
    var stream_1 = __require("stream");
    var debug_1 = require_src();
    Object.defineProperty(exports2, "debug", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return debug_1.debug;
    }, "get") });
    var itrToStream = /* @__PURE__ */ __name((itr) => stream_1.Readable.from(itr, { objectMode: false }), "itrToStream");
    exports2.itrToStream = itrToStream;
    var httpAgents = /* @__PURE__ */ new Map();
    var httpsAgents = /* @__PURE__ */ new Map();
    function getCached(map3, key, otherwise2) {
      let value = map3.get(key);
      if (value === void 0) {
        value = otherwise2();
        map3.set(key, value);
      }
      return value;
    }
    __name(getCached, "getCached");
    function baseFetchConfig(apiRoot) {
      if (apiRoot.startsWith("https:")) {
        return {
          compress: true,
          agent: getCached(httpsAgents, apiRoot, () => new https_1.Agent({ keepAlive: true }))
        };
      } else if (apiRoot.startsWith("http:")) {
        return {
          agent: getCached(httpAgents, apiRoot, () => new http_1.Agent({ keepAlive: true }))
        };
      } else
        return {};
    }
    __name(baseFetchConfig, "baseFetchConfig");
    exports2.defaultAdapter = "express";
  }
});

// node_modules/grammy/out/core/error.js
var require_error3 = __commonJS({
  "node_modules/grammy/out/core/error.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HttpError = exports2.GrammyError = void 0;
    exports2.toGrammyError = toGrammyError;
    exports2.toHttpError = toHttpError;
    var platform_node_js_1 = require_platform_node();
    var debug3 = (0, platform_node_js_1.debug)("grammy:warn");
    var GrammyError = class extends Error {
      static {
        __name(this, "GrammyError");
      }
      constructor(message, err2, method, payload) {
        var _a7;
        super(`${message} (${err2.error_code}: ${err2.description})`);
        this.method = method;
        this.payload = payload;
        this.ok = false;
        this.name = "GrammyError";
        this.error_code = err2.error_code;
        this.description = err2.description;
        this.parameters = (_a7 = err2.parameters) !== null && _a7 !== void 0 ? _a7 : {};
      }
    };
    exports2.GrammyError = GrammyError;
    function toGrammyError(err2, method, payload) {
      switch (err2.error_code) {
        case 401:
          debug3("Error 401 means that your bot token is wrong, talk to https://t.me/BotFather to check it.");
          break;
        case 409:
          debug3("Error 409 means that you are running your bot several times on long polling. Consider revoking the bot token if you believe that no other instance is running.");
          break;
      }
      return new GrammyError(`Call to '${method}' failed!`, err2, method, payload);
    }
    __name(toGrammyError, "toGrammyError");
    var HttpError = class extends Error {
      static {
        __name(this, "HttpError");
      }
      constructor(message, error40) {
        super(message);
        this.error = error40;
        this.name = "HttpError";
      }
    };
    exports2.HttpError = HttpError;
    function isTelegramError(err2) {
      return typeof err2 === "object" && err2 !== null && "status" in err2 && "statusText" in err2;
    }
    __name(isTelegramError, "isTelegramError");
    function toHttpError(method, sensitiveLogs, err2) {
      let msg = `Network request for '${method}' failed!`;
      if (isTelegramError(err2))
        msg += ` (${err2.status}: ${err2.statusText})`;
      if (sensitiveLogs && err2 instanceof Error)
        msg += ` ${err2.message}`;
      return new HttpError(msg, err2);
    }
    __name(toHttpError, "toHttpError");
  }
});

// node_modules/@grammyjs/types/mod.js
var require_mod = __commonJS({
  "node_modules/@grammyjs/types/mod.js"() {
    init_esbuild_shims();
  }
});

// node_modules/grammy/out/types.node.js
var require_types_node = __commonJS({
  "node_modules/grammy/out/types.node.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.InputFile = void 0;
    var fs_1 = __require("fs");
    var node_fetch_1 = require_lib4();
    var path_1 = __require("path");
    var platform_node_1 = require_platform_node();
    var debug3 = (0, platform_node_1.debug)("grammy:warn");
    __exportStar(require_mod(), exports2);
    var InputFile = class _InputFile {
      static {
        __name(this, "InputFile");
      }
      /**
       * Constructs an `InputFile` that can be used in the API to send files.
       *
       * @param file A path to a local file or a `Buffer` or a `fs.ReadStream` that specifies the file data
       * @param filename Optional name of the file
       */
      constructor(file2, filename) {
        this.consumed = false;
        this.fileData = file2;
        filename !== null && filename !== void 0 ? filename : filename = this.guessFilename(file2);
        this.filename = filename;
        if (typeof file2 === "string" && (file2.startsWith("http:") || file2.startsWith("https:"))) {
          debug3(`InputFile received the local file path '${file2}' that looks like a URL. Is this a mistake?`);
        }
      }
      guessFilename(file2) {
        if (typeof file2 === "string")
          return (0, path_1.basename)(file2);
        if ("url" in file2)
          return (0, path_1.basename)(file2.url);
        if (!(file2 instanceof URL))
          return void 0;
        if (file2.pathname !== "/") {
          const filename = (0, path_1.basename)(file2.pathname);
          if (filename)
            return filename;
        }
        return (0, path_1.basename)(file2.hostname);
      }
      /**
       * Internal method. Do not use.
       *
       * Converts this instance into a binary representation that can be sent to
       * the Bot API server in the request body.
       */
      async toRaw() {
        if (this.consumed) {
          throw new Error("Cannot reuse InputFile data source!");
        }
        const data = this.fileData;
        if (typeof data === "string")
          return (0, fs_1.createReadStream)(data);
        if (data instanceof URL) {
          return data.protocol === "file" ? (0, fs_1.createReadStream)(data.pathname) : fetchFile(data);
        }
        if ("url" in data)
          return fetchFile(data.url);
        if (data instanceof Uint8Array)
          return data;
        if (typeof data === "function") {
          return new _InputFile(await data()).toRaw();
        }
        this.consumed = true;
        return data;
      }
      toJSON() {
        throw new Error("InputFile instances must be sent via grammY");
      }
    };
    exports2.InputFile = InputFile;
    async function* fetchFile(url3) {
      const { body: body2 } = await (0, node_fetch_1.default)(url3);
      for await (const chunk of body2) {
        if (typeof chunk === "string") {
          throw new Error(`Could not transfer file, received string data instead of bytes from '${url3}'`);
        }
        yield chunk;
      }
    }
    __name(fetchFile, "fetchFile");
  }
});

// node_modules/grammy/out/types.js
var require_types10 = __commonJS({
  "node_modules/grammy/out/types.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_types_node(), exports2);
  }
});

// node_modules/grammy/out/core/payload.js
var require_payload = __commonJS({
  "node_modules/grammy/out/core/payload.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.requiresFormDataUpload = requiresFormDataUpload;
    exports2.createJsonPayload = createJsonPayload;
    exports2.createFormDataPayload = createFormDataPayload;
    var platform_node_js_1 = require_platform_node();
    var types_js_1 = require_types10();
    function requiresFormDataUpload(payload) {
      return payload instanceof types_js_1.InputFile || typeof payload === "object" && payload !== null && Object.values(payload).some((v2) => Array.isArray(v2) ? v2.some(requiresFormDataUpload) : v2 instanceof types_js_1.InputFile || requiresFormDataUpload(v2));
    }
    __name(requiresFormDataUpload, "requiresFormDataUpload");
    function str2(value) {
      return JSON.stringify(value, (_2, v2) => v2 !== null && v2 !== void 0 ? v2 : void 0);
    }
    __name(str2, "str");
    function createJsonPayload(payload) {
      return {
        method: "POST",
        headers: {
          "content-type": "application/json",
          connection: "keep-alive"
        },
        body: str2(payload)
      };
    }
    __name(createJsonPayload, "createJsonPayload");
    async function* protectItr(itr, onError2) {
      try {
        yield* itr;
      } catch (err2) {
        onError2(err2);
      }
    }
    __name(protectItr, "protectItr");
    function createFormDataPayload(payload, onError2) {
      const boundary = createBoundary2();
      const itr = payloadToMultipartItr(payload, boundary);
      const safeItr = protectItr(itr, onError2);
      const stream5 = (0, platform_node_js_1.itrToStream)(safeItr);
      return {
        method: "POST",
        headers: {
          "content-type": `multipart/form-data; boundary=${boundary}`,
          connection: "keep-alive"
        },
        body: stream5
      };
    }
    __name(createFormDataPayload, "createFormDataPayload");
    function createBoundary2() {
      return "----------" + randomId(32);
    }
    __name(createBoundary2, "createBoundary");
    function randomId(length = 16) {
      return Array.from(Array(length)).map(() => Math.random().toString(36)[2] || 0).join("");
    }
    __name(randomId, "randomId");
    var enc = new TextEncoder();
    async function* payloadToMultipartItr(payload, boundary) {
      const files = collectFiles(payload);
      yield enc.encode(`--${boundary}\r
`);
      const separator = enc.encode(`\r
--${boundary}\r
`);
      let first2 = true;
      for (const [key, value] of Object.entries(payload)) {
        if (value == null)
          continue;
        if (!first2)
          yield separator;
        yield valuePart(key, value instanceof types_js_1.InputFile ? value.toJSON() : typeof value === "object" ? str2(value) : value);
        first2 = false;
      }
      for (const { id, origin: origin2, file: file2 } of files) {
        if (!first2)
          yield separator;
        yield* filePart(id, origin2, file2);
        first2 = false;
      }
      yield enc.encode(`\r
--${boundary}--\r
`);
    }
    __name(payloadToMultipartItr, "payloadToMultipartItr");
    function collectFiles(value) {
      if (typeof value !== "object" || value === null)
        return [];
      return Object.entries(value).flatMap(([k2, v2]) => {
        if (Array.isArray(v2))
          return v2.flatMap((p2) => collectFiles(p2));
        else if (v2 instanceof types_js_1.InputFile) {
          const id = randomId();
          Object.assign(v2, { toJSON: /* @__PURE__ */ __name(() => `attach://${id}`, "toJSON") });
          const origin2 = k2 === "media" && "type" in value && typeof value.type === "string" ? value.type : k2;
          return { id, origin: origin2, file: v2 };
        } else
          return collectFiles(v2);
      });
    }
    __name(collectFiles, "collectFiles");
    function valuePart(key, value) {
      return enc.encode(`content-disposition:form-data;name="${key}"\r
\r
${value}`);
    }
    __name(valuePart, "valuePart");
    async function* filePart(id, origin2, input) {
      const filename = input.filename || `${origin2}.${getExt(origin2)}`;
      if (filename.includes("\r") || filename.includes("\n")) {
        throw new Error(`File paths cannot contain carriage-return (\\r) or newline (\\n) characters! Filename for property '${origin2}' was:
"""
${filename}
"""`);
      }
      yield enc.encode(`content-disposition:form-data;name="${id}";filename=${filename}\r
content-type:application/octet-stream\r
\r
`);
      const data = await input.toRaw();
      if (data instanceof Uint8Array)
        yield data;
      else
        yield* data;
    }
    __name(filePart, "filePart");
    function getExt(key) {
      switch (key) {
        case "certificate":
          return "pem";
        case "photo":
        case "thumbnail":
          return "jpg";
        case "voice":
          return "ogg";
        case "audio":
          return "mp3";
        case "animation":
        case "video":
        case "video_note":
          return "mp4";
        case "sticker":
          return "webp";
        default:
          return "dat";
      }
    }
    __name(getExt, "getExt");
  }
});

// node_modules/grammy/out/shim.node.js
var require_shim_node = __commonJS({
  "node_modules/grammy/out/shim.node.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.fetch = exports2.AbortController = void 0;
    var abort_controller_1 = require_abort_controller();
    Object.defineProperty(exports2, "AbortController", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return abort_controller_1.AbortController;
    }, "get") });
    var node_fetch_1 = require_lib4();
    Object.defineProperty(exports2, "fetch", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return node_fetch_1.default;
    }, "get") });
  }
});

// node_modules/grammy/out/core/client.js
var require_client4 = __commonJS({
  "node_modules/grammy/out/core/client.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.createRawApi = createRawApi;
    var platform_node_js_1 = require_platform_node();
    var error_js_1 = require_error3();
    var payload_js_1 = require_payload();
    var debug3 = (0, platform_node_js_1.debug)("grammy:core");
    function concatTransformer(prev, trans) {
      return (method, payload, signal) => trans(prev, method, payload, signal);
    }
    __name(concatTransformer, "concatTransformer");
    var ApiClient2 = class {
      static {
        __name(this, "ApiClient");
      }
      constructor(token2, options2 = {}, webhookReplyEnvelope = {}) {
        var _a7, _b2, _c2, _d, _e2, _f;
        this.token = token2;
        this.webhookReplyEnvelope = webhookReplyEnvelope;
        this.hasUsedWebhookReply = false;
        this.installedTransformers = [];
        this.call = async (method, p2, signal) => {
          const payload = p2 !== null && p2 !== void 0 ? p2 : {};
          debug3(`Calling ${method}`);
          if (signal !== void 0)
            validateSignal(method, payload, signal);
          const opts = this.options;
          const formDataRequired = (0, payload_js_1.requiresFormDataUpload)(payload);
          if (this.webhookReplyEnvelope.send !== void 0 && !this.hasUsedWebhookReply && !formDataRequired && opts.canUseWebhookReply(method)) {
            this.hasUsedWebhookReply = true;
            const config3 = (0, payload_js_1.createJsonPayload)({ ...payload, method });
            await this.webhookReplyEnvelope.send(config3.body);
            return { ok: true, result: true };
          }
          const controller = createAbortControllerFromSignal(signal);
          const timeout2 = createTimeout(controller, opts.timeoutSeconds, method);
          const streamErr = createStreamError(controller);
          const url3 = opts.buildUrl(opts.apiRoot, this.token, method, opts.environment);
          const config2 = formDataRequired ? (0, payload_js_1.createFormDataPayload)(payload, (err2) => streamErr.catch(err2)) : (0, payload_js_1.createJsonPayload)(payload);
          const sig = controller.signal;
          const options3 = { ...opts.baseFetchConfig, signal: sig, ...config2 };
          const successPromise = this.fetch(url3, options3).then((res) => res.json());
          const operations = [successPromise, streamErr.promise, timeout2.promise];
          try {
            return await Promise.race(operations);
          } catch (error40) {
            throw (0, error_js_1.toHttpError)(method, opts.sensitiveLogs, error40);
          } finally {
            if (timeout2.handle !== void 0)
              clearTimeout(timeout2.handle);
          }
        };
        const apiRoot = (_a7 = options2.apiRoot) !== null && _a7 !== void 0 ? _a7 : "https://api.telegram.org";
        const environment = (_b2 = options2.environment) !== null && _b2 !== void 0 ? _b2 : "prod";
        const { fetch: customFetch } = options2;
        const fetchFn = customFetch !== null && customFetch !== void 0 ? customFetch : shim_node_js_1.fetch;
        this.options = {
          apiRoot,
          environment,
          buildUrl: (_c2 = options2.buildUrl) !== null && _c2 !== void 0 ? _c2 : defaultBuildUrl,
          timeoutSeconds: (_d = options2.timeoutSeconds) !== null && _d !== void 0 ? _d : 500,
          baseFetchConfig: {
            ...(0, platform_node_js_1.baseFetchConfig)(apiRoot),
            ...options2.baseFetchConfig
          },
          canUseWebhookReply: (_e2 = options2.canUseWebhookReply) !== null && _e2 !== void 0 ? _e2 : () => false,
          sensitiveLogs: (_f = options2.sensitiveLogs) !== null && _f !== void 0 ? _f : false,
          fetch: /* @__PURE__ */ __name((...args2) => fetchFn(...args2), "fetch")
        };
        this.fetch = this.options.fetch;
        if (this.options.apiRoot.endsWith("/")) {
          throw new Error(`Remove the trailing '/' from the 'apiRoot' option (use '${this.options.apiRoot.substring(0, this.options.apiRoot.length - 1)}' instead of '${this.options.apiRoot}')`);
        }
      }
      use(...transformers) {
        this.call = transformers.reduce(concatTransformer, this.call);
        this.installedTransformers.push(...transformers);
        return this;
      }
      async callApi(method, payload, signal) {
        const data = await this.call(method, payload, signal);
        if (data.ok)
          return data.result;
        else
          throw (0, error_js_1.toGrammyError)(data, method, payload);
      }
    };
    function createRawApi(token2, options2, webhookReplyEnvelope) {
      const client = new ApiClient2(token2, options2, webhookReplyEnvelope);
      const proxyHandler2 = {
        get(_2, m3) {
          return m3 === "toJSON" ? "__internal" : m3 === "getMe" || m3 === "getWebhookInfo" || m3 === "getForumTopicIconStickers" || m3 === "getAvailableGifts" || m3 === "logOut" || m3 === "close" || m3 === "getMyStarBalance" || m3 === "removeMyProfilePhoto" ? client.callApi.bind(client, m3, {}) : client.callApi.bind(client, m3);
        },
        ...proxyMethods
      };
      const raw2 = new Proxy({}, proxyHandler2);
      const installedTransformers = client.installedTransformers;
      const api = {
        raw: raw2,
        installedTransformers,
        use: /* @__PURE__ */ __name((...t5) => {
          client.use(...t5);
          return api;
        }, "use")
      };
      return api;
    }
    __name(createRawApi, "createRawApi");
    var defaultBuildUrl = /* @__PURE__ */ __name((root, token2, method, env6) => {
      const prefix = env6 === "test" ? "test/" : "";
      return `${root}/bot${token2}/${prefix}${method}`;
    }, "defaultBuildUrl");
    var proxyMethods = {
      set() {
        return false;
      },
      defineProperty() {
        return false;
      },
      deleteProperty() {
        return false;
      },
      ownKeys() {
        return [];
      }
    };
    function createTimeout(controller, seconds, method) {
      let handle2 = void 0;
      const promise2 = new Promise((_2, reject) => {
        handle2 = setTimeout(() => {
          const msg = `Request to '${method}' timed out after ${seconds} seconds`;
          reject(new Error(msg));
          controller.abort();
        }, 1e3 * seconds);
      });
      return { promise: promise2, handle: handle2 };
    }
    __name(createTimeout, "createTimeout");
    function createStreamError(abortController) {
      let onError2 = /* @__PURE__ */ __name((err2) => {
        throw err2;
      }, "onError");
      const promise2 = new Promise((_2, reject) => {
        onError2 = /* @__PURE__ */ __name((err2) => {
          reject(err2);
          abortController.abort();
        }, "onError");
      });
      return { promise: promise2, catch: onError2 };
    }
    __name(createStreamError, "createStreamError");
    function createAbortControllerFromSignal(signal) {
      const abortController = new shim_node_js_1.AbortController();
      if (signal === void 0)
        return abortController;
      const sig = signal;
      function abort2() {
        abortController.abort();
        sig.removeEventListener("abort", abort2);
      }
      __name(abort2, "abort");
      if (sig.aborted)
        abort2();
      else
        sig.addEventListener("abort", abort2);
      return { abort: abort2, signal: abortController.signal };
    }
    __name(createAbortControllerFromSignal, "createAbortControllerFromSignal");
    function validateSignal(method, payload, signal) {
      if (typeof (signal === null || signal === void 0 ? void 0 : signal.addEventListener) === "function") {
        return;
      }
      let payload0 = JSON.stringify(payload);
      if (payload0.length > 20) {
        payload0 = payload0.substring(0, 16) + " ...";
      }
      let payload1 = JSON.stringify(signal);
      if (payload1.length > 20) {
        payload1 = payload1.substring(0, 16) + " ...";
      }
      throw new Error(`Incorrect abort signal instance found! You passed two payloads to '${method}' but you should merge the second one containing '${payload1}' into the first one containing '${payload0}'! If you are using context shortcuts, you may want to use a method on 'ctx.api' instead.

If you want to prevent such mistakes in the future, consider using TypeScript. https://www.typescriptlang.org/`);
    }
    __name(validateSignal, "validateSignal");
    var shim_node_js_1 = require_shim_node();
  }
});

// node_modules/grammy/out/core/api.js
var require_api4 = __commonJS({
  "node_modules/grammy/out/core/api.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Api = void 0;
    var client_js_1 = require_client4();
    var Api = class {
      static {
        __name(this, "Api");
      }
      /**
       * Constructs a new instance of `Api`. It is independent from all other
       * instances of this class. For example, this lets you install a custom set
       * of transformers.
       *
       * @param token Bot API token obtained from [@BotFather](https://t.me/BotFather)
       * @param options Optional API client options for the underlying client instance
       * @param webhookReplyEnvelope Optional envelope to handle webhook replies
       */
      constructor(token2, options2, webhookReplyEnvelope) {
        this.token = token2;
        this.options = options2;
        const { raw: raw2, use: use2, installedTransformers } = (0, client_js_1.createRawApi)(token2, options2, webhookReplyEnvelope);
        this.raw = raw2;
        this.config = {
          use: use2,
          installedTransformers: /* @__PURE__ */ __name(() => installedTransformers.slice(), "installedTransformers")
        };
      }
      /**
       * Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects.
       *
       * Notes
       * 1. This method will not work if an outgoing webhook is set up.
       * 2. In order to avoid getting duplicate updates, recalculate offset after each server response.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getupdates
       */
      getUpdates(other2, signal) {
        return this.raw.getUpdates({ ...other2 }, signal);
      }
      /**
       * Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.
       *
       * If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter secret_token. If specified, the request will contain a header “X-Telegram-Bot-Api-Secret-Token” with the secret token as content.
       *
       * Notes
       * 1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.
       * 2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.
       * 3. Ports currently supported for Webhooks: 443, 80, 88, 8443.
       *
       * If you're having any trouble setting up webhooks, please check out this amazing guide to webhooks.
       *
       * @param url HTTPS url to send updates to. Use an empty string to remove webhook integration
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setwebhook
       */
      setWebhook(url3, other2, signal) {
        return this.raw.setWebhook({ url: url3, ...other2 }, signal);
      }
      /**
       * Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletewebhook
       */
      deleteWebhook(other2, signal) {
        return this.raw.deleteWebhook({ ...other2 }, signal);
      }
      /**
       * Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getwebhookinfo
       */
      getWebhookInfo(signal) {
        return this.raw.getWebhookInfo(signal);
      }
      /**
       * A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getme
       */
      getMe(signal) {
        return this.raw.getMe(signal);
      }
      /**
       * Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. Requires no parameters.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#logout
       */
      logOut(signal) {
        return this.raw.logOut(signal);
      }
      /**
       * Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#close
       */
      close(signal) {
        return this.raw.close(signal);
      }
      /**
       * Use this method to send text messages. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param text Text of the message to be sent, 1-4096 characters after entities parsing
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendmessage
       */
      sendMessage(chat_id, text, other2, signal) {
        return this.raw.sendMessage({ chat_id, text, ...other2 }, signal);
      }
      /**
       * Use this method to stream a partial message to a user while the message is being generated. Returns True on success.
       *
       * @param chat_id Unique identifier for the target private chat
       * @param draft_id Unique identifier of the message draft; must be non-zero. Changes of drafts with the same identifier are animated
       * @param text Text of the message to be sent, 1-4096 characters after entities parsing
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendmessagedraft
       */
      sendMessageDraft(chat_id, draft_id, text, other2, signal) {
        return this.raw.sendMessageDraft({ chat_id, draft_id, text, ...other2 }, signal);
      }
      /**
       * Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param from_chat_id Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername)
       * @param message_id Message identifier in the chat specified in from_chat_id
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#forwardmessage
       */
      forwardMessage(chat_id, from_chat_id, message_id, other2, signal) {
        return this.raw.forwardMessage({ chat_id, from_chat_id, message_id, ...other2 }, signal);
      }
      /**
       * Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param from_chat_id Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername)
       * @param message_ids A list of 1-100 identifiers of messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#forwardmessages
       */
      forwardMessages(chat_id, from_chat_id, message_ids, other2, signal) {
        return this.raw.forwardMessages({
          chat_id,
          from_chat_id,
          message_ids,
          ...other2
        }, signal);
      }
      /**
       * Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param from_chat_id Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername)
       * @param message_id Message identifier in the chat specified in from_chat_id
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#copymessage
       */
      copyMessage(chat_id, from_chat_id, message_id, other2, signal) {
        return this.raw.copyMessage({ chat_id, from_chat_id, message_id, ...other2 }, signal);
      }
      /**
       * Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param from_chat_id Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername)
       * @param message_ids A list of 1-100 identifiers of messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#copymessages
       */
      copyMessages(chat_id, from_chat_id, message_ids, other2, signal) {
        return this.raw.copyMessages({
          chat_id,
          from_chat_id,
          message_ids,
          ...other2
        }, signal);
      }
      /**
       * Use this method to send photos. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param photo Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendphoto
       */
      sendPhoto(chat_id, photo, other2, signal) {
        return this.raw.sendPhoto({ chat_id, photo, ...other2 }, signal);
      }
      /**
       * Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
       *
       * For sending voice messages, use the sendVoice method instead.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param audio Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendaudio
       */
      sendAudio(chat_id, audio, other2, signal) {
        return this.raw.sendAudio({ chat_id, audio, ...other2 }, signal);
      }
      /**
       * Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param document File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#senddocument
       */
      sendDocument(chat_id, document2, other2, signal) {
        return this.raw.sendDocument({ chat_id, document: document2, ...other2 }, signal);
      }
      /**
       * Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param video Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendvideo
       */
      sendVideo(chat_id, video, other2, signal) {
        return this.raw.sendVideo({ chat_id, video, ...other2 }, signal);
      }
      /**
       * Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param animation Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendanimation
       */
      sendAnimation(chat_id, animation, other2, signal) {
        return this.raw.sendAnimation({ chat_id, animation, ...other2 }, signal);
      }
      /**
       * Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param voice Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendvoice
       */
      sendVoice(chat_id, voice, other2, signal) {
        return this.raw.sendVoice({ chat_id, voice, ...other2 }, signal);
      }
      /**
       * Use this method to send video messages. On success, the sent Message is returned.
       * As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param video_note Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data.. Sending video notes by a URL is currently unsupported
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendvideonote
       */
      sendVideoNote(chat_id, video_note, other2, signal) {
        return this.raw.sendVideoNote({ chat_id, video_note, ...other2 }, signal);
      }
      /**
       * Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param media An array describing messages to be sent, must include 2-10 items
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendmediagroup
       */
      sendMediaGroup(chat_id, media, other2, signal) {
        return this.raw.sendMediaGroup({ chat_id, media, ...other2 }, signal);
      }
      /**
       * Use this method to send point on the map. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param latitude Latitude of the location
       * @param longitude Longitude of the location
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendlocation
       */
      sendLocation(chat_id, latitude, longitude, other2, signal) {
        return this.raw.sendLocation({ chat_id, latitude, longitude, ...other2 }, signal);
      }
      /**
       * Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of the message to edit
       * @param latitude Latitude of new location
       * @param longitude Longitude of new location
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagelivelocation
       */
      editMessageLiveLocation(chat_id, message_id, latitude, longitude, other2, signal) {
        return this.raw.editMessageLiveLocation({ chat_id, message_id, latitude, longitude, ...other2 }, signal);
      }
      /**
       * Use this method to edit live location inline messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
       *
       * @param inline_message_id Identifier of the inline message
       * @param latitude Latitude of new location
       * @param longitude Longitude of new location
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagelivelocation
       */
      editMessageLiveLocationInline(inline_message_id, latitude, longitude, other2, signal) {
        return this.raw.editMessageLiveLocation({ inline_message_id, latitude, longitude, ...other2 }, signal);
      }
      /**
       * Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of the message with live location to stop
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#stopmessagelivelocation
       */
      stopMessageLiveLocation(chat_id, message_id, other2, signal) {
        return this.raw.stopMessageLiveLocation({ chat_id, message_id, ...other2 }, signal);
      }
      /**
       * Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.
       *
       * @param inline_message_id Identifier of the inline message
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#stopmessagelivelocation
       */
      stopMessageLiveLocationInline(inline_message_id, other2, signal) {
        return this.raw.stopMessageLiveLocation({ inline_message_id, ...other2 }, signal);
      }
      /**
       * Use this method to send paid media. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param star_count The number of Telegram Stars that must be paid to buy access to the media
       * @param media An array describing the media to be sent; up to 10 items
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendpaidmedia
       */
      sendPaidMedia(chat_id, star_count, media, other2, signal) {
        return this.raw.sendPaidMedia({ chat_id, star_count, media, ...other2 }, signal);
      }
      /**
       * Use this method to send information about a venue. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param latitude Latitude of the venue
       * @param longitude Longitude of the venue
       * @param title Name of the venue
       * @param address Address of the venue
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendvenue
       */
      sendVenue(chat_id, latitude, longitude, title, address, other2, signal) {
        return this.raw.sendVenue({ chat_id, latitude, longitude, title, address, ...other2 }, signal);
      }
      /**
       * Use this method to send phone contacts. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param phone_number Contact's phone number
       * @param first_name Contact's first name
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendcontact
       */
      sendContact(chat_id, phone_number, first_name, other2, signal) {
        return this.raw.sendContact({ chat_id, phone_number, first_name, ...other2 }, signal);
      }
      /**
       * Use this method to send a native poll. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param question Poll question, 1-300 characters
       * @param options A list of answer options, 2-12 strings 1-100 characters each
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendpoll
       */
      sendPoll(chat_id, question, options2, other2, signal) {
        const opts = options2.map((o3) => typeof o3 === "string" ? { text: o3 } : o3);
        return this.raw.sendPoll({ chat_id, question, options: opts, ...other2 }, signal);
      }
      /**
       * Use this method to send a checklist on behalf of a connected business account. On success, the sent Message is returned.
       *
       * @param business_connection_id Unique identifier of the business connection on behalf of which the message will be sent
       * @param chat_id Unique identifier for the target chat
       * @param checklist An object for the checklist to send
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendchecklist
       */
      sendChecklist(business_connection_id, chat_id, checklist, other2, signal) {
        return this.raw.sendChecklist({
          business_connection_id,
          chat_id,
          checklist,
          ...other2
        }, signal);
      }
      /**
       * Use this method to edit a checklist on behalf of a connected business account. On success, the edited Message is returned.
       *
       * @param business_connection_id Unique identifier of the business connection on behalf of which the message will be sent
       * @param chat_id Unique identifier for the target chat
       * @param message_id Unique identifier for the target message
       * @param checklist An object for the new checklist
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagechecklist
       */
      editMessageChecklist(business_connection_id, chat_id, message_id, checklist, other2, signal) {
        return this.raw.editMessageChecklist({
          business_connection_id,
          chat_id,
          message_id,
          checklist,
          ...other2
        }, signal);
      }
      /**
       * Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param emoji Emoji on which the dice throw animation is based. Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”. Dice can have values 1-6 for “🎲”, “🎯” and “🎳”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”. Defaults to “🎲”
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#senddice
       */
      sendDice(chat_id, emoji3, other2, signal) {
        return this.raw.sendDice({ chat_id, emoji: emoji3, ...other2 }, signal);
      }
      /**
       * Use this method to change the chosen reactions on a message. Service messages of some types can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of the target message
       * @param reaction A list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can't be used by bots.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setmessagereaction
       */
      setMessageReaction(chat_id, message_id, reaction, other2, signal) {
        return this.raw.setMessageReaction({
          chat_id,
          message_id,
          reaction,
          ...other2
        }, signal);
      }
      /**
       * Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
       *
       * Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.
       *
       * We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). Channel chats and channel direct messages chats aren't supported.
       * @param action Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendchataction
       */
      sendChatAction(chat_id, action, other2, signal) {
        return this.raw.sendChatAction({ chat_id, action, ...other2 }, signal);
      }
      /**
       * Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
       *
       * @param user_id Unique identifier of the target user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getuserprofilephotos
       */
      getUserProfilePhotos(user_id, other2, signal) {
        return this.raw.getUserProfilePhotos({ user_id, ...other2 }, signal);
      }
      /**
       * Use this method to get a list of profile audios for a user. Returns a UserProfileAudios object.
       *
       * @param user_id Unique identifier of the target user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getuserprofileaudios
       */
      getUserProfileAudios(user_id, other2, signal) {
        return this.raw.getUserProfileAudios({ user_id, ...other2 }, signal);
      }
      /**
       * Changes the emoji status for a given user that previously allowed the bot to manage their emoji status via the Mini App method requestEmojiStatusAccess. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setuseremojistatus
       */
      setUserEmojiStatus(user_id, other2, signal) {
        return this.raw.setUserEmojiStatus({ user_id, ...other2 }, signal);
      }
      /**
       * Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object.
       *
       * @param chat_id Unique identifier for the chat or username of the channel (in the format @channelusername)
       * @param user_id Unique identifier of the target user
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getuserchatboosts
       */
      getUserChatBoosts(chat_id, user_id, signal) {
        return this.raw.getUserChatBoosts({ chat_id, user_id }, signal);
      }
      /**
       * Returns the gifts owned and hosted by a user. Returns OwnedGifts on success.
       *
       * @param user_id Unique identifier of the user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getusergifts
       */
      getUserGifts(user_id, other2, signal) {
        return this.raw.getUserGifts({ user_id, ...other2 }, signal);
      }
      /**
       * Returns the gifts owned by a chat. Returns OwnedGifts on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatgifts
       */
      getChatGifts(chat_id, other2, signal) {
        return this.raw.getChatGifts({ chat_id, ...other2 }, signal);
      }
      /**
       * Use this method to get information about the connection of the bot with a business account. Returns a BusinessConnection object on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getbusinessconnection
       */
      getBusinessConnection(business_connection_id, signal) {
        return this.raw.getBusinessConnection({ business_connection_id }, signal);
      }
      /**
       * Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link `https://api.telegram.org/file/bot<token>/<file_path>`, where `<file_path>` is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
       *
       * Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.
       *
       * @param file_id File identifier to get info about
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getfile
       */
      getFile(file_id, signal) {
        return this.raw.getFile({ file_id }, signal);
      }
      /** @deprecated Use `banChatMember` instead. */
      kickChatMember(...args2) {
        return this.banChatMember(...args2);
      }
      /**
       * Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername)
       * @param user_id Unique identifier of the target user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#banchatmember
       */
      banChatMember(chat_id, user_id, other2, signal) {
        return this.raw.banChatMember({ chat_id, user_id, ...other2 }, signal);
      }
      /**
       * Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success.
       *
       * @param chat_id Unique identifier for the target group or username of the target supergroup or channel (in the format @username)
       * @param user_id Unique identifier of the target user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unbanchatmember
       */
      unbanChatMember(chat_id, user_id, other2, signal) {
        return this.raw.unbanChatMember({ chat_id, user_id, ...other2 }, signal);
      }
      /**
       * Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param user_id Unique identifier of the target user
       * @param permissions An object for new user permissions
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#restrictchatmember
       */
      restrictChatMember(chat_id, user_id, permissions, other2, signal) {
        return this.raw.restrictChatMember({ chat_id, user_id, permissions, ...other2 }, signal);
      }
      /**
       * Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param user_id Unique identifier of the target user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#promotechatmember
       */
      promoteChatMember(chat_id, user_id, other2, signal) {
        return this.raw.promoteChatMember({ chat_id, user_id, ...other2 }, signal);
      }
      /**
       * Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param user_id Unique identifier of the target user
       * @param custom_title New custom title for the administrator; 0-16 characters, emoji are not allowed
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatadministratorcustomtitle
       */
      setChatAdministratorCustomTitle(chat_id, user_id, custom_title, signal) {
        return this.raw.setChatAdministratorCustomTitle({ chat_id, user_id, custom_title }, signal);
      }
      /**
       * Use this method to set a tag for a regular member in a group or a supergroup. The bot must be an administrator in the chat for this to work and must have the “can_manage_tags” administrator right. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param user_id Unique identifier of the target user
       * @param tag New tag for the member; 0-16 characters, emoji are not allowed
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setChatMemberTag
       */
      setChatMemberTag(chat_id, user_id, tag2, signal) {
        return this.raw.setChatMemberTag({ chat_id, user_id, tag: tag2 }, signal);
      }
      /**
       * Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param sender_chat_id Unique identifier of the target sender chat
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#banchatsenderchat
       */
      banChatSenderChat(chat_id, sender_chat_id, signal) {
        return this.raw.banChatSenderChat({ chat_id, sender_chat_id }, signal);
      }
      /**
       * Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param sender_chat_id Unique identifier of the target sender chat
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unbanchatsenderchat
       */
      unbanChatSenderChat(chat_id, sender_chat_id, signal) {
        return this.raw.unbanChatSenderChat({ chat_id, sender_chat_id }, signal);
      }
      /**
       * Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param permissions New default chat permissions
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatpermissions
       */
      setChatPermissions(chat_id, permissions, other2, signal) {
        return this.raw.setChatPermissions({ chat_id, permissions, ...other2 }, signal);
      }
      /**
       * Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success.
       *
       * Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method. If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#exportchatinvitelink
       */
      exportChatInviteLink(chat_id, signal) {
        return this.raw.exportChatInviteLink({ chat_id }, signal);
      }
      /**
       * Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#createchatinvitelink
       */
      createChatInviteLink(chat_id, other2, signal) {
        return this.raw.createChatInviteLink({ chat_id, ...other2 }, signal);
      }
      /**
       * Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param invite_link The invite link to edit
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editchatinvitelink
       */
      editChatInviteLink(chat_id, invite_link, other2, signal) {
        return this.raw.editChatInviteLink({ chat_id, invite_link, ...other2 }, signal);
      }
      /**
       * Use this method to create a subscription invite link for a channel chat. The bot must have the can_invite_users administrator rights. The link can be edited using the method editChatSubscriptionInviteLink or revoked using the method revokeChatInviteLink. Returns the new invite link as a ChatInviteLink object.
       *
       * @param chat_id Unique identifier for the target channel chat or username of the target channel (in the format @channelusername)
       * @param subscription_period The number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days).
       * @param subscription_price The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; 1-2500
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#createchatsubscriptioninvitelink
       */
      createChatSubscriptionInviteLink(chat_id, subscription_period, subscription_price, other2, signal) {
        return this.raw.createChatSubscriptionInviteLink({ chat_id, subscription_period, subscription_price, ...other2 }, signal);
      }
      /**
       * Use this method to edit a subscription invite link created by the bot. The bot must have the can_invite_users administrator rights. Returns the edited invite link as a ChatInviteLink object.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param invite_link The invite link to edit
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editchatsubscriptioninvitelink
       */
      editChatSubscriptionInviteLink(chat_id, invite_link, other2, signal) {
        return this.raw.editChatSubscriptionInviteLink({ chat_id, invite_link, ...other2 }, signal);
      }
      /**
       * Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object.
       *
       * @param chat_id Unique identifier of the target chat or username of the target channel (in the format @channelusername)
       * @param invite_link The invite link to revoke
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#revokechatinvitelink
       */
      revokeChatInviteLink(chat_id, invite_link, signal) {
        return this.raw.revokeChatInviteLink({ chat_id, invite_link }, signal);
      }
      /**
       * Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param user_id Unique identifier of the target user
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#approvechatjoinrequest
       */
      approveChatJoinRequest(chat_id, user_id, signal) {
        return this.raw.approveChatJoinRequest({ chat_id, user_id }, signal);
      }
      /**
       * Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param user_id Unique identifier of the target user
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#declinechatjoinrequest
       */
      declineChatJoinRequest(chat_id, user_id, signal) {
        return this.raw.declineChatJoinRequest({ chat_id, user_id }, signal);
      }
      /**
       * Use this method to approve a suggested post in a direct messages chat. The bot must have the 'can_post_messages' administrator right in the corresponding channel chat.  Returns True on success.
       *
       * @param chat_id Unique identifier for the target direct messages chat
       * @param message_id Identifier of a suggested post message to approve
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#approvesuggestedpost
       */
      approveSuggestedPost(chat_id, message_id, other2, signal) {
        return this.raw.approveSuggestedPost({ chat_id, message_id, ...other2 }, signal);
      }
      /**
       * Use this method to decline a suggested post in a direct messages chat. The bot must have the 'can_manage_direct_messages' administrator right in the corresponding channel chat. Returns True on success.
       *
       * @param chat_id Unique identifier for the target direct messages chat
       * @param message_id Identifier of a suggested post message to decline
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#declinesuggestedpost
       */
      declineSuggestedPost(chat_id, message_id, other2, signal) {
        return this.raw.declineSuggestedPost({ chat_id, message_id, ...other2 }, signal);
      }
      /**
       * Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param photo New chat photo, uploaded using multipart/form-data
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatphoto
       */
      setChatPhoto(chat_id, photo, signal) {
        return this.raw.setChatPhoto({ chat_id, photo }, signal);
      }
      /**
       * Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletechatphoto
       */
      deleteChatPhoto(chat_id, signal) {
        return this.raw.deleteChatPhoto({ chat_id }, signal);
      }
      /**
       * Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param title New chat title, 1-255 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchattitle
       */
      setChatTitle(chat_id, title, signal) {
        return this.raw.setChatTitle({ chat_id, title }, signal);
      }
      /**
       * Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param description New chat description, 0-255 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatdescription
       */
      setChatDescription(chat_id, description, signal) {
        return this.raw.setChatDescription({ chat_id, description }, signal);
      }
      /**
       * Use this method to add a message to the list of pinned messages in a chat. In private chats and channel direct messages chats, all non-service messages can be pinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to pin messages in groups and channels respectively. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of a message to pin
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#pinchatmessage
       */
      pinChatMessage(chat_id, message_id, other2, signal) {
        return this.raw.pinChatMessage({ chat_id, message_id, ...other2 }, signal);
      }
      /**
       * Use this method to remove a message from the list of pinned messages in a chat. In private chats and channel direct messages chats, all messages can be unpinned. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin messages in groups and channels respectively. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of a message to unpin. If not specified, the most recent pinned message (by sending date) will be unpinned.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unpinchatmessage
       */
      unpinChatMessage(chat_id, message_id, other2, signal) {
        return this.raw.unpinChatMessage({ chat_id, message_id, ...other2 }, signal);
      }
      /**
       * Use this method to clear the list of pinned messages in a chat. In private chats and channel direct messages chats, no additional rights are required to unpin all pinned messages. Conversely, the bot must be an administrator with the 'can_pin_messages' right or the 'can_edit_messages' right to unpin all pinned messages in groups and channels respectively. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unpinallchatmessages
       */
      unpinAllChatMessages(chat_id, signal) {
        return this.raw.unpinAllChatMessages({ chat_id }, signal);
      }
      /**
       * Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername). Channel direct messages chats aren't supported; leave the corresponding channel instead.
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#leavechat
       */
      leaveChat(chat_id, signal) {
        return this.raw.leaveChat({ chat_id }, signal);
      }
      /**
       * Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchat
       */
      getChat(chat_id, signal) {
        return this.raw.getChat({ chat_id }, signal);
      }
      /**
       * Use this method to get a list of administrators in a chat, which aren't bots. Returns an Array of ChatMember objects.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatadministrators
       */
      getChatAdministrators(chat_id, signal) {
        return this.raw.getChatAdministrators({ chat_id }, signal);
      }
      /** @deprecated Use `getChatMemberCount` instead. */
      getChatMembersCount(...args2) {
        return this.getChatMemberCount(...args2);
      }
      /**
       * Use this method to get the number of members in a chat. Returns Int on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatmembercount
       */
      getChatMemberCount(chat_id, signal) {
        return this.raw.getChatMemberCount({ chat_id }, signal);
      }
      /**
       * Use this method to get information about a member of a chat. The method is guaranteed to work only if the bot is an administrator in the chat. Returns a ChatMember object on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
       * @param user_id Unique identifier of the target user
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatmember
       */
      getChatMember(chat_id, user_id, signal) {
        return this.raw.getChatMember({ chat_id, user_id }, signal);
      }
      /**
       * Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set ly returned in getChat requests to check if the bot can use this method. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param sticker_set_name Name of the sticker set to be set as the group sticker set
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatstickerset
       */
      setChatStickerSet(chat_id, sticker_set_name, signal) {
        return this.raw.setChatStickerSet({ chat_id, sticker_set_name }, signal);
      }
      /**
       * Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set ly returned in getChat requests to check if the bot can use this method. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletechatstickerset
       */
      deleteChatStickerSet(chat_id, signal) {
        return this.raw.deleteChatStickerSet({ chat_id }, signal);
      }
      /**
       * Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of Sticker objects.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getforumtopiciconstickers
       */
      getForumTopicIconStickers(signal) {
        return this.raw.getForumTopicIconStickers(signal);
      }
      /**
       * Use this method to create a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator right. Returns information about the created topic as a ForumTopic object.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param name Topic name, 1-128 characters
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#createforumtopic
       */
      createForumTopic(chat_id, name4, other2, signal) {
        return this.raw.createForumTopic({ chat_id, name: name4, ...other2 }, signal);
      }
      /**
       * Use this method to edit name and icon of a topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param message_thread_id Unique identifier for the target message thread of the forum topic
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editforumtopic
       */
      editForumTopic(chat_id, message_thread_id, other2, signal) {
        return this.raw.editForumTopic({ chat_id, message_thread_id, ...other2 }, signal);
      }
      /**
       * Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param message_thread_id Unique identifier for the target message thread of the forum topic
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#closeforumtopic
       */
      closeForumTopic(chat_id, message_thread_id, signal) {
        return this.raw.closeForumTopic({ chat_id, message_thread_id }, signal);
      }
      /**
       * Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param message_thread_id Unique identifier for the target message thread of the forum topic
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#reopenforumtopic
       */
      reopenForumTopic(chat_id, message_thread_id, signal) {
        return this.raw.reopenForumTopic({ chat_id, message_thread_id }, signal);
      }
      /**
       * Use this method to delete a forum topic along with all its messages in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param message_thread_id Unique identifier for the target message thread of the forum topic
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deleteforumtopic
       */
      deleteForumTopic(chat_id, message_thread_id, signal) {
        return this.raw.deleteForumTopic({ chat_id, message_thread_id }, signal);
      }
      /**
       * Use this method to clear the list of pinned messages in a forum topic in a forum supergroup chat or a private chat with a user. In the case of a supergroup chat the bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param message_thread_id Unique identifier for the target message thread of the forum topic
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unpinallforumtopicmessages
       */
      unpinAllForumTopicMessages(chat_id, message_thread_id, signal) {
        return this.raw.unpinAllForumTopicMessages({ chat_id, message_thread_id }, signal);
      }
      /**
       * Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param name New topic name, 1-128 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editgeneralforumtopic
       */
      editGeneralForumTopic(chat_id, name4, signal) {
        return this.raw.editGeneralForumTopic({ chat_id, name: name4 }, signal);
      }
      /**
       * Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#closegeneralforumtopic
       */
      closeGeneralForumTopic(chat_id, signal) {
        return this.raw.closeGeneralForumTopic({ chat_id }, signal);
      }
      /**
       * Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success.     *
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#reopengeneralforumtopic
       */
      reopenGeneralForumTopic(chat_id, signal) {
        return this.raw.reopenGeneralForumTopic({ chat_id }, signal);
      }
      /**
       * Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#hidegeneralforumtopic
       */
      hideGeneralForumTopic(chat_id, signal) {
        return this.raw.hideGeneralForumTopic({ chat_id }, signal);
      }
      /**
       * Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unhidegeneralforumtopic
       */
      unhideGeneralForumTopic(chat_id, signal) {
        return this.raw.unhideGeneralForumTopic({ chat_id }, signal);
      }
      /**
       * Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages
       */
      unpinAllGeneralForumTopicMessages(chat_id, signal) {
        return this.raw.unpinAllGeneralForumTopicMessages({ chat_id }, signal);
      }
      /**
       * Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
       *
       * Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter.
       *
       * @param callback_query_id Unique identifier for the query to be answered
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#answercallbackquery
       */
      answerCallbackQuery(callback_query_id, other2, signal) {
        return this.raw.answerCallbackQuery({ callback_query_id, ...other2 }, signal);
      }
      /**
       * Use this method to change the bot's name. Returns True on success.
       *
       * @param name New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setmyname
       */
      setMyName(name4, other2, signal) {
        return this.raw.setMyName({ name: name4, ...other2 }, signal);
      }
      /**
       * Use this method to get the current bot name for the given user language. Returns BotName on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getmyname
       */
      getMyName(other2, signal) {
        return this.raw.getMyName(other2 !== null && other2 !== void 0 ? other2 : {}, signal);
      }
      /**
       * Use this method to change the list of the bot's commands. See https://core.telegram.org/bots/features#commands for more details about bot commands. Returns True on success.
       *
       * @param commands A list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setmycommands
       */
      setMyCommands(commands, other2, signal) {
        return this.raw.setMyCommands({ commands, ...other2 }, signal);
      }
      /**
       * Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletemycommands
       */
      deleteMyCommands(other2, signal) {
        return this.raw.deleteMyCommands({ ...other2 }, signal);
      }
      /**
       * Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of BotCommand objects. If commands aren't set, an empty list is returned.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getmycommands
       */
      getMyCommands(other2, signal) {
        return this.raw.getMyCommands({ ...other2 }, signal);
      }
      /**
       * Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns True on success.
       *
       * @param description New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setmydescription
       */
      setMyDescription(description, other2, signal) {
        return this.raw.setMyDescription({ description, ...other2 }, signal);
      }
      /**
       * Use this method to get the current bot description for the given user language. Returns BotDescription on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getmydescription
       */
      getMyDescription(other2, signal) {
        return this.raw.getMyDescription({ ...other2 }, signal);
      }
      /**
       * Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns True on success.
       *
       * @param short_description New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setmyshortdescription
       */
      setMyShortDescription(short_description, other2, signal) {
        return this.raw.setMyShortDescription({ short_description, ...other2 }, signal);
      }
      /**
       * Use this method to get the current bot short description for the given user language. Returns BotShortDescription on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getmyshortdescription
       */
      getMyShortDescription(other2, signal) {
        return this.raw.getMyShortDescription({ ...other2 }, signal);
      }
      /**
       * Changes the profile photo of the bot. Returns True on success.
       *
       * @param photo The new profile photo to set
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setmyprofilephoto
       */
      setMyProfilePhoto(photo, signal) {
        return this.raw.setMyProfilePhoto({ photo }, signal);
      }
      /**
       * Removes the profile photo of the bot. Requires no parameters. Returns True on success.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#removemyprofilephoto
       */
      removeMyProfilePhoto(signal) {
        return this.raw.removeMyProfilePhoto(signal);
      }
      /**
       * Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setchatmenubutton
       */
      setChatMenuButton(other2, signal) {
        return this.raw.setChatMenuButton({ ...other2 }, signal);
      }
      /**
       * Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getchatmenubutton
       */
      getChatMenuButton(other2, signal) {
        return this.raw.getChatMenuButton({ ...other2 }, signal);
      }
      /**
       * Use this method to the change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setmydefaultadministratorrights
       */
      setMyDefaultAdministratorRights(other2, signal) {
        return this.raw.setMyDefaultAdministratorRights({ ...other2 }, signal);
      }
      /**
       * Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getmydefaultadministratorrights
       */
      getMyDefaultAdministratorRights(other2, signal) {
        return this.raw.getMyDefaultAdministratorRights({ ...other2 }, signal);
      }
      /**
       * A method to get the current Telegram Stars balance of the bot. Requires no parameters. On success, returns a StarAmount object.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getmystarbalance
       */
      getMyStarBalance(signal) {
        return this.raw.getMyStarBalance(signal);
      }
      /**
       * Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of the message to edit
       * @param text New text of the message, 1-4096 characters after entities parsing
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagetext
       */
      editMessageText(chat_id, message_id, text, other2, signal) {
        return this.raw.editMessageText({ chat_id, message_id, text, ...other2 }, signal);
      }
      /**
       * Use this method to edit text and game inline messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param inline_message_id Identifier of the inline message
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagetext
       */
      editMessageTextInline(inline_message_id, text, other2, signal) {
        return this.raw.editMessageText({ inline_message_id, text, ...other2 }, signal);
      }
      /**
       * Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of the message to edit
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagecaption
       */
      editMessageCaption(chat_id, message_id, other2, signal) {
        return this.raw.editMessageCaption({ chat_id, message_id, ...other2 }, signal);
      }
      /**
       * Use this method to edit captions of inline messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param inline_message_id Identifier of the inline message
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagecaption
       */
      editMessageCaptionInline(inline_message_id, other2, signal) {
        return this.raw.editMessageCaption({ inline_message_id, ...other2 }, signal);
      }
      /**
       * Use this method to edit animation, audio, document, photo, or video messages, or to add media to text messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of the message to edit
       * @param media An object for a new media content of the message
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagemedia
       */
      editMessageMedia(chat_id, message_id, media, other2, signal) {
        return this.raw.editMessageMedia({ chat_id, message_id, media, ...other2 }, signal);
      }
      /**
       * Use this method to edit animation, audio, document, photo, or video inline messages, or to add media to text inline messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param inline_message_id Identifier of the inline message
       * @param media An object for a new media content of the message
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagemedia
       */
      editMessageMediaInline(inline_message_id, media, other2, signal) {
        return this.raw.editMessageMedia({ inline_message_id, media, ...other2 }, signal);
      }
      /**
       * Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of the message to edit
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagereplymarkup
       */
      editMessageReplyMarkup(chat_id, message_id, other2, signal) {
        return this.raw.editMessageReplyMarkup({ chat_id, message_id, ...other2 }, signal);
      }
      /**
       * Use this method to edit only the reply markup of inline messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within 48 hours from the time they were sent.
       *
       * @param inline_message_id Identifier of the inline message
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editmessagereplymarkup
       */
      editMessageReplyMarkupInline(inline_message_id, other2, signal) {
        return this.raw.editMessageReplyMarkup({ inline_message_id, ...other2 }, signal);
      }
      /**
       * Use this method to stop a poll which was sent by the bot. On success, the stopped Poll is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of the original message with the poll
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#stoppoll
       */
      stopPoll(chat_id, message_id, other2, signal) {
        return this.raw.stopPoll({ chat_id, message_id, ...other2 }, signal);
      }
      /**
       * Use this method to delete a message, including service messages, with the following limitations:
       * - A message can only be deleted if it was sent less than 48 hours ago.
       * - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.
       * - Bots can delete outgoing messages in private chats, groups, and supergroups.
       * - Bots can delete incoming messages in private chats.
       * - Bots granted can_post_messages permissions can delete outgoing messages in channels.
       * - If the bot is an administrator of a group, it can delete any message there.
       * - If the bot has can_delete_messages administrator right in a supergroup or a channel, it can delete any message there.
       * - If the bot has can_manage_direct_messages administrator right in a channel, it can delete any message in the corresponding direct messages chat.
       * Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_id Identifier of the message to delete
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletemessage
       */
      deleteMessage(chat_id, message_id, signal) {
        return this.raw.deleteMessage({ chat_id, message_id }, signal);
      }
      /**
       * Use this method to delete multiple messages simultaneously. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param message_ids A list of 1-100 identifiers of messages to delete. See deleteMessage for limitations on which messages can be deleted
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletemessages
       */
      deleteMessages(chat_id, message_ids, signal) {
        return this.raw.deleteMessages({ chat_id, message_ids }, signal);
      }
      /**
       * Delete messages on behalf of a business account. Requires the can_delete_outgoing_messages business bot right to delete messages sent by the bot itself, or the can_delete_all_messages business bot right to delete any message. Returns True on success.
       *
       *     @param business_connection_id Unique identifier of the business connection on behalf of which to delete the messages
       *     @param message_ids A list of 1-100 identifiers of messages to delete. All messages must be from the same chat. See deleteMessage for limitations on which messages can be deleted
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletebusinessmessages
       */
      deleteBusinessMessages(business_connection_id, message_ids, signal) {
        return this.raw.deleteBusinessMessages({ business_connection_id, message_ids }, signal);
      }
      /**
       * Changes the first and last name of a managed business account. Requires the can_change_name business bot right. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param first_name The new value of the first name for the business account; 1-64 characters
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setbusinessaccountname
       */
      setBusinessAccountName(business_connection_id, first_name, other2, signal) {
        return this.raw.setBusinessAccountName({ business_connection_id, first_name, ...other2 }, signal);
      }
      /**
       * Changes the username of a managed business account. Requires the can_change_username business bot right. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection *
       * @param username The new value of the username for the business account; 0-32 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setbusinessaccountusername
       */
      setBusinessAccountUsername(business_connection_id, username, signal) {
        return this.raw.setBusinessAccountUsername({ business_connection_id, username }, signal);
      }
      /**
       * Changes the bio of a managed business account. Requires the can_change_bio business bot right. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param bio The new value of the bio for the business account; 0-140 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setbusinessaccountbio
       */
      setBusinessAccountBio(business_connection_id, bio, signal) {
        return this.raw.setBusinessAccountBio({ business_connection_id, bio }, signal);
      }
      /**
       * Changes the profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param photo The new profile photo to set
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setbusinessaccountprofilephoto
       */
      setBusinessAccountProfilePhoto(business_connection_id, photo, other2, signal) {
        return this.raw.setBusinessAccountProfilePhoto({ business_connection_id, photo, ...other2 }, signal);
      }
      /**
       * Removes the current profile photo of a managed business account. Requires the can_edit_profile_photo business bot right. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#removebusinessaccountprofilephoto
       */
      removeBusinessAccountProfilePhoto(business_connection_id, other2, signal) {
        return this.raw.removeBusinessAccountProfilePhoto({ business_connection_id, ...other2 }, signal);
      }
      /**
       * Changes the privacy settings pertaining to incoming gifts in a managed business account. Requires the can_change_gift_settings business bot right. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param show_gift_button Pass True, if a button for sending a gift to the user or by the business account must always be shown in the input field
       * @param accepted_gift_types Types of gifts accepted by the business account
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setbusinessaccountgiftsettings
       */
      setBusinessAccountGiftSettings(business_connection_id, show_gift_button, accepted_gift_types, signal) {
        return this.raw.setBusinessAccountGiftSettings({ business_connection_id, show_gift_button, accepted_gift_types }, signal);
      }
      /**
       * Returns the amount of Telegram Stars owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns StarAmount on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getbusinessaccountstarbalance
       */
      getBusinessAccountStarBalance(business_connection_id, signal) {
        return this.raw.getBusinessAccountStarBalance({ business_connection_id }, signal);
      }
      /**
       * Transfers Telegram Stars from the business account balance to the bot's balance. Requires the can_transfer_stars business bot right. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param star_count Number of Telegram Stars to transfer; 1-10000
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#transferbusinessaccountstars
       */
      transferBusinessAccountStars(business_connection_id, star_count, signal) {
        return this.raw.transferBusinessAccountStars({ business_connection_id, star_count }, signal);
      }
      /**
       * Returns the gifts received and owned by a managed business account. Requires the can_view_gifts_and_stars business bot right. Returns OwnedGifts on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getbusinessaccountgifts
       */
      getBusinessAccountGifts(business_connection_id, other2, signal) {
        return this.raw.getBusinessAccountGifts({ business_connection_id, ...other2 }, signal);
      }
      /**
       * Converts a given regular gift to Telegram Stars. Requires the can_convert_gifts_to_stars business bot right. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param owned_gift_id Unique identifier of the regular gift that should be converted to Telegram Stars
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#convertgifttostars
       */
      convertGiftToStars(business_connection_id, owned_gift_id, signal) {
        return this.raw.convertGiftToStars({ business_connection_id, owned_gift_id }, signal);
      }
      /**
       * Upgrades a given regular gift to a unique gift. Requires the can_transfer_and_upgrade_gifts business bot right. Additionally requires the can_transfer_stars business bot right if the upgrade is paid. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param owned_gift_id Unique identifier of the regular gift that should be upgraded to a unique one
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#upgradegift
       */
      upgradeGift(business_connection_id, owned_gift_id, other2, signal) {
        return this.raw.upgradeGift({ business_connection_id, owned_gift_id, ...other2 }, signal);
      }
      /**
       * Transfers an owned unique gift to another user. Requires the can_transfer_and_upgrade_gifts business bot right. Requires can_transfer_stars business bot right if the transfer is paid. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param owned_gift_id Unique identifier of the regular gift that should be transferred
       * @param new_owner_chat_id Unique identifier of the chat which will own the gift. The chat must be active in the last 24 hours.
       * @param star_count The amount of Telegram Stars that will be paid for the transfer from the business account balance. If positive, then the can_transfer_stars business bot right is required.
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#transfergift
       */
      transferGift(business_connection_id, owned_gift_id, new_owner_chat_id, star_count, signal) {
        return this.raw.transferGift({
          business_connection_id,
          owned_gift_id,
          new_owner_chat_id,
          star_count
        }, signal);
      }
      /**
       * Posts a story on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param content Content of the story
       * @param active_period Period after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#poststory
       */
      postStory(business_connection_id, content, active_period, other2, signal) {
        return this.raw.postStory({ business_connection_id, content, active_period, ...other2 }, signal);
      }
      /**
       * Reposts a story on behalf of a business account from another business account. Both business accounts must be managed by the same bot, and the story on the source account must have been posted (or reposted) by the bot. Requires the can_manage_stories business bot right for both business accounts. Returns Story on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param from_chat_id Unique identifier of the chat which posted the story that should be reposted
       * @param from_story_id Unique identifier of the story that should be reposted
       * @param active_period Period after which the story is moved to the archive, in seconds; must be one of 6 * 3600, 12 * 3600, 86400, or 2 * 86400
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#repoststory
       */
      repostStory(business_connection_id, from_chat_id, from_story_id, active_period, other2, signal) {
        return this.raw.repostStory({
          business_connection_id,
          from_chat_id,
          from_story_id,
          active_period,
          ...other2
        }, signal);
      }
      /**
       * Edits a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns Story on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param story_id Unique identifier of the story to edit
       * @param content Content of the story
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#editstory
       */
      editStory(business_connection_id, story_id, content, other2, signal) {
        return this.raw.editStory({ business_connection_id, story_id, content, ...other2 }, signal);
      }
      /**
       * Deletes a story previously posted by the bot on behalf of a managed business account. Requires the can_manage_stories business bot right. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection
       * @param story_id Unique identifier of the story to delete
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletestory
       */
      deleteStory(business_connection_id, story_id, signal) {
        return this.raw.deleteStory({ business_connection_id, story_id }, signal);
      }
      /**
       * Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param sticker Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. Video and animated stickers can't be sent via an HTTP URL.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendsticker
       */
      sendSticker(chat_id, sticker, other2, signal) {
        return this.raw.sendSticker({ chat_id, sticker, ...other2 }, signal);
      }
      /**
       * Use this method to get a sticker set. On success, a StickerSet object is returned.
       *
       * @param name Name of the sticker set
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getstickerset
       */
      getStickerSet(name4, signal) {
        return this.raw.getStickerSet({ name: name4 }, signal);
      }
      /**
       * Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.
       *
       * @param custom_emoji_ids A list of custom emoji identifiers
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getcustomemojistickers
       */
      getCustomEmojiStickers(custom_emoji_ids, signal) {
        return this.raw.getCustomEmojiStickers({ custom_emoji_ids }, signal);
      }
      /**
       * Use this method to upload a file with a sticker for later use in the createNewStickerSet, addStickerToSet, or replaceStickerInSet methods (the file can be used multiple times). Returns the uploaded File on success.
       *
       * @param user_id User identifier of sticker file owner
       * @param sticker_format Format of the sticker, must be one of “static”, “animated”, “video”
       * @param sticker A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements.
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#uploadstickerfile
       */
      uploadStickerFile(user_id, sticker_format, sticker, signal) {
        return this.raw.uploadStickerFile({ user_id, sticker_format, sticker }, signal);
      }
      /**
       * Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns True on success.
       *
       * @param user_id User identifier of created sticker set owner
       * @param name Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in `_by_<bot_username>`. `<bot_username>` is case insensitive. 1-64 characters.
       * @param title Sticker set title, 1-64 characters
       * @param stickers A list of 1-50 initial stickers to be added to the sticker set
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#createnewstickerset
       */
      createNewStickerSet(user_id, name4, title, stickers, other2, signal) {
        return this.raw.createNewStickerSet({ user_id, name: name4, title, stickers, ...other2 }, signal);
      }
      /**
       * Use this method to add a new sticker to a set created by the bot. The format of the added sticker must match the format of the other stickers in the set. Emoji sticker sets can have up to 200 stickers. Animated and video sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. Returns True on success.
       *
       * @param user_id User identifier of sticker set owner
       * @param name Sticker set name
       * @param sticker An object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed.
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#addstickertoset
       */
      addStickerToSet(user_id, name4, sticker, signal) {
        return this.raw.addStickerToSet({ user_id, name: name4, sticker }, signal);
      }
      /**
       * Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.
       *
       * @param sticker File identifier of the sticker
       * @param position New sticker position in the set, zero-based
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setstickerpositioninset
       */
      setStickerPositionInSet(sticker, position, signal) {
        return this.raw.setStickerPositionInSet({ sticker, position }, signal);
      }
      /**
       * Use this method to delete a sticker from a set created by the bot. Returns True on success.
       *
       * @param sticker File identifier of the sticker
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletestickerfromset
       */
      deleteStickerFromSet(sticker, signal) {
        return this.raw.deleteStickerFromSet({ sticker }, signal);
      }
      /**
       * Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling deleteStickerFromSet, then addStickerToSet, then setStickerPositionInSet. Returns True on success.
       *
       * @param user_id User identifier of the sticker set owner
       * @param name Sticker set name
       * @param old_sticker File identifier of the replaced sticker
       * @param sticker An object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set remains unchanged.:x
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#replacestickerinset
       */
      replaceStickerInSet(user_id, name4, old_sticker, sticker, signal) {
        return this.raw.replaceStickerInSet({ user_id, name: name4, old_sticker, sticker }, signal);
      }
      /**
       * Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success.
       *
       * @param sticker File identifier of the sticker
       * @param emoji_list A list of 1-20 emoji associated with the sticker
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setstickeremojilist
       */
      setStickerEmojiList(sticker, emoji_list, signal) {
        return this.raw.setStickerEmojiList({ sticker, emoji_list }, signal);
      }
      /**
       * Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns True on success.
       *
       * @param sticker File identifier of the sticker
       * @param keywords A list of 0-20 search keywords for the sticker with total length of up to 64 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setstickerkeywords
       */
      setStickerKeywords(sticker, keywords2, signal) {
        return this.raw.setStickerKeywords({ sticker, keywords: keywords2 }, signal);
      }
      /**
       * Use this method to change the mask position of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns True on success.
       *
       * @param sticker File identifier of the sticker
       * @param mask_position An object with the position where the mask should be placed on faces. Omit the parameter to remove the mask position.
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setstickermaskposition
       */
      setStickerMaskPosition(sticker, mask_position, signal) {
        return this.raw.setStickerMaskPosition({ sticker, mask_position }, signal);
      }
      /**
       * Use this method to set the title of a created sticker set. Returns True on success.
       *
       * @param name Sticker set name
       * @param title Sticker set title, 1-64 characters
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setstickersettitle
       */
      setStickerSetTitle(name4, title, signal) {
        return this.raw.setStickerSetTitle({ name: name4, title }, signal);
      }
      /**
       * Use this method to delete a sticker set that was created by the bot. Returns True on success.
       *
       * @param name Sticker set name
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#deletestickerset
       */
      deleteStickerSet(name4, signal) {
        return this.raw.deleteStickerSet({ name: name4 }, signal);
      }
      /**
       * Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns True on success.
       *
       * @param name Sticker set name
       * @param user_id User identifier of the sticker set owner
       * @param thumbnail A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail.
       * @param format Format of the thumbnail, must be one of “static” for a .WEBP or .PNG image, “animated” for a .TGS animation, or “video” for a WEBM video
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setstickersetthumbnail
       */
      setStickerSetThumbnail(name4, user_id, thumbnail, format4, signal) {
        return this.raw.setStickerSetThumbnail({ name: name4, user_id, thumbnail, format: format4 }, signal);
      }
      /**
       * Use this method to set the thumbnail of a custom emoji sticker set. Returns True on success.
       *
       * @param name Sticker set name
       * @param custom_emoji_id Custom emoji identifier of a sticker from the sticker set; pass an empty string to drop the thumbnail and use the first sticker as the thumbnail.
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setcustomemojistickersetthumbnail
       */
      setCustomEmojiStickerSetThumbnail(name4, custom_emoji_id, signal) {
        return this.raw.setCustomEmojiStickerSetThumbnail({
          name: name4,
          custom_emoji_id
        }, signal);
      }
      /**
       * Returns the list of gifts that can be sent by the bot to users and channel chats. Requires no parameters. Returns a Gifts object.
       *
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getavailablegifts
       */
      getAvailableGifts(signal) {
        return this.raw.getAvailableGifts(signal);
      }
      /**
       * Sends a gift to the given user. The gift can't be converted to Telegram Stars by the receiver. Returns True on success.
       *
       * @param user_id Unique identifier of the target user who will receive the gift
       * @param gift_id Identifier of the gift
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendgift
       */
      sendGift(user_id, gift_id, other2, signal) {
        return this.raw.sendGift({ user_id, gift_id, ...other2 }, signal);
      }
      /**
       * Gifts a Telegram Premium subscription to the given user. Returns True on success.
       *
       * @param user_id Unique identifier of the target user who will receive a Telegram Premium subscription
       * @param month_count Number of months the Telegram Premium subscription will be active for the user; must be one of 3, 6, or 12
       * @param star_count Number of Telegram Stars to pay for the Telegram Premium subscription; must be 1000 for 3 months, 1500 for 6 months, and 2500 for 12 months
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#giftpremiumsubscription
       */
      giftPremiumSubscription(user_id, month_count, star_count, other2, signal) {
        return this.raw.giftPremiumSubscription({ user_id, month_count, star_count, ...other2 }, signal);
      }
      /**
       * Sends a gift to the given channel chat. The gift can't be converted to Telegram Stars by the receiver. Returns True on success.
       *
       * @param chat_id Unique identifier for the chat or username of the channel (in the format @channelusername) that will receive the gift
       * @param gift_id Identifier of the gift
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendgift
       */
      sendGiftToChannel(chat_id, gift_id, other2, signal) {
        return this.raw.sendGift({ chat_id, gift_id, ...other2 }, signal);
      }
      /**
       * Use this method to send answers to an inline query. On success, True is returned.
       * No more than 50 results per query are allowed.
       *
       * Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities.
       *
       * @param inline_query_id Unique identifier for the answered query
       * @param results An array of results for the inline query
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#answerinlinequery
       */
      answerInlineQuery(inline_query_id, results, other2, signal) {
        return this.raw.answerInlineQuery({ inline_query_id, results, ...other2 }, signal);
      }
      /**
       * Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.
       *
       * @param web_app_query_id Unique identifier for the query to be answered
       * @param result An object describing the message to be sent
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#answerwebappquery
       */
      answerWebAppQuery(web_app_query_id, result, signal) {
        return this.raw.answerWebAppQuery({ web_app_query_id, result }, signal);
      }
      /**
       * Stores a message that can be sent by a user of a Mini App. Returns a PreparedInlineMessage object.
       *
       * @param user_id Unique identifier of the target user that can use the prepared message
       * @param result An object describing the message to be sent
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#savepreparedinlinemessage
       */
      savePreparedInlineMessage(user_id, result, other2, signal) {
        return this.raw.savePreparedInlineMessage({ user_id, result, ...other2 }, signal);
      }
      /**
       * Use this method to send invoices. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param title Product name, 1-32 characters
       * @param description Product description, 1-255 characters
       * @param payload Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
       * @param currency Three-letter ISO 4217 currency code, see more on currencies
       * @param prices Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendinvoice
       */
      sendInvoice(chat_id, title, description, payload, currency, prices, other2, signal) {
        return this.raw.sendInvoice({
          chat_id,
          title,
          description,
          payload,
          currency,
          prices,
          ...other2
        }, signal);
      }
      /**
       * Use this method to create a link for an invoice. Returns the created invoice link as String on success.
       *
       * @param title Product name, 1-32 characters
       * @param description Product description, 1-255 characters
       * @param payload Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
       * @param provider_token Payment provider token, obtained via BotFather
       * @param currency Three-letter ISO 4217 currency code, see more on currencies
       * @param prices Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#createinvoicelink
       */
      createInvoiceLink(title, description, payload, provider_token, currency, prices, other2, signal) {
        return this.raw.createInvoiceLink({
          title,
          description,
          payload,
          provider_token,
          currency,
          prices,
          ...other2
        }, signal);
      }
      /**
       * If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
       *
       * @param shipping_query_id Unique identifier for the query to be answered
       * @param ok Pass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#answershippingquery
       */
      answerShippingQuery(shipping_query_id, ok2, other2, signal) {
        return this.raw.answerShippingQuery({ shipping_query_id, ok: ok2, ...other2 }, signal);
      }
      /**
       * Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
       *
       * @param pre_checkout_query_id Unique identifier for the query to be answered
       * @param ok Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#answerprecheckoutquery
       */
      answerPreCheckoutQuery(pre_checkout_query_id, ok2, other2, signal) {
        return this.raw.answerPreCheckoutQuery({ pre_checkout_query_id, ok: ok2, ...other2 }, signal);
      }
      /**
       * Returns the bot's Telegram Star transactions in chronological order. On success, returns a StarTransactions object.
       *
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getstartransactions
       */
      getStarTransactions(other2, signal) {
        return this.raw.getStarTransactions({ ...other2 }, signal);
      }
      /**
       * Refunds a successful payment in Telegram Stars.
       *
       * @param user_id Identifier of the user whose payment will be refunded
       * @param telegram_payment_charge_id Telegram payment identifier
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#refundstarpayment
       */
      refundStarPayment(user_id, telegram_payment_charge_id, signal) {
        return this.raw.refundStarPayment({ user_id, telegram_payment_charge_id }, signal);
      }
      /**
       * Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars. Returns True on success.
       *
       * @param user_id Identifier of the user whose subscription will be edited
       * @param telegram_payment_charge_id Telegram payment identifier for the subscription
       * @param is_canceled Pass True to cancel extension of the user subscription; the subscription must be active up to the end of the current subscription period. Pass False to allow the user to re-enable a subscription that was previously canceled by the bot.
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#edituserstarsubscription
       */
      editUserStarSubscription(user_id, telegram_payment_charge_id, is_canceled, signal) {
        return this.raw.editUserStarSubscription({ user_id, telegram_payment_charge_id, is_canceled }, signal);
      }
      /**
       * Verifies a user on behalf of the organization which is represented by the bot. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#verifyuser
       */
      verifyUser(user_id, other2, signal) {
        return this.raw.verifyUser({ user_id, ...other2 }, signal);
      }
      /**
       * Verifies a chat on behalf of the organization which is represented by the bot. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername). Channel direct messages chats can't be verified.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#verifychat
       */
      verifyChat(chat_id, other2, signal) {
        return this.raw.verifyChat({ chat_id, ...other2 }, signal);
      }
      /**
       * Removes verification from a user who is currently verified on behalf of the organization represented by the bot. Returns True on success.
       *
       * @param user_id Unique identifier of the target user
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#removeuserverification
       */
      removeUserVerification(user_id, signal) {
        return this.raw.removeUserVerification({ user_id }, signal);
      }
      /**
       * Removes verification from a chat that is currently verified on behalf of the organization represented by the bot. Returns True on success.
       *
       * @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#removechatverification
       */
      removeChatVerification(chat_id, signal) {
        return this.raw.removeChatVerification({ chat_id }, signal);
      }
      /**
       * Marks incoming message as read on behalf of a business account. Requires the can_read_messages business bot right. Returns True on success.
       *
       * @param business_connection_id Unique identifier of the business connection on behalf of which to read the message
       * @param chat_id Unique identifier of the chat in which the message was received. The chat must have been active in the last 24 hours.
       * @param message_id Unique identifier of the message to mark as read
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#readbusinessmessage
       */
      readBusinessMessage(business_connection_id, chat_id, message_id, signal) {
        return this.raw.readBusinessMessage({ business_connection_id, chat_id, message_id }, signal);
      }
      /**
       * Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.
       *
       * Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
       *
       * @param user_id User identifier
       * @param errors An array describing the errors
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setpassportdataerrors
       */
      setPassportDataErrors(user_id, errors, signal) {
        return this.raw.setPassportDataErrors({ user_id, errors }, signal);
      }
      /**
       * Use this method to send a game. On success, the sent Message is returned.
       *
       * @param chat_id Unique identifier for the target chat. Games can't be sent to channel direct messages chats and channel chats.
       * @param game_short_name Short name of the game, serves as the unique identifier for the game. Set up your games via BotFather.
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#sendgame
       */
      sendGame(chat_id, game_short_name, other2, signal) {
        return this.raw.sendGame({ chat_id, game_short_name, ...other2 }, signal);
      }
      /**
       * Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
       *
       * @param chat_id Unique identifier for the target chat
       * @param message_id Identifier of the sent message
       * @param user_id User identifier
       * @param score New score, must be non-negative
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setgamescore
       */
      setGameScore(chat_id, message_id, user_id, score, other2, signal) {
        return this.raw.setGameScore({ chat_id, message_id, user_id, score, ...other2 }, signal);
      }
      /**
       * Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
       *
       * @param inline_message_id Identifier of the inline message
       * @param user_id User identifier
       * @param score New score, must be non-negative
       * @param other Optional remaining parameters, confer the official reference below
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#setgamescore
       */
      setGameScoreInline(inline_message_id, user_id, score, other2, signal) {
        return this.raw.setGameScore({ inline_message_id, user_id, score, ...other2 }, signal);
      }
      /**
       * Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects.
       *
       * This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change.
       *
       * @param chat_id Unique identifier for the target chat
       * @param message_id Identifier of the sent message
       * @param user_id Target user id
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getgamehighscores
       */
      getGameHighScores(chat_id, message_id, user_id, signal) {
        return this.raw.getGameHighScores({ chat_id, message_id, user_id }, signal);
      }
      /**
       * Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in an inline game. On success, returns an Array of GameHighScore objects.
       *
       * This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change.
       *
       * @param inline_message_id Identifier of the inline message
       * @param user_id Target user id
       * @param signal Optional `AbortSignal` to cancel the request
       *
       * **Official reference:** https://core.telegram.org/bots/api#getgamehighscores
       */
      getGameHighScoresInline(inline_message_id, user_id, signal) {
        return this.raw.getGameHighScores({ inline_message_id, user_id }, signal);
      }
    };
    exports2.Api = Api;
  }
});

// node_modules/grammy/out/bot.js
var require_bot = __commonJS({
  "node_modules/grammy/out/bot.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Bot = exports2.BotError = exports2.DEFAULT_UPDATE_TYPES = void 0;
    var composer_js_1 = require_composer2();
    Object.defineProperty(exports2, "BotError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return composer_js_1.BotError;
    }, "get") });
    var context_js_1 = require_context();
    var api_js_1 = require_api4();
    var error_js_1 = require_error3();
    var filter_js_1 = require_filter2();
    var platform_node_js_1 = require_platform_node();
    var debug3 = (0, platform_node_js_1.debug)("grammy:bot");
    var debugWarn = (0, platform_node_js_1.debug)("grammy:warn");
    var debugErr = (0, platform_node_js_1.debug)("grammy:error");
    exports2.DEFAULT_UPDATE_TYPES = [
      "message",
      "edited_message",
      "channel_post",
      "edited_channel_post",
      "business_connection",
      "business_message",
      "edited_business_message",
      "deleted_business_messages",
      "inline_query",
      "chosen_inline_result",
      "callback_query",
      "shipping_query",
      "pre_checkout_query",
      "purchased_paid_media",
      "poll",
      "poll_answer",
      "my_chat_member",
      "chat_join_request",
      "chat_boost",
      "removed_chat_boost"
    ];
    var Bot2 = class extends composer_js_1.Composer {
      static {
        __name(this, "Bot");
      }
      /**
       * Creates a new Bot with the given token.
       *
       * Remember that you can listen for messages by calling
       * ```ts
       * bot.on('message', ctx => { ... })
       * ```
       * or similar methods.
       *
       * The simplest way to start your bot is via simple long polling:
       * ```ts
       * bot.start()
       * ```
       *
       * @param token The bot's token as acquired from https://t.me/BotFather
       * @param config Optional configuration properties for the bot
       */
      constructor(token2, config2) {
        var _a7;
        super();
        this.token = token2;
        this.pollingRunning = false;
        this.lastTriedUpdateId = 0;
        this.observedUpdateTypes = /* @__PURE__ */ new Set();
        this.errorHandler = async (err2) => {
          var _a8, _b2;
          console.error("Error in middleware while handling update", (_b2 = (_a8 = err2.ctx) === null || _a8 === void 0 ? void 0 : _a8.update) === null || _b2 === void 0 ? void 0 : _b2.update_id, err2.error);
          console.error("No error handler was set!");
          console.error("Set your own error handler with `bot.catch = ...`");
          if (this.pollingRunning) {
            console.error("Stopping bot");
            await this.stop();
          }
          throw err2;
        };
        if (!token2)
          throw new Error("Empty token!");
        this.me = config2 === null || config2 === void 0 ? void 0 : config2.botInfo;
        this.clientConfig = config2 === null || config2 === void 0 ? void 0 : config2.client;
        this.ContextConstructor = (_a7 = config2 === null || config2 === void 0 ? void 0 : config2.ContextConstructor) !== null && _a7 !== void 0 ? _a7 : context_js_1.Context;
        this.api = new api_js_1.Api(token2, this.clientConfig);
      }
      /**
       * Information about the bot itself as retrieved from `api.getMe()`. Only
       * available after the bot has been initialized via `await bot.init()`, or
       * after the value has been set manually.
       *
       * Starting the bot will always perform the initialization automatically,
       * unless a manual value is already set.
       *
       * Note that the recommended way to set a custom bot information object is
       * to pass it to the configuration object of the `new Bot()` instantiation,
       * rather than assigning this property.
       */
      set botInfo(botInfo) {
        this.me = botInfo;
      }
      get botInfo() {
        if (this.me === void 0) {
          throw new Error("Bot information unavailable! Make sure to call `await bot.init()` before accessing `bot.botInfo`!");
        }
        return this.me;
      }
      /**
       * @inheritdoc
       */
      on(filter5, ...middleware) {
        for (const [u2] of (0, filter_js_1.parse)(filter5).flatMap(filter_js_1.preprocess)) {
          this.observedUpdateTypes.add(u2);
        }
        return super.on(filter5, ...middleware);
      }
      /**
       * @inheritdoc
       */
      reaction(reaction, ...middleware) {
        this.observedUpdateTypes.add("message_reaction");
        return super.reaction(reaction, ...middleware);
      }
      /**
       * Checks if the bot has been initialized. A bot is initialized if the bot
       * information is set. The bot information can either be set automatically
       * by calling `bot.init`, or manually through the bot constructor. Note that
       * usually, initialization is done automatically and you do not have to care
       * about this method.
       *
       * @returns true if the bot is initialized, and false otherwise
       */
      isInited() {
        return this.me !== void 0;
      }
      /**
       * Initializes the bot, i.e. fetches information about the bot itself. This
       * method is called automatically, you usually don't have to call it
       * manually.
       *
       * @param signal Optional `AbortSignal` to cancel the initialization
       */
      async init(signal) {
        var _a7;
        if (!this.isInited()) {
          debug3("Initializing bot");
          (_a7 = this.mePromise) !== null && _a7 !== void 0 ? _a7 : this.mePromise = withRetries(() => this.api.getMe(signal), signal);
          let me2;
          try {
            me2 = await this.mePromise;
          } finally {
            this.mePromise = void 0;
          }
          if (this.me === void 0)
            this.me = me2;
          else
            debug3("Bot info was set by now, will not overwrite");
        }
        debug3(`I am ${this.me.username}!`);
      }
      /**
       * Internal. Do not call. Handles an update batch sequentially by supplying
       * it one-by-one to the middleware. Handles middleware errors and stores the
       * last update identifier that was being tried to handle.
       *
       * @param updates An array of updates to handle
       */
      async handleUpdates(updates) {
        for (const update2 of updates) {
          this.lastTriedUpdateId = update2.update_id;
          try {
            await this.handleUpdate(update2);
          } catch (err2) {
            if (err2 instanceof composer_js_1.BotError) {
              await this.errorHandler(err2);
            } else {
              console.error("FATAL: grammY unable to handle:", err2);
              throw err2;
            }
          }
        }
      }
      /**
       * This is an internal method that you probably will not ever need to call.
       * It is used whenever a new update arrives from the Telegram servers that
       * your bot will handle.
       *
       * If you're writing a library on top of grammY, check out the
       * [documentation](https://grammy.dev/plugins/runner) of the runner
       * plugin for an example that uses this method.
       *
       * @param update An update from the Telegram Bot API
       * @param webhookReplyEnvelope An optional webhook reply envelope
       */
      async handleUpdate(update2, webhookReplyEnvelope) {
        if (this.me === void 0) {
          throw new Error("Bot not initialized! Either call `await bot.init()`, or directly set the `botInfo` option in the `Bot` constructor to specify a known bot info object.");
        }
        debug3(`Processing update ${update2.update_id}`);
        const api = new api_js_1.Api(this.token, this.clientConfig, webhookReplyEnvelope);
        const t5 = this.api.config.installedTransformers();
        if (t5.length > 0)
          api.config.use(...t5);
        const ctx = new this.ContextConstructor(update2, api, this.me);
        try {
          await (0, composer_js_1.run)(this.middleware(), ctx);
        } catch (err2) {
          debugErr(`Error in middleware for update ${update2.update_id}`);
          throw new composer_js_1.BotError(err2, ctx);
        }
      }
      /**
       * Starts your bot using long polling.
       *
       * > This method returns a `Promise` that will never resolve except if your
       * > bot is stopped. **You don't need to `await` the call to `bot.start`**,
       * > but remember to catch potential errors by calling `bot.catch`.
       * > Otherwise your bot will crash (and stop) if something goes wrong in
       * > your code.
       *
       * This method effectively enters a loop that will repeatedly call
       * `getUpdates` and run your middleware for every received update, allowing
       * your bot to respond to messages.
       *
       * If your bot is already running, this method does nothing.
       *
       * **Note that this starts your bot using a very simple long polling
       * implementation.** `bot.start` should only be used for small bots. While
       * the rest of grammY was built to perform well even under extreme loads,
       * simple long polling is not capable of scaling up in a similar fashion.
       * You should switch over to using `@grammyjs/runner` if you are running a
       * bot with high load.
       *
       * What exactly _high load_ means differs from bot to bot, but as a rule of
       * thumb, simple long polling should not be processing more than ~5K
       * messages every hour. Also, if your bot has long-running operations such
       * as large file transfers that block the middleware from completing, this
       * will impact the responsiveness negatively, so it makes sense to use the
       * `@grammyjs/runner` package even if you receive much fewer messages. If
       * you worry about how much load your bot can handle, check out the grammY
       * [documentation](https://grammy.dev/advanced/scaling) about scaling
       * up.
       *
       * @param options Options to use for simple long polling
       */
      async start(options2) {
        var _a7, _b2, _c2;
        const setup = [];
        if (!this.isInited()) {
          setup.push(this.init((_a7 = this.pollingAbortController) === null || _a7 === void 0 ? void 0 : _a7.signal));
        }
        if (this.pollingRunning) {
          await Promise.all(setup);
          debug3("Simple long polling already running!");
          return;
        }
        this.pollingRunning = true;
        this.pollingAbortController = new shim_node_js_1.AbortController();
        try {
          setup.push(withRetries(async () => {
            var _a8;
            await this.api.deleteWebhook({
              drop_pending_updates: options2 === null || options2 === void 0 ? void 0 : options2.drop_pending_updates
            }, (_a8 = this.pollingAbortController) === null || _a8 === void 0 ? void 0 : _a8.signal);
          }, (_b2 = this.pollingAbortController) === null || _b2 === void 0 ? void 0 : _b2.signal));
          await Promise.all(setup);
          await ((_c2 = options2 === null || options2 === void 0 ? void 0 : options2.onStart) === null || _c2 === void 0 ? void 0 : _c2.call(options2, this.botInfo));
        } catch (err2) {
          this.pollingRunning = false;
          this.pollingAbortController = void 0;
          throw err2;
        }
        if (!this.pollingRunning)
          return;
        validateAllowedUpdates(this.observedUpdateTypes, options2 === null || options2 === void 0 ? void 0 : options2.allowed_updates);
        this.use = noUseFunction;
        debug3("Starting simple long polling");
        await this.loop(options2);
        debug3("Middleware is done running");
      }
      /**
       * Stops the bot from long polling.
       *
       * All middleware that is currently being executed may complete, but no
       * further `getUpdates` calls will be performed. The current `getUpdates`
       * request will be cancelled.
       *
       * In addition, this method will _confirm_ the last received update to the
       * Telegram servers by calling `getUpdates` one last time with the latest
       * offset value. If any updates are received in this call, they are
       * discarded and will be fetched again when the bot starts up the next time.
       * Confer the official documentation on confirming updates if you want to
       * know more: https://core.telegram.org/bots/api#getupdates
       *
       * > Note that this method will not wait for the middleware stack to finish.
       * > If you need to run code after all middleware is done, consider waiting
       * > for the promise returned by `bot.start()` to resolve.
       */
      async stop() {
        var _a7;
        if (this.pollingRunning) {
          debug3("Stopping bot, saving update offset");
          this.pollingRunning = false;
          (_a7 = this.pollingAbortController) === null || _a7 === void 0 ? void 0 : _a7.abort();
          const offset = this.lastTriedUpdateId + 1;
          await this.api.getUpdates({ offset, limit: 1 }).finally(() => this.pollingAbortController = void 0);
        } else {
          debug3("Bot is not running!");
        }
      }
      /**
       * Returns true if the bot is currently running via built-in long polling,
       * and false otherwise.
       *
       * If this method returns true, it means that `bot.start()` has been called,
       * and that the bot has neither crashed nor was it stopped via a call to
       * `bot.stop()`. This also means that you cannot use this method to check if
       * a webhook server is running, or if grammY runner was started.
       *
       * Note that this method will already begin to return true even before the
       * call to `bot.start()` has completed its initialization phase (and hence
       * before `bot.isInited()` returns true). By extension, this method
       * returns true before `onStart` callback of `bot.start()` is invoked.
       */
      isRunning() {
        return this.pollingRunning;
      }
      /**
       * Sets the bots error handler that is used during long polling.
       *
       * You should call this method to set an error handler if you are using long
       * polling, no matter whether you use `bot.start` or the `@grammyjs/runner`
       * package to run your bot.
       *
       * Calling `bot.catch` when using other means of running your bot (or
       * webhooks) has no effect.
       *
       * @param errorHandler A function that handles potential middleware errors
       */
      catch(errorHandler) {
        this.errorHandler = errorHandler;
      }
      /**
       * Internal. Do not call. Enters a loop that will perform long polling until
       * the bot is stopped.
       */
      async loop(options2) {
        var _a7, _b2;
        const limit2 = options2 === null || options2 === void 0 ? void 0 : options2.limit;
        const timeout2 = (_a7 = options2 === null || options2 === void 0 ? void 0 : options2.timeout) !== null && _a7 !== void 0 ? _a7 : 30;
        let allowed_updates = (_b2 = options2 === null || options2 === void 0 ? void 0 : options2.allowed_updates) !== null && _b2 !== void 0 ? _b2 : [];
        try {
          while (this.pollingRunning) {
            const updates = await this.fetchUpdates({ limit: limit2, timeout: timeout2, allowed_updates });
            if (updates === void 0)
              break;
            await this.handleUpdates(updates);
            allowed_updates = void 0;
          }
        } finally {
          this.pollingRunning = false;
        }
      }
      /**
       * Internal. Do not call. Reliably fetches an update batch via `getUpdates`.
       * Handles all known errors. Returns `undefined` if the bot is stopped and
       * the call gets cancelled.
       *
       * @param options Polling options
       * @returns An array of updates, or `undefined` if the bot is stopped.
       */
      async fetchUpdates({ limit: limit2, timeout: timeout2, allowed_updates }) {
        var _a7;
        const offset = this.lastTriedUpdateId + 1;
        let updates = void 0;
        do {
          try {
            updates = await this.api.getUpdates({ offset, limit: limit2, timeout: timeout2, allowed_updates }, (_a7 = this.pollingAbortController) === null || _a7 === void 0 ? void 0 : _a7.signal);
          } catch (error40) {
            await this.handlePollingError(error40);
          }
        } while (updates === void 0 && this.pollingRunning);
        return updates;
      }
      /**
       * Internal. Do not call. Handles an error that occurred during long
       * polling.
       */
      async handlePollingError(error40) {
        var _a7;
        if (!this.pollingRunning) {
          debug3("Pending getUpdates request cancelled");
          return;
        }
        let sleepSeconds = 3;
        if (error40 instanceof error_js_1.GrammyError) {
          debugErr(error40.message);
          if (error40.error_code === 401 || error40.error_code === 409) {
            throw error40;
          } else if (error40.error_code === 429) {
            debugErr("Bot API server is closing.");
            sleepSeconds = (_a7 = error40.parameters.retry_after) !== null && _a7 !== void 0 ? _a7 : sleepSeconds;
          }
        } else
          debugErr(error40);
        debugErr(`Call to getUpdates failed, retrying in ${sleepSeconds} seconds ...`);
        await sleep4(sleepSeconds);
      }
    };
    exports2.Bot = Bot2;
    async function withRetries(task, signal) {
      const INITIAL_DELAY = 50;
      let lastDelay = INITIAL_DELAY;
      async function handleError2(error40) {
        let delay5 = false;
        let strategy = "rethrow";
        if (error40 instanceof error_js_1.HttpError) {
          delay5 = true;
          strategy = "retry";
        } else if (error40 instanceof error_js_1.GrammyError) {
          if (error40.error_code >= 500) {
            delay5 = true;
            strategy = "retry";
          } else if (error40.error_code === 429) {
            const retryAfter = error40.parameters.retry_after;
            if (typeof retryAfter === "number") {
              await sleep4(retryAfter, signal);
              lastDelay = INITIAL_DELAY;
            } else {
              delay5 = true;
            }
            strategy = "retry";
          }
        }
        if (delay5) {
          if (lastDelay !== INITIAL_DELAY) {
            await sleep4(lastDelay, signal);
          }
          const TWENTY_MINUTES = 20 * 60 * 1e3;
          lastDelay = Math.min(TWENTY_MINUTES, 2 * lastDelay);
        }
        return strategy;
      }
      __name(handleError2, "handleError");
      let result = { ok: false };
      while (!result.ok) {
        try {
          result = { ok: true, value: await task() };
        } catch (error40) {
          debugErr(error40);
          const strategy = await handleError2(error40);
          switch (strategy) {
            case "retry":
              continue;
            case "rethrow":
              throw error40;
          }
        }
      }
      return result.value;
    }
    __name(withRetries, "withRetries");
    async function sleep4(seconds, signal) {
      let handle2;
      let reject;
      function abort2() {
        reject === null || reject === void 0 ? void 0 : reject(new Error("Aborted delay"));
        if (handle2 !== void 0)
          clearTimeout(handle2);
      }
      __name(abort2, "abort");
      try {
        await new Promise((res, rej) => {
          reject = rej;
          if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
            abort2();
            return;
          }
          signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", abort2);
          handle2 = setTimeout(res, 1e3 * seconds);
        });
      } finally {
        signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", abort2);
      }
    }
    __name(sleep4, "sleep");
    function validateAllowedUpdates(updates, allowed = exports2.DEFAULT_UPDATE_TYPES) {
      const impossible = Array.from(updates).filter((u2) => !allowed.includes(u2));
      if (impossible.length > 0) {
        debugWarn(`You registered listeners for the following update types, but you did not specify them in \`allowed_updates\` so they may not be received: ${impossible.map((u2) => `'${u2}'`).join(", ")}`);
      }
    }
    __name(validateAllowedUpdates, "validateAllowedUpdates");
    function noUseFunction() {
      throw new Error(`It looks like you are registering more listeners on your bot from within other listeners! This means that every time your bot handles a message like this one, new listeners will be added. This list grows until your machine crashes, so grammY throws this error to tell you that you should probably do things a bit differently. If you're unsure how to resolve this problem, you can ask in the group chat: https://telegram.me/grammyjs

On the other hand, if you actually know what you're doing and you do need to install further middleware while your bot is running, consider installing a composer instance on your bot, and in turn augment the composer after the fact. This way, you can circumvent this protection against memory leaks.`);
    }
    __name(noUseFunction, "noUseFunction");
    var shim_node_js_1 = require_shim_node();
  }
});

// node_modules/grammy/out/convenience/constants.js
var require_constants19 = __commonJS({
  "node_modules/grammy/out/convenience/constants.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.API_CONSTANTS = void 0;
    var bot_js_1 = require_bot();
    var ALL_UPDATE_TYPES = [
      ...bot_js_1.DEFAULT_UPDATE_TYPES,
      "chat_member",
      "message_reaction",
      "message_reaction_count"
    ];
    var ALL_CHAT_PERMISSIONS = {
      can_send_messages: true,
      can_send_audios: true,
      can_send_documents: true,
      can_send_photos: true,
      can_send_videos: true,
      can_send_video_notes: true,
      can_send_voice_notes: true,
      can_send_polls: true,
      can_send_other_messages: true,
      can_add_web_page_previews: true,
      can_change_info: true,
      can_invite_users: true,
      can_edit_tag: true,
      can_pin_messages: true,
      can_manage_topics: true
    };
    exports2.API_CONSTANTS = {
      DEFAULT_UPDATE_TYPES: bot_js_1.DEFAULT_UPDATE_TYPES,
      ALL_UPDATE_TYPES,
      ALL_CHAT_PERMISSIONS
    };
    Object.freeze(exports2.API_CONSTANTS);
  }
});

// node_modules/grammy/out/convenience/inline_query.js
var require_inline_query = __commonJS({
  "node_modules/grammy/out/convenience/inline_query.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InlineQueryResultBuilder = void 0;
    function inputMessage(queryTemplate) {
      return {
        ...queryTemplate,
        ...inputMessageMethods(queryTemplate)
      };
    }
    __name(inputMessage, "inputMessage");
    function inputMessageMethods(queryTemplate) {
      return {
        text(message_text, options2 = {}) {
          const content = {
            message_text,
            ...options2
          };
          return { ...queryTemplate, input_message_content: content };
        },
        location(latitude, longitude, options2 = {}) {
          const content = {
            latitude,
            longitude,
            ...options2
          };
          return { ...queryTemplate, input_message_content: content };
        },
        venue(title, latitude, longitude, address, options2) {
          const content = {
            title,
            latitude,
            longitude,
            address,
            ...options2
          };
          return { ...queryTemplate, input_message_content: content };
        },
        contact(first_name, phone_number, options2 = {}) {
          const content = {
            first_name,
            phone_number,
            ...options2
          };
          return { ...queryTemplate, input_message_content: content };
        },
        invoice(title, description, payload, provider_token, currency, prices, options2 = {}) {
          const content = {
            title,
            description,
            payload,
            provider_token,
            currency,
            prices,
            ...options2
          };
          return { ...queryTemplate, input_message_content: content };
        }
      };
    }
    __name(inputMessageMethods, "inputMessageMethods");
    exports2.InlineQueryResultBuilder = {
      /**
       * Builds an InlineQueryResultArticle object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultarticle. Requires you
       * to specify the actual message content by calling another function on the
       * object returned from this method.
       *
       * @param id Unique identifier for this result, 1-64 Bytes
       * @param title Title of the result
       * @param options Remaining options
       */
      article(id, title, options2 = {}) {
        return inputMessageMethods({ type: "article", id, title, ...options2 });
      },
      /**
       * Builds an InlineQueryResultAudio object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultaudio.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param title Title
       * @param audio_url A valid URL for the audio file
       * @param options Remaining options
       */
      audio(id, title, audio_url, options2 = {}) {
        return inputMessage({
          type: "audio",
          id,
          title,
          audio_url: typeof audio_url === "string" ? audio_url : audio_url.href,
          ...options2
        });
      },
      /**
       * Builds an InlineQueryResultCachedAudio object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultcachedaudio.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param audio_file_id A valid file identifier for the audio file
       * @param options Remaining options
       */
      audioCached(id, audio_file_id, options2 = {}) {
        return inputMessage({ type: "audio", id, audio_file_id, ...options2 });
      },
      /**
       * Builds an InlineQueryResultContact object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultcontact.
       *
       * @param id Unique identifier for this result, 1-64 Bytes
       * @param phone_number Contact's phone number
       * @param first_name Contact's first name
       * @param options Remaining options
       */
      contact(id, phone_number, first_name, options2 = {}) {
        return inputMessage({ type: "contact", id, phone_number, first_name, ...options2 });
      },
      /**
       * Builds an InlineQueryResultDocument object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultdocument with
       * mime_type set to "application/pdf".
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param title Title for the result
       * @param document_url A valid URL for the file
       * @param options Remaining options
       */
      documentPdf(id, title, document_url, options2 = {}) {
        return inputMessage({
          type: "document",
          mime_type: "application/pdf",
          id,
          title,
          document_url: typeof document_url === "string" ? document_url : document_url.href,
          ...options2
        });
      },
      /**
       * Builds an InlineQueryResultDocument object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultdocument with
       * mime_type set to "application/zip".
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param title Title for the result
       * @param document_url A valid URL for the file
       * @param options Remaining options
       */
      documentZip(id, title, document_url, options2 = {}) {
        return inputMessage({
          type: "document",
          mime_type: "application/zip",
          id,
          title,
          document_url: typeof document_url === "string" ? document_url : document_url.href,
          ...options2
        });
      },
      /**
       * Builds an InlineQueryResultCachedDocument object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultcacheddocument.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param title Title for the result
       * @param document_file_id A valid file identifier for the file
       * @param options Remaining options
       */
      documentCached(id, title, document_file_id, options2 = {}) {
        return inputMessage({ type: "document", id, title, document_file_id, ...options2 });
      },
      /**
       * Builds an InlineQueryResultGame object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultgame.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param game_short_name Short name of the game
       * @param options Remaining options
       */
      game(id, game_short_name, options2 = {}) {
        return { type: "game", id, game_short_name, ...options2 };
      },
      /**
       * Builds an InlineQueryResultGif object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultgif.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param gif_url A valid URL for the GIF file. File size must not exceed 1MB
       * @param thumbnail_url URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result
       * @param options Remaining options
       */
      gif(id, gif_url, thumbnail_url, options2 = {}) {
        return inputMessage({
          type: "gif",
          id,
          gif_url: typeof gif_url === "string" ? gif_url : gif_url.href,
          thumbnail_url: typeof thumbnail_url === "string" ? thumbnail_url : thumbnail_url.href,
          ...options2
        });
      },
      /**
       * Builds an InlineQueryResultCachedGif object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultcachedgif.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param gif_file_id A valid file identifier for the GIF file
       * @param options Remaining options
       */
      gifCached(id, gif_file_id, options2 = {}) {
        return inputMessage({ type: "gif", id, gif_file_id, ...options2 });
      },
      /**
       * Builds an InlineQueryResultLocation object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultlocation.
       *
       * @param id Unique identifier for this result, 1-64 Bytes
       * @param title Location title
       * @param latitude Location latitude in degrees
       * @param longitude Location longitude in degrees
       * @param options Remaining options
       */
      location(id, title, latitude, longitude, options2 = {}) {
        return inputMessage({ type: "location", id, title, latitude, longitude, ...options2 });
      },
      /**
       * Builds an InlineQueryResultMpeg4Gif object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultmpeg4gif.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param mpeg4_url A valid URL for the MPEG4 file. File size must not exceed 1MB
       * @param thumbnail_url URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result
       * @param options Remaining options
       */
      mpeg4gif(id, mpeg4_url, thumbnail_url, options2 = {}) {
        return inputMessage({
          type: "mpeg4_gif",
          id,
          mpeg4_url: typeof mpeg4_url === "string" ? mpeg4_url : mpeg4_url.href,
          thumbnail_url: typeof thumbnail_url === "string" ? thumbnail_url : thumbnail_url.href,
          ...options2
        });
      },
      /**
       * Builds an InlineQueryResultCachedMpeg4Gif object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultcachedmpeg4gif.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param mpeg4_file_id A valid file identifier for the MPEG4 file
       * @param options Remaining options
       */
      mpeg4gifCached(id, mpeg4_file_id, options2 = {}) {
        return inputMessage({ type: "mpeg4_gif", id, mpeg4_file_id, ...options2 });
      },
      /**
       * Builds an InlineQueryResultPhoto object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultphoto with the
       * thumbnail defaulting to the photo itself.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param photo_url A valid URL of the photo. Photo must be in JPEG format. Photo size must not exceed 5MB
       * @param options Remaining options
       */
      photo(id, photo_url, options2 = {}) {
        const photoUrl = typeof photo_url === "string" ? photo_url : photo_url.href;
        return inputMessage({
          type: "photo",
          id,
          photo_url: photoUrl,
          thumbnail_url: photoUrl,
          ...options2
        });
      },
      /**
       * Builds an InlineQueryResultCachedPhoto object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultcachedphoto.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param photo_file_id A valid file identifier of the photo
       * @param options Remaining options
       */
      photoCached(id, photo_file_id, options2 = {}) {
        return inputMessage({ type: "photo", id, photo_file_id, ...options2 });
      },
      /**
       * Builds an InlineQueryResultCachedSticker object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultcachedsticker.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param sticker_file_id A valid file identifier of the sticker
       * @param options Remaining options
       */
      stickerCached(id, sticker_file_id, options2 = {}) {
        return inputMessage({ type: "sticker", id, sticker_file_id, ...options2 });
      },
      /**
       * Builds an InlineQueryResultVenue object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultvenue.
       *
       * @param id Unique identifier for this result, 1-64 Bytes
       * @param title Title of the venue
       * @param latitude Latitude of the venue location in degrees
       * @param longitude Longitude of the venue location in degrees
       * @param address Address of the venue
       * @param options Remaining options
       */
      venue(id, title, latitude, longitude, address, options2 = {}) {
        return inputMessage({
          type: "venue",
          id,
          title,
          latitude,
          longitude,
          address,
          ...options2
        });
      },
      /**
       * Builds an InlineQueryResultVideo object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultvideo with mime_type
       * set to "text/html". This will send an embedded video player. Requires you
       * to specify the actual message content by calling another function on the
       * object returned from this method.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param title Title for the result
       * @param video_url A valid URL for the embedded video player
       * @param thumbnail_url URL of the thumbnail (JPEG only) for the video
       * @param options Remaining options
       */
      videoHtml(id, title, video_url, thumbnail_url, options2 = {}) {
        return inputMessageMethods({
          type: "video",
          mime_type: "text/html",
          id,
          title,
          video_url: typeof video_url === "string" ? video_url : video_url.href,
          thumbnail_url: typeof thumbnail_url === "string" ? thumbnail_url : thumbnail_url.href,
          ...options2
        });
      },
      /**
       * Builds an InlineQueryResultVideo object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultvideo with mime_type
       * set to "video/mp4".
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param title Title for the result
       * @param video_url A valid URL for the video file
       * @param thumbnail_url URL of the thumbnail (JPEG only) for the video
       * @param options Remaining options
       */
      videoMp4(id, title, video_url, thumbnail_url, options2 = {}) {
        return inputMessage({
          type: "video",
          mime_type: "video/mp4",
          id,
          title,
          video_url: typeof video_url === "string" ? video_url : video_url.href,
          thumbnail_url: typeof thumbnail_url === "string" ? thumbnail_url : thumbnail_url.href,
          ...options2
        });
      },
      /**
       * Builds an InlineQueryResultCachedVideo object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultcachedvideo.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param title Title for the result
       * @param video_file_id A valid file identifier for the video file
       * @param options Remaining options
       */
      videoCached(id, title, video_file_id, options2 = {}) {
        return inputMessage({ type: "video", id, title, video_file_id, ...options2 });
      },
      /**
       * Builds an InlineQueryResultVoice object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultvoice.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param title Voice message title
       * @param voice_url A valid URL for the voice recording
       * @param options Remaining options
       */
      voice(id, title, voice_url, options2 = {}) {
        return inputMessage({
          type: "voice",
          id,
          title,
          voice_url: typeof voice_url === "string" ? voice_url : voice_url.href,
          ...options2
        });
      },
      /**
       * Builds an InlineQueryResultCachedVoice object as specified by
       * https://core.telegram.org/bots/api#inlinequeryresultcachedvoice.
       *
       * @param id Unique identifier for this result, 1-64 bytes
       * @param title Voice message title
       * @param voice_file_id A valid file identifier for the voice message
       * @param options Remaining options
       */
      voiceCached(id, title, voice_file_id, options2 = {}) {
        return inputMessage({ type: "voice", id, title, voice_file_id, ...options2 });
      }
    };
  }
});

// node_modules/grammy/out/convenience/input_media.js
var require_input_media = __commonJS({
  "node_modules/grammy/out/convenience/input_media.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InputMediaBuilder = void 0;
    exports2.InputMediaBuilder = {
      /**
       * Creates a new `InputMediaPhoto` object as specified by
       * https://core.telegram.org/bots/api#inputmediaphoto.
       *
       * @param media An `InputFile` instance or a file identifier
       * @param options Remaining optional options
       */
      photo(media, options2 = {}) {
        return { type: "photo", media, ...options2 };
      },
      /**
       * Creates a new `InputMediaVideo` object as specified by
       * https://core.telegram.org/bots/api#inputmediavideo.
       *
       * @param media An `InputFile` instance or a file identifier
       * @param options Remaining optional options
       */
      video(media, options2 = {}) {
        return { type: "video", media, ...options2 };
      },
      /**
       * Creates a new `InputMediaAnimation` object as specified by
       * https://core.telegram.org/bots/api#inputmediaanimation.
       *
       * @param media An `InputFile` instance or a file identifier
       * @param options Remaining optional options
       */
      animation(media, options2 = {}) {
        return { type: "animation", media, ...options2 };
      },
      /**
       * Creates a new `InputMediaAudio` object as specified by
       * https://core.telegram.org/bots/api#inputmediaaudio.
       *
       * @param media An `InputFile` instance or a file identifier
       * @param options Remaining optional options
       */
      audio(media, options2 = {}) {
        return { type: "audio", media, ...options2 };
      },
      /**
       * Creates a new `InputMediaDocument` object as specified by
       * https://core.telegram.org/bots/api#inputmediadocument.
       *
       * @param media An `InputFile` instance or a file identifier
       * @param options Remaining optional options
       */
      document(media, options2 = {}) {
        return { type: "document", media, ...options2 };
      }
    };
  }
});

// node_modules/grammy/out/convenience/keyboard.js
var require_keyboard = __commonJS({
  "node_modules/grammy/out/convenience/keyboard.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.InlineKeyboard = exports2.Keyboard = void 0;
    var Keyboard = class _Keyboard {
      static {
        __name(this, "Keyboard");
      }
      /**
       * Initialize a new `Keyboard` with an optional two-dimensional array of
       * `KeyboardButton` objects. This is the nested array that holds the custom
       * keyboard. It will be extended every time you call one of the provided
       * methods.
       *
       * @param keyboard An optional initial two-dimensional button array
       */
      constructor(keyboard = [[]]) {
        this.keyboard = keyboard;
      }
      /**
       * Allows you to add your own `KeyboardButton` objects if you already have
       * them for some reason. You most likely want to call one of the other
       * methods.
       *
       * @param buttons The buttons to add
       */
      add(...buttons) {
        var _a7;
        (_a7 = this.keyboard[this.keyboard.length - 1]) === null || _a7 === void 0 ? void 0 : _a7.push(...buttons);
        return this;
      }
      /**
       * Adds a 'line break'. Call this method to make sure that the next added
       * buttons will be on a new row.
       *
       * You may pass a number of `KeyboardButton` objects if you already have the
       * instances for some reason. You most likely don't want to pass any
       * arguments to `row`.
       *
       * @param buttons A number of buttons to add to the next row
       */
      row(...buttons) {
        this.keyboard.push(buttons);
        return this;
      }
      /**
       * Adds a new text button. This button will simply send the given text as a
       * text message back to your bot if a user clicks on it.
       *
       * @param text The text to display, and optional styling information
       * @param options Optional styling information
       */
      text(text, options2) {
        return this.add(_Keyboard.text(text, options2));
      }
      /**
       * Creates a new text button. This button will simply send the given text as
       * a text message back to your bot if a user clicks on it.
       *
       * @param text The text to display, and optional styling information
       * @param options Optional styling information
       */
      static text(text, options2) {
        return typeof options2 === "string" ? { text, style: options2 } : { text, ...options2 };
      }
      /**
       * Adds a new request users button. When the user presses the button, a list
       * of suitable users will be opened. Tapping on any number of users will
       * send their identifiers to the bot in a “users_shared” service message.
       * Available in private chats only.
       *
       * @param text The text to display, and optional styling information
       * @param requestId A signed 32-bit identifier of the request
       * @param options Options object for further requirements
       */
      requestUsers(text, requestId, options2 = {}) {
        return this.add(_Keyboard.requestUsers(text, requestId, options2));
      }
      /**
       * Creates a new request users button. When the user presses the button, a
       * list of suitable users will be opened. Tapping on any number of users
       * will send their identifiers to the bot in a “users_shared” service
       * message. Available in private chats only.
       *
       * @param text The text to display, and optional styling information
       * @param requestId A signed 32-bit identifier of the request
       * @param options Options object for further requirements
       */
      static requestUsers(text, requestId, options2 = {}) {
        return typeof text === "string" ? { text, request_users: { request_id: requestId, ...options2 } } : { ...text, request_users: { request_id: requestId, ...options2 } };
      }
      /**
       * Adds a new request chat button. When the user presses the button, a list
       * of suitable users will be opened. Tapping on a chat will send its
       * identifier to the bot in a “chat_shared” service message. Available in
       * private chats only.
       *
       * @param text The text to display, and optional styling information
       * @param requestId A signed 32-bit identifier of the request
       * @param options Options object for further requirements
       */
      requestChat(text, requestId, options2 = {
        chat_is_channel: false
      }) {
        return this.add(_Keyboard.requestChat(text, requestId, options2));
      }
      /**
       * Creates a new request chat button. When the user presses the button, a
       * list of suitable users will be opened. Tapping on a chat will send its
       * identifier to the bot in a “chat_shared” service message. Available in
       * private chats only.
       *
       * @param text The text to display, and optional styling information
       * @param requestId A signed 32-bit identifier of the request
       * @param options Options object for further requirements
       */
      static requestChat(text, requestId, options2 = {
        chat_is_channel: false
      }) {
        const request_chat = { request_id: requestId, ...options2 };
        return typeof text === "string" ? { text, request_chat } : { ...text, request_chat };
      }
      /**
       * Adds a new contact request button. The user's phone number will be sent
       * as a contact when the button is pressed. Available in private chats only.
       *
       * @param text The text to display, and optional styling information
       */
      requestContact(text) {
        return this.add(_Keyboard.requestContact(text));
      }
      /**
       * Creates a new contact request button. The user's phone number will be
       * sent as a contact when the button is pressed. Available in private chats
       * only.
       *
       * @param text The text to display, and optional styling information
       */
      static requestContact(text) {
        const request_contact = true;
        return typeof text === "string" ? { text, request_contact } : { ...text, request_contact };
      }
      /**
       * Adds a new location request button. The user's current location will be
       * sent when the button is pressed. Available in private chats only.
       *
       * @param text The text to display, and optional styling information
       */
      requestLocation(text) {
        return this.add(_Keyboard.requestLocation(text));
      }
      /**
       * Creates a new location request button. The user's current location will
       * be sent when the button is pressed. Available in private chats only.
       *
       * @param text The text to display, and optional styling information
       */
      static requestLocation(text) {
        const request_location = true;
        return typeof text === "string" ? { text, request_location } : { ...text, request_location };
      }
      /**
       * Adds a new poll request button. The user will be asked to create a poll
       * and send it to the bot when the button is pressed. Available in private
       * chats only.
       *
       * @param text The text to display, and optional styling information
       * @param type The type of permitted polls to create, omit if the user may
       * send a poll of any type
       */
      requestPoll(text, type) {
        return this.add(_Keyboard.requestPoll(text, type));
      }
      /**
       * Creates a new poll request button. The user will be asked to create a
       * poll and send it to the bot when the button is pressed. Available in
       * private chats only.
       *
       * @param text The text to display, and optional styling information
       * @param type The type of permitted polls to create, omit if the user may
       * send a poll of any type
       */
      static requestPoll(text, type) {
        const request_poll = { type };
        return typeof text === "string" ? { text, request_poll } : { ...text, request_poll };
      }
      /**
       * Adds a new web app button. The Web App that will be launched when the
       * user presses the button. The Web App will be able to send a
       * “web_app_data” service message. Available in private chats only.
       *
       * @param text The text to display, and optional styling information
       * @param url An HTTPS URL of a Web App to be opened with additional data
       */
      webApp(text, url3) {
        return this.add(_Keyboard.webApp(text, url3));
      }
      /**
       * Creates a new web app button. The Web App that will be launched when the
       * user presses the button. The Web App will be able to send a
       * “web_app_data” service message. Available in private chats only.
       *
       * @param text The text to display, and optional styling information
       * @param url An HTTPS URL of a Web App to be opened with additional data
       */
      static webApp(text, url3) {
        const web_app = { url: url3 };
        return typeof text === "string" ? { text, web_app } : { ...text, web_app };
      }
      /**
       * Adds a style to the last added button of the keyboard.
       *
       * ```ts
       * const keyboard = new Keyboard()
       *   .text('blue button')
       *   .style('primary')
       * ```
       *
       * @param style Style of the button
       */
      style(style) {
        const rows = this.keyboard.length;
        if (rows === 0) {
          throw new Error("Need to add a button before applying a style!");
        }
        const lastRow = this.keyboard[rows - 1];
        const cols = lastRow.length;
        if (cols === 0) {
          throw new Error("Need to add a button before applying a style!");
        }
        let lastButton = lastRow[cols - 1];
        if (typeof lastButton === "string") {
          lastButton = { text: lastButton };
          lastRow[cols - 1] = lastButton;
        }
        lastButton.style = style;
        return this;
      }
      /**
       * Adds a danger style to the last added button of the keyboard. Alias for
       * `.style('danger')`.
       *
       * ```ts
       * const keyboard = new Keyboard()
       *   .text('red button')
       *   .danger()
       * ```
       */
      danger() {
        return this.style("danger");
      }
      /**
       * Adds a success style to the last added button of the keyboard. Alias for
       * `.style('success')`.
       *
       * ```ts
       * const keyboard = new Keyboard()
       *   .text('green button')
       *   .success()
       * ```
       */
      success() {
        return this.style("success");
      }
      /**
       * Adds a primary style to the last added button of the keyboard. Alias for
       * `.style('primary')`.
       *
       * ```ts
       * const keyboard = new Keyboard()
       *   .text('blue button')
       *   .primary()
       * ```
       */
      primary() {
        return this.style("primary");
      }
      /**
       * Adds a custom emoji icon to the last added button of the keyboard.
       *
       * ```ts
       * const keyboard = new Keyboard()
       *   .text('button with icon')
       *   .icon(myCustomEmojiIconIdentifier)
       * ```
       *
       * @param icon Unique identifier of the custom emoji shown before the text of the button
       */
      icon(icon) {
        const rows = this.keyboard.length;
        if (rows === 0) {
          throw new Error("Need to add a button before adding an icon!");
        }
        const lastRow = this.keyboard[rows - 1];
        const cols = lastRow.length;
        if (cols === 0) {
          throw new Error("Need to add a button before adding an icon!");
        }
        let lastButton = lastRow[cols - 1];
        if (typeof lastButton === "string") {
          lastButton = { text: lastButton };
          lastRow[cols - 1] = lastButton;
        }
        lastButton.icon_custom_emoji_id = icon;
        return this;
      }
      /**
       * Make the current keyboard persistent. See
       * https://grammy.dev/plugins/keyboard#persistent-keyboards for more
       * details.
       *
       * Keyboards are not persistent by default, use this function to enable it
       * (without any parameters or pass `true`). Pass `false` to force the
       * keyboard to not persist.
       *
       * @param isEnabled `true` if the keyboard should persist, and `false` otherwise
       */
      persistent(isEnabled2 = true) {
        this.is_persistent = isEnabled2;
        return this;
      }
      /**
       * Make the current keyboard selective. See
       * https://grammy.dev/plugins/keyboard#selectively-send-custom-keyboards
       * for more details.
       *
       * Keyboards are non-selective by default, use this function to enable it
       * (without any parameters or pass `true`). Pass `false` to force the
       * keyboard to be non-selective.
       *
       * @param isEnabled `true` if the keyboard should be selective, and `false` otherwise
       */
      selected(isEnabled2 = true) {
        this.selective = isEnabled2;
        return this;
      }
      /**
       * Make the current keyboard one-time. See
       * https://grammy.dev/plugins/keyboard#one-time-custom-keyboards for
       * more details.
       *
       * Keyboards are non-one-time by default, use this function to enable it
       * (without any parameters or pass `true`). Pass `false` to force the
       * keyboard to be non-one-time.
       *
       * @param isEnabled `true` if the keyboard should be one-time, and `false` otherwise
       */
      oneTime(isEnabled2 = true) {
        this.one_time_keyboard = isEnabled2;
        return this;
      }
      /**
       * Make the current keyboard resized. See
       * https://grammy.dev/plugins/keyboard#resize-custom-keyboard for more
       * details.
       *
       * Keyboards are non-resized by default, use this function to enable it
       * (without any parameters or pass `true`). Pass `false` to force the
       * keyboard to be non-resized.
       *
       * @param isEnabled `true` if the keyboard should be resized, and `false` otherwise
       */
      resized(isEnabled2 = true) {
        this.resize_keyboard = isEnabled2;
        return this;
      }
      /**
       * Set the current keyboard's input field placeholder. See
       * https://grammy.dev/plugins/keyboard#input-field-placeholder for more
       * details.
       *
       * @param value The placeholder text
       */
      placeholder(value) {
        this.input_field_placeholder = value;
        return this;
      }
      /**
       * Creates a new keyboard that contains the transposed grid of buttons of
       * this keyboard. This means that the resulting keyboard has the rows and
       * columns flipped.
       *
       * Note that buttons can only span multiple columns, but never multiple
       * rows. This means that if the given arrays have different lengths, some
       * buttons might flow up in the layout. In these cases, transposing a
       * keyboard a second time will not undo the first transposition.
       *
       * Here are some examples.
       *
       * ```
       * original    transposed
       * [  a  ]  ~> [  a  ]
       *
       *             [  a  ]
       * [a b c]  ~> [  b  ]
       *             [  c  ]
       *
       * [ a b ]     [a c e]
       * [ c d ]  ~> [ b d ]
       * [  e  ]
       *
       * [ a b ]     [a c d]
       * [  c  ]  ~> [ b e ]
       * [d e f]     [  f  ]
       * ```
       */
      toTransposed() {
        const original = this.keyboard;
        const transposed = transpose(original);
        return this.clone(transposed);
      }
      /**
       * Creates a new keyboard with the same buttons but reflowed into a given
       * number of columns as if the buttons were text elements. Optionally, you
       * can specify if the flow should make sure to fill up the last row.
       *
       * This method is idempotent, so calling it a second time will effectively
       * clone this keyboard without reordering the buttons.
       *
       * Here are some examples.
       *
       * ```
       * original    flowed
       * [  a  ]  ~> [  a  ]    (4 columns)
       *
       *             [  a  ]
       * [a b c]  ~> [  b  ]    (1 column)
       *             [  c  ]
       *
       * [ a b ]     [a b c]
       * [ c d ]  ~> [ d e ]    (3 columns)
       * [  e  ]
       *
       * [ a b ]     [abcde]
       * [  c  ]  ~> [  f  ]    (5 columns)
       * [d e f]
       *
       * [a b c]     [  a  ]
       * [d e f]  ~> [b c d]    (3 columns, { fillLastRow: true })
       * [g h i]     [e f g]
       * [  j  ]     [h i j]
       * ```
       *
       * @param columns Maximum number of buttons per row
       * @param options Optional flowing behavior
       */
      toFlowed(columns, options2 = {}) {
        const original = this.keyboard;
        const flowed = reflow(original, columns, options2);
        return this.clone(flowed);
      }
      /**
       * Creates and returns a deep copy of this keyboard.
       *
       * Optionally takes a new grid of buttons to replace the current buttons. If
       * specified, only the options will be cloned, and the given buttons will be
       * used instead.
       */
      clone(keyboard = this.keyboard) {
        const clone4 = new _Keyboard(keyboard.map((row) => row.slice()));
        clone4.is_persistent = this.is_persistent;
        clone4.selective = this.selective;
        clone4.one_time_keyboard = this.one_time_keyboard;
        clone4.resize_keyboard = this.resize_keyboard;
        clone4.input_field_placeholder = this.input_field_placeholder;
        return clone4;
      }
      /**
       * Appends the buttons of the given keyboards to this keyboard. If other
       * options are specified in these keyboards, they will be ignored.
       *
       * @param sources A number of keyboards to append
       */
      append(...sources) {
        for (const source2 of sources) {
          const keyboard = _Keyboard.from(source2);
          this.keyboard.push(...keyboard.keyboard.map((row) => row.slice()));
        }
        return this;
      }
      /**
       * Returns the keyboard that was build. Note that it doesn't return
       * `resize_keyboard` or other options that may be set. You don't usually
       * need to call this method. It is no longer useful.
       */
      build() {
        return this.keyboard;
      }
      /**
       * Turns a two-dimensional keyboard button array into a keyboard instance.
       * You can use the static button builder methods to create keyboard button
       * objects.
       *
       * @param source A two-dimensional button array
       */
      static from(source2) {
        if (source2 instanceof _Keyboard)
          return source2.clone();
        function toButton(btn) {
          return typeof btn === "string" ? _Keyboard.text(btn) : btn;
        }
        __name(toButton, "toButton");
        return new _Keyboard(source2.map((row) => row.map(toButton)));
      }
    };
    exports2.Keyboard = Keyboard;
    var InlineKeyboard = class _InlineKeyboard {
      static {
        __name(this, "InlineKeyboard");
      }
      /**
       * Initialize a new `InlineKeyboard` with an optional two-dimensional array
       * of `InlineKeyboardButton` objects. This is the nested array that holds
       * the inline keyboard. It will be extended every time you call one of the
       * provided methods.
       *
       * @param inline_keyboard An optional initial two-dimensional button array
       */
      constructor(inline_keyboard = [[]]) {
        this.inline_keyboard = inline_keyboard;
      }
      /**
       * Allows you to add your own `InlineKeyboardButton` objects if you already
       * have them for some reason. You most likely want to call one of the other
       * methods.
       *
       * @param buttons The buttons to add
       */
      add(...buttons) {
        var _a7;
        (_a7 = this.inline_keyboard[this.inline_keyboard.length - 1]) === null || _a7 === void 0 ? void 0 : _a7.push(...buttons);
        return this;
      }
      /**
       * Adds a 'line break'. Call this method to make sure that the next added
       * buttons will be on a new row.
       *
       * You may pass a number of `InlineKeyboardButton` objects if you already
       * have the instances for some reason. You most likely don't want to pass
       * any arguments to `row`.
       *
       * @param buttons A number of buttons to add to the next row
       */
      row(...buttons) {
        this.inline_keyboard.push(buttons);
        return this;
      }
      /**
       * Adds a new URL button. Telegram clients will open the provided URL when
       * the button is pressed.
       *
       * @param text The text to display, and optional styling information
       * @param url HTTP or tg:// url to be opened when the button is pressed. Links tg://user?id=<user_id> can be used to mention a user by their ID without using a username, if this is allowed by their privacy settings.
       */
      url(text, url3) {
        return this.add(_InlineKeyboard.url(text, url3));
      }
      /**
       * Creates a new URL button. Telegram clients will open the provided URL
       * when the button is pressed.
       *
       * @param text The text to display, and optional styling information
       * @param url HTTP or tg:// url to be opened when the button is pressed. Links tg://user?id=<user_id> can be used to mention a user by their ID without using a username, if this is allowed by their privacy settings.
       */
      static url(text, url3) {
        return typeof text === "string" ? { text, url: url3 } : { ...text, url: url3 };
      }
      /**
       * Adds a new callback query button. The button contains a text and a custom
       * payload. This payload will be sent back to your bot when the button is
       * pressed. If you omit the payload, the display text will be sent back to
       * your bot.
       *
       * Your bot will receive an update every time a user presses any of the text
       * buttons. You can listen to these updates like this:
       * ```ts
       * // Specific buttons:
       * bot.callbackQuery('button-data', ctx => { ... })
       * // Any button of any inline keyboard:
       * bot.on('callback_query:data',    ctx => { ... })
       * ```
       *
       * @param text The text to display, and optional styling information
       * @param data The callback data to send back to your bot (default = text)
       */
      text(text, data = typeof text === "string" ? text : text.text) {
        return this.add(_InlineKeyboard.text(text, data));
      }
      /**
       * Creates a new callback query button. The button contains a text and a
       * custom payload. This payload will be sent back to your bot when the
       * button is pressed. If you omit the payload, the display text will be sent
       * back to your bot.
       *
       * Your bot will receive an update every time a user presses any of the text
       * buttons. You can listen to these updates like this:
       * ```ts
       * // Specific buttons:
       * bot.callbackQuery('button-data', ctx => { ... })
       * // Any button of any inline keyboard:
       * bot.on('callback_query:data',    ctx => { ... })
       * ```
       *
       * @param text The text to display, and optional styling information
       * @param data The callback data to send back to your bot (default = text)
       */
      static text(text, data = typeof text === "string" ? text : text.text) {
        return typeof text === "string" ? { text, callback_data: data } : { ...text, callback_data: data };
      }
      /**
       * Adds a new web app button, confer https://core.telegram.org/bots/webapps
       *
       * @param text The text to display, and optional styling information
       * @param url An HTTPS URL of a Web App to be opened with additional data
       */
      webApp(text, url3) {
        return this.add(_InlineKeyboard.webApp(text, url3));
      }
      /**
       * Creates a new web app button, confer https://core.telegram.org/bots/webapps
       *
       * @param text The text to display, and optional styling information
       * @param url An HTTPS URL of a Web App to be opened with additional data
       */
      static webApp(text, url3) {
        const web_app = typeof url3 === "string" ? { url: url3 } : url3;
        return typeof text === "string" ? { text, web_app } : { ...text, web_app };
      }
      /**
       * Adds a new login button. This can be used as a replacement for the
       * Telegram Login Widget. You must specify an HTTPS URL used to
       * automatically authorize the user.
       *
       * @param text The text to display, and optional styling information
       * @param loginUrl The login URL as string or `LoginUrl` object
       */
      login(text, loginUrl) {
        return this.add(_InlineKeyboard.login(text, loginUrl));
      }
      /**
       * Creates a new login button. This can be used as a replacement for the
       * Telegram Login Widget. You must specify an HTTPS URL used to
       * automatically authorize the user.
       *
       * @param text The text to display, and optional styling information
       * @param loginUrl The login URL as string or `LoginUrl` object
       */
      static login(text, loginUrl) {
        const login_url = typeof loginUrl === "string" ? { url: loginUrl } : loginUrl;
        return typeof text === "string" ? { text, login_url } : { ...text, login_url };
      }
      /**
       * Adds a new inline query button. Telegram clients will let the user pick a
       * chat when this button is pressed. This will start an inline query. The
       * selected chat will be prefilled with the name of your bot. You may
       * provide a text that is specified along with it.
       *
       * Your bot will in turn receive updates for inline queries. You can listen
       * to inline query updates like this:
       * ```ts
       * bot.on('inline_query', ctx => { ... })
       * ```
       *
       * @param text The text to display, and optional styling information
       * @param query The (optional) inline query string to prefill
       */
      switchInline(text, query = "") {
        return this.add(_InlineKeyboard.switchInline(text, query));
      }
      /**
       * Creates a new inline query button. Telegram clients will let the user pick a
       * chat when this button is pressed. This will start an inline query. The
       * selected chat will be prefilled with the name of your bot. You may
       * provide a text that is specified along with it.
       *
       * Your bot will in turn receive updates for inline queries. You can listen
       * to inline query updates like this:
       * ```ts
       * bot.on('inline_query', ctx => { ... })
       * ```
       *
       * @param text The text to display, and optional styling information
       * @param query The (optional) inline query string to prefill
       */
      static switchInline(text, query = "") {
        return typeof text === "string" ? { text, switch_inline_query: query } : { ...text, switch_inline_query: query };
      }
      /**
       * Adds a new inline query button that acts on the current chat. The
       * selected chat will be prefilled with the name of your bot. You may
       * provide a text that is specified along with it. This will start an inline
       * query.
       *
       * Your bot will in turn receive updates for inline queries. You can listen
       * to inline query updates like this:
       * ```ts
       * bot.on('inline_query', ctx => { ... })
       * ```
       *
       * @param text The text to display, and optional styling information
       * @param query The (optional) inline query string to prefill
       */
      switchInlineCurrent(text, query = "") {
        return this.add(_InlineKeyboard.switchInlineCurrent(text, query));
      }
      /**
       * Creates a new inline query button that acts on the current chat. The
       * selected chat will be prefilled with the name of your bot. You may
       * provide a text that is specified along with it. This will start an inline
       * query.
       *
       * Your bot will in turn receive updates for inline queries. You can listen
       * to inline query updates like this:
       * ```ts
       * bot.on('inline_query', ctx => { ... })
       * ```
       *
       * @param text The text to display, and optional styling information
       * @param query The (optional) inline query string to prefill
       */
      static switchInlineCurrent(text, query = "") {
        return typeof text === "string" ? { text, switch_inline_query_current_chat: query } : { ...text, switch_inline_query_current_chat: query };
      }
      /**
       * Adds a new inline query button. Telegram clients will let the user pick a
       * chat when this button is pressed. This will start an inline query. The
       * selected chat will be prefilled with the name of your bot. You may
       * provide a text that is specified along with it.
       *
       * Your bot will in turn receive updates for inline queries. You can listen
       * to inline query updates like this:
       * ```ts
       * bot.on('inline_query', ctx => { ... })
       * ```
       *
       * @param text The text to display, and optional styling information
       * @param query The query object describing which chats can be picked
       */
      switchInlineChosen(text, query = {}) {
        return this.add(_InlineKeyboard.switchInlineChosen(text, query));
      }
      /**
       * Creates a new inline query button. Telegram clients will let the user pick a
       * chat when this button is pressed. This will start an inline query. The
       * selected chat will be prefilled with the name of your bot. You may
       * provide a text that is specified along with it.
       *
       * Your bot will in turn receive updates for inline queries. You can listen
       * to inline query updates like this:
       * ```ts
       * bot.on('inline_query', ctx => { ... })
       * ```
       *
       * @param text The text to display, and optional styling information
       * @param query The query object describing which chats can be picked
       */
      static switchInlineChosen(text, query = {}) {
        return typeof text === "string" ? { text, switch_inline_query_chosen_chat: query } : { ...text, switch_inline_query_chosen_chat: query };
      }
      /**
       * Adds a new copy text button. When clicked, the specified text will be
       * copied to the clipboard.
       *
       * @param text The text to display, and optional styling information
       * @param copyText The text to be copied to the clipboard
       */
      copyText(text, copyText) {
        return this.add(_InlineKeyboard.copyText(text, copyText));
      }
      /**
       * Creates a new copy text button. When clicked, the specified text will be
       * copied to the clipboard.
       *
       * @param text The text to display, and optional styling information
       * @param copyText The text to be copied to the clipboard
       */
      static copyText(text, copyText) {
        const copy_text = typeof copyText === "string" ? { text: copyText } : copyText;
        return typeof text === "string" ? { text, copy_text } : { ...text, copy_text };
      }
      /**
       * Adds a new game query button, confer
       * https://core.telegram.org/bots/api#games
       *
       * This type of button must always be the first button in the first row.
       *
       * @param text The text to display, and optional styling information
       */
      game(text) {
        return this.add(_InlineKeyboard.game(text));
      }
      /**
       * Creates a new game query button, confer
       * https://core.telegram.org/bots/api#games
       *
       * This type of button must always be the first button in the first row.
       *
       * @param text The text to display, and optional styling information
       */
      static game(text) {
        const callback_game = {};
        return typeof text === "string" ? { text, callback_game } : { ...text, callback_game };
      }
      /**
       * Adds a new payment button, confer
       * https://core.telegram.org/bots/api#payments
       *
       * This type of button must always be the first button in the first row and
       * can only be used in invoice messages.
       *
       * @param text The text to display, and optional styling information. Substrings “⭐” and “XTR” in the buttons's text will be replaced with a Telegram Star icon.
       */
      pay(text) {
        return this.add(_InlineKeyboard.pay(text));
      }
      /**
       * Create a new payment button, confer
       * https://core.telegram.org/bots/api#payments
       *
       * This type of button must always be the first button in the first row and
       * can only be used in invoice messages.
       *
       * @param text The text to display, and optional styling information. Substrings “⭐” and “XTR” in the buttons's text will be replaced with a Telegram Star icon.
       */
      static pay(text) {
        const pay = true;
        return typeof text === "string" ? { text, pay } : { ...text, pay };
      }
      /**
       * Adds a style to the last added button of the inline keyboard.
       *
       * ```ts
       * const keyboard = new InlineKeyboard()
       *   .text('blue button')
       *   .style('primary')
       * ```
       *
       * @param style Style of the button
       */
      style(style) {
        const rows = this.inline_keyboard.length;
        if (rows === 0) {
          throw new Error("Need to add a button before applying a style!");
        }
        const lastRow = this.inline_keyboard[rows - 1];
        const cols = lastRow.length;
        if (cols === 0) {
          throw new Error("Need to add a button before applying a style!");
        }
        lastRow[cols - 1].style = style;
        return this;
      }
      /**
       * Adds a danger style to the last added button of the inline keyboard.
       * Alias for `.style('danger')`.
       *
       * ```ts
       * const keyboard = new InlineKeyboard()
       *   .text('red button')
       *   .danger()
       * ```
       */
      danger() {
        return this.style("danger");
      }
      /**
       * Adds a success style to the last added button of the inline keyboard.
       * Alias for `.style('success')`.
       *
       * ```ts
       * const keyboard = new InlineKeyboard()
       *   .text('green button')
       *   .success()
       * ```
       */
      success() {
        return this.style("success");
      }
      /**
       * Adds a primary style to the last added button of the inline keyboard.
       * Alias for `.style('primary')`.
       *
       * ```ts
       * const keyboard = new InlineKeyboard()
       *   .text('blue button')
       *   .primary()
       * ```
       */
      primary() {
        return this.style("primary");
      }
      /**
       * Adds a custom emoji icon to the last added button of the inline keyboard.
       *
       * ```ts
       * const keyboard = new InlineKeyboard()
       *   .text('button with icon')
       *   .icon(myCustomEmojiIconIdentifier)
       * ```
       *
       * @param icon Unique identifier of the custom emoji shown before the text of the button
       */
      icon(icon) {
        const rows = this.inline_keyboard.length;
        if (rows === 0) {
          throw new Error("Need to add a button before adding an icon!");
        }
        const lastRow = this.inline_keyboard[rows - 1];
        const cols = lastRow.length;
        if (cols === 0) {
          throw new Error("Need to add a button before adding an icon!");
        }
        lastRow[cols - 1].icon_custom_emoji_id = icon;
        return this;
      }
      /**
       * Creates a new inline keyboard that contains the transposed grid of
       * buttons of this inline keyboard. This means that the resulting inline
       * keyboard has the rows and columns flipped.
       *
       * Note that inline buttons can only span multiple columns, but never
       * multiple rows. This means that if the given arrays have different
       * lengths, some buttons might flow up in the layout. In these cases,
       * transposing an inline keyboard a second time will not undo the first
       * transposition.
       *
       * Here are some examples.
       *
       * ```
       * original    transposed
       * [  a  ]  ~> [  a  ]
       *
       *             [  a  ]
       * [a b c]  ~> [  b  ]
       *             [  c  ]
       *
       * [ a b ]     [a c e]
       * [ c d ]  ~> [ b d ]
       * [  e  ]
       *
       * [ a b ]     [a c d]
       * [  c  ]  ~> [ b e ]
       * [d e f]     [  f  ]
       * ```
       */
      toTransposed() {
        const original = this.inline_keyboard;
        const transposed = transpose(original);
        return new _InlineKeyboard(transposed);
      }
      /**
       * Creates a new inline keyboard with the same buttons but reflowed into a
       * given number of columns as if the buttons were text elements. Optionally,
       * you can specify if the flow should make sure to fill up the last row.
       *
       * This method is idempotent, so calling it a second time will effectively
       * clone this inline keyboard without reordering the buttons.
       *
       * Here are some examples.
       *
       * ```
       * original    flowed
       * [  a  ]  ~> [  a  ]    (4 columns)
       *
       *             [  a  ]
       * [a b c]  ~> [  b  ]    (1 column)
       *             [  c  ]
       *
       * [ a b ]     [a b c]
       * [ c d ]  ~> [ d e ]    (3 columns)
       * [  e  ]
       *
       * [ a b ]     [abcde]
       * [  c  ]  ~> [  f  ]    (5 columns)
       * [d e f]
       *
       * [a b c]     [  a  ]
       * [d e f]  ~> [b c d]    (3 columns, { fillLastRow: true })
       * [g h i]     [e f g]
       * [  j  ]     [h i j]
       * ```
       *
       * @param columns Maximum number of buttons per row
       * @param options Optional flowing behavior
       */
      toFlowed(columns, options2 = {}) {
        const original = this.inline_keyboard;
        const flowed = reflow(original, columns, options2);
        return new _InlineKeyboard(flowed);
      }
      /**
       * Creates and returns a deep copy of this inline keyboard.
       */
      clone() {
        return new _InlineKeyboard(this.inline_keyboard.map((row) => row.slice()));
      }
      /**
       * Appends the buttons of the given inline keyboards to this keyboard.
       *
       * @param sources A number of inline keyboards to append
       */
      append(...sources) {
        for (const source2 of sources) {
          const keyboard = _InlineKeyboard.from(source2);
          this.inline_keyboard.push(...keyboard.inline_keyboard.map((row) => row.slice()));
        }
        return this;
      }
      /**
       * Turns a two-dimensional inline button array into an inline keyboard
       * instance. You can use the static button builder methods to create inline
       * button objects.
       *
       * @param source A two-dimensional inline button array
       */
      static from(source2) {
        if (source2 instanceof _InlineKeyboard)
          return source2.clone();
        return new _InlineKeyboard(source2.map((row) => row.slice()));
      }
    };
    exports2.InlineKeyboard = InlineKeyboard;
    function transpose(grid) {
      var _a7;
      const transposed = [];
      for (let i4 = 0; i4 < grid.length; i4++) {
        const row = grid[i4];
        for (let j2 = 0; j2 < row.length; j2++) {
          const button = row[j2];
          ((_a7 = transposed[j2]) !== null && _a7 !== void 0 ? _a7 : transposed[j2] = []).push(button);
        }
      }
      return transposed;
    }
    __name(transpose, "transpose");
    function reflow(grid, columns, { fillLastRow = false }) {
      var _a7;
      let first2 = columns;
      if (fillLastRow) {
        const buttonCount = grid.map((row) => row.length).reduce((a2, b2) => a2 + b2, 0);
        first2 = buttonCount % columns;
      }
      const reflowed = [];
      for (const row of grid) {
        for (const button of row) {
          const at2 = Math.max(0, reflowed.length - 1);
          const max = at2 === 0 ? first2 : columns;
          let next = (_a7 = reflowed[at2]) !== null && _a7 !== void 0 ? _a7 : reflowed[at2] = [];
          if (next.length === max) {
            next = [];
            reflowed.push(next);
          }
          next.push(button);
        }
      }
      return reflowed;
    }
    __name(reflow, "reflow");
  }
});

// node_modules/grammy/out/convenience/session.js
var require_session = __commonJS({
  "node_modules/grammy/out/convenience/session.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.MemorySessionStorage = void 0;
    exports2.session = session;
    exports2.lazySession = lazySession;
    exports2.enhanceStorage = enhanceStorage;
    var platform_node_js_1 = require_platform_node();
    var debug3 = (0, platform_node_js_1.debug)("grammy:session");
    function session(options2 = {}) {
      return options2.type === "multi" ? strictMultiSession(options2) : strictSingleSession(options2);
    }
    __name(session, "session");
    function strictSingleSession(options2) {
      const { initial, storage, getSessionKey, custom: custom3 } = fillDefaults(options2);
      return async (ctx, next) => {
        const propSession = new PropertySession(storage, ctx, "session", initial);
        const key = await getSessionKey(ctx);
        await propSession.init(key, { custom: custom3, lazy: false });
        await next();
        await propSession.finish();
      };
    }
    __name(strictSingleSession, "strictSingleSession");
    function strictMultiSession(options2) {
      const props = Object.keys(options2).filter((k2) => k2 !== "type");
      const defaults4 = Object.fromEntries(props.map((prop) => [prop, fillDefaults(options2[prop])]));
      return async (ctx, next) => {
        ctx.session = {};
        const propSessions = await Promise.all(props.map(async (prop) => {
          const { initial, storage, getSessionKey, custom: custom3 } = defaults4[prop];
          const s5 = new PropertySession(
            // @ts-expect-error cannot express that the storage works for a concrete prop
            storage,
            ctx.session,
            prop,
            initial
          );
          const key = await getSessionKey(ctx);
          await s5.init(key, { custom: custom3, lazy: false });
          return s5;
        }));
        await next();
        if (ctx.session == null)
          propSessions.forEach((s5) => s5.delete());
        await Promise.all(propSessions.map((s5) => s5.finish()));
      };
    }
    __name(strictMultiSession, "strictMultiSession");
    function lazySession(options2 = {}) {
      if (options2.type !== void 0 && options2.type !== "single") {
        throw new Error("Cannot use lazy multi sessions!");
      }
      const { initial, storage, getSessionKey, custom: custom3 } = fillDefaults(options2);
      return async (ctx, next) => {
        const propSession = new PropertySession(
          // @ts-expect-error suppress promise nature of values
          storage,
          ctx,
          "session",
          initial
        );
        const key = await getSessionKey(ctx);
        await propSession.init(key, { custom: custom3, lazy: true });
        await next();
        await propSession.finish();
      };
    }
    __name(lazySession, "lazySession");
    var PropertySession = class {
      static {
        __name(this, "PropertySession");
      }
      constructor(storage, obj, prop, initial) {
        this.storage = storage;
        this.obj = obj;
        this.prop = prop;
        this.initial = initial;
        this.fetching = false;
        this.read = false;
        this.wrote = false;
      }
      /** Performs a read op and stores the result in `this.value` */
      load() {
        if (this.key === void 0) {
          return;
        }
        if (this.wrote) {
          return;
        }
        if (this.promise === void 0) {
          this.fetching = true;
          this.promise = Promise.resolve(this.storage.read(this.key)).then((val) => {
            var _a7;
            this.fetching = false;
            if (this.wrote) {
              return this.value;
            }
            if (val !== void 0) {
              this.value = val;
              return val;
            }
            val = (_a7 = this.initial) === null || _a7 === void 0 ? void 0 : _a7.call(this);
            if (val !== void 0) {
              this.wrote = true;
              this.value = val;
            }
            return val;
          });
        }
        return this.promise;
      }
      async init(key, opts) {
        this.key = key;
        if (!opts.lazy)
          await this.load();
        Object.defineProperty(this.obj, this.prop, {
          enumerable: true,
          get: /* @__PURE__ */ __name(() => {
            if (key === void 0) {
              const msg = undef("access", opts);
              throw new Error(msg);
            }
            this.read = true;
            if (!opts.lazy || this.wrote)
              return this.value;
            this.load();
            return this.fetching ? this.promise : this.value;
          }, "get"),
          set: /* @__PURE__ */ __name((v2) => {
            if (key === void 0) {
              const msg = undef("assign", opts);
              throw new Error(msg);
            }
            this.wrote = true;
            this.fetching = false;
            this.value = v2;
          }, "set")
        });
      }
      delete() {
        Object.assign(this.obj, { [this.prop]: void 0 });
      }
      async finish() {
        if (this.key !== void 0) {
          if (this.read)
            await this.load();
          if (this.read || this.wrote) {
            const value = await this.value;
            if (value == null)
              await this.storage.delete(this.key);
            else
              await this.storage.write(this.key, value);
          }
        }
      }
    };
    function fillDefaults(opts = {}) {
      let { prefix = "", getSessionKey = defaultGetSessionKey, initial, storage } = opts;
      if (storage == null) {
        debug3("Storing session data in memory, all data will be lost when the bot restarts.");
        storage = new MemorySessionStorage();
      }
      const custom3 = getSessionKey !== defaultGetSessionKey;
      return {
        initial,
        storage,
        getSessionKey: /* @__PURE__ */ __name(async (ctx) => {
          const key = await getSessionKey(ctx);
          return key === void 0 ? void 0 : prefix + key;
        }, "getSessionKey"),
        custom: custom3
      };
    }
    __name(fillDefaults, "fillDefaults");
    function defaultGetSessionKey(ctx) {
      var _a7;
      return (_a7 = ctx.chatId) === null || _a7 === void 0 ? void 0 : _a7.toString();
    }
    __name(defaultGetSessionKey, "defaultGetSessionKey");
    function undef(op, opts) {
      const { lazy: lazy2 = false, custom: custom3 } = opts;
      const reason = custom3 ? "the custom `getSessionKey` function returned undefined for this update" : "this update does not belong to a chat, so the session key is undefined";
      return `Cannot ${op} ${lazy2 ? "lazy " : ""}session data because ${reason}!`;
    }
    __name(undef, "undef");
    function isEnhance(value) {
      return value === void 0 || typeof value === "object" && value !== null && "__d" in value;
    }
    __name(isEnhance, "isEnhance");
    function enhanceStorage(options2) {
      let { storage, millisecondsToLive, migrations } = options2;
      storage = compatStorage(storage);
      if (millisecondsToLive !== void 0) {
        storage = timeoutStorage(storage, millisecondsToLive);
      }
      if (migrations !== void 0) {
        storage = migrationStorage(storage, migrations);
      }
      return wrapStorage(storage);
    }
    __name(enhanceStorage, "enhanceStorage");
    function compatStorage(storage) {
      return {
        read: /* @__PURE__ */ __name(async (k2) => {
          const v2 = await storage.read(k2);
          return isEnhance(v2) ? v2 : { __d: v2 };
        }, "read"),
        write: /* @__PURE__ */ __name((k2, v2) => storage.write(k2, v2), "write"),
        delete: /* @__PURE__ */ __name((k2) => storage.delete(k2), "delete")
      };
    }
    __name(compatStorage, "compatStorage");
    function timeoutStorage(storage, millisecondsToLive) {
      const ttlStorage = {
        read: /* @__PURE__ */ __name(async (k2) => {
          const value = await storage.read(k2);
          if (value === void 0)
            return void 0;
          if (value.e === void 0) {
            await ttlStorage.write(k2, value);
            return value;
          }
          if (value.e < Date.now()) {
            await ttlStorage.delete(k2);
            return void 0;
          }
          return value;
        }, "read"),
        write: /* @__PURE__ */ __name(async (k2, v2) => {
          v2.e = addExpiryDate(v2, millisecondsToLive).expires;
          await storage.write(k2, v2);
        }, "write"),
        delete: /* @__PURE__ */ __name((k2) => storage.delete(k2), "delete")
      };
      return ttlStorage;
    }
    __name(timeoutStorage, "timeoutStorage");
    function migrationStorage(storage, migrations) {
      const versions = Object.keys(migrations).map((v2) => parseInt(v2)).sort((a2, b2) => a2 - b2);
      const count = versions.length;
      if (count === 0)
        throw new Error("No migrations given!");
      const earliest = versions[0];
      const last2 = count - 1;
      const latest = versions[last2];
      const index = /* @__PURE__ */ new Map();
      versions.forEach((v2, i4) => index.set(v2, i4));
      function nextAfter(current) {
        let i4 = last2;
        while (current <= versions[i4])
          i4--;
        return i4;
      }
      __name(nextAfter, "nextAfter");
      return {
        read: /* @__PURE__ */ __name(async (k2) => {
          var _a7;
          const val = await storage.read(k2);
          if (val === void 0)
            return val;
          let { __d: value, v: current = earliest - 1 } = val;
          let i4 = 1 + ((_a7 = index.get(current)) !== null && _a7 !== void 0 ? _a7 : nextAfter(current));
          for (; i4 < count; i4++)
            value = migrations[versions[i4]](value);
          return { ...val, v: latest, __d: value };
        }, "read"),
        write: /* @__PURE__ */ __name((k2, v2) => storage.write(k2, { v: latest, ...v2 }), "write"),
        delete: /* @__PURE__ */ __name((k2) => storage.delete(k2), "delete")
      };
    }
    __name(migrationStorage, "migrationStorage");
    function wrapStorage(storage) {
      return {
        read: /* @__PURE__ */ __name((k2) => Promise.resolve(storage.read(k2)).then((v2) => v2 === null || v2 === void 0 ? void 0 : v2.__d), "read"),
        write: /* @__PURE__ */ __name((k2, v2) => storage.write(k2, { __d: v2 }), "write"),
        delete: /* @__PURE__ */ __name((k2) => storage.delete(k2), "delete")
      };
    }
    __name(wrapStorage, "wrapStorage");
    var MemorySessionStorage = class {
      static {
        __name(this, "MemorySessionStorage");
      }
      /**
       * Constructs a new memory session storage with the given time to live. Note
       * that this storage adapter will not store your data permanently.
       *
       * @param timeToLive TTL in milliseconds, default is `Infinity`
       */
      constructor(timeToLive) {
        this.timeToLive = timeToLive;
        this.storage = /* @__PURE__ */ new Map();
      }
      read(key) {
        const value = this.storage.get(key);
        if (value === void 0)
          return void 0;
        if (value.expires !== void 0 && value.expires < Date.now()) {
          this.delete(key);
          return void 0;
        }
        return value.session;
      }
      /**
       * @deprecated Use {@link readAllValues} instead
       */
      readAll() {
        return this.readAllValues();
      }
      readAllKeys() {
        return Array.from(this.storage.keys());
      }
      readAllValues() {
        return Array.from(this.storage.keys()).map((key) => this.read(key)).filter((value) => value !== void 0);
      }
      readAllEntries() {
        return Array.from(this.storage.keys()).map((key) => [key, this.read(key)]).filter((pair) => pair[1] !== void 0);
      }
      has(key) {
        return this.storage.has(key);
      }
      write(key, value) {
        this.storage.set(key, addExpiryDate(value, this.timeToLive));
      }
      delete(key) {
        this.storage.delete(key);
      }
    };
    exports2.MemorySessionStorage = MemorySessionStorage;
    function addExpiryDate(value, ttl) {
      if (ttl !== void 0 && ttl < Infinity) {
        const now = Date.now();
        return { session: value, expires: now + ttl };
      } else {
        return { session: value };
      }
    }
    __name(addExpiryDate, "addExpiryDate");
  }
});

// node_modules/grammy/out/convenience/frameworks.js
var require_frameworks = __commonJS({
  "node_modules/grammy/out/convenience/frameworks.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.adapters = void 0;
    var SECRET_HEADER = "X-Telegram-Bot-Api-Secret-Token";
    var SECRET_HEADER_LOWERCASE = SECRET_HEADER.toLowerCase();
    var WRONG_TOKEN_ERROR = "secret token is wrong";
    var ok2 = /* @__PURE__ */ __name(() => new Response(null, { status: 200 }), "ok");
    var okJson = /* @__PURE__ */ __name((json3) => new Response(json3, {
      status: 200,
      headers: { "Content-Type": "application/json" }
    }), "okJson");
    var unauthorized = /* @__PURE__ */ __name(() => new Response('"unauthorized"', {
      status: 401,
      statusText: WRONG_TOKEN_ERROR
    }), "unauthorized");
    var awsLambda = /* @__PURE__ */ __name((event, _context, callback) => ({
      get update() {
        var _a7;
        return JSON.parse((_a7 = event.body) !== null && _a7 !== void 0 ? _a7 : "{}");
      },
      header: event.headers[SECRET_HEADER],
      end: /* @__PURE__ */ __name(() => callback(null, { statusCode: 200 }), "end"),
      respond: /* @__PURE__ */ __name((json3) => callback(null, {
        statusCode: 200,
        headers: { "Content-Type": "application/json" },
        body: json3
      }), "respond"),
      unauthorized: /* @__PURE__ */ __name(() => callback(null, { statusCode: 401 }), "unauthorized")
    }), "awsLambda");
    var awsLambdaAsync = /* @__PURE__ */ __name((event, _context) => {
      let resolveResponse;
      return {
        get update() {
          var _a7;
          return JSON.parse((_a7 = event.body) !== null && _a7 !== void 0 ? _a7 : "{}");
        },
        header: event.headers[SECRET_HEADER],
        end: /* @__PURE__ */ __name(() => resolveResponse({ statusCode: 200 }), "end"),
        respond: /* @__PURE__ */ __name((json3) => resolveResponse({
          statusCode: 200,
          headers: { "Content-Type": "application/json" },
          body: json3
        }), "respond"),
        unauthorized: /* @__PURE__ */ __name(() => resolveResponse({ statusCode: 401 }), "unauthorized"),
        handlerReturn: new Promise((res) => resolveResponse = res)
      };
    }, "awsLambdaAsync");
    var azure = /* @__PURE__ */ __name((context2, request4) => {
      var _a7, _b2;
      return {
        get update() {
          return request4.body;
        },
        header: (_b2 = (_a7 = context2.res) === null || _a7 === void 0 ? void 0 : _a7.headers) === null || _b2 === void 0 ? void 0 : _b2[SECRET_HEADER],
        end: /* @__PURE__ */ __name(() => context2.res = {
          status: 200,
          body: ""
        }, "end"),
        respond: /* @__PURE__ */ __name((json3) => {
          var _a8, _b3, _c2, _d;
          (_b3 = (_a8 = context2.res) === null || _a8 === void 0 ? void 0 : _a8.set) === null || _b3 === void 0 ? void 0 : _b3.call(_a8, "Content-Type", "application/json");
          (_d = (_c2 = context2.res) === null || _c2 === void 0 ? void 0 : _c2.send) === null || _d === void 0 ? void 0 : _d.call(_c2, json3);
        }, "respond"),
        unauthorized: /* @__PURE__ */ __name(() => {
          var _a8, _b3;
          (_b3 = (_a8 = context2.res) === null || _a8 === void 0 ? void 0 : _a8.send) === null || _b3 === void 0 ? void 0 : _b3.call(_a8, 401, WRONG_TOKEN_ERROR);
        }, "unauthorized")
      };
    }, "azure");
    var azureV4 = /* @__PURE__ */ __name((request4) => {
      let resolveResponse;
      return {
        get update() {
          return request4.json();
        },
        header: request4.headers.get(SECRET_HEADER) || void 0,
        end: /* @__PURE__ */ __name(() => resolveResponse({ status: 204 }), "end"),
        respond: /* @__PURE__ */ __name((json3) => resolveResponse({ jsonBody: json3 }), "respond"),
        unauthorized: /* @__PURE__ */ __name(() => resolveResponse({ status: 401, body: WRONG_TOKEN_ERROR }), "unauthorized"),
        handlerReturn: new Promise((resolve42) => resolveResponse = resolve42)
      };
    }, "azureV4");
    var bun = /* @__PURE__ */ __name((request4) => {
      let resolveResponse;
      return {
        get update() {
          return request4.json();
        },
        header: request4.headers.get(SECRET_HEADER) || void 0,
        end: /* @__PURE__ */ __name(() => {
          resolveResponse(ok2());
        }, "end"),
        respond: /* @__PURE__ */ __name((json3) => {
          resolveResponse(okJson(json3));
        }, "respond"),
        unauthorized: /* @__PURE__ */ __name(() => {
          resolveResponse(unauthorized());
        }, "unauthorized"),
        handlerReturn: new Promise((res) => resolveResponse = res)
      };
    }, "bun");
    var cloudflare = /* @__PURE__ */ __name((event) => {
      let resolveResponse;
      event.respondWith(new Promise((resolve42) => {
        resolveResponse = resolve42;
      }));
      return {
        get update() {
          return event.request.json();
        },
        header: event.request.headers.get(SECRET_HEADER) || void 0,
        end: /* @__PURE__ */ __name(() => {
          resolveResponse(ok2());
        }, "end"),
        respond: /* @__PURE__ */ __name((json3) => {
          resolveResponse(okJson(json3));
        }, "respond"),
        unauthorized: /* @__PURE__ */ __name(() => {
          resolveResponse(unauthorized());
        }, "unauthorized")
      };
    }, "cloudflare");
    var cloudflareModule = /* @__PURE__ */ __name((request4) => {
      let resolveResponse;
      return {
        get update() {
          return request4.json();
        },
        header: request4.headers.get(SECRET_HEADER) || void 0,
        end: /* @__PURE__ */ __name(() => {
          resolveResponse(ok2());
        }, "end"),
        respond: /* @__PURE__ */ __name((json3) => {
          resolveResponse(okJson(json3));
        }, "respond"),
        unauthorized: /* @__PURE__ */ __name(() => {
          resolveResponse(unauthorized());
        }, "unauthorized"),
        handlerReturn: new Promise((res) => resolveResponse = res)
      };
    }, "cloudflareModule");
    var express = /* @__PURE__ */ __name((req, res) => ({
      get update() {
        return req.body;
      },
      header: req.header(SECRET_HEADER),
      end: /* @__PURE__ */ __name(() => res.end(), "end"),
      respond: /* @__PURE__ */ __name((json3) => {
        res.set("Content-Type", "application/json");
        res.send(json3);
      }, "respond"),
      unauthorized: /* @__PURE__ */ __name(() => {
        res.status(401).send(WRONG_TOKEN_ERROR);
      }, "unauthorized")
    }), "express");
    var fastify = /* @__PURE__ */ __name((request4, reply) => ({
      get update() {
        return request4.body;
      },
      header: request4.headers[SECRET_HEADER_LOWERCASE],
      end: /* @__PURE__ */ __name(() => reply.send(""), "end"),
      respond: /* @__PURE__ */ __name((json3) => reply.headers({ "Content-Type": "application/json" }).send(json3), "respond"),
      unauthorized: /* @__PURE__ */ __name(() => reply.code(401).send(WRONG_TOKEN_ERROR), "unauthorized")
    }), "fastify");
    var hono = /* @__PURE__ */ __name((c4) => {
      let resolveResponse;
      return {
        get update() {
          return c4.req.json();
        },
        header: c4.req.header(SECRET_HEADER),
        end: /* @__PURE__ */ __name(() => {
          resolveResponse(c4.body(""));
        }, "end"),
        respond: /* @__PURE__ */ __name((json3) => {
          resolveResponse(c4.json(json3));
        }, "respond"),
        unauthorized: /* @__PURE__ */ __name(() => {
          c4.status(401);
          resolveResponse(c4.body(""));
        }, "unauthorized"),
        handlerReturn: new Promise((res) => resolveResponse = res)
      };
    }, "hono");
    var http9 = /* @__PURE__ */ __name((req, res) => {
      const secretHeaderFromRequest = req.headers[SECRET_HEADER_LOWERCASE];
      return {
        get update() {
          return new Promise((resolve42, reject) => {
            const chunks = [];
            req.on("data", (chunk) => chunks.push(chunk)).once("end", () => {
              const raw2 = Buffer.concat(chunks).toString("utf-8");
              try {
                resolve42(JSON.parse(raw2));
              } catch (err2) {
                reject(err2);
              }
            }).once("error", reject);
          });
        },
        header: Array.isArray(secretHeaderFromRequest) ? secretHeaderFromRequest[0] : secretHeaderFromRequest,
        end: /* @__PURE__ */ __name(() => res.end(), "end"),
        respond: /* @__PURE__ */ __name((json3) => res.writeHead(200, { "Content-Type": "application/json" }).end(json3), "respond"),
        unauthorized: /* @__PURE__ */ __name(() => res.writeHead(401).end(WRONG_TOKEN_ERROR), "unauthorized")
      };
    }, "http");
    var koa = /* @__PURE__ */ __name((ctx) => ({
      get update() {
        return ctx.request.body;
      },
      header: ctx.get(SECRET_HEADER) || void 0,
      end: /* @__PURE__ */ __name(() => {
        ctx.body = "";
      }, "end"),
      respond: /* @__PURE__ */ __name((json3) => {
        ctx.set("Content-Type", "application/json");
        ctx.response.body = json3;
      }, "respond"),
      unauthorized: /* @__PURE__ */ __name(() => {
        ctx.status = 401;
      }, "unauthorized")
    }), "koa");
    var nextJs = /* @__PURE__ */ __name((request4, response) => ({
      get update() {
        return request4.body;
      },
      header: request4.headers[SECRET_HEADER_LOWERCASE],
      end: /* @__PURE__ */ __name(() => response.end(), "end"),
      respond: /* @__PURE__ */ __name((json3) => response.status(200).json(json3), "respond"),
      unauthorized: /* @__PURE__ */ __name(() => response.status(401).send(WRONG_TOKEN_ERROR), "unauthorized")
    }), "nextJs");
    var nhttp = /* @__PURE__ */ __name((rev) => ({
      get update() {
        return rev.body;
      },
      header: rev.headers.get(SECRET_HEADER) || void 0,
      end: /* @__PURE__ */ __name(() => rev.response.sendStatus(200), "end"),
      respond: /* @__PURE__ */ __name((json3) => rev.response.status(200).send(json3), "respond"),
      unauthorized: /* @__PURE__ */ __name(() => rev.response.status(401).send(WRONG_TOKEN_ERROR), "unauthorized")
    }), "nhttp");
    var oak = /* @__PURE__ */ __name((ctx) => ({
      get update() {
        return ctx.request.body.json();
      },
      header: ctx.request.headers.get(SECRET_HEADER) || void 0,
      end: /* @__PURE__ */ __name(() => {
        ctx.response.status = 200;
      }, "end"),
      respond: /* @__PURE__ */ __name((json3) => {
        ctx.response.type = "json";
        ctx.response.body = json3;
      }, "respond"),
      unauthorized: /* @__PURE__ */ __name(() => {
        ctx.response.status = 401;
      }, "unauthorized")
    }), "oak");
    var serveHttp = /* @__PURE__ */ __name((requestEvent) => ({
      get update() {
        return requestEvent.request.json();
      },
      header: requestEvent.request.headers.get(SECRET_HEADER) || void 0,
      end: /* @__PURE__ */ __name(() => requestEvent.respondWith(ok2()), "end"),
      respond: /* @__PURE__ */ __name((json3) => requestEvent.respondWith(okJson(json3)), "respond"),
      unauthorized: /* @__PURE__ */ __name(() => requestEvent.respondWith(unauthorized()), "unauthorized")
    }), "serveHttp");
    var stdHttp = /* @__PURE__ */ __name((req) => {
      let resolveResponse;
      return {
        get update() {
          return req.json();
        },
        header: req.headers.get(SECRET_HEADER) || void 0,
        end: /* @__PURE__ */ __name(() => {
          if (resolveResponse)
            resolveResponse(ok2());
        }, "end"),
        respond: /* @__PURE__ */ __name((json3) => {
          if (resolveResponse)
            resolveResponse(okJson(json3));
        }, "respond"),
        unauthorized: /* @__PURE__ */ __name(() => {
          if (resolveResponse)
            resolveResponse(unauthorized());
        }, "unauthorized"),
        handlerReturn: new Promise((res) => resolveResponse = res)
      };
    }, "stdHttp");
    var sveltekit = /* @__PURE__ */ __name(({ request: request4 }) => {
      let resolveResponse;
      return {
        get update() {
          return request4.json();
        },
        header: request4.headers.get(SECRET_HEADER) || void 0,
        end: /* @__PURE__ */ __name(() => {
          if (resolveResponse)
            resolveResponse(ok2());
        }, "end"),
        respond: /* @__PURE__ */ __name((json3) => {
          if (resolveResponse)
            resolveResponse(okJson(json3));
        }, "respond"),
        unauthorized: /* @__PURE__ */ __name(() => {
          if (resolveResponse)
            resolveResponse(unauthorized());
        }, "unauthorized"),
        handlerReturn: new Promise((res) => resolveResponse = res)
      };
    }, "sveltekit");
    var worktop = /* @__PURE__ */ __name((req, res) => {
      var _a7;
      return {
        get update() {
          return req.json();
        },
        header: (_a7 = req.headers.get(SECRET_HEADER)) !== null && _a7 !== void 0 ? _a7 : void 0,
        end: /* @__PURE__ */ __name(() => res.end(null), "end"),
        respond: /* @__PURE__ */ __name((json3) => res.send(200, json3), "respond"),
        unauthorized: /* @__PURE__ */ __name(() => res.send(401, WRONG_TOKEN_ERROR), "unauthorized")
      };
    }, "worktop");
    var elysia = /* @__PURE__ */ __name((ctx) => {
      let resolveResponse;
      return {
        // @note technically the type shouldn't be limited to Promise, because it's fine to await plain values as well
        get update() {
          return ctx.body;
        },
        header: ctx.headers[SECRET_HEADER_LOWERCASE],
        end() {
          resolveResponse("");
        },
        respond(json3) {
          ctx.set.headers["content-type"] = "application/json";
          resolveResponse(json3);
        },
        unauthorized() {
          ctx.set.status = 401;
          resolveResponse("");
        },
        handlerReturn: new Promise((res) => resolveResponse = res)
      };
    }, "elysia");
    exports2.adapters = {
      "aws-lambda": awsLambda,
      "aws-lambda-async": awsLambdaAsync,
      azure,
      "azure-v4": azureV4,
      bun,
      cloudflare,
      "cloudflare-mod": cloudflareModule,
      elysia,
      express,
      fastify,
      hono,
      http: http9,
      https: http9,
      koa,
      "next-js": nextJs,
      nhttp,
      oak,
      serveHttp,
      "std/http": stdHttp,
      sveltekit,
      worktop
    };
  }
});

// node_modules/grammy/out/convenience/webhook.js
var require_webhook = __commonJS({
  "node_modules/grammy/out/convenience/webhook.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.webhookCallback = webhookCallback;
    var platform_node_js_1 = require_platform_node();
    var frameworks_js_1 = require_frameworks();
    var debugErr = (0, platform_node_js_1.debug)("grammy:error");
    var callbackAdapter = /* @__PURE__ */ __name((update2, callback, header, unauthorized = () => callback('"unauthorized"')) => ({
      update: Promise.resolve(update2),
      respond: callback,
      header,
      unauthorized
    }), "callbackAdapter");
    var adapters = { ...frameworks_js_1.adapters, callback: callbackAdapter };
    function compareSecretToken(header, token2) {
      if (token2 === void 0) {
        return true;
      }
      if (header === void 0) {
        return false;
      }
      const encoder = new TextEncoder();
      const headerBytes = encoder.encode(header);
      const tokenBytes = encoder.encode(token2);
      if (headerBytes.length !== tokenBytes.length) {
        return false;
      }
      let hasDifference = 0;
      for (let i4 = 0; i4 < tokenBytes.length; i4++) {
        const headerByte = i4 < headerBytes.length ? headerBytes[i4] : 0;
        const tokenByte = tokenBytes[i4];
        hasDifference |= headerByte ^ tokenByte;
      }
      return hasDifference === 0;
    }
    __name(compareSecretToken, "compareSecretToken");
    function webhookCallback(bot, adapter2 = platform_node_js_1.defaultAdapter, onTimeout, timeoutMilliseconds, secretToken) {
      if (bot.isRunning()) {
        throw new Error("Bot is already running via long polling, the webhook setup won't receive any updates!");
      } else {
        bot.start = () => {
          throw new Error("You already started the bot via webhooks, calling `bot.start()` starts the bot with long polling and this will prevent your webhook setup from receiving any updates!");
        };
      }
      const { onTimeout: timeout2 = "throw", timeoutMilliseconds: ms = 1e4, secretToken: token2 } = typeof onTimeout === "object" ? onTimeout : { onTimeout, timeoutMilliseconds, secretToken };
      let initialized = false;
      const server = typeof adapter2 === "string" ? adapters[adapter2] : adapter2;
      return async (...args2) => {
        var _a7;
        const handler = server(...args2);
        if (!initialized) {
          await bot.init();
          initialized = true;
        }
        if (!compareSecretToken(handler.header, token2)) {
          await handler.unauthorized();
          return handler.handlerReturn;
        }
        let usedWebhookReply = false;
        const webhookReplyEnvelope = {
          async send(json3) {
            usedWebhookReply = true;
            await handler.respond(json3);
          }
        };
        await timeoutIfNecessary(bot.handleUpdate(await handler.update, webhookReplyEnvelope), typeof timeout2 === "function" ? () => timeout2(...args2) : timeout2, ms);
        if (!usedWebhookReply)
          (_a7 = handler.end) === null || _a7 === void 0 ? void 0 : _a7.call(handler);
        return handler.handlerReturn;
      };
    }
    __name(webhookCallback, "webhookCallback");
    function timeoutIfNecessary(task, onTimeout, timeout2) {
      if (timeout2 === Infinity)
        return task;
      return new Promise((resolve42, reject) => {
        const handle2 = setTimeout(() => {
          debugErr(`Request timed out after ${timeout2} ms`);
          if (onTimeout === "throw") {
            reject(new Error(`Request timed out after ${timeout2} ms`));
          } else {
            if (typeof onTimeout === "function")
              onTimeout();
            resolve42();
          }
          const now = Date.now();
          task.finally(() => {
            const diff4 = Date.now() - now;
            debugErr(`Request completed ${diff4} ms after timeout!`);
          });
        }, timeout2);
        task.then(resolve42).catch(reject).finally(() => clearTimeout(handle2));
      });
    }
    __name(timeoutIfNecessary, "timeoutIfNecessary");
  }
});

// node_modules/grammy/out/mod.js
var require_mod2 = __commonJS({
  "node_modules/grammy/out/mod.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.HttpError = exports2.GrammyError = exports2.Api = exports2.matchFilter = exports2.Composer = exports2.Context = exports2.InputFile = exports2.BotError = exports2.Bot = void 0;
    var bot_js_1 = require_bot();
    Object.defineProperty(exports2, "Bot", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return bot_js_1.Bot;
    }, "get") });
    Object.defineProperty(exports2, "BotError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return bot_js_1.BotError;
    }, "get") });
    var types_js_1 = require_types10();
    Object.defineProperty(exports2, "InputFile", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return types_js_1.InputFile;
    }, "get") });
    var context_js_1 = require_context();
    Object.defineProperty(exports2, "Context", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return context_js_1.Context;
    }, "get") });
    __exportStar(require_constants19(), exports2);
    __exportStar(require_inline_query(), exports2);
    __exportStar(require_input_media(), exports2);
    __exportStar(require_keyboard(), exports2);
    __exportStar(require_session(), exports2);
    __exportStar(require_webhook(), exports2);
    var composer_js_1 = require_composer2();
    Object.defineProperty(exports2, "Composer", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return composer_js_1.Composer;
    }, "get") });
    var filter_js_1 = require_filter2();
    Object.defineProperty(exports2, "matchFilter", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return filter_js_1.matchFilter;
    }, "get") });
    var api_js_1 = require_api4();
    Object.defineProperty(exports2, "Api", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return api_js_1.Api;
    }, "get") });
    var error_js_1 = require_error3();
    Object.defineProperty(exports2, "GrammyError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return error_js_1.GrammyError;
    }, "get") });
    Object.defineProperty(exports2, "HttpError", { enumerable: true, get: /* @__PURE__ */ __name(function() {
      return error_js_1.HttpError;
    }, "get") });
  }
});

// node_modules/telegram-markdown-formatter/dist/lib/converters.js
function convertHtmlChars(text) {
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
}
function splitByTag(outText, mdTag, htmlTag) {
  const tagPattern = new RegExp(String.raw`(?<!\w)${escapeRegExp(mdTag)}(.*?)${escapeRegExp(mdTag)}(?!\w)`, "gs");
  if (htmlTag === 'span class="tg-spoiler"') {
    return outText.replace(tagPattern, '<span class="tg-spoiler">$1</span>');
  }
  return outText.replace(tagPattern, `<${htmlTag}>$1</${htmlTag}>`);
}
function escapeRegExp(s5) {
  return s5.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var init_converters = __esm({
  "node_modules/telegram-markdown-formatter/dist/lib/converters.js"() {
    init_esbuild_shims();
    __name(convertHtmlChars, "convertHtmlChars");
    __name(splitByTag, "splitByTag");
    __name(escapeRegExp, "escapeRegExp");
  }
});

// node_modules/telegram-markdown-formatter/dist/lib/extractors.js
function ensureClosingDelimiters(text) {
  const cleaned = text.replace(CODE_BLOCK_RE, "");
  const stack = [];
  for (const line of cleaned.split(/\r?\n/)) {
    const m3 = line.trim().match(/^(?<fence>`{3,})(?<lang>\w+)?$/);
    if (!m3 || !m3.groups)
      continue;
    const fence = m3.groups["fence"];
    if (stack.length && fence === stack[stack.length - 1])
      stack.pop();
    else
      stack.push(fence);
  }
  let out2 = text;
  if (stack.length)
    out2 += "\n" + stack[stack.length - 1];
  let cleanedInline = out2.replace(CODE_BLOCK_RE, "");
  if ((cleanedInline.match(/```/g) || []).length % 2 !== 0)
    out2 += "```";
  cleanedInline = out2.replace(CODE_BLOCK_RE, "");
  if ((cleanedInline.match(/`/g) || []).length % 2 !== 0)
    out2 += "`";
  return out2;
}
function extractAndConvertCodeBlocks(text) {
  const ensured = ensureClosingDelimiters(text);
  const placeholders = [];
  const codeBlocks = {};
  const codeBlockPattern = /(`{3,})(\w+)?\r?\n?([\s\S]*?)(\r?\n?)\1/gs;
  let modifiedText = ensured;
  for (const match2 of ensured.matchAll(codeBlockPattern)) {
    const language = (match2[2] || "").trim();
    const codeContent = (match2[3] || "") + (match2[4] || "");
    const escaped = codeContent.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
    const placeholder = `CODEBLOCKPLACEHOLDER${placeholders.length}`;
    placeholders.push(placeholder);
    const html2 = language ? `<pre><code class="language-${language}">${escaped}</code></pre>` : `<pre><code>${escaped}</code></pre>`;
    codeBlocks[placeholder] = html2;
    modifiedText = modifiedText.replace(match2[0], placeholder);
  }
  return { modifiedText, codeBlocks };
}
function reinsertCodeBlocks(text, codeBlocks) {
  let out2 = text;
  for (const [ph, html2] of Object.entries(codeBlocks)) {
    out2 = out2.replace(ph, html2);
  }
  return out2;
}
function extractInlineCodeSnippets(text) {
  const inlineSnippets = {};
  let counter = 0;
  const modifiedText = text.replace(/`([^`]+)`/g, (_m, g1) => {
    const placeholder = `INLINECODEPLACEHOLDER${counter++}`;
    inlineSnippets[placeholder] = g1;
    return placeholder;
  });
  return { modifiedText, inlineSnippets };
}
var CODE_BLOCK_RE;
var init_extractors = __esm({
  "node_modules/telegram-markdown-formatter/dist/lib/extractors.js"() {
    init_esbuild_shims();
    CODE_BLOCK_RE = /(`{3,})(\w+)?\r?\n?[\s\S]*?(?:\r?\n)?\1/gs;
    __name(ensureClosingDelimiters, "ensureClosingDelimiters");
    __name(extractAndConvertCodeBlocks, "extractAndConvertCodeBlocks");
    __name(reinsertCodeBlocks, "reinsertCodeBlocks");
    __name(extractInlineCodeSnippets, "extractInlineCodeSnippets");
  }
});

// node_modules/telegram-markdown-formatter/dist/lib/formatters.js
function combineBlockquotes(text) {
  const lines = text.split("\n");
  const combined = [];
  let buf = [];
  let inBlock = false;
  let isExpandable = false;
  for (const line of lines) {
    if (line.startsWith("**>")) {
      inBlock = true;
      isExpandable = true;
      buf.push(line.slice(3).trim());
    } else if (line.startsWith(">")) {
      if (!inBlock) {
        inBlock = true;
        isExpandable = false;
      }
      buf.push(line.slice(1).trim());
    } else {
      if (inBlock) {
        combined.push(isExpandable ? `<blockquote expandable>${buf.join("\n")}</blockquote>` : `<blockquote>${buf.join("\n")}</blockquote>`);
        buf = [];
        inBlock = false;
        isExpandable = false;
      }
      combined.push(line);
    }
  }
  if (inBlock) {
    combined.push(isExpandable ? `<blockquote expandable>${buf.join("\n")}</blockquote>` : `<blockquote>${buf.join("\n")}</blockquote>`);
  }
  return combined.join("\n");
}
var init_formatters2 = __esm({
  "node_modules/telegram-markdown-formatter/dist/lib/formatters.js"() {
    init_esbuild_shims();
    __name(combineBlockquotes, "combineBlockquotes");
  }
});

// node_modules/telegram-markdown-formatter/dist/lib/helpers.js
function removeBlockquoteEscaping(output) {
  let out2 = output.replaceAll("&lt;blockquote&gt;", "<blockquote>").replaceAll("&lt;/blockquote&gt;", "</blockquote>");
  out2 = out2.replaceAll("&lt;blockquote expandable&gt;", "<blockquote expandable>").replaceAll("&lt;/blockquote&gt;", "</blockquote>");
  return out2;
}
function removeSpoilerEscaping(output) {
  return output.replaceAll('&lt;span class="tg-spoiler"&gt;', '<span class="tg-spoiler">').replaceAll("&lt;/span&gt;", "</span>");
}
var init_helpers3 = __esm({
  "node_modules/telegram-markdown-formatter/dist/lib/helpers.js"() {
    init_esbuild_shims();
    __name(removeBlockquoteEscaping, "removeBlockquoteEscaping");
    __name(removeSpoilerEscaping, "removeSpoilerEscaping");
  }
});

// node_modules/telegram-markdown-formatter/dist/lib/telegramFormat.js
function telegramFormat(input) {
  let text = combineBlockquotes(input);
  const { modifiedText, codeBlocks } = extractAndConvertCodeBlocks(text);
  text = modifiedText;
  const inline2 = extractInlineCodeSnippets(text);
  text = inline2.modifiedText;
  text = convertHtmlChars(text);
  text = text.replace(/^(#{1,6})\s+(.+)$/gm, "<b>$2</b>");
  text = text.replace(/^(\s*)[\-*]\s+(.+)$/gm, "$1\u2022 $2");
  text = text.replace(/\*\*\*(.*?)\*\*\*/gs, "<b><i>$1</i></b>");
  text = text.replace(/___(.*?)___/gs, "<u><i>$1</i></u>");
  text = splitByTag(text, "**", "b");
  text = splitByTag(text, "__", "u");
  text = splitByTag(text, "~~", "s");
  text = splitByTag(text, "||", 'span class="tg-spoiler"');
  text = text.replace(/(?<![A-Za-z0-9])\*(?=[^\s])(.*?)(?<!\s)\*(?![A-Za-z0-9])/gs, "<i>$1</i>");
  text = splitByTag(text, "_", "i");
  text = text.replace(/【[^】]+】/g, "");
  const linkPattern = /(?:!?)\[((?:[^\[\]]|\[.*?\])*)\]\(([^)]+)\)/g;
  text = text.replace(linkPattern, '<a href="$2">$1</a>');
  for (const [ph, snippet] of Object.entries(inline2.inlineSnippets)) {
    const escaped = snippet.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
    text = text.replace(ph, `<code>${escaped}</code>`);
  }
  text = reinsertCodeBlocks(text, codeBlocks);
  text = removeBlockquoteEscaping(text);
  text = removeSpoilerEscaping(text);
  text = text.replace(/\n{3,}/g, "\n\n");
  return text.trim();
}
var init_telegramFormat = __esm({
  "node_modules/telegram-markdown-formatter/dist/lib/telegramFormat.js"() {
    init_esbuild_shims();
    init_converters();
    init_extractors();
    init_formatters2();
    init_helpers3();
    __name(telegramFormat, "telegramFormat");
  }
});

// node_modules/telegram-markdown-formatter/dist/lib/htmlSplitter.js
function parseAttributes(raw2) {
  const attrs = [];
  const re3 = /(\w+)=["']([^"']*)["']/g;
  let m3;
  while (m3 = re3.exec(raw2))
    attrs.push([m3[1], m3[2]]);
  return attrs;
}
function splitPreBlock(preBlock) {
  const langAware = preBlock.match(/^<pre><code(.*?)>([\s\S]*)<\/code><\/pre>$/);
  if (langAware) {
    const [, attr, content] = langAware;
    const lines2 = content.split(/(\r?\n)/);
    const chunks2 = [];
    let buf2 = "";
    for (const piece of lines2) {
      if (buf2.length + piece.length + "<pre><code></code></pre>".length > MAX_LENGTH) {
        chunks2.push(`<pre><code${attr}>${buf2}</code></pre>`);
        buf2 = "";
      }
      buf2 += piece;
    }
    if (buf2)
      chunks2.push(`<pre><code${attr}>${buf2}</code></pre>`);
    return chunks2;
  }
  const inner = preBlock.slice(5, -6);
  const lines = inner.split(/(\r?\n)/);
  const chunks = [];
  let buf = "";
  for (const piece of lines) {
    if (buf.length + piece.length + "<pre></pre>".length > MAX_LENGTH) {
      chunks.push(`<pre>${buf}</pre>`);
      buf = "";
    }
    buf += piece;
  }
  if (buf)
    chunks.push(`<pre>${buf}</pre>`);
  return chunks;
}
function splitHtmlForTelegram(text) {
  const chunks = [];
  const pattern = /(<pre>.*?<\/pre>|<pre><code.*?<\/code><\/pre>)/gs;
  const parts2 = text.split(pattern);
  for (const part of parts2) {
    if (!part)
      continue;
    if (part.startsWith("<pre>") || part.startsWith("<pre><code")) {
      chunks.push(...splitPreBlock(part));
    } else {
      const tracker = new HTMLTagTracker();
      let current = "";
      const blocks = part.split(/(\n\s*\n|<br\s*\/?>(?:\n)?|\n)/);
      for (const block2 of blocks) {
        const prospective = current + block2;
        if (prospective.length > MAX_LENGTH) {
          tracker.feed(current);
          const openTags = tracker.getOpenTagsHtml();
          const closeTags = tracker.getClosingTagsHtml();
          chunks.push(openTags + current + closeTags);
          current = block2;
        } else {
          current = prospective;
        }
      }
      if (current.trim()) {
        tracker.feed(current);
        const openTags = tracker.getOpenTagsHtml();
        const closeTags = tracker.getClosingTagsHtml();
        chunks.push(openTags + current + closeTags);
      }
    }
  }
  const merged = [];
  let buf = "";
  for (const c4 of chunks) {
    if (buf.length + c4.length <= MAX_LENGTH)
      buf += c4;
    else {
      if (buf)
        merged.push(buf);
      buf = c4;
    }
  }
  if (buf)
    merged.push(buf);
  return merged;
}
var MAX_LENGTH, HTMLTagTracker;
var init_htmlSplitter = __esm({
  "node_modules/telegram-markdown-formatter/dist/lib/htmlSplitter.js"() {
    init_esbuild_shims();
    MAX_LENGTH = 4096;
    HTMLTagTracker = class {
      static {
        __name(this, "HTMLTagTracker");
      }
      constructor() {
        this.openTags = [];
      }
      feed(html2) {
        const tagRegex = /<\/?([a-zA-Z0-9]+)([^>]*)>/g;
        let m3;
        while (m3 = tagRegex.exec(html2)) {
          const isClosing = html2[m3.index + 1] === "/";
          const tag2 = m3[1];
          if (!isClosing) {
            if (["b", "i", "u", "s", "code", "pre", "a", "span", "blockquote"].includes(tag2)) {
              const attrs = parseAttributes(m3[2]);
              this.openTags.push([tag2, attrs]);
            }
          } else {
            for (let i4 = this.openTags.length - 1; i4 >= 0; i4--) {
              if (this.openTags[i4][0] === tag2) {
                this.openTags.splice(i4, 1);
                break;
              }
            }
          }
        }
      }
      getOpenTagsHtml() {
        return this.openTags.map(([tag2, attrs]) => {
          const attrStr = attrs.length ? " " + attrs.map(([k2, v2]) => `${k2}="${v2}"`).join(" ") : "";
          return `<${tag2}${attrStr}>`;
        }).join("");
      }
      getClosingTagsHtml() {
        return [...this.openTags].reverse().map(([tag2]) => `</${tag2}>`).join("");
      }
    };
    __name(parseAttributes, "parseAttributes");
    __name(splitPreBlock, "splitPreBlock");
    __name(splitHtmlForTelegram, "splitHtmlForTelegram");
  }
});

// node_modules/telegram-markdown-formatter/dist/index.js
var init_dist6 = __esm({
  "node_modules/telegram-markdown-formatter/dist/index.js"() {
    init_esbuild_shims();
    init_telegramFormat();
    init_htmlSplitter();
  }
});

// packages/channels/telegram/dist/TelegramAdapter.js
import { mkdirSync as mkdirSync15, writeFileSync as writeFileSync17 } from "node:fs";
import { randomUUID as randomUUID13 } from "node:crypto";
import { basename as basename23, join as join53 } from "node:path";
import { tmpdir as tmpdir7 } from "node:os";
var import_grammy, import_https_proxy_agent2, TelegramChannel;
var init_TelegramAdapter = __esm({
  "packages/channels/telegram/dist/TelegramAdapter.js"() {
    "use strict";
    init_esbuild_shims();
    import_grammy = __toESM(require_mod2(), 1);
    import_https_proxy_agent2 = __toESM(require_dist3(), 1);
    init_dist6();
    init_dist5();
    TelegramChannel = class extends ChannelBase {
      static {
        __name(this, "TelegramChannel");
      }
      bot;
      botId = 0;
      botUsername = "";
      constructor(name4, config2, bridge, options2) {
        super(name4, config2, bridge, options2);
        const botConfig = this.proxy ? {
          client: {
            baseFetchConfig: { agent: new import_https_proxy_agent2.HttpsProxyAgent(this.proxy) }
          }
        } : void 0;
        this.bot = new import_grammy.Bot(config2.token, botConfig);
      }
      getFileUrl(filePath) {
        return `https://api.telegram.org/file/bot${this.bot.token}/${filePath}`;
      }
      async connect() {
        const botInfo = await this.bot.api.getMe();
        this.botId = botInfo.id;
        this.botUsername = botInfo.username ?? "";
        this.bot.on("message:text", async (ctx) => {
          const msg = ctx.message;
          const text = msg.text;
          const envelope = this.buildEnvelope(msg, text, msg.entities);
          this.handleInbound(envelope).catch((err2) => {
            process.stderr.write(`[Telegram:${this.name}] Error handling message: ${err2}
`);
            ctx.reply("Sorry, something went wrong processing your message.").catch(() => {
            });
          });
        });
        this.bot.on("message:photo", async (ctx) => {
          const msg = ctx.message;
          const envelope = this.buildEnvelope(msg, msg.caption || "(image)", msg.caption_entities);
          const photo = msg.photo[msg.photo.length - 1];
          if (!photo)
            return;
          try {
            const file2 = await ctx.api.getFile(photo.file_id);
            const fileUrl = this.getFileUrl(file2.file_path);
            const resp = await fetch(fileUrl);
            if (!resp.ok)
              throw new Error(`HTTP ${resp.status}`);
            const buf = Buffer.from(await resp.arrayBuffer());
            envelope.imageBase64 = buf.toString("base64");
            envelope.imageMimeType = "image/jpeg";
          } catch (err2) {
            process.stderr.write(`[Telegram:${this.name}] Failed to download photo: ${err2 instanceof Error ? err2.message : err2}
`);
          }
          this.handleInbound(envelope).catch((err2) => {
            process.stderr.write(`[Telegram:${this.name}] Error handling message: ${err2}
`);
            ctx.reply("Sorry, something went wrong processing your message.").catch(() => {
            });
          });
        });
        this.bot.on("message:document", async (ctx) => {
          const msg = ctx.message;
          const doc = msg.document;
          const fileName = doc.file_name || `file_${Date.now()}`;
          const envelope = this.buildEnvelope(msg, msg.caption || `(file: ${fileName})`, msg.caption_entities);
          try {
            const file2 = await ctx.api.getFile(doc.file_id);
            const fileUrl = this.getFileUrl(file2.file_path);
            const resp = await fetch(fileUrl);
            if (!resp.ok)
              throw new Error(`HTTP ${resp.status}`);
            const buf = Buffer.from(await resp.arrayBuffer());
            const dir = join53(tmpdir7(), "channel-files", randomUUID13());
            mkdirSync15(dir, { recursive: true });
            const filePath = join53(dir, basename23(fileName) || `file_${Date.now()}`);
            writeFileSync17(filePath, buf);
            envelope.text = msg.caption || "";
            envelope.attachments = [
              {
                type: "file",
                filePath,
                mimeType: doc.mime_type || "application/octet-stream",
                fileName
              }
            ];
          } catch (err2) {
            process.stderr.write(`[Telegram:${this.name}] Failed to download document: ${err2 instanceof Error ? err2.message : err2}
`);
            envelope.text = (msg.caption || "") + `

(User sent a file "${fileName}" but download failed)`;
          }
          this.handleInbound(envelope).catch((err2) => {
            process.stderr.write(`[Telegram:${this.name}] Error handling message: ${err2}
`);
            ctx.reply("Sorry, something went wrong processing your message.").catch(() => {
            });
          });
        });
        this.bot.on("message:voice", async (ctx) => {
          const msg = ctx.message;
          const voice = msg.voice;
          const fileName = `voice_${Date.now()}.ogg`;
          const envelope = this.buildEnvelope(msg, msg.caption || "(voice message)", msg.caption_entities);
          try {
            const file2 = await ctx.api.getFile(voice.file_id);
            const fileUrl = this.getFileUrl(file2.file_path);
            const resp = await fetch(fileUrl);
            if (!resp.ok)
              throw new Error(`HTTP ${resp.status}`);
            const buf = Buffer.from(await resp.arrayBuffer());
            const dir = join53(tmpdir7(), "channel-files", randomUUID13());
            mkdirSync15(dir, { recursive: true });
            const filePath = join53(dir, fileName);
            writeFileSync17(filePath, buf);
            envelope.text = msg.caption || "";
            envelope.attachments = [
              {
                type: "audio",
                filePath,
                mimeType: voice.mime_type || "audio/ogg",
                fileName
              }
            ];
          } catch (err2) {
            process.stderr.write(`[Telegram:${this.name}] Failed to download voice message: ${err2 instanceof Error ? err2.message : err2}
`);
            envelope.text = (msg.caption || "") + `

(User sent a voice message but download failed)`;
          }
          this.handleInbound(envelope).catch((err2) => {
            process.stderr.write(`[Telegram:${this.name}] Error handling message: ${err2}
`);
            ctx.reply("Sorry, something went wrong processing your message.").catch(() => {
            });
          });
        });
        this.bot.start({ drop_pending_updates: true }).catch((err2) => {
          process.stderr.write(`[Telegram:${this.name}] Bot launch error: ${err2}
`);
        });
        process.once("SIGINT", () => this.bot.stop());
        process.once("SIGTERM", () => this.bot.stop());
      }
      /** Per-chat typing interval — repeats every 4s since Telegram expires it after 5s. */
      typingIntervals = /* @__PURE__ */ new Map();
      onPromptStart(chatId) {
        const existing = this.typingIntervals.get(chatId);
        if (existing)
          clearInterval(existing);
        const sendTyping2 = /* @__PURE__ */ __name(() => this.bot.api.sendChatAction(chatId, "typing").catch(() => {
        }), "sendTyping");
        sendTyping2();
        this.typingIntervals.set(chatId, setInterval(sendTyping2, 4e3));
      }
      onPromptEnd(chatId) {
        const interval = this.typingIntervals.get(chatId);
        if (interval) {
          clearInterval(interval);
          this.typingIntervals.delete(chatId);
        }
      }
      async sendMessage(chatId, text) {
        const html2 = telegramFormat(text);
        const chunks = splitHtmlForTelegram(html2);
        for (const chunk of chunks) {
          try {
            await this.bot.api.sendMessage(chatId, chunk, {
              parse_mode: "HTML"
            });
          } catch {
            await this.bot.api.sendMessage(chatId, chunk.replace(/<[^>]*>/g, ""));
          }
        }
      }
      disconnect() {
        this.bot.stop();
      }
      buildEnvelope(msg, text, entities) {
        const isGroup = msg.chat.type === "group" || msg.chat.type === "supergroup";
        const isMentioned = entities?.some((e4) => e4.type === "mention" && this.botUsername && text.slice(e4.offset, e4.offset + e4.length).toLowerCase() === `@${this.botUsername.toLowerCase()}`) ?? false;
        const isReplyToBot = msg.reply_to_message?.from?.id === this.botId;
        let cleanText = text;
        if (isMentioned && this.botUsername) {
          cleanText = text.replace(new RegExp(`@${this.botUsername}`, "gi"), "").trim();
        }
        const referencedText = msg.reply_to_message?.text || void 0;
        return {
          channelName: this.name,
          senderId: String(msg.from.id),
          senderName: msg.from.first_name + (msg.from.last_name ? ` ${msg.from.last_name}` : ""),
          chatId: String(msg.chat.id),
          text: cleanText,
          isGroup,
          isMentioned,
          isReplyToBot,
          referencedText
        };
      }
    };
  }
});

// packages/channels/telegram/dist/index.js
var dist_exports2 = {};
__export(dist_exports2, {
  TelegramChannel: () => TelegramChannel,
  plugin: () => plugin
});
var plugin;
var init_dist7 = __esm({
  "packages/channels/telegram/dist/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_TelegramAdapter();
    init_TelegramAdapter();
    plugin = {
      channelType: "telegram",
      displayName: "Telegram",
      requiredConfigFields: ["token"],
      createChannel: /* @__PURE__ */ __name((name4, config2, bridge, options2) => new TelegramChannel(name4, config2, bridge, options2), "createChannel")
    };
  }
});

// packages/channels/weixin/dist/accounts.js
import { existsSync as existsSync32, mkdirSync as mkdirSync16, readFileSync as readFileSync25, writeFileSync as writeFileSync18, unlinkSync as unlinkSync5, chmodSync } from "node:fs";
import { join as join54 } from "node:path";
import { homedir as homedir24 } from "node:os";
function getStateDir() {
  const dir = process.env["WEIXIN_STATE_DIR"] || join54(homedir24(), ".qwen", "channels", "weixin");
  if (!existsSync32(dir)) {
    mkdirSync16(dir, { recursive: true });
  }
  return dir;
}
function accountPath() {
  return join54(getStateDir(), "account.json");
}
function loadAccount() {
  const p2 = accountPath();
  if (!existsSync32(p2))
    return null;
  try {
    return JSON.parse(readFileSync25(p2, "utf-8"));
  } catch {
    return null;
  }
}
function saveAccount(data) {
  const p2 = accountPath();
  writeFileSync18(p2, JSON.stringify(data, null, 2), "utf-8");
  chmodSync(p2, 384);
}
function clearAccount() {
  const p2 = accountPath();
  if (existsSync32(p2)) {
    unlinkSync5(p2);
  }
}
var DEFAULT_BASE_URL;
var init_accounts = __esm({
  "packages/channels/weixin/dist/accounts.js"() {
    "use strict";
    init_esbuild_shims();
    DEFAULT_BASE_URL = "https://ilinkai.weixin.qq.com";
    __name(getStateDir, "getStateDir");
    __name(accountPath, "accountPath");
    __name(loadAccount, "loadAccount");
    __name(saveAccount, "saveAccount");
    __name(clearAccount, "clearAccount");
  }
});

// packages/channels/weixin/dist/api.js
function buildClientVersion(version2) {
  const parts2 = version2.split(".").map((p2) => parseInt(p2, 10));
  const major2 = parts2[0] ?? 0;
  const minor = parts2[1] ?? 0;
  const patch = parts2[2] ?? 0;
  return (major2 & 255) << 16 | (minor & 255) << 8 | patch & 255;
}
function baseInfo() {
  return { channel_version: ILINK_PROTOCOL_VERSION };
}
function randomUin() {
  const buf = new Uint8Array(4);
  crypto.getRandomValues(buf);
  return btoa(String.fromCharCode(...buf));
}
function buildHeaders2(token2) {
  const headers = {
    "Content-Type": "application/json",
    "X-WECHAT-UIN": randomUin(),
    "iLink-App-Id": "bot",
    "iLink-App-ClientVersion": String(buildClientVersion(ILINK_PROTOCOL_VERSION))
  };
  if (token2) {
    headers["AuthorizationType"] = "ilink_bot_token";
    headers["Authorization"] = `Bearer ${token2}`;
  }
  return headers;
}
async function post(baseUrl, path150, body2, token2, timeoutMs = 4e4, signal) {
  const controller = new AbortController();
  const timeout2 = setTimeout(() => controller.abort(), timeoutMs);
  if (signal) {
    signal.addEventListener("abort", () => controller.abort(), { once: true });
  }
  try {
    const resp = await fetch(`${baseUrl}${path150}`, {
      method: "POST",
      headers: buildHeaders2(token2),
      body: JSON.stringify(body2),
      signal: controller.signal
    });
    if (!resp.ok) {
      throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
    }
    return await resp.json();
  } finally {
    clearTimeout(timeout2);
  }
}
async function getUpdates(baseUrl, token2, getUpdatesBuf, timeoutMs = 4e4, signal) {
  const body2 = {
    get_updates_buf: getUpdatesBuf,
    base_info: baseInfo()
  };
  try {
    return await post(baseUrl, "/ilink/bot/getupdates", body2, token2, timeoutMs, signal);
  } catch (err2) {
    if (err2 instanceof Error && err2.name === "AbortError") {
      return { ret: 0, msgs: [], get_updates_buf: getUpdatesBuf };
    }
    throw err2;
  }
}
async function sendMessage(baseUrl, token2, msg) {
  const body2 = { msg, base_info: baseInfo() };
  await post(baseUrl, "/ilink/bot/sendmessage", body2, token2);
}
async function getConfig(baseUrl, token2, userId, contextToken) {
  const body2 = {
    ilink_user_id: userId,
    context_token: contextToken,
    base_info: baseInfo()
  };
  return post(baseUrl, "/ilink/bot/getconfig", body2, token2);
}
async function sendTyping(baseUrl, token2, req) {
  const body2 = { ...req, base_info: baseInfo() };
  return post(baseUrl, "/ilink/bot/sendtyping", body2, token2);
}
var ILINK_PROTOCOL_VERSION;
var init_api2 = __esm({
  "packages/channels/weixin/dist/api.js"() {
    "use strict";
    init_esbuild_shims();
    ILINK_PROTOCOL_VERSION = "2.1.3";
    __name(buildClientVersion, "buildClientVersion");
    __name(baseInfo, "baseInfo");
    __name(randomUin, "randomUin");
    __name(buildHeaders2, "buildHeaders");
    __name(post, "post");
    __name(getUpdates, "getUpdates");
    __name(sendMessage, "sendMessage");
    __name(getConfig, "getConfig");
    __name(sendTyping, "sendTyping");
  }
});

// packages/channels/weixin/dist/types.js
var MessageType, MessageItemType, MessageState, TypingStatus;
var init_types20 = __esm({
  "packages/channels/weixin/dist/types.js"() {
    "use strict";
    init_esbuild_shims();
    MessageType = {
      NONE: 0,
      USER: 1,
      BOT: 2
    };
    MessageItemType = {
      NONE: 0,
      TEXT: 1,
      IMAGE: 2,
      VOICE: 3,
      FILE: 4,
      VIDEO: 5
    };
    MessageState = {
      NEW: 0,
      GENERATING: 1,
      FINISH: 2
    };
    TypingStatus = {
      TYPING: 1,
      CANCEL: 2
    };
  }
});

// packages/channels/weixin/dist/monitor.js
import { existsSync as existsSync33, readFileSync as readFileSync26, writeFileSync as writeFileSync19 } from "node:fs";
import { join as join55 } from "node:path";
function getContextToken(userId) {
  return contextTokens.get(userId);
}
function cursorPath() {
  return join55(getStateDir(), "cursor.txt");
}
function loadCursor() {
  const p2 = cursorPath();
  if (existsSync33(p2))
    return readFileSync26(p2, "utf-8").trim();
  return "";
}
function saveCursor(cursor) {
  writeFileSync19(cursorPath(), cursor, "utf-8");
}
async function startPollLoop(params) {
  const { baseUrl, token: token2, onMessage, abortSignal } = params;
  let cursor = loadCursor();
  let consecutiveErrors = 0;
  let pollTimeoutMs = 4e4;
  process.stderr.write("[weixin] Starting message poll loop...\n");
  while (!abortSignal.aborted) {
    try {
      const resp = await getUpdates(baseUrl, token2, cursor, pollTimeoutMs, abortSignal);
      if (resp.errcode === -14) {
        process.stderr.write("[weixin] Session expired (errcode -14). Pausing 30s...\n");
        await new Promise((r5) => setTimeout(r5, 3e4));
        continue;
      }
      if (resp.ret !== 0 && resp.ret !== void 0) {
        throw new Error(`getUpdates error: ret=${resp.ret} errcode=${resp.errcode} ${resp.errmsg}`);
      }
      consecutiveErrors = 0;
      if (resp.longpolling_timeout_ms && resp.longpolling_timeout_ms > 0) {
        pollTimeoutMs = resp.longpolling_timeout_ms + 5e3;
      }
      if (resp.msgs && resp.msgs.length > 0) {
        for (const msg of resp.msgs) {
          await processMessage(msg, onMessage);
        }
      }
      if (resp.get_updates_buf) {
        cursor = resp.get_updates_buf;
        saveCursor(cursor);
      }
    } catch (err2) {
      if (abortSignal.aborted)
        break;
      consecutiveErrors++;
      process.stderr.write(`[weixin] Poll error (${consecutiveErrors}): ${err2 instanceof Error ? err2.message : err2}
`);
      if (consecutiveErrors >= 3) {
        process.stderr.write("[weixin] Too many consecutive errors, backing off 30s...\n");
        await new Promise((r5) => setTimeout(r5, 3e4));
        consecutiveErrors = 0;
      } else {
        await new Promise((r5) => setTimeout(r5, 2e3));
      }
    }
  }
  process.stderr.write("[weixin] Poll loop stopped.\n");
}
async function processMessage(msg, onMessage) {
  if (msg.message_type !== MessageType.USER)
    return;
  const fromUserId = msg.from_user_id;
  if (!fromUserId)
    return;
  if (msg.context_token) {
    contextTokens.set(fromUserId, msg.context_token);
  }
  let textContent2 = "";
  let image2;
  let file2;
  let refText;
  if (msg.item_list) {
    for (const item of msg.item_list) {
      if (item.type === MessageItemType.TEXT && item.text_item?.text) {
        textContent2 += (textContent2 ? "\n" : "") + item.text_item.text;
      }
      if (item.ref_msg) {
        const refItem = item.ref_msg.message_item;
        if (refItem?.text_item?.text) {
          refText = refItem.text_item.text;
        } else if (item.ref_msg.title) {
          refText = item.ref_msg.title;
        }
      }
      if (item.type === MessageItemType.IMAGE && item.image_item) {
        const media = item.image_item.media;
        if (media?.encrypt_query_param && media.aes_key) {
          image2 = {
            encryptQueryParam: media.encrypt_query_param,
            aesKey: media.aes_key
          };
        }
      } else if (item.type === MessageItemType.FILE && item.file_item) {
        const media = item.file_item.media;
        if (media?.encrypt_query_param && media.aes_key) {
          file2 = {
            encryptQueryParam: media.encrypt_query_param,
            aesKey: media.aes_key,
            fileName: item.file_item.file_name || `file_${Date.now()}`
          };
        }
      }
    }
  }
  if (!textContent2 && !image2 && !file2)
    return;
  await onMessage({
    fromUserId,
    messageId: String(msg.message_id || ""),
    text: textContent2 || (file2 ? `(file: ${file2.fileName})` : "(image)"),
    image: image2,
    file: file2,
    refText
  });
}
var contextTokens;
var init_monitor = __esm({
  "packages/channels/weixin/dist/monitor.js"() {
    "use strict";
    init_esbuild_shims();
    init_api2();
    init_types20();
    init_accounts();
    contextTokens = /* @__PURE__ */ new Map();
    __name(getContextToken, "getContextToken");
    __name(cursorPath, "cursorPath");
    __name(loadCursor, "loadCursor");
    __name(saveCursor, "saveCursor");
    __name(startPollLoop, "startPollLoop");
    __name(processMessage, "processMessage");
  }
});

// packages/channels/weixin/dist/send.js
import { randomUUID as randomUUID14 } from "node:crypto";
function markdownToPlainText(text) {
  return text.replace(/```[\s\S]*?\n([\s\S]*?)```/g, "$1").replace(/`([^`]+)`/g, "$1").replace(/\*\*\*(.+?)\*\*\*/g, "$1").replace(/\*\*(.+?)\*\*/g, "$1").replace(/\*(.+?)\*/g, "$1").replace(/___(.+?)___/g, "$1").replace(/__(.+?)__/g, "$1").replace(/_(.+?)_/g, "$1").replace(/~~(.+?)~~/g, "$1").replace(/^#{1,6}\s+/gm, "").replace(/\[([^\]]+)\]\(([^)]+)\)/g, "$1 ($2)").replace(/!\[([^\]]*)\]\([^)]+\)/g, "[$1]").replace(/^>\s+/gm, "").replace(/^[-*_]{3,}$/gm, "---").replace(/^[\s]*[-*+]\s+/gm, "- ").replace(/^[\s]*(\d+)\.\s+/gm, "$1. ").replace(/\n{3,}/g, "\n\n").trim();
}
async function sendText(params) {
  const { to, text, baseUrl, token: token2, contextToken } = params;
  const plainText = markdownToPlainText(text);
  await sendMessage(baseUrl, token2, {
    to_user_id: to,
    from_user_id: "",
    client_id: randomUUID14(),
    message_type: MessageType.BOT,
    message_state: MessageState.FINISH,
    context_token: contextToken,
    item_list: [{ type: MessageItemType.TEXT, text_item: { text: plainText } }]
  });
}
var init_send = __esm({
  "packages/channels/weixin/dist/send.js"() {
    "use strict";
    init_esbuild_shims();
    init_api2();
    init_types20();
    __name(markdownToPlainText, "markdownToPlainText");
    __name(sendText, "sendText");
  }
});

// packages/channels/weixin/dist/media.js
import { createDecipheriv as createDecipheriv2 } from "node:crypto";
function buildCdnDownloadUrl(encryptedQueryParam) {
  return `${CDN_BASE_URL}/download?encrypted_query_param=${encodeURIComponent(encryptedQueryParam)}`;
}
function decryptAesEcb(ciphertext, key) {
  const decipher = createDecipheriv2("aes-128-ecb", key, null);
  return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
}
function parseAesKey(aesKeyBase64) {
  const decoded = Buffer.from(aesKeyBase64, "base64");
  if (decoded.length === 16) {
    return decoded;
  }
  if (decoded.length === 32 && /^[0-9a-fA-F]{32}$/.test(decoded.toString("ascii"))) {
    return Buffer.from(decoded.toString("ascii"), "hex");
  }
  throw new Error(`Invalid aes_key: expected 16 raw bytes or 32 hex chars, got ${decoded.length} bytes`);
}
async function downloadAndDecrypt(encryptQueryParam, aesKey) {
  const url3 = buildCdnDownloadUrl(encryptQueryParam);
  const resp = await fetch(url3);
  if (!resp.ok) {
    throw new Error(`CDN download failed: HTTP ${resp.status}`);
  }
  const ciphertext = Buffer.from(await resp.arrayBuffer());
  const keyBuf = parseAesKey(aesKey);
  return decryptAesEcb(ciphertext, keyBuf);
}
var CDN_BASE_URL;
var init_media = __esm({
  "packages/channels/weixin/dist/media.js"() {
    "use strict";
    init_esbuild_shims();
    CDN_BASE_URL = "https://novac2c.cdn.weixin.qq.com/c2c";
    __name(buildCdnDownloadUrl, "buildCdnDownloadUrl");
    __name(decryptAesEcb, "decryptAesEcb");
    __name(parseAesKey, "parseAesKey");
    __name(downloadAndDecrypt, "downloadAndDecrypt");
  }
});

// packages/channels/weixin/dist/WeixinAdapter.js
import { mkdirSync as mkdirSync17, writeFileSync as writeFileSync20 } from "node:fs";
import { randomUUID as randomUUID15 } from "node:crypto";
import { basename as basename24, join as join56 } from "node:path";
import { tmpdir as tmpdir8 } from "node:os";
function detectImageMime(data) {
  if (data[0] === 137 && data[1] === 80 && data[2] === 78 && data[3] === 71) {
    return "image/png";
  }
  if (data[0] === 71 && data[1] === 73 && data[2] === 70) {
    return "image/gif";
  }
  if (data[0] === 82 && data[1] === 73 && data[2] === 70 && data[3] === 70) {
    return "image/webp";
  }
  return "image/jpeg";
}
var typingTickets, WeixinChannel;
var init_WeixinAdapter = __esm({
  "packages/channels/weixin/dist/WeixinAdapter.js"() {
    "use strict";
    init_esbuild_shims();
    init_dist5();
    init_accounts();
    init_monitor();
    init_send();
    init_media();
    init_api2();
    init_types20();
    typingTickets = /* @__PURE__ */ new Map();
    WeixinChannel = class extends ChannelBase {
      static {
        __name(this, "WeixinChannel");
      }
      abortController = null;
      baseUrl;
      token = "";
      constructor(name4, config2, bridge, options2) {
        super(name4, config2, bridge, options2);
        this.baseUrl = config2.baseUrl || DEFAULT_BASE_URL;
      }
      async connect() {
        const account = loadAccount();
        if (!account) {
          throw new Error('WeChat account not configured. Run "qwen channel configure-weixin" first.');
        }
        this.token = account.token;
        if (account.baseUrl) {
          this.baseUrl = account.baseUrl;
        }
        this.abortController = new AbortController();
        startPollLoop({
          baseUrl: this.baseUrl,
          token: this.token,
          onMessage: /* @__PURE__ */ __name(async (msg) => {
            const envelope = {
              channelName: this.name,
              senderId: msg.fromUserId,
              senderName: msg.fromUserId,
              chatId: msg.fromUserId,
              text: msg.text,
              isGroup: false,
              isMentioned: false,
              isReplyToBot: false,
              referencedText: msg.refText
            };
            this.handleInboundWithMedia(envelope, msg.image, msg.file).catch((err2) => {
              const errMsg = err2 instanceof Error ? err2.message : JSON.stringify(err2, null, 2);
              process.stderr.write(`[Weixin:${this.name}] Error handling message: ${errMsg}
`);
            });
          }, "onMessage"),
          abortSignal: this.abortController.signal
        }).catch((err2) => {
          if (!this.abortController?.signal.aborted) {
            process.stderr.write(`[Weixin:${this.name}] Poll loop error: ${err2}
`);
          }
        });
        process.stderr.write(`[Weixin:${this.name}] Connected to WeChat (${this.baseUrl})
`);
      }
      onPromptStart(chatId) {
        this.setTyping(chatId, true).catch(() => {
        });
      }
      onPromptEnd(chatId) {
        this.setTyping(chatId, false).catch(() => {
        });
      }
      async handleInboundWithMedia(envelope, image2, file2) {
        if (image2) {
          try {
            const imageData = await downloadAndDecrypt(image2.encryptQueryParam, image2.aesKey);
            envelope.imageBase64 = imageData.toString("base64");
            envelope.imageMimeType = detectImageMime(imageData);
          } catch (err2) {
            process.stderr.write(`[Weixin:${this.name}] Failed to download image: ${err2 instanceof Error ? err2.message : err2}
`);
          }
        }
        if (file2) {
          try {
            const fileData = await downloadAndDecrypt(file2.encryptQueryParam, file2.aesKey);
            const dir = join56(tmpdir8(), "channel-files", randomUUID15());
            mkdirSync17(dir, { recursive: true });
            const filePath = join56(dir, basename24(file2.fileName) || `file_${Date.now()}`);
            writeFileSync20(filePath, fileData);
            envelope.attachments = [
              {
                type: "file",
                filePath,
                mimeType: "application/octet-stream",
                fileName: file2.fileName
              }
            ];
          } catch (err2) {
            process.stderr.write(`[Weixin:${this.name}] Failed to download file: ${err2 instanceof Error ? err2.message : err2}
`);
            envelope.text = `(User sent a file "${file2.fileName}" but download failed)`;
          }
        }
        await super.handleInbound(envelope);
      }
      async sendMessage(chatId, text) {
        const contextToken = getContextToken(chatId) || "";
        await sendText({
          to: chatId,
          text,
          baseUrl: this.baseUrl,
          token: this.token,
          contextToken
        });
      }
      disconnect() {
        if (this.abortController) {
          this.abortController.abort();
          this.abortController = null;
        }
      }
      async setTyping(userId, typing) {
        try {
          let ticket = typingTickets.get(userId);
          if (!ticket) {
            const contextToken = getContextToken(userId);
            const config2 = await getConfig(this.baseUrl, this.token, userId, contextToken);
            if (config2.typing_ticket) {
              ticket = config2.typing_ticket;
              typingTickets.set(userId, ticket);
            }
          }
          if (!ticket)
            return;
          await sendTyping(this.baseUrl, this.token, {
            ilink_user_id: userId,
            typing_ticket: ticket,
            status: typing ? TypingStatus.TYPING : TypingStatus.CANCEL
          });
        } catch {
        }
      }
    };
    __name(detectImageMime, "detectImageMime");
  }
});

// packages/channels/weixin/dist/index.js
var dist_exports3 = {};
__export(dist_exports3, {
  WeixinChannel: () => WeixinChannel,
  plugin: () => plugin2
});
var plugin2;
var init_dist8 = __esm({
  "packages/channels/weixin/dist/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_WeixinAdapter();
    init_WeixinAdapter();
    plugin2 = {
      channelType: "weixin",
      displayName: "WeChat",
      createChannel: /* @__PURE__ */ __name((name4, config2, bridge, options2) => new WeixinChannel(name4, config2, bridge, options2), "createChannel")
    };
  }
});

// node_modules/dingtalk-stream-sdk-nodejs/dist/constants.mjs
var TOPIC_ROBOT;
var init_constants9 = __esm({
  "node_modules/dingtalk-stream-sdk-nodejs/dist/constants.mjs"() {
    init_esbuild_shims();
    TOPIC_ROBOT = "/v1.0/im/bot/messages/get";
  }
});

// node_modules/axios/lib/helpers/bind.js
function bind(fn, thisArg) {
  return /* @__PURE__ */ __name(function wrap2() {
    return fn.apply(thisArg, arguments);
  }, "wrap");
}
var init_bind = __esm({
  "node_modules/axios/lib/helpers/bind.js"() {
    "use strict";
    init_esbuild_shims();
    __name(bind, "bind");
  }
});

// node_modules/axios/lib/utils.js
function isBuffer(val) {
  return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction4(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
function isArrayBufferView2(val) {
  let result;
  if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
    result = ArrayBuffer.isView(val);
  } else {
    result = val && val.buffer && isArrayBuffer(val.buffer);
  }
  return result;
}
function getGlobal2() {
  if (typeof globalThis !== "undefined") return globalThis;
  if (typeof self !== "undefined") return self;
  if (typeof window !== "undefined") return window;
  if (typeof globalThis !== "undefined") return globalThis;
  return {};
}
function forEach2(obj, fn, { allOwnKeys = false } = {}) {
  if (obj === null || typeof obj === "undefined") {
    return;
  }
  let i4;
  let l3;
  if (typeof obj !== "object") {
    obj = [obj];
  }
  if (isArray2(obj)) {
    for (i4 = 0, l3 = obj.length; i4 < l3; i4++) {
      fn.call(null, obj[i4], i4, obj);
    }
  } else {
    if (isBuffer(obj)) {
      return;
    }
    const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
    const len = keys.length;
    let key;
    for (i4 = 0; i4 < len; i4++) {
      key = keys[i4];
      fn.call(null, obj[key], key, obj);
    }
  }
}
function findKey(obj, key) {
  if (isBuffer(obj)) {
    return null;
  }
  key = key.toLowerCase();
  const keys = Object.keys(obj);
  let i4 = keys.length;
  let _key;
  while (i4-- > 0) {
    _key = keys[i4];
    if (key === _key.toLowerCase()) {
      return _key;
    }
  }
  return null;
}
function merge4() {
  const { caseless, skipUndefined } = isContextDefined(this) && this || {};
  const result = {};
  const assignValue = /* @__PURE__ */ __name((val, key) => {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      return;
    }
    const targetKey = caseless && findKey(result, key) || key;
    if (isPlainObject8(result[targetKey]) && isPlainObject8(val)) {
      result[targetKey] = merge4(result[targetKey], val);
    } else if (isPlainObject8(val)) {
      result[targetKey] = merge4({}, val);
    } else if (isArray2(val)) {
      result[targetKey] = val.slice();
    } else if (!skipUndefined || !isUndefined(val)) {
      result[targetKey] = val;
    }
  }, "assignValue");
  for (let i4 = 0, l3 = arguments.length; i4 < l3; i4++) {
    arguments[i4] && forEach2(arguments[i4], assignValue);
  }
  return result;
}
function isSpecCompliantForm(thing) {
  return !!(thing && isFunction4(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
}
var toString, getPrototypeOf, iterator, toStringTag, kindOf, kindOfTest, typeOfTest, isArray2, isUndefined, isArrayBuffer, isString, isFunction4, isNumber3, isObject2, isBoolean2, isPlainObject8, isEmptyObject, isDate, isFile3, isReactNativeBlob, isReactNative, isBlob3, isFileList, isStream2, G2, FormDataCtor, isFormData2, isURLSearchParams, isReadableStream, isRequest2, isResponse, isHeaders, trim, _global2, isContextDefined, extend2, stripBOM, inherits, toFlatObject, endsWith, toArray, isTypedArray, forEachEntry, matchAll, isHTMLForm, toCamelCase, hasOwnProperty2, isRegExp, reduceDescriptors, freezeMethods, toObjectSet, noop7, toFiniteNumber, toJSONObject, isAsyncFn, isThenable, _setImmediate, asap, isIterable, utils_default;
var init_utils7 = __esm({
  "node_modules/axios/lib/utils.js"() {
    "use strict";
    init_esbuild_shims();
    init_bind();
    ({ toString } = Object.prototype);
    ({ getPrototypeOf } = Object);
    ({ iterator, toStringTag } = Symbol);
    kindOf = /* @__PURE__ */ ((cache5) => (thing) => {
      const str2 = toString.call(thing);
      return cache5[str2] || (cache5[str2] = str2.slice(8, -1).toLowerCase());
    })(/* @__PURE__ */ Object.create(null));
    kindOfTest = /* @__PURE__ */ __name((type) => {
      type = type.toLowerCase();
      return (thing) => kindOf(thing) === type;
    }, "kindOfTest");
    typeOfTest = /* @__PURE__ */ __name((type) => (thing) => typeof thing === type, "typeOfTest");
    ({ isArray: isArray2 } = Array);
    isUndefined = typeOfTest("undefined");
    __name(isBuffer, "isBuffer");
    isArrayBuffer = kindOfTest("ArrayBuffer");
    __name(isArrayBufferView2, "isArrayBufferView");
    isString = typeOfTest("string");
    isFunction4 = typeOfTest("function");
    isNumber3 = typeOfTest("number");
    isObject2 = /* @__PURE__ */ __name((thing) => thing !== null && typeof thing === "object", "isObject");
    isBoolean2 = /* @__PURE__ */ __name((thing) => thing === true || thing === false, "isBoolean");
    isPlainObject8 = /* @__PURE__ */ __name((val) => {
      if (kindOf(val) !== "object") {
        return false;
      }
      const prototype2 = getPrototypeOf(val);
      return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
    }, "isPlainObject");
    isEmptyObject = /* @__PURE__ */ __name((val) => {
      if (!isObject2(val) || isBuffer(val)) {
        return false;
      }
      try {
        return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
      } catch (e4) {
        return false;
      }
    }, "isEmptyObject");
    isDate = kindOfTest("Date");
    isFile3 = kindOfTest("File");
    isReactNativeBlob = /* @__PURE__ */ __name((value) => {
      return !!(value && typeof value.uri !== "undefined");
    }, "isReactNativeBlob");
    isReactNative = /* @__PURE__ */ __name((formData) => formData && typeof formData.getParts !== "undefined", "isReactNative");
    isBlob3 = kindOfTest("Blob");
    isFileList = kindOfTest("FileList");
    isStream2 = /* @__PURE__ */ __name((val) => isObject2(val) && isFunction4(val.pipe), "isStream");
    __name(getGlobal2, "getGlobal");
    G2 = getGlobal2();
    FormDataCtor = typeof G2.FormData !== "undefined" ? G2.FormData : void 0;
    isFormData2 = /* @__PURE__ */ __name((thing) => {
      let kind2;
      return thing && (FormDataCtor && thing instanceof FormDataCtor || isFunction4(thing.append) && ((kind2 = kindOf(thing)) === "formdata" || // detect form-data instance
      kind2 === "object" && isFunction4(thing.toString) && thing.toString() === "[object FormData]"));
    }, "isFormData");
    isURLSearchParams = kindOfTest("URLSearchParams");
    [isReadableStream, isRequest2, isResponse, isHeaders] = [
      "ReadableStream",
      "Request",
      "Response",
      "Headers"
    ].map(kindOfTest);
    trim = /* @__PURE__ */ __name((str2) => {
      return str2.trim ? str2.trim() : str2.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
    }, "trim");
    __name(forEach2, "forEach");
    __name(findKey, "findKey");
    _global2 = (() => {
      if (typeof globalThis !== "undefined") return globalThis;
      return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : globalThis;
    })();
    isContextDefined = /* @__PURE__ */ __name((context2) => !isUndefined(context2) && context2 !== _global2, "isContextDefined");
    __name(merge4, "merge");
    extend2 = /* @__PURE__ */ __name((a2, b2, thisArg, { allOwnKeys } = {}) => {
      forEach2(
        b2,
        (val, key) => {
          if (thisArg && isFunction4(val)) {
            Object.defineProperty(a2, key, {
              value: bind(val, thisArg),
              writable: true,
              enumerable: true,
              configurable: true
            });
          } else {
            Object.defineProperty(a2, key, {
              value: val,
              writable: true,
              enumerable: true,
              configurable: true
            });
          }
        },
        { allOwnKeys }
      );
      return a2;
    }, "extend");
    stripBOM = /* @__PURE__ */ __name((content) => {
      if (content.charCodeAt(0) === 65279) {
        content = content.slice(1);
      }
      return content;
    }, "stripBOM");
    inherits = /* @__PURE__ */ __name((constructor, superConstructor, props, descriptors) => {
      constructor.prototype = Object.create(superConstructor.prototype, descriptors);
      Object.defineProperty(constructor.prototype, "constructor", {
        value: constructor,
        writable: true,
        enumerable: false,
        configurable: true
      });
      Object.defineProperty(constructor, "super", {
        value: superConstructor.prototype
      });
      props && Object.assign(constructor.prototype, props);
    }, "inherits");
    toFlatObject = /* @__PURE__ */ __name((sourceObj, destObj, filter5, propFilter) => {
      let props;
      let i4;
      let prop;
      const merged = {};
      destObj = destObj || {};
      if (sourceObj == null) return destObj;
      do {
        props = Object.getOwnPropertyNames(sourceObj);
        i4 = props.length;
        while (i4-- > 0) {
          prop = props[i4];
          if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
            destObj[prop] = sourceObj[prop];
            merged[prop] = true;
          }
        }
        sourceObj = filter5 !== false && getPrototypeOf(sourceObj);
      } while (sourceObj && (!filter5 || filter5(sourceObj, destObj)) && sourceObj !== Object.prototype);
      return destObj;
    }, "toFlatObject");
    endsWith = /* @__PURE__ */ __name((str2, searchString, position) => {
      str2 = String(str2);
      if (position === void 0 || position > str2.length) {
        position = str2.length;
      }
      position -= searchString.length;
      const lastIndex = str2.indexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
    }, "endsWith");
    toArray = /* @__PURE__ */ __name((thing) => {
      if (!thing) return null;
      if (isArray2(thing)) return thing;
      let i4 = thing.length;
      if (!isNumber3(i4)) return null;
      const arr = new Array(i4);
      while (i4-- > 0) {
        arr[i4] = thing[i4];
      }
      return arr;
    }, "toArray");
    isTypedArray = /* @__PURE__ */ ((TypedArray) => {
      return (thing) => {
        return TypedArray && thing instanceof TypedArray;
      };
    })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
    forEachEntry = /* @__PURE__ */ __name((obj, fn) => {
      const generator = obj && obj[iterator];
      const _iterator = generator.call(obj);
      let result;
      while ((result = _iterator.next()) && !result.done) {
        const pair = result.value;
        fn.call(obj, pair[0], pair[1]);
      }
    }, "forEachEntry");
    matchAll = /* @__PURE__ */ __name((regExp, str2) => {
      let matches2;
      const arr = [];
      while ((matches2 = regExp.exec(str2)) !== null) {
        arr.push(matches2);
      }
      return arr;
    }, "matchAll");
    isHTMLForm = kindOfTest("HTMLFormElement");
    toCamelCase = /* @__PURE__ */ __name((str2) => {
      return str2.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, /* @__PURE__ */ __name(function replacer(m3, p1, p2) {
        return p1.toUpperCase() + p2;
      }, "replacer"));
    }, "toCamelCase");
    hasOwnProperty2 = (({ hasOwnProperty: hasOwnProperty3 }) => (obj, prop) => hasOwnProperty3.call(obj, prop))(Object.prototype);
    isRegExp = kindOfTest("RegExp");
    reduceDescriptors = /* @__PURE__ */ __name((obj, reducer) => {
      const descriptors = Object.getOwnPropertyDescriptors(obj);
      const reducedDescriptors = {};
      forEach2(descriptors, (descriptor2, name4) => {
        let ret;
        if ((ret = reducer(descriptor2, name4, obj)) !== false) {
          reducedDescriptors[name4] = ret || descriptor2;
        }
      });
      Object.defineProperties(obj, reducedDescriptors);
    }, "reduceDescriptors");
    freezeMethods = /* @__PURE__ */ __name((obj) => {
      reduceDescriptors(obj, (descriptor2, name4) => {
        if (isFunction4(obj) && ["arguments", "caller", "callee"].indexOf(name4) !== -1) {
          return false;
        }
        const value = obj[name4];
        if (!isFunction4(value)) return;
        descriptor2.enumerable = false;
        if ("writable" in descriptor2) {
          descriptor2.writable = false;
          return;
        }
        if (!descriptor2.set) {
          descriptor2.set = () => {
            throw Error("Can not rewrite read-only method '" + name4 + "'");
          };
        }
      });
    }, "freezeMethods");
    toObjectSet = /* @__PURE__ */ __name((arrayOrString, delimiter2) => {
      const obj = {};
      const define2 = /* @__PURE__ */ __name((arr) => {
        arr.forEach((value) => {
          obj[value] = true;
        });
      }, "define");
      isArray2(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter2));
      return obj;
    }, "toObjectSet");
    noop7 = /* @__PURE__ */ __name(() => {
    }, "noop");
    toFiniteNumber = /* @__PURE__ */ __name((value, defaultValue) => {
      return value != null && Number.isFinite(value = +value) ? value : defaultValue;
    }, "toFiniteNumber");
    __name(isSpecCompliantForm, "isSpecCompliantForm");
    toJSONObject = /* @__PURE__ */ __name((obj) => {
      const stack = new Array(10);
      const visit = /* @__PURE__ */ __name((source2, i4) => {
        if (isObject2(source2)) {
          if (stack.indexOf(source2) >= 0) {
            return;
          }
          if (isBuffer(source2)) {
            return source2;
          }
          if (!("toJSON" in source2)) {
            stack[i4] = source2;
            const target = isArray2(source2) ? [] : {};
            forEach2(source2, (value, key) => {
              const reducedValue = visit(value, i4 + 1);
              !isUndefined(reducedValue) && (target[key] = reducedValue);
            });
            stack[i4] = void 0;
            return target;
          }
        }
        return source2;
      }, "visit");
      return visit(obj, 0);
    }, "toJSONObject");
    isAsyncFn = kindOfTest("AsyncFunction");
    isThenable = /* @__PURE__ */ __name((thing) => thing && (isObject2(thing) || isFunction4(thing)) && isFunction4(thing.then) && isFunction4(thing.catch), "isThenable");
    _setImmediate = ((setImmediateSupported, postMessageSupported) => {
      if (setImmediateSupported) {
        return setImmediate;
      }
      return postMessageSupported ? ((token2, callbacks) => {
        _global2.addEventListener(
          "message",
          ({ source: source2, data }) => {
            if (source2 === _global2 && data === token2) {
              callbacks.length && callbacks.shift()();
            }
          },
          false
        );
        return (cb) => {
          callbacks.push(cb);
          _global2.postMessage(token2, "*");
        };
      })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
    })(typeof setImmediate === "function", isFunction4(_global2.postMessage));
    asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global2) : typeof process !== "undefined" && process.nextTick || _setImmediate;
    isIterable = /* @__PURE__ */ __name((thing) => thing != null && isFunction4(thing[iterator]), "isIterable");
    utils_default = {
      isArray: isArray2,
      isArrayBuffer,
      isBuffer,
      isFormData: isFormData2,
      isArrayBufferView: isArrayBufferView2,
      isString,
      isNumber: isNumber3,
      isBoolean: isBoolean2,
      isObject: isObject2,
      isPlainObject: isPlainObject8,
      isEmptyObject,
      isReadableStream,
      isRequest: isRequest2,
      isResponse,
      isHeaders,
      isUndefined,
      isDate,
      isFile: isFile3,
      isReactNativeBlob,
      isReactNative,
      isBlob: isBlob3,
      isRegExp,
      isFunction: isFunction4,
      isStream: isStream2,
      isURLSearchParams,
      isTypedArray,
      isFileList,
      forEach: forEach2,
      merge: merge4,
      extend: extend2,
      trim,
      stripBOM,
      inherits,
      toFlatObject,
      kindOf,
      kindOfTest,
      endsWith,
      toArray,
      forEachEntry,
      matchAll,
      isHTMLForm,
      hasOwnProperty: hasOwnProperty2,
      hasOwnProp: hasOwnProperty2,
      // an alias to avoid ESLint no-prototype-builtins detection
      reduceDescriptors,
      freezeMethods,
      toObjectSet,
      toCamelCase,
      noop: noop7,
      toFiniteNumber,
      findKey,
      global: _global2,
      isContextDefined,
      isSpecCompliantForm,
      toJSONObject,
      isAsyncFn,
      isThenable,
      setImmediate: _setImmediate,
      asap,
      isIterable
    };
  }
});

// node_modules/axios/lib/core/AxiosError.js
var AxiosError, AxiosError_default;
var init_AxiosError = __esm({
  "node_modules/axios/lib/core/AxiosError.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    AxiosError = class _AxiosError extends Error {
      static {
        __name(this, "AxiosError");
      }
      static from(error40, code2, config2, request4, response, customProps) {
        const axiosError = new _AxiosError(error40.message, code2 || error40.code, config2, request4, response);
        axiosError.cause = error40;
        axiosError.name = error40.name;
        if (error40.status != null && axiosError.status == null) {
          axiosError.status = error40.status;
        }
        customProps && Object.assign(axiosError, customProps);
        return axiosError;
      }
      /**
       * Create an Error with the specified message, config, error code, request and response.
       *
       * @param {string} message The error message.
       * @param {string} [code] The error code (for example, 'ECONNABORTED').
       * @param {Object} [config] The config.
       * @param {Object} [request] The request.
       * @param {Object} [response] The response.
       *
       * @returns {Error} The created error.
       */
      constructor(message, code2, config2, request4, response) {
        super(message);
        Object.defineProperty(this, "message", {
          value: message,
          enumerable: true,
          writable: true,
          configurable: true
        });
        this.name = "AxiosError";
        this.isAxiosError = true;
        code2 && (this.code = code2);
        config2 && (this.config = config2);
        request4 && (this.request = request4);
        if (response) {
          this.response = response;
          this.status = response.status;
        }
      }
      toJSON() {
        return {
          // Standard
          message: this.message,
          name: this.name,
          // Microsoft
          description: this.description,
          number: this.number,
          // Mozilla
          fileName: this.fileName,
          lineNumber: this.lineNumber,
          columnNumber: this.columnNumber,
          stack: this.stack,
          // Axios
          config: utils_default.toJSONObject(this.config),
          code: this.code,
          status: this.status
        };
      }
    };
    AxiosError.ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
    AxiosError.ERR_BAD_OPTION = "ERR_BAD_OPTION";
    AxiosError.ECONNABORTED = "ECONNABORTED";
    AxiosError.ETIMEDOUT = "ETIMEDOUT";
    AxiosError.ERR_NETWORK = "ERR_NETWORK";
    AxiosError.ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
    AxiosError.ERR_DEPRECATED = "ERR_DEPRECATED";
    AxiosError.ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
    AxiosError.ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
    AxiosError.ERR_CANCELED = "ERR_CANCELED";
    AxiosError.ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
    AxiosError.ERR_INVALID_URL = "ERR_INVALID_URL";
    AxiosError_default = AxiosError;
  }
});

// node_modules/delayed-stream/lib/delayed_stream.js
var require_delayed_stream = __commonJS({
  "node_modules/delayed-stream/lib/delayed_stream.js"(exports2, module2) {
    init_esbuild_shims();
    var Stream9 = __require("stream").Stream;
    var util5 = __require("util");
    module2.exports = DelayedStream;
    function DelayedStream() {
      this.source = null;
      this.dataSize = 0;
      this.maxDataSize = 1024 * 1024;
      this.pauseStream = true;
      this._maxDataSizeExceeded = false;
      this._released = false;
      this._bufferedEvents = [];
    }
    __name(DelayedStream, "DelayedStream");
    util5.inherits(DelayedStream, Stream9);
    DelayedStream.create = function(source2, options2) {
      var delayedStream = new this();
      options2 = options2 || {};
      for (var option2 in options2) {
        delayedStream[option2] = options2[option2];
      }
      delayedStream.source = source2;
      var realEmit = source2.emit;
      source2.emit = function() {
        delayedStream._handleEmit(arguments);
        return realEmit.apply(source2, arguments);
      };
      source2.on("error", function() {
      });
      if (delayedStream.pauseStream) {
        source2.pause();
      }
      return delayedStream;
    };
    Object.defineProperty(DelayedStream.prototype, "readable", {
      configurable: true,
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return this.source.readable;
      }, "get")
    });
    DelayedStream.prototype.setEncoding = function() {
      return this.source.setEncoding.apply(this.source, arguments);
    };
    DelayedStream.prototype.resume = function() {
      if (!this._released) {
        this.release();
      }
      this.source.resume();
    };
    DelayedStream.prototype.pause = function() {
      this.source.pause();
    };
    DelayedStream.prototype.release = function() {
      this._released = true;
      this._bufferedEvents.forEach(function(args2) {
        this.emit.apply(this, args2);
      }.bind(this));
      this._bufferedEvents = [];
    };
    DelayedStream.prototype.pipe = function() {
      var r5 = Stream9.prototype.pipe.apply(this, arguments);
      this.resume();
      return r5;
    };
    DelayedStream.prototype._handleEmit = function(args2) {
      if (this._released) {
        this.emit.apply(this, args2);
        return;
      }
      if (args2[0] === "data") {
        this.dataSize += args2[1].length;
        this._checkIfMaxDataSizeExceeded();
      }
      this._bufferedEvents.push(args2);
    };
    DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
      if (this._maxDataSizeExceeded) {
        return;
      }
      if (this.dataSize <= this.maxDataSize) {
        return;
      }
      this._maxDataSizeExceeded = true;
      var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded.";
      this.emit("error", new Error(message));
    };
  }
});

// node_modules/combined-stream/lib/combined_stream.js
var require_combined_stream = __commonJS({
  "node_modules/combined-stream/lib/combined_stream.js"(exports2, module2) {
    init_esbuild_shims();
    var util5 = __require("util");
    var Stream9 = __require("stream").Stream;
    var DelayedStream = require_delayed_stream();
    module2.exports = CombinedStream;
    function CombinedStream() {
      this.writable = false;
      this.readable = true;
      this.dataSize = 0;
      this.maxDataSize = 2 * 1024 * 1024;
      this.pauseStreams = true;
      this._released = false;
      this._streams = [];
      this._currentStream = null;
      this._insideLoop = false;
      this._pendingNext = false;
    }
    __name(CombinedStream, "CombinedStream");
    util5.inherits(CombinedStream, Stream9);
    CombinedStream.create = function(options2) {
      var combinedStream = new this();
      options2 = options2 || {};
      for (var option2 in options2) {
        combinedStream[option2] = options2[option2];
      }
      return combinedStream;
    };
    CombinedStream.isStreamLike = function(stream5) {
      return typeof stream5 !== "function" && typeof stream5 !== "string" && typeof stream5 !== "boolean" && typeof stream5 !== "number" && !Buffer.isBuffer(stream5);
    };
    CombinedStream.prototype.append = function(stream5) {
      var isStreamLike = CombinedStream.isStreamLike(stream5);
      if (isStreamLike) {
        if (!(stream5 instanceof DelayedStream)) {
          var newStream = DelayedStream.create(stream5, {
            maxDataSize: Infinity,
            pauseStream: this.pauseStreams
          });
          stream5.on("data", this._checkDataSize.bind(this));
          stream5 = newStream;
        }
        this._handleErrors(stream5);
        if (this.pauseStreams) {
          stream5.pause();
        }
      }
      this._streams.push(stream5);
      return this;
    };
    CombinedStream.prototype.pipe = function(dest, options2) {
      Stream9.prototype.pipe.call(this, dest, options2);
      this.resume();
      return dest;
    };
    CombinedStream.prototype._getNext = function() {
      this._currentStream = null;
      if (this._insideLoop) {
        this._pendingNext = true;
        return;
      }
      this._insideLoop = true;
      try {
        do {
          this._pendingNext = false;
          this._realGetNext();
        } while (this._pendingNext);
      } finally {
        this._insideLoop = false;
      }
    };
    CombinedStream.prototype._realGetNext = function() {
      var stream5 = this._streams.shift();
      if (typeof stream5 == "undefined") {
        this.end();
        return;
      }
      if (typeof stream5 !== "function") {
        this._pipeNext(stream5);
        return;
      }
      var getStream = stream5;
      getStream(function(stream6) {
        var isStreamLike = CombinedStream.isStreamLike(stream6);
        if (isStreamLike) {
          stream6.on("data", this._checkDataSize.bind(this));
          this._handleErrors(stream6);
        }
        this._pipeNext(stream6);
      }.bind(this));
    };
    CombinedStream.prototype._pipeNext = function(stream5) {
      this._currentStream = stream5;
      var isStreamLike = CombinedStream.isStreamLike(stream5);
      if (isStreamLike) {
        stream5.on("end", this._getNext.bind(this));
        stream5.pipe(this, { end: false });
        return;
      }
      var value = stream5;
      this.write(value);
      this._getNext();
    };
    CombinedStream.prototype._handleErrors = function(stream5) {
      var self2 = this;
      stream5.on("error", function(err2) {
        self2._emitError(err2);
      });
    };
    CombinedStream.prototype.write = function(data) {
      this.emit("data", data);
    };
    CombinedStream.prototype.pause = function() {
      if (!this.pauseStreams) {
        return;
      }
      if (this.pauseStreams && this._currentStream && typeof this._currentStream.pause == "function") this._currentStream.pause();
      this.emit("pause");
    };
    CombinedStream.prototype.resume = function() {
      if (!this._released) {
        this._released = true;
        this.writable = true;
        this._getNext();
      }
      if (this.pauseStreams && this._currentStream && typeof this._currentStream.resume == "function") this._currentStream.resume();
      this.emit("resume");
    };
    CombinedStream.prototype.end = function() {
      this._reset();
      this.emit("end");
    };
    CombinedStream.prototype.destroy = function() {
      this._reset();
      this.emit("close");
    };
    CombinedStream.prototype._reset = function() {
      this.writable = false;
      this._streams = [];
      this._currentStream = null;
    };
    CombinedStream.prototype._checkDataSize = function() {
      this._updateDataSize();
      if (this.dataSize <= this.maxDataSize) {
        return;
      }
      var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded.";
      this._emitError(new Error(message));
    };
    CombinedStream.prototype._updateDataSize = function() {
      this.dataSize = 0;
      var self2 = this;
      this._streams.forEach(function(stream5) {
        if (!stream5.dataSize) {
          return;
        }
        self2.dataSize += stream5.dataSize;
      });
      if (this._currentStream && this._currentStream.dataSize) {
        this.dataSize += this._currentStream.dataSize;
      }
    };
    CombinedStream.prototype._emitError = function(err2) {
      this._reset();
      this.emit("error", err2);
    };
  }
});

// node_modules/mime-db/db.json
var require_db = __commonJS({
  "node_modules/mime-db/db.json"(exports2, module2) {
    module2.exports = {
      "application/1d-interleaved-parityfec": {
        source: "iana"
      },
      "application/3gpdash-qoe-report+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/3gpp-ims+xml": {
        source: "iana",
        compressible: true
      },
      "application/3gpphal+json": {
        source: "iana",
        compressible: true
      },
      "application/3gpphalforms+json": {
        source: "iana",
        compressible: true
      },
      "application/a2l": {
        source: "iana"
      },
      "application/ace+cbor": {
        source: "iana"
      },
      "application/ace+json": {
        source: "iana",
        compressible: true
      },
      "application/ace-groupcomm+cbor": {
        source: "iana"
      },
      "application/ace-trl+cbor": {
        source: "iana"
      },
      "application/activemessage": {
        source: "iana"
      },
      "application/activity+json": {
        source: "iana",
        compressible: true
      },
      "application/aif+cbor": {
        source: "iana"
      },
      "application/aif+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-cdni+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-cdnifilter+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-costmap+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-costmapfilter+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-directory+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointcost+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointcostparams+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointprop+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-endpointpropparams+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-error+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-networkmap+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-networkmapfilter+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-propmap+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-propmapparams+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-tips+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-tipsparams+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-updatestreamcontrol+json": {
        source: "iana",
        compressible: true
      },
      "application/alto-updatestreamparams+json": {
        source: "iana",
        compressible: true
      },
      "application/aml": {
        source: "iana"
      },
      "application/andrew-inset": {
        source: "iana",
        extensions: ["ez"]
      },
      "application/appinstaller": {
        compressible: false,
        extensions: ["appinstaller"]
      },
      "application/applefile": {
        source: "iana"
      },
      "application/applixware": {
        source: "apache",
        extensions: ["aw"]
      },
      "application/appx": {
        compressible: false,
        extensions: ["appx"]
      },
      "application/appxbundle": {
        compressible: false,
        extensions: ["appxbundle"]
      },
      "application/at+jwt": {
        source: "iana"
      },
      "application/atf": {
        source: "iana"
      },
      "application/atfx": {
        source: "iana"
      },
      "application/atom+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atom"]
      },
      "application/atomcat+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atomcat"]
      },
      "application/atomdeleted+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atomdeleted"]
      },
      "application/atomicmail": {
        source: "iana"
      },
      "application/atomsvc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["atomsvc"]
      },
      "application/atsc-dwd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["dwd"]
      },
      "application/atsc-dynamic-event-message": {
        source: "iana"
      },
      "application/atsc-held+xml": {
        source: "iana",
        compressible: true,
        extensions: ["held"]
      },
      "application/atsc-rdt+json": {
        source: "iana",
        compressible: true
      },
      "application/atsc-rsat+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rsat"]
      },
      "application/atxml": {
        source: "iana"
      },
      "application/auth-policy+xml": {
        source: "iana",
        compressible: true
      },
      "application/automationml-aml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["aml"]
      },
      "application/automationml-amlx+zip": {
        source: "iana",
        compressible: false,
        extensions: ["amlx"]
      },
      "application/bacnet-xdd+zip": {
        source: "iana",
        compressible: false
      },
      "application/batch-smtp": {
        source: "iana"
      },
      "application/bdoc": {
        compressible: false,
        extensions: ["bdoc"]
      },
      "application/beep+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/bufr": {
        source: "iana"
      },
      "application/c2pa": {
        source: "iana"
      },
      "application/calendar+json": {
        source: "iana",
        compressible: true
      },
      "application/calendar+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xcs"]
      },
      "application/call-completion": {
        source: "iana"
      },
      "application/cals-1840": {
        source: "iana"
      },
      "application/captive+json": {
        source: "iana",
        compressible: true
      },
      "application/cbor": {
        source: "iana"
      },
      "application/cbor-seq": {
        source: "iana"
      },
      "application/cccex": {
        source: "iana"
      },
      "application/ccmp+xml": {
        source: "iana",
        compressible: true
      },
      "application/ccxml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ccxml"]
      },
      "application/cda+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/cdfx+xml": {
        source: "iana",
        compressible: true,
        extensions: ["cdfx"]
      },
      "application/cdmi-capability": {
        source: "iana",
        extensions: ["cdmia"]
      },
      "application/cdmi-container": {
        source: "iana",
        extensions: ["cdmic"]
      },
      "application/cdmi-domain": {
        source: "iana",
        extensions: ["cdmid"]
      },
      "application/cdmi-object": {
        source: "iana",
        extensions: ["cdmio"]
      },
      "application/cdmi-queue": {
        source: "iana",
        extensions: ["cdmiq"]
      },
      "application/cdni": {
        source: "iana"
      },
      "application/ce+cbor": {
        source: "iana"
      },
      "application/cea": {
        source: "iana"
      },
      "application/cea-2018+xml": {
        source: "iana",
        compressible: true
      },
      "application/cellml+xml": {
        source: "iana",
        compressible: true
      },
      "application/cfw": {
        source: "iana"
      },
      "application/cid-edhoc+cbor-seq": {
        source: "iana"
      },
      "application/city+json": {
        source: "iana",
        compressible: true
      },
      "application/city+json-seq": {
        source: "iana"
      },
      "application/clr": {
        source: "iana"
      },
      "application/clue+xml": {
        source: "iana",
        compressible: true
      },
      "application/clue_info+xml": {
        source: "iana",
        compressible: true
      },
      "application/cms": {
        source: "iana"
      },
      "application/cnrp+xml": {
        source: "iana",
        compressible: true
      },
      "application/coap-eap": {
        source: "iana"
      },
      "application/coap-group+json": {
        source: "iana",
        compressible: true
      },
      "application/coap-payload": {
        source: "iana"
      },
      "application/commonground": {
        source: "iana"
      },
      "application/concise-problem-details+cbor": {
        source: "iana"
      },
      "application/conference-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/cose": {
        source: "iana"
      },
      "application/cose-key": {
        source: "iana"
      },
      "application/cose-key-set": {
        source: "iana"
      },
      "application/cose-x509": {
        source: "iana"
      },
      "application/cpl+xml": {
        source: "iana",
        compressible: true,
        extensions: ["cpl"]
      },
      "application/csrattrs": {
        source: "iana"
      },
      "application/csta+xml": {
        source: "iana",
        compressible: true
      },
      "application/cstadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/csvm+json": {
        source: "iana",
        compressible: true
      },
      "application/cu-seeme": {
        source: "apache",
        extensions: ["cu"]
      },
      "application/cwl": {
        source: "iana",
        extensions: ["cwl"]
      },
      "application/cwl+json": {
        source: "iana",
        compressible: true
      },
      "application/cwl+yaml": {
        source: "iana"
      },
      "application/cwt": {
        source: "iana"
      },
      "application/cybercash": {
        source: "iana"
      },
      "application/dart": {
        compressible: true
      },
      "application/dash+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpd"]
      },
      "application/dash-patch+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpp"]
      },
      "application/dashdelta": {
        source: "iana"
      },
      "application/davmount+xml": {
        source: "iana",
        compressible: true,
        extensions: ["davmount"]
      },
      "application/dca-rft": {
        source: "iana"
      },
      "application/dcd": {
        source: "iana"
      },
      "application/dec-dx": {
        source: "iana"
      },
      "application/dialog-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/dicom": {
        source: "iana",
        extensions: ["dcm"]
      },
      "application/dicom+json": {
        source: "iana",
        compressible: true
      },
      "application/dicom+xml": {
        source: "iana",
        compressible: true
      },
      "application/dii": {
        source: "iana"
      },
      "application/dit": {
        source: "iana"
      },
      "application/dns": {
        source: "iana"
      },
      "application/dns+json": {
        source: "iana",
        compressible: true
      },
      "application/dns-message": {
        source: "iana"
      },
      "application/docbook+xml": {
        source: "apache",
        compressible: true,
        extensions: ["dbk"]
      },
      "application/dots+cbor": {
        source: "iana"
      },
      "application/dpop+jwt": {
        source: "iana"
      },
      "application/dskpp+xml": {
        source: "iana",
        compressible: true
      },
      "application/dssc+der": {
        source: "iana",
        extensions: ["dssc"]
      },
      "application/dssc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xdssc"]
      },
      "application/dvcs": {
        source: "iana"
      },
      "application/eat+cwt": {
        source: "iana"
      },
      "application/eat+jwt": {
        source: "iana"
      },
      "application/eat-bun+cbor": {
        source: "iana"
      },
      "application/eat-bun+json": {
        source: "iana",
        compressible: true
      },
      "application/eat-ucs+cbor": {
        source: "iana"
      },
      "application/eat-ucs+json": {
        source: "iana",
        compressible: true
      },
      "application/ecmascript": {
        source: "apache",
        compressible: true,
        extensions: ["ecma"]
      },
      "application/edhoc+cbor-seq": {
        source: "iana"
      },
      "application/edi-consent": {
        source: "iana"
      },
      "application/edi-x12": {
        source: "iana",
        compressible: false
      },
      "application/edifact": {
        source: "iana",
        compressible: false
      },
      "application/efi": {
        source: "iana"
      },
      "application/elm+json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/elm+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.cap+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/emergencycalldata.comment+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.control+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.deviceinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.ecall.msd": {
        source: "iana"
      },
      "application/emergencycalldata.legacyesn+json": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.providerinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.serviceinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.subscriberinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/emergencycalldata.veds+xml": {
        source: "iana",
        compressible: true
      },
      "application/emma+xml": {
        source: "iana",
        compressible: true,
        extensions: ["emma"]
      },
      "application/emotionml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["emotionml"]
      },
      "application/encaprtp": {
        source: "iana"
      },
      "application/entity-statement+jwt": {
        source: "iana"
      },
      "application/epp+xml": {
        source: "iana",
        compressible: true
      },
      "application/epub+zip": {
        source: "iana",
        compressible: false,
        extensions: ["epub"]
      },
      "application/eshop": {
        source: "iana"
      },
      "application/exi": {
        source: "iana",
        extensions: ["exi"]
      },
      "application/expect-ct-report+json": {
        source: "iana",
        compressible: true
      },
      "application/express": {
        source: "iana",
        extensions: ["exp"]
      },
      "application/fastinfoset": {
        source: "iana"
      },
      "application/fastsoap": {
        source: "iana"
      },
      "application/fdf": {
        source: "iana",
        extensions: ["fdf"]
      },
      "application/fdt+xml": {
        source: "iana",
        compressible: true,
        extensions: ["fdt"]
      },
      "application/fhir+json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/fhir+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/fido.trusted-apps+json": {
        compressible: true
      },
      "application/fits": {
        source: "iana"
      },
      "application/flexfec": {
        source: "iana"
      },
      "application/font-sfnt": {
        source: "iana"
      },
      "application/font-tdpfr": {
        source: "iana",
        extensions: ["pfr"]
      },
      "application/font-woff": {
        source: "iana",
        compressible: false
      },
      "application/framework-attributes+xml": {
        source: "iana",
        compressible: true
      },
      "application/geo+json": {
        source: "iana",
        compressible: true,
        extensions: ["geojson"]
      },
      "application/geo+json-seq": {
        source: "iana"
      },
      "application/geopackage+sqlite3": {
        source: "iana"
      },
      "application/geopose+json": {
        source: "iana",
        compressible: true
      },
      "application/geoxacml+json": {
        source: "iana",
        compressible: true
      },
      "application/geoxacml+xml": {
        source: "iana",
        compressible: true
      },
      "application/gltf-buffer": {
        source: "iana"
      },
      "application/gml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["gml"]
      },
      "application/gnap-binding-jws": {
        source: "iana"
      },
      "application/gnap-binding-jwsd": {
        source: "iana"
      },
      "application/gnap-binding-rotation-jws": {
        source: "iana"
      },
      "application/gnap-binding-rotation-jwsd": {
        source: "iana"
      },
      "application/gpx+xml": {
        source: "apache",
        compressible: true,
        extensions: ["gpx"]
      },
      "application/grib": {
        source: "iana"
      },
      "application/gxf": {
        source: "apache",
        extensions: ["gxf"]
      },
      "application/gzip": {
        source: "iana",
        compressible: false,
        extensions: ["gz"]
      },
      "application/h224": {
        source: "iana"
      },
      "application/held+xml": {
        source: "iana",
        compressible: true
      },
      "application/hjson": {
        extensions: ["hjson"]
      },
      "application/hl7v2+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/http": {
        source: "iana"
      },
      "application/hyperstudio": {
        source: "iana",
        extensions: ["stk"]
      },
      "application/ibe-key-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/ibe-pkg-reply+xml": {
        source: "iana",
        compressible: true
      },
      "application/ibe-pp-data": {
        source: "iana"
      },
      "application/iges": {
        source: "iana"
      },
      "application/im-iscomposing+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/index": {
        source: "iana"
      },
      "application/index.cmd": {
        source: "iana"
      },
      "application/index.obj": {
        source: "iana"
      },
      "application/index.response": {
        source: "iana"
      },
      "application/index.vnd": {
        source: "iana"
      },
      "application/inkml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ink", "inkml"]
      },
      "application/iotp": {
        source: "iana"
      },
      "application/ipfix": {
        source: "iana",
        extensions: ["ipfix"]
      },
      "application/ipp": {
        source: "iana"
      },
      "application/isup": {
        source: "iana"
      },
      "application/its+xml": {
        source: "iana",
        compressible: true,
        extensions: ["its"]
      },
      "application/java-archive": {
        source: "iana",
        compressible: false,
        extensions: ["jar", "war", "ear"]
      },
      "application/java-serialized-object": {
        source: "apache",
        compressible: false,
        extensions: ["ser"]
      },
      "application/java-vm": {
        source: "apache",
        compressible: false,
        extensions: ["class"]
      },
      "application/javascript": {
        source: "apache",
        charset: "UTF-8",
        compressible: true,
        extensions: ["js"]
      },
      "application/jf2feed+json": {
        source: "iana",
        compressible: true
      },
      "application/jose": {
        source: "iana"
      },
      "application/jose+json": {
        source: "iana",
        compressible: true
      },
      "application/jrd+json": {
        source: "iana",
        compressible: true
      },
      "application/jscalendar+json": {
        source: "iana",
        compressible: true
      },
      "application/jscontact+json": {
        source: "iana",
        compressible: true
      },
      "application/json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["json", "map"]
      },
      "application/json-patch+json": {
        source: "iana",
        compressible: true
      },
      "application/json-seq": {
        source: "iana"
      },
      "application/json5": {
        extensions: ["json5"]
      },
      "application/jsonml+json": {
        source: "apache",
        compressible: true,
        extensions: ["jsonml"]
      },
      "application/jsonpath": {
        source: "iana"
      },
      "application/jwk+json": {
        source: "iana",
        compressible: true
      },
      "application/jwk-set+json": {
        source: "iana",
        compressible: true
      },
      "application/jwk-set+jwt": {
        source: "iana"
      },
      "application/jwt": {
        source: "iana"
      },
      "application/kpml-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/kpml-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/ld+json": {
        source: "iana",
        compressible: true,
        extensions: ["jsonld"]
      },
      "application/lgr+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lgr"]
      },
      "application/link-format": {
        source: "iana"
      },
      "application/linkset": {
        source: "iana"
      },
      "application/linkset+json": {
        source: "iana",
        compressible: true
      },
      "application/load-control+xml": {
        source: "iana",
        compressible: true
      },
      "application/logout+jwt": {
        source: "iana"
      },
      "application/lost+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lostxml"]
      },
      "application/lostsync+xml": {
        source: "iana",
        compressible: true
      },
      "application/lpf+zip": {
        source: "iana",
        compressible: false
      },
      "application/lxf": {
        source: "iana"
      },
      "application/mac-binhex40": {
        source: "iana",
        extensions: ["hqx"]
      },
      "application/mac-compactpro": {
        source: "apache",
        extensions: ["cpt"]
      },
      "application/macwriteii": {
        source: "iana"
      },
      "application/mads+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mads"]
      },
      "application/manifest+json": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["webmanifest"]
      },
      "application/marc": {
        source: "iana",
        extensions: ["mrc"]
      },
      "application/marcxml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mrcx"]
      },
      "application/mathematica": {
        source: "iana",
        extensions: ["ma", "nb", "mb"]
      },
      "application/mathml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mathml"]
      },
      "application/mathml-content+xml": {
        source: "iana",
        compressible: true
      },
      "application/mathml-presentation+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-associated-procedure-description+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-deregister+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-envelope+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-msk+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-msk-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-protection-description+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-reception-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-register+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-register-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-schedule+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbms-user-service-description+xml": {
        source: "iana",
        compressible: true
      },
      "application/mbox": {
        source: "iana",
        extensions: ["mbox"]
      },
      "application/media-policy-dataset+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpf"]
      },
      "application/media_control+xml": {
        source: "iana",
        compressible: true
      },
      "application/mediaservercontrol+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mscml"]
      },
      "application/merge-patch+json": {
        source: "iana",
        compressible: true
      },
      "application/metalink+xml": {
        source: "apache",
        compressible: true,
        extensions: ["metalink"]
      },
      "application/metalink4+xml": {
        source: "iana",
        compressible: true,
        extensions: ["meta4"]
      },
      "application/mets+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mets"]
      },
      "application/mf4": {
        source: "iana"
      },
      "application/mikey": {
        source: "iana"
      },
      "application/mipc": {
        source: "iana"
      },
      "application/missing-blocks+cbor-seq": {
        source: "iana"
      },
      "application/mmt-aei+xml": {
        source: "iana",
        compressible: true,
        extensions: ["maei"]
      },
      "application/mmt-usd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["musd"]
      },
      "application/mods+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mods"]
      },
      "application/moss-keys": {
        source: "iana"
      },
      "application/moss-signature": {
        source: "iana"
      },
      "application/mosskey-data": {
        source: "iana"
      },
      "application/mosskey-request": {
        source: "iana"
      },
      "application/mp21": {
        source: "iana",
        extensions: ["m21", "mp21"]
      },
      "application/mp4": {
        source: "iana",
        extensions: ["mp4", "mpg4", "mp4s", "m4p"]
      },
      "application/mpeg4-generic": {
        source: "iana"
      },
      "application/mpeg4-iod": {
        source: "iana"
      },
      "application/mpeg4-iod-xmt": {
        source: "iana"
      },
      "application/mrb-consumer+xml": {
        source: "iana",
        compressible: true
      },
      "application/mrb-publish+xml": {
        source: "iana",
        compressible: true
      },
      "application/msc-ivr+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/msc-mixer+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/msix": {
        compressible: false,
        extensions: ["msix"]
      },
      "application/msixbundle": {
        compressible: false,
        extensions: ["msixbundle"]
      },
      "application/msword": {
        source: "iana",
        compressible: false,
        extensions: ["doc", "dot"]
      },
      "application/mud+json": {
        source: "iana",
        compressible: true
      },
      "application/multipart-core": {
        source: "iana"
      },
      "application/mxf": {
        source: "iana",
        extensions: ["mxf"]
      },
      "application/n-quads": {
        source: "iana",
        extensions: ["nq"]
      },
      "application/n-triples": {
        source: "iana",
        extensions: ["nt"]
      },
      "application/nasdata": {
        source: "iana"
      },
      "application/news-checkgroups": {
        source: "iana",
        charset: "US-ASCII"
      },
      "application/news-groupinfo": {
        source: "iana",
        charset: "US-ASCII"
      },
      "application/news-transmission": {
        source: "iana"
      },
      "application/nlsml+xml": {
        source: "iana",
        compressible: true
      },
      "application/node": {
        source: "iana",
        extensions: ["cjs"]
      },
      "application/nss": {
        source: "iana"
      },
      "application/oauth-authz-req+jwt": {
        source: "iana"
      },
      "application/oblivious-dns-message": {
        source: "iana"
      },
      "application/ocsp-request": {
        source: "iana"
      },
      "application/ocsp-response": {
        source: "iana"
      },
      "application/octet-stream": {
        source: "iana",
        compressible: true,
        extensions: ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"]
      },
      "application/oda": {
        source: "iana",
        extensions: ["oda"]
      },
      "application/odm+xml": {
        source: "iana",
        compressible: true
      },
      "application/odx": {
        source: "iana"
      },
      "application/oebps-package+xml": {
        source: "iana",
        compressible: true,
        extensions: ["opf"]
      },
      "application/ogg": {
        source: "iana",
        compressible: false,
        extensions: ["ogx"]
      },
      "application/ohttp-keys": {
        source: "iana"
      },
      "application/omdoc+xml": {
        source: "apache",
        compressible: true,
        extensions: ["omdoc"]
      },
      "application/onenote": {
        source: "apache",
        extensions: ["onetoc", "onetoc2", "onetmp", "onepkg", "one", "onea"]
      },
      "application/opc-nodeset+xml": {
        source: "iana",
        compressible: true
      },
      "application/oscore": {
        source: "iana"
      },
      "application/oxps": {
        source: "iana",
        extensions: ["oxps"]
      },
      "application/p21": {
        source: "iana"
      },
      "application/p21+zip": {
        source: "iana",
        compressible: false
      },
      "application/p2p-overlay+xml": {
        source: "iana",
        compressible: true,
        extensions: ["relo"]
      },
      "application/parityfec": {
        source: "iana"
      },
      "application/passport": {
        source: "iana"
      },
      "application/patch-ops-error+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xer"]
      },
      "application/pdf": {
        source: "iana",
        compressible: false,
        extensions: ["pdf"]
      },
      "application/pdx": {
        source: "iana"
      },
      "application/pem-certificate-chain": {
        source: "iana"
      },
      "application/pgp-encrypted": {
        source: "iana",
        compressible: false,
        extensions: ["pgp"]
      },
      "application/pgp-keys": {
        source: "iana",
        extensions: ["asc"]
      },
      "application/pgp-signature": {
        source: "iana",
        extensions: ["sig", "asc"]
      },
      "application/pics-rules": {
        source: "apache",
        extensions: ["prf"]
      },
      "application/pidf+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/pidf-diff+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/pkcs10": {
        source: "iana",
        extensions: ["p10"]
      },
      "application/pkcs12": {
        source: "iana"
      },
      "application/pkcs7-mime": {
        source: "iana",
        extensions: ["p7m", "p7c"]
      },
      "application/pkcs7-signature": {
        source: "iana",
        extensions: ["p7s"]
      },
      "application/pkcs8": {
        source: "iana",
        extensions: ["p8"]
      },
      "application/pkcs8-encrypted": {
        source: "iana"
      },
      "application/pkix-attr-cert": {
        source: "iana",
        extensions: ["ac"]
      },
      "application/pkix-cert": {
        source: "iana",
        extensions: ["cer"]
      },
      "application/pkix-crl": {
        source: "iana",
        extensions: ["crl"]
      },
      "application/pkix-pkipath": {
        source: "iana",
        extensions: ["pkipath"]
      },
      "application/pkixcmp": {
        source: "iana",
        extensions: ["pki"]
      },
      "application/pls+xml": {
        source: "iana",
        compressible: true,
        extensions: ["pls"]
      },
      "application/poc-settings+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/postscript": {
        source: "iana",
        compressible: true,
        extensions: ["ai", "eps", "ps"]
      },
      "application/ppsp-tracker+json": {
        source: "iana",
        compressible: true
      },
      "application/private-token-issuer-directory": {
        source: "iana"
      },
      "application/private-token-request": {
        source: "iana"
      },
      "application/private-token-response": {
        source: "iana"
      },
      "application/problem+json": {
        source: "iana",
        compressible: true
      },
      "application/problem+xml": {
        source: "iana",
        compressible: true
      },
      "application/provenance+xml": {
        source: "iana",
        compressible: true,
        extensions: ["provx"]
      },
      "application/provided-claims+jwt": {
        source: "iana"
      },
      "application/prs.alvestrand.titrax-sheet": {
        source: "iana"
      },
      "application/prs.cww": {
        source: "iana",
        extensions: ["cww"]
      },
      "application/prs.cyn": {
        source: "iana",
        charset: "7-BIT"
      },
      "application/prs.hpub+zip": {
        source: "iana",
        compressible: false
      },
      "application/prs.implied-document+xml": {
        source: "iana",
        compressible: true
      },
      "application/prs.implied-executable": {
        source: "iana"
      },
      "application/prs.implied-object+json": {
        source: "iana",
        compressible: true
      },
      "application/prs.implied-object+json-seq": {
        source: "iana"
      },
      "application/prs.implied-object+yaml": {
        source: "iana"
      },
      "application/prs.implied-structure": {
        source: "iana"
      },
      "application/prs.mayfile": {
        source: "iana"
      },
      "application/prs.nprend": {
        source: "iana"
      },
      "application/prs.plucker": {
        source: "iana"
      },
      "application/prs.rdf-xml-crypt": {
        source: "iana"
      },
      "application/prs.vcfbzip2": {
        source: "iana"
      },
      "application/prs.xsf+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xsf"]
      },
      "application/pskc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["pskcxml"]
      },
      "application/pvd+json": {
        source: "iana",
        compressible: true
      },
      "application/qsig": {
        source: "iana"
      },
      "application/raml+yaml": {
        compressible: true,
        extensions: ["raml"]
      },
      "application/raptorfec": {
        source: "iana"
      },
      "application/rdap+json": {
        source: "iana",
        compressible: true
      },
      "application/rdf+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rdf", "owl"]
      },
      "application/reginfo+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rif"]
      },
      "application/relax-ng-compact-syntax": {
        source: "iana",
        extensions: ["rnc"]
      },
      "application/remote-printing": {
        source: "apache"
      },
      "application/reputon+json": {
        source: "iana",
        compressible: true
      },
      "application/resolve-response+jwt": {
        source: "iana"
      },
      "application/resource-lists+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rl"]
      },
      "application/resource-lists-diff+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rld"]
      },
      "application/rfc+xml": {
        source: "iana",
        compressible: true
      },
      "application/riscos": {
        source: "iana"
      },
      "application/rlmi+xml": {
        source: "iana",
        compressible: true
      },
      "application/rls-services+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rs"]
      },
      "application/route-apd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rapd"]
      },
      "application/route-s-tsid+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sls"]
      },
      "application/route-usd+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rusd"]
      },
      "application/rpki-checklist": {
        source: "iana"
      },
      "application/rpki-ghostbusters": {
        source: "iana",
        extensions: ["gbr"]
      },
      "application/rpki-manifest": {
        source: "iana",
        extensions: ["mft"]
      },
      "application/rpki-publication": {
        source: "iana"
      },
      "application/rpki-roa": {
        source: "iana",
        extensions: ["roa"]
      },
      "application/rpki-signed-tal": {
        source: "iana"
      },
      "application/rpki-updown": {
        source: "iana"
      },
      "application/rsd+xml": {
        source: "apache",
        compressible: true,
        extensions: ["rsd"]
      },
      "application/rss+xml": {
        source: "apache",
        compressible: true,
        extensions: ["rss"]
      },
      "application/rtf": {
        source: "iana",
        compressible: true,
        extensions: ["rtf"]
      },
      "application/rtploopback": {
        source: "iana"
      },
      "application/rtx": {
        source: "iana"
      },
      "application/samlassertion+xml": {
        source: "iana",
        compressible: true
      },
      "application/samlmetadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/sarif+json": {
        source: "iana",
        compressible: true
      },
      "application/sarif-external-properties+json": {
        source: "iana",
        compressible: true
      },
      "application/sbe": {
        source: "iana"
      },
      "application/sbml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sbml"]
      },
      "application/scaip+xml": {
        source: "iana",
        compressible: true
      },
      "application/scim+json": {
        source: "iana",
        compressible: true
      },
      "application/scvp-cv-request": {
        source: "iana",
        extensions: ["scq"]
      },
      "application/scvp-cv-response": {
        source: "iana",
        extensions: ["scs"]
      },
      "application/scvp-vp-request": {
        source: "iana",
        extensions: ["spq"]
      },
      "application/scvp-vp-response": {
        source: "iana",
        extensions: ["spp"]
      },
      "application/sdp": {
        source: "iana",
        extensions: ["sdp"]
      },
      "application/secevent+jwt": {
        source: "iana"
      },
      "application/senml+cbor": {
        source: "iana"
      },
      "application/senml+json": {
        source: "iana",
        compressible: true
      },
      "application/senml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["senmlx"]
      },
      "application/senml-etch+cbor": {
        source: "iana"
      },
      "application/senml-etch+json": {
        source: "iana",
        compressible: true
      },
      "application/senml-exi": {
        source: "iana"
      },
      "application/sensml+cbor": {
        source: "iana"
      },
      "application/sensml+json": {
        source: "iana",
        compressible: true
      },
      "application/sensml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sensmlx"]
      },
      "application/sensml-exi": {
        source: "iana"
      },
      "application/sep+xml": {
        source: "iana",
        compressible: true
      },
      "application/sep-exi": {
        source: "iana"
      },
      "application/session-info": {
        source: "iana"
      },
      "application/set-payment": {
        source: "iana"
      },
      "application/set-payment-initiation": {
        source: "iana",
        extensions: ["setpay"]
      },
      "application/set-registration": {
        source: "iana"
      },
      "application/set-registration-initiation": {
        source: "iana",
        extensions: ["setreg"]
      },
      "application/sgml": {
        source: "iana"
      },
      "application/sgml-open-catalog": {
        source: "iana"
      },
      "application/shf+xml": {
        source: "iana",
        compressible: true,
        extensions: ["shf"]
      },
      "application/sieve": {
        source: "iana",
        extensions: ["siv", "sieve"]
      },
      "application/simple-filter+xml": {
        source: "iana",
        compressible: true
      },
      "application/simple-message-summary": {
        source: "iana"
      },
      "application/simplesymbolcontainer": {
        source: "iana"
      },
      "application/sipc": {
        source: "iana"
      },
      "application/slate": {
        source: "iana"
      },
      "application/smil": {
        source: "apache"
      },
      "application/smil+xml": {
        source: "iana",
        compressible: true,
        extensions: ["smi", "smil"]
      },
      "application/smpte336m": {
        source: "iana"
      },
      "application/soap+fastinfoset": {
        source: "iana"
      },
      "application/soap+xml": {
        source: "iana",
        compressible: true
      },
      "application/sparql-query": {
        source: "iana",
        extensions: ["rq"]
      },
      "application/sparql-results+xml": {
        source: "iana",
        compressible: true,
        extensions: ["srx"]
      },
      "application/spdx+json": {
        source: "iana",
        compressible: true
      },
      "application/spirits-event+xml": {
        source: "iana",
        compressible: true
      },
      "application/sql": {
        source: "iana",
        extensions: ["sql"]
      },
      "application/srgs": {
        source: "iana",
        extensions: ["gram"]
      },
      "application/srgs+xml": {
        source: "iana",
        compressible: true,
        extensions: ["grxml"]
      },
      "application/sru+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sru"]
      },
      "application/ssdl+xml": {
        source: "apache",
        compressible: true,
        extensions: ["ssdl"]
      },
      "application/sslkeylogfile": {
        source: "iana"
      },
      "application/ssml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ssml"]
      },
      "application/st2110-41": {
        source: "iana"
      },
      "application/stix+json": {
        source: "iana",
        compressible: true
      },
      "application/stratum": {
        source: "iana"
      },
      "application/swid+cbor": {
        source: "iana"
      },
      "application/swid+xml": {
        source: "iana",
        compressible: true,
        extensions: ["swidtag"]
      },
      "application/tamp-apex-update": {
        source: "iana"
      },
      "application/tamp-apex-update-confirm": {
        source: "iana"
      },
      "application/tamp-community-update": {
        source: "iana"
      },
      "application/tamp-community-update-confirm": {
        source: "iana"
      },
      "application/tamp-error": {
        source: "iana"
      },
      "application/tamp-sequence-adjust": {
        source: "iana"
      },
      "application/tamp-sequence-adjust-confirm": {
        source: "iana"
      },
      "application/tamp-status-query": {
        source: "iana"
      },
      "application/tamp-status-response": {
        source: "iana"
      },
      "application/tamp-update": {
        source: "iana"
      },
      "application/tamp-update-confirm": {
        source: "iana"
      },
      "application/tar": {
        compressible: true
      },
      "application/taxii+json": {
        source: "iana",
        compressible: true
      },
      "application/td+json": {
        source: "iana",
        compressible: true
      },
      "application/tei+xml": {
        source: "iana",
        compressible: true,
        extensions: ["tei", "teicorpus"]
      },
      "application/tetra_isi": {
        source: "iana"
      },
      "application/thraud+xml": {
        source: "iana",
        compressible: true,
        extensions: ["tfi"]
      },
      "application/timestamp-query": {
        source: "iana"
      },
      "application/timestamp-reply": {
        source: "iana"
      },
      "application/timestamped-data": {
        source: "iana",
        extensions: ["tsd"]
      },
      "application/tlsrpt+gzip": {
        source: "iana"
      },
      "application/tlsrpt+json": {
        source: "iana",
        compressible: true
      },
      "application/tm+json": {
        source: "iana",
        compressible: true
      },
      "application/tnauthlist": {
        source: "iana"
      },
      "application/toc+cbor": {
        source: "iana"
      },
      "application/token-introspection+jwt": {
        source: "iana"
      },
      "application/toml": {
        source: "iana",
        compressible: true,
        extensions: ["toml"]
      },
      "application/trickle-ice-sdpfrag": {
        source: "iana"
      },
      "application/trig": {
        source: "iana",
        extensions: ["trig"]
      },
      "application/trust-chain+json": {
        source: "iana",
        compressible: true
      },
      "application/trust-mark+jwt": {
        source: "iana"
      },
      "application/trust-mark-delegation+jwt": {
        source: "iana"
      },
      "application/ttml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ttml"]
      },
      "application/tve-trigger": {
        source: "iana"
      },
      "application/tzif": {
        source: "iana"
      },
      "application/tzif-leap": {
        source: "iana"
      },
      "application/ubjson": {
        compressible: false,
        extensions: ["ubj"]
      },
      "application/uccs+cbor": {
        source: "iana"
      },
      "application/ujcs+json": {
        source: "iana",
        compressible: true
      },
      "application/ulpfec": {
        source: "iana"
      },
      "application/urc-grpsheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/urc-ressheet+xml": {
        source: "iana",
        compressible: true,
        extensions: ["rsheet"]
      },
      "application/urc-targetdesc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["td"]
      },
      "application/urc-uisocketdesc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vc": {
        source: "iana"
      },
      "application/vc+cose": {
        source: "iana"
      },
      "application/vc+jwt": {
        source: "iana"
      },
      "application/vcard+json": {
        source: "iana",
        compressible: true
      },
      "application/vcard+xml": {
        source: "iana",
        compressible: true
      },
      "application/vemmi": {
        source: "iana"
      },
      "application/vividence.scriptfile": {
        source: "apache"
      },
      "application/vnd.1000minds.decision-model+xml": {
        source: "iana",
        compressible: true,
        extensions: ["1km"]
      },
      "application/vnd.1ob": {
        source: "iana"
      },
      "application/vnd.3gpp-prose+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp-prose-pc3a+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp-prose-pc3ach+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp-prose-pc3ch+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp-prose-pc8+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp-v2x-local-service-information": {
        source: "iana"
      },
      "application/vnd.3gpp.5gnas": {
        source: "iana"
      },
      "application/vnd.3gpp.5gsa2x": {
        source: "iana"
      },
      "application/vnd.3gpp.5gsa2x-local-service-information": {
        source: "iana"
      },
      "application/vnd.3gpp.5gsv2x": {
        source: "iana"
      },
      "application/vnd.3gpp.5gsv2x-local-service-information": {
        source: "iana"
      },
      "application/vnd.3gpp.access-transfer-events+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.bsf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.crs+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.current-location-discovery+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.gmop+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.gtpc": {
        source: "iana"
      },
      "application/vnd.3gpp.interworking-data": {
        source: "iana"
      },
      "application/vnd.3gpp.lpp": {
        source: "iana"
      },
      "application/vnd.3gpp.mc-signalling-ear": {
        source: "iana"
      },
      "application/vnd.3gpp.mcdata-affiliation-command+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-msgstore-ctrl-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-payload": {
        source: "iana"
      },
      "application/vnd.3gpp.mcdata-regroup+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-service-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-signalling": {
        source: "iana"
      },
      "application/vnd.3gpp.mcdata-ue-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcdata-user-profile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-affiliation-command+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-floor-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-location-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-regroup+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-service-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-signed+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-ue-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-ue-init-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcptt-user-profile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-affiliation-command+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-location-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-regroup+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-service-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-transmission-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-ue-config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mcvideo-user-profile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.mid-call+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.ngap": {
        source: "iana"
      },
      "application/vnd.3gpp.pfcp": {
        source: "iana"
      },
      "application/vnd.3gpp.pic-bw-large": {
        source: "iana",
        extensions: ["plb"]
      },
      "application/vnd.3gpp.pic-bw-small": {
        source: "iana",
        extensions: ["psb"]
      },
      "application/vnd.3gpp.pic-bw-var": {
        source: "iana",
        extensions: ["pvb"]
      },
      "application/vnd.3gpp.pinapp-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.s1ap": {
        source: "iana"
      },
      "application/vnd.3gpp.seal-group-doc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.seal-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.seal-location-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.seal-mbms-usage-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.seal-network-qos-management-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.seal-ue-config-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.seal-unicast-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.seal-user-profile-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.sms": {
        source: "iana"
      },
      "application/vnd.3gpp.sms+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.srvcc-ext+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.srvcc-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.state-and-event-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.ussd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp.v2x": {
        source: "iana"
      },
      "application/vnd.3gpp.vae-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp2.bcmcsinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.3gpp2.sms": {
        source: "iana"
      },
      "application/vnd.3gpp2.tcap": {
        source: "iana",
        extensions: ["tcap"]
      },
      "application/vnd.3lightssoftware.imagescal": {
        source: "iana"
      },
      "application/vnd.3m.post-it-notes": {
        source: "iana",
        extensions: ["pwn"]
      },
      "application/vnd.accpac.simply.aso": {
        source: "iana",
        extensions: ["aso"]
      },
      "application/vnd.accpac.simply.imp": {
        source: "iana",
        extensions: ["imp"]
      },
      "application/vnd.acm.addressxfer+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.acm.chatbot+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.acucobol": {
        source: "iana",
        extensions: ["acu"]
      },
      "application/vnd.acucorp": {
        source: "iana",
        extensions: ["atc", "acutc"]
      },
      "application/vnd.adobe.air-application-installer-package+zip": {
        source: "apache",
        compressible: false,
        extensions: ["air"]
      },
      "application/vnd.adobe.flash.movie": {
        source: "iana"
      },
      "application/vnd.adobe.formscentral.fcdt": {
        source: "iana",
        extensions: ["fcdt"]
      },
      "application/vnd.adobe.fxp": {
        source: "iana",
        extensions: ["fxp", "fxpl"]
      },
      "application/vnd.adobe.partial-upload": {
        source: "iana"
      },
      "application/vnd.adobe.xdp+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xdp"]
      },
      "application/vnd.adobe.xfdf": {
        source: "apache",
        extensions: ["xfdf"]
      },
      "application/vnd.aether.imp": {
        source: "iana"
      },
      "application/vnd.afpc.afplinedata": {
        source: "iana"
      },
      "application/vnd.afpc.afplinedata-pagedef": {
        source: "iana"
      },
      "application/vnd.afpc.cmoca-cmresource": {
        source: "iana"
      },
      "application/vnd.afpc.foca-charset": {
        source: "iana"
      },
      "application/vnd.afpc.foca-codedfont": {
        source: "iana"
      },
      "application/vnd.afpc.foca-codepage": {
        source: "iana"
      },
      "application/vnd.afpc.modca": {
        source: "iana"
      },
      "application/vnd.afpc.modca-cmtable": {
        source: "iana"
      },
      "application/vnd.afpc.modca-formdef": {
        source: "iana"
      },
      "application/vnd.afpc.modca-mediummap": {
        source: "iana"
      },
      "application/vnd.afpc.modca-objectcontainer": {
        source: "iana"
      },
      "application/vnd.afpc.modca-overlay": {
        source: "iana"
      },
      "application/vnd.afpc.modca-pagesegment": {
        source: "iana"
      },
      "application/vnd.age": {
        source: "iana",
        extensions: ["age"]
      },
      "application/vnd.ah-barcode": {
        source: "apache"
      },
      "application/vnd.ahead.space": {
        source: "iana",
        extensions: ["ahead"]
      },
      "application/vnd.airzip.filesecure.azf": {
        source: "iana",
        extensions: ["azf"]
      },
      "application/vnd.airzip.filesecure.azs": {
        source: "iana",
        extensions: ["azs"]
      },
      "application/vnd.amadeus+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.amazon.ebook": {
        source: "apache",
        extensions: ["azw"]
      },
      "application/vnd.amazon.mobi8-ebook": {
        source: "iana"
      },
      "application/vnd.americandynamics.acc": {
        source: "iana",
        extensions: ["acc"]
      },
      "application/vnd.amiga.ami": {
        source: "iana",
        extensions: ["ami"]
      },
      "application/vnd.amundsen.maze+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.android.ota": {
        source: "iana"
      },
      "application/vnd.android.package-archive": {
        source: "apache",
        compressible: false,
        extensions: ["apk"]
      },
      "application/vnd.anki": {
        source: "iana"
      },
      "application/vnd.anser-web-certificate-issue-initiation": {
        source: "iana",
        extensions: ["cii"]
      },
      "application/vnd.anser-web-funds-transfer-initiation": {
        source: "apache",
        extensions: ["fti"]
      },
      "application/vnd.antix.game-component": {
        source: "iana",
        extensions: ["atx"]
      },
      "application/vnd.apache.arrow.file": {
        source: "iana"
      },
      "application/vnd.apache.arrow.stream": {
        source: "iana"
      },
      "application/vnd.apache.parquet": {
        source: "iana"
      },
      "application/vnd.apache.thrift.binary": {
        source: "iana"
      },
      "application/vnd.apache.thrift.compact": {
        source: "iana"
      },
      "application/vnd.apache.thrift.json": {
        source: "iana"
      },
      "application/vnd.apexlang": {
        source: "iana"
      },
      "application/vnd.api+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.aplextor.warrp+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.apothekende.reservation+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.apple.installer+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mpkg"]
      },
      "application/vnd.apple.keynote": {
        source: "iana",
        extensions: ["key"]
      },
      "application/vnd.apple.mpegurl": {
        source: "iana",
        extensions: ["m3u8"]
      },
      "application/vnd.apple.numbers": {
        source: "iana",
        extensions: ["numbers"]
      },
      "application/vnd.apple.pages": {
        source: "iana",
        extensions: ["pages"]
      },
      "application/vnd.apple.pkpass": {
        compressible: false,
        extensions: ["pkpass"]
      },
      "application/vnd.arastra.swi": {
        source: "apache"
      },
      "application/vnd.aristanetworks.swi": {
        source: "iana",
        extensions: ["swi"]
      },
      "application/vnd.artisan+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.artsquare": {
        source: "iana"
      },
      "application/vnd.astraea-software.iota": {
        source: "iana",
        extensions: ["iota"]
      },
      "application/vnd.audiograph": {
        source: "iana",
        extensions: ["aep"]
      },
      "application/vnd.autodesk.fbx": {
        extensions: ["fbx"]
      },
      "application/vnd.autopackage": {
        source: "iana"
      },
      "application/vnd.avalon+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.avistar+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.balsamiq.bmml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["bmml"]
      },
      "application/vnd.balsamiq.bmpr": {
        source: "iana"
      },
      "application/vnd.banana-accounting": {
        source: "iana"
      },
      "application/vnd.bbf.usp.error": {
        source: "iana"
      },
      "application/vnd.bbf.usp.msg": {
        source: "iana"
      },
      "application/vnd.bbf.usp.msg+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.bekitzur-stech+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.belightsoft.lhzd+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.belightsoft.lhzl+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.bint.med-content": {
        source: "iana"
      },
      "application/vnd.biopax.rdf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.blink-idb-value-wrapper": {
        source: "iana"
      },
      "application/vnd.blueice.multipass": {
        source: "iana",
        extensions: ["mpm"]
      },
      "application/vnd.bluetooth.ep.oob": {
        source: "iana"
      },
      "application/vnd.bluetooth.le.oob": {
        source: "iana"
      },
      "application/vnd.bmi": {
        source: "iana",
        extensions: ["bmi"]
      },
      "application/vnd.bpf": {
        source: "iana"
      },
      "application/vnd.bpf3": {
        source: "iana"
      },
      "application/vnd.businessobjects": {
        source: "iana",
        extensions: ["rep"]
      },
      "application/vnd.byu.uapi+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.bzip3": {
        source: "iana"
      },
      "application/vnd.c3voc.schedule+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cab-jscript": {
        source: "iana"
      },
      "application/vnd.canon-cpdl": {
        source: "iana"
      },
      "application/vnd.canon-lips": {
        source: "iana"
      },
      "application/vnd.capasystems-pg+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cendio.thinlinc.clientconf": {
        source: "iana"
      },
      "application/vnd.century-systems.tcp_stream": {
        source: "iana"
      },
      "application/vnd.chemdraw+xml": {
        source: "iana",
        compressible: true,
        extensions: ["cdxml"]
      },
      "application/vnd.chess-pgn": {
        source: "iana"
      },
      "application/vnd.chipnuts.karaoke-mmd": {
        source: "iana",
        extensions: ["mmd"]
      },
      "application/vnd.ciedi": {
        source: "iana"
      },
      "application/vnd.cinderella": {
        source: "iana",
        extensions: ["cdy"]
      },
      "application/vnd.cirpack.isdn-ext": {
        source: "iana"
      },
      "application/vnd.citationstyles.style+xml": {
        source: "iana",
        compressible: true,
        extensions: ["csl"]
      },
      "application/vnd.claymore": {
        source: "iana",
        extensions: ["cla"]
      },
      "application/vnd.cloanto.rp9": {
        source: "iana",
        extensions: ["rp9"]
      },
      "application/vnd.clonk.c4group": {
        source: "iana",
        extensions: ["c4g", "c4d", "c4f", "c4p", "c4u"]
      },
      "application/vnd.cluetrust.cartomobile-config": {
        source: "iana",
        extensions: ["c11amc"]
      },
      "application/vnd.cluetrust.cartomobile-config-pkg": {
        source: "iana",
        extensions: ["c11amz"]
      },
      "application/vnd.cncf.helm.chart.content.v1.tar+gzip": {
        source: "iana"
      },
      "application/vnd.cncf.helm.chart.provenance.v1.prov": {
        source: "iana"
      },
      "application/vnd.cncf.helm.config.v1+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.coffeescript": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.document": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.document-template": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.presentation": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.presentation-template": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.spreadsheet": {
        source: "iana"
      },
      "application/vnd.collabio.xodocuments.spreadsheet-template": {
        source: "iana"
      },
      "application/vnd.collection+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.collection.doc+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.collection.next+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.comicbook+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.comicbook-rar": {
        source: "iana"
      },
      "application/vnd.commerce-battelle": {
        source: "iana"
      },
      "application/vnd.commonspace": {
        source: "iana",
        extensions: ["csp"]
      },
      "application/vnd.contact.cmsg": {
        source: "iana",
        extensions: ["cdbcmsg"]
      },
      "application/vnd.coreos.ignition+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cosmocaller": {
        source: "iana",
        extensions: ["cmc"]
      },
      "application/vnd.crick.clicker": {
        source: "iana",
        extensions: ["clkx"]
      },
      "application/vnd.crick.clicker.keyboard": {
        source: "iana",
        extensions: ["clkk"]
      },
      "application/vnd.crick.clicker.palette": {
        source: "iana",
        extensions: ["clkp"]
      },
      "application/vnd.crick.clicker.template": {
        source: "iana",
        extensions: ["clkt"]
      },
      "application/vnd.crick.clicker.wordbank": {
        source: "iana",
        extensions: ["clkw"]
      },
      "application/vnd.criticaltools.wbs+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wbs"]
      },
      "application/vnd.cryptii.pipe+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.crypto-shade-file": {
        source: "iana"
      },
      "application/vnd.cryptomator.encrypted": {
        source: "iana"
      },
      "application/vnd.cryptomator.vault": {
        source: "iana"
      },
      "application/vnd.ctc-posml": {
        source: "iana",
        extensions: ["pml"]
      },
      "application/vnd.ctct.ws+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cups-pdf": {
        source: "iana"
      },
      "application/vnd.cups-postscript": {
        source: "iana"
      },
      "application/vnd.cups-ppd": {
        source: "iana",
        extensions: ["ppd"]
      },
      "application/vnd.cups-raster": {
        source: "iana"
      },
      "application/vnd.cups-raw": {
        source: "iana"
      },
      "application/vnd.curl": {
        source: "iana"
      },
      "application/vnd.curl.car": {
        source: "apache",
        extensions: ["car"]
      },
      "application/vnd.curl.pcurl": {
        source: "apache",
        extensions: ["pcurl"]
      },
      "application/vnd.cyan.dean.root+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cybank": {
        source: "iana"
      },
      "application/vnd.cyclonedx+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.cyclonedx+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.d2l.coursepackage1p0+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.d3m-dataset": {
        source: "iana"
      },
      "application/vnd.d3m-problem": {
        source: "iana"
      },
      "application/vnd.dart": {
        source: "iana",
        compressible: true,
        extensions: ["dart"]
      },
      "application/vnd.data-vision.rdz": {
        source: "iana",
        extensions: ["rdz"]
      },
      "application/vnd.datalog": {
        source: "iana"
      },
      "application/vnd.datapackage+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dataresource+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dbf": {
        source: "iana",
        extensions: ["dbf"]
      },
      "application/vnd.dcmp+xml": {
        source: "iana",
        compressible: true,
        extensions: ["dcmp"]
      },
      "application/vnd.debian.binary-package": {
        source: "iana"
      },
      "application/vnd.dece.data": {
        source: "iana",
        extensions: ["uvf", "uvvf", "uvd", "uvvd"]
      },
      "application/vnd.dece.ttml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["uvt", "uvvt"]
      },
      "application/vnd.dece.unspecified": {
        source: "iana",
        extensions: ["uvx", "uvvx"]
      },
      "application/vnd.dece.zip": {
        source: "iana",
        extensions: ["uvz", "uvvz"]
      },
      "application/vnd.denovo.fcselayout-link": {
        source: "iana",
        extensions: ["fe_launch"]
      },
      "application/vnd.desmume.movie": {
        source: "iana"
      },
      "application/vnd.dir-bi.plate-dl-nosuffix": {
        source: "iana"
      },
      "application/vnd.dm.delegation+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dna": {
        source: "iana",
        extensions: ["dna"]
      },
      "application/vnd.document+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dolby.mlp": {
        source: "apache",
        extensions: ["mlp"]
      },
      "application/vnd.dolby.mobile.1": {
        source: "iana"
      },
      "application/vnd.dolby.mobile.2": {
        source: "iana"
      },
      "application/vnd.doremir.scorecloud-binary-document": {
        source: "iana"
      },
      "application/vnd.dpgraph": {
        source: "iana",
        extensions: ["dpg"]
      },
      "application/vnd.dreamfactory": {
        source: "iana",
        extensions: ["dfac"]
      },
      "application/vnd.drive+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ds-keypoint": {
        source: "apache",
        extensions: ["kpxx"]
      },
      "application/vnd.dtg.local": {
        source: "iana"
      },
      "application/vnd.dtg.local.flash": {
        source: "iana"
      },
      "application/vnd.dtg.local.html": {
        source: "iana"
      },
      "application/vnd.dvb.ait": {
        source: "iana",
        extensions: ["ait"]
      },
      "application/vnd.dvb.dvbisl+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.dvbj": {
        source: "iana"
      },
      "application/vnd.dvb.esgcontainer": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcdftnotifaccess": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcesgaccess": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcesgaccess2": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcesgpdd": {
        source: "iana"
      },
      "application/vnd.dvb.ipdcroaming": {
        source: "iana"
      },
      "application/vnd.dvb.iptv.alfec-base": {
        source: "iana"
      },
      "application/vnd.dvb.iptv.alfec-enhancement": {
        source: "iana"
      },
      "application/vnd.dvb.notif-aggregate-root+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-container+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-generic+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-ia-msglist+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-ia-registration-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-ia-registration-response+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.notif-init+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.dvb.pfr": {
        source: "iana"
      },
      "application/vnd.dvb.service": {
        source: "iana",
        extensions: ["svc"]
      },
      "application/vnd.dxr": {
        source: "iana"
      },
      "application/vnd.dynageo": {
        source: "iana",
        extensions: ["geo"]
      },
      "application/vnd.dzr": {
        source: "iana"
      },
      "application/vnd.easykaraoke.cdgdownload": {
        source: "iana"
      },
      "application/vnd.ecdis-update": {
        source: "iana"
      },
      "application/vnd.ecip.rlp": {
        source: "iana"
      },
      "application/vnd.eclipse.ditto+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ecowin.chart": {
        source: "iana",
        extensions: ["mag"]
      },
      "application/vnd.ecowin.filerequest": {
        source: "iana"
      },
      "application/vnd.ecowin.fileupdate": {
        source: "iana"
      },
      "application/vnd.ecowin.series": {
        source: "iana"
      },
      "application/vnd.ecowin.seriesrequest": {
        source: "iana"
      },
      "application/vnd.ecowin.seriesupdate": {
        source: "iana"
      },
      "application/vnd.efi.img": {
        source: "iana"
      },
      "application/vnd.efi.iso": {
        source: "iana"
      },
      "application/vnd.eln+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.emclient.accessrequest+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.enliven": {
        source: "iana",
        extensions: ["nml"]
      },
      "application/vnd.enphase.envoy": {
        source: "iana"
      },
      "application/vnd.eprints.data+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.epson.esf": {
        source: "iana",
        extensions: ["esf"]
      },
      "application/vnd.epson.msf": {
        source: "iana",
        extensions: ["msf"]
      },
      "application/vnd.epson.quickanime": {
        source: "iana",
        extensions: ["qam"]
      },
      "application/vnd.epson.salt": {
        source: "iana",
        extensions: ["slt"]
      },
      "application/vnd.epson.ssf": {
        source: "iana",
        extensions: ["ssf"]
      },
      "application/vnd.ericsson.quickcall": {
        source: "iana"
      },
      "application/vnd.erofs": {
        source: "iana"
      },
      "application/vnd.espass-espass+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.eszigno3+xml": {
        source: "iana",
        compressible: true,
        extensions: ["es3", "et3"]
      },
      "application/vnd.etsi.aoc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.asic-e+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.etsi.asic-s+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.etsi.cug+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvcommand+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvdiscovery+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsad-bc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsad-cod+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsad-npvr+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvservice+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvsync+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.iptvueprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.mcid+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.mheg5": {
        source: "iana"
      },
      "application/vnd.etsi.overload-control-policy-dataset+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.pstn+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.sci+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.simservs+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.timestamp-token": {
        source: "iana"
      },
      "application/vnd.etsi.tsl+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.etsi.tsl.der": {
        source: "iana"
      },
      "application/vnd.eu.kasparian.car+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.eudora.data": {
        source: "iana"
      },
      "application/vnd.evolv.ecig.profile": {
        source: "iana"
      },
      "application/vnd.evolv.ecig.settings": {
        source: "iana"
      },
      "application/vnd.evolv.ecig.theme": {
        source: "iana"
      },
      "application/vnd.exstream-empower+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.exstream-package": {
        source: "iana"
      },
      "application/vnd.ezpix-album": {
        source: "iana",
        extensions: ["ez2"]
      },
      "application/vnd.ezpix-package": {
        source: "iana",
        extensions: ["ez3"]
      },
      "application/vnd.f-secure.mobile": {
        source: "iana"
      },
      "application/vnd.familysearch.gedcom+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.fastcopy-disk-image": {
        source: "iana"
      },
      "application/vnd.fdf": {
        source: "apache",
        extensions: ["fdf"]
      },
      "application/vnd.fdsn.mseed": {
        source: "iana",
        extensions: ["mseed"]
      },
      "application/vnd.fdsn.seed": {
        source: "iana",
        extensions: ["seed", "dataless"]
      },
      "application/vnd.fdsn.stationxml+xml": {
        source: "iana",
        charset: "XML-BASED",
        compressible: true
      },
      "application/vnd.ffsns": {
        source: "iana"
      },
      "application/vnd.ficlab.flb+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.filmit.zfc": {
        source: "iana"
      },
      "application/vnd.fints": {
        source: "iana"
      },
      "application/vnd.firemonkeys.cloudcell": {
        source: "iana"
      },
      "application/vnd.flographit": {
        source: "iana",
        extensions: ["gph"]
      },
      "application/vnd.fluxtime.clip": {
        source: "iana",
        extensions: ["ftc"]
      },
      "application/vnd.font-fontforge-sfd": {
        source: "iana"
      },
      "application/vnd.framemaker": {
        source: "iana",
        extensions: ["fm", "frame", "maker", "book"]
      },
      "application/vnd.freelog.comic": {
        source: "iana"
      },
      "application/vnd.frogans.fnc": {
        source: "apache",
        extensions: ["fnc"]
      },
      "application/vnd.frogans.ltf": {
        source: "apache",
        extensions: ["ltf"]
      },
      "application/vnd.fsc.weblaunch": {
        source: "iana",
        extensions: ["fsc"]
      },
      "application/vnd.fujifilm.fb.docuworks": {
        source: "iana"
      },
      "application/vnd.fujifilm.fb.docuworks.binder": {
        source: "iana"
      },
      "application/vnd.fujifilm.fb.docuworks.container": {
        source: "iana"
      },
      "application/vnd.fujifilm.fb.jfi+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.fujitsu.oasys": {
        source: "iana",
        extensions: ["oas"]
      },
      "application/vnd.fujitsu.oasys2": {
        source: "iana",
        extensions: ["oa2"]
      },
      "application/vnd.fujitsu.oasys3": {
        source: "iana",
        extensions: ["oa3"]
      },
      "application/vnd.fujitsu.oasysgp": {
        source: "iana",
        extensions: ["fg5"]
      },
      "application/vnd.fujitsu.oasysprs": {
        source: "iana",
        extensions: ["bh2"]
      },
      "application/vnd.fujixerox.art-ex": {
        source: "iana"
      },
      "application/vnd.fujixerox.art4": {
        source: "iana"
      },
      "application/vnd.fujixerox.ddd": {
        source: "iana",
        extensions: ["ddd"]
      },
      "application/vnd.fujixerox.docuworks": {
        source: "iana",
        extensions: ["xdw"]
      },
      "application/vnd.fujixerox.docuworks.binder": {
        source: "iana",
        extensions: ["xbd"]
      },
      "application/vnd.fujixerox.docuworks.container": {
        source: "iana"
      },
      "application/vnd.fujixerox.hbpl": {
        source: "iana"
      },
      "application/vnd.fut-misnet": {
        source: "iana"
      },
      "application/vnd.futoin+cbor": {
        source: "iana"
      },
      "application/vnd.futoin+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.fuzzysheet": {
        source: "iana",
        extensions: ["fzs"]
      },
      "application/vnd.ga4gh.passport+jwt": {
        source: "iana"
      },
      "application/vnd.genomatix.tuxedo": {
        source: "iana",
        extensions: ["txd"]
      },
      "application/vnd.genozip": {
        source: "iana"
      },
      "application/vnd.gentics.grd+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.gentoo.catmetadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.gentoo.ebuild": {
        source: "iana"
      },
      "application/vnd.gentoo.eclass": {
        source: "iana"
      },
      "application/vnd.gentoo.gpkg": {
        source: "iana"
      },
      "application/vnd.gentoo.manifest": {
        source: "iana"
      },
      "application/vnd.gentoo.pkgmetadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.gentoo.xpak": {
        source: "iana"
      },
      "application/vnd.geo+json": {
        source: "apache",
        compressible: true
      },
      "application/vnd.geocube+xml": {
        source: "apache",
        compressible: true
      },
      "application/vnd.geogebra.file": {
        source: "iana",
        extensions: ["ggb"]
      },
      "application/vnd.geogebra.pinboard": {
        source: "iana"
      },
      "application/vnd.geogebra.slides": {
        source: "iana",
        extensions: ["ggs"]
      },
      "application/vnd.geogebra.tool": {
        source: "iana",
        extensions: ["ggt"]
      },
      "application/vnd.geometry-explorer": {
        source: "iana",
        extensions: ["gex", "gre"]
      },
      "application/vnd.geonext": {
        source: "iana",
        extensions: ["gxt"]
      },
      "application/vnd.geoplan": {
        source: "iana",
        extensions: ["g2w"]
      },
      "application/vnd.geospace": {
        source: "iana",
        extensions: ["g3w"]
      },
      "application/vnd.gerber": {
        source: "iana"
      },
      "application/vnd.globalplatform.card-content-mgt": {
        source: "iana"
      },
      "application/vnd.globalplatform.card-content-mgt-response": {
        source: "iana"
      },
      "application/vnd.gmx": {
        source: "iana",
        extensions: ["gmx"]
      },
      "application/vnd.gnu.taler.exchange+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.gnu.taler.merchant+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.google-apps.audio": {},
      "application/vnd.google-apps.document": {
        compressible: false,
        extensions: ["gdoc"]
      },
      "application/vnd.google-apps.drawing": {
        compressible: false,
        extensions: ["gdraw"]
      },
      "application/vnd.google-apps.drive-sdk": {
        compressible: false
      },
      "application/vnd.google-apps.file": {},
      "application/vnd.google-apps.folder": {
        compressible: false
      },
      "application/vnd.google-apps.form": {
        compressible: false,
        extensions: ["gform"]
      },
      "application/vnd.google-apps.fusiontable": {},
      "application/vnd.google-apps.jam": {
        compressible: false,
        extensions: ["gjam"]
      },
      "application/vnd.google-apps.mail-layout": {},
      "application/vnd.google-apps.map": {
        compressible: false,
        extensions: ["gmap"]
      },
      "application/vnd.google-apps.photo": {},
      "application/vnd.google-apps.presentation": {
        compressible: false,
        extensions: ["gslides"]
      },
      "application/vnd.google-apps.script": {
        compressible: false,
        extensions: ["gscript"]
      },
      "application/vnd.google-apps.shortcut": {},
      "application/vnd.google-apps.site": {
        compressible: false,
        extensions: ["gsite"]
      },
      "application/vnd.google-apps.spreadsheet": {
        compressible: false,
        extensions: ["gsheet"]
      },
      "application/vnd.google-apps.unknown": {},
      "application/vnd.google-apps.video": {},
      "application/vnd.google-earth.kml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["kml"]
      },
      "application/vnd.google-earth.kmz": {
        source: "iana",
        compressible: false,
        extensions: ["kmz"]
      },
      "application/vnd.gov.sk.e-form+xml": {
        source: "apache",
        compressible: true
      },
      "application/vnd.gov.sk.e-form+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.gov.sk.xmldatacontainer+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xdcf"]
      },
      "application/vnd.gpxsee.map+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.grafeq": {
        source: "iana",
        extensions: ["gqf", "gqs"]
      },
      "application/vnd.gridmp": {
        source: "iana"
      },
      "application/vnd.groove-account": {
        source: "iana",
        extensions: ["gac"]
      },
      "application/vnd.groove-help": {
        source: "iana",
        extensions: ["ghf"]
      },
      "application/vnd.groove-identity-message": {
        source: "iana",
        extensions: ["gim"]
      },
      "application/vnd.groove-injector": {
        source: "iana",
        extensions: ["grv"]
      },
      "application/vnd.groove-tool-message": {
        source: "iana",
        extensions: ["gtm"]
      },
      "application/vnd.groove-tool-template": {
        source: "iana",
        extensions: ["tpl"]
      },
      "application/vnd.groove-vcard": {
        source: "iana",
        extensions: ["vcg"]
      },
      "application/vnd.hal+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hal+xml": {
        source: "iana",
        compressible: true,
        extensions: ["hal"]
      },
      "application/vnd.handheld-entertainment+xml": {
        source: "iana",
        compressible: true,
        extensions: ["zmm"]
      },
      "application/vnd.hbci": {
        source: "iana",
        extensions: ["hbci"]
      },
      "application/vnd.hc+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hcl-bireports": {
        source: "iana"
      },
      "application/vnd.hdt": {
        source: "iana"
      },
      "application/vnd.heroku+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hhe.lesson-player": {
        source: "iana",
        extensions: ["les"]
      },
      "application/vnd.hp-hpgl": {
        source: "iana",
        extensions: ["hpgl"]
      },
      "application/vnd.hp-hpid": {
        source: "iana",
        extensions: ["hpid"]
      },
      "application/vnd.hp-hps": {
        source: "iana",
        extensions: ["hps"]
      },
      "application/vnd.hp-jlyt": {
        source: "iana",
        extensions: ["jlt"]
      },
      "application/vnd.hp-pcl": {
        source: "iana",
        extensions: ["pcl"]
      },
      "application/vnd.hp-pclxl": {
        source: "iana",
        extensions: ["pclxl"]
      },
      "application/vnd.hsl": {
        source: "iana"
      },
      "application/vnd.httphone": {
        source: "iana"
      },
      "application/vnd.hydrostatix.sof-data": {
        source: "iana",
        extensions: ["sfd-hdstx"]
      },
      "application/vnd.hyper+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hyper-item+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hyperdrive+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.hzn-3d-crossword": {
        source: "iana"
      },
      "application/vnd.ibm.afplinedata": {
        source: "apache"
      },
      "application/vnd.ibm.electronic-media": {
        source: "iana"
      },
      "application/vnd.ibm.minipay": {
        source: "iana",
        extensions: ["mpy"]
      },
      "application/vnd.ibm.modcap": {
        source: "apache",
        extensions: ["afp", "listafp", "list3820"]
      },
      "application/vnd.ibm.rights-management": {
        source: "iana",
        extensions: ["irm"]
      },
      "application/vnd.ibm.secure-container": {
        source: "iana",
        extensions: ["sc"]
      },
      "application/vnd.iccprofile": {
        source: "iana",
        extensions: ["icc", "icm"]
      },
      "application/vnd.ieee.1905": {
        source: "iana"
      },
      "application/vnd.igloader": {
        source: "iana",
        extensions: ["igl"]
      },
      "application/vnd.imagemeter.folder+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.imagemeter.image+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.immervision-ivp": {
        source: "iana",
        extensions: ["ivp"]
      },
      "application/vnd.immervision-ivu": {
        source: "iana",
        extensions: ["ivu"]
      },
      "application/vnd.ims.imsccv1p1": {
        source: "iana"
      },
      "application/vnd.ims.imsccv1p2": {
        source: "iana"
      },
      "application/vnd.ims.imsccv1p3": {
        source: "iana"
      },
      "application/vnd.ims.lis.v2.result+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolconsumerprofile+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolproxy+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolproxy.id+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolsettings+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ims.lti.v2.toolsettings.simple+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.informedcontrol.rms+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.informix-visionary": {
        source: "apache"
      },
      "application/vnd.infotech.project": {
        source: "iana"
      },
      "application/vnd.infotech.project+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.innopath.wamp.notification": {
        source: "iana"
      },
      "application/vnd.insors.igm": {
        source: "iana",
        extensions: ["igm"]
      },
      "application/vnd.intercon.formnet": {
        source: "iana",
        extensions: ["xpw", "xpx"]
      },
      "application/vnd.intergeo": {
        source: "iana",
        extensions: ["i2g"]
      },
      "application/vnd.intertrust.digibox": {
        source: "iana"
      },
      "application/vnd.intertrust.nncp": {
        source: "iana"
      },
      "application/vnd.intu.qbo": {
        source: "iana",
        extensions: ["qbo"]
      },
      "application/vnd.intu.qfx": {
        source: "iana",
        extensions: ["qfx"]
      },
      "application/vnd.ipfs.ipns-record": {
        source: "iana"
      },
      "application/vnd.ipld.car": {
        source: "iana"
      },
      "application/vnd.ipld.dag-cbor": {
        source: "iana"
      },
      "application/vnd.ipld.dag-json": {
        source: "iana"
      },
      "application/vnd.ipld.raw": {
        source: "iana"
      },
      "application/vnd.iptc.g2.catalogitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.conceptitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.knowledgeitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.newsitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.newsmessage+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.packageitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.iptc.g2.planningitem+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ipunplugged.rcprofile": {
        source: "iana",
        extensions: ["rcprofile"]
      },
      "application/vnd.irepository.package+xml": {
        source: "iana",
        compressible: true,
        extensions: ["irp"]
      },
      "application/vnd.is-xpr": {
        source: "iana",
        extensions: ["xpr"]
      },
      "application/vnd.isac.fcs": {
        source: "iana",
        extensions: ["fcs"]
      },
      "application/vnd.iso11783-10+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.jam": {
        source: "iana",
        extensions: ["jam"]
      },
      "application/vnd.japannet-directory-service": {
        source: "iana"
      },
      "application/vnd.japannet-jpnstore-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-payment-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-registration": {
        source: "iana"
      },
      "application/vnd.japannet-registration-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-setstore-wakeup": {
        source: "iana"
      },
      "application/vnd.japannet-verification": {
        source: "iana"
      },
      "application/vnd.japannet-verification-wakeup": {
        source: "iana"
      },
      "application/vnd.jcp.javame.midlet-rms": {
        source: "iana",
        extensions: ["rms"]
      },
      "application/vnd.jisp": {
        source: "iana",
        extensions: ["jisp"]
      },
      "application/vnd.joost.joda-archive": {
        source: "iana",
        extensions: ["joda"]
      },
      "application/vnd.jsk.isdn-ngn": {
        source: "iana"
      },
      "application/vnd.kahootz": {
        source: "iana",
        extensions: ["ktz", "ktr"]
      },
      "application/vnd.kde.karbon": {
        source: "iana",
        extensions: ["karbon"]
      },
      "application/vnd.kde.kchart": {
        source: "iana",
        extensions: ["chrt"]
      },
      "application/vnd.kde.kformula": {
        source: "iana",
        extensions: ["kfo"]
      },
      "application/vnd.kde.kivio": {
        source: "iana",
        extensions: ["flw"]
      },
      "application/vnd.kde.kontour": {
        source: "iana",
        extensions: ["kon"]
      },
      "application/vnd.kde.kpresenter": {
        source: "iana",
        extensions: ["kpr", "kpt"]
      },
      "application/vnd.kde.kspread": {
        source: "iana",
        extensions: ["ksp"]
      },
      "application/vnd.kde.kword": {
        source: "iana",
        extensions: ["kwd", "kwt"]
      },
      "application/vnd.kdl": {
        source: "iana"
      },
      "application/vnd.kenameaapp": {
        source: "iana",
        extensions: ["htke"]
      },
      "application/vnd.keyman.kmp+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.keyman.kmx": {
        source: "iana"
      },
      "application/vnd.kidspiration": {
        source: "iana",
        extensions: ["kia"]
      },
      "application/vnd.kinar": {
        source: "iana",
        extensions: ["kne", "knp"]
      },
      "application/vnd.koan": {
        source: "iana",
        extensions: ["skp", "skd", "skt", "skm"]
      },
      "application/vnd.kodak-descriptor": {
        source: "iana",
        extensions: ["sse"]
      },
      "application/vnd.las": {
        source: "iana"
      },
      "application/vnd.las.las+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.las.las+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lasxml"]
      },
      "application/vnd.laszip": {
        source: "iana"
      },
      "application/vnd.ldev.productlicensing": {
        source: "iana"
      },
      "application/vnd.leap+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.liberty-request+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.llamagraphics.life-balance.desktop": {
        source: "iana",
        extensions: ["lbd"]
      },
      "application/vnd.llamagraphics.life-balance.exchange+xml": {
        source: "iana",
        compressible: true,
        extensions: ["lbe"]
      },
      "application/vnd.logipipe.circuit+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.loom": {
        source: "iana"
      },
      "application/vnd.lotus-1-2-3": {
        source: "iana",
        extensions: ["123"]
      },
      "application/vnd.lotus-approach": {
        source: "iana",
        extensions: ["apr"]
      },
      "application/vnd.lotus-freelance": {
        source: "iana",
        extensions: ["pre"]
      },
      "application/vnd.lotus-notes": {
        source: "iana",
        extensions: ["nsf"]
      },
      "application/vnd.lotus-organizer": {
        source: "iana",
        extensions: ["org"]
      },
      "application/vnd.lotus-screencam": {
        source: "iana",
        extensions: ["scm"]
      },
      "application/vnd.lotus-wordpro": {
        source: "iana",
        extensions: ["lwp"]
      },
      "application/vnd.macports.portpkg": {
        source: "iana",
        extensions: ["portpkg"]
      },
      "application/vnd.mapbox-vector-tile": {
        source: "iana",
        extensions: ["mvt"]
      },
      "application/vnd.marlin.drm.actiontoken+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.marlin.drm.conftoken+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.marlin.drm.license+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.marlin.drm.mdcf": {
        source: "iana"
      },
      "application/vnd.mason+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.maxar.archive.3tz+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.maxmind.maxmind-db": {
        source: "iana"
      },
      "application/vnd.mcd": {
        source: "iana",
        extensions: ["mcd"]
      },
      "application/vnd.mdl": {
        source: "iana"
      },
      "application/vnd.mdl-mbsdf": {
        source: "iana"
      },
      "application/vnd.medcalcdata": {
        source: "iana",
        extensions: ["mc1"]
      },
      "application/vnd.mediastation.cdkey": {
        source: "iana",
        extensions: ["cdkey"]
      },
      "application/vnd.medicalholodeck.recordxr": {
        source: "iana"
      },
      "application/vnd.meridian-slingshot": {
        source: "iana"
      },
      "application/vnd.mermaid": {
        source: "iana"
      },
      "application/vnd.mfer": {
        source: "iana",
        extensions: ["mwf"]
      },
      "application/vnd.mfmp": {
        source: "iana",
        extensions: ["mfm"]
      },
      "application/vnd.micro+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.micrografx.flo": {
        source: "iana",
        extensions: ["flo"]
      },
      "application/vnd.micrografx.igx": {
        source: "iana",
        extensions: ["igx"]
      },
      "application/vnd.microsoft.portable-executable": {
        source: "iana"
      },
      "application/vnd.microsoft.windows.thumbnail-cache": {
        source: "iana"
      },
      "application/vnd.miele+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.mif": {
        source: "iana",
        extensions: ["mif"]
      },
      "application/vnd.minisoft-hp3000-save": {
        source: "iana"
      },
      "application/vnd.mitsubishi.misty-guard.trustweb": {
        source: "iana"
      },
      "application/vnd.mobius.daf": {
        source: "iana",
        extensions: ["daf"]
      },
      "application/vnd.mobius.dis": {
        source: "iana",
        extensions: ["dis"]
      },
      "application/vnd.mobius.mbk": {
        source: "iana",
        extensions: ["mbk"]
      },
      "application/vnd.mobius.mqy": {
        source: "iana",
        extensions: ["mqy"]
      },
      "application/vnd.mobius.msl": {
        source: "iana",
        extensions: ["msl"]
      },
      "application/vnd.mobius.plc": {
        source: "iana",
        extensions: ["plc"]
      },
      "application/vnd.mobius.txf": {
        source: "iana",
        extensions: ["txf"]
      },
      "application/vnd.modl": {
        source: "iana"
      },
      "application/vnd.mophun.application": {
        source: "iana",
        extensions: ["mpn"]
      },
      "application/vnd.mophun.certificate": {
        source: "iana",
        extensions: ["mpc"]
      },
      "application/vnd.motorola.flexsuite": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.adsi": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.fis": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.gotap": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.kmr": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.ttc": {
        source: "iana"
      },
      "application/vnd.motorola.flexsuite.wem": {
        source: "iana"
      },
      "application/vnd.motorola.iprm": {
        source: "iana"
      },
      "application/vnd.mozilla.xul+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xul"]
      },
      "application/vnd.ms-3mfdocument": {
        source: "iana"
      },
      "application/vnd.ms-artgalry": {
        source: "iana",
        extensions: ["cil"]
      },
      "application/vnd.ms-asf": {
        source: "iana"
      },
      "application/vnd.ms-cab-compressed": {
        source: "iana",
        extensions: ["cab"]
      },
      "application/vnd.ms-color.iccprofile": {
        source: "apache"
      },
      "application/vnd.ms-excel": {
        source: "iana",
        compressible: false,
        extensions: ["xls", "xlm", "xla", "xlc", "xlt", "xlw"]
      },
      "application/vnd.ms-excel.addin.macroenabled.12": {
        source: "iana",
        extensions: ["xlam"]
      },
      "application/vnd.ms-excel.sheet.binary.macroenabled.12": {
        source: "iana",
        extensions: ["xlsb"]
      },
      "application/vnd.ms-excel.sheet.macroenabled.12": {
        source: "iana",
        extensions: ["xlsm"]
      },
      "application/vnd.ms-excel.template.macroenabled.12": {
        source: "iana",
        extensions: ["xltm"]
      },
      "application/vnd.ms-fontobject": {
        source: "iana",
        compressible: true,
        extensions: ["eot"]
      },
      "application/vnd.ms-htmlhelp": {
        source: "iana",
        extensions: ["chm"]
      },
      "application/vnd.ms-ims": {
        source: "iana",
        extensions: ["ims"]
      },
      "application/vnd.ms-lrm": {
        source: "iana",
        extensions: ["lrm"]
      },
      "application/vnd.ms-office.activex+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-officetheme": {
        source: "iana",
        extensions: ["thmx"]
      },
      "application/vnd.ms-opentype": {
        source: "apache",
        compressible: true
      },
      "application/vnd.ms-outlook": {
        compressible: false,
        extensions: ["msg"]
      },
      "application/vnd.ms-package.obfuscated-opentype": {
        source: "apache"
      },
      "application/vnd.ms-pki.seccat": {
        source: "apache",
        extensions: ["cat"]
      },
      "application/vnd.ms-pki.stl": {
        source: "apache",
        extensions: ["stl"]
      },
      "application/vnd.ms-playready.initiator+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-powerpoint": {
        source: "iana",
        compressible: false,
        extensions: ["ppt", "pps", "pot"]
      },
      "application/vnd.ms-powerpoint.addin.macroenabled.12": {
        source: "iana",
        extensions: ["ppam"]
      },
      "application/vnd.ms-powerpoint.presentation.macroenabled.12": {
        source: "iana",
        extensions: ["pptm"]
      },
      "application/vnd.ms-powerpoint.slide.macroenabled.12": {
        source: "iana",
        extensions: ["sldm"]
      },
      "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
        source: "iana",
        extensions: ["ppsm"]
      },
      "application/vnd.ms-powerpoint.template.macroenabled.12": {
        source: "iana",
        extensions: ["potm"]
      },
      "application/vnd.ms-printdevicecapabilities+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-printing.printticket+xml": {
        source: "apache",
        compressible: true
      },
      "application/vnd.ms-printschematicket+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.ms-project": {
        source: "iana",
        extensions: ["mpp", "mpt"]
      },
      "application/vnd.ms-tnef": {
        source: "iana"
      },
      "application/vnd.ms-visio.viewer": {
        extensions: ["vdx"]
      },
      "application/vnd.ms-windows.devicepairing": {
        source: "iana"
      },
      "application/vnd.ms-windows.nwprinting.oob": {
        source: "iana"
      },
      "application/vnd.ms-windows.printerpairing": {
        source: "iana"
      },
      "application/vnd.ms-windows.wsd.oob": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.lic-chlg-req": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.lic-resp": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.meter-chlg-req": {
        source: "iana"
      },
      "application/vnd.ms-wmdrm.meter-resp": {
        source: "iana"
      },
      "application/vnd.ms-word.document.macroenabled.12": {
        source: "iana",
        extensions: ["docm"]
      },
      "application/vnd.ms-word.template.macroenabled.12": {
        source: "iana",
        extensions: ["dotm"]
      },
      "application/vnd.ms-works": {
        source: "iana",
        extensions: ["wps", "wks", "wcm", "wdb"]
      },
      "application/vnd.ms-wpl": {
        source: "iana",
        extensions: ["wpl"]
      },
      "application/vnd.ms-xpsdocument": {
        source: "iana",
        compressible: false,
        extensions: ["xps"]
      },
      "application/vnd.msa-disk-image": {
        source: "iana"
      },
      "application/vnd.mseq": {
        source: "iana",
        extensions: ["mseq"]
      },
      "application/vnd.msgpack": {
        source: "iana"
      },
      "application/vnd.msign": {
        source: "iana"
      },
      "application/vnd.multiad.creator": {
        source: "iana"
      },
      "application/vnd.multiad.creator.cif": {
        source: "iana"
      },
      "application/vnd.music-niff": {
        source: "iana"
      },
      "application/vnd.musician": {
        source: "iana",
        extensions: ["mus"]
      },
      "application/vnd.muvee.style": {
        source: "iana",
        extensions: ["msty"]
      },
      "application/vnd.mynfc": {
        source: "iana",
        extensions: ["taglet"]
      },
      "application/vnd.nacamar.ybrid+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nato.bindingdataobject+cbor": {
        source: "iana"
      },
      "application/vnd.nato.bindingdataobject+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nato.bindingdataobject+xml": {
        source: "iana",
        compressible: true,
        extensions: ["bdo"]
      },
      "application/vnd.nato.openxmlformats-package.iepd+zip": {
        source: "iana",
        compressible: false
      },
      "application/vnd.ncd.control": {
        source: "iana"
      },
      "application/vnd.ncd.reference": {
        source: "iana"
      },
      "application/vnd.nearst.inv+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nebumind.line": {
        source: "iana"
      },
      "application/vnd.nervana": {
        source: "iana"
      },
      "application/vnd.netfpx": {
        source: "iana"
      },
      "application/vnd.neurolanguage.nlu": {
        source: "iana",
        extensions: ["nlu"]
      },
      "application/vnd.nimn": {
        source: "iana"
      },
      "application/vnd.nintendo.nitro.rom": {
        source: "iana"
      },
      "application/vnd.nintendo.snes.rom": {
        source: "iana"
      },
      "application/vnd.nitf": {
        source: "iana",
        extensions: ["ntf", "nitf"]
      },
      "application/vnd.noblenet-directory": {
        source: "iana",
        extensions: ["nnd"]
      },
      "application/vnd.noblenet-sealer": {
        source: "iana",
        extensions: ["nns"]
      },
      "application/vnd.noblenet-web": {
        source: "iana",
        extensions: ["nnw"]
      },
      "application/vnd.nokia.catalogs": {
        source: "iana"
      },
      "application/vnd.nokia.conml+wbxml": {
        source: "iana"
      },
      "application/vnd.nokia.conml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.iptv.config+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.isds-radio-presets": {
        source: "iana"
      },
      "application/vnd.nokia.landmark+wbxml": {
        source: "iana"
      },
      "application/vnd.nokia.landmark+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.landmarkcollection+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.n-gage.ac+xml": {
        source: "iana",
        compressible: true,
        extensions: ["ac"]
      },
      "application/vnd.nokia.n-gage.data": {
        source: "iana",
        extensions: ["ngdat"]
      },
      "application/vnd.nokia.n-gage.symbian.install": {
        source: "apache",
        extensions: ["n-gage"]
      },
      "application/vnd.nokia.ncd": {
        source: "iana"
      },
      "application/vnd.nokia.pcd+wbxml": {
        source: "iana"
      },
      "application/vnd.nokia.pcd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.nokia.radio-preset": {
        source: "iana",
        extensions: ["rpst"]
      },
      "application/vnd.nokia.radio-presets": {
        source: "iana",
        extensions: ["rpss"]
      },
      "application/vnd.novadigm.edm": {
        source: "iana",
        extensions: ["edm"]
      },
      "application/vnd.novadigm.edx": {
        source: "iana",
        extensions: ["edx"]
      },
      "application/vnd.novadigm.ext": {
        source: "iana",
        extensions: ["ext"]
      },
      "application/vnd.ntt-local.content-share": {
        source: "iana"
      },
      "application/vnd.ntt-local.file-transfer": {
        source: "iana"
      },
      "application/vnd.ntt-local.ogw_remote-access": {
        source: "iana"
      },
      "application/vnd.ntt-local.sip-ta_remote": {
        source: "iana"
      },
      "application/vnd.ntt-local.sip-ta_tcp_stream": {
        source: "iana"
      },
      "application/vnd.oai.workflows": {
        source: "iana"
      },
      "application/vnd.oai.workflows+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oai.workflows+yaml": {
        source: "iana"
      },
      "application/vnd.oasis.opendocument.base": {
        source: "iana"
      },
      "application/vnd.oasis.opendocument.chart": {
        source: "iana",
        extensions: ["odc"]
      },
      "application/vnd.oasis.opendocument.chart-template": {
        source: "iana",
        extensions: ["otc"]
      },
      "application/vnd.oasis.opendocument.database": {
        source: "apache",
        extensions: ["odb"]
      },
      "application/vnd.oasis.opendocument.formula": {
        source: "iana",
        extensions: ["odf"]
      },
      "application/vnd.oasis.opendocument.formula-template": {
        source: "iana",
        extensions: ["odft"]
      },
      "application/vnd.oasis.opendocument.graphics": {
        source: "iana",
        compressible: false,
        extensions: ["odg"]
      },
      "application/vnd.oasis.opendocument.graphics-template": {
        source: "iana",
        extensions: ["otg"]
      },
      "application/vnd.oasis.opendocument.image": {
        source: "iana",
        extensions: ["odi"]
      },
      "application/vnd.oasis.opendocument.image-template": {
        source: "iana",
        extensions: ["oti"]
      },
      "application/vnd.oasis.opendocument.presentation": {
        source: "iana",
        compressible: false,
        extensions: ["odp"]
      },
      "application/vnd.oasis.opendocument.presentation-template": {
        source: "iana",
        extensions: ["otp"]
      },
      "application/vnd.oasis.opendocument.spreadsheet": {
        source: "iana",
        compressible: false,
        extensions: ["ods"]
      },
      "application/vnd.oasis.opendocument.spreadsheet-template": {
        source: "iana",
        extensions: ["ots"]
      },
      "application/vnd.oasis.opendocument.text": {
        source: "iana",
        compressible: false,
        extensions: ["odt"]
      },
      "application/vnd.oasis.opendocument.text-master": {
        source: "iana",
        extensions: ["odm"]
      },
      "application/vnd.oasis.opendocument.text-master-template": {
        source: "iana"
      },
      "application/vnd.oasis.opendocument.text-template": {
        source: "iana",
        extensions: ["ott"]
      },
      "application/vnd.oasis.opendocument.text-web": {
        source: "iana",
        extensions: ["oth"]
      },
      "application/vnd.obn": {
        source: "iana"
      },
      "application/vnd.ocf+cbor": {
        source: "iana"
      },
      "application/vnd.oci.image.manifest.v1+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oftn.l10n+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.contentaccessdownload+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.contentaccessstreaming+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.cspg-hexbinary": {
        source: "iana"
      },
      "application/vnd.oipf.dae.svg+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.dae.xhtml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.mippvcontrolmessage+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.pae.gem": {
        source: "iana"
      },
      "application/vnd.oipf.spdiscovery+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.spdlist+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.ueprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oipf.userprofile+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.olpc-sugar": {
        source: "iana",
        extensions: ["xo"]
      },
      "application/vnd.oma-scws-config": {
        source: "iana"
      },
      "application/vnd.oma-scws-http-request": {
        source: "iana"
      },
      "application/vnd.oma-scws-http-response": {
        source: "iana"
      },
      "application/vnd.oma.bcast.associated-procedure-parameter+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.drm-trigger+xml": {
        source: "apache",
        compressible: true
      },
      "application/vnd.oma.bcast.imd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.ltkm": {
        source: "iana"
      },
      "application/vnd.oma.bcast.notification+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.provisioningtrigger": {
        source: "iana"
      },
      "application/vnd.oma.bcast.sgboot": {
        source: "iana"
      },
      "application/vnd.oma.bcast.sgdd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.sgdu": {
        source: "iana"
      },
      "application/vnd.oma.bcast.simple-symbol-container": {
        source: "iana"
      },
      "application/vnd.oma.bcast.smartcard-trigger+xml": {
        source: "apache",
        compressible: true
      },
      "application/vnd.oma.bcast.sprov+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.bcast.stkm": {
        source: "iana"
      },
      "application/vnd.oma.cab-address-book+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-feature-handler+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-pcc+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-subs-invite+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.cab-user-prefs+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.dcd": {
        source: "iana"
      },
      "application/vnd.oma.dcdc": {
        source: "iana"
      },
      "application/vnd.oma.dd2+xml": {
        source: "iana",
        compressible: true,
        extensions: ["dd2"]
      },
      "application/vnd.oma.drm.risd+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.group-usage-list+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.lwm2m+cbor": {
        source: "iana"
      },
      "application/vnd.oma.lwm2m+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.lwm2m+tlv": {
        source: "iana"
      },
      "application/vnd.oma.pal+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.detailed-progress-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.final-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.groups+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.invocation-descriptor+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.poc.optimized-progress-report+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.push": {
        source: "iana"
      },
      "application/vnd.oma.scidm.messages+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oma.xcap-directory+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.omads-email+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.omads-file+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.omads-folder+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.omaloc-supl-init": {
        source: "iana"
      },
      "application/vnd.onepager": {
        source: "iana"
      },
      "application/vnd.onepagertamp": {
        source: "iana"
      },
      "application/vnd.onepagertamx": {
        source: "iana"
      },
      "application/vnd.onepagertat": {
        source: "iana"
      },
      "application/vnd.onepagertatp": {
        source: "iana"
      },
      "application/vnd.onepagertatx": {
        source: "iana"
      },
      "application/vnd.onvif.metadata": {
        source: "iana"
      },
      "application/vnd.openblox.game+xml": {
        source: "iana",
        compressible: true,
        extensions: ["obgx"]
      },
      "application/vnd.openblox.game-binary": {
        source: "iana"
      },
      "application/vnd.openeye.oeb": {
        source: "iana"
      },
      "application/vnd.openofficeorg.extension": {
        source: "apache",
        extensions: ["oxt"]
      },
      "application/vnd.openstreetmap.data+xml": {
        source: "iana",
        compressible: true,
        extensions: ["osm"]
      },
      "application/vnd.opentimestamps.ots": {
        source: "iana"
      },
      "application/vnd.openvpi.dspx+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.custom-properties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawing+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.extended-properties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.presentation": {
        source: "iana",
        compressible: false,
        extensions: ["pptx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slide": {
        source: "iana",
        extensions: ["sldx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
        source: "iana",
        extensions: ["ppsx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.template": {
        source: "iana",
        extensions: ["potx"]
      },
      "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
        source: "iana",
        compressible: false,
        extensions: ["xlsx"]
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
        source: "iana",
        extensions: ["xltx"]
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.theme+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.themeoverride+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.vmldrawing": {
        source: "iana"
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
        source: "iana",
        compressible: false,
        extensions: ["docx"]
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
        source: "iana",
        extensions: ["dotx"]
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-package.core-properties+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.openxmlformats-package.relationships+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oracle.resource+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.orange.indata": {
        source: "iana"
      },
      "application/vnd.osa.netdeploy": {
        source: "iana"
      },
      "application/vnd.osgeo.mapguide.package": {
        source: "iana",
        extensions: ["mgp"]
      },
      "application/vnd.osgi.bundle": {
        source: "iana"
      },
      "application/vnd.osgi.dp": {
        source: "iana",
        extensions: ["dp"]
      },
      "application/vnd.osgi.subsystem": {
        source: "iana",
        extensions: ["esa"]
      },
      "application/vnd.otps.ct-kip+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.oxli.countgraph": {
        source: "iana"
      },
      "application/vnd.pagerduty+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.palm": {
        source: "iana",
        extensions: ["pdb", "pqa", "oprc"]
      },
      "application/vnd.panoply": {
        source: "iana"
      },
      "application/vnd.paos.xml": {
        source: "iana"
      },
      "application/vnd.patentdive": {
        source: "iana"
      },
      "application/vnd.patientecommsdoc": {
        source: "iana"
      },
      "application/vnd.pawaafile": {
        source: "iana",
        extensions: ["paw"]
      },
      "application/vnd.pcos": {
        source: "iana"
      },
      "application/vnd.pg.format": {
        source: "iana",
        extensions: ["str"]
      },
      "application/vnd.pg.osasli": {
        source: "iana",
        extensions: ["ei6"]
      },
      "application/vnd.piaccess.application-licence": {
        source: "iana"
      },
      "application/vnd.picsel": {
        source: "iana",
        extensions: ["efif"]
      },
      "application/vnd.pmi.widget": {
        source: "iana",
        extensions: ["wg"]
      },
      "application/vnd.poc.group-advertisement+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.pocketlearn": {
        source: "iana",
        extensions: ["plf"]
      },
      "application/vnd.powerbuilder6": {
        source: "iana",
        extensions: ["pbd"]
      },
      "application/vnd.powerbuilder6-s": {
        source: "iana"
      },
      "application/vnd.powerbuilder7": {
        source: "iana"
      },
      "application/vnd.powerbuilder7-s": {
        source: "iana"
      },
      "application/vnd.powerbuilder75": {
        source: "iana"
      },
      "application/vnd.powerbuilder75-s": {
        source: "iana"
      },
      "application/vnd.preminet": {
        source: "iana"
      },
      "application/vnd.previewsystems.box": {
        source: "iana",
        extensions: ["box"]
      },
      "application/vnd.procrate.brushset": {
        extensions: ["brushset"]
      },
      "application/vnd.procreate.brush": {
        extensions: ["brush"]
      },
      "application/vnd.procreate.dream": {
        extensions: ["drm"]
      },
      "application/vnd.proteus.magazine": {
        source: "iana",
        extensions: ["mgz"]
      },
      "application/vnd.psfs": {
        source: "iana"
      },
      "application/vnd.pt.mundusmundi": {
        source: "iana"
      },
      "application/vnd.publishare-delta-tree": {
        source: "iana",
        extensions: ["qps"]
      },
      "application/vnd.pvi.ptid1": {
        source: "iana",
        extensions: ["ptid"]
      },
      "application/vnd.pwg-multiplexed": {
        source: "iana"
      },
      "application/vnd.pwg-xhtml-print+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xhtm"]
      },
      "application/vnd.qualcomm.brew-app-res": {
        source: "iana"
      },
      "application/vnd.quarantainenet": {
        source: "iana"
      },
      "application/vnd.quark.quarkxpress": {
        source: "iana",
        extensions: ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"]
      },
      "application/vnd.quobject-quoxdocument": {
        source: "iana"
      },
      "application/vnd.radisys.moml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-conf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-conn+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-dialog+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-audit-stream+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-conf+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-base+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-fax-detect+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-group+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-speech+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.radisys.msml-dialog-transform+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.rainstor.data": {
        source: "iana"
      },
      "application/vnd.rapid": {
        source: "iana"
      },
      "application/vnd.rar": {
        source: "iana",
        extensions: ["rar"]
      },
      "application/vnd.realvnc.bed": {
        source: "iana",
        extensions: ["bed"]
      },
      "application/vnd.recordare.musicxml": {
        source: "iana",
        extensions: ["mxl"]
      },
      "application/vnd.recordare.musicxml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["musicxml"]
      },
      "application/vnd.relpipe": {
        source: "iana"
      },
      "application/vnd.renlearn.rlprint": {
        source: "iana"
      },
      "application/vnd.resilient.logic": {
        source: "iana"
      },
      "application/vnd.restful+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.rig.cryptonote": {
        source: "iana",
        extensions: ["cryptonote"]
      },
      "application/vnd.rim.cod": {
        source: "apache",
        extensions: ["cod"]
      },
      "application/vnd.rn-realmedia": {
        source: "apache",
        extensions: ["rm"]
      },
      "application/vnd.rn-realmedia-vbr": {
        source: "apache",
        extensions: ["rmvb"]
      },
      "application/vnd.route66.link66+xml": {
        source: "iana",
        compressible: true,
        extensions: ["link66"]
      },
      "application/vnd.rs-274x": {
        source: "iana"
      },
      "application/vnd.ruckus.download": {
        source: "iana"
      },
      "application/vnd.s3sms": {
        source: "iana"
      },
      "application/vnd.sailingtracker.track": {
        source: "iana",
        extensions: ["st"]
      },
      "application/vnd.sar": {
        source: "iana"
      },
      "application/vnd.sbm.cid": {
        source: "iana"
      },
      "application/vnd.sbm.mid2": {
        source: "iana"
      },
      "application/vnd.scribus": {
        source: "iana"
      },
      "application/vnd.sealed.3df": {
        source: "iana"
      },
      "application/vnd.sealed.csf": {
        source: "iana"
      },
      "application/vnd.sealed.doc": {
        source: "iana"
      },
      "application/vnd.sealed.eml": {
        source: "iana"
      },
      "application/vnd.sealed.mht": {
        source: "iana"
      },
      "application/vnd.sealed.net": {
        source: "iana"
      },
      "application/vnd.sealed.ppt": {
        source: "iana"
      },
      "application/vnd.sealed.tiff": {
        source: "iana"
      },
      "application/vnd.sealed.xls": {
        source: "iana"
      },
      "application/vnd.sealedmedia.softseal.html": {
        source: "iana"
      },
      "application/vnd.sealedmedia.softseal.pdf": {
        source: "iana"
      },
      "application/vnd.seemail": {
        source: "iana",
        extensions: ["see"]
      },
      "application/vnd.seis+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.sema": {
        source: "iana",
        extensions: ["sema"]
      },
      "application/vnd.semd": {
        source: "iana",
        extensions: ["semd"]
      },
      "application/vnd.semf": {
        source: "iana",
        extensions: ["semf"]
      },
      "application/vnd.shade-save-file": {
        source: "iana"
      },
      "application/vnd.shana.informed.formdata": {
        source: "iana",
        extensions: ["ifm"]
      },
      "application/vnd.shana.informed.formtemplate": {
        source: "iana",
        extensions: ["itp"]
      },
      "application/vnd.shana.informed.interchange": {
        source: "iana",
        extensions: ["iif"]
      },
      "application/vnd.shana.informed.package": {
        source: "iana",
        extensions: ["ipk"]
      },
      "application/vnd.shootproof+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.shopkick+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.shp": {
        source: "iana"
      },
      "application/vnd.shx": {
        source: "iana"
      },
      "application/vnd.sigrok.session": {
        source: "iana"
      },
      "application/vnd.simtech-mindmapper": {
        source: "iana",
        extensions: ["twd", "twds"]
      },
      "application/vnd.siren+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.sketchometry": {
        source: "iana"
      },
      "application/vnd.smaf": {
        source: "iana",
        extensions: ["mmf"]
      },
      "application/vnd.smart.notebook": {
        source: "iana"
      },
      "application/vnd.smart.teacher": {
        source: "iana",
        extensions: ["teacher"]
      },
      "application/vnd.smintio.portals.archive": {
        source: "iana"
      },
      "application/vnd.snesdev-page-table": {
        source: "iana"
      },
      "application/vnd.software602.filler.form+xml": {
        source: "iana",
        compressible: true,
        extensions: ["fo"]
      },
      "application/vnd.software602.filler.form-xml-zip": {
        source: "iana"
      },
      "application/vnd.solent.sdkm+xml": {
        source: "iana",
        compressible: true,
        extensions: ["sdkm", "sdkd"]
      },
      "application/vnd.spotfire.dxp": {
        source: "iana",
        extensions: ["dxp"]
      },
      "application/vnd.spotfire.sfs": {
        source: "iana",
        extensions: ["sfs"]
      },
      "application/vnd.sqlite3": {
        source: "iana"
      },
      "application/vnd.sss-cod": {
        source: "iana"
      },
      "application/vnd.sss-dtf": {
        source: "iana"
      },
      "application/vnd.sss-ntf": {
        source: "iana"
      },
      "application/vnd.stardivision.calc": {
        source: "apache",
        extensions: ["sdc"]
      },
      "application/vnd.stardivision.draw": {
        source: "apache",
        extensions: ["sda"]
      },
      "application/vnd.stardivision.impress": {
        source: "apache",
        extensions: ["sdd"]
      },
      "application/vnd.stardivision.math": {
        source: "apache",
        extensions: ["smf"]
      },
      "application/vnd.stardivision.writer": {
        source: "apache",
        extensions: ["sdw", "vor"]
      },
      "application/vnd.stardivision.writer-global": {
        source: "apache",
        extensions: ["sgl"]
      },
      "application/vnd.stepmania.package": {
        source: "iana",
        extensions: ["smzip"]
      },
      "application/vnd.stepmania.stepchart": {
        source: "iana",
        extensions: ["sm"]
      },
      "application/vnd.street-stream": {
        source: "iana"
      },
      "application/vnd.sun.wadl+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wadl"]
      },
      "application/vnd.sun.xml.calc": {
        source: "apache",
        extensions: ["sxc"]
      },
      "application/vnd.sun.xml.calc.template": {
        source: "apache",
        extensions: ["stc"]
      },
      "application/vnd.sun.xml.draw": {
        source: "apache",
        extensions: ["sxd"]
      },
      "application/vnd.sun.xml.draw.template": {
        source: "apache",
        extensions: ["std"]
      },
      "application/vnd.sun.xml.impress": {
        source: "apache",
        extensions: ["sxi"]
      },
      "application/vnd.sun.xml.impress.template": {
        source: "apache",
        extensions: ["sti"]
      },
      "application/vnd.sun.xml.math": {
        source: "apache",
        extensions: ["sxm"]
      },
      "application/vnd.sun.xml.writer": {
        source: "apache",
        extensions: ["sxw"]
      },
      "application/vnd.sun.xml.writer.global": {
        source: "apache",
        extensions: ["sxg"]
      },
      "application/vnd.sun.xml.writer.template": {
        source: "apache",
        extensions: ["stw"]
      },
      "application/vnd.sus-calendar": {
        source: "iana",
        extensions: ["sus", "susp"]
      },
      "application/vnd.svd": {
        source: "iana",
        extensions: ["svd"]
      },
      "application/vnd.swiftview-ics": {
        source: "iana"
      },
      "application/vnd.sybyl.mol2": {
        source: "iana"
      },
      "application/vnd.sycle+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.syft+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.symbian.install": {
        source: "apache",
        extensions: ["sis", "sisx"]
      },
      "application/vnd.syncml+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["xsm"]
      },
      "application/vnd.syncml.dm+wbxml": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["bdm"]
      },
      "application/vnd.syncml.dm+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["xdm"]
      },
      "application/vnd.syncml.dm.notification": {
        source: "iana"
      },
      "application/vnd.syncml.dmddf+wbxml": {
        source: "iana"
      },
      "application/vnd.syncml.dmddf+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["ddf"]
      },
      "application/vnd.syncml.dmtnds+wbxml": {
        source: "iana"
      },
      "application/vnd.syncml.dmtnds+xml": {
        source: "iana",
        charset: "UTF-8",
        compressible: true
      },
      "application/vnd.syncml.ds.notification": {
        source: "iana"
      },
      "application/vnd.tableschema+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.tao.intent-module-archive": {
        source: "iana",
        extensions: ["tao"]
      },
      "application/vnd.tcpdump.pcap": {
        source: "iana",
        extensions: ["pcap", "cap", "dmp"]
      },
      "application/vnd.think-cell.ppttc+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.tmd.mediaflex.api+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.tml": {
        source: "iana"
      },
      "application/vnd.tmobile-livetv": {
        source: "iana",
        extensions: ["tmo"]
      },
      "application/vnd.tri.onesource": {
        source: "iana"
      },
      "application/vnd.trid.tpt": {
        source: "iana",
        extensions: ["tpt"]
      },
      "application/vnd.triscape.mxs": {
        source: "iana",
        extensions: ["mxs"]
      },
      "application/vnd.trueapp": {
        source: "iana",
        extensions: ["tra"]
      },
      "application/vnd.truedoc": {
        source: "iana"
      },
      "application/vnd.ubisoft.webplayer": {
        source: "iana"
      },
      "application/vnd.ufdl": {
        source: "iana",
        extensions: ["ufd", "ufdl"]
      },
      "application/vnd.uic.osdm+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.uiq.theme": {
        source: "iana",
        extensions: ["utz"]
      },
      "application/vnd.umajin": {
        source: "iana",
        extensions: ["umj"]
      },
      "application/vnd.unity": {
        source: "iana",
        extensions: ["unityweb"]
      },
      "application/vnd.uoml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["uoml", "uo"]
      },
      "application/vnd.uplanet.alert": {
        source: "iana"
      },
      "application/vnd.uplanet.alert-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.bearer-choice": {
        source: "iana"
      },
      "application/vnd.uplanet.bearer-choice-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.cacheop": {
        source: "iana"
      },
      "application/vnd.uplanet.cacheop-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.channel": {
        source: "iana"
      },
      "application/vnd.uplanet.channel-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.list": {
        source: "iana"
      },
      "application/vnd.uplanet.list-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.listcmd": {
        source: "iana"
      },
      "application/vnd.uplanet.listcmd-wbxml": {
        source: "iana"
      },
      "application/vnd.uplanet.signal": {
        source: "iana"
      },
      "application/vnd.uri-map": {
        source: "iana"
      },
      "application/vnd.valve.source.material": {
        source: "iana"
      },
      "application/vnd.vcx": {
        source: "iana",
        extensions: ["vcx"]
      },
      "application/vnd.vd-study": {
        source: "iana"
      },
      "application/vnd.vectorworks": {
        source: "iana"
      },
      "application/vnd.vel+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.veraison.tsm-report+cbor": {
        source: "iana"
      },
      "application/vnd.veraison.tsm-report+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.verimatrix.vcas": {
        source: "iana"
      },
      "application/vnd.veritone.aion+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.veryant.thin": {
        source: "iana"
      },
      "application/vnd.ves.encrypted": {
        source: "iana"
      },
      "application/vnd.vidsoft.vidconference": {
        source: "iana"
      },
      "application/vnd.visio": {
        source: "iana",
        extensions: ["vsd", "vst", "vss", "vsw", "vsdx", "vtx"]
      },
      "application/vnd.visionary": {
        source: "iana",
        extensions: ["vis"]
      },
      "application/vnd.vividence.scriptfile": {
        source: "iana"
      },
      "application/vnd.vocalshaper.vsp4": {
        source: "iana"
      },
      "application/vnd.vsf": {
        source: "iana",
        extensions: ["vsf"]
      },
      "application/vnd.wap.sic": {
        source: "iana"
      },
      "application/vnd.wap.slc": {
        source: "iana"
      },
      "application/vnd.wap.wbxml": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["wbxml"]
      },
      "application/vnd.wap.wmlc": {
        source: "iana",
        extensions: ["wmlc"]
      },
      "application/vnd.wap.wmlscriptc": {
        source: "iana",
        extensions: ["wmlsc"]
      },
      "application/vnd.wasmflow.wafl": {
        source: "iana"
      },
      "application/vnd.webturbo": {
        source: "iana",
        extensions: ["wtb"]
      },
      "application/vnd.wfa.dpp": {
        source: "iana"
      },
      "application/vnd.wfa.p2p": {
        source: "iana"
      },
      "application/vnd.wfa.wsc": {
        source: "iana"
      },
      "application/vnd.windows.devicepairing": {
        source: "iana"
      },
      "application/vnd.wmc": {
        source: "iana"
      },
      "application/vnd.wmf.bootstrap": {
        source: "iana"
      },
      "application/vnd.wolfram.mathematica": {
        source: "iana"
      },
      "application/vnd.wolfram.mathematica.package": {
        source: "iana"
      },
      "application/vnd.wolfram.player": {
        source: "iana",
        extensions: ["nbp"]
      },
      "application/vnd.wordlift": {
        source: "iana"
      },
      "application/vnd.wordperfect": {
        source: "iana",
        extensions: ["wpd"]
      },
      "application/vnd.wqd": {
        source: "iana",
        extensions: ["wqd"]
      },
      "application/vnd.wrq-hp3000-labelled": {
        source: "iana"
      },
      "application/vnd.wt.stf": {
        source: "iana",
        extensions: ["stf"]
      },
      "application/vnd.wv.csp+wbxml": {
        source: "iana"
      },
      "application/vnd.wv.csp+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.wv.ssp+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.xacml+json": {
        source: "iana",
        compressible: true
      },
      "application/vnd.xara": {
        source: "iana",
        extensions: ["xar"]
      },
      "application/vnd.xarin.cpj": {
        source: "iana"
      },
      "application/vnd.xecrets-encrypted": {
        source: "iana"
      },
      "application/vnd.xfdl": {
        source: "iana",
        extensions: ["xfdl"]
      },
      "application/vnd.xfdl.webform": {
        source: "iana"
      },
      "application/vnd.xmi+xml": {
        source: "iana",
        compressible: true
      },
      "application/vnd.xmpie.cpkg": {
        source: "iana"
      },
      "application/vnd.xmpie.dpkg": {
        source: "iana"
      },
      "application/vnd.xmpie.plan": {
        source: "iana"
      },
      "application/vnd.xmpie.ppkg": {
        source: "iana"
      },
      "application/vnd.xmpie.xlim": {
        source: "iana"
      },
      "application/vnd.yamaha.hv-dic": {
        source: "iana",
        extensions: ["hvd"]
      },
      "application/vnd.yamaha.hv-script": {
        source: "iana",
        extensions: ["hvs"]
      },
      "application/vnd.yamaha.hv-voice": {
        source: "iana",
        extensions: ["hvp"]
      },
      "application/vnd.yamaha.openscoreformat": {
        source: "iana",
        extensions: ["osf"]
      },
      "application/vnd.yamaha.openscoreformat.osfpvg+xml": {
        source: "iana",
        compressible: true,
        extensions: ["osfpvg"]
      },
      "application/vnd.yamaha.remote-setup": {
        source: "iana"
      },
      "application/vnd.yamaha.smaf-audio": {
        source: "iana",
        extensions: ["saf"]
      },
      "application/vnd.yamaha.smaf-phrase": {
        source: "iana",
        extensions: ["spf"]
      },
      "application/vnd.yamaha.through-ngn": {
        source: "iana"
      },
      "application/vnd.yamaha.tunnel-udpencap": {
        source: "iana"
      },
      "application/vnd.yaoweme": {
        source: "iana"
      },
      "application/vnd.yellowriver-custom-menu": {
        source: "iana",
        extensions: ["cmp"]
      },
      "application/vnd.zul": {
        source: "iana",
        extensions: ["zir", "zirz"]
      },
      "application/vnd.zzazz.deck+xml": {
        source: "iana",
        compressible: true,
        extensions: ["zaz"]
      },
      "application/voicexml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["vxml"]
      },
      "application/voucher-cms+json": {
        source: "iana",
        compressible: true
      },
      "application/voucher-jws+json": {
        source: "iana",
        compressible: true
      },
      "application/vp": {
        source: "iana"
      },
      "application/vp+cose": {
        source: "iana"
      },
      "application/vp+jwt": {
        source: "iana"
      },
      "application/vq-rtcpxr": {
        source: "iana"
      },
      "application/wasm": {
        source: "iana",
        compressible: true,
        extensions: ["wasm"]
      },
      "application/watcherinfo+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wif"]
      },
      "application/webpush-options+json": {
        source: "iana",
        compressible: true
      },
      "application/whoispp-query": {
        source: "iana"
      },
      "application/whoispp-response": {
        source: "iana"
      },
      "application/widget": {
        source: "iana",
        extensions: ["wgt"]
      },
      "application/winhlp": {
        source: "apache",
        extensions: ["hlp"]
      },
      "application/wita": {
        source: "iana"
      },
      "application/wordperfect5.1": {
        source: "iana"
      },
      "application/wsdl+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wsdl"]
      },
      "application/wspolicy+xml": {
        source: "iana",
        compressible: true,
        extensions: ["wspolicy"]
      },
      "application/x-7z-compressed": {
        source: "apache",
        compressible: false,
        extensions: ["7z"]
      },
      "application/x-abiword": {
        source: "apache",
        extensions: ["abw"]
      },
      "application/x-ace-compressed": {
        source: "apache",
        extensions: ["ace"]
      },
      "application/x-amf": {
        source: "apache"
      },
      "application/x-apple-diskimage": {
        source: "apache",
        extensions: ["dmg"]
      },
      "application/x-arj": {
        compressible: false,
        extensions: ["arj"]
      },
      "application/x-authorware-bin": {
        source: "apache",
        extensions: ["aab", "x32", "u32", "vox"]
      },
      "application/x-authorware-map": {
        source: "apache",
        extensions: ["aam"]
      },
      "application/x-authorware-seg": {
        source: "apache",
        extensions: ["aas"]
      },
      "application/x-bcpio": {
        source: "apache",
        extensions: ["bcpio"]
      },
      "application/x-bdoc": {
        compressible: false,
        extensions: ["bdoc"]
      },
      "application/x-bittorrent": {
        source: "apache",
        extensions: ["torrent"]
      },
      "application/x-blender": {
        extensions: ["blend"]
      },
      "application/x-blorb": {
        source: "apache",
        extensions: ["blb", "blorb"]
      },
      "application/x-bzip": {
        source: "apache",
        compressible: false,
        extensions: ["bz"]
      },
      "application/x-bzip2": {
        source: "apache",
        compressible: false,
        extensions: ["bz2", "boz"]
      },
      "application/x-cbr": {
        source: "apache",
        extensions: ["cbr", "cba", "cbt", "cbz", "cb7"]
      },
      "application/x-cdlink": {
        source: "apache",
        extensions: ["vcd"]
      },
      "application/x-cfs-compressed": {
        source: "apache",
        extensions: ["cfs"]
      },
      "application/x-chat": {
        source: "apache",
        extensions: ["chat"]
      },
      "application/x-chess-pgn": {
        source: "apache",
        extensions: ["pgn"]
      },
      "application/x-chrome-extension": {
        extensions: ["crx"]
      },
      "application/x-cocoa": {
        source: "nginx",
        extensions: ["cco"]
      },
      "application/x-compress": {
        source: "apache"
      },
      "application/x-compressed": {
        extensions: ["rar"]
      },
      "application/x-conference": {
        source: "apache",
        extensions: ["nsc"]
      },
      "application/x-cpio": {
        source: "apache",
        extensions: ["cpio"]
      },
      "application/x-csh": {
        source: "apache",
        extensions: ["csh"]
      },
      "application/x-deb": {
        compressible: false
      },
      "application/x-debian-package": {
        source: "apache",
        extensions: ["deb", "udeb"]
      },
      "application/x-dgc-compressed": {
        source: "apache",
        extensions: ["dgc"]
      },
      "application/x-director": {
        source: "apache",
        extensions: ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"]
      },
      "application/x-doom": {
        source: "apache",
        extensions: ["wad"]
      },
      "application/x-dtbncx+xml": {
        source: "apache",
        compressible: true,
        extensions: ["ncx"]
      },
      "application/x-dtbook+xml": {
        source: "apache",
        compressible: true,
        extensions: ["dtb"]
      },
      "application/x-dtbresource+xml": {
        source: "apache",
        compressible: true,
        extensions: ["res"]
      },
      "application/x-dvi": {
        source: "apache",
        compressible: false,
        extensions: ["dvi"]
      },
      "application/x-envoy": {
        source: "apache",
        extensions: ["evy"]
      },
      "application/x-eva": {
        source: "apache",
        extensions: ["eva"]
      },
      "application/x-font-bdf": {
        source: "apache",
        extensions: ["bdf"]
      },
      "application/x-font-dos": {
        source: "apache"
      },
      "application/x-font-framemaker": {
        source: "apache"
      },
      "application/x-font-ghostscript": {
        source: "apache",
        extensions: ["gsf"]
      },
      "application/x-font-libgrx": {
        source: "apache"
      },
      "application/x-font-linux-psf": {
        source: "apache",
        extensions: ["psf"]
      },
      "application/x-font-pcf": {
        source: "apache",
        extensions: ["pcf"]
      },
      "application/x-font-snf": {
        source: "apache",
        extensions: ["snf"]
      },
      "application/x-font-speedo": {
        source: "apache"
      },
      "application/x-font-sunos-news": {
        source: "apache"
      },
      "application/x-font-type1": {
        source: "apache",
        extensions: ["pfa", "pfb", "pfm", "afm"]
      },
      "application/x-font-vfont": {
        source: "apache"
      },
      "application/x-freearc": {
        source: "apache",
        extensions: ["arc"]
      },
      "application/x-futuresplash": {
        source: "apache",
        extensions: ["spl"]
      },
      "application/x-gca-compressed": {
        source: "apache",
        extensions: ["gca"]
      },
      "application/x-glulx": {
        source: "apache",
        extensions: ["ulx"]
      },
      "application/x-gnumeric": {
        source: "apache",
        extensions: ["gnumeric"]
      },
      "application/x-gramps-xml": {
        source: "apache",
        extensions: ["gramps"]
      },
      "application/x-gtar": {
        source: "apache",
        extensions: ["gtar"]
      },
      "application/x-gzip": {
        source: "apache"
      },
      "application/x-hdf": {
        source: "apache",
        extensions: ["hdf"]
      },
      "application/x-httpd-php": {
        compressible: true,
        extensions: ["php"]
      },
      "application/x-install-instructions": {
        source: "apache",
        extensions: ["install"]
      },
      "application/x-ipynb+json": {
        compressible: true,
        extensions: ["ipynb"]
      },
      "application/x-iso9660-image": {
        source: "apache",
        extensions: ["iso"]
      },
      "application/x-iwork-keynote-sffkey": {
        extensions: ["key"]
      },
      "application/x-iwork-numbers-sffnumbers": {
        extensions: ["numbers"]
      },
      "application/x-iwork-pages-sffpages": {
        extensions: ["pages"]
      },
      "application/x-java-archive-diff": {
        source: "nginx",
        extensions: ["jardiff"]
      },
      "application/x-java-jnlp-file": {
        source: "apache",
        compressible: false,
        extensions: ["jnlp"]
      },
      "application/x-javascript": {
        compressible: true
      },
      "application/x-keepass2": {
        extensions: ["kdbx"]
      },
      "application/x-latex": {
        source: "apache",
        compressible: false,
        extensions: ["latex"]
      },
      "application/x-lua-bytecode": {
        extensions: ["luac"]
      },
      "application/x-lzh-compressed": {
        source: "apache",
        extensions: ["lzh", "lha"]
      },
      "application/x-makeself": {
        source: "nginx",
        extensions: ["run"]
      },
      "application/x-mie": {
        source: "apache",
        extensions: ["mie"]
      },
      "application/x-mobipocket-ebook": {
        source: "apache",
        extensions: ["prc", "mobi"]
      },
      "application/x-mpegurl": {
        compressible: false
      },
      "application/x-ms-application": {
        source: "apache",
        extensions: ["application"]
      },
      "application/x-ms-shortcut": {
        source: "apache",
        extensions: ["lnk"]
      },
      "application/x-ms-wmd": {
        source: "apache",
        extensions: ["wmd"]
      },
      "application/x-ms-wmz": {
        source: "apache",
        extensions: ["wmz"]
      },
      "application/x-ms-xbap": {
        source: "apache",
        extensions: ["xbap"]
      },
      "application/x-msaccess": {
        source: "apache",
        extensions: ["mdb"]
      },
      "application/x-msbinder": {
        source: "apache",
        extensions: ["obd"]
      },
      "application/x-mscardfile": {
        source: "apache",
        extensions: ["crd"]
      },
      "application/x-msclip": {
        source: "apache",
        extensions: ["clp"]
      },
      "application/x-msdos-program": {
        extensions: ["exe"]
      },
      "application/x-msdownload": {
        source: "apache",
        extensions: ["exe", "dll", "com", "bat", "msi"]
      },
      "application/x-msmediaview": {
        source: "apache",
        extensions: ["mvb", "m13", "m14"]
      },
      "application/x-msmetafile": {
        source: "apache",
        extensions: ["wmf", "wmz", "emf", "emz"]
      },
      "application/x-msmoney": {
        source: "apache",
        extensions: ["mny"]
      },
      "application/x-mspublisher": {
        source: "apache",
        extensions: ["pub"]
      },
      "application/x-msschedule": {
        source: "apache",
        extensions: ["scd"]
      },
      "application/x-msterminal": {
        source: "apache",
        extensions: ["trm"]
      },
      "application/x-mswrite": {
        source: "apache",
        extensions: ["wri"]
      },
      "application/x-netcdf": {
        source: "apache",
        extensions: ["nc", "cdf"]
      },
      "application/x-ns-proxy-autoconfig": {
        compressible: true,
        extensions: ["pac"]
      },
      "application/x-nzb": {
        source: "apache",
        extensions: ["nzb"]
      },
      "application/x-perl": {
        source: "nginx",
        extensions: ["pl", "pm"]
      },
      "application/x-pilot": {
        source: "nginx",
        extensions: ["prc", "pdb"]
      },
      "application/x-pkcs12": {
        source: "apache",
        compressible: false,
        extensions: ["p12", "pfx"]
      },
      "application/x-pkcs7-certificates": {
        source: "apache",
        extensions: ["p7b", "spc"]
      },
      "application/x-pkcs7-certreqresp": {
        source: "apache",
        extensions: ["p7r"]
      },
      "application/x-pki-message": {
        source: "iana"
      },
      "application/x-rar-compressed": {
        source: "apache",
        compressible: false,
        extensions: ["rar"]
      },
      "application/x-redhat-package-manager": {
        source: "nginx",
        extensions: ["rpm"]
      },
      "application/x-research-info-systems": {
        source: "apache",
        extensions: ["ris"]
      },
      "application/x-sea": {
        source: "nginx",
        extensions: ["sea"]
      },
      "application/x-sh": {
        source: "apache",
        compressible: true,
        extensions: ["sh"]
      },
      "application/x-shar": {
        source: "apache",
        extensions: ["shar"]
      },
      "application/x-shockwave-flash": {
        source: "apache",
        compressible: false,
        extensions: ["swf"]
      },
      "application/x-silverlight-app": {
        source: "apache",
        extensions: ["xap"]
      },
      "application/x-sql": {
        source: "apache",
        extensions: ["sql"]
      },
      "application/x-stuffit": {
        source: "apache",
        compressible: false,
        extensions: ["sit"]
      },
      "application/x-stuffitx": {
        source: "apache",
        extensions: ["sitx"]
      },
      "application/x-subrip": {
        source: "apache",
        extensions: ["srt"]
      },
      "application/x-sv4cpio": {
        source: "apache",
        extensions: ["sv4cpio"]
      },
      "application/x-sv4crc": {
        source: "apache",
        extensions: ["sv4crc"]
      },
      "application/x-t3vm-image": {
        source: "apache",
        extensions: ["t3"]
      },
      "application/x-tads": {
        source: "apache",
        extensions: ["gam"]
      },
      "application/x-tar": {
        source: "apache",
        compressible: true,
        extensions: ["tar"]
      },
      "application/x-tcl": {
        source: "apache",
        extensions: ["tcl", "tk"]
      },
      "application/x-tex": {
        source: "apache",
        extensions: ["tex"]
      },
      "application/x-tex-tfm": {
        source: "apache",
        extensions: ["tfm"]
      },
      "application/x-texinfo": {
        source: "apache",
        extensions: ["texinfo", "texi"]
      },
      "application/x-tgif": {
        source: "apache",
        extensions: ["obj"]
      },
      "application/x-ustar": {
        source: "apache",
        extensions: ["ustar"]
      },
      "application/x-virtualbox-hdd": {
        compressible: true,
        extensions: ["hdd"]
      },
      "application/x-virtualbox-ova": {
        compressible: true,
        extensions: ["ova"]
      },
      "application/x-virtualbox-ovf": {
        compressible: true,
        extensions: ["ovf"]
      },
      "application/x-virtualbox-vbox": {
        compressible: true,
        extensions: ["vbox"]
      },
      "application/x-virtualbox-vbox-extpack": {
        compressible: false,
        extensions: ["vbox-extpack"]
      },
      "application/x-virtualbox-vdi": {
        compressible: true,
        extensions: ["vdi"]
      },
      "application/x-virtualbox-vhd": {
        compressible: true,
        extensions: ["vhd"]
      },
      "application/x-virtualbox-vmdk": {
        compressible: true,
        extensions: ["vmdk"]
      },
      "application/x-wais-source": {
        source: "apache",
        extensions: ["src"]
      },
      "application/x-web-app-manifest+json": {
        compressible: true,
        extensions: ["webapp"]
      },
      "application/x-www-form-urlencoded": {
        source: "iana",
        compressible: true
      },
      "application/x-x509-ca-cert": {
        source: "iana",
        extensions: ["der", "crt", "pem"]
      },
      "application/x-x509-ca-ra-cert": {
        source: "iana"
      },
      "application/x-x509-next-ca-cert": {
        source: "iana"
      },
      "application/x-xfig": {
        source: "apache",
        extensions: ["fig"]
      },
      "application/x-xliff+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xlf"]
      },
      "application/x-xpinstall": {
        source: "apache",
        compressible: false,
        extensions: ["xpi"]
      },
      "application/x-xz": {
        source: "apache",
        extensions: ["xz"]
      },
      "application/x-zip-compressed": {
        extensions: ["zip"]
      },
      "application/x-zmachine": {
        source: "apache",
        extensions: ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"]
      },
      "application/x400-bp": {
        source: "iana"
      },
      "application/xacml+xml": {
        source: "iana",
        compressible: true
      },
      "application/xaml+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xaml"]
      },
      "application/xcap-att+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xav"]
      },
      "application/xcap-caps+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xca"]
      },
      "application/xcap-diff+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xdf"]
      },
      "application/xcap-el+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xel"]
      },
      "application/xcap-error+xml": {
        source: "iana",
        compressible: true
      },
      "application/xcap-ns+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xns"]
      },
      "application/xcon-conference-info+xml": {
        source: "iana",
        compressible: true
      },
      "application/xcon-conference-info-diff+xml": {
        source: "iana",
        compressible: true
      },
      "application/xenc+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xenc"]
      },
      "application/xfdf": {
        source: "iana",
        extensions: ["xfdf"]
      },
      "application/xhtml+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xhtml", "xht"]
      },
      "application/xhtml-voice+xml": {
        source: "apache",
        compressible: true
      },
      "application/xliff+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xlf"]
      },
      "application/xml": {
        source: "iana",
        compressible: true,
        extensions: ["xml", "xsl", "xsd", "rng"]
      },
      "application/xml-dtd": {
        source: "iana",
        compressible: true,
        extensions: ["dtd"]
      },
      "application/xml-external-parsed-entity": {
        source: "iana"
      },
      "application/xml-patch+xml": {
        source: "iana",
        compressible: true
      },
      "application/xmpp+xml": {
        source: "iana",
        compressible: true
      },
      "application/xop+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xop"]
      },
      "application/xproc+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xpl"]
      },
      "application/xslt+xml": {
        source: "iana",
        compressible: true,
        extensions: ["xsl", "xslt"]
      },
      "application/xspf+xml": {
        source: "apache",
        compressible: true,
        extensions: ["xspf"]
      },
      "application/xv+xml": {
        source: "iana",
        compressible: true,
        extensions: ["mxml", "xhvml", "xvml", "xvm"]
      },
      "application/yaml": {
        source: "iana"
      },
      "application/yang": {
        source: "iana",
        extensions: ["yang"]
      },
      "application/yang-data+cbor": {
        source: "iana"
      },
      "application/yang-data+json": {
        source: "iana",
        compressible: true
      },
      "application/yang-data+xml": {
        source: "iana",
        compressible: true
      },
      "application/yang-patch+json": {
        source: "iana",
        compressible: true
      },
      "application/yang-patch+xml": {
        source: "iana",
        compressible: true
      },
      "application/yang-sid+json": {
        source: "iana",
        compressible: true
      },
      "application/yin+xml": {
        source: "iana",
        compressible: true,
        extensions: ["yin"]
      },
      "application/zip": {
        source: "iana",
        compressible: false,
        extensions: ["zip"]
      },
      "application/zip+dotlottie": {
        extensions: ["lottie"]
      },
      "application/zlib": {
        source: "iana"
      },
      "application/zstd": {
        source: "iana"
      },
      "audio/1d-interleaved-parityfec": {
        source: "iana"
      },
      "audio/32kadpcm": {
        source: "iana"
      },
      "audio/3gpp": {
        source: "iana",
        compressible: false,
        extensions: ["3gpp"]
      },
      "audio/3gpp2": {
        source: "iana"
      },
      "audio/aac": {
        source: "iana",
        extensions: ["adts", "aac"]
      },
      "audio/ac3": {
        source: "iana"
      },
      "audio/adpcm": {
        source: "apache",
        extensions: ["adp"]
      },
      "audio/amr": {
        source: "iana",
        extensions: ["amr"]
      },
      "audio/amr-wb": {
        source: "iana"
      },
      "audio/amr-wb+": {
        source: "iana"
      },
      "audio/aptx": {
        source: "iana"
      },
      "audio/asc": {
        source: "iana"
      },
      "audio/atrac-advanced-lossless": {
        source: "iana"
      },
      "audio/atrac-x": {
        source: "iana"
      },
      "audio/atrac3": {
        source: "iana"
      },
      "audio/basic": {
        source: "iana",
        compressible: false,
        extensions: ["au", "snd"]
      },
      "audio/bv16": {
        source: "iana"
      },
      "audio/bv32": {
        source: "iana"
      },
      "audio/clearmode": {
        source: "iana"
      },
      "audio/cn": {
        source: "iana"
      },
      "audio/dat12": {
        source: "iana"
      },
      "audio/dls": {
        source: "iana"
      },
      "audio/dsr-es201108": {
        source: "iana"
      },
      "audio/dsr-es202050": {
        source: "iana"
      },
      "audio/dsr-es202211": {
        source: "iana"
      },
      "audio/dsr-es202212": {
        source: "iana"
      },
      "audio/dv": {
        source: "iana"
      },
      "audio/dvi4": {
        source: "iana"
      },
      "audio/eac3": {
        source: "iana"
      },
      "audio/encaprtp": {
        source: "iana"
      },
      "audio/evrc": {
        source: "iana"
      },
      "audio/evrc-qcp": {
        source: "iana"
      },
      "audio/evrc0": {
        source: "iana"
      },
      "audio/evrc1": {
        source: "iana"
      },
      "audio/evrcb": {
        source: "iana"
      },
      "audio/evrcb0": {
        source: "iana"
      },
      "audio/evrcb1": {
        source: "iana"
      },
      "audio/evrcnw": {
        source: "iana"
      },
      "audio/evrcnw0": {
        source: "iana"
      },
      "audio/evrcnw1": {
        source: "iana"
      },
      "audio/evrcwb": {
        source: "iana"
      },
      "audio/evrcwb0": {
        source: "iana"
      },
      "audio/evrcwb1": {
        source: "iana"
      },
      "audio/evs": {
        source: "iana"
      },
      "audio/flac": {
        source: "iana"
      },
      "audio/flexfec": {
        source: "iana"
      },
      "audio/fwdred": {
        source: "iana"
      },
      "audio/g711-0": {
        source: "iana"
      },
      "audio/g719": {
        source: "iana"
      },
      "audio/g722": {
        source: "iana"
      },
      "audio/g7221": {
        source: "iana"
      },
      "audio/g723": {
        source: "iana"
      },
      "audio/g726-16": {
        source: "iana"
      },
      "audio/g726-24": {
        source: "iana"
      },
      "audio/g726-32": {
        source: "iana"
      },
      "audio/g726-40": {
        source: "iana"
      },
      "audio/g728": {
        source: "iana"
      },
      "audio/g729": {
        source: "iana"
      },
      "audio/g7291": {
        source: "iana"
      },
      "audio/g729d": {
        source: "iana"
      },
      "audio/g729e": {
        source: "iana"
      },
      "audio/gsm": {
        source: "iana"
      },
      "audio/gsm-efr": {
        source: "iana"
      },
      "audio/gsm-hr-08": {
        source: "iana"
      },
      "audio/ilbc": {
        source: "iana"
      },
      "audio/ip-mr_v2.5": {
        source: "iana"
      },
      "audio/isac": {
        source: "apache"
      },
      "audio/l16": {
        source: "iana"
      },
      "audio/l20": {
        source: "iana"
      },
      "audio/l24": {
        source: "iana",
        compressible: false
      },
      "audio/l8": {
        source: "iana"
      },
      "audio/lpc": {
        source: "iana"
      },
      "audio/matroska": {
        source: "iana"
      },
      "audio/melp": {
        source: "iana"
      },
      "audio/melp1200": {
        source: "iana"
      },
      "audio/melp2400": {
        source: "iana"
      },
      "audio/melp600": {
        source: "iana"
      },
      "audio/mhas": {
        source: "iana"
      },
      "audio/midi": {
        source: "apache",
        extensions: ["mid", "midi", "kar", "rmi"]
      },
      "audio/midi-clip": {
        source: "iana"
      },
      "audio/mobile-xmf": {
        source: "iana",
        extensions: ["mxmf"]
      },
      "audio/mp3": {
        compressible: false,
        extensions: ["mp3"]
      },
      "audio/mp4": {
        source: "iana",
        compressible: false,
        extensions: ["m4a", "mp4a", "m4b"]
      },
      "audio/mp4a-latm": {
        source: "iana"
      },
      "audio/mpa": {
        source: "iana"
      },
      "audio/mpa-robust": {
        source: "iana"
      },
      "audio/mpeg": {
        source: "iana",
        compressible: false,
        extensions: ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"]
      },
      "audio/mpeg4-generic": {
        source: "iana"
      },
      "audio/musepack": {
        source: "apache"
      },
      "audio/ogg": {
        source: "iana",
        compressible: false,
        extensions: ["oga", "ogg", "spx", "opus"]
      },
      "audio/opus": {
        source: "iana"
      },
      "audio/parityfec": {
        source: "iana"
      },
      "audio/pcma": {
        source: "iana"
      },
      "audio/pcma-wb": {
        source: "iana"
      },
      "audio/pcmu": {
        source: "iana"
      },
      "audio/pcmu-wb": {
        source: "iana"
      },
      "audio/prs.sid": {
        source: "iana"
      },
      "audio/qcelp": {
        source: "iana"
      },
      "audio/raptorfec": {
        source: "iana"
      },
      "audio/red": {
        source: "iana"
      },
      "audio/rtp-enc-aescm128": {
        source: "iana"
      },
      "audio/rtp-midi": {
        source: "iana"
      },
      "audio/rtploopback": {
        source: "iana"
      },
      "audio/rtx": {
        source: "iana"
      },
      "audio/s3m": {
        source: "apache",
        extensions: ["s3m"]
      },
      "audio/scip": {
        source: "iana"
      },
      "audio/silk": {
        source: "apache",
        extensions: ["sil"]
      },
      "audio/smv": {
        source: "iana"
      },
      "audio/smv-qcp": {
        source: "iana"
      },
      "audio/smv0": {
        source: "iana"
      },
      "audio/sofa": {
        source: "iana"
      },
      "audio/sp-midi": {
        source: "iana"
      },
      "audio/speex": {
        source: "iana"
      },
      "audio/t140c": {
        source: "iana"
      },
      "audio/t38": {
        source: "iana"
      },
      "audio/telephone-event": {
        source: "iana"
      },
      "audio/tetra_acelp": {
        source: "iana"
      },
      "audio/tetra_acelp_bb": {
        source: "iana"
      },
      "audio/tone": {
        source: "iana"
      },
      "audio/tsvcis": {
        source: "iana"
      },
      "audio/uemclip": {
        source: "iana"
      },
      "audio/ulpfec": {
        source: "iana"
      },
      "audio/usac": {
        source: "iana"
      },
      "audio/vdvi": {
        source: "iana"
      },
      "audio/vmr-wb": {
        source: "iana"
      },
      "audio/vnd.3gpp.iufp": {
        source: "iana"
      },
      "audio/vnd.4sb": {
        source: "iana"
      },
      "audio/vnd.audiokoz": {
        source: "iana"
      },
      "audio/vnd.celp": {
        source: "iana"
      },
      "audio/vnd.cisco.nse": {
        source: "iana"
      },
      "audio/vnd.cmles.radio-events": {
        source: "iana"
      },
      "audio/vnd.cns.anp1": {
        source: "iana"
      },
      "audio/vnd.cns.inf1": {
        source: "iana"
      },
      "audio/vnd.dece.audio": {
        source: "iana",
        extensions: ["uva", "uvva"]
      },
      "audio/vnd.digital-winds": {
        source: "iana",
        extensions: ["eol"]
      },
      "audio/vnd.dlna.adts": {
        source: "iana"
      },
      "audio/vnd.dolby.heaac.1": {
        source: "iana"
      },
      "audio/vnd.dolby.heaac.2": {
        source: "iana"
      },
      "audio/vnd.dolby.mlp": {
        source: "iana"
      },
      "audio/vnd.dolby.mps": {
        source: "iana"
      },
      "audio/vnd.dolby.pl2": {
        source: "iana"
      },
      "audio/vnd.dolby.pl2x": {
        source: "iana"
      },
      "audio/vnd.dolby.pl2z": {
        source: "iana"
      },
      "audio/vnd.dolby.pulse.1": {
        source: "iana"
      },
      "audio/vnd.dra": {
        source: "iana",
        extensions: ["dra"]
      },
      "audio/vnd.dts": {
        source: "iana",
        extensions: ["dts"]
      },
      "audio/vnd.dts.hd": {
        source: "iana",
        extensions: ["dtshd"]
      },
      "audio/vnd.dts.uhd": {
        source: "iana"
      },
      "audio/vnd.dvb.file": {
        source: "iana"
      },
      "audio/vnd.everad.plj": {
        source: "iana"
      },
      "audio/vnd.hns.audio": {
        source: "iana"
      },
      "audio/vnd.lucent.voice": {
        source: "iana",
        extensions: ["lvp"]
      },
      "audio/vnd.ms-playready.media.pya": {
        source: "iana",
        extensions: ["pya"]
      },
      "audio/vnd.nokia.mobile-xmf": {
        source: "iana"
      },
      "audio/vnd.nortel.vbk": {
        source: "iana"
      },
      "audio/vnd.nuera.ecelp4800": {
        source: "iana",
        extensions: ["ecelp4800"]
      },
      "audio/vnd.nuera.ecelp7470": {
        source: "iana",
        extensions: ["ecelp7470"]
      },
      "audio/vnd.nuera.ecelp9600": {
        source: "iana",
        extensions: ["ecelp9600"]
      },
      "audio/vnd.octel.sbc": {
        source: "iana"
      },
      "audio/vnd.presonus.multitrack": {
        source: "iana"
      },
      "audio/vnd.qcelp": {
        source: "apache"
      },
      "audio/vnd.rhetorex.32kadpcm": {
        source: "iana"
      },
      "audio/vnd.rip": {
        source: "iana",
        extensions: ["rip"]
      },
      "audio/vnd.rn-realaudio": {
        compressible: false
      },
      "audio/vnd.sealedmedia.softseal.mpeg": {
        source: "iana"
      },
      "audio/vnd.vmx.cvsd": {
        source: "iana"
      },
      "audio/vnd.wave": {
        compressible: false
      },
      "audio/vorbis": {
        source: "iana",
        compressible: false
      },
      "audio/vorbis-config": {
        source: "iana"
      },
      "audio/wav": {
        compressible: false,
        extensions: ["wav"]
      },
      "audio/wave": {
        compressible: false,
        extensions: ["wav"]
      },
      "audio/webm": {
        source: "apache",
        compressible: false,
        extensions: ["weba"]
      },
      "audio/x-aac": {
        source: "apache",
        compressible: false,
        extensions: ["aac"]
      },
      "audio/x-aiff": {
        source: "apache",
        extensions: ["aif", "aiff", "aifc"]
      },
      "audio/x-caf": {
        source: "apache",
        compressible: false,
        extensions: ["caf"]
      },
      "audio/x-flac": {
        source: "apache",
        extensions: ["flac"]
      },
      "audio/x-m4a": {
        source: "nginx",
        extensions: ["m4a"]
      },
      "audio/x-matroska": {
        source: "apache",
        extensions: ["mka"]
      },
      "audio/x-mpegurl": {
        source: "apache",
        extensions: ["m3u"]
      },
      "audio/x-ms-wax": {
        source: "apache",
        extensions: ["wax"]
      },
      "audio/x-ms-wma": {
        source: "apache",
        extensions: ["wma"]
      },
      "audio/x-pn-realaudio": {
        source: "apache",
        extensions: ["ram", "ra"]
      },
      "audio/x-pn-realaudio-plugin": {
        source: "apache",
        extensions: ["rmp"]
      },
      "audio/x-realaudio": {
        source: "nginx",
        extensions: ["ra"]
      },
      "audio/x-tta": {
        source: "apache"
      },
      "audio/x-wav": {
        source: "apache",
        extensions: ["wav"]
      },
      "audio/xm": {
        source: "apache",
        extensions: ["xm"]
      },
      "chemical/x-cdx": {
        source: "apache",
        extensions: ["cdx"]
      },
      "chemical/x-cif": {
        source: "apache",
        extensions: ["cif"]
      },
      "chemical/x-cmdf": {
        source: "apache",
        extensions: ["cmdf"]
      },
      "chemical/x-cml": {
        source: "apache",
        extensions: ["cml"]
      },
      "chemical/x-csml": {
        source: "apache",
        extensions: ["csml"]
      },
      "chemical/x-pdb": {
        source: "apache"
      },
      "chemical/x-xyz": {
        source: "apache",
        extensions: ["xyz"]
      },
      "font/collection": {
        source: "iana",
        extensions: ["ttc"]
      },
      "font/otf": {
        source: "iana",
        compressible: true,
        extensions: ["otf"]
      },
      "font/sfnt": {
        source: "iana"
      },
      "font/ttf": {
        source: "iana",
        compressible: true,
        extensions: ["ttf"]
      },
      "font/woff": {
        source: "iana",
        extensions: ["woff"]
      },
      "font/woff2": {
        source: "iana",
        extensions: ["woff2"]
      },
      "image/aces": {
        source: "iana",
        extensions: ["exr"]
      },
      "image/apng": {
        source: "iana",
        compressible: false,
        extensions: ["apng"]
      },
      "image/avci": {
        source: "iana",
        extensions: ["avci"]
      },
      "image/avcs": {
        source: "iana",
        extensions: ["avcs"]
      },
      "image/avif": {
        source: "iana",
        compressible: false,
        extensions: ["avif"]
      },
      "image/bmp": {
        source: "iana",
        compressible: true,
        extensions: ["bmp", "dib"]
      },
      "image/cgm": {
        source: "iana",
        extensions: ["cgm"]
      },
      "image/dicom-rle": {
        source: "iana",
        extensions: ["drle"]
      },
      "image/dpx": {
        source: "iana",
        extensions: ["dpx"]
      },
      "image/emf": {
        source: "iana",
        extensions: ["emf"]
      },
      "image/fits": {
        source: "iana",
        extensions: ["fits"]
      },
      "image/g3fax": {
        source: "iana",
        extensions: ["g3"]
      },
      "image/gif": {
        source: "iana",
        compressible: false,
        extensions: ["gif"]
      },
      "image/heic": {
        source: "iana",
        extensions: ["heic"]
      },
      "image/heic-sequence": {
        source: "iana",
        extensions: ["heics"]
      },
      "image/heif": {
        source: "iana",
        extensions: ["heif"]
      },
      "image/heif-sequence": {
        source: "iana",
        extensions: ["heifs"]
      },
      "image/hej2k": {
        source: "iana",
        extensions: ["hej2"]
      },
      "image/ief": {
        source: "iana",
        extensions: ["ief"]
      },
      "image/j2c": {
        source: "iana"
      },
      "image/jaii": {
        source: "iana",
        extensions: ["jaii"]
      },
      "image/jais": {
        source: "iana",
        extensions: ["jais"]
      },
      "image/jls": {
        source: "iana",
        extensions: ["jls"]
      },
      "image/jp2": {
        source: "iana",
        compressible: false,
        extensions: ["jp2", "jpg2"]
      },
      "image/jpeg": {
        source: "iana",
        compressible: false,
        extensions: ["jpg", "jpeg", "jpe"]
      },
      "image/jph": {
        source: "iana",
        extensions: ["jph"]
      },
      "image/jphc": {
        source: "iana",
        extensions: ["jhc"]
      },
      "image/jpm": {
        source: "iana",
        compressible: false,
        extensions: ["jpm", "jpgm"]
      },
      "image/jpx": {
        source: "iana",
        compressible: false,
        extensions: ["jpx", "jpf"]
      },
      "image/jxl": {
        source: "iana",
        extensions: ["jxl"]
      },
      "image/jxr": {
        source: "iana",
        extensions: ["jxr"]
      },
      "image/jxra": {
        source: "iana",
        extensions: ["jxra"]
      },
      "image/jxrs": {
        source: "iana",
        extensions: ["jxrs"]
      },
      "image/jxs": {
        source: "iana",
        extensions: ["jxs"]
      },
      "image/jxsc": {
        source: "iana",
        extensions: ["jxsc"]
      },
      "image/jxsi": {
        source: "iana",
        extensions: ["jxsi"]
      },
      "image/jxss": {
        source: "iana",
        extensions: ["jxss"]
      },
      "image/ktx": {
        source: "iana",
        extensions: ["ktx"]
      },
      "image/ktx2": {
        source: "iana",
        extensions: ["ktx2"]
      },
      "image/naplps": {
        source: "iana"
      },
      "image/pjpeg": {
        compressible: false,
        extensions: ["jfif"]
      },
      "image/png": {
        source: "iana",
        compressible: false,
        extensions: ["png"]
      },
      "image/prs.btif": {
        source: "iana",
        extensions: ["btif", "btf"]
      },
      "image/prs.pti": {
        source: "iana",
        extensions: ["pti"]
      },
      "image/pwg-raster": {
        source: "iana"
      },
      "image/sgi": {
        source: "apache",
        extensions: ["sgi"]
      },
      "image/svg+xml": {
        source: "iana",
        compressible: true,
        extensions: ["svg", "svgz"]
      },
      "image/t38": {
        source: "iana",
        extensions: ["t38"]
      },
      "image/tiff": {
        source: "iana",
        compressible: false,
        extensions: ["tif", "tiff"]
      },
      "image/tiff-fx": {
        source: "iana",
        extensions: ["tfx"]
      },
      "image/vnd.adobe.photoshop": {
        source: "iana",
        compressible: true,
        extensions: ["psd"]
      },
      "image/vnd.airzip.accelerator.azv": {
        source: "iana",
        extensions: ["azv"]
      },
      "image/vnd.clip": {
        source: "iana"
      },
      "image/vnd.cns.inf2": {
        source: "iana"
      },
      "image/vnd.dece.graphic": {
        source: "iana",
        extensions: ["uvi", "uvvi", "uvg", "uvvg"]
      },
      "image/vnd.djvu": {
        source: "iana",
        extensions: ["djvu", "djv"]
      },
      "image/vnd.dvb.subtitle": {
        source: "iana",
        extensions: ["sub"]
      },
      "image/vnd.dwg": {
        source: "iana",
        extensions: ["dwg"]
      },
      "image/vnd.dxf": {
        source: "iana",
        extensions: ["dxf"]
      },
      "image/vnd.fastbidsheet": {
        source: "iana",
        extensions: ["fbs"]
      },
      "image/vnd.fpx": {
        source: "iana",
        extensions: ["fpx"]
      },
      "image/vnd.fst": {
        source: "iana",
        extensions: ["fst"]
      },
      "image/vnd.fujixerox.edmics-mmr": {
        source: "iana",
        extensions: ["mmr"]
      },
      "image/vnd.fujixerox.edmics-rlc": {
        source: "iana",
        extensions: ["rlc"]
      },
      "image/vnd.globalgraphics.pgb": {
        source: "iana"
      },
      "image/vnd.microsoft.icon": {
        source: "iana",
        compressible: true,
        extensions: ["ico"]
      },
      "image/vnd.mix": {
        source: "iana"
      },
      "image/vnd.mozilla.apng": {
        source: "iana"
      },
      "image/vnd.ms-dds": {
        compressible: true,
        extensions: ["dds"]
      },
      "image/vnd.ms-modi": {
        source: "iana",
        extensions: ["mdi"]
      },
      "image/vnd.ms-photo": {
        source: "apache",
        extensions: ["wdp"]
      },
      "image/vnd.net-fpx": {
        source: "iana",
        extensions: ["npx"]
      },
      "image/vnd.pco.b16": {
        source: "iana",
        extensions: ["b16"]
      },
      "image/vnd.radiance": {
        source: "iana"
      },
      "image/vnd.sealed.png": {
        source: "iana"
      },
      "image/vnd.sealedmedia.softseal.gif": {
        source: "iana"
      },
      "image/vnd.sealedmedia.softseal.jpg": {
        source: "iana"
      },
      "image/vnd.svf": {
        source: "iana"
      },
      "image/vnd.tencent.tap": {
        source: "iana",
        extensions: ["tap"]
      },
      "image/vnd.valve.source.texture": {
        source: "iana",
        extensions: ["vtf"]
      },
      "image/vnd.wap.wbmp": {
        source: "iana",
        extensions: ["wbmp"]
      },
      "image/vnd.xiff": {
        source: "iana",
        extensions: ["xif"]
      },
      "image/vnd.zbrush.pcx": {
        source: "iana",
        extensions: ["pcx"]
      },
      "image/webp": {
        source: "iana",
        extensions: ["webp"]
      },
      "image/wmf": {
        source: "iana",
        extensions: ["wmf"]
      },
      "image/x-3ds": {
        source: "apache",
        extensions: ["3ds"]
      },
      "image/x-adobe-dng": {
        extensions: ["dng"]
      },
      "image/x-cmu-raster": {
        source: "apache",
        extensions: ["ras"]
      },
      "image/x-cmx": {
        source: "apache",
        extensions: ["cmx"]
      },
      "image/x-emf": {
        source: "iana"
      },
      "image/x-freehand": {
        source: "apache",
        extensions: ["fh", "fhc", "fh4", "fh5", "fh7"]
      },
      "image/x-icon": {
        source: "apache",
        compressible: true,
        extensions: ["ico"]
      },
      "image/x-jng": {
        source: "nginx",
        extensions: ["jng"]
      },
      "image/x-mrsid-image": {
        source: "apache",
        extensions: ["sid"]
      },
      "image/x-ms-bmp": {
        source: "nginx",
        compressible: true,
        extensions: ["bmp"]
      },
      "image/x-pcx": {
        source: "apache",
        extensions: ["pcx"]
      },
      "image/x-pict": {
        source: "apache",
        extensions: ["pic", "pct"]
      },
      "image/x-portable-anymap": {
        source: "apache",
        extensions: ["pnm"]
      },
      "image/x-portable-bitmap": {
        source: "apache",
        extensions: ["pbm"]
      },
      "image/x-portable-graymap": {
        source: "apache",
        extensions: ["pgm"]
      },
      "image/x-portable-pixmap": {
        source: "apache",
        extensions: ["ppm"]
      },
      "image/x-rgb": {
        source: "apache",
        extensions: ["rgb"]
      },
      "image/x-tga": {
        source: "apache",
        extensions: ["tga"]
      },
      "image/x-wmf": {
        source: "iana"
      },
      "image/x-xbitmap": {
        source: "apache",
        extensions: ["xbm"]
      },
      "image/x-xcf": {
        compressible: false
      },
      "image/x-xpixmap": {
        source: "apache",
        extensions: ["xpm"]
      },
      "image/x-xwindowdump": {
        source: "apache",
        extensions: ["xwd"]
      },
      "message/bhttp": {
        source: "iana"
      },
      "message/cpim": {
        source: "iana"
      },
      "message/delivery-status": {
        source: "iana"
      },
      "message/disposition-notification": {
        source: "iana",
        extensions: [
          "disposition-notification"
        ]
      },
      "message/external-body": {
        source: "iana"
      },
      "message/feedback-report": {
        source: "iana"
      },
      "message/global": {
        source: "iana",
        extensions: ["u8msg"]
      },
      "message/global-delivery-status": {
        source: "iana",
        extensions: ["u8dsn"]
      },
      "message/global-disposition-notification": {
        source: "iana",
        extensions: ["u8mdn"]
      },
      "message/global-headers": {
        source: "iana",
        extensions: ["u8hdr"]
      },
      "message/http": {
        source: "iana",
        compressible: false
      },
      "message/imdn+xml": {
        source: "iana",
        compressible: true
      },
      "message/mls": {
        source: "iana"
      },
      "message/news": {
        source: "apache"
      },
      "message/ohttp-req": {
        source: "iana"
      },
      "message/ohttp-res": {
        source: "iana"
      },
      "message/partial": {
        source: "iana",
        compressible: false
      },
      "message/rfc822": {
        source: "iana",
        compressible: true,
        extensions: ["eml", "mime", "mht", "mhtml"]
      },
      "message/s-http": {
        source: "apache"
      },
      "message/sip": {
        source: "iana"
      },
      "message/sipfrag": {
        source: "iana"
      },
      "message/tracking-status": {
        source: "iana"
      },
      "message/vnd.si.simp": {
        source: "apache"
      },
      "message/vnd.wfa.wsc": {
        source: "iana",
        extensions: ["wsc"]
      },
      "model/3mf": {
        source: "iana",
        extensions: ["3mf"]
      },
      "model/e57": {
        source: "iana"
      },
      "model/gltf+json": {
        source: "iana",
        compressible: true,
        extensions: ["gltf"]
      },
      "model/gltf-binary": {
        source: "iana",
        compressible: true,
        extensions: ["glb"]
      },
      "model/iges": {
        source: "iana",
        compressible: false,
        extensions: ["igs", "iges"]
      },
      "model/jt": {
        source: "iana",
        extensions: ["jt"]
      },
      "model/mesh": {
        source: "iana",
        compressible: false,
        extensions: ["msh", "mesh", "silo"]
      },
      "model/mtl": {
        source: "iana",
        extensions: ["mtl"]
      },
      "model/obj": {
        source: "iana",
        extensions: ["obj"]
      },
      "model/prc": {
        source: "iana",
        extensions: ["prc"]
      },
      "model/step": {
        source: "iana",
        extensions: ["step", "stp", "stpnc", "p21", "210"]
      },
      "model/step+xml": {
        source: "iana",
        compressible: true,
        extensions: ["stpx"]
      },
      "model/step+zip": {
        source: "iana",
        compressible: false,
        extensions: ["stpz"]
      },
      "model/step-xml+zip": {
        source: "iana",
        compressible: false,
        extensions: ["stpxz"]
      },
      "model/stl": {
        source: "iana",
        extensions: ["stl"]
      },
      "model/u3d": {
        source: "iana",
        extensions: ["u3d"]
      },
      "model/vnd.bary": {
        source: "iana",
        extensions: ["bary"]
      },
      "model/vnd.cld": {
        source: "iana",
        extensions: ["cld"]
      },
      "model/vnd.collada+xml": {
        source: "iana",
        compressible: true,
        extensions: ["dae"]
      },
      "model/vnd.dwf": {
        source: "iana",
        extensions: ["dwf"]
      },
      "model/vnd.flatland.3dml": {
        source: "iana"
      },
      "model/vnd.gdl": {
        source: "iana",
        extensions: ["gdl"]
      },
      "model/vnd.gs-gdl": {
        source: "apache"
      },
      "model/vnd.gs.gdl": {
        source: "iana"
      },
      "model/vnd.gtw": {
        source: "iana",
        extensions: ["gtw"]
      },
      "model/vnd.moml+xml": {
        source: "iana",
        compressible: true
      },
      "model/vnd.mts": {
        source: "iana",
        extensions: ["mts"]
      },
      "model/vnd.opengex": {
        source: "iana",
        extensions: ["ogex"]
      },
      "model/vnd.parasolid.transmit.binary": {
        source: "iana",
        extensions: ["x_b"]
      },
      "model/vnd.parasolid.transmit.text": {
        source: "iana",
        extensions: ["x_t"]
      },
      "model/vnd.pytha.pyox": {
        source: "iana",
        extensions: ["pyo", "pyox"]
      },
      "model/vnd.rosette.annotated-data-model": {
        source: "iana"
      },
      "model/vnd.sap.vds": {
        source: "iana",
        extensions: ["vds"]
      },
      "model/vnd.usda": {
        source: "iana",
        extensions: ["usda"]
      },
      "model/vnd.usdz+zip": {
        source: "iana",
        compressible: false,
        extensions: ["usdz"]
      },
      "model/vnd.valve.source.compiled-map": {
        source: "iana",
        extensions: ["bsp"]
      },
      "model/vnd.vtu": {
        source: "iana",
        extensions: ["vtu"]
      },
      "model/vrml": {
        source: "iana",
        compressible: false,
        extensions: ["wrl", "vrml"]
      },
      "model/x3d+binary": {
        source: "apache",
        compressible: false,
        extensions: ["x3db", "x3dbz"]
      },
      "model/x3d+fastinfoset": {
        source: "iana",
        extensions: ["x3db"]
      },
      "model/x3d+vrml": {
        source: "apache",
        compressible: false,
        extensions: ["x3dv", "x3dvz"]
      },
      "model/x3d+xml": {
        source: "iana",
        compressible: true,
        extensions: ["x3d", "x3dz"]
      },
      "model/x3d-vrml": {
        source: "iana",
        extensions: ["x3dv"]
      },
      "multipart/alternative": {
        source: "iana",
        compressible: false
      },
      "multipart/appledouble": {
        source: "iana"
      },
      "multipart/byteranges": {
        source: "iana"
      },
      "multipart/digest": {
        source: "iana"
      },
      "multipart/encrypted": {
        source: "iana",
        compressible: false
      },
      "multipart/form-data": {
        source: "iana",
        compressible: false
      },
      "multipart/header-set": {
        source: "iana"
      },
      "multipart/mixed": {
        source: "iana"
      },
      "multipart/multilingual": {
        source: "iana"
      },
      "multipart/parallel": {
        source: "iana"
      },
      "multipart/related": {
        source: "iana",
        compressible: false
      },
      "multipart/report": {
        source: "iana"
      },
      "multipart/signed": {
        source: "iana",
        compressible: false
      },
      "multipart/vnd.bint.med-plus": {
        source: "iana"
      },
      "multipart/voice-message": {
        source: "iana"
      },
      "multipart/x-mixed-replace": {
        source: "iana"
      },
      "text/1d-interleaved-parityfec": {
        source: "iana"
      },
      "text/cache-manifest": {
        source: "iana",
        compressible: true,
        extensions: ["appcache", "manifest"]
      },
      "text/calendar": {
        source: "iana",
        extensions: ["ics", "ifb"]
      },
      "text/calender": {
        compressible: true
      },
      "text/cmd": {
        compressible: true
      },
      "text/coffeescript": {
        extensions: ["coffee", "litcoffee"]
      },
      "text/cql": {
        source: "iana"
      },
      "text/cql-expression": {
        source: "iana"
      },
      "text/cql-identifier": {
        source: "iana"
      },
      "text/css": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["css"]
      },
      "text/csv": {
        source: "iana",
        compressible: true,
        extensions: ["csv"]
      },
      "text/csv-schema": {
        source: "iana"
      },
      "text/directory": {
        source: "iana"
      },
      "text/dns": {
        source: "iana"
      },
      "text/ecmascript": {
        source: "apache"
      },
      "text/encaprtp": {
        source: "iana"
      },
      "text/enriched": {
        source: "iana"
      },
      "text/fhirpath": {
        source: "iana"
      },
      "text/flexfec": {
        source: "iana"
      },
      "text/fwdred": {
        source: "iana"
      },
      "text/gff3": {
        source: "iana"
      },
      "text/grammar-ref-list": {
        source: "iana"
      },
      "text/hl7v2": {
        source: "iana"
      },
      "text/html": {
        source: "iana",
        compressible: true,
        extensions: ["html", "htm", "shtml"]
      },
      "text/jade": {
        extensions: ["jade"]
      },
      "text/javascript": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["js", "mjs"]
      },
      "text/jcr-cnd": {
        source: "iana"
      },
      "text/jsx": {
        compressible: true,
        extensions: ["jsx"]
      },
      "text/less": {
        compressible: true,
        extensions: ["less"]
      },
      "text/markdown": {
        source: "iana",
        compressible: true,
        extensions: ["md", "markdown"]
      },
      "text/mathml": {
        source: "nginx",
        extensions: ["mml"]
      },
      "text/mdx": {
        compressible: true,
        extensions: ["mdx"]
      },
      "text/mizar": {
        source: "iana"
      },
      "text/n3": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["n3"]
      },
      "text/parameters": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/parityfec": {
        source: "iana"
      },
      "text/plain": {
        source: "iana",
        compressible: true,
        extensions: ["txt", "text", "conf", "def", "list", "log", "in", "ini"]
      },
      "text/provenance-notation": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/prs.fallenstein.rst": {
        source: "iana"
      },
      "text/prs.lines.tag": {
        source: "iana",
        extensions: ["dsc"]
      },
      "text/prs.prop.logic": {
        source: "iana"
      },
      "text/prs.texi": {
        source: "iana"
      },
      "text/raptorfec": {
        source: "iana"
      },
      "text/red": {
        source: "iana"
      },
      "text/rfc822-headers": {
        source: "iana"
      },
      "text/richtext": {
        source: "iana",
        compressible: true,
        extensions: ["rtx"]
      },
      "text/rtf": {
        source: "iana",
        compressible: true,
        extensions: ["rtf"]
      },
      "text/rtp-enc-aescm128": {
        source: "iana"
      },
      "text/rtploopback": {
        source: "iana"
      },
      "text/rtx": {
        source: "iana"
      },
      "text/sgml": {
        source: "iana",
        extensions: ["sgml", "sgm"]
      },
      "text/shaclc": {
        source: "iana"
      },
      "text/shex": {
        source: "iana",
        extensions: ["shex"]
      },
      "text/slim": {
        extensions: ["slim", "slm"]
      },
      "text/spdx": {
        source: "iana",
        extensions: ["spdx"]
      },
      "text/strings": {
        source: "iana"
      },
      "text/stylus": {
        extensions: ["stylus", "styl"]
      },
      "text/t140": {
        source: "iana"
      },
      "text/tab-separated-values": {
        source: "iana",
        compressible: true,
        extensions: ["tsv"]
      },
      "text/troff": {
        source: "iana",
        extensions: ["t", "tr", "roff", "man", "me", "ms"]
      },
      "text/turtle": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["ttl"]
      },
      "text/ulpfec": {
        source: "iana"
      },
      "text/uri-list": {
        source: "iana",
        compressible: true,
        extensions: ["uri", "uris", "urls"]
      },
      "text/vcard": {
        source: "iana",
        compressible: true,
        extensions: ["vcard"]
      },
      "text/vnd.a": {
        source: "iana"
      },
      "text/vnd.abc": {
        source: "iana"
      },
      "text/vnd.ascii-art": {
        source: "iana"
      },
      "text/vnd.curl": {
        source: "iana",
        extensions: ["curl"]
      },
      "text/vnd.curl.dcurl": {
        source: "apache",
        extensions: ["dcurl"]
      },
      "text/vnd.curl.mcurl": {
        source: "apache",
        extensions: ["mcurl"]
      },
      "text/vnd.curl.scurl": {
        source: "apache",
        extensions: ["scurl"]
      },
      "text/vnd.debian.copyright": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/vnd.dmclientscript": {
        source: "iana"
      },
      "text/vnd.dvb.subtitle": {
        source: "iana",
        extensions: ["sub"]
      },
      "text/vnd.esmertec.theme-descriptor": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/vnd.exchangeable": {
        source: "iana"
      },
      "text/vnd.familysearch.gedcom": {
        source: "iana",
        extensions: ["ged"]
      },
      "text/vnd.ficlab.flt": {
        source: "iana"
      },
      "text/vnd.fly": {
        source: "iana",
        extensions: ["fly"]
      },
      "text/vnd.fmi.flexstor": {
        source: "iana",
        extensions: ["flx"]
      },
      "text/vnd.gml": {
        source: "iana"
      },
      "text/vnd.graphviz": {
        source: "iana",
        extensions: ["gv"]
      },
      "text/vnd.hans": {
        source: "iana"
      },
      "text/vnd.hgl": {
        source: "iana"
      },
      "text/vnd.in3d.3dml": {
        source: "iana",
        extensions: ["3dml"]
      },
      "text/vnd.in3d.spot": {
        source: "iana",
        extensions: ["spot"]
      },
      "text/vnd.iptc.newsml": {
        source: "iana"
      },
      "text/vnd.iptc.nitf": {
        source: "iana"
      },
      "text/vnd.latex-z": {
        source: "iana"
      },
      "text/vnd.motorola.reflex": {
        source: "iana"
      },
      "text/vnd.ms-mediapackage": {
        source: "iana"
      },
      "text/vnd.net2phone.commcenter.command": {
        source: "iana"
      },
      "text/vnd.radisys.msml-basic-layout": {
        source: "iana"
      },
      "text/vnd.senx.warpscript": {
        source: "iana"
      },
      "text/vnd.si.uricatalogue": {
        source: "apache"
      },
      "text/vnd.sosi": {
        source: "iana"
      },
      "text/vnd.sun.j2me.app-descriptor": {
        source: "iana",
        charset: "UTF-8",
        extensions: ["jad"]
      },
      "text/vnd.trolltech.linguist": {
        source: "iana",
        charset: "UTF-8"
      },
      "text/vnd.vcf": {
        source: "iana"
      },
      "text/vnd.wap.si": {
        source: "iana"
      },
      "text/vnd.wap.sl": {
        source: "iana"
      },
      "text/vnd.wap.wml": {
        source: "iana",
        extensions: ["wml"]
      },
      "text/vnd.wap.wmlscript": {
        source: "iana",
        extensions: ["wmls"]
      },
      "text/vnd.zoo.kcl": {
        source: "iana"
      },
      "text/vtt": {
        source: "iana",
        charset: "UTF-8",
        compressible: true,
        extensions: ["vtt"]
      },
      "text/wgsl": {
        source: "iana",
        extensions: ["wgsl"]
      },
      "text/x-asm": {
        source: "apache",
        extensions: ["s", "asm"]
      },
      "text/x-c": {
        source: "apache",
        extensions: ["c", "cc", "cxx", "cpp", "h", "hh", "dic"]
      },
      "text/x-component": {
        source: "nginx",
        extensions: ["htc"]
      },
      "text/x-fortran": {
        source: "apache",
        extensions: ["f", "for", "f77", "f90"]
      },
      "text/x-gwt-rpc": {
        compressible: true
      },
      "text/x-handlebars-template": {
        extensions: ["hbs"]
      },
      "text/x-java-source": {
        source: "apache",
        extensions: ["java"]
      },
      "text/x-jquery-tmpl": {
        compressible: true
      },
      "text/x-lua": {
        extensions: ["lua"]
      },
      "text/x-markdown": {
        compressible: true,
        extensions: ["mkd"]
      },
      "text/x-nfo": {
        source: "apache",
        extensions: ["nfo"]
      },
      "text/x-opml": {
        source: "apache",
        extensions: ["opml"]
      },
      "text/x-org": {
        compressible: true,
        extensions: ["org"]
      },
      "text/x-pascal": {
        source: "apache",
        extensions: ["p", "pas"]
      },
      "text/x-processing": {
        compressible: true,
        extensions: ["pde"]
      },
      "text/x-sass": {
        extensions: ["sass"]
      },
      "text/x-scss": {
        extensions: ["scss"]
      },
      "text/x-setext": {
        source: "apache",
        extensions: ["etx"]
      },
      "text/x-sfv": {
        source: "apache",
        extensions: ["sfv"]
      },
      "text/x-suse-ymp": {
        compressible: true,
        extensions: ["ymp"]
      },
      "text/x-uuencode": {
        source: "apache",
        extensions: ["uu"]
      },
      "text/x-vcalendar": {
        source: "apache",
        extensions: ["vcs"]
      },
      "text/x-vcard": {
        source: "apache",
        extensions: ["vcf"]
      },
      "text/xml": {
        source: "iana",
        compressible: true,
        extensions: ["xml"]
      },
      "text/xml-external-parsed-entity": {
        source: "iana"
      },
      "text/yaml": {
        compressible: true,
        extensions: ["yaml", "yml"]
      },
      "video/1d-interleaved-parityfec": {
        source: "iana"
      },
      "video/3gpp": {
        source: "iana",
        extensions: ["3gp", "3gpp"]
      },
      "video/3gpp-tt": {
        source: "iana"
      },
      "video/3gpp2": {
        source: "iana",
        extensions: ["3g2"]
      },
      "video/av1": {
        source: "iana"
      },
      "video/bmpeg": {
        source: "iana"
      },
      "video/bt656": {
        source: "iana"
      },
      "video/celb": {
        source: "iana"
      },
      "video/dv": {
        source: "iana"
      },
      "video/encaprtp": {
        source: "iana"
      },
      "video/evc": {
        source: "iana"
      },
      "video/ffv1": {
        source: "iana"
      },
      "video/flexfec": {
        source: "iana"
      },
      "video/h261": {
        source: "iana",
        extensions: ["h261"]
      },
      "video/h263": {
        source: "iana",
        extensions: ["h263"]
      },
      "video/h263-1998": {
        source: "iana"
      },
      "video/h263-2000": {
        source: "iana"
      },
      "video/h264": {
        source: "iana",
        extensions: ["h264"]
      },
      "video/h264-rcdo": {
        source: "iana"
      },
      "video/h264-svc": {
        source: "iana"
      },
      "video/h265": {
        source: "iana"
      },
      "video/h266": {
        source: "iana"
      },
      "video/iso.segment": {
        source: "iana",
        extensions: ["m4s"]
      },
      "video/jpeg": {
        source: "iana",
        extensions: ["jpgv"]
      },
      "video/jpeg2000": {
        source: "iana"
      },
      "video/jpm": {
        source: "apache",
        extensions: ["jpm", "jpgm"]
      },
      "video/jxsv": {
        source: "iana"
      },
      "video/lottie+json": {
        source: "iana",
        compressible: true
      },
      "video/matroska": {
        source: "iana"
      },
      "video/matroska-3d": {
        source: "iana"
      },
      "video/mj2": {
        source: "iana",
        extensions: ["mj2", "mjp2"]
      },
      "video/mp1s": {
        source: "iana"
      },
      "video/mp2p": {
        source: "iana"
      },
      "video/mp2t": {
        source: "iana",
        extensions: ["ts", "m2t", "m2ts", "mts"]
      },
      "video/mp4": {
        source: "iana",
        compressible: false,
        extensions: ["mp4", "mp4v", "mpg4"]
      },
      "video/mp4v-es": {
        source: "iana"
      },
      "video/mpeg": {
        source: "iana",
        compressible: false,
        extensions: ["mpeg", "mpg", "mpe", "m1v", "m2v"]
      },
      "video/mpeg4-generic": {
        source: "iana"
      },
      "video/mpv": {
        source: "iana"
      },
      "video/nv": {
        source: "iana"
      },
      "video/ogg": {
        source: "iana",
        compressible: false,
        extensions: ["ogv"]
      },
      "video/parityfec": {
        source: "iana"
      },
      "video/pointer": {
        source: "iana"
      },
      "video/quicktime": {
        source: "iana",
        compressible: false,
        extensions: ["qt", "mov"]
      },
      "video/raptorfec": {
        source: "iana"
      },
      "video/raw": {
        source: "iana"
      },
      "video/rtp-enc-aescm128": {
        source: "iana"
      },
      "video/rtploopback": {
        source: "iana"
      },
      "video/rtx": {
        source: "iana"
      },
      "video/scip": {
        source: "iana"
      },
      "video/smpte291": {
        source: "iana"
      },
      "video/smpte292m": {
        source: "iana"
      },
      "video/ulpfec": {
        source: "iana"
      },
      "video/vc1": {
        source: "iana"
      },
      "video/vc2": {
        source: "iana"
      },
      "video/vnd.cctv": {
        source: "iana"
      },
      "video/vnd.dece.hd": {
        source: "iana",
        extensions: ["uvh", "uvvh"]
      },
      "video/vnd.dece.mobile": {
        source: "iana",
        extensions: ["uvm", "uvvm"]
      },
      "video/vnd.dece.mp4": {
        source: "iana"
      },
      "video/vnd.dece.pd": {
        source: "iana",
        extensions: ["uvp", "uvvp"]
      },
      "video/vnd.dece.sd": {
        source: "iana",
        extensions: ["uvs", "uvvs"]
      },
      "video/vnd.dece.video": {
        source: "iana",
        extensions: ["uvv", "uvvv"]
      },
      "video/vnd.directv.mpeg": {
        source: "iana"
      },
      "video/vnd.directv.mpeg-tts": {
        source: "iana"
      },
      "video/vnd.dlna.mpeg-tts": {
        source: "iana"
      },
      "video/vnd.dvb.file": {
        source: "iana",
        extensions: ["dvb"]
      },
      "video/vnd.fvt": {
        source: "iana",
        extensions: ["fvt"]
      },
      "video/vnd.hns.video": {
        source: "iana"
      },
      "video/vnd.iptvforum.1dparityfec-1010": {
        source: "iana"
      },
      "video/vnd.iptvforum.1dparityfec-2005": {
        source: "iana"
      },
      "video/vnd.iptvforum.2dparityfec-1010": {
        source: "iana"
      },
      "video/vnd.iptvforum.2dparityfec-2005": {
        source: "iana"
      },
      "video/vnd.iptvforum.ttsavc": {
        source: "iana"
      },
      "video/vnd.iptvforum.ttsmpeg2": {
        source: "iana"
      },
      "video/vnd.motorola.video": {
        source: "iana"
      },
      "video/vnd.motorola.videop": {
        source: "iana"
      },
      "video/vnd.mpegurl": {
        source: "iana",
        extensions: ["mxu", "m4u"]
      },
      "video/vnd.ms-playready.media.pyv": {
        source: "iana",
        extensions: ["pyv"]
      },
      "video/vnd.nokia.interleaved-multimedia": {
        source: "iana"
      },
      "video/vnd.nokia.mp4vr": {
        source: "iana"
      },
      "video/vnd.nokia.videovoip": {
        source: "iana"
      },
      "video/vnd.objectvideo": {
        source: "iana"
      },
      "video/vnd.planar": {
        source: "iana"
      },
      "video/vnd.radgamettools.bink": {
        source: "iana"
      },
      "video/vnd.radgamettools.smacker": {
        source: "apache"
      },
      "video/vnd.sealed.mpeg1": {
        source: "iana"
      },
      "video/vnd.sealed.mpeg4": {
        source: "iana"
      },
      "video/vnd.sealed.swf": {
        source: "iana"
      },
      "video/vnd.sealedmedia.softseal.mov": {
        source: "iana"
      },
      "video/vnd.uvvu.mp4": {
        source: "iana",
        extensions: ["uvu", "uvvu"]
      },
      "video/vnd.vivo": {
        source: "iana",
        extensions: ["viv"]
      },
      "video/vnd.youtube.yt": {
        source: "iana"
      },
      "video/vp8": {
        source: "iana"
      },
      "video/vp9": {
        source: "iana"
      },
      "video/webm": {
        source: "apache",
        compressible: false,
        extensions: ["webm"]
      },
      "video/x-f4v": {
        source: "apache",
        extensions: ["f4v"]
      },
      "video/x-fli": {
        source: "apache",
        extensions: ["fli"]
      },
      "video/x-flv": {
        source: "apache",
        compressible: false,
        extensions: ["flv"]
      },
      "video/x-m4v": {
        source: "apache",
        extensions: ["m4v"]
      },
      "video/x-matroska": {
        source: "apache",
        compressible: false,
        extensions: ["mkv", "mk3d", "mks"]
      },
      "video/x-mng": {
        source: "apache",
        extensions: ["mng"]
      },
      "video/x-ms-asf": {
        source: "apache",
        extensions: ["asf", "asx"]
      },
      "video/x-ms-vob": {
        source: "apache",
        extensions: ["vob"]
      },
      "video/x-ms-wm": {
        source: "apache",
        extensions: ["wm"]
      },
      "video/x-ms-wmv": {
        source: "apache",
        compressible: false,
        extensions: ["wmv"]
      },
      "video/x-ms-wmx": {
        source: "apache",
        extensions: ["wmx"]
      },
      "video/x-ms-wvx": {
        source: "apache",
        extensions: ["wvx"]
      },
      "video/x-msvideo": {
        source: "apache",
        extensions: ["avi"]
      },
      "video/x-sgi-movie": {
        source: "apache",
        extensions: ["movie"]
      },
      "video/x-smv": {
        source: "apache",
        extensions: ["smv"]
      },
      "x-conference/x-cooltalk": {
        source: "apache",
        extensions: ["ice"]
      },
      "x-shader/x-fragment": {
        compressible: true
      },
      "x-shader/x-vertex": {
        compressible: true
      }
    };
  }
});

// node_modules/mime-db/index.js
var require_mime_db = __commonJS({
  "node_modules/mime-db/index.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = require_db();
  }
});

// node_modules/form-data/node_modules/mime-types/index.js
var require_mime_types = __commonJS({
  "node_modules/form-data/node_modules/mime-types/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var db = require_mime_db();
    var extname7 = __require("path").extname;
    var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/;
    var TEXT_TYPE_REGEXP = /^text\//i;
    exports2.charset = charset;
    exports2.charsets = { lookup: charset };
    exports2.contentType = contentType;
    exports2.extension = extension;
    exports2.extensions = /* @__PURE__ */ Object.create(null);
    exports2.lookup = lookup2;
    exports2.types = /* @__PURE__ */ Object.create(null);
    populateMaps(exports2.extensions, exports2.types);
    function charset(type) {
      if (!type || typeof type !== "string") {
        return false;
      }
      var match2 = EXTRACT_TYPE_REGEXP.exec(type);
      var mime = match2 && db[match2[1].toLowerCase()];
      if (mime && mime.charset) {
        return mime.charset;
      }
      if (match2 && TEXT_TYPE_REGEXP.test(match2[1])) {
        return "UTF-8";
      }
      return false;
    }
    __name(charset, "charset");
    function contentType(str2) {
      if (!str2 || typeof str2 !== "string") {
        return false;
      }
      var mime = str2.indexOf("/") === -1 ? exports2.lookup(str2) : str2;
      if (!mime) {
        return false;
      }
      if (mime.indexOf("charset") === -1) {
        var charset2 = exports2.charset(mime);
        if (charset2) mime += "; charset=" + charset2.toLowerCase();
      }
      return mime;
    }
    __name(contentType, "contentType");
    function extension(type) {
      if (!type || typeof type !== "string") {
        return false;
      }
      var match2 = EXTRACT_TYPE_REGEXP.exec(type);
      var exts = match2 && exports2.extensions[match2[1].toLowerCase()];
      if (!exts || !exts.length) {
        return false;
      }
      return exts[0];
    }
    __name(extension, "extension");
    function lookup2(path150) {
      if (!path150 || typeof path150 !== "string") {
        return false;
      }
      var extension2 = extname7("x." + path150).toLowerCase().substr(1);
      if (!extension2) {
        return false;
      }
      return exports2.types[extension2] || false;
    }
    __name(lookup2, "lookup");
    function populateMaps(extensions, types7) {
      var preference = ["nginx", "apache", void 0, "iana"];
      Object.keys(db).forEach(/* @__PURE__ */ __name(function forEachMimeType(type) {
        var mime = db[type];
        var exts = mime.extensions;
        if (!exts || !exts.length) {
          return;
        }
        extensions[type] = exts;
        for (var i4 = 0; i4 < exts.length; i4++) {
          var extension2 = exts[i4];
          if (types7[extension2]) {
            var from = preference.indexOf(db[types7[extension2]].source);
            var to = preference.indexOf(mime.source);
            if (types7[extension2] !== "application/octet-stream" && (from > to || from === to && types7[extension2].substr(0, 12) === "application/")) {
              continue;
            }
          }
          types7[extension2] = type;
        }
      }, "forEachMimeType"));
    }
    __name(populateMaps, "populateMaps");
  }
});

// node_modules/asynckit/lib/defer.js
var require_defer = __commonJS({
  "node_modules/asynckit/lib/defer.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = defer2;
    function defer2(fn) {
      var nextTick = typeof setImmediate == "function" ? setImmediate : typeof process == "object" && typeof process.nextTick == "function" ? process.nextTick : null;
      if (nextTick) {
        nextTick(fn);
      } else {
        setTimeout(fn, 0);
      }
    }
    __name(defer2, "defer");
  }
});

// node_modules/asynckit/lib/async.js
var require_async3 = __commonJS({
  "node_modules/asynckit/lib/async.js"(exports2, module2) {
    init_esbuild_shims();
    var defer2 = require_defer();
    module2.exports = async;
    function async(callback) {
      var isAsync2 = false;
      defer2(function() {
        isAsync2 = true;
      });
      return /* @__PURE__ */ __name(function async_callback(err2, result) {
        if (isAsync2) {
          callback(err2, result);
        } else {
          defer2(/* @__PURE__ */ __name(function nextTick_callback() {
            callback(err2, result);
          }, "nextTick_callback"));
        }
      }, "async_callback");
    }
    __name(async, "async");
  }
});

// node_modules/asynckit/lib/abort.js
var require_abort = __commonJS({
  "node_modules/asynckit/lib/abort.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = abort2;
    function abort2(state) {
      Object.keys(state.jobs).forEach(clean.bind(state));
      state.jobs = {};
    }
    __name(abort2, "abort");
    function clean(key) {
      if (typeof this.jobs[key] == "function") {
        this.jobs[key]();
      }
    }
    __name(clean, "clean");
  }
});

// node_modules/asynckit/lib/iterate.js
var require_iterate = __commonJS({
  "node_modules/asynckit/lib/iterate.js"(exports2, module2) {
    init_esbuild_shims();
    var async = require_async3();
    var abort2 = require_abort();
    module2.exports = iterate2;
    function iterate2(list3, iterator2, state, callback) {
      var key = state["keyedList"] ? state["keyedList"][state.index] : state.index;
      state.jobs[key] = runJob(iterator2, key, list3[key], function(error40, output) {
        if (!(key in state.jobs)) {
          return;
        }
        delete state.jobs[key];
        if (error40) {
          abort2(state);
        } else {
          state.results[key] = output;
        }
        callback(error40, state.results);
      });
    }
    __name(iterate2, "iterate");
    function runJob(iterator2, key, item, callback) {
      var aborter;
      if (iterator2.length == 2) {
        aborter = iterator2(item, async(callback));
      } else {
        aborter = iterator2(item, key, async(callback));
      }
      return aborter;
    }
    __name(runJob, "runJob");
  }
});

// node_modules/asynckit/lib/state.js
var require_state = __commonJS({
  "node_modules/asynckit/lib/state.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = state;
    function state(list3, sortMethod) {
      var isNamedList = !Array.isArray(list3), initState = {
        index: 0,
        keyedList: isNamedList || sortMethod ? Object.keys(list3) : null,
        jobs: {},
        results: isNamedList ? {} : [],
        size: isNamedList ? Object.keys(list3).length : list3.length
      };
      if (sortMethod) {
        initState.keyedList.sort(isNamedList ? sortMethod : function(a2, b2) {
          return sortMethod(list3[a2], list3[b2]);
        });
      }
      return initState;
    }
    __name(state, "state");
  }
});

// node_modules/asynckit/lib/terminator.js
var require_terminator = __commonJS({
  "node_modules/asynckit/lib/terminator.js"(exports2, module2) {
    init_esbuild_shims();
    var abort2 = require_abort();
    var async = require_async3();
    module2.exports = terminator;
    function terminator(callback) {
      if (!Object.keys(this.jobs).length) {
        return;
      }
      this.index = this.size;
      abort2(this);
      async(callback)(null, this.results);
    }
    __name(terminator, "terminator");
  }
});

// node_modules/asynckit/parallel.js
var require_parallel = __commonJS({
  "node_modules/asynckit/parallel.js"(exports2, module2) {
    init_esbuild_shims();
    var iterate2 = require_iterate();
    var initState = require_state();
    var terminator = require_terminator();
    module2.exports = parallel;
    function parallel(list3, iterator2, callback) {
      var state = initState(list3);
      while (state.index < (state["keyedList"] || list3).length) {
        iterate2(list3, iterator2, state, function(error40, result) {
          if (error40) {
            callback(error40, result);
            return;
          }
          if (Object.keys(state.jobs).length === 0) {
            callback(null, state.results);
            return;
          }
        });
        state.index++;
      }
      return terminator.bind(state, callback);
    }
    __name(parallel, "parallel");
  }
});

// node_modules/asynckit/serialOrdered.js
var require_serialOrdered = __commonJS({
  "node_modules/asynckit/serialOrdered.js"(exports2, module2) {
    init_esbuild_shims();
    var iterate2 = require_iterate();
    var initState = require_state();
    var terminator = require_terminator();
    module2.exports = serialOrdered;
    module2.exports.ascending = ascending;
    module2.exports.descending = descending;
    function serialOrdered(list3, iterator2, sortMethod, callback) {
      var state = initState(list3, sortMethod);
      iterate2(list3, iterator2, state, /* @__PURE__ */ __name(function iteratorHandler(error40, result) {
        if (error40) {
          callback(error40, result);
          return;
        }
        state.index++;
        if (state.index < (state["keyedList"] || list3).length) {
          iterate2(list3, iterator2, state, iteratorHandler);
          return;
        }
        callback(null, state.results);
      }, "iteratorHandler"));
      return terminator.bind(state, callback);
    }
    __name(serialOrdered, "serialOrdered");
    function ascending(a2, b2) {
      return a2 < b2 ? -1 : a2 > b2 ? 1 : 0;
    }
    __name(ascending, "ascending");
    function descending(a2, b2) {
      return -1 * ascending(a2, b2);
    }
    __name(descending, "descending");
  }
});

// node_modules/asynckit/serial.js
var require_serial = __commonJS({
  "node_modules/asynckit/serial.js"(exports2, module2) {
    init_esbuild_shims();
    var serialOrdered = require_serialOrdered();
    module2.exports = serial;
    function serial(list3, iterator2, callback) {
      return serialOrdered(list3, iterator2, null, callback);
    }
    __name(serial, "serial");
  }
});

// node_modules/asynckit/index.js
var require_asynckit = __commonJS({
  "node_modules/asynckit/index.js"(exports2, module2) {
    init_esbuild_shims();
    module2.exports = {
      parallel: require_parallel(),
      serial: require_serial(),
      serialOrdered: require_serialOrdered()
    };
  }
});

// node_modules/es-object-atoms/index.js
var require_es_object_atoms = __commonJS({
  "node_modules/es-object-atoms/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Object;
  }
});

// node_modules/es-errors/index.js
var require_es_errors = __commonJS({
  "node_modules/es-errors/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Error;
  }
});

// node_modules/es-errors/eval.js
var require_eval = __commonJS({
  "node_modules/es-errors/eval.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = EvalError;
  }
});

// node_modules/es-errors/range.js
var require_range = __commonJS({
  "node_modules/es-errors/range.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = RangeError;
  }
});

// node_modules/es-errors/ref.js
var require_ref4 = __commonJS({
  "node_modules/es-errors/ref.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = ReferenceError;
  }
});

// node_modules/es-errors/syntax.js
var require_syntax = __commonJS({
  "node_modules/es-errors/syntax.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = SyntaxError;
  }
});

// node_modules/es-errors/type.js
var require_type3 = __commonJS({
  "node_modules/es-errors/type.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = TypeError;
  }
});

// node_modules/es-errors/uri.js
var require_uri4 = __commonJS({
  "node_modules/es-errors/uri.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = URIError;
  }
});

// node_modules/math-intrinsics/abs.js
var require_abs = __commonJS({
  "node_modules/math-intrinsics/abs.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Math.abs;
  }
});

// node_modules/math-intrinsics/floor.js
var require_floor = __commonJS({
  "node_modules/math-intrinsics/floor.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Math.floor;
  }
});

// node_modules/math-intrinsics/max.js
var require_max = __commonJS({
  "node_modules/math-intrinsics/max.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Math.max;
  }
});

// node_modules/math-intrinsics/min.js
var require_min = __commonJS({
  "node_modules/math-intrinsics/min.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Math.min;
  }
});

// node_modules/math-intrinsics/pow.js
var require_pow = __commonJS({
  "node_modules/math-intrinsics/pow.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Math.pow;
  }
});

// node_modules/math-intrinsics/round.js
var require_round = __commonJS({
  "node_modules/math-intrinsics/round.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Math.round;
  }
});

// node_modules/math-intrinsics/isNaN.js
var require_isNaN = __commonJS({
  "node_modules/math-intrinsics/isNaN.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Number.isNaN || /* @__PURE__ */ __name(function isNaN2(a2) {
      return a2 !== a2;
    }, "isNaN");
  }
});

// node_modules/math-intrinsics/sign.js
var require_sign = __commonJS({
  "node_modules/math-intrinsics/sign.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var $isNaN = require_isNaN();
    module2.exports = /* @__PURE__ */ __name(function sign(number4) {
      if ($isNaN(number4) || number4 === 0) {
        return number4;
      }
      return number4 < 0 ? -1 : 1;
    }, "sign");
  }
});

// node_modules/gopd/gOPD.js
var require_gOPD = __commonJS({
  "node_modules/gopd/gOPD.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Object.getOwnPropertyDescriptor;
  }
});

// node_modules/gopd/index.js
var require_gopd = __commonJS({
  "node_modules/gopd/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var $gOPD = require_gOPD();
    if ($gOPD) {
      try {
        $gOPD([], "length");
      } catch (e4) {
        $gOPD = null;
      }
    }
    module2.exports = $gOPD;
  }
});

// node_modules/es-define-property/index.js
var require_es_define_property = __commonJS({
  "node_modules/es-define-property/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var $defineProperty = Object.defineProperty || false;
    if ($defineProperty) {
      try {
        $defineProperty({}, "a", { value: 1 });
      } catch (e4) {
        $defineProperty = false;
      }
    }
    module2.exports = $defineProperty;
  }
});

// node_modules/has-symbols/shams.js
var require_shams = __commonJS({
  "node_modules/has-symbols/shams.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = /* @__PURE__ */ __name(function hasSymbols() {
      if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") {
        return false;
      }
      if (typeof Symbol.iterator === "symbol") {
        return true;
      }
      var obj = {};
      var sym = Symbol("test");
      var symObj = Object(sym);
      if (typeof sym === "string") {
        return false;
      }
      if (Object.prototype.toString.call(sym) !== "[object Symbol]") {
        return false;
      }
      if (Object.prototype.toString.call(symObj) !== "[object Symbol]") {
        return false;
      }
      var symVal = 42;
      obj[sym] = symVal;
      for (var _2 in obj) {
        return false;
      }
      if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) {
        return false;
      }
      if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) {
        return false;
      }
      var syms = Object.getOwnPropertySymbols(obj);
      if (syms.length !== 1 || syms[0] !== sym) {
        return false;
      }
      if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) {
        return false;
      }
      if (typeof Object.getOwnPropertyDescriptor === "function") {
        var descriptor2 = (
          /** @type {PropertyDescriptor} */
          Object.getOwnPropertyDescriptor(obj, sym)
        );
        if (descriptor2.value !== symVal || descriptor2.enumerable !== true) {
          return false;
        }
      }
      return true;
    }, "hasSymbols");
  }
});

// node_modules/has-symbols/index.js
var require_has_symbols = __commonJS({
  "node_modules/has-symbols/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var origSymbol = typeof Symbol !== "undefined" && Symbol;
    var hasSymbolSham = require_shams();
    module2.exports = /* @__PURE__ */ __name(function hasNativeSymbols() {
      if (typeof origSymbol !== "function") {
        return false;
      }
      if (typeof Symbol !== "function") {
        return false;
      }
      if (typeof origSymbol("foo") !== "symbol") {
        return false;
      }
      if (typeof Symbol("bar") !== "symbol") {
        return false;
      }
      return hasSymbolSham();
    }, "hasNativeSymbols");
  }
});

// node_modules/get-proto/Reflect.getPrototypeOf.js
var require_Reflect_getPrototypeOf = __commonJS({
  "node_modules/get-proto/Reflect.getPrototypeOf.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
  }
});

// node_modules/get-proto/Object.getPrototypeOf.js
var require_Object_getPrototypeOf = __commonJS({
  "node_modules/get-proto/Object.getPrototypeOf.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var $Object = require_es_object_atoms();
    module2.exports = $Object.getPrototypeOf || null;
  }
});

// node_modules/call-bind-apply-helpers/functionCall.js
var require_functionCall = __commonJS({
  "node_modules/call-bind-apply-helpers/functionCall.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Function.prototype.call;
  }
});

// node_modules/call-bind-apply-helpers/functionApply.js
var require_functionApply = __commonJS({
  "node_modules/call-bind-apply-helpers/functionApply.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = Function.prototype.apply;
  }
});

// node_modules/call-bind-apply-helpers/reflectApply.js
var require_reflectApply = __commonJS({
  "node_modules/call-bind-apply-helpers/reflectApply.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
  }
});

// node_modules/call-bind-apply-helpers/actualApply.js
var require_actualApply = __commonJS({
  "node_modules/call-bind-apply-helpers/actualApply.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var bind2 = require_function_bind();
    var $apply = require_functionApply();
    var $call = require_functionCall();
    var $reflectApply = require_reflectApply();
    module2.exports = $reflectApply || bind2.call($call, $apply);
  }
});

// node_modules/call-bind-apply-helpers/index.js
var require_call_bind_apply_helpers = __commonJS({
  "node_modules/call-bind-apply-helpers/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var bind2 = require_function_bind();
    var $TypeError = require_type3();
    var $call = require_functionCall();
    var $actualApply = require_actualApply();
    module2.exports = /* @__PURE__ */ __name(function callBindBasic(args2) {
      if (args2.length < 1 || typeof args2[0] !== "function") {
        throw new $TypeError("a function is required");
      }
      return $actualApply(bind2, $call, args2);
    }, "callBindBasic");
  }
});

// node_modules/dunder-proto/get.js
var require_get = __commonJS({
  "node_modules/dunder-proto/get.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var callBind = require_call_bind_apply_helpers();
    var gOPD = require_gopd();
    var hasProtoAccessor;
    try {
      hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */
      [].__proto__ === Array.prototype;
    } catch (e4) {
      if (!e4 || typeof e4 !== "object" || !("code" in e4) || e4.code !== "ERR_PROTO_ACCESS") {
        throw e4;
      }
    }
    var desc2 = !!hasProtoAccessor && gOPD && gOPD(
      Object.prototype,
      /** @type {keyof typeof Object.prototype} */
      "__proto__"
    );
    var $Object = Object;
    var $getPrototypeOf = $Object.getPrototypeOf;
    module2.exports = desc2 && typeof desc2.get === "function" ? callBind([desc2.get]) : typeof $getPrototypeOf === "function" ? (
      /** @type {import('./get')} */
      /* @__PURE__ */ __name(function getDunder(value) {
        return $getPrototypeOf(value == null ? value : $Object(value));
      }, "getDunder")
    ) : false;
  }
});

// node_modules/get-proto/index.js
var require_get_proto = __commonJS({
  "node_modules/get-proto/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var reflectGetProto = require_Reflect_getPrototypeOf();
    var originalGetProto = require_Object_getPrototypeOf();
    var getDunderProto = require_get();
    module2.exports = reflectGetProto ? /* @__PURE__ */ __name(function getProto(O2) {
      return reflectGetProto(O2);
    }, "getProto") : originalGetProto ? /* @__PURE__ */ __name(function getProto(O2) {
      if (!O2 || typeof O2 !== "object" && typeof O2 !== "function") {
        throw new TypeError("getProto: not an object");
      }
      return originalGetProto(O2);
    }, "getProto") : getDunderProto ? /* @__PURE__ */ __name(function getProto(O2) {
      return getDunderProto(O2);
    }, "getProto") : null;
  }
});

// node_modules/get-intrinsic/index.js
var require_get_intrinsic = __commonJS({
  "node_modules/get-intrinsic/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var undefined2;
    var $Object = require_es_object_atoms();
    var $Error = require_es_errors();
    var $EvalError = require_eval();
    var $RangeError = require_range();
    var $ReferenceError = require_ref4();
    var $SyntaxError = require_syntax();
    var $TypeError = require_type3();
    var $URIError = require_uri4();
    var abs = require_abs();
    var floor = require_floor();
    var max = require_max();
    var min = require_min();
    var pow = require_pow();
    var round = require_round();
    var sign = require_sign();
    var $Function = Function;
    var getEvalledConstructor = /* @__PURE__ */ __name(function(expressionSyntax) {
      try {
        return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
      } catch (e4) {
      }
    }, "getEvalledConstructor");
    var $gOPD = require_gopd();
    var $defineProperty = require_es_define_property();
    var throwTypeError = /* @__PURE__ */ __name(function() {
      throw new $TypeError();
    }, "throwTypeError");
    var ThrowTypeError = $gOPD ? function() {
      try {
        arguments.callee;
        return throwTypeError;
      } catch (calleeThrows) {
        try {
          return $gOPD(arguments, "callee").get;
        } catch (gOPDthrows) {
          return throwTypeError;
        }
      }
    }() : throwTypeError;
    var hasSymbols = require_has_symbols()();
    var getProto = require_get_proto();
    var $ObjectGPO = require_Object_getPrototypeOf();
    var $ReflectGPO = require_Reflect_getPrototypeOf();
    var $apply = require_functionApply();
    var $call = require_functionCall();
    var needsEval = {};
    var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined2 : getProto(Uint8Array);
    var INTRINSICS = {
      __proto__: null,
      "%AggregateError%": typeof AggregateError === "undefined" ? undefined2 : AggregateError,
      "%Array%": Array,
      "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined2 : ArrayBuffer,
      "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2,
      "%AsyncFromSyncIteratorPrototype%": undefined2,
      "%AsyncFunction%": needsEval,
      "%AsyncGenerator%": needsEval,
      "%AsyncGeneratorFunction%": needsEval,
      "%AsyncIteratorPrototype%": needsEval,
      "%Atomics%": typeof Atomics === "undefined" ? undefined2 : Atomics,
      "%BigInt%": typeof BigInt === "undefined" ? undefined2 : BigInt,
      "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined2 : BigInt64Array,
      "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined2 : BigUint64Array,
      "%Boolean%": Boolean,
      "%DataView%": typeof DataView === "undefined" ? undefined2 : DataView,
      "%Date%": Date,
      "%decodeURI%": decodeURI,
      "%decodeURIComponent%": decodeURIComponent,
      "%encodeURI%": encodeURI,
      "%encodeURIComponent%": encodeURIComponent,
      "%Error%": $Error,
      "%eval%": eval,
      // eslint-disable-line no-eval
      "%EvalError%": $EvalError,
      "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array,
      "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array,
      "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array,
      "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry,
      "%Function%": $Function,
      "%GeneratorFunction%": needsEval,
      "%Int8Array%": typeof Int8Array === "undefined" ? undefined2 : Int8Array,
      "%Int16Array%": typeof Int16Array === "undefined" ? undefined2 : Int16Array,
      "%Int32Array%": typeof Int32Array === "undefined" ? undefined2 : Int32Array,
      "%isFinite%": isFinite,
      "%isNaN%": isNaN,
      "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2,
      "%JSON%": typeof JSON === "object" ? JSON : undefined2,
      "%Map%": typeof Map === "undefined" ? undefined2 : Map,
      "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()),
      "%Math%": Math,
      "%Number%": Number,
      "%Object%": $Object,
      "%Object.getOwnPropertyDescriptor%": $gOPD,
      "%parseFloat%": parseFloat,
      "%parseInt%": parseInt,
      "%Promise%": typeof Promise === "undefined" ? undefined2 : Promise,
      "%Proxy%": typeof Proxy === "undefined" ? undefined2 : Proxy,
      "%RangeError%": $RangeError,
      "%ReferenceError%": $ReferenceError,
      "%Reflect%": typeof Reflect === "undefined" ? undefined2 : Reflect,
      "%RegExp%": RegExp,
      "%Set%": typeof Set === "undefined" ? undefined2 : Set,
      "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined2 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()),
      "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined2 : SharedArrayBuffer,
      "%String%": String,
      "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2,
      "%Symbol%": hasSymbols ? Symbol : undefined2,
      "%SyntaxError%": $SyntaxError,
      "%ThrowTypeError%": ThrowTypeError,
      "%TypedArray%": TypedArray,
      "%TypeError%": $TypeError,
      "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined2 : Uint8Array,
      "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined2 : Uint8ClampedArray,
      "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined2 : Uint16Array,
      "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined2 : Uint32Array,
      "%URIError%": $URIError,
      "%WeakMap%": typeof WeakMap === "undefined" ? undefined2 : WeakMap,
      "%WeakRef%": typeof WeakRef === "undefined" ? undefined2 : WeakRef,
      "%WeakSet%": typeof WeakSet === "undefined" ? undefined2 : WeakSet,
      "%Function.prototype.call%": $call,
      "%Function.prototype.apply%": $apply,
      "%Object.defineProperty%": $defineProperty,
      "%Object.getPrototypeOf%": $ObjectGPO,
      "%Math.abs%": abs,
      "%Math.floor%": floor,
      "%Math.max%": max,
      "%Math.min%": min,
      "%Math.pow%": pow,
      "%Math.round%": round,
      "%Math.sign%": sign,
      "%Reflect.getPrototypeOf%": $ReflectGPO
    };
    if (getProto) {
      try {
        null.error;
      } catch (e4) {
        errorProto = getProto(getProto(e4));
        INTRINSICS["%Error.prototype%"] = errorProto;
      }
    }
    var errorProto;
    var doEval = /* @__PURE__ */ __name(function doEval2(name4) {
      var value;
      if (name4 === "%AsyncFunction%") {
        value = getEvalledConstructor("async function () {}");
      } else if (name4 === "%GeneratorFunction%") {
        value = getEvalledConstructor("function* () {}");
      } else if (name4 === "%AsyncGeneratorFunction%") {
        value = getEvalledConstructor("async function* () {}");
      } else if (name4 === "%AsyncGenerator%") {
        var fn = doEval2("%AsyncGeneratorFunction%");
        if (fn) {
          value = fn.prototype;
        }
      } else if (name4 === "%AsyncIteratorPrototype%") {
        var gen = doEval2("%AsyncGenerator%");
        if (gen && getProto) {
          value = getProto(gen.prototype);
        }
      }
      INTRINSICS[name4] = value;
      return value;
    }, "doEval");
    var LEGACY_ALIASES = {
      __proto__: null,
      "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"],
      "%ArrayPrototype%": ["Array", "prototype"],
      "%ArrayProto_entries%": ["Array", "prototype", "entries"],
      "%ArrayProto_forEach%": ["Array", "prototype", "forEach"],
      "%ArrayProto_keys%": ["Array", "prototype", "keys"],
      "%ArrayProto_values%": ["Array", "prototype", "values"],
      "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"],
      "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"],
      "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"],
      "%BooleanPrototype%": ["Boolean", "prototype"],
      "%DataViewPrototype%": ["DataView", "prototype"],
      "%DatePrototype%": ["Date", "prototype"],
      "%ErrorPrototype%": ["Error", "prototype"],
      "%EvalErrorPrototype%": ["EvalError", "prototype"],
      "%Float32ArrayPrototype%": ["Float32Array", "prototype"],
      "%Float64ArrayPrototype%": ["Float64Array", "prototype"],
      "%FunctionPrototype%": ["Function", "prototype"],
      "%Generator%": ["GeneratorFunction", "prototype"],
      "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"],
      "%Int8ArrayPrototype%": ["Int8Array", "prototype"],
      "%Int16ArrayPrototype%": ["Int16Array", "prototype"],
      "%Int32ArrayPrototype%": ["Int32Array", "prototype"],
      "%JSONParse%": ["JSON", "parse"],
      "%JSONStringify%": ["JSON", "stringify"],
      "%MapPrototype%": ["Map", "prototype"],
      "%NumberPrototype%": ["Number", "prototype"],
      "%ObjectPrototype%": ["Object", "prototype"],
      "%ObjProto_toString%": ["Object", "prototype", "toString"],
      "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"],
      "%PromisePrototype%": ["Promise", "prototype"],
      "%PromiseProto_then%": ["Promise", "prototype", "then"],
      "%Promise_all%": ["Promise", "all"],
      "%Promise_reject%": ["Promise", "reject"],
      "%Promise_resolve%": ["Promise", "resolve"],
      "%RangeErrorPrototype%": ["RangeError", "prototype"],
      "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"],
      "%RegExpPrototype%": ["RegExp", "prototype"],
      "%SetPrototype%": ["Set", "prototype"],
      "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"],
      "%StringPrototype%": ["String", "prototype"],
      "%SymbolPrototype%": ["Symbol", "prototype"],
      "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"],
      "%TypedArrayPrototype%": ["TypedArray", "prototype"],
      "%TypeErrorPrototype%": ["TypeError", "prototype"],
      "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"],
      "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"],
      "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"],
      "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"],
      "%URIErrorPrototype%": ["URIError", "prototype"],
      "%WeakMapPrototype%": ["WeakMap", "prototype"],
      "%WeakSetPrototype%": ["WeakSet", "prototype"]
    };
    var bind2 = require_function_bind();
    var hasOwn3 = require_hasown();
    var $concat = bind2.call($call, Array.prototype.concat);
    var $spliceApply = bind2.call($apply, Array.prototype.splice);
    var $replace = bind2.call($call, String.prototype.replace);
    var $strSlice = bind2.call($call, String.prototype.slice);
    var $exec = bind2.call($call, RegExp.prototype.exec);
    var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
    var reEscapeChar = /\\(\\)?/g;
    var stringToPath = /* @__PURE__ */ __name(function stringToPath2(string4) {
      var first2 = $strSlice(string4, 0, 1);
      var last2 = $strSlice(string4, -1);
      if (first2 === "%" && last2 !== "%") {
        throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
      } else if (last2 === "%" && first2 !== "%") {
        throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
      }
      var result = [];
      $replace(string4, rePropName, function(match2, number4, quote3, subString) {
        result[result.length] = quote3 ? $replace(subString, reEscapeChar, "$1") : number4 || match2;
      });
      return result;
    }, "stringToPath");
    var getBaseIntrinsic = /* @__PURE__ */ __name(function getBaseIntrinsic2(name4, allowMissing) {
      var intrinsicName = name4;
      var alias;
      if (hasOwn3(LEGACY_ALIASES, intrinsicName)) {
        alias = LEGACY_ALIASES[intrinsicName];
        intrinsicName = "%" + alias[0] + "%";
      }
      if (hasOwn3(INTRINSICS, intrinsicName)) {
        var value = INTRINSICS[intrinsicName];
        if (value === needsEval) {
          value = doEval(intrinsicName);
        }
        if (typeof value === "undefined" && !allowMissing) {
          throw new $TypeError("intrinsic " + name4 + " exists, but is not available. Please file an issue!");
        }
        return {
          alias,
          name: intrinsicName,
          value
        };
      }
      throw new $SyntaxError("intrinsic " + name4 + " does not exist!");
    }, "getBaseIntrinsic");
    module2.exports = /* @__PURE__ */ __name(function GetIntrinsic(name4, allowMissing) {
      if (typeof name4 !== "string" || name4.length === 0) {
        throw new $TypeError("intrinsic name must be a non-empty string");
      }
      if (arguments.length > 1 && typeof allowMissing !== "boolean") {
        throw new $TypeError('"allowMissing" argument must be a boolean');
      }
      if ($exec(/^%?[^%]*%?$/, name4) === null) {
        throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
      }
      var parts2 = stringToPath(name4);
      var intrinsicBaseName = parts2.length > 0 ? parts2[0] : "";
      var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
      var intrinsicRealName = intrinsic.name;
      var value = intrinsic.value;
      var skipFurtherCaching = false;
      var alias = intrinsic.alias;
      if (alias) {
        intrinsicBaseName = alias[0];
        $spliceApply(parts2, $concat([0, 1], alias));
      }
      for (var i4 = 1, isOwn = true; i4 < parts2.length; i4 += 1) {
        var part = parts2[i4];
        var first2 = $strSlice(part, 0, 1);
        var last2 = $strSlice(part, -1);
        if ((first2 === '"' || first2 === "'" || first2 === "`" || (last2 === '"' || last2 === "'" || last2 === "`")) && first2 !== last2) {
          throw new $SyntaxError("property names with quotes must have matching quotes");
        }
        if (part === "constructor" || !isOwn) {
          skipFurtherCaching = true;
        }
        intrinsicBaseName += "." + part;
        intrinsicRealName = "%" + intrinsicBaseName + "%";
        if (hasOwn3(INTRINSICS, intrinsicRealName)) {
          value = INTRINSICS[intrinsicRealName];
        } else if (value != null) {
          if (!(part in value)) {
            if (!allowMissing) {
              throw new $TypeError("base intrinsic for " + name4 + " exists, but the property is not available.");
            }
            return void undefined2;
          }
          if ($gOPD && i4 + 1 >= parts2.length) {
            var desc2 = $gOPD(value, part);
            isOwn = !!desc2;
            if (isOwn && "get" in desc2 && !("originalValue" in desc2.get)) {
              value = desc2.get;
            } else {
              value = value[part];
            }
          } else {
            isOwn = hasOwn3(value, part);
            value = value[part];
          }
          if (isOwn && !skipFurtherCaching) {
            INTRINSICS[intrinsicRealName] = value;
          }
        }
      }
      return value;
    }, "GetIntrinsic");
  }
});

// node_modules/has-tostringtag/shams.js
var require_shams2 = __commonJS({
  "node_modules/has-tostringtag/shams.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var hasSymbols = require_shams();
    module2.exports = /* @__PURE__ */ __name(function hasToStringTagShams() {
      return hasSymbols() && !!Symbol.toStringTag;
    }, "hasToStringTagShams");
  }
});

// node_modules/es-set-tostringtag/index.js
var require_es_set_tostringtag = __commonJS({
  "node_modules/es-set-tostringtag/index.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var GetIntrinsic = require_get_intrinsic();
    var $defineProperty = GetIntrinsic("%Object.defineProperty%", true);
    var hasToStringTag = require_shams2()();
    var hasOwn3 = require_hasown();
    var $TypeError = require_type3();
    var toStringTag2 = hasToStringTag ? Symbol.toStringTag : null;
    module2.exports = /* @__PURE__ */ __name(function setToStringTag(object3, value) {
      var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force;
      var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable;
      if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") {
        throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");
      }
      if (toStringTag2 && (overrideIfSet || !hasOwn3(object3, toStringTag2))) {
        if ($defineProperty) {
          $defineProperty(object3, toStringTag2, {
            configurable: !nonConfigurable,
            enumerable: false,
            value,
            writable: false
          });
        } else {
          object3[toStringTag2] = value;
        }
      }
    }, "setToStringTag");
  }
});

// node_modules/form-data/lib/populate.js
var require_populate = __commonJS({
  "node_modules/form-data/lib/populate.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    module2.exports = function(dst, src) {
      Object.keys(src).forEach(function(prop) {
        dst[prop] = dst[prop] || src[prop];
      });
      return dst;
    };
  }
});

// node_modules/form-data/lib/form_data.js
var require_form_data = __commonJS({
  "node_modules/form-data/lib/form_data.js"(exports2, module2) {
    "use strict";
    init_esbuild_shims();
    var CombinedStream = require_combined_stream();
    var util5 = __require("util");
    var path150 = __require("path");
    var http9 = __require("http");
    var https9 = __require("https");
    var parseUrl = __require("url").parse;
    var fs142 = __require("fs");
    var Stream9 = __require("stream").Stream;
    var crypto18 = __require("crypto");
    var mime = require_mime_types();
    var asynckit = require_asynckit();
    var setToStringTag = require_es_set_tostringtag();
    var hasOwn3 = require_hasown();
    var populate = require_populate();
    function FormData7(options2) {
      if (!(this instanceof FormData7)) {
        return new FormData7(options2);
      }
      this._overheadLength = 0;
      this._valueLength = 0;
      this._valuesToMeasure = [];
      CombinedStream.call(this);
      options2 = options2 || {};
      for (var option2 in options2) {
        this[option2] = options2[option2];
      }
    }
    __name(FormData7, "FormData");
    util5.inherits(FormData7, CombinedStream);
    FormData7.LINE_BREAK = "\r\n";
    FormData7.DEFAULT_CONTENT_TYPE = "application/octet-stream";
    FormData7.prototype.append = function(field, value, options2) {
      options2 = options2 || {};
      if (typeof options2 === "string") {
        options2 = { filename: options2 };
      }
      var append3 = CombinedStream.prototype.append.bind(this);
      if (typeof value === "number" || value == null) {
        value = String(value);
      }
      if (Array.isArray(value)) {
        this._error(new Error("Arrays are not supported."));
        return;
      }
      var header = this._multiPartHeader(field, value, options2);
      var footer = this._multiPartFooter();
      append3(header);
      append3(value);
      append3(footer);
      this._trackLength(header, value, options2);
    };
    FormData7.prototype._trackLength = function(header, value, options2) {
      var valueLength = 0;
      if (options2.knownLength != null) {
        valueLength += Number(options2.knownLength);
      } else if (Buffer.isBuffer(value)) {
        valueLength = value.length;
      } else if (typeof value === "string") {
        valueLength = Buffer.byteLength(value);
      }
      this._valueLength += valueLength;
      this._overheadLength += Buffer.byteLength(header) + FormData7.LINE_BREAK.length;
      if (!value || !value.path && !(value.readable && hasOwn3(value, "httpVersion")) && !(value instanceof Stream9)) {
        return;
      }
      if (!options2.knownLength) {
        this._valuesToMeasure.push(value);
      }
    };
    FormData7.prototype._lengthRetriever = function(value, callback) {
      if (hasOwn3(value, "fd")) {
        if (value.end != void 0 && value.end != Infinity && value.start != void 0) {
          callback(null, value.end + 1 - (value.start ? value.start : 0));
        } else {
          fs142.stat(value.path, function(err2, stat14) {
            if (err2) {
              callback(err2);
              return;
            }
            var fileSize = stat14.size - (value.start ? value.start : 0);
            callback(null, fileSize);
          });
        }
      } else if (hasOwn3(value, "httpVersion")) {
        callback(null, Number(value.headers["content-length"]));
      } else if (hasOwn3(value, "httpModule")) {
        value.on("response", function(response) {
          value.pause();
          callback(null, Number(response.headers["content-length"]));
        });
        value.resume();
      } else {
        callback("Unknown stream");
      }
    };
    FormData7.prototype._multiPartHeader = function(field, value, options2) {
      if (typeof options2.header === "string") {
        return options2.header;
      }
      var contentDisposition = this._getContentDisposition(value, options2);
      var contentType = this._getContentType(value, options2);
      var contents = "";
      var headers = {
        // add custom disposition as third element or keep it two elements if not
        "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []),
        // if no content type. allow it to be empty array
        "Content-Type": [].concat(contentType || [])
      };
      if (typeof options2.header === "object") {
        populate(headers, options2.header);
      }
      var header;
      for (var prop in headers) {
        if (hasOwn3(headers, prop)) {
          header = headers[prop];
          if (header == null) {
            continue;
          }
          if (!Array.isArray(header)) {
            header = [header];
          }
          if (header.length) {
            contents += prop + ": " + header.join("; ") + FormData7.LINE_BREAK;
          }
        }
      }
      return "--" + this.getBoundary() + FormData7.LINE_BREAK + contents + FormData7.LINE_BREAK;
    };
    FormData7.prototype._getContentDisposition = function(value, options2) {
      var filename;
      if (typeof options2.filepath === "string") {
        filename = path150.normalize(options2.filepath).replace(/\\/g, "/");
      } else if (options2.filename || value && (value.name || value.path)) {
        filename = path150.basename(options2.filename || value && (value.name || value.path));
      } else if (value && value.readable && hasOwn3(value, "httpVersion")) {
        filename = path150.basename(value.client._httpMessage.path || "");
      }
      if (filename) {
        return 'filename="' + filename + '"';
      }
    };
    FormData7.prototype._getContentType = function(value, options2) {
      var contentType = options2.contentType;
      if (!contentType && value && value.name) {
        contentType = mime.lookup(value.name);
      }
      if (!contentType && value && value.path) {
        contentType = mime.lookup(value.path);
      }
      if (!contentType && value && value.readable && hasOwn3(value, "httpVersion")) {
        contentType = value.headers["content-type"];
      }
      if (!contentType && (options2.filepath || options2.filename)) {
        contentType = mime.lookup(options2.filepath || options2.filename);
      }
      if (!contentType && value && typeof value === "object") {
        contentType = FormData7.DEFAULT_CONTENT_TYPE;
      }
      return contentType;
    };
    FormData7.prototype._multiPartFooter = function() {
      return function(next) {
        var footer = FormData7.LINE_BREAK;
        var lastPart = this._streams.length === 0;
        if (lastPart) {
          footer += this._lastBoundary();
        }
        next(footer);
      }.bind(this);
    };
    FormData7.prototype._lastBoundary = function() {
      return "--" + this.getBoundary() + "--" + FormData7.LINE_BREAK;
    };
    FormData7.prototype.getHeaders = function(userHeaders) {
      var header;
      var formHeaders = {
        "content-type": "multipart/form-data; boundary=" + this.getBoundary()
      };
      for (header in userHeaders) {
        if (hasOwn3(userHeaders, header)) {
          formHeaders[header.toLowerCase()] = userHeaders[header];
        }
      }
      return formHeaders;
    };
    FormData7.prototype.setBoundary = function(boundary) {
      if (typeof boundary !== "string") {
        throw new TypeError("FormData boundary must be a string");
      }
      this._boundary = boundary;
    };
    FormData7.prototype.getBoundary = function() {
      if (!this._boundary) {
        this._generateBoundary();
      }
      return this._boundary;
    };
    FormData7.prototype.getBuffer = function() {
      var dataBuffer = new Buffer.alloc(0);
      var boundary = this.getBoundary();
      for (var i4 = 0, len = this._streams.length; i4 < len; i4++) {
        if (typeof this._streams[i4] !== "function") {
          if (Buffer.isBuffer(this._streams[i4])) {
            dataBuffer = Buffer.concat([dataBuffer, this._streams[i4]]);
          } else {
            dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i4])]);
          }
          if (typeof this._streams[i4] !== "string" || this._streams[i4].substring(2, boundary.length + 2) !== boundary) {
            dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData7.LINE_BREAK)]);
          }
        }
      }
      return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]);
    };
    FormData7.prototype._generateBoundary = function() {
      this._boundary = "--------------------------" + crypto18.randomBytes(12).toString("hex");
    };
    FormData7.prototype.getLengthSync = function() {
      var knownLength = this._overheadLength + this._valueLength;
      if (this._streams.length) {
        knownLength += this._lastBoundary().length;
      }
      if (!this.hasKnownLength()) {
        this._error(new Error("Cannot calculate proper length in synchronous way."));
      }
      return knownLength;
    };
    FormData7.prototype.hasKnownLength = function() {
      var hasKnownLength = true;
      if (this._valuesToMeasure.length) {
        hasKnownLength = false;
      }
      return hasKnownLength;
    };
    FormData7.prototype.getLength = function(cb) {
      var knownLength = this._overheadLength + this._valueLength;
      if (this._streams.length) {
        knownLength += this._lastBoundary().length;
      }
      if (!this._valuesToMeasure.length) {
        process.nextTick(cb.bind(this, null, knownLength));
        return;
      }
      asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err2, values) {
        if (err2) {
          cb(err2);
          return;
        }
        values.forEach(function(length) {
          knownLength += length;
        });
        cb(null, knownLength);
      });
    };
    FormData7.prototype.submit = function(params, cb) {
      var request4;
      var options2;
      var defaults4 = { method: "post" };
      if (typeof params === "string") {
        params = parseUrl(params);
        options2 = populate({
          port: params.port,
          path: params.pathname,
          host: params.hostname,
          protocol: params.protocol
        }, defaults4);
      } else {
        options2 = populate(params, defaults4);
        if (!options2.port) {
          options2.port = options2.protocol === "https:" ? 443 : 80;
        }
      }
      options2.headers = this.getHeaders(params.headers);
      if (options2.protocol === "https:") {
        request4 = https9.request(options2);
      } else {
        request4 = http9.request(options2);
      }
      this.getLength(function(err2, length) {
        if (err2 && err2 !== "Unknown stream") {
          this._error(err2);
          return;
        }
        if (length) {
          request4.setHeader("Content-Length", length);
        }
        this.pipe(request4);
        if (cb) {
          var onResponse;
          var callback = /* @__PURE__ */ __name(function(error40, responce) {
            request4.removeListener("error", callback);
            request4.removeListener("response", onResponse);
            return cb.call(this, error40, responce);
          }, "callback");
          onResponse = callback.bind(this, null);
          request4.on("error", callback);
          request4.on("response", onResponse);
        }
      }.bind(this));
      return request4;
    };
    FormData7.prototype._error = function(err2) {
      if (!this.error) {
        this.error = err2;
        this.pause();
        this.emit("error", err2);
      }
    };
    FormData7.prototype.toString = function() {
      return "[object FormData]";
    };
    setToStringTag(FormData7.prototype, "FormData");
    module2.exports = FormData7;
  }
});

// node_modules/axios/lib/platform/node/classes/FormData.js
var import_form_data, FormData_default;
var init_FormData2 = __esm({
  "node_modules/axios/lib/platform/node/classes/FormData.js"() {
    init_esbuild_shims();
    import_form_data = __toESM(require_form_data(), 1);
    FormData_default = import_form_data.default;
  }
});

// node_modules/axios/lib/helpers/toFormData.js
function isVisitable(thing) {
  return utils_default.isPlainObject(thing) || utils_default.isArray(thing);
}
function removeBrackets(key) {
  return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key;
}
function renderKey(path150, key, dots) {
  if (!path150) return key;
  return path150.concat(key).map(/* @__PURE__ */ __name(function each(token2, i4) {
    token2 = removeBrackets(token2);
    return !dots && i4 ? "[" + token2 + "]" : token2;
  }, "each")).join(dots ? "." : "");
}
function isFlatArray(arr) {
  return utils_default.isArray(arr) && !arr.some(isVisitable);
}
function toFormData2(obj, formData, options2) {
  if (!utils_default.isObject(obj)) {
    throw new TypeError("target must be an object");
  }
  formData = formData || new (FormData_default || FormData)();
  options2 = utils_default.toFlatObject(
    options2,
    {
      metaTokens: true,
      dots: false,
      indexes: false
    },
    false,
    /* @__PURE__ */ __name(function defined(option2, source2) {
      return !utils_default.isUndefined(source2[option2]);
    }, "defined")
  );
  const metaTokens = options2.metaTokens;
  const visitor = options2.visitor || defaultVisitor;
  const dots = options2.dots;
  const indexes = options2.indexes;
  const _Blob2 = options2.Blob || typeof Blob !== "undefined" && Blob;
  const useBlob = _Blob2 && utils_default.isSpecCompliantForm(formData);
  if (!utils_default.isFunction(visitor)) {
    throw new TypeError("visitor must be a function");
  }
  function convertValue(value) {
    if (value === null) return "";
    if (utils_default.isDate(value)) {
      return value.toISOString();
    }
    if (utils_default.isBoolean(value)) {
      return value.toString();
    }
    if (!useBlob && utils_default.isBlob(value)) {
      throw new AxiosError_default("Blob is not supported. Use a Buffer instead.");
    }
    if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) {
      return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
    }
    return value;
  }
  __name(convertValue, "convertValue");
  function defaultVisitor(value, key, path150) {
    let arr = value;
    if (utils_default.isReactNative(formData) && utils_default.isReactNativeBlob(value)) {
      formData.append(renderKey(path150, key, dots), convertValue(value));
      return false;
    }
    if (value && !path150 && typeof value === "object") {
      if (utils_default.endsWith(key, "{}")) {
        key = metaTokens ? key : key.slice(0, -2);
        value = JSON.stringify(value);
      } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) {
        key = removeBrackets(key);
        arr.forEach(/* @__PURE__ */ __name(function each(el, index) {
          !(utils_default.isUndefined(el) || el === null) && formData.append(
            // eslint-disable-next-line no-nested-ternary
            indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]",
            convertValue(el)
          );
        }, "each"));
        return false;
      }
    }
    if (isVisitable(value)) {
      return true;
    }
    formData.append(renderKey(path150, key, dots), convertValue(value));
    return false;
  }
  __name(defaultVisitor, "defaultVisitor");
  const stack = [];
  const exposedHelpers = Object.assign(predicates, {
    defaultVisitor,
    convertValue,
    isVisitable
  });
  function build(value, path150) {
    if (utils_default.isUndefined(value)) return;
    if (stack.indexOf(value) !== -1) {
      throw Error("Circular reference detected in " + path150.join("."));
    }
    stack.push(value);
    utils_default.forEach(value, /* @__PURE__ */ __name(function each(el, key) {
      const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path150, exposedHelpers);
      if (result === true) {
        build(el, path150 ? path150.concat(key) : [key]);
      }
    }, "each"));
    stack.pop();
  }
  __name(build, "build");
  if (!utils_default.isObject(obj)) {
    throw new TypeError("data must be an object");
  }
  build(obj);
  return formData;
}
var predicates, toFormData_default;
var init_toFormData = __esm({
  "node_modules/axios/lib/helpers/toFormData.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    init_AxiosError();
    init_FormData2();
    __name(isVisitable, "isVisitable");
    __name(removeBrackets, "removeBrackets");
    __name(renderKey, "renderKey");
    __name(isFlatArray, "isFlatArray");
    predicates = utils_default.toFlatObject(utils_default, {}, null, /* @__PURE__ */ __name(function filter4(prop) {
      return /^is[A-Z]/.test(prop);
    }, "filter"));
    __name(toFormData2, "toFormData");
    toFormData_default = toFormData2;
  }
});

// node_modules/axios/lib/helpers/AxiosURLSearchParams.js
function encode4(str2) {
  const charMap = {
    "!": "%21",
    "'": "%27",
    "(": "%28",
    ")": "%29",
    "~": "%7E",
    "%20": "+",
    "%00": "\0"
  };
  return encodeURIComponent(str2).replace(/[!'()~]|%20|%00/g, /* @__PURE__ */ __name(function replacer(match2) {
    return charMap[match2];
  }, "replacer"));
}
function AxiosURLSearchParams(params, options2) {
  this._pairs = [];
  params && toFormData_default(params, this, options2);
}
var prototype, AxiosURLSearchParams_default;
var init_AxiosURLSearchParams = __esm({
  "node_modules/axios/lib/helpers/AxiosURLSearchParams.js"() {
    "use strict";
    init_esbuild_shims();
    init_toFormData();
    __name(encode4, "encode");
    __name(AxiosURLSearchParams, "AxiosURLSearchParams");
    prototype = AxiosURLSearchParams.prototype;
    prototype.append = /* @__PURE__ */ __name(function append2(name4, value) {
      this._pairs.push([name4, value]);
    }, "append");
    prototype.toString = /* @__PURE__ */ __name(function toString2(encoder) {
      const _encode = encoder ? function(value) {
        return encoder.call(this, value, encode4);
      } : encode4;
      return this._pairs.map(/* @__PURE__ */ __name(function each(pair) {
        return _encode(pair[0]) + "=" + _encode(pair[1]);
      }, "each"), "").join("&");
    }, "toString");
    AxiosURLSearchParams_default = AxiosURLSearchParams;
  }
});

// node_modules/axios/lib/helpers/buildURL.js
function encode5(val) {
  return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+");
}
function buildURL(url3, params, options2) {
  if (!params) {
    return url3;
  }
  const _encode = options2 && options2.encode || encode5;
  const _options = utils_default.isFunction(options2) ? {
    serialize: options2
  } : options2;
  const serializeFn = _options && _options.serialize;
  let serializedParams;
  if (serializeFn) {
    serializedParams = serializeFn(params, _options);
  } else {
    serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, _options).toString(_encode);
  }
  if (serializedParams) {
    const hashmarkIndex = url3.indexOf("#");
    if (hashmarkIndex !== -1) {
      url3 = url3.slice(0, hashmarkIndex);
    }
    url3 += (url3.indexOf("?") === -1 ? "?" : "&") + serializedParams;
  }
  return url3;
}
var init_buildURL = __esm({
  "node_modules/axios/lib/helpers/buildURL.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    init_AxiosURLSearchParams();
    __name(encode5, "encode");
    __name(buildURL, "buildURL");
  }
});

// node_modules/axios/lib/core/InterceptorManager.js
var InterceptorManager, InterceptorManager_default;
var init_InterceptorManager = __esm({
  "node_modules/axios/lib/core/InterceptorManager.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    InterceptorManager = class {
      static {
        __name(this, "InterceptorManager");
      }
      constructor() {
        this.handlers = [];
      }
      /**
       * Add a new interceptor to the stack
       *
       * @param {Function} fulfilled The function to handle `then` for a `Promise`
       * @param {Function} rejected The function to handle `reject` for a `Promise`
       * @param {Object} options The options for the interceptor, synchronous and runWhen
       *
       * @return {Number} An ID used to remove interceptor later
       */
      use(fulfilled, rejected, options2) {
        this.handlers.push({
          fulfilled,
          rejected,
          synchronous: options2 ? options2.synchronous : false,
          runWhen: options2 ? options2.runWhen : null
        });
        return this.handlers.length - 1;
      }
      /**
       * Remove an interceptor from the stack
       *
       * @param {Number} id The ID that was returned by `use`
       *
       * @returns {void}
       */
      eject(id) {
        if (this.handlers[id]) {
          this.handlers[id] = null;
        }
      }
      /**
       * Clear all interceptors from the stack
       *
       * @returns {void}
       */
      clear() {
        if (this.handlers) {
          this.handlers = [];
        }
      }
      /**
       * Iterate over all the registered interceptors
       *
       * This method is particularly useful for skipping over any
       * interceptors that may have become `null` calling `eject`.
       *
       * @param {Function} fn The function to call for each interceptor
       *
       * @returns {void}
       */
      forEach(fn) {
        utils_default.forEach(this.handlers, /* @__PURE__ */ __name(function forEachHandler(h3) {
          if (h3 !== null) {
            fn(h3);
          }
        }, "forEachHandler"));
      }
    };
    InterceptorManager_default = InterceptorManager;
  }
});

// node_modules/axios/lib/defaults/transitional.js
var transitional_default;
var init_transitional = __esm({
  "node_modules/axios/lib/defaults/transitional.js"() {
    "use strict";
    init_esbuild_shims();
    transitional_default = {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false,
      legacyInterceptorReqResOrdering: true
    };
  }
});

// node_modules/axios/lib/platform/node/classes/URLSearchParams.js
import url2 from "url";
var URLSearchParams_default;
var init_URLSearchParams = __esm({
  "node_modules/axios/lib/platform/node/classes/URLSearchParams.js"() {
    "use strict";
    init_esbuild_shims();
    URLSearchParams_default = url2.URLSearchParams;
  }
});

// node_modules/axios/lib/platform/node/index.js
import crypto15 from "crypto";
var ALPHA, DIGIT, ALPHABET, generateString, node_default2;
var init_node4 = __esm({
  "node_modules/axios/lib/platform/node/index.js"() {
    init_esbuild_shims();
    init_URLSearchParams();
    init_FormData2();
    ALPHA = "abcdefghijklmnopqrstuvwxyz";
    DIGIT = "0123456789";
    ALPHABET = {
      DIGIT,
      ALPHA,
      ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
    };
    generateString = /* @__PURE__ */ __name((size = 16, alphabet2 = ALPHABET.ALPHA_DIGIT) => {
      let str2 = "";
      const { length } = alphabet2;
      const randomValues = new Uint32Array(size);
      crypto15.randomFillSync(randomValues);
      for (let i4 = 0; i4 < size; i4++) {
        str2 += alphabet2[randomValues[i4] % length];
      }
      return str2;
    }, "generateString");
    node_default2 = {
      isNode: true,
      classes: {
        URLSearchParams: URLSearchParams_default,
        FormData: FormData_default,
        Blob: typeof Blob !== "undefined" && Blob || null
      },
      ALPHABET,
      generateString,
      protocols: ["http", "https", "file", "data"]
    };
  }
});

// node_modules/axios/lib/platform/common/utils.js
var utils_exports2 = {};
__export(utils_exports2, {
  hasBrowserEnv: () => hasBrowserEnv,
  hasStandardBrowserEnv: () => hasStandardBrowserEnv,
  hasStandardBrowserWebWorkerEnv: () => hasStandardBrowserWebWorkerEnv,
  navigator: () => _navigator,
  origin: () => origin
});
var hasBrowserEnv, _navigator, hasStandardBrowserEnv, hasStandardBrowserWebWorkerEnv, origin;
var init_utils8 = __esm({
  "node_modules/axios/lib/platform/common/utils.js"() {
    init_esbuild_shims();
    hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
    _navigator = typeof navigator === "object" && navigator || void 0;
    hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
    hasStandardBrowserWebWorkerEnv = (() => {
      return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
      self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
    })();
    origin = hasBrowserEnv && window.location.href || "http://localhost";
  }
});

// node_modules/axios/lib/platform/index.js
var platform_default;
var init_platform2 = __esm({
  "node_modules/axios/lib/platform/index.js"() {
    init_esbuild_shims();
    init_node4();
    init_utils8();
    platform_default = {
      ...utils_exports2,
      ...node_default2
    };
  }
});

// node_modules/axios/lib/helpers/toURLEncodedForm.js
function toURLEncodedForm(data, options2) {
  return toFormData_default(data, new platform_default.classes.URLSearchParams(), {
    visitor: /* @__PURE__ */ __name(function(value, key, path150, helpers) {
      if (platform_default.isNode && utils_default.isBuffer(value)) {
        this.append(key, value.toString("base64"));
        return false;
      }
      return helpers.defaultVisitor.apply(this, arguments);
    }, "visitor"),
    ...options2
  });
}
var init_toURLEncodedForm = __esm({
  "node_modules/axios/lib/helpers/toURLEncodedForm.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    init_toFormData();
    init_platform2();
    __name(toURLEncodedForm, "toURLEncodedForm");
  }
});

// node_modules/axios/lib/helpers/formDataToJSON.js
function parsePropPath(name4) {
  return utils_default.matchAll(/\w+|\[(\w*)]/g, name4).map((match2) => {
    return match2[0] === "[]" ? "" : match2[1] || match2[0];
  });
}
function arrayToObject(arr) {
  const obj = {};
  const keys = Object.keys(arr);
  let i4;
  const len = keys.length;
  let key;
  for (i4 = 0; i4 < len; i4++) {
    key = keys[i4];
    obj[key] = arr[key];
  }
  return obj;
}
function formDataToJSON(formData) {
  function buildPath(path150, value, target, index) {
    let name4 = path150[index++];
    if (name4 === "__proto__") return true;
    const isNumericKey = Number.isFinite(+name4);
    const isLast = index >= path150.length;
    name4 = !name4 && utils_default.isArray(target) ? target.length : name4;
    if (isLast) {
      if (utils_default.hasOwnProp(target, name4)) {
        target[name4] = [target[name4], value];
      } else {
        target[name4] = value;
      }
      return !isNumericKey;
    }
    if (!target[name4] || !utils_default.isObject(target[name4])) {
      target[name4] = [];
    }
    const result = buildPath(path150, value, target[name4], index);
    if (result && utils_default.isArray(target[name4])) {
      target[name4] = arrayToObject(target[name4]);
    }
    return !isNumericKey;
  }
  __name(buildPath, "buildPath");
  if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) {
    const obj = {};
    utils_default.forEachEntry(formData, (name4, value) => {
      buildPath(parsePropPath(name4), value, obj, 0);
    });
    return obj;
  }
  return null;
}
var formDataToJSON_default;
var init_formDataToJSON = __esm({
  "node_modules/axios/lib/helpers/formDataToJSON.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    __name(parsePropPath, "parsePropPath");
    __name(arrayToObject, "arrayToObject");
    __name(formDataToJSON, "formDataToJSON");
    formDataToJSON_default = formDataToJSON;
  }
});

// node_modules/axios/lib/defaults/index.js
function stringifySafely(rawValue, parser6, encoder) {
  if (utils_default.isString(rawValue)) {
    try {
      (parser6 || JSON.parse)(rawValue);
      return utils_default.trim(rawValue);
    } catch (e4) {
      if (e4.name !== "SyntaxError") {
        throw e4;
      }
    }
  }
  return (encoder || JSON.stringify)(rawValue);
}
var defaults3, defaults_default;
var init_defaults = __esm({
  "node_modules/axios/lib/defaults/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    init_AxiosError();
    init_transitional();
    init_toFormData();
    init_toURLEncodedForm();
    init_platform2();
    init_formDataToJSON();
    __name(stringifySafely, "stringifySafely");
    defaults3 = {
      transitional: transitional_default,
      adapter: ["xhr", "http", "fetch"],
      transformRequest: [
        /* @__PURE__ */ __name(function transformRequest(data, headers) {
          const contentType = headers.getContentType() || "";
          const hasJSONContentType = contentType.indexOf("application/json") > -1;
          const isObjectPayload = utils_default.isObject(data);
          if (isObjectPayload && utils_default.isHTMLForm(data)) {
            data = new FormData(data);
          }
          const isFormData3 = utils_default.isFormData(data);
          if (isFormData3) {
            return hasJSONContentType ? JSON.stringify(formDataToJSON_default(data)) : data;
          }
          if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data) || utils_default.isReadableStream(data)) {
            return data;
          }
          if (utils_default.isArrayBufferView(data)) {
            return data.buffer;
          }
          if (utils_default.isURLSearchParams(data)) {
            headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
            return data.toString();
          }
          let isFileList2;
          if (isObjectPayload) {
            if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
              return toURLEncodedForm(data, this.formSerializer).toString();
            }
            if ((isFileList2 = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
              const _FormData = this.env && this.env.FormData;
              return toFormData_default(
                isFileList2 ? { "files[]": data } : data,
                _FormData && new _FormData(),
                this.formSerializer
              );
            }
          }
          if (isObjectPayload || hasJSONContentType) {
            headers.setContentType("application/json", false);
            return stringifySafely(data);
          }
          return data;
        }, "transformRequest")
      ],
      transformResponse: [
        /* @__PURE__ */ __name(function transformResponse(data) {
          const transitional2 = this.transitional || defaults3.transitional;
          const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
          const JSONRequested = this.responseType === "json";
          if (utils_default.isResponse(data) || utils_default.isReadableStream(data)) {
            return data;
          }
          if (data && utils_default.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
            const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
            const strictJSONParsing = !silentJSONParsing && JSONRequested;
            try {
              return JSON.parse(data, this.parseReviver);
            } catch (e4) {
              if (strictJSONParsing) {
                if (e4.name === "SyntaxError") {
                  throw AxiosError_default.from(e4, AxiosError_default.ERR_BAD_RESPONSE, this, null, this.response);
                }
                throw e4;
              }
            }
          }
          return data;
        }, "transformResponse")
      ],
      /**
       * A timeout in milliseconds to abort a request. If set to 0 (default) a
       * timeout is not created.
       */
      timeout: 0,
      xsrfCookieName: "XSRF-TOKEN",
      xsrfHeaderName: "X-XSRF-TOKEN",
      maxContentLength: -1,
      maxBodyLength: -1,
      env: {
        FormData: platform_default.classes.FormData,
        Blob: platform_default.classes.Blob
      },
      validateStatus: /* @__PURE__ */ __name(function validateStatus(status) {
        return status >= 200 && status < 300;
      }, "validateStatus"),
      headers: {
        common: {
          Accept: "application/json, text/plain, */*",
          "Content-Type": void 0
        }
      }
    };
    utils_default.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
      defaults3.headers[method] = {};
    });
    defaults_default = defaults3;
  }
});

// node_modules/axios/lib/helpers/parseHeaders.js
var ignoreDuplicateOf, parseHeaders_default;
var init_parseHeaders = __esm({
  "node_modules/axios/lib/helpers/parseHeaders.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    ignoreDuplicateOf = utils_default.toObjectSet([
      "age",
      "authorization",
      "content-length",
      "content-type",
      "etag",
      "expires",
      "from",
      "host",
      "if-modified-since",
      "if-unmodified-since",
      "last-modified",
      "location",
      "max-forwards",
      "proxy-authorization",
      "referer",
      "retry-after",
      "user-agent"
    ]);
    parseHeaders_default = /* @__PURE__ */ __name((rawHeaders) => {
      const parsed = {};
      let key;
      let val;
      let i4;
      rawHeaders && rawHeaders.split("\n").forEach(/* @__PURE__ */ __name(function parser6(line) {
        i4 = line.indexOf(":");
        key = line.substring(0, i4).trim().toLowerCase();
        val = line.substring(i4 + 1).trim();
        if (!key || parsed[key] && ignoreDuplicateOf[key]) {
          return;
        }
        if (key === "set-cookie") {
          if (parsed[key]) {
            parsed[key].push(val);
          } else {
            parsed[key] = [val];
          }
        } else {
          parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
        }
      }, "parser"));
      return parsed;
    }, "default");
  }
});

// node_modules/axios/lib/core/AxiosHeaders.js
function normalizeHeader(header) {
  return header && String(header).trim().toLowerCase();
}
function normalizeValue2(value) {
  if (value === false || value == null) {
    return value;
  }
  return utils_default.isArray(value) ? value.map(normalizeValue2) : String(value);
}
function parseTokens(str2) {
  const tokens = /* @__PURE__ */ Object.create(null);
  const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  let match2;
  while (match2 = tokensRE.exec(str2)) {
    tokens[match2[1]] = match2[2];
  }
  return tokens;
}
function matchHeaderValue(context2, value, header, filter5, isHeaderNameFilter) {
  if (utils_default.isFunction(filter5)) {
    return filter5.call(this, value, header);
  }
  if (isHeaderNameFilter) {
    value = header;
  }
  if (!utils_default.isString(value)) return;
  if (utils_default.isString(filter5)) {
    return value.indexOf(filter5) !== -1;
  }
  if (utils_default.isRegExp(filter5)) {
    return filter5.test(value);
  }
}
function formatHeader(header) {
  return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str2) => {
    return char.toUpperCase() + str2;
  });
}
function buildAccessors(obj, header) {
  const accessorName = utils_default.toCamelCase(" " + header);
  ["get", "set", "has"].forEach((methodName) => {
    Object.defineProperty(obj, methodName + accessorName, {
      value: /* @__PURE__ */ __name(function(arg1, arg2, arg3) {
        return this[methodName].call(this, header, arg1, arg2, arg3);
      }, "value"),
      configurable: true
    });
  });
}
var $internals, isValidHeaderName, AxiosHeaders, AxiosHeaders_default;
var init_AxiosHeaders = __esm({
  "node_modules/axios/lib/core/AxiosHeaders.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    init_parseHeaders();
    $internals = Symbol("internals");
    __name(normalizeHeader, "normalizeHeader");
    __name(normalizeValue2, "normalizeValue");
    __name(parseTokens, "parseTokens");
    isValidHeaderName = /* @__PURE__ */ __name((str2) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str2.trim()), "isValidHeaderName");
    __name(matchHeaderValue, "matchHeaderValue");
    __name(formatHeader, "formatHeader");
    __name(buildAccessors, "buildAccessors");
    AxiosHeaders = class {
      static {
        __name(this, "AxiosHeaders");
      }
      constructor(headers) {
        headers && this.set(headers);
      }
      set(header, valueOrRewrite, rewrite) {
        const self2 = this;
        function setHeader(_value, _header, _rewrite) {
          const lHeader = normalizeHeader(_header);
          if (!lHeader) {
            throw new Error("header name must be a non-empty string");
          }
          const key = utils_default.findKey(self2, lHeader);
          if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
            self2[key || _header] = normalizeValue2(_value);
          }
        }
        __name(setHeader, "setHeader");
        const setHeaders = /* @__PURE__ */ __name((headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)), "setHeaders");
        if (utils_default.isPlainObject(header) || header instanceof this.constructor) {
          setHeaders(header, valueOrRewrite);
        } else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
          setHeaders(parseHeaders_default(header), valueOrRewrite);
        } else if (utils_default.isObject(header) && utils_default.isIterable(header)) {
          let obj = {}, dest, key;
          for (const entry of header) {
            if (!utils_default.isArray(entry)) {
              throw TypeError("Object iterator must return a key-value pair");
            }
            obj[key = entry[0]] = (dest = obj[key]) ? utils_default.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
          }
          setHeaders(obj, valueOrRewrite);
        } else {
          header != null && setHeader(valueOrRewrite, header, rewrite);
        }
        return this;
      }
      get(header, parser6) {
        header = normalizeHeader(header);
        if (header) {
          const key = utils_default.findKey(this, header);
          if (key) {
            const value = this[key];
            if (!parser6) {
              return value;
            }
            if (parser6 === true) {
              return parseTokens(value);
            }
            if (utils_default.isFunction(parser6)) {
              return parser6.call(this, value, key);
            }
            if (utils_default.isRegExp(parser6)) {
              return parser6.exec(value);
            }
            throw new TypeError("parser must be boolean|regexp|function");
          }
        }
      }
      has(header, matcher) {
        header = normalizeHeader(header);
        if (header) {
          const key = utils_default.findKey(this, header);
          return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
        }
        return false;
      }
      delete(header, matcher) {
        const self2 = this;
        let deleted = false;
        function deleteHeader(_header) {
          _header = normalizeHeader(_header);
          if (_header) {
            const key = utils_default.findKey(self2, _header);
            if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
              delete self2[key];
              deleted = true;
            }
          }
        }
        __name(deleteHeader, "deleteHeader");
        if (utils_default.isArray(header)) {
          header.forEach(deleteHeader);
        } else {
          deleteHeader(header);
        }
        return deleted;
      }
      clear(matcher) {
        const keys = Object.keys(this);
        let i4 = keys.length;
        let deleted = false;
        while (i4--) {
          const key = keys[i4];
          if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
            delete this[key];
            deleted = true;
          }
        }
        return deleted;
      }
      normalize(format4) {
        const self2 = this;
        const headers = {};
        utils_default.forEach(this, (value, header) => {
          const key = utils_default.findKey(headers, header);
          if (key) {
            self2[key] = normalizeValue2(value);
            delete self2[header];
            return;
          }
          const normalized2 = format4 ? formatHeader(header) : String(header).trim();
          if (normalized2 !== header) {
            delete self2[header];
          }
          self2[normalized2] = normalizeValue2(value);
          headers[normalized2] = true;
        });
        return this;
      }
      concat(...targets) {
        return this.constructor.concat(this, ...targets);
      }
      toJSON(asStrings) {
        const obj = /* @__PURE__ */ Object.create(null);
        utils_default.forEach(this, (value, header) => {
          value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value);
        });
        return obj;
      }
      [Symbol.iterator]() {
        return Object.entries(this.toJSON())[Symbol.iterator]();
      }
      toString() {
        return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
      }
      getSetCookie() {
        return this.get("set-cookie") || [];
      }
      get [Symbol.toStringTag]() {
        return "AxiosHeaders";
      }
      static from(thing) {
        return thing instanceof this ? thing : new this(thing);
      }
      static concat(first2, ...targets) {
        const computed = new this(first2);
        targets.forEach((target) => computed.set(target));
        return computed;
      }
      static accessor(header) {
        const internals = this[$internals] = this[$internals] = {
          accessors: {}
        };
        const accessors = internals.accessors;
        const prototype2 = this.prototype;
        function defineAccessor(_header) {
          const lHeader = normalizeHeader(_header);
          if (!accessors[lHeader]) {
            buildAccessors(prototype2, _header);
            accessors[lHeader] = true;
          }
        }
        __name(defineAccessor, "defineAccessor");
        utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
        return this;
      }
    };
    AxiosHeaders.accessor([
      "Content-Type",
      "Content-Length",
      "Accept",
      "Accept-Encoding",
      "User-Agent",
      "Authorization"
    ]);
    utils_default.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
      let mapped = key[0].toUpperCase() + key.slice(1);
      return {
        get: /* @__PURE__ */ __name(() => value, "get"),
        set(headerValue) {
          this[mapped] = headerValue;
        }
      };
    });
    utils_default.freezeMethods(AxiosHeaders);
    AxiosHeaders_default = AxiosHeaders;
  }
});

// node_modules/axios/lib/core/transformData.js
function transformData(fns, response) {
  const config2 = this || defaults_default;
  const context2 = response || config2;
  const headers = AxiosHeaders_default.from(context2.headers);
  let data = context2.data;
  utils_default.forEach(fns, /* @__PURE__ */ __name(function transform2(fn) {
    data = fn.call(config2, data, headers.normalize(), response ? response.status : void 0);
  }, "transform"));
  headers.normalize();
  return data;
}
var init_transformData = __esm({
  "node_modules/axios/lib/core/transformData.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    init_defaults();
    init_AxiosHeaders();
    __name(transformData, "transformData");
  }
});

// node_modules/axios/lib/cancel/isCancel.js
function isCancel(value) {
  return !!(value && value.__CANCEL__);
}
var init_isCancel = __esm({
  "node_modules/axios/lib/cancel/isCancel.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isCancel, "isCancel");
  }
});

// node_modules/axios/lib/cancel/CanceledError.js
var CanceledError, CanceledError_default;
var init_CanceledError = __esm({
  "node_modules/axios/lib/cancel/CanceledError.js"() {
    "use strict";
    init_esbuild_shims();
    init_AxiosError();
    CanceledError = class extends AxiosError_default {
      static {
        __name(this, "CanceledError");
      }
      /**
       * A `CanceledError` is an object that is thrown when an operation is canceled.
       *
       * @param {string=} message The message.
       * @param {Object=} config The config.
       * @param {Object=} request The request.
       *
       * @returns {CanceledError} The created error.
       */
      constructor(message, config2, request4) {
        super(message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config2, request4);
        this.name = "CanceledError";
        this.__CANCEL__ = true;
      }
    };
    CanceledError_default = CanceledError;
  }
});

// node_modules/axios/lib/core/settle.js
function settle(resolve42, reject, response) {
  const validateStatus2 = response.config.validateStatus;
  if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
    resolve42(response);
  } else {
    reject(
      new AxiosError_default(
        "Request failed with status code " + response.status,
        [AxiosError_default.ERR_BAD_REQUEST, AxiosError_default.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
        response.config,
        response.request,
        response
      )
    );
  }
}
var init_settle = __esm({
  "node_modules/axios/lib/core/settle.js"() {
    "use strict";
    init_esbuild_shims();
    init_AxiosError();
    __name(settle, "settle");
  }
});

// node_modules/axios/lib/helpers/isAbsoluteURL.js
function isAbsoluteURL3(url3) {
  if (typeof url3 !== "string") {
    return false;
  }
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url3);
}
var init_isAbsoluteURL = __esm({
  "node_modules/axios/lib/helpers/isAbsoluteURL.js"() {
    "use strict";
    init_esbuild_shims();
    __name(isAbsoluteURL3, "isAbsoluteURL");
  }
});

// node_modules/axios/lib/helpers/combineURLs.js
function combineURLs(baseURL, relativeURL) {
  return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
}
var init_combineURLs = __esm({
  "node_modules/axios/lib/helpers/combineURLs.js"() {
    "use strict";
    init_esbuild_shims();
    __name(combineURLs, "combineURLs");
  }
});

// node_modules/axios/lib/core/buildFullPath.js
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
  let isRelativeUrl = !isAbsoluteURL3(requestedURL);
  if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
}
var init_buildFullPath = __esm({
  "node_modules/axios/lib/core/buildFullPath.js"() {
    "use strict";
    init_esbuild_shims();
    init_isAbsoluteURL();
    init_combineURLs();
    __name(buildFullPath, "buildFullPath");
  }
});

// node_modules/proxy-from-env/index.js
var require_proxy_from_env = __commonJS({
  "node_modules/proxy-from-env/index.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var parseUrl = __require("url").parse;
    var DEFAULT_PORTS = {
      ftp: 21,
      gopher: 70,
      http: 80,
      https: 443,
      ws: 80,
      wss: 443
    };
    var stringEndsWith = String.prototype.endsWith || function(s5) {
      return s5.length <= this.length && this.indexOf(s5, this.length - s5.length) !== -1;
    };
    function getProxyForUrl(url3) {
      var parsedUrl = typeof url3 === "string" ? parseUrl(url3) : url3 || {};
      var proto3 = parsedUrl.protocol;
      var hostname4 = parsedUrl.host;
      var port = parsedUrl.port;
      if (typeof hostname4 !== "string" || !hostname4 || typeof proto3 !== "string") {
        return "";
      }
      proto3 = proto3.split(":", 1)[0];
      hostname4 = hostname4.replace(/:\d*$/, "");
      port = parseInt(port) || DEFAULT_PORTS[proto3] || 0;
      if (!shouldProxy(hostname4, port)) {
        return "";
      }
      var proxy2 = getEnv2("npm_config_" + proto3 + "_proxy") || getEnv2(proto3 + "_proxy") || getEnv2("npm_config_proxy") || getEnv2("all_proxy");
      if (proxy2 && proxy2.indexOf("://") === -1) {
        proxy2 = proto3 + "://" + proxy2;
      }
      return proxy2;
    }
    __name(getProxyForUrl, "getProxyForUrl");
    function shouldProxy(hostname4, port) {
      var NO_PROXY = (getEnv2("npm_config_no_proxy") || getEnv2("no_proxy")).toLowerCase();
      if (!NO_PROXY) {
        return true;
      }
      if (NO_PROXY === "*") {
        return false;
      }
      return NO_PROXY.split(/[,\s]/).every(function(proxy2) {
        if (!proxy2) {
          return true;
        }
        var parsedProxy = proxy2.match(/^(.+):(\d+)$/);
        var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy2;
        var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
        if (parsedProxyPort && parsedProxyPort !== port) {
          return true;
        }
        if (!/^[.*]/.test(parsedProxyHostname)) {
          return hostname4 !== parsedProxyHostname;
        }
        if (parsedProxyHostname.charAt(0) === "*") {
          parsedProxyHostname = parsedProxyHostname.slice(1);
        }
        return !stringEndsWith.call(hostname4, parsedProxyHostname);
      });
    }
    __name(shouldProxy, "shouldProxy");
    function getEnv2(key) {
      return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || "";
    }
    __name(getEnv2, "getEnv");
    exports2.getProxyForUrl = getProxyForUrl;
  }
});

// node_modules/follow-redirects/debug.js
var require_debug2 = __commonJS({
  "node_modules/follow-redirects/debug.js"(exports2, module2) {
    init_esbuild_shims();
    var debug3;
    module2.exports = function() {
      if (!debug3) {
        try {
          debug3 = require_src()("follow-redirects");
        } catch (error40) {
        }
        if (typeof debug3 !== "function") {
          debug3 = /* @__PURE__ */ __name(function() {
          }, "debug");
        }
      }
      debug3.apply(null, arguments);
    };
  }
});

// node_modules/follow-redirects/index.js
var require_follow_redirects = __commonJS({
  "node_modules/follow-redirects/index.js"(exports2, module2) {
    init_esbuild_shims();
    var url3 = __require("url");
    var URL5 = url3.URL;
    var http9 = __require("http");
    var https9 = __require("https");
    var Writable4 = __require("stream").Writable;
    var assert4 = __require("assert");
    var debug3 = require_debug2();
    (/* @__PURE__ */ __name(function detectUnsupportedEnvironment() {
      var looksLikeNode = typeof process !== "undefined";
      var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
      var looksLikeV8 = isFunction7(Error.captureStackTrace);
      if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {
        console.warn("The follow-redirects package should be excluded from browser builds.");
      }
    }, "detectUnsupportedEnvironment"))();
    var useNativeURL = false;
    try {
      assert4(new URL5(""));
    } catch (error40) {
      useNativeURL = error40.code === "ERR_INVALID_URL";
    }
    var preservedUrlFields = [
      "auth",
      "host",
      "hostname",
      "href",
      "path",
      "pathname",
      "port",
      "protocol",
      "query",
      "search",
      "hash"
    ];
    var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
    var eventHandlers = /* @__PURE__ */ Object.create(null);
    events.forEach(function(event) {
      eventHandlers[event] = function(arg1, arg2, arg3) {
        this._redirectable.emit(event, arg1, arg2, arg3);
      };
    });
    var InvalidUrlError = createErrorType(
      "ERR_INVALID_URL",
      "Invalid URL",
      TypeError
    );
    var RedirectionError = createErrorType(
      "ERR_FR_REDIRECTION_FAILURE",
      "Redirected request failed"
    );
    var TooManyRedirectsError = createErrorType(
      "ERR_FR_TOO_MANY_REDIRECTS",
      "Maximum number of redirects exceeded",
      RedirectionError
    );
    var MaxBodyLengthExceededError = createErrorType(
      "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
      "Request body larger than maxBodyLength limit"
    );
    var WriteAfterEndError = createErrorType(
      "ERR_STREAM_WRITE_AFTER_END",
      "write after end"
    );
    var destroy = Writable4.prototype.destroy || noop11;
    function RedirectableRequest(options2, responseCallback) {
      Writable4.call(this);
      this._sanitizeOptions(options2);
      this._options = options2;
      this._ended = false;
      this._ending = false;
      this._redirectCount = 0;
      this._redirects = [];
      this._requestBodyLength = 0;
      this._requestBodyBuffers = [];
      if (responseCallback) {
        this.on("response", responseCallback);
      }
      var self2 = this;
      this._onNativeResponse = function(response) {
        try {
          self2._processResponse(response);
        } catch (cause) {
          self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause }));
        }
      };
      this._performRequest();
    }
    __name(RedirectableRequest, "RedirectableRequest");
    RedirectableRequest.prototype = Object.create(Writable4.prototype);
    RedirectableRequest.prototype.abort = function() {
      destroyRequest(this._currentRequest);
      this._currentRequest.abort();
      this.emit("abort");
    };
    RedirectableRequest.prototype.destroy = function(error40) {
      destroyRequest(this._currentRequest, error40);
      destroy.call(this, error40);
      return this;
    };
    RedirectableRequest.prototype.write = function(data, encoding, callback) {
      if (this._ending) {
        throw new WriteAfterEndError();
      }
      if (!isString3(data) && !isBuffer2(data)) {
        throw new TypeError("data should be a string, Buffer or Uint8Array");
      }
      if (isFunction7(encoding)) {
        callback = encoding;
        encoding = null;
      }
      if (data.length === 0) {
        if (callback) {
          callback();
        }
        return;
      }
      if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
        this._requestBodyLength += data.length;
        this._requestBodyBuffers.push({ data, encoding });
        this._currentRequest.write(data, encoding, callback);
      } else {
        this.emit("error", new MaxBodyLengthExceededError());
        this.abort();
      }
    };
    RedirectableRequest.prototype.end = function(data, encoding, callback) {
      if (isFunction7(data)) {
        callback = data;
        data = encoding = null;
      } else if (isFunction7(encoding)) {
        callback = encoding;
        encoding = null;
      }
      if (!data) {
        this._ended = this._ending = true;
        this._currentRequest.end(null, null, callback);
      } else {
        var self2 = this;
        var currentRequest = this._currentRequest;
        this.write(data, encoding, function() {
          self2._ended = true;
          currentRequest.end(null, null, callback);
        });
        this._ending = true;
      }
    };
    RedirectableRequest.prototype.setHeader = function(name4, value) {
      this._options.headers[name4] = value;
      this._currentRequest.setHeader(name4, value);
    };
    RedirectableRequest.prototype.removeHeader = function(name4) {
      delete this._options.headers[name4];
      this._currentRequest.removeHeader(name4);
    };
    RedirectableRequest.prototype.setTimeout = function(msecs, callback) {
      var self2 = this;
      function destroyOnTimeout(socket) {
        socket.setTimeout(msecs);
        socket.removeListener("timeout", socket.destroy);
        socket.addListener("timeout", socket.destroy);
      }
      __name(destroyOnTimeout, "destroyOnTimeout");
      function startTimer(socket) {
        if (self2._timeout) {
          clearTimeout(self2._timeout);
        }
        self2._timeout = setTimeout(function() {
          self2.emit("timeout");
          clearTimer();
        }, msecs);
        destroyOnTimeout(socket);
      }
      __name(startTimer, "startTimer");
      function clearTimer() {
        if (self2._timeout) {
          clearTimeout(self2._timeout);
          self2._timeout = null;
        }
        self2.removeListener("abort", clearTimer);
        self2.removeListener("error", clearTimer);
        self2.removeListener("response", clearTimer);
        self2.removeListener("close", clearTimer);
        if (callback) {
          self2.removeListener("timeout", callback);
        }
        if (!self2.socket) {
          self2._currentRequest.removeListener("socket", startTimer);
        }
      }
      __name(clearTimer, "clearTimer");
      if (callback) {
        this.on("timeout", callback);
      }
      if (this.socket) {
        startTimer(this.socket);
      } else {
        this._currentRequest.once("socket", startTimer);
      }
      this.on("socket", destroyOnTimeout);
      this.on("abort", clearTimer);
      this.on("error", clearTimer);
      this.on("response", clearTimer);
      this.on("close", clearTimer);
      return this;
    };
    [
      "flushHeaders",
      "getHeader",
      "setNoDelay",
      "setSocketKeepAlive"
    ].forEach(function(method) {
      RedirectableRequest.prototype[method] = function(a2, b2) {
        return this._currentRequest[method](a2, b2);
      };
    });
    ["aborted", "connection", "socket"].forEach(function(property) {
      Object.defineProperty(RedirectableRequest.prototype, property, {
        get: /* @__PURE__ */ __name(function() {
          return this._currentRequest[property];
        }, "get")
      });
    });
    RedirectableRequest.prototype._sanitizeOptions = function(options2) {
      if (!options2.headers) {
        options2.headers = {};
      }
      if (options2.host) {
        if (!options2.hostname) {
          options2.hostname = options2.host;
        }
        delete options2.host;
      }
      if (!options2.pathname && options2.path) {
        var searchPos = options2.path.indexOf("?");
        if (searchPos < 0) {
          options2.pathname = options2.path;
        } else {
          options2.pathname = options2.path.substring(0, searchPos);
          options2.search = options2.path.substring(searchPos);
        }
      }
    };
    RedirectableRequest.prototype._performRequest = function() {
      var protocol = this._options.protocol;
      var nativeProtocol = this._options.nativeProtocols[protocol];
      if (!nativeProtocol) {
        throw new TypeError("Unsupported protocol " + protocol);
      }
      if (this._options.agents) {
        var scheme = protocol.slice(0, -1);
        this._options.agent = this._options.agents[scheme];
      }
      var request4 = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse);
      request4._redirectable = this;
      for (var event of events) {
        request4.on(event, eventHandlers[event]);
      }
      this._currentUrl = /^\//.test(this._options.path) ? url3.format(this._options) : (
        // When making a request to a proxy, […]
        // a client MUST send the target URI in absolute-form […].
        this._options.path
      );
      if (this._isRedirect) {
        var i4 = 0;
        var self2 = this;
        var buffers = this._requestBodyBuffers;
        (/* @__PURE__ */ __name(function writeNext(error40) {
          if (request4 === self2._currentRequest) {
            if (error40) {
              self2.emit("error", error40);
            } else if (i4 < buffers.length) {
              var buffer = buffers[i4++];
              if (!request4.finished) {
                request4.write(buffer.data, buffer.encoding, writeNext);
              }
            } else if (self2._ended) {
              request4.end();
            }
          }
        }, "writeNext"))();
      }
    };
    RedirectableRequest.prototype._processResponse = function(response) {
      var statusCode = response.statusCode;
      if (this._options.trackRedirects) {
        this._redirects.push({
          url: this._currentUrl,
          headers: response.headers,
          statusCode
        });
      }
      var location = response.headers.location;
      if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) {
        response.responseUrl = this._currentUrl;
        response.redirects = this._redirects;
        this.emit("response", response);
        this._requestBodyBuffers = [];
        return;
      }
      destroyRequest(this._currentRequest);
      response.destroy();
      if (++this._redirectCount > this._options.maxRedirects) {
        throw new TooManyRedirectsError();
      }
      var requestHeaders;
      var beforeRedirect = this._options.beforeRedirect;
      if (beforeRedirect) {
        requestHeaders = Object.assign({
          // The Host header was set by nativeProtocol.request
          Host: response.req.getHeader("host")
        }, this._options.headers);
      }
      var method = this._options.method;
      if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || // RFC7231§6.4.4: The 303 (See Other) status code indicates that
      // the server is redirecting the user agent to a different resource […]
      // A user agent can perform a retrieval request targeting that URI
      // (a GET or HEAD request if using HTTP) […]
      statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) {
        this._options.method = "GET";
        this._requestBodyBuffers = [];
        removeMatchingHeaders(/^content-/i, this._options.headers);
      }
      var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
      var currentUrlParts = parseUrl(this._currentUrl);
      var currentHost = currentHostHeader || currentUrlParts.host;
      var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url3.format(Object.assign(currentUrlParts, { host: currentHost }));
      var redirectUrl = resolveUrl(location, currentUrl);
      debug3("redirecting to", redirectUrl.href);
      this._isRedirect = true;
      spreadUrlObject(redirectUrl, this._options);
      if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) {
        removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
      }
      if (isFunction7(beforeRedirect)) {
        var responseDetails = {
          headers: response.headers,
          statusCode
        };
        var requestDetails = {
          url: currentUrl,
          method,
          headers: requestHeaders
        };
        beforeRedirect(this._options, responseDetails, requestDetails);
        this._sanitizeOptions(this._options);
      }
      this._performRequest();
    };
    function wrap2(protocols) {
      var exports3 = {
        maxRedirects: 21,
        maxBodyLength: 10 * 1024 * 1024
      };
      var nativeProtocols = {};
      Object.keys(protocols).forEach(function(scheme) {
        var protocol = scheme + ":";
        var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
        var wrappedProtocol = exports3[scheme] = Object.create(nativeProtocol);
        function request4(input, options2, callback) {
          if (isURL(input)) {
            input = spreadUrlObject(input);
          } else if (isString3(input)) {
            input = spreadUrlObject(parseUrl(input));
          } else {
            callback = options2;
            options2 = validateUrl2(input);
            input = { protocol };
          }
          if (isFunction7(options2)) {
            callback = options2;
            options2 = null;
          }
          options2 = Object.assign({
            maxRedirects: exports3.maxRedirects,
            maxBodyLength: exports3.maxBodyLength
          }, input, options2);
          options2.nativeProtocols = nativeProtocols;
          if (!isString3(options2.host) && !isString3(options2.hostname)) {
            options2.hostname = "::1";
          }
          assert4.equal(options2.protocol, protocol, "protocol mismatch");
          debug3("options", options2);
          return new RedirectableRequest(options2, callback);
        }
        __name(request4, "request");
        function get4(input, options2, callback) {
          var wrappedRequest = wrappedProtocol.request(input, options2, callback);
          wrappedRequest.end();
          return wrappedRequest;
        }
        __name(get4, "get");
        Object.defineProperties(wrappedProtocol, {
          request: { value: request4, configurable: true, enumerable: true, writable: true },
          get: { value: get4, configurable: true, enumerable: true, writable: true }
        });
      });
      return exports3;
    }
    __name(wrap2, "wrap");
    function noop11() {
    }
    __name(noop11, "noop");
    function parseUrl(input) {
      var parsed;
      if (useNativeURL) {
        parsed = new URL5(input);
      } else {
        parsed = validateUrl2(url3.parse(input));
        if (!isString3(parsed.protocol)) {
          throw new InvalidUrlError({ input });
        }
      }
      return parsed;
    }
    __name(parseUrl, "parseUrl");
    function resolveUrl(relative14, base) {
      return useNativeURL ? new URL5(relative14, base) : parseUrl(url3.resolve(base, relative14));
    }
    __name(resolveUrl, "resolveUrl");
    function validateUrl2(input) {
      if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
        throw new InvalidUrlError({ input: input.href || input });
      }
      if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
        throw new InvalidUrlError({ input: input.href || input });
      }
      return input;
    }
    __name(validateUrl2, "validateUrl");
    function spreadUrlObject(urlObject, target) {
      var spread3 = target || {};
      for (var key of preservedUrlFields) {
        spread3[key] = urlObject[key];
      }
      if (spread3.hostname.startsWith("[")) {
        spread3.hostname = spread3.hostname.slice(1, -1);
      }
      if (spread3.port !== "") {
        spread3.port = Number(spread3.port);
      }
      spread3.path = spread3.search ? spread3.pathname + spread3.search : spread3.pathname;
      return spread3;
    }
    __name(spreadUrlObject, "spreadUrlObject");
    function removeMatchingHeaders(regex3, headers) {
      var lastValue;
      for (var header in headers) {
        if (regex3.test(header)) {
          lastValue = headers[header];
          delete headers[header];
        }
      }
      return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim();
    }
    __name(removeMatchingHeaders, "removeMatchingHeaders");
    function createErrorType(code2, message, baseClass) {
      function CustomError(properties) {
        if (isFunction7(Error.captureStackTrace)) {
          Error.captureStackTrace(this, this.constructor);
        }
        Object.assign(this, properties || {});
        this.code = code2;
        this.message = this.cause ? message + ": " + this.cause.message : message;
      }
      __name(CustomError, "CustomError");
      CustomError.prototype = new (baseClass || Error)();
      Object.defineProperties(CustomError.prototype, {
        constructor: {
          value: CustomError,
          enumerable: false
        },
        name: {
          value: "Error [" + code2 + "]",
          enumerable: false
        }
      });
      return CustomError;
    }
    __name(createErrorType, "createErrorType");
    function destroyRequest(request4, error40) {
      for (var event of events) {
        request4.removeListener(event, eventHandlers[event]);
      }
      request4.on("error", noop11);
      request4.destroy(error40);
    }
    __name(destroyRequest, "destroyRequest");
    function isSubdomain(subdomain, domain2) {
      assert4(isString3(subdomain) && isString3(domain2));
      var dot = subdomain.length - domain2.length - 1;
      return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain2);
    }
    __name(isSubdomain, "isSubdomain");
    function isString3(value) {
      return typeof value === "string" || value instanceof String;
    }
    __name(isString3, "isString");
    function isFunction7(value) {
      return typeof value === "function";
    }
    __name(isFunction7, "isFunction");
    function isBuffer2(value) {
      return typeof value === "object" && "length" in value;
    }
    __name(isBuffer2, "isBuffer");
    function isURL(value) {
      return URL5 && value instanceof URL5;
    }
    __name(isURL, "isURL");
    module2.exports = wrap2({ http: http9, https: https9 });
    module2.exports.wrap = wrap2;
  }
});

// node_modules/axios/lib/env/data.js
var VERSION5;
var init_data = __esm({
  "node_modules/axios/lib/env/data.js"() {
    init_esbuild_shims();
    VERSION5 = "1.13.6";
  }
});

// node_modules/axios/lib/helpers/parseProtocol.js
function parseProtocol(url3) {
  const match2 = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url3);
  return match2 && match2[1] || "";
}
var init_parseProtocol = __esm({
  "node_modules/axios/lib/helpers/parseProtocol.js"() {
    "use strict";
    init_esbuild_shims();
    __name(parseProtocol, "parseProtocol");
  }
});

// node_modules/axios/lib/helpers/fromDataURI.js
function fromDataURI(uri, asBlob, options2) {
  const _Blob2 = options2 && options2.Blob || platform_default.classes.Blob;
  const protocol = parseProtocol(uri);
  if (asBlob === void 0 && _Blob2) {
    asBlob = true;
  }
  if (protocol === "data") {
    uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
    const match2 = DATA_URL_PATTERN.exec(uri);
    if (!match2) {
      throw new AxiosError_default("Invalid URL", AxiosError_default.ERR_INVALID_URL);
    }
    const mime = match2[1];
    const isBase64 = match2[2];
    const body2 = match2[3];
    const buffer = Buffer.from(decodeURIComponent(body2), isBase64 ? "base64" : "utf8");
    if (asBlob) {
      if (!_Blob2) {
        throw new AxiosError_default("Blob is not supported", AxiosError_default.ERR_NOT_SUPPORT);
      }
      return new _Blob2([buffer], { type: mime });
    }
    return buffer;
  }
  throw new AxiosError_default("Unsupported protocol " + protocol, AxiosError_default.ERR_NOT_SUPPORT);
}
var DATA_URL_PATTERN;
var init_fromDataURI = __esm({
  "node_modules/axios/lib/helpers/fromDataURI.js"() {
    "use strict";
    init_esbuild_shims();
    init_AxiosError();
    init_parseProtocol();
    init_platform2();
    DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
    __name(fromDataURI, "fromDataURI");
  }
});

// node_modules/axios/lib/helpers/AxiosTransformStream.js
import stream2 from "stream";
var kInternals, AxiosTransformStream, AxiosTransformStream_default;
var init_AxiosTransformStream = __esm({
  "node_modules/axios/lib/helpers/AxiosTransformStream.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    kInternals = Symbol("internals");
    AxiosTransformStream = class extends stream2.Transform {
      static {
        __name(this, "AxiosTransformStream");
      }
      constructor(options2) {
        options2 = utils_default.toFlatObject(
          options2,
          {
            maxRate: 0,
            chunkSize: 64 * 1024,
            minChunkSize: 100,
            timeWindow: 500,
            ticksRate: 2,
            samplesCount: 15
          },
          null,
          (prop, source2) => {
            return !utils_default.isUndefined(source2[prop]);
          }
        );
        super({
          readableHighWaterMark: options2.chunkSize
        });
        const internals = this[kInternals] = {
          timeWindow: options2.timeWindow,
          chunkSize: options2.chunkSize,
          maxRate: options2.maxRate,
          minChunkSize: options2.minChunkSize,
          bytesSeen: 0,
          isCaptured: false,
          notifiedBytesLoaded: 0,
          ts: Date.now(),
          bytes: 0,
          onReadCallback: null
        };
        this.on("newListener", (event) => {
          if (event === "progress") {
            if (!internals.isCaptured) {
              internals.isCaptured = true;
            }
          }
        });
      }
      _read(size) {
        const internals = this[kInternals];
        if (internals.onReadCallback) {
          internals.onReadCallback();
        }
        return super._read(size);
      }
      _transform(chunk, encoding, callback) {
        const internals = this[kInternals];
        const maxRate = internals.maxRate;
        const readableHighWaterMark = this.readableHighWaterMark;
        const timeWindow = internals.timeWindow;
        const divider = 1e3 / timeWindow;
        const bytesThreshold = maxRate / divider;
        const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
        const pushChunk = /* @__PURE__ */ __name((_chunk, _callback) => {
          const bytes = Buffer.byteLength(_chunk);
          internals.bytesSeen += bytes;
          internals.bytes += bytes;
          internals.isCaptured && this.emit("progress", internals.bytesSeen);
          if (this.push(_chunk)) {
            process.nextTick(_callback);
          } else {
            internals.onReadCallback = () => {
              internals.onReadCallback = null;
              process.nextTick(_callback);
            };
          }
        }, "pushChunk");
        const transformChunk = /* @__PURE__ */ __name((_chunk, _callback) => {
          const chunkSize = Buffer.byteLength(_chunk);
          let chunkRemainder = null;
          let maxChunkSize = readableHighWaterMark;
          let bytesLeft;
          let passed = 0;
          if (maxRate) {
            const now = Date.now();
            if (!internals.ts || (passed = now - internals.ts) >= timeWindow) {
              internals.ts = now;
              bytesLeft = bytesThreshold - internals.bytes;
              internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
              passed = 0;
            }
            bytesLeft = bytesThreshold - internals.bytes;
          }
          if (maxRate) {
            if (bytesLeft <= 0) {
              return setTimeout(() => {
                _callback(null, _chunk);
              }, timeWindow - passed);
            }
            if (bytesLeft < maxChunkSize) {
              maxChunkSize = bytesLeft;
            }
          }
          if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) {
            chunkRemainder = _chunk.subarray(maxChunkSize);
            _chunk = _chunk.subarray(0, maxChunkSize);
          }
          pushChunk(
            _chunk,
            chunkRemainder ? () => {
              process.nextTick(_callback, null, chunkRemainder);
            } : _callback
          );
        }, "transformChunk");
        transformChunk(chunk, /* @__PURE__ */ __name(function transformNextChunk(err2, _chunk) {
          if (err2) {
            return callback(err2);
          }
          if (_chunk) {
            transformChunk(_chunk, transformNextChunk);
          } else {
            callback(null);
          }
        }, "transformNextChunk"));
      }
    };
    AxiosTransformStream_default = AxiosTransformStream;
  }
});

// node_modules/axios/lib/helpers/readBlob.js
var asyncIterator, readBlob, readBlob_default;
var init_readBlob = __esm({
  "node_modules/axios/lib/helpers/readBlob.js"() {
    init_esbuild_shims();
    ({ asyncIterator } = Symbol);
    readBlob = /* @__PURE__ */ __name(async function* (blob) {
      if (blob.stream) {
        yield* blob.stream();
      } else if (blob.arrayBuffer) {
        yield await blob.arrayBuffer();
      } else if (blob[asyncIterator]) {
        yield* blob[asyncIterator]();
      } else {
        yield blob;
      }
    }, "readBlob");
    readBlob_default = readBlob;
  }
});

// node_modules/axios/lib/helpers/formDataToStream.js
import util3 from "util";
import { Readable as Readable6 } from "stream";
var BOUNDARY_ALPHABET, textEncoder, CRLF, CRLF_BYTES, CRLF_BYTES_COUNT, FormDataPart, formDataToStream, formDataToStream_default;
var init_formDataToStream = __esm({
  "node_modules/axios/lib/helpers/formDataToStream.js"() {
    init_esbuild_shims();
    init_utils7();
    init_readBlob();
    init_platform2();
    BOUNDARY_ALPHABET = platform_default.ALPHABET.ALPHA_DIGIT + "-_";
    textEncoder = typeof TextEncoder === "function" ? new TextEncoder() : new util3.TextEncoder();
    CRLF = "\r\n";
    CRLF_BYTES = textEncoder.encode(CRLF);
    CRLF_BYTES_COUNT = 2;
    FormDataPart = class {
      static {
        __name(this, "FormDataPart");
      }
      constructor(name4, value) {
        const { escapeName: escapeName2 } = this.constructor;
        const isStringValue = utils_default.isString(value);
        let headers = `Content-Disposition: form-data; name="${escapeName2(name4)}"${!isStringValue && value.name ? `; filename="${escapeName2(value.name)}"` : ""}${CRLF}`;
        if (isStringValue) {
          value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
        } else {
          headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`;
        }
        this.headers = textEncoder.encode(headers + CRLF);
        this.contentLength = isStringValue ? value.byteLength : value.size;
        this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
        this.name = name4;
        this.value = value;
      }
      async *encode() {
        yield this.headers;
        const { value } = this;
        if (utils_default.isTypedArray(value)) {
          yield value;
        } else {
          yield* readBlob_default(value);
        }
        yield CRLF_BYTES;
      }
      static escapeName(name4) {
        return String(name4).replace(
          /[\r\n"]/g,
          (match2) => ({
            "\r": "%0D",
            "\n": "%0A",
            '"': "%22"
          })[match2]
        );
      }
    };
    formDataToStream = /* @__PURE__ */ __name((form, headersHandler, options2) => {
      const {
        tag: tag2 = "form-data-boundary",
        size = 25,
        boundary = tag2 + "-" + platform_default.generateString(size, BOUNDARY_ALPHABET)
      } = options2 || {};
      if (!utils_default.isFormData(form)) {
        throw TypeError("FormData instance required");
      }
      if (boundary.length < 1 || boundary.length > 70) {
        throw Error("boundary must be 10-70 characters long");
      }
      const boundaryBytes = textEncoder.encode("--" + boundary + CRLF);
      const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF);
      let contentLength = footerBytes.byteLength;
      const parts2 = Array.from(form.entries()).map(([name4, value]) => {
        const part = new FormDataPart(name4, value);
        contentLength += part.size;
        return part;
      });
      contentLength += boundaryBytes.byteLength * parts2.length;
      contentLength = utils_default.toFiniteNumber(contentLength);
      const computedHeaders = {
        "Content-Type": `multipart/form-data; boundary=${boundary}`
      };
      if (Number.isFinite(contentLength)) {
        computedHeaders["Content-Length"] = contentLength;
      }
      headersHandler && headersHandler(computedHeaders);
      return Readable6.from(
        async function* () {
          for (const part of parts2) {
            yield boundaryBytes;
            yield* part.encode();
          }
          yield footerBytes;
        }()
      );
    }, "formDataToStream");
    formDataToStream_default = formDataToStream;
  }
});

// node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js
import stream3 from "stream";
var ZlibHeaderTransformStream, ZlibHeaderTransformStream_default;
var init_ZlibHeaderTransformStream = __esm({
  "node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js"() {
    "use strict";
    init_esbuild_shims();
    ZlibHeaderTransformStream = class extends stream3.Transform {
      static {
        __name(this, "ZlibHeaderTransformStream");
      }
      __transform(chunk, encoding, callback) {
        this.push(chunk);
        callback();
      }
      _transform(chunk, encoding, callback) {
        if (chunk.length !== 0) {
          this._transform = this.__transform;
          if (chunk[0] !== 120) {
            const header = Buffer.alloc(2);
            header[0] = 120;
            header[1] = 156;
            this.push(header, encoding);
          }
        }
        this.__transform(chunk, encoding, callback);
      }
    };
    ZlibHeaderTransformStream_default = ZlibHeaderTransformStream;
  }
});

// node_modules/axios/lib/helpers/callbackify.js
var callbackify, callbackify_default;
var init_callbackify = __esm({
  "node_modules/axios/lib/helpers/callbackify.js"() {
    init_esbuild_shims();
    init_utils7();
    callbackify = /* @__PURE__ */ __name((fn, reducer) => {
      return utils_default.isAsyncFn(fn) ? function(...args2) {
        const cb = args2.pop();
        fn.apply(this, args2).then((value) => {
          try {
            reducer ? cb(null, ...reducer(value)) : cb(null, value);
          } catch (err2) {
            cb(err2);
          }
        }, cb);
      } : fn;
    }, "callbackify");
    callbackify_default = callbackify;
  }
});

// node_modules/axios/lib/helpers/speedometer.js
function speedometer(samplesCount, min) {
  samplesCount = samplesCount || 10;
  const bytes = new Array(samplesCount);
  const timestamps = new Array(samplesCount);
  let head = 0;
  let tail = 0;
  let firstSampleTS;
  min = min !== void 0 ? min : 1e3;
  return /* @__PURE__ */ __name(function push2(chunkLength) {
    const now = Date.now();
    const startedAt = timestamps[tail];
    if (!firstSampleTS) {
      firstSampleTS = now;
    }
    bytes[head] = chunkLength;
    timestamps[head] = now;
    let i4 = tail;
    let bytesCount = 0;
    while (i4 !== head) {
      bytesCount += bytes[i4++];
      i4 = i4 % samplesCount;
    }
    head = (head + 1) % samplesCount;
    if (head === tail) {
      tail = (tail + 1) % samplesCount;
    }
    if (now - firstSampleTS < min) {
      return;
    }
    const passed = startedAt && now - startedAt;
    return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
  }, "push");
}
var speedometer_default;
var init_speedometer = __esm({
  "node_modules/axios/lib/helpers/speedometer.js"() {
    "use strict";
    init_esbuild_shims();
    __name(speedometer, "speedometer");
    speedometer_default = speedometer;
  }
});

// node_modules/axios/lib/helpers/throttle.js
function throttle2(fn, freq) {
  let timestamp = 0;
  let threshold = 1e3 / freq;
  let lastArgs;
  let timer;
  const invoke = /* @__PURE__ */ __name((args2, now = Date.now()) => {
    timestamp = now;
    lastArgs = null;
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    fn(...args2);
  }, "invoke");
  const throttled = /* @__PURE__ */ __name((...args2) => {
    const now = Date.now();
    const passed = now - timestamp;
    if (passed >= threshold) {
      invoke(args2, now);
    } else {
      lastArgs = args2;
      if (!timer) {
        timer = setTimeout(() => {
          timer = null;
          invoke(lastArgs);
        }, threshold - passed);
      }
    }
  }, "throttled");
  const flush = /* @__PURE__ */ __name(() => lastArgs && invoke(lastArgs), "flush");
  return [throttled, flush];
}
var throttle_default;
var init_throttle = __esm({
  "node_modules/axios/lib/helpers/throttle.js"() {
    init_esbuild_shims();
    __name(throttle2, "throttle");
    throttle_default = throttle2;
  }
});

// node_modules/axios/lib/helpers/progressEventReducer.js
var progressEventReducer, progressEventDecorator, asyncDecorator;
var init_progressEventReducer = __esm({
  "node_modules/axios/lib/helpers/progressEventReducer.js"() {
    init_esbuild_shims();
    init_speedometer();
    init_throttle();
    init_utils7();
    progressEventReducer = /* @__PURE__ */ __name((listener, isDownloadStream, freq = 3) => {
      let bytesNotified = 0;
      const _speedometer = speedometer_default(50, 250);
      return throttle_default((e4) => {
        const loaded = e4.loaded;
        const total = e4.lengthComputable ? e4.total : void 0;
        const progressBytes = loaded - bytesNotified;
        const rate = _speedometer(progressBytes);
        const inRange = loaded <= total;
        bytesNotified = loaded;
        const data = {
          loaded,
          total,
          progress: total ? loaded / total : void 0,
          bytes: progressBytes,
          rate: rate ? rate : void 0,
          estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
          event: e4,
          lengthComputable: total != null,
          [isDownloadStream ? "download" : "upload"]: true
        };
        listener(data);
      }, freq);
    }, "progressEventReducer");
    progressEventDecorator = /* @__PURE__ */ __name((total, throttled) => {
      const lengthComputable = total != null;
      return [
        (loaded) => throttled[0]({
          lengthComputable,
          total,
          loaded
        }),
        throttled[1]
      ];
    }, "progressEventDecorator");
    asyncDecorator = /* @__PURE__ */ __name((fn) => (...args2) => utils_default.asap(() => fn(...args2)), "asyncDecorator");
  }
});

// node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js
function estimateDataURLDecodedBytes(url3) {
  if (!url3 || typeof url3 !== "string") return 0;
  if (!url3.startsWith("data:")) return 0;
  const comma = url3.indexOf(",");
  if (comma < 0) return 0;
  const meta = url3.slice(5, comma);
  const body2 = url3.slice(comma + 1);
  const isBase64 = /;base64/i.test(meta);
  if (isBase64) {
    let effectiveLen = body2.length;
    const len = body2.length;
    for (let i4 = 0; i4 < len; i4++) {
      if (body2.charCodeAt(i4) === 37 && i4 + 2 < len) {
        const a2 = body2.charCodeAt(i4 + 1);
        const b2 = body2.charCodeAt(i4 + 2);
        const isHex3 = (a2 >= 48 && a2 <= 57 || a2 >= 65 && a2 <= 70 || a2 >= 97 && a2 <= 102) && (b2 >= 48 && b2 <= 57 || b2 >= 65 && b2 <= 70 || b2 >= 97 && b2 <= 102);
        if (isHex3) {
          effectiveLen -= 2;
          i4 += 2;
        }
      }
    }
    let pad2 = 0;
    let idx = len - 1;
    const tailIsPct3D = /* @__PURE__ */ __name((j2) => j2 >= 2 && body2.charCodeAt(j2 - 2) === 37 && // '%'
    body2.charCodeAt(j2 - 1) === 51 && // '3'
    (body2.charCodeAt(j2) === 68 || body2.charCodeAt(j2) === 100), "tailIsPct3D");
    if (idx >= 0) {
      if (body2.charCodeAt(idx) === 61) {
        pad2++;
        idx--;
      } else if (tailIsPct3D(idx)) {
        pad2++;
        idx -= 3;
      }
    }
    if (pad2 === 1 && idx >= 0) {
      if (body2.charCodeAt(idx) === 61) {
        pad2++;
      } else if (tailIsPct3D(idx)) {
        pad2++;
      }
    }
    const groups = Math.floor(effectiveLen / 4);
    const bytes = groups * 3 - (pad2 || 0);
    return bytes > 0 ? bytes : 0;
  }
  return Buffer.byteLength(body2, "utf8");
}
var init_estimateDataURLDecodedBytes = __esm({
  "node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js"() {
    init_esbuild_shims();
    __name(estimateDataURLDecodedBytes, "estimateDataURLDecodedBytes");
  }
});

// node_modules/axios/lib/adapters/http.js
import http6 from "http";
import https7 from "https";
import http22 from "http2";
import util4 from "util";
import zlib3 from "zlib";
import stream4 from "stream";
import { EventEmitter as EventEmitter13 } from "events";
function dispatchBeforeRedirect(options2, responseDetails) {
  if (options2.beforeRedirects.proxy) {
    options2.beforeRedirects.proxy(options2);
  }
  if (options2.beforeRedirects.config) {
    options2.beforeRedirects.config(options2, responseDetails);
  }
}
function setProxy(options2, configProxy, location) {
  let proxy2 = configProxy;
  if (!proxy2 && proxy2 !== false) {
    const proxyUrl = import_proxy_from_env.default.getProxyForUrl(location);
    if (proxyUrl) {
      proxy2 = new URL(proxyUrl);
    }
  }
  if (proxy2) {
    if (proxy2.username) {
      proxy2.auth = (proxy2.username || "") + ":" + (proxy2.password || "");
    }
    if (proxy2.auth) {
      const validProxyAuth = Boolean(proxy2.auth.username || proxy2.auth.password);
      if (validProxyAuth) {
        proxy2.auth = (proxy2.auth.username || "") + ":" + (proxy2.auth.password || "");
      } else if (typeof proxy2.auth === "object") {
        throw new AxiosError_default("Invalid proxy authorization", AxiosError_default.ERR_BAD_OPTION, { proxy: proxy2 });
      }
      const base643 = Buffer.from(proxy2.auth, "utf8").toString("base64");
      options2.headers["Proxy-Authorization"] = "Basic " + base643;
    }
    options2.headers.host = options2.hostname + (options2.port ? ":" + options2.port : "");
    const proxyHost = proxy2.hostname || proxy2.host;
    options2.hostname = proxyHost;
    options2.host = proxyHost;
    options2.port = proxy2.port;
    options2.path = location;
    if (proxy2.protocol) {
      options2.protocol = proxy2.protocol.includes(":") ? proxy2.protocol : `${proxy2.protocol}:`;
    }
  }
  options2.beforeRedirects.proxy = /* @__PURE__ */ __name(function beforeRedirect(redirectOptions) {
    setProxy(redirectOptions, configProxy, redirectOptions.href);
  }, "beforeRedirect");
}
var import_proxy_from_env, import_follow_redirects, zlibOptions, brotliOptions, isBrotliSupported, httpFollow, httpsFollow, isHttps, supportedProtocols, flushOnFinish, Http2Sessions, http2Sessions, isHttpAdapterSupported, wrapAsync, resolveFamily, buildAddressEntry, http2Transport, http_default;
var init_http = __esm({
  "node_modules/axios/lib/adapters/http.js"() {
    init_esbuild_shims();
    init_utils7();
    init_settle();
    init_buildFullPath();
    init_buildURL();
    import_proxy_from_env = __toESM(require_proxy_from_env(), 1);
    import_follow_redirects = __toESM(require_follow_redirects(), 1);
    init_data();
    init_transitional();
    init_AxiosError();
    init_CanceledError();
    init_platform2();
    init_fromDataURI();
    init_AxiosHeaders();
    init_AxiosTransformStream();
    init_formDataToStream();
    init_readBlob();
    init_ZlibHeaderTransformStream();
    init_callbackify();
    init_progressEventReducer();
    init_estimateDataURLDecodedBytes();
    zlibOptions = {
      flush: zlib3.constants.Z_SYNC_FLUSH,
      finishFlush: zlib3.constants.Z_SYNC_FLUSH
    };
    brotliOptions = {
      flush: zlib3.constants.BROTLI_OPERATION_FLUSH,
      finishFlush: zlib3.constants.BROTLI_OPERATION_FLUSH
    };
    isBrotliSupported = utils_default.isFunction(zlib3.createBrotliDecompress);
    ({ http: httpFollow, https: httpsFollow } = import_follow_redirects.default);
    isHttps = /https:?/;
    supportedProtocols = platform_default.protocols.map((protocol) => {
      return protocol + ":";
    });
    flushOnFinish = /* @__PURE__ */ __name((stream5, [throttled, flush]) => {
      stream5.on("end", flush).on("error", flush);
      return throttled;
    }, "flushOnFinish");
    Http2Sessions = class {
      static {
        __name(this, "Http2Sessions");
      }
      constructor() {
        this.sessions = /* @__PURE__ */ Object.create(null);
      }
      getSession(authority, options2) {
        options2 = Object.assign(
          {
            sessionTimeout: 1e3
          },
          options2
        );
        let authoritySessions = this.sessions[authority];
        if (authoritySessions) {
          let len = authoritySessions.length;
          for (let i4 = 0; i4 < len; i4++) {
            const [sessionHandle, sessionOptions] = authoritySessions[i4];
            if (!sessionHandle.destroyed && !sessionHandle.closed && util4.isDeepStrictEqual(sessionOptions, options2)) {
              return sessionHandle;
            }
          }
        }
        const session = http22.connect(authority, options2);
        let removed;
        const removeSession = /* @__PURE__ */ __name(() => {
          if (removed) {
            return;
          }
          removed = true;
          let entries = authoritySessions, len = entries.length, i4 = len;
          while (i4--) {
            if (entries[i4][0] === session) {
              if (len === 1) {
                delete this.sessions[authority];
              } else {
                entries.splice(i4, 1);
              }
              return;
            }
          }
        }, "removeSession");
        const originalRequestFn = session.request;
        const { sessionTimeout } = options2;
        if (sessionTimeout != null) {
          let timer;
          let streamsCount = 0;
          session.request = function() {
            const stream5 = originalRequestFn.apply(this, arguments);
            streamsCount++;
            if (timer) {
              clearTimeout(timer);
              timer = null;
            }
            stream5.once("close", () => {
              if (!--streamsCount) {
                timer = setTimeout(() => {
                  timer = null;
                  removeSession();
                }, sessionTimeout);
              }
            });
            return stream5;
          };
        }
        session.once("close", removeSession);
        let entry = [session, options2];
        authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry];
        return session;
      }
    };
    http2Sessions = new Http2Sessions();
    __name(dispatchBeforeRedirect, "dispatchBeforeRedirect");
    __name(setProxy, "setProxy");
    isHttpAdapterSupported = typeof process !== "undefined" && utils_default.kindOf(process) === "process";
    wrapAsync = /* @__PURE__ */ __name((asyncExecutor) => {
      return new Promise((resolve42, reject) => {
        let onDone;
        let isDone;
        const done = /* @__PURE__ */ __name((value, isRejected) => {
          if (isDone) return;
          isDone = true;
          onDone && onDone(value, isRejected);
        }, "done");
        const _resolve = /* @__PURE__ */ __name((value) => {
          done(value);
          resolve42(value);
        }, "_resolve");
        const _reject = /* @__PURE__ */ __name((reason) => {
          done(reason, true);
          reject(reason);
        }, "_reject");
        asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject);
      });
    }, "wrapAsync");
    resolveFamily = /* @__PURE__ */ __name(({ address, family }) => {
      if (!utils_default.isString(address)) {
        throw TypeError("address must be a string");
      }
      return {
        address,
        family: family || (address.indexOf(".") < 0 ? 6 : 4)
      };
    }, "resolveFamily");
    buildAddressEntry = /* @__PURE__ */ __name((address, family) => resolveFamily(utils_default.isObject(address) ? address : { address, family }), "buildAddressEntry");
    http2Transport = {
      request(options2, cb) {
        const authority = options2.protocol + "//" + options2.hostname + ":" + (options2.port || (options2.protocol === "https:" ? 443 : 80));
        const { http2Options, headers } = options2;
        const session = http2Sessions.getSession(authority, http2Options);
        const { HTTP2_HEADER_SCHEME, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = http22.constants;
        const http2Headers = {
          [HTTP2_HEADER_SCHEME]: options2.protocol.replace(":", ""),
          [HTTP2_HEADER_METHOD]: options2.method,
          [HTTP2_HEADER_PATH]: options2.path
        };
        utils_default.forEach(headers, (header, name4) => {
          name4.charAt(0) !== ":" && (http2Headers[name4] = header);
        });
        const req = session.request(http2Headers);
        req.once("response", (responseHeaders) => {
          const response = req;
          responseHeaders = Object.assign({}, responseHeaders);
          const status = responseHeaders[HTTP2_HEADER_STATUS];
          delete responseHeaders[HTTP2_HEADER_STATUS];
          response.headers = responseHeaders;
          response.statusCode = +status;
          cb(response);
        });
        return req;
      }
    };
    http_default = isHttpAdapterSupported && /* @__PURE__ */ __name(function httpAdapter(config2) {
      return wrapAsync(/* @__PURE__ */ __name(async function dispatchHttpRequest(resolve42, reject, onDone) {
        let { data, lookup: lookup2, family, httpVersion = 1, http2Options } = config2;
        const { responseType, responseEncoding } = config2;
        const method = config2.method.toUpperCase();
        let isDone;
        let rejected = false;
        let req;
        httpVersion = +httpVersion;
        if (Number.isNaN(httpVersion)) {
          throw TypeError(`Invalid protocol version: '${config2.httpVersion}' is not a number`);
        }
        if (httpVersion !== 1 && httpVersion !== 2) {
          throw TypeError(`Unsupported protocol version '${httpVersion}'`);
        }
        const isHttp2 = httpVersion === 2;
        if (lookup2) {
          const _lookup = callbackify_default(lookup2, (value) => utils_default.isArray(value) ? value : [value]);
          lookup2 = /* @__PURE__ */ __name((hostname4, opt, cb) => {
            _lookup(hostname4, opt, (err2, arg0, arg1) => {
              if (err2) {
                return cb(err2);
              }
              const addresses = utils_default.isArray(arg0) ? arg0.map((addr2) => buildAddressEntry(addr2)) : [buildAddressEntry(arg0, arg1)];
              opt.all ? cb(err2, addresses) : cb(err2, addresses[0].address, addresses[0].family);
            });
          }, "lookup");
        }
        const abortEmitter = new EventEmitter13();
        function abort2(reason) {
          try {
            abortEmitter.emit(
              "abort",
              !reason || reason.type ? new CanceledError_default(null, config2, req) : reason
            );
          } catch (err2) {
            console.warn("emit error", err2);
          }
        }
        __name(abort2, "abort");
        abortEmitter.once("abort", reject);
        const onFinished = /* @__PURE__ */ __name(() => {
          if (config2.cancelToken) {
            config2.cancelToken.unsubscribe(abort2);
          }
          if (config2.signal) {
            config2.signal.removeEventListener("abort", abort2);
          }
          abortEmitter.removeAllListeners();
        }, "onFinished");
        if (config2.cancelToken || config2.signal) {
          config2.cancelToken && config2.cancelToken.subscribe(abort2);
          if (config2.signal) {
            config2.signal.aborted ? abort2() : config2.signal.addEventListener("abort", abort2);
          }
        }
        onDone((response, isRejected) => {
          isDone = true;
          if (isRejected) {
            rejected = true;
            onFinished();
            return;
          }
          const { data: data2 } = response;
          if (data2 instanceof stream4.Readable || data2 instanceof stream4.Duplex) {
            const offListeners = stream4.finished(data2, () => {
              offListeners();
              onFinished();
            });
          } else {
            onFinished();
          }
        });
        const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
        const parsed = new URL(fullPath, platform_default.hasBrowserEnv ? platform_default.origin : void 0);
        const protocol = parsed.protocol || supportedProtocols[0];
        if (protocol === "data:") {
          if (config2.maxContentLength > -1) {
            const dataUrl = String(config2.url || fullPath || "");
            const estimated = estimateDataURLDecodedBytes(dataUrl);
            if (estimated > config2.maxContentLength) {
              return reject(
                new AxiosError_default(
                  "maxContentLength size of " + config2.maxContentLength + " exceeded",
                  AxiosError_default.ERR_BAD_RESPONSE,
                  config2
                )
              );
            }
          }
          let convertedData;
          if (method !== "GET") {
            return settle(resolve42, reject, {
              status: 405,
              statusText: "method not allowed",
              headers: {},
              config: config2
            });
          }
          try {
            convertedData = fromDataURI(config2.url, responseType === "blob", {
              Blob: config2.env && config2.env.Blob
            });
          } catch (err2) {
            throw AxiosError_default.from(err2, AxiosError_default.ERR_BAD_REQUEST, config2);
          }
          if (responseType === "text") {
            convertedData = convertedData.toString(responseEncoding);
            if (!responseEncoding || responseEncoding === "utf8") {
              convertedData = utils_default.stripBOM(convertedData);
            }
          } else if (responseType === "stream") {
            convertedData = stream4.Readable.from(convertedData);
          }
          return settle(resolve42, reject, {
            data: convertedData,
            status: 200,
            statusText: "OK",
            headers: new AxiosHeaders_default(),
            config: config2
          });
        }
        if (supportedProtocols.indexOf(protocol) === -1) {
          return reject(
            new AxiosError_default("Unsupported protocol " + protocol, AxiosError_default.ERR_BAD_REQUEST, config2)
          );
        }
        const headers = AxiosHeaders_default.from(config2.headers).normalize();
        headers.set("User-Agent", "axios/" + VERSION5, false);
        const { onUploadProgress, onDownloadProgress } = config2;
        const maxRate = config2.maxRate;
        let maxUploadRate = void 0;
        let maxDownloadRate = void 0;
        if (utils_default.isSpecCompliantForm(data)) {
          const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
          data = formDataToStream_default(
            data,
            (formHeaders) => {
              headers.set(formHeaders);
            },
            {
              tag: `axios-${VERSION5}-boundary`,
              boundary: userBoundary && userBoundary[1] || void 0
            }
          );
        } else if (utils_default.isFormData(data) && utils_default.isFunction(data.getHeaders)) {
          headers.set(data.getHeaders());
          if (!headers.hasContentLength()) {
            try {
              const knownLength = await util4.promisify(data.getLength).call(data);
              Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
            } catch (e4) {
            }
          }
        } else if (utils_default.isBlob(data) || utils_default.isFile(data)) {
          data.size && headers.setContentType(data.type || "application/octet-stream");
          headers.setContentLength(data.size || 0);
          data = stream4.Readable.from(readBlob_default(data));
        } else if (data && !utils_default.isStream(data)) {
          if (Buffer.isBuffer(data)) {
          } else if (utils_default.isArrayBuffer(data)) {
            data = Buffer.from(new Uint8Array(data));
          } else if (utils_default.isString(data)) {
            data = Buffer.from(data, "utf-8");
          } else {
            return reject(
              new AxiosError_default(
                "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",
                AxiosError_default.ERR_BAD_REQUEST,
                config2
              )
            );
          }
          headers.setContentLength(data.length, false);
          if (config2.maxBodyLength > -1 && data.length > config2.maxBodyLength) {
            return reject(
              new AxiosError_default(
                "Request body larger than maxBodyLength limit",
                AxiosError_default.ERR_BAD_REQUEST,
                config2
              )
            );
          }
        }
        const contentLength = utils_default.toFiniteNumber(headers.getContentLength());
        if (utils_default.isArray(maxRate)) {
          maxUploadRate = maxRate[0];
          maxDownloadRate = maxRate[1];
        } else {
          maxUploadRate = maxDownloadRate = maxRate;
        }
        if (data && (onUploadProgress || maxUploadRate)) {
          if (!utils_default.isStream(data)) {
            data = stream4.Readable.from(data, { objectMode: false });
          }
          data = stream4.pipeline(
            [
              data,
              new AxiosTransformStream_default({
                maxRate: utils_default.toFiniteNumber(maxUploadRate)
              })
            ],
            utils_default.noop
          );
          onUploadProgress && data.on(
            "progress",
            flushOnFinish(
              data,
              progressEventDecorator(
                contentLength,
                progressEventReducer(asyncDecorator(onUploadProgress), false, 3)
              )
            )
          );
        }
        let auth2 = void 0;
        if (config2.auth) {
          const username = config2.auth.username || "";
          const password = config2.auth.password || "";
          auth2 = username + ":" + password;
        }
        if (!auth2 && parsed.username) {
          const urlUsername = parsed.username;
          const urlPassword = parsed.password;
          auth2 = urlUsername + ":" + urlPassword;
        }
        auth2 && headers.delete("authorization");
        let path150;
        try {
          path150 = buildURL(
            parsed.pathname + parsed.search,
            config2.params,
            config2.paramsSerializer
          ).replace(/^\?/, "");
        } catch (err2) {
          const customErr = new Error(err2.message);
          customErr.config = config2;
          customErr.url = config2.url;
          customErr.exists = true;
          return reject(customErr);
        }
        headers.set(
          "Accept-Encoding",
          "gzip, compress, deflate" + (isBrotliSupported ? ", br" : ""),
          false
        );
        const options2 = {
          path: path150,
          method,
          headers: headers.toJSON(),
          agents: { http: config2.httpAgent, https: config2.httpsAgent },
          auth: auth2,
          protocol,
          family,
          beforeRedirect: dispatchBeforeRedirect,
          beforeRedirects: {},
          http2Options
        };
        !utils_default.isUndefined(lookup2) && (options2.lookup = lookup2);
        if (config2.socketPath) {
          options2.socketPath = config2.socketPath;
        } else {
          options2.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;
          options2.port = parsed.port;
          setProxy(
            options2,
            config2.proxy,
            protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options2.path
          );
        }
        let transport;
        const isHttpsRequest = isHttps.test(options2.protocol);
        options2.agent = isHttpsRequest ? config2.httpsAgent : config2.httpAgent;
        if (isHttp2) {
          transport = http2Transport;
        } else {
          if (config2.transport) {
            transport = config2.transport;
          } else if (config2.maxRedirects === 0) {
            transport = isHttpsRequest ? https7 : http6;
          } else {
            if (config2.maxRedirects) {
              options2.maxRedirects = config2.maxRedirects;
            }
            if (config2.beforeRedirect) {
              options2.beforeRedirects.config = config2.beforeRedirect;
            }
            transport = isHttpsRequest ? httpsFollow : httpFollow;
          }
        }
        if (config2.maxBodyLength > -1) {
          options2.maxBodyLength = config2.maxBodyLength;
        } else {
          options2.maxBodyLength = Infinity;
        }
        if (config2.insecureHTTPParser) {
          options2.insecureHTTPParser = config2.insecureHTTPParser;
        }
        req = transport.request(options2, /* @__PURE__ */ __name(function handleResponse(res) {
          if (req.destroyed) return;
          const streams = [res];
          const responseLength = utils_default.toFiniteNumber(res.headers["content-length"]);
          if (onDownloadProgress || maxDownloadRate) {
            const transformStream = new AxiosTransformStream_default({
              maxRate: utils_default.toFiniteNumber(maxDownloadRate)
            });
            onDownloadProgress && transformStream.on(
              "progress",
              flushOnFinish(
                transformStream,
                progressEventDecorator(
                  responseLength,
                  progressEventReducer(asyncDecorator(onDownloadProgress), true, 3)
                )
              )
            );
            streams.push(transformStream);
          }
          let responseStream = res;
          const lastRequest = res.req || req;
          if (config2.decompress !== false && res.headers["content-encoding"]) {
            if (method === "HEAD" || res.statusCode === 204) {
              delete res.headers["content-encoding"];
            }
            switch ((res.headers["content-encoding"] || "").toLowerCase()) {
              /*eslint default-case:0*/
              case "gzip":
              case "x-gzip":
              case "compress":
              case "x-compress":
                streams.push(zlib3.createUnzip(zlibOptions));
                delete res.headers["content-encoding"];
                break;
              case "deflate":
                streams.push(new ZlibHeaderTransformStream_default());
                streams.push(zlib3.createUnzip(zlibOptions));
                delete res.headers["content-encoding"];
                break;
              case "br":
                if (isBrotliSupported) {
                  streams.push(zlib3.createBrotliDecompress(brotliOptions));
                  delete res.headers["content-encoding"];
                }
            }
          }
          responseStream = streams.length > 1 ? stream4.pipeline(streams, utils_default.noop) : streams[0];
          const response = {
            status: res.statusCode,
            statusText: res.statusMessage,
            headers: new AxiosHeaders_default(res.headers),
            config: config2,
            request: lastRequest
          };
          if (responseType === "stream") {
            response.data = responseStream;
            settle(resolve42, reject, response);
          } else {
            const responseBuffer = [];
            let totalResponseBytes = 0;
            responseStream.on("data", /* @__PURE__ */ __name(function handleStreamData(chunk) {
              responseBuffer.push(chunk);
              totalResponseBytes += chunk.length;
              if (config2.maxContentLength > -1 && totalResponseBytes > config2.maxContentLength) {
                rejected = true;
                responseStream.destroy();
                abort2(
                  new AxiosError_default(
                    "maxContentLength size of " + config2.maxContentLength + " exceeded",
                    AxiosError_default.ERR_BAD_RESPONSE,
                    config2,
                    lastRequest
                  )
                );
              }
            }, "handleStreamData"));
            responseStream.on("aborted", /* @__PURE__ */ __name(function handlerStreamAborted() {
              if (rejected) {
                return;
              }
              const err2 = new AxiosError_default(
                "stream has been aborted",
                AxiosError_default.ERR_BAD_RESPONSE,
                config2,
                lastRequest
              );
              responseStream.destroy(err2);
              reject(err2);
            }, "handlerStreamAborted"));
            responseStream.on("error", /* @__PURE__ */ __name(function handleStreamError(err2) {
              if (req.destroyed) return;
              reject(AxiosError_default.from(err2, null, config2, lastRequest));
            }, "handleStreamError"));
            responseStream.on("end", /* @__PURE__ */ __name(function handleStreamEnd() {
              try {
                let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
                if (responseType !== "arraybuffer") {
                  responseData = responseData.toString(responseEncoding);
                  if (!responseEncoding || responseEncoding === "utf8") {
                    responseData = utils_default.stripBOM(responseData);
                  }
                }
                response.data = responseData;
              } catch (err2) {
                return reject(AxiosError_default.from(err2, null, config2, response.request, response));
              }
              settle(resolve42, reject, response);
            }, "handleStreamEnd"));
          }
          abortEmitter.once("abort", (err2) => {
            if (!responseStream.destroyed) {
              responseStream.emit("error", err2);
              responseStream.destroy();
            }
          });
        }, "handleResponse"));
        abortEmitter.once("abort", (err2) => {
          if (req.close) {
            req.close();
          } else {
            req.destroy(err2);
          }
        });
        req.on("error", /* @__PURE__ */ __name(function handleRequestError(err2) {
          reject(AxiosError_default.from(err2, null, config2, req));
        }, "handleRequestError"));
        req.on("socket", /* @__PURE__ */ __name(function handleRequestSocket(socket) {
          socket.setKeepAlive(true, 1e3 * 60);
        }, "handleRequestSocket"));
        if (config2.timeout) {
          const timeout2 = parseInt(config2.timeout, 10);
          if (Number.isNaN(timeout2)) {
            abort2(
              new AxiosError_default(
                "error trying to parse `config.timeout` to int",
                AxiosError_default.ERR_BAD_OPTION_VALUE,
                config2,
                req
              )
            );
            return;
          }
          req.setTimeout(timeout2, /* @__PURE__ */ __name(function handleRequestTimeout() {
            if (isDone) return;
            let timeoutErrorMessage = config2.timeout ? "timeout of " + config2.timeout + "ms exceeded" : "timeout exceeded";
            const transitional2 = config2.transitional || transitional_default;
            if (config2.timeoutErrorMessage) {
              timeoutErrorMessage = config2.timeoutErrorMessage;
            }
            abort2(
              new AxiosError_default(
                timeoutErrorMessage,
                transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED,
                config2,
                req
              )
            );
          }, "handleRequestTimeout"));
        } else {
          req.setTimeout(0);
        }
        if (utils_default.isStream(data)) {
          let ended = false;
          let errored = false;
          data.on("end", () => {
            ended = true;
          });
          data.once("error", (err2) => {
            errored = true;
            req.destroy(err2);
          });
          data.on("close", () => {
            if (!ended && !errored) {
              abort2(new CanceledError_default("Request stream has been aborted", config2, req));
            }
          });
          data.pipe(req);
        } else {
          data && req.write(data);
          req.end();
        }
      }, "dispatchHttpRequest"));
    }, "httpAdapter");
  }
});

// node_modules/axios/lib/helpers/isURLSameOrigin.js
var isURLSameOrigin_default;
var init_isURLSameOrigin = __esm({
  "node_modules/axios/lib/helpers/isURLSameOrigin.js"() {
    init_esbuild_shims();
    init_platform2();
    isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url3) => {
      url3 = new URL(url3, platform_default.origin);
      return origin2.protocol === url3.protocol && origin2.host === url3.host && (isMSIE || origin2.port === url3.port);
    })(
      new URL(platform_default.origin),
      platform_default.navigator && /(msie|trident)/i.test(platform_default.navigator.userAgent)
    ) : () => true;
  }
});

// node_modules/axios/lib/helpers/cookies.js
var cookies_default;
var init_cookies = __esm({
  "node_modules/axios/lib/helpers/cookies.js"() {
    init_esbuild_shims();
    init_utils7();
    init_platform2();
    cookies_default = platform_default.hasStandardBrowserEnv ? (
      // Standard browser envs support document.cookie
      {
        write(name4, value, expires, path150, domain2, secure, sameSite) {
          if (typeof document === "undefined") return;
          const cookie = [`${name4}=${encodeURIComponent(value)}`];
          if (utils_default.isNumber(expires)) {
            cookie.push(`expires=${new Date(expires).toUTCString()}`);
          }
          if (utils_default.isString(path150)) {
            cookie.push(`path=${path150}`);
          }
          if (utils_default.isString(domain2)) {
            cookie.push(`domain=${domain2}`);
          }
          if (secure === true) {
            cookie.push("secure");
          }
          if (utils_default.isString(sameSite)) {
            cookie.push(`SameSite=${sameSite}`);
          }
          document.cookie = cookie.join("; ");
        },
        read(name4) {
          if (typeof document === "undefined") return null;
          const match2 = document.cookie.match(new RegExp("(?:^|; )" + name4 + "=([^;]*)"));
          return match2 ? decodeURIComponent(match2[1]) : null;
        },
        remove(name4) {
          this.write(name4, "", Date.now() - 864e5, "/");
        }
      }
    ) : (
      // Non-standard browser env (web workers, react-native) lack needed support.
      {
        write() {
        },
        read() {
          return null;
        },
        remove() {
        }
      }
    );
  }
});

// node_modules/axios/lib/core/mergeConfig.js
function mergeConfig(config1, config2) {
  config2 = config2 || {};
  const config3 = {};
  function getMergedValue(target, source2, prop, caseless) {
    if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source2)) {
      return utils_default.merge.call({ caseless }, target, source2);
    } else if (utils_default.isPlainObject(source2)) {
      return utils_default.merge({}, source2);
    } else if (utils_default.isArray(source2)) {
      return source2.slice();
    }
    return source2;
  }
  __name(getMergedValue, "getMergedValue");
  function mergeDeepProperties(a2, b2, prop, caseless) {
    if (!utils_default.isUndefined(b2)) {
      return getMergedValue(a2, b2, prop, caseless);
    } else if (!utils_default.isUndefined(a2)) {
      return getMergedValue(void 0, a2, prop, caseless);
    }
  }
  __name(mergeDeepProperties, "mergeDeepProperties");
  function valueFromConfig2(a2, b2) {
    if (!utils_default.isUndefined(b2)) {
      return getMergedValue(void 0, b2);
    }
  }
  __name(valueFromConfig2, "valueFromConfig2");
  function defaultToConfig2(a2, b2) {
    if (!utils_default.isUndefined(b2)) {
      return getMergedValue(void 0, b2);
    } else if (!utils_default.isUndefined(a2)) {
      return getMergedValue(void 0, a2);
    }
  }
  __name(defaultToConfig2, "defaultToConfig2");
  function mergeDirectKeys(a2, b2, prop) {
    if (prop in config2) {
      return getMergedValue(a2, b2);
    } else if (prop in config1) {
      return getMergedValue(void 0, a2);
    }
  }
  __name(mergeDirectKeys, "mergeDirectKeys");
  const mergeMap = {
    url: valueFromConfig2,
    method: valueFromConfig2,
    data: valueFromConfig2,
    baseURL: defaultToConfig2,
    transformRequest: defaultToConfig2,
    transformResponse: defaultToConfig2,
    paramsSerializer: defaultToConfig2,
    timeout: defaultToConfig2,
    timeoutMessage: defaultToConfig2,
    withCredentials: defaultToConfig2,
    withXSRFToken: defaultToConfig2,
    adapter: defaultToConfig2,
    responseType: defaultToConfig2,
    xsrfCookieName: defaultToConfig2,
    xsrfHeaderName: defaultToConfig2,
    onUploadProgress: defaultToConfig2,
    onDownloadProgress: defaultToConfig2,
    decompress: defaultToConfig2,
    maxContentLength: defaultToConfig2,
    maxBodyLength: defaultToConfig2,
    beforeRedirect: defaultToConfig2,
    transport: defaultToConfig2,
    httpAgent: defaultToConfig2,
    httpsAgent: defaultToConfig2,
    cancelToken: defaultToConfig2,
    socketPath: defaultToConfig2,
    responseEncoding: defaultToConfig2,
    validateStatus: mergeDirectKeys,
    headers: /* @__PURE__ */ __name((a2, b2, prop) => mergeDeepProperties(headersToObject(a2), headersToObject(b2), prop, true), "headers")
  };
  utils_default.forEach(Object.keys({ ...config1, ...config2 }), /* @__PURE__ */ __name(function computeConfigValue(prop) {
    if (prop === "__proto__" || prop === "constructor" || prop === "prototype") return;
    const merge5 = utils_default.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
    const configValue = merge5(config1[prop], config2[prop], prop);
    utils_default.isUndefined(configValue) && merge5 !== mergeDirectKeys || (config3[prop] = configValue);
  }, "computeConfigValue"));
  return config3;
}
var headersToObject;
var init_mergeConfig = __esm({
  "node_modules/axios/lib/core/mergeConfig.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    init_AxiosHeaders();
    headersToObject = /* @__PURE__ */ __name((thing) => thing instanceof AxiosHeaders_default ? { ...thing } : thing, "headersToObject");
    __name(mergeConfig, "mergeConfig");
  }
});

// node_modules/axios/lib/helpers/resolveConfig.js
var resolveConfig_default;
var init_resolveConfig = __esm({
  "node_modules/axios/lib/helpers/resolveConfig.js"() {
    init_esbuild_shims();
    init_platform2();
    init_utils7();
    init_isURLSameOrigin();
    init_cookies();
    init_buildFullPath();
    init_mergeConfig();
    init_AxiosHeaders();
    init_buildURL();
    resolveConfig_default = /* @__PURE__ */ __name((config2) => {
      const newConfig = mergeConfig({}, config2);
      let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth: auth2 } = newConfig;
      newConfig.headers = headers = AxiosHeaders_default.from(headers);
      newConfig.url = buildURL(
        buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls),
        config2.params,
        config2.paramsSerializer
      );
      if (auth2) {
        headers.set(
          "Authorization",
          "Basic " + btoa(
            (auth2.username || "") + ":" + (auth2.password ? unescape(encodeURIComponent(auth2.password)) : "")
          )
        );
      }
      if (utils_default.isFormData(data)) {
        if (platform_default.hasStandardBrowserEnv || platform_default.hasStandardBrowserWebWorkerEnv) {
          headers.setContentType(void 0);
        } else if (utils_default.isFunction(data.getHeaders)) {
          const formHeaders = data.getHeaders();
          const allowedHeaders = ["content-type", "content-length"];
          Object.entries(formHeaders).forEach(([key, val]) => {
            if (allowedHeaders.includes(key.toLowerCase())) {
              headers.set(key, val);
            }
          });
        }
      }
      if (platform_default.hasStandardBrowserEnv) {
        withXSRFToken && utils_default.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
        if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin_default(newConfig.url)) {
          const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies_default.read(xsrfCookieName);
          if (xsrfValue) {
            headers.set(xsrfHeaderName, xsrfValue);
          }
        }
      }
      return newConfig;
    }, "default");
  }
});

// node_modules/axios/lib/adapters/xhr.js
var isXHRAdapterSupported, xhr_default;
var init_xhr = __esm({
  "node_modules/axios/lib/adapters/xhr.js"() {
    init_esbuild_shims();
    init_utils7();
    init_settle();
    init_transitional();
    init_AxiosError();
    init_CanceledError();
    init_parseProtocol();
    init_platform2();
    init_AxiosHeaders();
    init_progressEventReducer();
    init_resolveConfig();
    isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
    xhr_default = isXHRAdapterSupported && function(config2) {
      return new Promise(/* @__PURE__ */ __name(function dispatchXhrRequest(resolve42, reject) {
        const _config = resolveConfig_default(config2);
        let requestData = _config.data;
        const requestHeaders = AxiosHeaders_default.from(_config.headers).normalize();
        let { responseType, onUploadProgress, onDownloadProgress } = _config;
        let onCanceled;
        let uploadThrottled, downloadThrottled;
        let flushUpload, flushDownload;
        function done() {
          flushUpload && flushUpload();
          flushDownload && flushDownload();
          _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
          _config.signal && _config.signal.removeEventListener("abort", onCanceled);
        }
        __name(done, "done");
        let request4 = new XMLHttpRequest();
        request4.open(_config.method.toUpperCase(), _config.url, true);
        request4.timeout = _config.timeout;
        function onloadend() {
          if (!request4) {
            return;
          }
          const responseHeaders = AxiosHeaders_default.from(
            "getAllResponseHeaders" in request4 && request4.getAllResponseHeaders()
          );
          const responseData = !responseType || responseType === "text" || responseType === "json" ? request4.responseText : request4.response;
          const response = {
            data: responseData,
            status: request4.status,
            statusText: request4.statusText,
            headers: responseHeaders,
            config: config2,
            request: request4
          };
          settle(
            /* @__PURE__ */ __name(function _resolve(value) {
              resolve42(value);
              done();
            }, "_resolve"),
            /* @__PURE__ */ __name(function _reject(err2) {
              reject(err2);
              done();
            }, "_reject"),
            response
          );
          request4 = null;
        }
        __name(onloadend, "onloadend");
        if ("onloadend" in request4) {
          request4.onloadend = onloadend;
        } else {
          request4.onreadystatechange = /* @__PURE__ */ __name(function handleLoad() {
            if (!request4 || request4.readyState !== 4) {
              return;
            }
            if (request4.status === 0 && !(request4.responseURL && request4.responseURL.indexOf("file:") === 0)) {
              return;
            }
            setTimeout(onloadend);
          }, "handleLoad");
        }
        request4.onabort = /* @__PURE__ */ __name(function handleAbort() {
          if (!request4) {
            return;
          }
          reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config2, request4));
          request4 = null;
        }, "handleAbort");
        request4.onerror = /* @__PURE__ */ __name(function handleError2(event) {
          const msg = event && event.message ? event.message : "Network Error";
          const err2 = new AxiosError_default(msg, AxiosError_default.ERR_NETWORK, config2, request4);
          err2.event = event || null;
          reject(err2);
          request4 = null;
        }, "handleError");
        request4.ontimeout = /* @__PURE__ */ __name(function handleTimeout() {
          let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
          const transitional2 = _config.transitional || transitional_default;
          if (_config.timeoutErrorMessage) {
            timeoutErrorMessage = _config.timeoutErrorMessage;
          }
          reject(
            new AxiosError_default(
              timeoutErrorMessage,
              transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED,
              config2,
              request4
            )
          );
          request4 = null;
        }, "handleTimeout");
        requestData === void 0 && requestHeaders.setContentType(null);
        if ("setRequestHeader" in request4) {
          utils_default.forEach(requestHeaders.toJSON(), /* @__PURE__ */ __name(function setRequestHeader(val, key) {
            request4.setRequestHeader(key, val);
          }, "setRequestHeader"));
        }
        if (!utils_default.isUndefined(_config.withCredentials)) {
          request4.withCredentials = !!_config.withCredentials;
        }
        if (responseType && responseType !== "json") {
          request4.responseType = _config.responseType;
        }
        if (onDownloadProgress) {
          [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
          request4.addEventListener("progress", downloadThrottled);
        }
        if (onUploadProgress && request4.upload) {
          [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
          request4.upload.addEventListener("progress", uploadThrottled);
          request4.upload.addEventListener("loadend", flushUpload);
        }
        if (_config.cancelToken || _config.signal) {
          onCanceled = /* @__PURE__ */ __name((cancel) => {
            if (!request4) {
              return;
            }
            reject(!cancel || cancel.type ? new CanceledError_default(null, config2, request4) : cancel);
            request4.abort();
            request4 = null;
          }, "onCanceled");
          _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
          if (_config.signal) {
            _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
          }
        }
        const protocol = parseProtocol(_config.url);
        if (protocol && platform_default.protocols.indexOf(protocol) === -1) {
          reject(
            new AxiosError_default(
              "Unsupported protocol " + protocol + ":",
              AxiosError_default.ERR_BAD_REQUEST,
              config2
            )
          );
          return;
        }
        request4.send(requestData || null);
      }, "dispatchXhrRequest"));
    };
  }
});

// node_modules/axios/lib/helpers/composeSignals.js
var composeSignals, composeSignals_default;
var init_composeSignals = __esm({
  "node_modules/axios/lib/helpers/composeSignals.js"() {
    init_esbuild_shims();
    init_CanceledError();
    init_AxiosError();
    init_utils7();
    composeSignals = /* @__PURE__ */ __name((signals, timeout2) => {
      const { length } = signals = signals ? signals.filter(Boolean) : [];
      if (timeout2 || length) {
        let controller = new AbortController();
        let aborted2;
        const onabort = /* @__PURE__ */ __name(function(reason) {
          if (!aborted2) {
            aborted2 = true;
            unsubscribe();
            const err2 = reason instanceof Error ? reason : this.reason;
            controller.abort(
              err2 instanceof AxiosError_default ? err2 : new CanceledError_default(err2 instanceof Error ? err2.message : err2)
            );
          }
        }, "onabort");
        let timer = timeout2 && setTimeout(() => {
          timer = null;
          onabort(new AxiosError_default(`timeout of ${timeout2}ms exceeded`, AxiosError_default.ETIMEDOUT));
        }, timeout2);
        const unsubscribe = /* @__PURE__ */ __name(() => {
          if (signals) {
            timer && clearTimeout(timer);
            timer = null;
            signals.forEach((signal2) => {
              signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
            });
            signals = null;
          }
        }, "unsubscribe");
        signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
        const { signal } = controller;
        signal.unsubscribe = () => utils_default.asap(unsubscribe);
        return signal;
      }
    }, "composeSignals");
    composeSignals_default = composeSignals;
  }
});

// node_modules/axios/lib/helpers/trackStream.js
var streamChunk, readBytes, readStream, trackStream;
var init_trackStream = __esm({
  "node_modules/axios/lib/helpers/trackStream.js"() {
    init_esbuild_shims();
    streamChunk = /* @__PURE__ */ __name(function* (chunk, chunkSize) {
      let len = chunk.byteLength;
      if (!chunkSize || len < chunkSize) {
        yield chunk;
        return;
      }
      let pos2 = 0;
      let end;
      while (pos2 < len) {
        end = pos2 + chunkSize;
        yield chunk.slice(pos2, end);
        pos2 = end;
      }
    }, "streamChunk");
    readBytes = /* @__PURE__ */ __name(async function* (iterable, chunkSize) {
      for await (const chunk of readStream(iterable)) {
        yield* streamChunk(chunk, chunkSize);
      }
    }, "readBytes");
    readStream = /* @__PURE__ */ __name(async function* (stream5) {
      if (stream5[Symbol.asyncIterator]) {
        yield* stream5;
        return;
      }
      const reader = stream5.getReader();
      try {
        for (; ; ) {
          const { done, value } = await reader.read();
          if (done) {
            break;
          }
          yield value;
        }
      } finally {
        await reader.cancel();
      }
    }, "readStream");
    trackStream = /* @__PURE__ */ __name((stream5, chunkSize, onProgress, onFinish) => {
      const iterator2 = readBytes(stream5, chunkSize);
      let bytes = 0;
      let done;
      let _onFinish = /* @__PURE__ */ __name((e4) => {
        if (!done) {
          done = true;
          onFinish && onFinish(e4);
        }
      }, "_onFinish");
      return new ReadableStream(
        {
          async pull(controller) {
            try {
              const { done: done2, value } = await iterator2.next();
              if (done2) {
                _onFinish();
                controller.close();
                return;
              }
              let len = value.byteLength;
              if (onProgress) {
                let loadedBytes = bytes += len;
                onProgress(loadedBytes);
              }
              controller.enqueue(new Uint8Array(value));
            } catch (err2) {
              _onFinish(err2);
              throw err2;
            }
          },
          cancel(reason) {
            _onFinish(reason);
            return iterator2.return();
          }
        },
        {
          highWaterMark: 2
        }
      );
    }, "trackStream");
  }
});

// node_modules/axios/lib/adapters/fetch.js
var DEFAULT_CHUNK_SIZE, isFunction5, globalFetchAPI, ReadableStream5, TextEncoder2, test, factory, seedCache, getFetch, adapter;
var init_fetch3 = __esm({
  "node_modules/axios/lib/adapters/fetch.js"() {
    init_esbuild_shims();
    init_platform2();
    init_utils7();
    init_AxiosError();
    init_composeSignals();
    init_trackStream();
    init_AxiosHeaders();
    init_progressEventReducer();
    init_resolveConfig();
    init_settle();
    DEFAULT_CHUNK_SIZE = 64 * 1024;
    ({ isFunction: isFunction5 } = utils_default);
    globalFetchAPI = (({ Request: Request6, Response: Response6 }) => ({
      Request: Request6,
      Response: Response6
    }))(utils_default.global);
    ({ ReadableStream: ReadableStream5, TextEncoder: TextEncoder2 } = utils_default.global);
    test = /* @__PURE__ */ __name((fn, ...args2) => {
      try {
        return !!fn(...args2);
      } catch (e4) {
        return false;
      }
    }, "test");
    factory = /* @__PURE__ */ __name((env6) => {
      env6 = utils_default.merge.call(
        {
          skipUndefined: true
        },
        globalFetchAPI,
        env6
      );
      const { fetch: envFetch, Request: Request6, Response: Response6 } = env6;
      const isFetchSupported = envFetch ? isFunction5(envFetch) : typeof fetch === "function";
      const isRequestSupported = isFunction5(Request6);
      const isResponseSupported = isFunction5(Response6);
      if (!isFetchSupported) {
        return false;
      }
      const isReadableStreamSupported = isFetchSupported && isFunction5(ReadableStream5);
      const encodeText = isFetchSupported && (typeof TextEncoder2 === "function" ? /* @__PURE__ */ ((encoder) => (str2) => encoder.encode(str2))(new TextEncoder2()) : async (str2) => new Uint8Array(await new Request6(str2).arrayBuffer()));
      const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
        let duplexAccessed = false;
        const hasContentType = new Request6(platform_default.origin, {
          body: new ReadableStream5(),
          method: "POST",
          get duplex() {
            duplexAccessed = true;
            return "half";
          }
        }).headers.has("Content-Type");
        return duplexAccessed && !hasContentType;
      });
      const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils_default.isReadableStream(new Response6("").body));
      const resolvers = {
        stream: supportsResponseStream && ((res) => res.body)
      };
      isFetchSupported && (() => {
        ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
          !resolvers[type] && (resolvers[type] = (res, config2) => {
            let method = res && res[type];
            if (method) {
              return method.call(res);
            }
            throw new AxiosError_default(
              `Response type '${type}' is not supported`,
              AxiosError_default.ERR_NOT_SUPPORT,
              config2
            );
          });
        });
      })();
      const getBodyLength = /* @__PURE__ */ __name(async (body2) => {
        if (body2 == null) {
          return 0;
        }
        if (utils_default.isBlob(body2)) {
          return body2.size;
        }
        if (utils_default.isSpecCompliantForm(body2)) {
          const _request = new Request6(platform_default.origin, {
            method: "POST",
            body: body2
          });
          return (await _request.arrayBuffer()).byteLength;
        }
        if (utils_default.isArrayBufferView(body2) || utils_default.isArrayBuffer(body2)) {
          return body2.byteLength;
        }
        if (utils_default.isURLSearchParams(body2)) {
          body2 = body2 + "";
        }
        if (utils_default.isString(body2)) {
          return (await encodeText(body2)).byteLength;
        }
      }, "getBodyLength");
      const resolveBodyLength = /* @__PURE__ */ __name(async (headers, body2) => {
        const length = utils_default.toFiniteNumber(headers.getContentLength());
        return length == null ? getBodyLength(body2) : length;
      }, "resolveBodyLength");
      return async (config2) => {
        let {
          url: url3,
          method,
          data,
          signal,
          cancelToken,
          timeout: timeout2,
          onDownloadProgress,
          onUploadProgress,
          responseType,
          headers,
          withCredentials = "same-origin",
          fetchOptions
        } = resolveConfig_default(config2);
        let _fetch2 = envFetch || fetch;
        responseType = responseType ? (responseType + "").toLowerCase() : "text";
        let composedSignal = composeSignals_default(
          [signal, cancelToken && cancelToken.toAbortSignal()],
          timeout2
        );
        let request4 = null;
        const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
          composedSignal.unsubscribe();
        });
        let requestContentLength;
        try {
          if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
            let _request = new Request6(url3, {
              method: "POST",
              body: data,
              duplex: "half"
            });
            let contentTypeHeader;
            if (utils_default.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
              headers.setContentType(contentTypeHeader);
            }
            if (_request.body) {
              const [onProgress, flush] = progressEventDecorator(
                requestContentLength,
                progressEventReducer(asyncDecorator(onUploadProgress))
              );
              data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
            }
          }
          if (!utils_default.isString(withCredentials)) {
            withCredentials = withCredentials ? "include" : "omit";
          }
          const isCredentialsSupported = isRequestSupported && "credentials" in Request6.prototype;
          const resolvedOptions = {
            ...fetchOptions,
            signal: composedSignal,
            method: method.toUpperCase(),
            headers: headers.normalize().toJSON(),
            body: data,
            duplex: "half",
            credentials: isCredentialsSupported ? withCredentials : void 0
          };
          request4 = isRequestSupported && new Request6(url3, resolvedOptions);
          let response = await (isRequestSupported ? _fetch2(request4, fetchOptions) : _fetch2(url3, resolvedOptions));
          const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
          if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
            const options2 = {};
            ["status", "statusText", "headers"].forEach((prop) => {
              options2[prop] = response[prop];
            });
            const responseContentLength = utils_default.toFiniteNumber(response.headers.get("content-length"));
            const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
              responseContentLength,
              progressEventReducer(asyncDecorator(onDownloadProgress), true)
            ) || [];
            response = new Response6(
              trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
                flush && flush();
                unsubscribe && unsubscribe();
              }),
              options2
            );
          }
          responseType = responseType || "text";
          let responseData = await resolvers[utils_default.findKey(resolvers, responseType) || "text"](
            response,
            config2
          );
          !isStreamResponse && unsubscribe && unsubscribe();
          return await new Promise((resolve42, reject) => {
            settle(resolve42, reject, {
              data: responseData,
              headers: AxiosHeaders_default.from(response.headers),
              status: response.status,
              statusText: response.statusText,
              config: config2,
              request: request4
            });
          });
        } catch (err2) {
          unsubscribe && unsubscribe();
          if (err2 && err2.name === "TypeError" && /Load failed|fetch/i.test(err2.message)) {
            throw Object.assign(
              new AxiosError_default(
                "Network Error",
                AxiosError_default.ERR_NETWORK,
                config2,
                request4,
                err2 && err2.response
              ),
              {
                cause: err2.cause || err2
              }
            );
          }
          throw AxiosError_default.from(err2, err2 && err2.code, config2, request4, err2 && err2.response);
        }
      };
    }, "factory");
    seedCache = /* @__PURE__ */ new Map();
    getFetch = /* @__PURE__ */ __name((config2) => {
      let env6 = config2 && config2.env || {};
      const { fetch: fetch5, Request: Request6, Response: Response6 } = env6;
      const seeds = [Request6, Response6, fetch5];
      let len = seeds.length, i4 = len, seed, target, map3 = seedCache;
      while (i4--) {
        seed = seeds[i4];
        target = map3.get(seed);
        target === void 0 && map3.set(seed, target = i4 ? /* @__PURE__ */ new Map() : factory(env6));
        map3 = target;
      }
      return target;
    }, "getFetch");
    adapter = getFetch();
  }
});

// node_modules/axios/lib/adapters/adapters.js
function getAdapter(adapters, config2) {
  adapters = utils_default.isArray(adapters) ? adapters : [adapters];
  const { length } = adapters;
  let nameOrAdapter;
  let adapter2;
  const rejectedReasons = {};
  for (let i4 = 0; i4 < length; i4++) {
    nameOrAdapter = adapters[i4];
    let id;
    adapter2 = nameOrAdapter;
    if (!isResolvedHandle(nameOrAdapter)) {
      adapter2 = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
      if (adapter2 === void 0) {
        throw new AxiosError_default(`Unknown adapter '${id}'`);
      }
    }
    if (adapter2 && (utils_default.isFunction(adapter2) || (adapter2 = adapter2.get(config2)))) {
      break;
    }
    rejectedReasons[id || "#" + i4] = adapter2;
  }
  if (!adapter2) {
    const reasons = Object.entries(rejectedReasons).map(
      ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
    );
    let s5 = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
    throw new AxiosError_default(
      `There is no suitable adapter to dispatch the request ` + s5,
      "ERR_NOT_SUPPORT"
    );
  }
  return adapter2;
}
var knownAdapters, renderReason, isResolvedHandle, adapters_default;
var init_adapters = __esm({
  "node_modules/axios/lib/adapters/adapters.js"() {
    init_esbuild_shims();
    init_utils7();
    init_http();
    init_xhr();
    init_fetch3();
    init_AxiosError();
    knownAdapters = {
      http: http_default,
      xhr: xhr_default,
      fetch: {
        get: getFetch
      }
    };
    utils_default.forEach(knownAdapters, (fn, value) => {
      if (fn) {
        try {
          Object.defineProperty(fn, "name", { value });
        } catch (e4) {
        }
        Object.defineProperty(fn, "adapterName", { value });
      }
    });
    renderReason = /* @__PURE__ */ __name((reason) => `- ${reason}`, "renderReason");
    isResolvedHandle = /* @__PURE__ */ __name((adapter2) => utils_default.isFunction(adapter2) || adapter2 === null || adapter2 === false, "isResolvedHandle");
    __name(getAdapter, "getAdapter");
    adapters_default = {
      /**
       * Resolve an adapter from a list of adapter names or functions.
       * @type {Function}
       */
      getAdapter,
      /**
       * Exposes all known adapters
       * @type {Object<string, Function|Object>}
       */
      adapters: knownAdapters
    };
  }
});

// node_modules/axios/lib/core/dispatchRequest.js
function throwIfCancellationRequested(config2) {
  if (config2.cancelToken) {
    config2.cancelToken.throwIfRequested();
  }
  if (config2.signal && config2.signal.aborted) {
    throw new CanceledError_default(null, config2);
  }
}
function dispatchRequest(config2) {
  throwIfCancellationRequested(config2);
  config2.headers = AxiosHeaders_default.from(config2.headers);
  config2.data = transformData.call(config2, config2.transformRequest);
  if (["post", "put", "patch"].indexOf(config2.method) !== -1) {
    config2.headers.setContentType("application/x-www-form-urlencoded", false);
  }
  const adapter2 = adapters_default.getAdapter(config2.adapter || defaults_default.adapter, config2);
  return adapter2(config2).then(
    /* @__PURE__ */ __name(function onAdapterResolution(response) {
      throwIfCancellationRequested(config2);
      response.data = transformData.call(config2, config2.transformResponse, response);
      response.headers = AxiosHeaders_default.from(response.headers);
      return response;
    }, "onAdapterResolution"),
    /* @__PURE__ */ __name(function onAdapterRejection(reason) {
      if (!isCancel(reason)) {
        throwIfCancellationRequested(config2);
        if (reason && reason.response) {
          reason.response.data = transformData.call(
            config2,
            config2.transformResponse,
            reason.response
          );
          reason.response.headers = AxiosHeaders_default.from(reason.response.headers);
        }
      }
      return Promise.reject(reason);
    }, "onAdapterRejection")
  );
}
var init_dispatchRequest = __esm({
  "node_modules/axios/lib/core/dispatchRequest.js"() {
    "use strict";
    init_esbuild_shims();
    init_transformData();
    init_isCancel();
    init_defaults();
    init_CanceledError();
    init_AxiosHeaders();
    init_adapters();
    __name(throwIfCancellationRequested, "throwIfCancellationRequested");
    __name(dispatchRequest, "dispatchRequest");
  }
});

// node_modules/axios/lib/helpers/validator.js
function assertOptions(options2, schema, allowUnknown) {
  if (typeof options2 !== "object") {
    throw new AxiosError_default("options must be an object", AxiosError_default.ERR_BAD_OPTION_VALUE);
  }
  const keys = Object.keys(options2);
  let i4 = keys.length;
  while (i4-- > 0) {
    const opt = keys[i4];
    const validator = schema[opt];
    if (validator) {
      const value = options2[opt];
      const result = value === void 0 || validator(value, opt, options2);
      if (result !== true) {
        throw new AxiosError_default(
          "option " + opt + " must be " + result,
          AxiosError_default.ERR_BAD_OPTION_VALUE
        );
      }
      continue;
    }
    if (allowUnknown !== true) {
      throw new AxiosError_default("Unknown option " + opt, AxiosError_default.ERR_BAD_OPTION);
    }
  }
}
var validators, deprecatedWarnings, validator_default;
var init_validator = __esm({
  "node_modules/axios/lib/helpers/validator.js"() {
    "use strict";
    init_esbuild_shims();
    init_data();
    init_AxiosError();
    validators = {};
    ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i4) => {
      validators[type] = /* @__PURE__ */ __name(function validator(thing) {
        return typeof thing === type || "a" + (i4 < 1 ? "n " : " ") + type;
      }, "validator");
    });
    deprecatedWarnings = {};
    validators.transitional = /* @__PURE__ */ __name(function transitional(validator, version2, message) {
      function formatMessage(opt, desc2) {
        return "[Axios v" + VERSION5 + "] Transitional option '" + opt + "'" + desc2 + (message ? ". " + message : "");
      }
      __name(formatMessage, "formatMessage");
      return (value, opt, opts) => {
        if (validator === false) {
          throw new AxiosError_default(
            formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : "")),
            AxiosError_default.ERR_DEPRECATED
          );
        }
        if (version2 && !deprecatedWarnings[opt]) {
          deprecatedWarnings[opt] = true;
          console.warn(
            formatMessage(
              opt,
              " has been deprecated since v" + version2 + " and will be removed in the near future"
            )
          );
        }
        return validator ? validator(value, opt, opts) : true;
      };
    }, "transitional");
    validators.spelling = /* @__PURE__ */ __name(function spelling(correctSpelling) {
      return (value, opt) => {
        console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
        return true;
      };
    }, "spelling");
    __name(assertOptions, "assertOptions");
    validator_default = {
      assertOptions,
      validators
    };
  }
});

// node_modules/axios/lib/core/Axios.js
var validators2, Axios, Axios_default;
var init_Axios = __esm({
  "node_modules/axios/lib/core/Axios.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    init_buildURL();
    init_InterceptorManager();
    init_dispatchRequest();
    init_mergeConfig();
    init_buildFullPath();
    init_validator();
    init_AxiosHeaders();
    init_transitional();
    validators2 = validator_default.validators;
    Axios = class {
      static {
        __name(this, "Axios");
      }
      constructor(instanceConfig) {
        this.defaults = instanceConfig || {};
        this.interceptors = {
          request: new InterceptorManager_default(),
          response: new InterceptorManager_default()
        };
      }
      /**
       * Dispatch a request
       *
       * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
       * @param {?Object} config
       *
       * @returns {Promise} The Promise to be fulfilled
       */
      async request(configOrUrl, config2) {
        try {
          return await this._request(configOrUrl, config2);
        } catch (err2) {
          if (err2 instanceof Error) {
            let dummy = {};
            Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
            const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
            try {
              if (!err2.stack) {
                err2.stack = stack;
              } else if (stack && !String(err2.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
                err2.stack += "\n" + stack;
              }
            } catch (e4) {
            }
          }
          throw err2;
        }
      }
      _request(configOrUrl, config2) {
        if (typeof configOrUrl === "string") {
          config2 = config2 || {};
          config2.url = configOrUrl;
        } else {
          config2 = configOrUrl || {};
        }
        config2 = mergeConfig(this.defaults, config2);
        const { transitional: transitional2, paramsSerializer, headers } = config2;
        if (transitional2 !== void 0) {
          validator_default.assertOptions(
            transitional2,
            {
              silentJSONParsing: validators2.transitional(validators2.boolean),
              forcedJSONParsing: validators2.transitional(validators2.boolean),
              clarifyTimeoutError: validators2.transitional(validators2.boolean),
              legacyInterceptorReqResOrdering: validators2.transitional(validators2.boolean)
            },
            false
          );
        }
        if (paramsSerializer != null) {
          if (utils_default.isFunction(paramsSerializer)) {
            config2.paramsSerializer = {
              serialize: paramsSerializer
            };
          } else {
            validator_default.assertOptions(
              paramsSerializer,
              {
                encode: validators2.function,
                serialize: validators2.function
              },
              true
            );
          }
        }
        if (config2.allowAbsoluteUrls !== void 0) {
        } else if (this.defaults.allowAbsoluteUrls !== void 0) {
          config2.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
        } else {
          config2.allowAbsoluteUrls = true;
        }
        validator_default.assertOptions(
          config2,
          {
            baseUrl: validators2.spelling("baseURL"),
            withXsrfToken: validators2.spelling("withXSRFToken")
          },
          true
        );
        config2.method = (config2.method || this.defaults.method || "get").toLowerCase();
        let contextHeaders = headers && utils_default.merge(headers.common, headers[config2.method]);
        headers && utils_default.forEach(["delete", "get", "head", "post", "put", "patch", "common"], (method) => {
          delete headers[method];
        });
        config2.headers = AxiosHeaders_default.concat(contextHeaders, headers);
        const requestInterceptorChain = [];
        let synchronousRequestInterceptors = true;
        this.interceptors.request.forEach(/* @__PURE__ */ __name(function unshiftRequestInterceptors(interceptor) {
          if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config2) === false) {
            return;
          }
          synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
          const transitional3 = config2.transitional || transitional_default;
          const legacyInterceptorReqResOrdering = transitional3 && transitional3.legacyInterceptorReqResOrdering;
          if (legacyInterceptorReqResOrdering) {
            requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
          } else {
            requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
          }
        }, "unshiftRequestInterceptors"));
        const responseInterceptorChain = [];
        this.interceptors.response.forEach(/* @__PURE__ */ __name(function pushResponseInterceptors(interceptor) {
          responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
        }, "pushResponseInterceptors"));
        let promise2;
        let i4 = 0;
        let len;
        if (!synchronousRequestInterceptors) {
          const chain2 = [dispatchRequest.bind(this), void 0];
          chain2.unshift(...requestInterceptorChain);
          chain2.push(...responseInterceptorChain);
          len = chain2.length;
          promise2 = Promise.resolve(config2);
          while (i4 < len) {
            promise2 = promise2.then(chain2[i4++], chain2[i4++]);
          }
          return promise2;
        }
        len = requestInterceptorChain.length;
        let newConfig = config2;
        while (i4 < len) {
          const onFulfilled = requestInterceptorChain[i4++];
          const onRejected = requestInterceptorChain[i4++];
          try {
            newConfig = onFulfilled(newConfig);
          } catch (error40) {
            onRejected.call(this, error40);
            break;
          }
        }
        try {
          promise2 = dispatchRequest.call(this, newConfig);
        } catch (error40) {
          return Promise.reject(error40);
        }
        i4 = 0;
        len = responseInterceptorChain.length;
        while (i4 < len) {
          promise2 = promise2.then(responseInterceptorChain[i4++], responseInterceptorChain[i4++]);
        }
        return promise2;
      }
      getUri(config2) {
        config2 = mergeConfig(this.defaults, config2);
        const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
        return buildURL(fullPath, config2.params, config2.paramsSerializer);
      }
    };
    utils_default.forEach(["delete", "get", "head", "options"], /* @__PURE__ */ __name(function forEachMethodNoData(method) {
      Axios.prototype[method] = function(url3, config2) {
        return this.request(
          mergeConfig(config2 || {}, {
            method,
            url: url3,
            data: (config2 || {}).data
          })
        );
      };
    }, "forEachMethodNoData"));
    utils_default.forEach(["post", "put", "patch"], /* @__PURE__ */ __name(function forEachMethodWithData(method) {
      function generateHTTPMethod(isForm) {
        return /* @__PURE__ */ __name(function httpMethod(url3, data, config2) {
          return this.request(
            mergeConfig(config2 || {}, {
              method,
              headers: isForm ? {
                "Content-Type": "multipart/form-data"
              } : {},
              url: url3,
              data
            })
          );
        }, "httpMethod");
      }
      __name(generateHTTPMethod, "generateHTTPMethod");
      Axios.prototype[method] = generateHTTPMethod();
      Axios.prototype[method + "Form"] = generateHTTPMethod(true);
    }, "forEachMethodWithData"));
    Axios_default = Axios;
  }
});

// node_modules/axios/lib/cancel/CancelToken.js
var CancelToken, CancelToken_default;
var init_CancelToken = __esm({
  "node_modules/axios/lib/cancel/CancelToken.js"() {
    "use strict";
    init_esbuild_shims();
    init_CanceledError();
    CancelToken = class _CancelToken {
      static {
        __name(this, "CancelToken");
      }
      constructor(executor) {
        if (typeof executor !== "function") {
          throw new TypeError("executor must be a function.");
        }
        let resolvePromise;
        this.promise = new Promise(/* @__PURE__ */ __name(function promiseExecutor(resolve42) {
          resolvePromise = resolve42;
        }, "promiseExecutor"));
        const token2 = this;
        this.promise.then((cancel) => {
          if (!token2._listeners) return;
          let i4 = token2._listeners.length;
          while (i4-- > 0) {
            token2._listeners[i4](cancel);
          }
          token2._listeners = null;
        });
        this.promise.then = (onfulfilled) => {
          let _resolve;
          const promise2 = new Promise((resolve42) => {
            token2.subscribe(resolve42);
            _resolve = resolve42;
          }).then(onfulfilled);
          promise2.cancel = /* @__PURE__ */ __name(function reject() {
            token2.unsubscribe(_resolve);
          }, "reject");
          return promise2;
        };
        executor(/* @__PURE__ */ __name(function cancel(message, config2, request4) {
          if (token2.reason) {
            return;
          }
          token2.reason = new CanceledError_default(message, config2, request4);
          resolvePromise(token2.reason);
        }, "cancel"));
      }
      /**
       * Throws a `CanceledError` if cancellation has been requested.
       */
      throwIfRequested() {
        if (this.reason) {
          throw this.reason;
        }
      }
      /**
       * Subscribe to the cancel signal
       */
      subscribe(listener) {
        if (this.reason) {
          listener(this.reason);
          return;
        }
        if (this._listeners) {
          this._listeners.push(listener);
        } else {
          this._listeners = [listener];
        }
      }
      /**
       * Unsubscribe from the cancel signal
       */
      unsubscribe(listener) {
        if (!this._listeners) {
          return;
        }
        const index = this._listeners.indexOf(listener);
        if (index !== -1) {
          this._listeners.splice(index, 1);
        }
      }
      toAbortSignal() {
        const controller = new AbortController();
        const abort2 = /* @__PURE__ */ __name((err2) => {
          controller.abort(err2);
        }, "abort");
        this.subscribe(abort2);
        controller.signal.unsubscribe = () => this.unsubscribe(abort2);
        return controller.signal;
      }
      /**
       * Returns an object that contains a new `CancelToken` and a function that, when called,
       * cancels the `CancelToken`.
       */
      static source() {
        let cancel;
        const token2 = new _CancelToken(/* @__PURE__ */ __name(function executor(c4) {
          cancel = c4;
        }, "executor"));
        return {
          token: token2,
          cancel
        };
      }
    };
    CancelToken_default = CancelToken;
  }
});

// node_modules/axios/lib/helpers/spread.js
function spread(callback) {
  return /* @__PURE__ */ __name(function wrap2(arr) {
    return callback.apply(null, arr);
  }, "wrap");
}
var init_spread = __esm({
  "node_modules/axios/lib/helpers/spread.js"() {
    "use strict";
    init_esbuild_shims();
    __name(spread, "spread");
  }
});

// node_modules/axios/lib/helpers/isAxiosError.js
function isAxiosError(payload) {
  return utils_default.isObject(payload) && payload.isAxiosError === true;
}
var init_isAxiosError = __esm({
  "node_modules/axios/lib/helpers/isAxiosError.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    __name(isAxiosError, "isAxiosError");
  }
});

// node_modules/axios/lib/helpers/HttpStatusCode.js
var HttpStatusCode, HttpStatusCode_default;
var init_HttpStatusCode = __esm({
  "node_modules/axios/lib/helpers/HttpStatusCode.js"() {
    init_esbuild_shims();
    HttpStatusCode = {
      Continue: 100,
      SwitchingProtocols: 101,
      Processing: 102,
      EarlyHints: 103,
      Ok: 200,
      Created: 201,
      Accepted: 202,
      NonAuthoritativeInformation: 203,
      NoContent: 204,
      ResetContent: 205,
      PartialContent: 206,
      MultiStatus: 207,
      AlreadyReported: 208,
      ImUsed: 226,
      MultipleChoices: 300,
      MovedPermanently: 301,
      Found: 302,
      SeeOther: 303,
      NotModified: 304,
      UseProxy: 305,
      Unused: 306,
      TemporaryRedirect: 307,
      PermanentRedirect: 308,
      BadRequest: 400,
      Unauthorized: 401,
      PaymentRequired: 402,
      Forbidden: 403,
      NotFound: 404,
      MethodNotAllowed: 405,
      NotAcceptable: 406,
      ProxyAuthenticationRequired: 407,
      RequestTimeout: 408,
      Conflict: 409,
      Gone: 410,
      LengthRequired: 411,
      PreconditionFailed: 412,
      PayloadTooLarge: 413,
      UriTooLong: 414,
      UnsupportedMediaType: 415,
      RangeNotSatisfiable: 416,
      ExpectationFailed: 417,
      ImATeapot: 418,
      MisdirectedRequest: 421,
      UnprocessableEntity: 422,
      Locked: 423,
      FailedDependency: 424,
      TooEarly: 425,
      UpgradeRequired: 426,
      PreconditionRequired: 428,
      TooManyRequests: 429,
      RequestHeaderFieldsTooLarge: 431,
      UnavailableForLegalReasons: 451,
      InternalServerError: 500,
      NotImplemented: 501,
      BadGateway: 502,
      ServiceUnavailable: 503,
      GatewayTimeout: 504,
      HttpVersionNotSupported: 505,
      VariantAlsoNegotiates: 506,
      InsufficientStorage: 507,
      LoopDetected: 508,
      NotExtended: 510,
      NetworkAuthenticationRequired: 511,
      WebServerIsDown: 521,
      ConnectionTimedOut: 522,
      OriginIsUnreachable: 523,
      TimeoutOccurred: 524,
      SslHandshakeFailed: 525,
      InvalidSslCertificate: 526
    };
    Object.entries(HttpStatusCode).forEach(([key, value]) => {
      HttpStatusCode[value] = key;
    });
    HttpStatusCode_default = HttpStatusCode;
  }
});

// node_modules/axios/lib/axios.js
function createInstance(defaultConfig2) {
  const context2 = new Axios_default(defaultConfig2);
  const instance2 = bind(Axios_default.prototype.request, context2);
  utils_default.extend(instance2, Axios_default.prototype, context2, { allOwnKeys: true });
  utils_default.extend(instance2, context2, null, { allOwnKeys: true });
  instance2.create = /* @__PURE__ */ __name(function create4(instanceConfig) {
    return createInstance(mergeConfig(defaultConfig2, instanceConfig));
  }, "create");
  return instance2;
}
var axios, axios_default;
var init_axios = __esm({
  "node_modules/axios/lib/axios.js"() {
    "use strict";
    init_esbuild_shims();
    init_utils7();
    init_bind();
    init_Axios();
    init_mergeConfig();
    init_defaults();
    init_formDataToJSON();
    init_CanceledError();
    init_CancelToken();
    init_isCancel();
    init_data();
    init_toFormData();
    init_AxiosError();
    init_spread();
    init_isAxiosError();
    init_AxiosHeaders();
    init_adapters();
    init_HttpStatusCode();
    __name(createInstance, "createInstance");
    axios = createInstance(defaults_default);
    axios.Axios = Axios_default;
    axios.CanceledError = CanceledError_default;
    axios.CancelToken = CancelToken_default;
    axios.isCancel = isCancel;
    axios.VERSION = VERSION5;
    axios.toFormData = toFormData_default;
    axios.AxiosError = AxiosError_default;
    axios.Cancel = axios.CanceledError;
    axios.all = /* @__PURE__ */ __name(function all2(promises9) {
      return Promise.all(promises9);
    }, "all");
    axios.spread = spread;
    axios.isAxiosError = isAxiosError;
    axios.mergeConfig = mergeConfig;
    axios.AxiosHeaders = AxiosHeaders_default;
    axios.formToJSON = (thing) => formDataToJSON_default(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing);
    axios.getAdapter = adapters_default.getAdapter;
    axios.HttpStatusCode = HttpStatusCode_default;
    axios.default = axios;
    axios_default = axios;
  }
});

// node_modules/axios/index.js
var Axios2, AxiosError2, CanceledError2, isCancel2, CancelToken2, VERSION6, all3, Cancel, isAxiosError2, spread2, toFormData3, AxiosHeaders2, HttpStatusCode2, formToJSON, getAdapter2, mergeConfig2;
var init_axios2 = __esm({
  "node_modules/axios/index.js"() {
    init_esbuild_shims();
    init_axios();
    ({
      Axios: Axios2,
      AxiosError: AxiosError2,
      CanceledError: CanceledError2,
      isCancel: isCancel2,
      CancelToken: CancelToken2,
      VERSION: VERSION6,
      all: all3,
      Cancel,
      isAxiosError: isAxiosError2,
      spread: spread2,
      toFormData: toFormData3,
      AxiosHeaders: AxiosHeaders2,
      HttpStatusCode: HttpStatusCode2,
      formToJSON,
      getAdapter: getAdapter2,
      mergeConfig: mergeConfig2
    } = axios_default);
  }
});

// node_modules/dingtalk-stream-sdk-nodejs/dist/client.mjs
import EventEmitter14 from "events";
var EventAck, defaultConfig, DWClient;
var init_client5 = __esm({
  "node_modules/dingtalk-stream-sdk-nodejs/dist/client.mjs"() {
    init_esbuild_shims();
    init_wrapper();
    init_axios2();
    EventAck = /* @__PURE__ */ ((EventAck2) => {
      EventAck2["SUCCESS"] = "SUCCESS";
      EventAck2["LATER"] = "LATER";
      return EventAck2;
    })(EventAck || {});
    defaultConfig = {
      autoReconnect: true,
      keepAlive: false,
      ua: "",
      subscriptions: [
        {
          type: "EVENT",
          topic: "*"
        }
      ]
    };
    DWClient = class extends EventEmitter14 {
      static {
        __name(this, "DWClient");
      }
      debug = true;
      connected = false;
      registered = false;
      reconnecting = false;
      userDisconnect = false;
      reconnectInterval = 1e3;
      heartbeat_interval = 8e3;
      heartbeatIntervallId;
      sslopts = { rejectUnauthorized: true };
      config;
      socket;
      dw_url;
      isAlive = false;
      onEventReceived = /* @__PURE__ */ __name((msg) => {
        return {
          status: "SUCCESS"
          /* SUCCESS */
        };
      }, "onEventReceived");
      constructor(opts) {
        super();
        this.config = {
          ...defaultConfig,
          ...opts
        };
        if (!this.config.clientId || !this.config.clientSecret) {
          console.error("clientId or clientSecret is null");
          throw new Error("clientId or clientSecret is null");
        }
      }
      getConfig() {
        return { ...this.config };
      }
      printDebug(msg) {
        if (this.debug) {
          const date5 = "[" + (/* @__PURE__ */ new Date()).toISOString() + "]";
          console.info(date5, msg);
        }
      }
      registerAllEventListener(onEventReceived) {
        this.onEventReceived = onEventReceived;
        return this;
      }
      registerCallbackListener(eventId, callback) {
        if (!eventId || !callback) {
          console.error(
            "registerCallbackListener: eventId and callback must be defined"
          );
          throw new Error(
            "registerCallbackListener: eventId and callback must be defined"
          );
        }
        if (!this.config.subscriptions.find(
          (x3) => x3.topic === eventId && x3.type === "CALLBACK"
        )) {
          this.config.subscriptions.push({
            type: "CALLBACK",
            topic: eventId
          });
        }
        this.on(eventId, callback);
        return this;
      }
      async getEndpoint() {
        this.printDebug("get connect endpoint by config");
        console.log(this.config);
        const result = await axios_default.get(
          `https://oapi.dingtalk.com/gettoken?appkey=${this.config.clientId}&appsecret=${this.config.clientSecret}`
        );
        if (result.status === 200 && result.data.access_token) {
          this.config.access_token = result.data.access_token;
          const res = await axios_default({
            url: "https://api.dingtalk.com/v1.0/gateway/connections/open",
            method: "POST",
            responseType: "json",
            data: {
              clientId: this.config.clientId,
              clientSecret: this.config.clientSecret,
              ua: this.config.ua,
              subscriptions: this.config.subscriptions
            },
            headers: {
              // 这个接口得加个，否则默认返回的会是xml
              Accept: "application/json",
              "access-token": result.data.access_token
              // 'd136e657-5998-4cc4-a055-2b7ceab0f212'
            }
          });
          console.log("res.data", JSON.stringify(res.data));
          if (res.data) {
            this.config.endpoint = res.data;
            const { endpoint, ticket } = res.data;
            if (!endpoint || !ticket) {
              this.printDebug("endpoint or ticket is null");
              throw new Error("endpoint or ticket is null");
            }
            this.dw_url = `${endpoint}?ticket=${ticket}`;
            return this;
          } else {
            throw new Error("build: get endpoint failed");
          }
        } else {
          throw new Error("build: get access_token failed");
        }
      }
      _connect() {
        return new Promise((resolve42, reject) => {
          this.userDisconnect = false;
          this.printDebug("Connecting to dingtalk websocket @ " + this.dw_url);
          this.socket = new wrapper_default(this.dw_url, this.sslopts);
          this.socket.on("open", () => {
            this.connected = true;
            this.printDebug("Socket open");
            if (this.config.keepAlive) {
              this.isAlive = true;
              this.heartbeatIntervallId = setInterval(() => {
                var _a7, _b2;
                if (this.isAlive === false) {
                  console.error(
                    "TERMINATE SOCKET: Ping Pong does not transfer heartbeat within heartbeat intervall"
                  );
                  return (_a7 = this.socket) == null ? void 0 : _a7.terminate();
                }
                this.isAlive = false;
                (_b2 = this.socket) == null ? void 0 : _b2.ping("", true);
              }, this.heartbeat_interval);
            }
          });
          this.socket.on("pong", () => {
            this.heartbeat();
          });
          this.socket.on("message", (data) => {
            this.onDownStream(data);
          });
          this.socket.on("close", (err2) => {
            this.printDebug("Socket closed");
            this.connected = false;
            this.registered = false;
            if (this.config.autoReconnect && !this.userDisconnect) {
              this.reconnecting = true;
              this.printDebug(
                "Reconnecting in " + this.reconnectInterval / 1e3 + " seconds..."
              );
              setTimeout(this.connect.bind(this), this.reconnectInterval);
            }
          });
          this.socket.on("error", (err2) => {
            this.printDebug("SOCKET ERROR");
            console.warn("ERROR", err2);
          });
          resolve42();
        });
      }
      async connect() {
        await this.getEndpoint();
        await this._connect();
      }
      disconnect() {
        var _a7;
        console.info("Disconnecting.");
        this.userDisconnect = true;
        if (this.config.keepAlive && this.heartbeatIntervallId !== void 0) {
          clearInterval(this.heartbeatIntervallId);
        }
        (_a7 = this.socket) == null ? void 0 : _a7.close();
      }
      heartbeat() {
        this.isAlive = true;
        this.printDebug("CLIENT-SIDE HEARTBEAT");
      }
      onDownStream(data) {
        this.printDebug("Received message from dingtalk websocket server");
        this.printDebug(data);
        console.log(data);
        const msg = JSON.parse(data);
        switch (msg.type) {
          case "SYSTEM":
            this.onSystem(msg);
            break;
          case "EVENT":
            this.onEvent(msg);
            break;
          case "CALLBACK":
            this.onCallback(msg);
            break;
        }
      }
      onSystem(downstream) {
        var _a7;
        switch (downstream.headers.topic) {
          case "CONNECTED": {
            this.printDebug("CONNECTED");
            break;
          }
          case "REGISTERED": {
            this.registered = true;
            this.reconnecting = false;
            break;
          }
          case "disconnect": {
            this.connected = false;
            this.registered = false;
            break;
          }
          case "KEEPALIVE": {
            this.heartbeat();
            break;
          }
          case "ping": {
            this.printDebug("PING");
            (_a7 = this.socket) == null ? void 0 : _a7.send(
              JSON.stringify({
                code: 200,
                headers: downstream.headers,
                message: "OK",
                data: downstream.data
              })
            );
            break;
          }
        }
      }
      onEvent(message) {
        var _a7;
        this.printDebug("received event, message=" + JSON.stringify(message));
        const ackData = this.onEventReceived(message);
        (_a7 = this.socket) == null ? void 0 : _a7.send(JSON.stringify({
          code: 200,
          headers: {
            contentType: "application/json",
            messageId: message.headers.messageId
          },
          message: "OK",
          data: JSON.stringify(ackData)
        }));
      }
      onCallback(message) {
        this.emit(message.headers.topic, message);
      }
      send(messageId, value) {
        var _a7;
        if (!messageId) {
          console.error("send: messageId must be defined");
          throw new Error("send: messageId must be defined");
        }
        const msg = {
          code: 200,
          headers: {
            contentType: "application/json",
            messageId
          },
          message: "OK",
          data: JSON.stringify(value)
        };
        (_a7 = this.socket) == null ? void 0 : _a7.send(JSON.stringify(msg));
      }
    };
  }
});

// node_modules/dingtalk-stream-sdk-nodejs/dist/index.mjs
var init_dist9 = __esm({
  "node_modules/dingtalk-stream-sdk-nodejs/dist/index.mjs"() {
    init_esbuild_shims();
    init_constants9();
    init_client5();
    init_wrapper();
  }
});

// packages/channels/dingtalk/dist/markdown.js
function isTableSeparator(line) {
  const trimmed2 = line.trim();
  if (!trimmed2.includes("-"))
    return false;
  const cells = trimmed2.replace(/^\|/, "").replace(/\|$/, "").split("|").map((c4) => c4.trim());
  return cells.length > 0 && cells.every((c4) => /^:?-{3,}:?$/.test(c4));
}
function isTableRow(line) {
  const trimmed2 = line.trim();
  return trimmed2.includes("|") && !trimmed2.startsWith("```");
}
function parseTableRow(line) {
  return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c4) => c4.trim());
}
function renderTable(lines) {
  const rows = lines.map(parseTableRow).filter((cells) => cells.length > 0);
  return rows.map((cells) => cells.join(" | ")).join("  \n");
}
function convertTables(text) {
  const lines = text.split("\n");
  const output = [];
  let i4 = 0;
  let inCode = false;
  while (i4 < lines.length) {
    const line = lines[i4] || "";
    if (line.trim().startsWith("```")) {
      inCode = !inCode;
      output.push(line);
      i4++;
      continue;
    }
    if (!inCode && i4 + 1 < lines.length && isTableRow(line) && isTableSeparator(lines[i4 + 1] || "")) {
      const tableLines = [line];
      i4 += 2;
      while (i4 < lines.length && isTableRow(lines[i4] || "")) {
        tableLines.push(lines[i4] || "");
        i4++;
      }
      output.push(renderTable(tableLines));
      continue;
    }
    output.push(line);
    i4++;
  }
  return output.join("\n");
}
function splitChunks(text) {
  if (!text || text.length <= CHUNK_LIMIT) {
    return [text];
  }
  const chunks = [];
  let buf = "";
  const lines = text.split("\n");
  let inCode = false;
  for (const line of lines) {
    const fenceCount = (line.match(/```/g) || []).length;
    if (buf.length + line.length + 1 > CHUNK_LIMIT && buf.length > 0) {
      if (inCode) {
        buf += "\n```";
      }
      chunks.push(buf);
      buf = inCode ? "```\n" : "";
    }
    buf += (buf ? "\n" : "") + line;
    if (fenceCount % 2 === 1) {
      inCode = !inCode;
    }
  }
  if (buf) {
    chunks.push(buf);
  }
  return chunks;
}
function extractTitle(text) {
  const firstLine = text.split("\n")[0] || "";
  const cleaned = firstLine.replace(/^[#*\s\->]+/, "").slice(0, 20);
  return cleaned || "Reply";
}
function normalizeDingTalkMarkdown(text) {
  const converted = convertTables(text);
  return splitChunks(converted);
}
var CHUNK_LIMIT;
var init_markdown = __esm({
  "packages/channels/dingtalk/dist/markdown.js"() {
    "use strict";
    init_esbuild_shims();
    CHUNK_LIMIT = 3800;
    __name(isTableSeparator, "isTableSeparator");
    __name(isTableRow, "isTableRow");
    __name(parseTableRow, "parseTableRow");
    __name(renderTable, "renderTable");
    __name(convertTables, "convertTables");
    __name(splitChunks, "splitChunks");
    __name(extractTitle, "extractTitle");
    __name(normalizeDingTalkMarkdown, "normalizeDingTalkMarkdown");
  }
});

// packages/channels/dingtalk/dist/media.js
async function downloadMedia(downloadCode, robotCode, accessToken) {
  if (!downloadCode || !robotCode || !accessToken) {
    return null;
  }
  try {
    const apiResp = await fetch(DOWNLOAD_API, {
      method: "POST",
      headers: {
        "x-acs-dingtalk-access-token": accessToken,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ downloadCode, robotCode })
    });
    if (!apiResp.ok) {
      const detail = await apiResp.text().catch(() => "");
      process.stderr.write(`[DingTalk] downloadMedia API failed: HTTP ${apiResp.status} ${detail}
`);
      return null;
    }
    const payload = await apiResp.json();
    const downloadUrl = payload["downloadUrl"] ?? payload["data"]?.["downloadUrl"];
    if (!downloadUrl) {
      process.stderr.write(`[DingTalk] downloadMedia: no downloadUrl in response
`);
      return null;
    }
    const fileResp = await fetch(downloadUrl);
    if (!fileResp.ok) {
      process.stderr.write(`[DingTalk] downloadMedia file fetch failed: HTTP ${fileResp.status}
`);
      return null;
    }
    const mimeType = fileResp.headers.get("content-type") || "application/octet-stream";
    const buffer = Buffer.from(await fileResp.arrayBuffer());
    return { buffer, mimeType };
  } catch (err2) {
    process.stderr.write(`[DingTalk] downloadMedia error: ${err2 instanceof Error ? err2.message : err2}
`);
    return null;
  }
}
var DOWNLOAD_API;
var init_media2 = __esm({
  "packages/channels/dingtalk/dist/media.js"() {
    "use strict";
    init_esbuild_shims();
    DOWNLOAD_API = "https://api.dingtalk.com/v1.0/robot/messageFiles/download";
    __name(downloadMedia, "downloadMedia");
  }
});

// packages/channels/dingtalk/dist/DingtalkAdapter.js
import { mkdirSync as mkdirSync18, writeFileSync as writeFileSync21 } from "node:fs";
import { randomUUID as randomUUID16 } from "node:crypto";
import { basename as basename25, join as join57 } from "node:path";
import { tmpdir as tmpdir9 } from "node:os";
var DEDUP_TTL_MS, ACK_REACTION_NAME, ACK_EMOTION_ID, ACK_EMOTION_BG_ID, EMOTION_API, DingtalkChannel;
var init_DingtalkAdapter = __esm({
  "packages/channels/dingtalk/dist/DingtalkAdapter.js"() {
    "use strict";
    init_esbuild_shims();
    init_dist9();
    init_dist5();
    init_markdown();
    init_media2();
    DEDUP_TTL_MS = 5 * 60 * 1e3;
    ACK_REACTION_NAME = "\u{1F440}";
    ACK_EMOTION_ID = "2659900";
    ACK_EMOTION_BG_ID = "im_bg_1";
    EMOTION_API = "https://api.dingtalk.com/v1.0/robot/emotion";
    DingtalkChannel = class extends ChannelBase {
      static {
        __name(this, "DingtalkChannel");
      }
      client;
      seenMessages = /* @__PURE__ */ new Map();
      dedupTimer;
      /** Map conversationId → latest sessionWebhook URL for sending replies. */
      webhooks = /* @__PURE__ */ new Map();
      constructor(name4, config2, bridge, options2) {
        super(name4, config2, bridge, options2);
        if (!config2.clientId || !config2.clientSecret) {
          throw new Error(`Channel "${name4}" requires clientId and clientSecret for DingTalk.`);
        }
        this.client = new DWClient({
          clientId: config2.clientId,
          clientSecret: config2.clientSecret
        });
      }
      async connect() {
        this.client.registerCallbackListener(TOPIC_ROBOT, (msg) => {
          this.client.send(msg.headers.messageId, {
            status: EventAck.SUCCESS,
            message: "ok"
          });
          this.onMessage(msg);
        });
        await this.client.connect();
        this.dedupTimer = setInterval(() => {
          const now = Date.now();
          for (const [id, ts] of this.seenMessages) {
            if (now - ts > DEDUP_TTL_MS) {
              this.seenMessages.delete(id);
            }
          }
        }, 6e4);
        process.stderr.write(`[DingTalk:${this.name}] Connected via stream.
`);
      }
      async sendMessage(chatId, text) {
        const webhook = this.webhooks.get(chatId);
        if (!webhook) {
          process.stderr.write(`[DingTalk:${this.name}] No webhook for chatId ${chatId}, cannot send.
`);
          return;
        }
        const chunks = normalizeDingTalkMarkdown(text);
        const title = extractTitle(text);
        for (let i4 = 0; i4 < chunks.length; i4++) {
          const chunk = chunks[i4];
          const body2 = {
            msgtype: "markdown",
            markdown: {
              title: i4 === 0 ? title : `${title} (cont.)`,
              text: chunk
            }
          };
          const resp = await fetch(webhook, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(body2)
          });
          if (!resp.ok) {
            const detail = await resp.text().catch(() => "");
            process.stderr.write(`[DingTalk:${this.name}] sendMessage failed: HTTP ${resp.status} ${detail}
`);
          }
        }
      }
      getAccessToken() {
        return this.client.getConfig().access_token;
      }
      async emotionApi(endpoint, msgId, conversationId) {
        const token2 = this.getAccessToken();
        if (!token2)
          return;
        const robotCode = this.config.clientId;
        if (!robotCode || !msgId || !conversationId)
          return;
        try {
          const resp = await fetch(`${EMOTION_API}/${endpoint}`, {
            method: "POST",
            headers: {
              "x-acs-dingtalk-access-token": token2,
              "Content-Type": "application/json"
            },
            body: JSON.stringify({
              robotCode,
              openMsgId: msgId,
              openConversationId: conversationId,
              emotionType: 2,
              emotionName: ACK_REACTION_NAME,
              textEmotion: {
                emotionId: ACK_EMOTION_ID,
                emotionName: ACK_REACTION_NAME,
                text: ACK_REACTION_NAME,
                backgroundId: ACK_EMOTION_BG_ID
              }
            })
          });
          if (!resp.ok) {
            const detail = await resp.text().catch(() => "");
            process.stderr.write(`[DingTalk:${this.name}] emotion/${endpoint} failed: ${resp.status} ${detail}
`);
          }
        } catch {
        }
      }
      async attachReaction(msgId, conversationId) {
        await this.emotionApi("reply", msgId, conversationId);
      }
      async recallReaction(msgId, conversationId) {
        await this.emotionApi("recall", msgId, conversationId);
      }
      disconnect() {
        if (this.dedupTimer) {
          clearInterval(this.dedupTimer);
        }
        this.client.disconnect();
        process.stderr.write(`[DingTalk:${this.name}] Disconnected.
`);
      }
      /**
       * The chatId passed to onPromptStart/onPromptEnd is `conversationId ||
       * sessionWebhook` (see message handler below). Reactions require a real
       * conversation ID — skip the webhook-URL fallback case.
       */
      isConversationId(chatId) {
        return !!chatId && !chatId.startsWith("http");
      }
      onPromptStart(chatId, _sessionId, messageId) {
        if (!messageId || !this.isConversationId(chatId))
          return;
        this.attachReaction(messageId, chatId).catch(() => {
        });
      }
      onPromptEnd(chatId, _sessionId, messageId) {
        if (!messageId || !this.isConversationId(chatId))
          return;
        this.recallReaction(messageId, chatId).catch(() => {
        });
      }
      /**
       * Extract quoted/referenced message context from a reply.
       * DingTalk provides this via text.repliedMsg (newer) or quoteMessage (legacy).
       */
      extractQuotedContext(data) {
        if (data.text?.isReplyMsg && data.text.repliedMsg) {
          const replied = data.text.repliedMsg;
          const isReplyToBot = !!data.chatbotUserId && replied.senderId === data.chatbotUserId;
          const text = this.summarizeRepliedContent(replied);
          return { referencedText: text || void 0, isReplyToBot };
        }
        if (data.quoteMessage) {
          const quote3 = data.quoteMessage;
          const isReplyToBot = !!data.chatbotUserId && quote3.senderId === data.chatbotUserId;
          const text = quote3.text?.content?.trim();
          return { referencedText: text || void 0, isReplyToBot };
        }
        return { isReplyToBot: false };
      }
      /**
       * Build a text summary from a repliedMsg, handling text, richText, and
       * media message types with placeholders.
       */
      summarizeRepliedContent(replied) {
        const msgType = replied.msgType;
        const content = replied.content;
        if (content?.text?.trim()) {
          return content.text.trim();
        }
        if (content?.richText && Array.isArray(content.richText)) {
          const parts2 = [];
          for (const part of content.richText) {
            const partType = part.type || "text";
            if (partType === "text" && part.text) {
              parts2.push(part.text);
            } else if (partType === "picture") {
              parts2.push("[image]");
            } else if (partType === "at" && part.atName) {
              parts2.push(`@${part.atName}`);
            }
          }
          const summary = parts2.join("").trim();
          if (summary)
            return summary;
        }
        switch (msgType) {
          case "picture":
            return "[image]";
          case "file":
            return `[file: ${content?.fileName || "file"}]`;
          case "audio":
            return "[audio]";
          case "video":
            return "[video]";
          default:
            break;
        }
        return "";
      }
      /**
       * Extract text and media download codes from an incoming DingTalk message.
       * Handles text, richText, picture, file, audio, and video message types.
       */
      extractContent(data) {
        const msgtype = data.msgtype || "text";
        if (msgtype === "richText") {
          const richText = data.content?.richText;
          if (!Array.isArray(richText)) {
            return { text: "", downloadCodes: [] };
          }
          let text = "";
          const codes = [];
          for (const part of richText) {
            const partType = part.type || "text";
            if (partType === "text" && part.text) {
              text += part.text;
            } else if (partType === "picture" && part.downloadCode) {
              codes.push(part.downloadCode);
            }
          }
          return {
            text: text.trim() || (codes.length > 0 ? "(image)" : ""),
            downloadCodes: codes,
            mediaType: codes.length > 0 ? "image" : void 0
          };
        }
        if (msgtype === "picture") {
          const code2 = data.content?.downloadCode;
          return {
            text: "(image)",
            downloadCodes: code2 ? [code2] : [],
            mediaType: "image"
          };
        }
        if (msgtype === "file") {
          const code2 = data.content?.downloadCode;
          const fileName = data.content?.fileName || void 0;
          return {
            text: `(file: ${fileName || "file"})`,
            downloadCodes: code2 ? [code2] : [],
            mediaType: "file",
            fileName
          };
        }
        if (msgtype === "audio") {
          const code2 = data.content?.downloadCode;
          const recognition = data.content?.recognition;
          return {
            text: recognition || "(audio)",
            downloadCodes: code2 ? [code2] : [],
            mediaType: "audio"
          };
        }
        if (msgtype === "video") {
          const code2 = data.content?.downloadCode;
          return {
            text: "(video)",
            downloadCodes: code2 ? [code2] : [],
            mediaType: "video"
          };
        }
        return { text: data.text?.content?.trim() || "", downloadCodes: [] };
      }
      /**
       * Download a media file and attach it to the envelope.
       * Images → base64 in envelope; files → saved to temp dir with path in text.
       */
      async attachMedia(envelope, downloadCode, mediaType, fileName) {
        const token2 = this.getAccessToken();
        const robotCode = this.config.clientId;
        if (!token2 || !robotCode) {
          process.stderr.write(`[DingTalk:${this.name}] Cannot download media: missing token or robotCode.
`);
          return;
        }
        const media = await downloadMedia(downloadCode, robotCode, token2);
        if (!media)
          return;
        if (mediaType === "image") {
          const mimeType = media.mimeType.startsWith("image/") ? media.mimeType : "image/jpeg";
          envelope.attachments = [
            ...envelope.attachments || [],
            {
              type: "image",
              data: media.buffer.toString("base64"),
              mimeType
            }
          ];
        } else {
          const dir = join57(tmpdir9(), "channel-files", randomUUID16());
          mkdirSync18(dir, { recursive: true });
          const safeName = basename25(fileName || "") || `dingtalk_${mediaType}_${Date.now()}`;
          const filePath = join57(dir, safeName);
          writeFileSync21(filePath, media.buffer);
          if (envelope.text === `(file: ${fileName || "file"})` || envelope.text === "(audio)" || envelope.text === "(video)") {
            envelope.text = "";
          }
          envelope.attachments = [
            ...envelope.attachments || [],
            {
              type: mediaType,
              filePath,
              mimeType: media.mimeType,
              fileName: safeName
            }
          ];
        }
      }
      onMessage(downstream) {
        try {
          const data = typeof downstream.data === "string" ? JSON.parse(downstream.data) : downstream.data;
          const msgId = data.msgId || downstream.headers.messageId;
          if (msgId && this.seenMessages.has(msgId)) {
            return;
          }
          if (msgId) {
            this.seenMessages.set(msgId, Date.now());
          }
          const isGroup = data.conversationType === "2";
          const sessionWebhook = data.sessionWebhook;
          const conversationId = data.conversationId;
          if (!sessionWebhook) {
            process.stderr.write(`[DingTalk:${this.name}] No sessionWebhook in message, skipping.
`);
            return;
          }
          if (conversationId) {
            this.webhooks.set(conversationId, sessionWebhook);
          }
          const isMentioned = Boolean(data.isInAtList);
          const content = this.extractContent(data);
          let cleanText = content.text;
          if (isMentioned) {
            cleanText = cleanText.replace(/@\S+/, "").trim();
          }
          const quoted = this.extractQuotedContext(data);
          const chatId = conversationId || sessionWebhook;
          const envelopeText = isMentioned ? cleanText : cleanText || content.text;
          const envelope = {
            channelName: this.name,
            senderId: data.senderStaffId || data.senderId || "",
            senderName: data.senderNick || "Unknown",
            chatId,
            text: envelopeText,
            isGroup,
            isMentioned,
            isReplyToBot: quoted.isReplyToBot,
            referencedText: quoted.referencedText
          };
          envelope.messageId = msgId;
          const processMessage2 = /* @__PURE__ */ __name(async () => {
            if (content.downloadCodes.length > 0 && content.mediaType) {
              await this.attachMedia(envelope, content.downloadCodes[0], content.mediaType, content.fileName);
            }
            await this.handleInbound(envelope);
          }, "processMessage");
          processMessage2().catch((err2) => {
            process.stderr.write(`[DingTalk:${this.name}] Error handling message: ${err2}
`);
            this.sendMessage(chatId, "Sorry, something went wrong processing your message.").catch(() => {
            });
          });
        } catch (err2) {
          process.stderr.write(`[DingTalk:${this.name}] Failed to parse message: ${err2}
`);
        }
      }
    };
  }
});

// packages/channels/dingtalk/dist/index.js
var dist_exports4 = {};
__export(dist_exports4, {
  DingtalkChannel: () => DingtalkChannel,
  downloadMedia: () => downloadMedia,
  plugin: () => plugin3
});
var plugin3;
var init_dist10 = __esm({
  "packages/channels/dingtalk/dist/index.js"() {
    "use strict";
    init_esbuild_shims();
    init_DingtalkAdapter();
    init_media2();
    init_DingtalkAdapter();
    plugin3 = {
      channelType: "dingtalk",
      displayName: "DingTalk",
      requiredConfigFields: ["clientId", "clientSecret"],
      createChannel: /* @__PURE__ */ __name((name4, config2, bridge, options2) => new DingtalkChannel(name4, config2, bridge, options2), "createChannel")
    };
  }
});

// packages/cli/src/ui/commands/types.ts
var init_types21 = __esm({
  "packages/cli/src/ui/commands/types.ts"() {
    "use strict";
    init_esbuild_shims();
  }
});

// packages/cli/src/ui/types.ts
var import_react26;
var init_types22 = __esm({
  "packages/cli/src/ui/types.ts"() {
    "use strict";
    init_esbuild_shims();
    import_react26 = __toESM(require_react(), 1);
  }
});

// packages/cli/src/ui/commands/contextCommand.ts
var contextCommand_exports = {};
__export(contextCommand_exports, {
  collectContextData: () => collectContextData,
  contextCommand: () => contextCommand,
  formatContextUsageText: () => formatContextUsageText
});
function estimateTokens(text) {
  if (!text || text.length === 0) return 0;
  let asciiChars = 0;
  let nonAsciiChars = 0;
  for (let i4 = 0; i4 < text.length; i4++) {
    const charCode = text.charCodeAt(i4);
    if (charCode < 128) {
      asciiChars++;
    } else {
      nonAsciiChars++;
    }
  }
  return Math.ceil(asciiChars / 4 + nonAsciiChars * 1.5);
}
function parseMemoryFiles(memoryContent) {
  if (!memoryContent || memoryContent.trim().length === 0) return [];
  const results = [];
  const regex3 = /--- Context from: (.+?) ---\n([\s\S]*?)--- End of Context from: \1 ---/g;
  let match2;
  while ((match2 = regex3.exec(memoryContent)) !== null) {
    const filePath = match2[1];
    const content = match2[2];
    results.push({
      path: filePath,
      tokens: estimateTokens(content)
    });
  }
  if (results.length === 0 && memoryContent.trim().length > 0) {
    results.push({
      path: t4("memory"),
      tokens: estimateTokens(memoryContent)
    });
  }
  return results;
}
async function collectContextData(config2, showDetails) {
  const modelName = config2.getModel() || "unknown";
  const contentGeneratorConfig = config2.getContentGeneratorConfig();
  const contextWindowSize = contentGeneratorConfig.contextWindowSize ?? DEFAULT_TOKEN_LIMIT;
  const apiTotalTokens = uiTelemetryService.getLastPromptTokenCount();
  const apiCachedTokens = uiTelemetryService.getLastCachedContentTokenCount();
  const systemPromptText = getCoreSystemPrompt(void 0, modelName);
  const systemPromptTokens = estimateTokens(systemPromptText);
  const toolRegistry = config2.getToolRegistry();
  const allTools = toolRegistry ? toolRegistry.getAllTools() : [];
  const toolDeclarations = toolRegistry ? toolRegistry.getFunctionDeclarations() : [];
  const toolsJsonStr = JSON.stringify(toolDeclarations);
  const allToolsTokens = estimateTokens(toolsJsonStr);
  const builtinTools = [];
  const mcpTools = [];
  for (const tool of allTools) {
    const toolJsonStr = JSON.stringify(tool.schema);
    const tokens = estimateTokens(toolJsonStr);
    if (tool instanceof DiscoveredMCPTool) {
      mcpTools.push({
        name: `${tool.serverName}__${tool.serverToolName || tool.name}`,
        tokens
      });
    } else if (tool.name !== ToolNames.SKILL) {
      builtinTools.push({
        name: tool.name,
        tokens
      });
    }
  }
  const memoryContent = config2.getUserMemory();
  const memoryFiles = parseMemoryFiles(memoryContent);
  const memoryFilesTokens = memoryFiles.reduce((sum, f5) => sum + f5.tokens, 0);
  const skillTool = allTools.find((tool) => tool.name === ToolNames.SKILL);
  const skillToolDefinitionTokens = skillTool ? estimateTokens(JSON.stringify(skillTool.schema)) : 0;
  const loadedSkillNames = skillTool && "getLoadedSkillNames" in skillTool ? skillTool.getLoadedSkillNames() : /* @__PURE__ */ new Set();
  const skillManager = config2.getSkillManager();
  const skillConfigs = skillManager ? await skillManager.listSkills() : [];
  let loadedBodiesTokens = 0;
  const skills = skillConfigs.map((skill) => {
    const listingTokens = estimateTokens(
      `<skill>
<name>
${skill.name}
</name>
<description>
${skill.description} (${skill.level})
</description>
<location>
${skill.level}
</location>
</skill>`
    );
    const isLoaded = loadedSkillNames.has(skill.name);
    let bodyTokens;
    if (isLoaded && skill.body) {
      const baseDir = skill.filePath ? skill.filePath.replace(/\/[^/]+$/, "") : "";
      bodyTokens = estimateTokens(buildSkillLlmContent(baseDir, skill.body));
      loadedBodiesTokens += bodyTokens;
    }
    return {
      name: skill.name,
      tokens: listingTokens,
      loaded: isLoaded,
      bodyTokens
    };
  });
  const skillsTokens = skillToolDefinitionTokens + loadedBodiesTokens;
  const compressionThreshold = config2.getChatCompression()?.contextPercentageThreshold ?? DEFAULT_COMPRESSION_THRESHOLD;
  const autocompactBuffer = compressionThreshold > 0 ? Math.round((1 - compressionThreshold) * contextWindowSize) : 0;
  const rawOverhead = systemPromptTokens + allToolsTokens + memoryFilesTokens + loadedBodiesTokens;
  const isEstimated = apiTotalTokens === 0;
  const mcpToolsTotalTokens = mcpTools.reduce(
    (sum, tool) => sum + tool.tokens,
    0
  );
  let totalTokens;
  let displaySystemPrompt;
  let displayBuiltinTools;
  let displayMcpTools;
  let displayMemoryFiles;
  let displaySkills;
  let messagesTokens;
  let freeSpace;
  let detailBuiltinTools;
  let detailMcpTools;
  let detailMemoryFiles;
  let detailSkills;
  if (isEstimated) {
    totalTokens = 0;
    displaySystemPrompt = systemPromptTokens;
    displaySkills = skillsTokens;
    displayBuiltinTools = Math.max(
      0,
      allToolsTokens - skillToolDefinitionTokens - mcpToolsTotalTokens
    );
    displayMcpTools = mcpToolsTotalTokens;
    displayMemoryFiles = memoryFilesTokens;
    messagesTokens = 0;
    freeSpace = Math.max(
      0,
      contextWindowSize - rawOverhead - autocompactBuffer
    );
    detailBuiltinTools = builtinTools;
    detailMcpTools = mcpTools;
    detailMemoryFiles = memoryFiles;
    detailSkills = skills;
  } else {
    totalTokens = apiTotalTokens;
    const overheadScale = rawOverhead > totalTokens ? totalTokens / rawOverhead : 1;
    displaySystemPrompt = Math.round(systemPromptTokens * overheadScale);
    const scaledAllTools = Math.round(allToolsTokens * overheadScale);
    displayMemoryFiles = Math.round(memoryFilesTokens * overheadScale);
    displaySkills = Math.round(skillsTokens * overheadScale);
    const scaledMcpTotal = Math.round(mcpToolsTotalTokens * overheadScale);
    displayMcpTools = scaledMcpTotal;
    const scaledSkillDefinition = Math.round(
      skillToolDefinitionTokens * overheadScale
    );
    displayBuiltinTools = Math.max(
      0,
      scaledAllTools - scaledSkillDefinition - scaledMcpTotal
    );
    const scaledOverhead = displaySystemPrompt + scaledAllTools + displayMemoryFiles + Math.round(loadedBodiesTokens * overheadScale);
    if (apiCachedTokens > 0) {
      messagesTokens = Math.max(0, totalTokens - apiCachedTokens);
    } else {
      messagesTokens = Math.max(0, totalTokens - scaledOverhead);
    }
    freeSpace = Math.max(
      0,
      contextWindowSize - totalTokens - autocompactBuffer
    );
    const scaleDetail = /* @__PURE__ */ __name((items) => overheadScale < 1 ? items.map((item) => ({
      ...item,
      tokens: Math.round(item.tokens * overheadScale)
    })) : items, "scaleDetail");
    detailBuiltinTools = scaleDetail(builtinTools);
    detailMcpTools = scaleDetail(mcpTools);
    detailMemoryFiles = scaleDetail(memoryFiles);
    detailSkills = overheadScale < 1 ? skills.map((item) => ({
      ...item,
      tokens: Math.round(item.tokens * overheadScale),
      bodyTokens: item.bodyTokens ? Math.round(item.bodyTokens * overheadScale) : void 0
    })) : skills;
  }
  const breakdown = {
    systemPrompt: displaySystemPrompt,
    builtinTools: displayBuiltinTools,
    mcpTools: displayMcpTools,
    memoryFiles: displayMemoryFiles,
    skills: displaySkills,
    messages: messagesTokens,
    freeSpace,
    autocompactBuffer
  };
  return {
    type: "context_usage" /* CONTEXT_USAGE */,
    modelName,
    totalTokens,
    contextWindowSize,
    breakdown,
    builtinTools: showDetails ? detailBuiltinTools : [],
    mcpTools: showDetails ? detailMcpTools : [],
    memoryFiles: showDetails ? detailMemoryFiles : [],
    skills: showDetails ? detailSkills : [],
    isEstimated,
    showDetails
  };
}
function fmtTokens(tokens) {
  if (tokens >= 1e3) {
    return `${(tokens / 1e3).toFixed(1)}k`;
  }
  return `${tokens}`;
}
function fmtCategoryRow(label, tokens, contextWindowSize, indent = "  ") {
  const percentage = (tokens / contextWindowSize * 100).toFixed(1);
  const right3 = `${fmtTokens(tokens)} tokens (${percentage}%)`;
  const leftPart = `${indent}${label}`;
  const totalWidth = 56;
  const dots = Math.max(1, totalWidth - leftPart.length - right3.length);
  return `${leftPart}${" ".repeat(dots)}${right3}`;
}
function formatContextUsageText(data) {
  const {
    modelName,
    totalTokens,
    contextWindowSize,
    breakdown,
    builtinTools,
    mcpTools,
    memoryFiles,
    skills,
    isEstimated,
    showDetails
  } = data;
  const lines = [];
  lines.push("## Context Usage");
  lines.push("");
  if (isEstimated) {
    lines.push("*No API response yet. Send a message to see actual usage.*");
    lines.push("");
    lines.push("**Estimated pre-conversation overhead**");
    lines.push(
      `Model: ${modelName}  Context window: ${fmtTokens(contextWindowSize)} tokens`
    );
    lines.push("");
  } else {
    lines.push(
      `Model: ${modelName}  Context window: ${fmtTokens(contextWindowSize)} tokens`
    );
    lines.push("");
    lines.push(fmtCategoryRow("Used", totalTokens, contextWindowSize));
    lines.push(fmtCategoryRow("Free", breakdown.freeSpace, contextWindowSize));
    lines.push(
      fmtCategoryRow(
        "Autocompact buffer",
        breakdown.autocompactBuffer,
        contextWindowSize
      )
    );
    lines.push("");
    lines.push("**Usage by category**");
  }
  lines.push(
    fmtCategoryRow("System prompt", breakdown.systemPrompt, contextWindowSize)
  );
  lines.push(
    fmtCategoryRow("Built-in tools", breakdown.builtinTools, contextWindowSize)
  );
  if (breakdown.mcpTools > 0) {
    lines.push(
      fmtCategoryRow("MCP tools", breakdown.mcpTools, contextWindowSize)
    );
  }
  lines.push(
    fmtCategoryRow("Memory files", breakdown.memoryFiles, contextWindowSize)
  );
  lines.push(fmtCategoryRow("Skills", breakdown.skills, contextWindowSize));
  if (!isEstimated) {
    lines.push(
      fmtCategoryRow("Messages", breakdown.messages, contextWindowSize)
    );
  }
  if (showDetails) {
    const sortedBuiltin = [...builtinTools].sort((a2, b2) => b2.tokens - a2.tokens);
    const sortedMcp = [...mcpTools].sort((a2, b2) => b2.tokens - a2.tokens);
    const sortedMemory = [...memoryFiles].sort((a2, b2) => b2.tokens - a2.tokens);
    const sortedSkills = [...skills].sort((a2, b2) => {
      if (a2.loaded !== b2.loaded) return a2.loaded ? -1 : 1;
      return b2.tokens + (b2.bodyTokens ?? 0) - (a2.tokens + (a2.bodyTokens ?? 0));
    });
    if (sortedBuiltin.length > 0) {
      lines.push("");
      lines.push("**Built-in tools**");
      for (const tool of sortedBuiltin) {
        lines.push(
          fmtCategoryRow(tool.name, tool.tokens, contextWindowSize, "  \u2514 ")
        );
      }
    }
    if (sortedMcp.length > 0) {
      lines.push("");
      lines.push("**MCP tools**");
      for (const tool of sortedMcp) {
        lines.push(
          fmtCategoryRow(tool.name, tool.tokens, contextWindowSize, "  \u2514 ")
        );
      }
    }
    if (sortedMemory.length > 0) {
      lines.push("");
      lines.push("**Memory files**");
      for (const file2 of sortedMemory) {
        lines.push(
          fmtCategoryRow(file2.path, file2.tokens, contextWindowSize, "  \u2514 ")
        );
      }
    }
    if (sortedSkills.length > 0) {
      lines.push("");
      lines.push("**Skills**");
      for (const skill of sortedSkills) {
        const label = skill.loaded ? `${skill.name} (active)` : skill.name;
        lines.push(
          fmtCategoryRow(label, skill.tokens, contextWindowSize, "  \u2514 ")
        );
        if (skill.loaded && skill.bodyTokens && skill.bodyTokens > 0) {
          lines.push(
            fmtCategoryRow(
              "body loaded",
              skill.bodyTokens,
              contextWindowSize,
              "    \u2514 "
            )
          );
        }
      }
    }
  } else {
    lines.push("");
    lines.push("*Run /context detail for per-item breakdown.*");
  }
  return lines.join("\n");
}
var DEFAULT_COMPRESSION_THRESHOLD, contextCommand;
var init_contextCommand = __esm({
  "packages/cli/src/ui/commands/contextCommand.ts"() {
    "use strict";
    init_esbuild_shims();
    init_types21();
    init_types22();
    init_dist4();
    init_i18n();
    DEFAULT_COMPRESSION_THRESHOLD = 0.7;
    __name(estimateTokens, "estimateTokens");
    __name(parseMemoryFiles, "parseMemoryFiles");
    __name(collectContextData, "collectContextData");
    __name(fmtTokens, "fmtTokens");
    __name(fmtCategoryRow, "fmtCategoryRow");
    __name(formatContextUsageText, "formatContextUsageText");
    contextCommand = {
      name: "context",
      get description() {
        return t4(
          'Show context window usage breakdown. Use "/context detail" for per-item breakdown.'
        );
      },
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive", "non_interactive", "acp"],
      action: /* @__PURE__ */ __name(async (context2, args2) => {
        const showDetails = args2?.trim().toLowerCase() === "detail" || args2?.trim().toLowerCase() === "-d";
        const executionMode = context2.executionMode ?? "interactive";
        const { config: config2 } = context2.services;
        if (!config2) {
          if (executionMode === "interactive") {
            context2.ui.addItem(
              {
                type: "error" /* ERROR */,
                text: t4("Config not loaded.")
              },
              Date.now()
            );
            return;
          }
          return {
            type: "message",
            messageType: "error",
            content: t4("Config not loaded.")
          };
        }
        const contextUsageItem = await collectContextData(config2, showDetails);
        if (executionMode === "interactive") {
          context2.ui.addItem(contextUsageItem, Date.now());
          return;
        } else {
          return {
            type: "message",
            messageType: "info",
            content: formatContextUsageText(contextUsageItem)
          };
        }
      }, "action"),
      subCommands: [
        {
          name: "detail",
          get description() {
            return t4("Show per-item context usage breakdown.");
          },
          kind: "built-in" /* BUILT_IN */,
          supportedModes: ["interactive", "non_interactive", "acp"],
          action: /* @__PURE__ */ __name(async (context2) => {
            await contextCommand.action(context2, "detail");
          }, "action")
        }
      ]
    };
  }
});

// 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/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((name4) => {
        const prop = obj[name4];
        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((name4, { prefix }) => {
      if (name4.startsWith("language:")) {
        return name4.replace("language:", "language-");
      }
      if (name4.includes(".")) {
        const pieces = name4.split(".");
        return [
          `${prefix}${pieces.shift()}`,
          ...pieces.map((x3, i4) => `${x3}${"_".repeat(i4 + 1)}`)
        ].join(" ");
      }
      return `${prefix}${name4}`;
    }, "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, name4) {
        const node = emitter.root;
        if (name4) node.scope = `language:${name4}`;
        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(...args2) {
      const joined = args2.map((x3) => source2(x3)).join("");
      return joined;
    }
    __name(concat2, "concat");
    function stripOptionsFromArgs2(args2) {
      const opts = args2[args2.length - 1];
      if (typeof opts === "object" && opts.constructor === Object) {
        args2.splice(args2.length - 1, 1);
        return opts;
      } else {
        return {};
      }
    }
    __name(stripOptionsFromArgs2, "stripOptionsFromArgs");
    function either2(...args2) {
      const opts = stripOptionsFromArgs2(args2);
      const joined = "(" + (opts.capture ? "" : "?:") + args2.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 out2 = "";
        while (re3.length > 0) {
          const match2 = BACKREF_RE.exec(re3);
          if (!match2) {
            out2 += re3;
            break;
          }
          out2 += re3.substring(0, match2.index);
          re3 = re3.substring(match2.index + match2[0].length);
          if (match2[0][0] === "\\" && match2[1]) {
            out2 += "\\" + String(Number(match2[1]) + offset);
          } else {
            out2 += match2[0];
            if (match2[0] === "(") {
              numCaptures++;
            }
          }
        }
        return out2;
      }).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 error40 = /* @__PURE__ */ __name((message) => {
      console.error(message);
    }, "error");
    var warn = /* @__PURE__ */ __name((message, ...args2) => {
      console.log(`WARN: ${message}`, ...args2);
    }, "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 i4 = 1; i4 <= regexes.length; i4++) {
        positions[i4 + offset] = scopeNames[i4];
        emit[i4 + offset] = true;
        offset += countMatchGroups(regexes[i4 - 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) {
        error40("skip, excludeBegin, returnBegin not compatible with beginScope: {}");
        throw MultiClassError;
      }
      if (typeof mode.beginScope !== "object" || mode.beginScope === null) {
        error40("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) {
        error40("skip, excludeEnd, returnEnd not compatible with endScope: {}");
        throw MultiClassError;
      }
      if (typeof mode.endScope !== "object" || mode.endScope === null) {
        error40("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 i4 = match2.findIndex((el, i5) => i5 > 0 && el !== void 0);
          const matchData = this.matchIndexes[i4];
          match2.splice(0, i4);
          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 i4 = 1;
          const max = match2.length - 1;
          while (i4 <= max) {
            if (!scope._emit[i4]) {
              i4++;
              continue;
            }
            const klass = language.classNameAliases[scope[i4]] || scope[i4];
            const text = match2[i4];
            if (klass) {
              emitKeyword(text, klass);
            } else {
              modeBuffer = text;
              processKeywords();
              modeBuffer = "";
            }
            i4++;
          }
        }
        __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 origin2 = 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 (origin2.skip) {
            modeBuffer += lexeme;
          } else {
            if (!(origin2.returnEnd || origin2.excludeEnd)) {
              modeBuffer += lexeme;
            }
            processBuffer();
            if (origin2.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 origin2.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 err2 = new Error(`0 width match regex (${languageName})`);
              err2.languageName = languageName;
              err2.badRule = lastMatch.rule;
              throw err2;
            }
            return 1;
          }
          lastMatch = match2;
          if (match2.type === "begin") {
            return doBeginMatch(match2);
          } else if (match2.type === "illegal" && !ignoreIllegals) {
            const err2 = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top2.scope || "<unnamed>") + '"');
            err2.mode = top2;
            throw err2;
          } 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 err2 = new Error("potential infinite loop, way more iterations than matches");
            throw err2;
          }
          modeBuffer += lexeme;
          return lexeme.length;
        }
        __name(processLexeme, "processLexeme");
        const language = getLanguage(languageName);
        if (!language) {
          error40(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 (err2) {
          if (err2.message && err2.message.includes("Illegal")) {
            return {
              language: languageName,
              value: escape7(codeToHighlight),
              illegal: true,
              relevance: 0,
              _illegalBy: {
                message: err2.message,
                index,
                context: codeToHighlight.slice(index - 100, index + 100),
                mode: err2.mode,
                resultSoFar: result
              },
              _emitter: emitter
            };
          } else if (SAFE_MODE) {
            return {
              language: languageName,
              value: escape7(codeToHighlight),
              illegal: false,
              relevance: 0,
              errorRaised: err2,
              _emitter: emitter,
              _top: top2
            };
          } else {
            throw err2;
          }
        }
      }
      __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(
          (name4) => _highlight(name4, 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 err2 = new HTMLInjectionError(
              "One of your code blocks includes unescaped HTML.",
              element.innerHTML
            );
            throw err2;
          }
        }
        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) {
          error40("Language definition for '{}' could not be registered.".replace("{}", languageName));
          if (!SAFE_MODE) {
            throw error$1;
          } else {
            error40(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(name4) {
        name4 = (name4 || "").toLowerCase();
        return languages[name4] || languages[aliases[name4]];
      }
      __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(name4) {
        const lang = getLanguage(name4);
        return lang && !lang.disableAutodetect;
      }
      __name(autoDetection, "autoDetection");
      function upgradePluginAPI(plugin4) {
        if (plugin4["before:highlightBlock"] && !plugin4["before:highlightElement"]) {
          plugin4["before:highlightElement"] = (data) => {
            plugin4["before:highlightBlock"](
              Object.assign({ block: data.el }, data)
            );
          };
        }
        if (plugin4["after:highlightBlock"] && !plugin4["after:highlightElement"]) {
          plugin4["after:highlightElement"] = (data) => {
            plugin4["after:highlightBlock"](
              Object.assign({ block: data.el }, data)
            );
          };
        }
      }
      __name(upgradePluginAPI, "upgradePluginAPI");
      function addPlugin(plugin4) {
        upgradePluginAPI(plugin4);
        plugins.push(plugin4);
      }
      __name(addPlugin, "addPlugin");
      function removePlugin(plugin4) {
        const index = plugins.indexOf(plugin4);
        if (index !== -1) {
          plugins.splice(index, 1);
        }
      }
      __name(removePlugin, "removePlugin");
      function fire(event, args2) {
        const cb = event;
        plugins.forEach(function(plugin4) {
          if (plugin4[cb]) {
            plugin4[cb](args2);
          }
        });
      }
      __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/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 name4 = getComponentNameFromType(type);
          return name4 ? "<" + name4 + ">" : "<...>";
        } 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 (hasOwnProperty3.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 (hasOwnProperty3.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, hasOwnProperty3 = 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/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 Fragment29 = 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 = Fragment29;
        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 hasOwnProperty3 = 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 i4 = 0; i4 < 10; i4++) {
          test2["_" + String.fromCharCode(i4)] = i4;
        }
        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 (err2) {
        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 (hasOwnProperty3.call(from, key)) {
            to[key] = from[key];
          }
        }
        if (getOwnPropertySymbols) {
          symbols = getOwnPropertySymbols(from);
          for (var i4 = 0; i4 < symbols.length; i4++) {
            if (propIsEnumerable.call(from, symbols[i4])) {
              to[symbols[i4]] = from[symbols[i4]];
            }
          }
        }
      }
      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 error40;
            try {
              if (typeof typeSpecs[typeSpecName] !== "function") {
                var err2 = 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`."
                );
                err2.name = "Invariant Violation";
                throw err2;
              }
              error40 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
            } catch (ex) {
              error40 = ex;
            }
            if (error40 && !(error40 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 error40 + ". 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 (error40 instanceof Error && !(error40.message in loggedTypeFailures)) {
              loggedTypeFailures[error40.message] = true;
              var stack = getStack ? getStack() : "";
              printWarning(
                "Failed " + location + " type: " + error40.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 err2 = 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"
              );
              err2.name = "Invariant Violation";
              throw err2;
            } 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 i4 = 0; i4 < propValue.length; i4++) {
            var error40 = typeChecker(propValue, i4, componentName, location, propFullName + "[" + i4 + "]", ReactPropTypesSecret);
            if (error40 instanceof Error) {
              return error40;
            }
          }
          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 i4 = 0; i4 < expectedValues.length; i4++) {
            if (is(propValue, expectedValues[i4])) {
              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 error40 = typeChecker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
              if (error40 instanceof Error) {
                return error40;
              }
            }
          }
          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 i4 = 0; i4 < arrayOfTypeCheckers.length; i4++) {
          var checker = arrayOfTypeCheckers[i4];
          if (typeof checker !== "function") {
            printWarning(
              "Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i4 + "."
            );
            return emptyFunctionThatReturnsNull;
          }
        }
        function validate3(props, propName, componentName, location, propFullName) {
          var expectedTypes = [];
          for (var i5 = 0; i5 < arrayOfTypeCheckers.length; i5++) {
            var checker2 = arrayOfTypeCheckers[i5];
            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 error40 = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
            if (error40) {
              return error40;
            }
          }
          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 error40 = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
            if (error40) {
              return error40;
            }
          }
          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 iterator2 = iteratorFn.call(propValue);
              var step;
              if (iteratorFn !== propValue.entries) {
                while (!(step = iterator2.next()).done) {
                  if (!isNode3(step.value)) {
                    return false;
                  }
                }
              } else {
                while (!(step = iterator2.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 err2 = 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"
        );
        err2.name = "Invariant Violation";
        throw err2;
      }
      __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/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 os59 = __require("os");
    var tty3 = __require("tty");
    var hasFlag3 = require_has_flag2();
    var { env: env6 } = 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 env6) {
      if (env6.FORCE_COLOR === "true") {
        forceColor = 1;
      } else if (env6.FORCE_COLOR === "false") {
        forceColor = 0;
      } else {
        forceColor = env6.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env6.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 (env6.TERM === "dumb") {
        return min;
      }
      if (process.platform === "win32") {
        const osRelease = os59.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 (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].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 ("TERM_PROGRAM" in env6) {
        const version2 = 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(supportsColor3, "supportsColor");
    function getSupportLevel(stream5) {
      const level = supportsColor3(stream5, stream5 && stream5.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 parseVersion2(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(parseVersion2, "parseVersion");
    function supportsHyperlink(stream5) {
      const { env: env6 } = process;
      if ("FORCE_HYPERLINK" in env6) {
        return !(env6.FORCE_HYPERLINK.length > 0 && parseInt(env6.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 env6) {
        return true;
      }
      if (!supportsColor3.supportsColor(stream5)) {
        return false;
      }
      if (stream5 && !stream5.isTTY) {
        return false;
      }
      if (process.platform === "win32") {
        return false;
      }
      if ("CI" in env6) {
        return false;
      }
      if ("TEAMCITY_VERSION" in env6) {
        return false;
      }
      if ("TERM_PROGRAM" in env6) {
        const version2 = parseVersion2(env6.TERM_PROGRAM_VERSION);
        switch (env6.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 env6) {
        if (env6.VTE_VERSION === "0.50.0") {
          return false;
        }
        const version2 = parseVersion2(env6.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/tinycolor2/cjs/tinycolor.js
var require_tinycolor = __commonJS({
  "node_modules/tinycolor2/cjs/tinycolor.js"(exports2, module2) {
    init_esbuild_shims();
    (function(global2, factory2) {
      typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory2() : typeof define === "function" && define.amd ? define(factory2) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.tinycolor = factory2());
    })(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, G3, 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) G3 = GsRGB / 12.92;
          else G3 = 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 * G3 + 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 toString3(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, args2) {
          var color = fn.apply(null, [this].concat([].slice.call(args2)));
          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, args2) {
          return fn.apply(null, [this].concat([].slice.call(args2)));
        }, "_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 i4 in color) {
            if (color.hasOwnProperty(i4)) {
              if (i4 === "a") {
                newColor[i4] = color[i4];
              } else {
                newColor[i4] = convertToPercentage(color[i4]);
              }
            }
          }
          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 i4 = Math.floor(h3), f5 = h3 - i4, p2 = v2 * (1 - s5), q2 = v2 * (1 - f5 * s5), t5 = v2 * (1 - (1 - f5) * s5), mod2 = i4 % 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 i4 = 1; i4 < number4; i4++) {
          result.push(tinycolor({
            h: (hsl.h + i4 * 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, out2;
        out2 = false;
        wcag2Parms = validateWCAG2Parms(wcag2);
        switch (wcag2Parms.level + wcag2Parms.size) {
          case "AAsmall":
          case "AAAlarge":
            out2 = readability >= 4.5;
            break;
          case "AAlarge":
            out2 = readability >= 3;
            break;
          case "AAAsmall":
            out2 = readability >= 7;
            break;
        }
        return out2;
      };
      tinycolor.mostReadable = function(baseColor, colorList, args2) {
        var bestColor = null;
        var bestScore = 0;
        var readability;
        var includeFallbackColors, level, size;
        args2 = args2 || {};
        includeFallbackColors = args2.includeFallbackColors;
        level = args2.level;
        size = args2.size;
        for (var i4 = 0; i4 < colorList.length; i4++) {
          readability = tinycolor.readability(baseColor, colorList[i4]);
          if (readability > bestScore) {
            bestScore = readability;
            bestColor = tinycolor(colorList[i4]);
          }
        }
        if (tinycolor.isReadable(baseColor, bestColor, {
          level,
          size
        }) || !includeFallbackColors) {
          return bestColor;
        } else {
          args2.includeFallbackColors = false;
          return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args2);
        }
      };
      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 i4 in o3) {
          if (o3.hasOwnProperty(i4)) {
            flipped[o3[i4]] = i4;
          }
        }
        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(start2, end, steps) {
      let step = {};
      for (let k2 in start2) {
        if (start2.hasOwnProperty(k2)) {
          step[k2] = steps === 0 ? 0 : (end[k2] - start2[k2]) / steps;
        }
      }
      return step;
    }
    __name(stepize, "stepize");
    function interpolate2(step, start2, i4, max) {
      let color = {};
      for (let k2 in start2) {
        if (start2.hasOwnProperty(k2)) {
          color[k2] = step[k2] * i4 + start2[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, stop22, steps) {
      const start2 = stop1.color.toRgb();
      const end = stop22.color.toRgb();
      const step = stepize(start2, end, steps);
      let gradient = [stop1.color];
      for (let i4 = 1; i4 < steps; i4++) {
        const color = interpolate2(step, start2, i4, RGBA_MAX);
        gradient.push(tinycolor(color));
      }
      return gradient;
    }
    __name(interpolateRgb, "interpolateRgb");
    function interpolateHsv(stop1, stop22, steps, mode) {
      const start2 = stop1.color.toHsv();
      const end = stop22.color.toHsv();
      if (start2.s === 0 || end.s === 0) {
        return interpolateRgb(stop1, stop22, steps);
      }
      let trigonometric;
      if (typeof mode === "boolean") {
        trigonometric = mode;
      } else {
        const trigShortest = start2.h < end.h && end.h - start2.h < 180 || start2.h > end.h && start2.h - end.h > 180;
        trigonometric = mode === "long" && trigShortest || mode === "short" && !trigShortest;
      }
      const step = stepize(start2, end, steps);
      let gradient = [stop1.color];
      let diff4;
      if (start2.h <= end.h && !trigonometric || start2.h >= end.h && trigonometric) {
        diff4 = end.h - start2.h;
      } else if (trigonometric) {
        diff4 = 360 - end.h + start2.h;
      } else {
        diff4 = 360 - start2.h + end.h;
      }
      step.h = Math.pow(-1, trigonometric ? 1 : 0) * Math.abs(diff4) / steps;
      for (let i4 = 1; i4 < steps; i4++) {
        const color = interpolate2(step, start2, i4, 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 i4 = 1; i4 < l3; i4++) {
        const step = (steps - 1) * (stops[i4].pos - stops[i4 - 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 start2, end;
      for (let i4 = 0, l3 = stops.length; i4 < l3 - 1; i4++) {
        if (pos2 >= stops[i4].pos && pos2 < stops[i4 + 1].pos) {
          start2 = stops[i4];
          end = stops[i4 + 1];
          break;
        }
      }
      if (!start2) {
        start2 = end = stops[stops.length - 1];
      }
      const step = stepize(start2.color[method](), end.color[method](), (end.pos - start2.pos) * 100);
      const color = interpolate2(step, start2.color[method](), (pos2 - start2.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((stop3, i4) => {
          const hasPosition = stop3.pos !== void 0;
          if (havingPositions ^ hasPosition) {
            throw new Error("Cannot mix positionned and not posionned color stops");
          }
          if (hasPosition) {
            const hasColor = stop3.color !== void 0;
            if (!hasColor && (lastColorLess || i4 === 0 || i4 === l3 - 1)) {
              throw new Error("Cannot define two consecutive position-only stops");
            }
            lastColorLess = !hasColor;
            stop3 = {
              color: hasColor ? tinycolor(stop3.color) : null,
              colorLess: !hasColor,
              pos: stop3.pos
            };
            if (stop3.pos < 0 || stop3.pos > 1) {
              throw new Error("Color stops positions must be between 0 and 1");
            } else if (stop3.pos < p2) {
              throw new Error("Color stops positions are not ordered");
            }
            p2 = stop3.pos;
          } else {
            stop3 = {
              color: tinycolor(stop3.color !== void 0 ? stop3.color : stop3),
              pos: i4 / (l3 - 1)
            };
          }
          return stop3;
        });
        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(stop3) {
          stops.push({
            color: stop3.color,
            pos: 1 - stop3.pos
          });
        });
        return new _TinyGradient(stops.reverse());
      }
      /**
       * Return new instance with looped stops
       * @return {TinyGradient}
       */
      loop() {
        let stops1 = [];
        let stops2 = [];
        this.stops.forEach((stop3) => {
          stops1.push({
            color: stop3.color,
            pos: stop3.pos / 2
          });
        });
        this.stops.slice(0, -1).forEach((stop3) => {
          stops2.push({
            color: stop3.color,
            pos: 1 - stop3.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((stop3, i4) => {
          if (stop3.colorLess) {
            stop3.color = interpolateRgb(this.stops[i4 - 1], this.stops[i4 + 1], 2)[1];
          }
        });
        for (let i4 = 0, l3 = this.stops.length; i4 < l3 - 1; i4++) {
          const rgb = interpolateRgb(this.stops[i4], this.stops[i4 + 1], substeps[i4]);
          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((stop3, i4) => {
          if (stop3.colorLess) {
            stop3.color = interpolateHsv(this.stops[i4 - 1], this.stops[i4 + 1], 2, mode)[1];
          }
        });
        for (let i4 = 0, l3 = this.stops.length; i4 < l3 - 1; i4++) {
          const hsv = interpolateHsv(this.stops[i4], this.stops[i4 + 1], substeps[i4], 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(stop3) {
          css2 += ", " + (stop3.colorLess ? "" : stop3.color.toRgbString() + " ") + stop3.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 chalk10 = require_source();
    var tinygradient = require_tinygradient();
    var forbiddenChars = /\s/g;
    function InitGradient(...args2) {
      const grad = tinygradient.apply(this, args2);
      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 : chalk10.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 += chalk10.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);
    }
  }
});

// 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](instance2) {
        if (instance2 && typeof instance2 === "object" && exports2.GAXIOS_ERROR_SYMBOL in instance2 && instance2[exports2.GAXIOS_ERROR_SYMBOL] === pkg2.version) {
          return true;
        }
        return Function.prototype[Symbol.hasInstance].call(_GaxiosError, instance2);
      }
      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(err2) {
      let config2 = getConfig2(err2);
      if (!err2 || !err2.config || !config2 && !err2.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;
      err2.config.retryConfig = config2;
      const shouldRetryFn = config2.shouldRetry || shouldRetryRequest;
      if (!await shouldRetryFn(err2)) {
        return { shouldRetry: false, config: err2.config };
      }
      const delay5 = getNextRetryDelay(config2);
      err2.config.retryConfig.currentRetryAttempt += 1;
      const backoff = config2.retryBackoff ? config2.retryBackoff(err2, delay5) : new Promise((resolve42) => {
        setTimeout(resolve42, delay5);
      });
      if (config2.onRetryAttempt) {
        await config2.onRetryAttempt(err2);
      }
      await backoff;
      return { shouldRetry: true, config: err2.config };
    }
    __name(getRetryConfig, "getRetryConfig");
    function shouldRetryRequest(err2) {
      const config2 = getConfig2(err2);
      if (err2.config.signal?.aborted && err2.code !== "TimeoutError" || err2.code === "AbortError") {
        return false;
      }
      if (!config2 || config2.retry === 0) {
        return false;
      }
      if (!err2.response && (config2.currentRetryAttempt || 0) >= config2.noResponseRetries) {
        return false;
      }
      if (!config2.httpMethodsToRetry || !config2.httpMethodsToRetry.includes(err2.config.method?.toUpperCase() || "GET")) {
        return false;
      }
      if (err2.response && err2.response.status) {
        let isInRange = false;
        for (const [min, max] of config2.statusCodesToRetry) {
          const status = err2.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 getConfig2(err2) {
      if (err2 && err2.config && err2.config.retryConfig) {
        return err2.config.retryConfig;
      }
      return;
    }
    __name(getConfig2, "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, isBlob4, 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");
    isBlob4 = /* @__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: () => toFormData4
});
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 toFormData4(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 file2 = new file_default(entryChunks, filename, { type: contentType });
    formData.append(entryName, file2);
  }, "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, noop10, 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");
    noop10 = /* @__PURE__ */ __name(() => {
    }, "noop");
    MultipartParser2 = class {
      static {
        __name(this, "MultipartParser");
      }
      /**
       * @param {string} boundary
       */
      constructor(boundary) {
        this.index = 0;
        this.flags = 0;
        this.onHeaderEnd = noop10;
        this.onHeaderField = noop10;
        this.onHeadersEnd = noop10;
        this.onHeaderValue = noop10;
        this.onPartBegin = noop10;
        this.onPartData = noop10;
        this.onPartEnd = noop10;
        this.boundaryChars = {};
        boundary = "\r\n--" + boundary;
        const ui8a = new Uint8Array(boundary.length);
        for (let i4 = 0; i4 < boundary.length; i4++) {
          ui8a[i4] = boundary.charCodeAt(i4);
          this.boundaryChars[ui8a[i4]] = true;
        }
        this.boundary = ui8a;
        this.lookbehind = new Uint8Array(this.boundary.length + 8);
        this.state = S3.START_BOUNDARY;
      }
      /**
       * @param {Uint8Array} data
       */
      write(data) {
        let i4 = 0;
        const length_ = data.length;
        let previousIndex = this.index;
        let { lookbehind, boundary, boundaryChars, index, state, flags: flags2 } = this;
        const boundaryLength = this.boundary.length;
        const boundaryEnd = boundaryLength - 1;
        const bufferLength = data.length;
        let c4;
        let cl;
        const mark = /* @__PURE__ */ __name((name4) => {
          this[name4 + "Mark"] = i4;
        }, "mark");
        const clear = /* @__PURE__ */ __name((name4) => {
          delete this[name4 + "Mark"];
        }, "clear");
        const callback = /* @__PURE__ */ __name((callbackSymbol, start2, end, ui8a) => {
          if (start2 === void 0 || start2 !== end) {
            this[callbackSymbol](ui8a && ui8a.subarray(start2, end));
          }
        }, "callback");
        const dataCallback = /* @__PURE__ */ __name((name4, clear2) => {
          const markSymbol = name4 + "Mark";
          if (!(markSymbol in this)) {
            return;
          }
          if (clear2) {
            callback(name4, this[markSymbol], i4, data);
            delete this[markSymbol];
          } else {
            callback(name4, this[markSymbol], data.length, data);
            this[markSymbol] = 0;
          }
        }, "dataCallback");
        for (i4 = 0; i4 < length_; i4++) {
          c4 = data[i4];
          switch (state) {
            case S3.START_BOUNDARY:
              if (index === boundary.length - 2) {
                if (c4 === HYPHEN2) {
                  flags2 |= F3.LAST_BOUNDARY;
                } else if (c4 !== CR2) {
                  return;
                }
                index++;
                break;
              } else if (index - 1 === boundary.length - 2) {
                if (flags2 & F3.LAST_BOUNDARY && c4 === HYPHEN2) {
                  state = S3.END;
                  flags2 = 0;
                } else if (!(flags2 & 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) {
                i4 += boundaryEnd;
                while (i4 < bufferLength && !(data[i4] in boundaryChars)) {
                  i4 += boundaryLength;
                }
                i4 -= boundaryEnd;
                c4 = data[i4];
              }
              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) {
                  flags2 |= F3.PART_BOUNDARY;
                } else if (c4 === HYPHEN2) {
                  flags2 |= F3.LAST_BOUNDARY;
                } else {
                  index = 0;
                }
              } else if (index - 1 === boundary.length) {
                if (flags2 & F3.PART_BOUNDARY) {
                  index = 0;
                  if (c4 === LF2) {
                    flags2 &= ~F3.PART_BOUNDARY;
                    callback("onPartEnd");
                    callback("onPartBegin");
                    state = S3.HEADER_FIELD_START;
                    break;
                  }
                } else if (flags2 & F3.LAST_BOUNDARY) {
                  if (c4 === HYPHEN2) {
                    callback("onPartEnd");
                    state = S3.END;
                    flags2 = 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");
                i4--;
              }
              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 = flags2;
      }
      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(toFormData4, "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: body2 } = data;
  if (body2 === null) {
    return Buffer7.alloc(0);
  }
  if (!(body2 instanceof Stream7)) {
    return Buffer7.alloc(0);
  }
  const accum = [];
  let accumBytes = 0;
  try {
    for await (const chunk of body2) {
      if (data.size > 0 && accumBytes + chunk.length > data.size) {
        const error40 = new FetchError3(`content size at ${data.url} over limit: ${data.size}`, "max-size");
        body2.destroy(error40);
        throw error40;
      }
      accumBytes += chunk.length;
      accum.push(chunk);
    }
  } catch (error40) {
    const error_ = error40 instanceof FetchBaseError2 ? error40 : new FetchError3(`Invalid response body while trying to fetch ${data.url}: ${error40.message}`, "system", error40);
    throw error_;
  }
  if (body2.readableEnded === true || body2._readableState.ended === true) {
    try {
      if (accum.every((c4) => typeof c4 === "string")) {
        return Buffer7.from(accum.join(""));
      }
      return Buffer7.concat(accum, accumBytes);
    } catch (error40) {
      throw new FetchError3(`Could not create Buffer from response body for ${data.url}: ${error40.message}`, "system", error40);
    }
  } 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(body2, {
        size = 0
      } = {}) {
        let boundary = null;
        if (body2 === null) {
          body2 = null;
        } else if (isURLSearchParameters2(body2)) {
          body2 = Buffer7.from(body2.toString());
        } else if (isBlob4(body2)) {
        } else if (Buffer7.isBuffer(body2)) {
        } else if (types5.isAnyArrayBuffer(body2)) {
          body2 = Buffer7.from(body2);
        } else if (ArrayBuffer.isView(body2)) {
          body2 = Buffer7.from(body2.buffer, body2.byteOffset, body2.byteLength);
        } else if (body2 instanceof Stream7) {
        } else if (body2 instanceof FormData2) {
          body2 = formDataToBlob(body2);
          boundary = body2.type.split("=")[1];
        } else {
          body2 = Buffer7.from(String(body2));
        }
        let stream5 = body2;
        if (Buffer7.isBuffer(body2)) {
          stream5 = Stream7.Readable.from(body2);
        } else if (isBlob4(body2)) {
          stream5 = Stream7.Readable.from(body2.stream());
        }
        this[INTERNALS4] = {
          body: body2,
          stream: stream5,
          boundary,
          disturbed: false,
          error: null
        };
        this.size = size;
        if (body2 instanceof Stream7) {
          body2.on("error", (error_) => {
            const error40 = error_ instanceof FetchBaseError2 ? error_ : new FetchError3(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
            this[INTERNALS4].error = error40;
          });
        }
      }
      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 [name4, value] of parameters) {
            formData.append(name4, value);
          }
          return formData;
        }
        const { toFormData: toFormData5 } = await Promise.resolve().then(() => (init_multipart_parser2(), multipart_parser_exports2));
        return toFormData5(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((instance2, highWaterMark) => {
      let p1;
      let p2;
      let { body: body2 } = instance2[INTERNALS4];
      if (instance2.bodyUsed) {
        throw new Error("cannot clone body after it is used");
      }
      if (body2 instanceof Stream7 && typeof body2.getBoundary !== "function") {
        p1 = new PassThrough6({ highWaterMark });
        p2 = new PassThrough6({ highWaterMark });
        body2.pipe(p1);
        body2.pipe(p2);
        instance2[INTERNALS4].stream = p1;
        body2 = p2;
      }
      return body2;
    }, "clone");
    getNonSpecFormDataBoundary2 = deprecate4(
      (body2) => body2.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((body2, request4) => {
      if (body2 === null) {
        return null;
      }
      if (typeof body2 === "string") {
        return "text/plain;charset=UTF-8";
      }
      if (isURLSearchParameters2(body2)) {
        return "application/x-www-form-urlencoded;charset=UTF-8";
      }
      if (isBlob4(body2)) {
        return body2.type || null;
      }
      if (Buffer7.isBuffer(body2) || types5.isAnyArrayBuffer(body2) || ArrayBuffer.isView(body2)) {
        return null;
      }
      if (body2 instanceof FormData2) {
        return `multipart/form-data; boundary=${request4[INTERNALS4].boundary}`;
      }
      if (body2 && typeof body2.getBoundary === "function") {
        return `multipart/form-data;boundary=${getNonSpecFormDataBoundary2(body2)}`;
      }
      if (body2 instanceof Stream7) {
        return null;
      }
      return "text/plain;charset=UTF-8";
    }, "extractContentType");
    getTotalBytes2 = /* @__PURE__ */ __name((request4) => {
      const { body: body2 } = request4[INTERNALS4];
      if (body2 === null) {
        return 0;
      }
      if (isBlob4(body2)) {
        return body2.size;
      }
      if (Buffer7.isBuffer(body2)) {
        return body2.length;
      }
      if (body2 && typeof body2.getLengthSync === "function") {
        return body2.hasKnownLength && body2.hasKnownLength() ? body2.getLengthSync() : null;
      }
      return null;
    }, "getTotalBytes");
    writeToStream2 = /* @__PURE__ */ __name(async (dest, { body: body2 }) => {
      if (body2 === null) {
        dest.end();
      } else {
        await pipeline2(body2, dest);
      }
    }, "writeToStream");
  }
});

// packages/cli/node_modules/node-fetch/src/headers.js
import { types as types6 } from "node:util";
import http7 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(([name4, value]) => {
      try {
        validateHeaderName2(name4);
        validateHeaderValue2(name4, 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 http7.validateHeaderName === "function" ? http7.validateHeaderName : (name4) => {
      if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name4)) {
        const error40 = new TypeError(`Header name must be a valid HTTP token [${name4}]`);
        Object.defineProperty(error40, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
        throw error40;
      }
    };
    validateHeaderValue2 = typeof http7.validateHeaderValue === "function" ? http7.validateHeaderValue : (name4, value) => {
      if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
        const error40 = new TypeError(`Invalid character in header content ["${name4}"]`);
        Object.defineProperty(error40, "code", { value: "ERR_INVALID_CHAR" });
        throw error40;
      }
    };
    Headers5 = class _Headers extends URLSearchParams {
      static {
        __name(this, "Headers");
      }
      /**
       * Headers class
       *
       * @constructor
       * @param {HeadersInit} [init] - Response headers
       */
      constructor(init2) {
        let result = [];
        if (init2 instanceof _Headers) {
          const raw2 = init2.raw();
          for (const [name4, values] of Object.entries(raw2)) {
            result.push(...values.map((value) => [name4, value]));
          }
        } else if (init2 == null) {
        } else if (typeof init2 === "object" && !types6.isBoxedPrimitive(init2)) {
          const method = init2[Symbol.iterator];
          if (method == null) {
            result.push(...Object.entries(init2));
          } else {
            if (typeof method !== "function") {
              throw new TypeError("Header pairs must be iterable");
            }
            result = [...init2].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(([name4, value]) => {
          validateHeaderName2(name4);
          validateHeaderValue2(name4, String(value));
          return [String(name4).toLowerCase(), String(value)];
        }) : void 0;
        super(result);
        return new Proxy(this, {
          get(target, p2, receiver) {
            switch (p2) {
              case "append":
              case "set":
                return (name4, value) => {
                  validateHeaderName2(name4);
                  validateHeaderValue2(name4, String(value));
                  return URLSearchParams.prototype[p2].call(
                    target,
                    String(name4).toLowerCase(),
                    String(value)
                  );
                };
              case "delete":
              case "has":
              case "getAll":
                return (name4) => {
                  validateHeaderName2(name4);
                  return URLSearchParams.prototype[p2].call(
                    target,
                    String(name4).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(name4) {
        const values = this.getAll(name4);
        if (values.length === 0) {
          return null;
        }
        let value = values.join(", ");
        if (/^content-encoding$/i.test(name4)) {
          value = value.toLowerCase();
        }
        return value;
      }
      forEach(callback, thisArg = void 0) {
        for (const name4 of this.keys()) {
          Reflect.apply(callback, thisArg, [this.get(name4), name4, this]);
        }
      }
      *values() {
        for (const name4 of this.keys()) {
          yield this.get(name4);
        }
      }
      /**
       * @type {() => IterableIterator<[string, string]>}
       */
      *entries() {
        for (const name4 of this.keys()) {
          yield [name4, this.get(name4)];
        }
      }
      [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(body2 = null, options2 = {}) {
        super(body2, options2);
        const status = options2.status != null ? options2.status : 200;
        const headers = new Headers5(options2.headers);
        if (body2 !== null && !headers.has("Content-Type")) {
          const contentType = extractContentType2(body2, 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(url3, 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(url3).toString()
          },
          status
        });
      }
      static error() {
        const response = new _Response(null, { status: 0, statusText: "" });
        response[INTERNALS5].type = "error";
        return response;
      }
      static json(data = void 0, init2 = {}) {
        const body2 = JSON.stringify(data);
        if (body2 === void 0) {
          throw new TypeError("data is not JSON serializable");
        }
        const headers = new Headers5(init2 && init2.headers);
        if (!headers.has("content-type")) {
          headers.set("content-type", "application/json");
        }
        return new _Response(body2, {
          ...init2,
          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 isIP3 } from "node:net";
function stripURLForUseAsAReferrer2(url3, originOnly = false) {
  if (url3 == null) {
    return "no-referrer";
  }
  url3 = new URL(url3);
  if (/^(about|blob|data):$/.test(url3.protocol)) {
    return "no-referrer";
  }
  url3.username = "";
  url3.password = "";
  url3.hash = "";
  if (originOnly) {
    url3.pathname = "";
    url3.search = "";
  }
  return url3;
}
function validateReferrerPolicy2(referrerPolicy) {
  if (!ReferrerPolicy2.has(referrerPolicy)) {
    throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
  }
  return referrerPolicy;
}
function isOriginPotentiallyTrustworthy2(url3) {
  if (/^(http|ws)s:$/.test(url3.protocol)) {
    return true;
  }
  const hostIp = url3.host.replace(/(^\[)|(]$)/g, "");
  const hostIPVersion = isIP3(hostIp);
  if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
    return true;
  }
  if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
    return true;
  }
  if (url3.host === "localhost" || url3.host.endsWith(".localhost")) {
    return false;
  }
  if (url3.protocol === "file:") {
    return true;
  }
  return false;
}
function isUrlPotentiallyTrustworthy2(url3) {
  if (/^about:(blank|srcdoc)$/.test(url3)) {
    return true;
  }
  if (url3.protocol === "data:") {
    return true;
  }
  if (/^(blob|filesystem):$/.test(url3.protocol)) {
    return true;
  }
  return isOriginPotentiallyTrustworthy2(url3);
}
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, isRequest3, 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");
    isRequest3 = /* @__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, init2 = {}) {
        let parsedURL;
        if (isRequest3(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 = init2.method || input.method || "GET";
        if (/^(delete|get|head|options|post|put)$/i.test(method)) {
          method = method.toUpperCase();
        }
        if (!isRequest3(init2) && "data" in init2) {
          doBadDataWarn2();
        }
        if ((init2.body != null || isRequest3(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body");
        }
        const inputBody = init2.body ? init2.body : isRequest3(input) && input.body !== null ? clone3(input) : null;
        super(inputBody, {
          size: init2.size || input.size || 0
        });
        const headers = new Headers5(init2.headers || input.headers || {});
        if (inputBody !== null && !headers.has("Content-Type")) {
          const contentType = extractContentType2(inputBody, this);
          if (contentType) {
            headers.set("Content-Type", contentType);
          }
        }
        let signal = isRequest3(input) ? input.signal : null;
        if ("signal" in init2) {
          signal = init2.signal;
        }
        if (signal != null && !isAbortSignal2(signal)) {
          throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");
        }
        let referrer = init2.referrer == null ? input.referrer : init2.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: init2.redirect || input.redirect || "follow",
          headers,
          parsedURL,
          signal,
          referrer
        };
        this.follow = init2.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init2.follow;
        this.compress = init2.compress === void 0 ? input.compress === void 0 ? true : input.compress : init2.compress;
        this.counter = init2.counter || input.counter || 0;
        this.agent = init2.agent || input.agent;
        this.highWaterMark = init2.highWaterMark || input.highWaterMark || 16384;
        this.insecureHTTPParser = init2.insecureHTTPParser || input.insecureHTTPParser || false;
        this.referrerPolicy = init2.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 http8 from "node:http";
import https8 from "node:https";
import zlib4 from "node:zlib";
import Stream8, { PassThrough as PassThrough7, pipeline as pump2 } from "node:stream";
import { Buffer as Buffer8 } from "node:buffer";
async function fetch4(url3, options_) {
  return new Promise((resolve42, reject) => {
    const request4 = new Request5(url3, options_);
    const { parsedURL, options: options2 } = getNodeRequestOptions2(request4);
    if (!supportedSchemas2.has(parsedURL.protocol)) {
      throw new TypeError(`node-fetch cannot load ${url3}. 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 } });
      resolve42(response2);
      return;
    }
    const send = (parsedURL.protocol === "https:" ? https8 : http8).request;
    const { signal } = request4;
    let response = null;
    const abort2 = /* @__PURE__ */ __name(() => {
      const error40 = new AbortError3("The operation was aborted.");
      reject(error40);
      if (request4.body && request4.body instanceof Stream8.Readable) {
        request4.body.destroy(error40);
      }
      if (!response || !response.body) {
        return;
      }
      response.body.emit("error", error40);
    }, "abort");
    if (signal && signal.aborted) {
      abort2();
      return;
    }
    const abortAndFinalize = /* @__PURE__ */ __name(() => {
      abort2();
      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", (error40) => {
      reject(new FetchError3(`request to ${request4.url} failed, reason: ${error40.message}`, "system", error40));
      finalize();
    });
    fixResponseChunkedTransferBadEnding2(request_, (error40) => {
      if (response && response.body) {
        response.body.destroy(error40);
      }
    });
    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 error40 = new Error("Premature close");
            error40.code = "ERR_STREAM_PREMATURE_CLOSE";
            response.body.emit("error", error40);
          }
        });
      });
    }
    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 name4 of ["authorization", "www-authenticate", "cookie", "cookie2"]) {
                requestOptions.headers.delete(name4);
              }
            }
            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;
            }
            resolve42(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 body2 = pump2(response_, new PassThrough7(), (error40) => {
        if (error40) {
          reject(error40);
        }
      });
      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(body2, responseOptions);
        resolve42(response);
        return;
      }
      const zlibOptions2 = {
        flush: zlib4.Z_SYNC_FLUSH,
        finishFlush: zlib4.Z_SYNC_FLUSH
      };
      if (codings === "gzip" || codings === "x-gzip") {
        body2 = pump2(body2, zlib4.createGunzip(zlibOptions2), (error40) => {
          if (error40) {
            reject(error40);
          }
        });
        response = new Response5(body2, responseOptions);
        resolve42(response);
        return;
      }
      if (codings === "deflate" || codings === "x-deflate") {
        const raw2 = pump2(response_, new PassThrough7(), (error40) => {
          if (error40) {
            reject(error40);
          }
        });
        raw2.once("data", (chunk) => {
          if ((chunk[0] & 15) === 8) {
            body2 = pump2(body2, zlib4.createInflate(), (error40) => {
              if (error40) {
                reject(error40);
              }
            });
          } else {
            body2 = pump2(body2, zlib4.createInflateRaw(), (error40) => {
              if (error40) {
                reject(error40);
              }
            });
          }
          response = new Response5(body2, responseOptions);
          resolve42(response);
        });
        raw2.once("end", () => {
          if (!response) {
            response = new Response5(body2, responseOptions);
            resolve42(response);
          }
        });
        return;
      }
      if (codings === "br") {
        body2 = pump2(body2, zlib4.createBrotliDecompress(), (error40) => {
          if (error40) {
            reject(error40);
          }
        });
        response = new Response5(body2, responseOptions);
        resolve42(response);
        return;
      }
      response = new Response5(body2, responseOptions);
      resolve42(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 error40 = new Error("Premature close");
        error40.code = "ERR_STREAM_PREMATURE_CLOSE";
        errorCallback(error40);
      }
    }, "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 randomUUID21 = /* @__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(defaults4) {
        this.defaults = defaults4 || {};
        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(...args2) {
        const input = args2[0];
        const init2 = args2[1];
        let url3 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url3 = new URL(input);
        } else if (input instanceof URL) {
          url3 = input;
        } else if (input && input.url) {
          url3 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          _a7.mergeHeaders(headers, input.headers);
        }
        if (init2) {
          _a7.mergeHeaders(headers, new Headers(init2.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init2, ...input, headers, url: url3 });
        } else {
          return this.request({ ...init2, headers, url: url3 });
        }
      }
      /**
       * 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 err2;
          if (e4 instanceof common_js_1.GaxiosError) {
            err2 = e4;
          } else if (e4 instanceof Error) {
            err2 = new common_js_1.GaxiosError(e4.message, opts, void 0, e4);
          } else {
            err2 = new common_js_1.GaxiosError("Unexpected Gaxios Error", opts, void 0, e4);
          }
          const { shouldRetry, config: config2 } = await (0, retry_js_1.getRetryConfig)(err2);
          if (shouldRetry && config2) {
            err2.config.retryConfig.currentRetryAttempt = config2.retryConfig.currentRetryAttempt;
            opts.retryConfig = err2.config?.retryConfig;
            this.#appendTimeoutToSignal(opts);
            return this._request(opts);
          }
          if (opts.errorRedactor) {
            opts.errorRedactor(err2);
          }
          throw err2;
        }
      }
      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(url3, noProxy = []) {
        const candidate = new URL(url3);
        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 url3 = opts.url instanceof URL ? opts.url : new URL(opts.url);
            for (const [key, value] of new URLSearchParams(opts.params)) {
              url3.searchParams.append(key, value);
            }
            opts.url = url3;
          }
        }
        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 randomUUID21();
          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 proxy2 = opts.proxy || process?.env?.HTTPS_PROXY || process?.env?.https_proxy || process?.env?.HTTP_PROXY || process?.env?.http_proxy;
        if (opts.agent) {
        } else if (proxy2 && this.#urlMayUseProxy(opts.url, opts.noProxy)) {
          const HttpsProxyAgent3 = await _a7.#getProxyAgent();
          if (this.agentCache.has(proxy2)) {
            opts.agent = this.agentCache.get(proxy2);
          } else {
            opts.agent = new HttpsProxyAgent3(proxy2, {
              cert: opts.cert,
              key: opts.key
            });
            this.agentCache.set(proxy2, 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_dist3()))).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, ...append3) {
        base = base instanceof Headers ? base : new Headers(base);
        for (const headers of append3) {
          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(stream5) {
        return stream5 && // May happen in browsers.
        stream5.isTTY && (typeof stream5.getColorDepth === "function" ? stream5.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), i4 = 0; i4 < k2.length; i4++) if (k2[i4] !== "default") __createBinding(result, mod2, k2[i4]);
        }
        __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 process51 = __importStar(__require("process"));
    var util5 = __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 = (...args2) => this.invokeSeverity(LogSeverity.DEBUG, ...args2);
        this.func.info = (...args2) => this.invokeSeverity(LogSeverity.INFO, ...args2);
        this.func.warn = (...args2) => this.invokeSeverity(LogSeverity.WARNING, ...args2);
        this.func.error = (...args2) => this.invokeSeverity(LogSeverity.ERROR, ...args2);
        this.func.sublog = (namespace2) => log(namespace2, this.func);
      }
      invoke(fields, ...args2) {
        if (this.upstream) {
          try {
            this.upstream(fields, ...args2);
          } catch (e4) {
          }
        }
        try {
          this.emit("log", fields, args2);
        } catch (e4) {
        }
      }
      invokeSeverity(severity, ...args2) {
        this.invoke({ severity }, ...args2);
      }
    };
    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 = process51.env[exports2.env.nodeEnables]) !== null && _a7 !== void 0 ? _a7 : "*";
        if (nodeFlag === "all") {
          nodeFlag = "*";
        }
        this.filters = nodeFlag.split(",");
      }
      log(namespace, fields, ...args2) {
        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, ...args2);
        } 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, ...args2) => {
          var _a7;
          const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`;
          const pid = `${colours_1.Colours.yellow}${process51.pid}${colours_1.Colours.reset}`;
          let level;
          switch (fields.severity) {
            case LogSeverity.ERROR:
              level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`;
              break;
            case LogSeverity.INFO:
              level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`;
              break;
            case LogSeverity.WARNING:
              level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`;
              break;
            default:
              level = (_a7 = fields.severity) !== null && _a7 !== void 0 ? _a7 : LogSeverity.DEFAULT;
              break;
          }
          const msg = util5.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args2);
          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 debugLogger174 = this.debugPkg(namespace);
        return (fields, ...args2) => {
          debugLogger174(args2[0], ...args2.slice(1));
        };
      }
      setFilters() {
        var _a7;
        const existingFilters = (_a7 = process51.env["NODE_DEBUG"]) !== null && _a7 !== void 0 ? _a7 : "";
        process51.env["NODE_DEBUG"] = `${existingFilters}${existingFilters ? "," : ""}${this.filters.join(",")}`;
      }
    };
    function getDebugBackend(debugPkg) {
      return new DebugBackend(debugPkg);
    }
    __name(getDebugBackend, "getDebugBackend");
    var StructuredBackend = class extends DebugLogBackendBase {
      static {
        __name(this, "StructuredBackend");
      }
      constructor(upstream) {
        var _a7;
        super();
        this.upstream = (_a7 = upstream) !== null && _a7 !== void 0 ? _a7 : void 0;
      }
      makeLogger(namespace) {
        var _a7;
        const debugLogger174 = (_a7 = this.upstream) === null || _a7 === void 0 ? void 0 : _a7.makeLogger(namespace);
        return (fields, ...args2) => {
          var _a8;
          const severity = (_a8 = fields.severity) !== null && _a8 !== void 0 ? _a8 : LogSeverity.INFO;
          const json3 = Object.assign({
            severity,
            message: util5.format(...args2)
          }, fields);
          const jsonString = JSON.stringify(json3);
          if (debugLogger174) {
            debugLogger174(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 = process51.env[exports2.env.nodeEnables];
        if (!enablesFlag) {
          return exports2.placeholder;
        }
      }
      if (!namespace) {
        return exports2.placeholder;
      }
      if (parent) {
        namespace = `${parent.instance.namespace}:${namespace}`;
      }
      const existing = loggerCache.get(namespace);
      if (existing) {
        return existing.func;
      }
      if (cachedBackend === null) {
        return exports2.placeholder;
      } else if (cachedBackend === void 0) {
        cachedBackend = getNodeBackend();
      }
      const logger6 = (() => {
        let previousBackend = void 0;
        const newLogger = new AdhocDebugLogger(namespace, (fields, ...args2) => {
          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, ...args2);
        });
        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), i4 = 0; i4 < k2.length; i4++) if (k2[i4] !== "default") __createBinding(result, mod2, k2[i4]);
        }
        __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 = instance2;
    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 instance2(options2) {
      return metadataAccessor("instance", options2);
    }
    __name(instance2, "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 err2 = e4;
        if (process.env.DEBUG_AUTH) {
          console.info(err2);
        }
        if (err2.type === "request-timeout") {
          return false;
        }
        if (err2.response && err2.response.status === 404) {
          return false;
        } else {
          if (!(err2.response && err2.response.status === 404) && // A warning is emitted if we see an unexpected err.code, or err.code
          // is not populated:
          (!err2.code || ![
            "EHOSTDOWN",
            "EHOSTUNREACH",
            "ENETUNREACH",
            "ENOENT",
            "ENOTFOUND",
            "ECONNREFUSED"
          ].includes(err2.code.toString()))) {
            let code2 = "UNKNOWN";
            if (err2.code)
              code2 = err2.code.toString();
            process.emitWarning(`received unexpected error = ${err2.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 inputBuffer2 = new TextEncoder().encode(str2);
        const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer2);
        return base64js.fromByteArray(new Uint8Array(outputBuffer));
      }
      randomBytesBase64(count) {
        const array2 = new Uint8Array(count);
        window.crypto.getRandomValues(array2);
        return base64js.fromByteArray(array2);
      }
      static padBase64(base643) {
        while (base643.length % 4 !== 0) {
          base643 += "=";
        }
        return base643;
      }
      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(base643) {
        const uint8array = base64js.toByteArray(_BrowserCrypto.padBase64(base643));
        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 inputBuffer2 = new TextEncoder().encode(str2);
        const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer2);
        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 crypto18 = __require("crypto");
    var NodeCrypto = class {
      static {
        __name(this, "NodeCrypto");
      }
      async sha256DigestBase64(str2) {
        return crypto18.createHash("sha256").update(str2).digest("base64");
      }
      randomBytesBase64(count) {
        return crypto18.randomBytes(count).toString("base64");
      }
      async verify(pubkey, data, signature) {
        const verifier = crypto18.createVerify("RSA-SHA256");
        verifier.update(data);
        verifier.end();
        return verifier.verify(pubkey, signature, "base64");
      }
      async sign(privateKey, data) {
        const signer = crypto18.createSign("RSA-SHA256");
        signer.update(data);
        signer.end();
        return signer.sign(privateKey, "base64");
      }
      decodeBase64StringUtf8(base643) {
        return Buffer.from(base643, "base64").toString("utf-8");
      }
      encodeBase64StringUtf8(text) {
        return Buffer.from(text, "utf-8").toString("base64");
      }
      /**
       * Computes the SHA-256 hash of the provided string.
       * @param str The plain text string to hash.
       * @return A promise that resolves with the SHA-256 hash of the provided
       *   string in hexadecimal encoding.
       */
      async sha256DigestHex(str2) {
        return crypto18.createHash("sha256").update(str2).digest("hex");
      }
      /**
       * Computes the HMAC hash of a message using the provided crypto key and the
       * SHA-256 algorithm.
       * @param key The secret crypto key in utf-8 or ArrayBuffer format.
       * @param msg The plain text message.
       * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
       *   format.
       */
      async signWithHmacSha256(key, msg) {
        const cryptoKey = typeof key === "string" ? key : toBuffer(key);
        return toArrayBuffer(crypto18.createHmac("sha256", cryptoKey).update(msg).digest());
      }
    };
    exports2.NodeCrypto = NodeCrypto;
    function toArrayBuffer(buffer) {
      return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
    }
    __name(toArrayBuffer, "toArrayBuffer");
    function toBuffer(arrayBuffer) {
      return Buffer.from(arrayBuffer);
    }
    __name(toBuffer, "toBuffer");
  }
});

// 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 fs142 = __require("fs");
    var os59 = __require("os");
    var path150 = __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 fs142.promises.lstat(filePath);
        return stats.isFile();
      } catch (e4) {
        return false;
      }
    }
    __name(isValidFile, "isValidFile");
    function getWellKnownCertificateConfigFileLocation() {
      const configDir = process.env.CLOUDSDK_CONFIG || (_isWindows() ? path150.join(process.env.APPDATA || "", CLOUDSDK_CONFIG_DIRECTORY) : path150.join(process.env.HOME || "", ".config", CLOUDSDK_CONFIG_DIRECTORY));
      return path150.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);
    }
    __name(getWellKnownCertificateConfigFileLocation, "getWellKnownCertificateConfigFileLocation");
    function _isWindows() {
      return os59.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(...args2) {
        const input = args2[0];
        const init2 = args2[1];
        let url3 = void 0;
        const headers = new Headers();
        if (typeof input === "string") {
          url3 = new URL(input);
        } else if (input instanceof URL) {
          url3 = input;
        } else if (input && input.url) {
          url3 = new URL(input.url);
        }
        if (input && typeof input === "object" && "headers" in input) {
          gaxios_1.Gaxios.mergeHeaders(headers, input.headers);
        }
        if (init2) {
          gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init2.headers));
        }
        if (typeof input === "object" && !(input instanceof URL)) {
          return this.request({ ...init2, ...input, headers, url: url3 });
        } else {
          return this.request({ ...init2, headers, url: url3 });
        }
      }
      /**
       * 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 (error40) => {
          try {
            const symbols = error40.config;
            const methodName = symbols[_AuthClient.RequestMethodNameSymbol];
            const logId = symbols[_AuthClient.RequestLogIdSymbol];
            if (methodName) {
              _AuthClient.log.info("%s [%s] error %j", methodName, logId, error40.response?.data);
            } else {
              _AuthClient.log.error("[%s] error %j", logId, error40.response?.data);
            }
          } catch (e4) {
          }
          throw error40;
        }, "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(env6, pay) {
        this.envelope = env6;
        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 stream5 = __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 crypto18 = (0, crypto_1.createCrypto)();
        const randomString2 = crypto18.randomBytesBase64(96);
        const codeVerifier = randomString2.replace(/\+/g, "~").replace(/=/g, "_").replace(/\//g, "-");
        const unencodedCodeChallenge = await crypto18.sha256DigestBase64(codeVerifier);
        const codeChallenge = unencodedCodeChallenge.split("=")[0].replace(/\+/g, "-").replace(/\//g, "_");
        return { codeVerifier, codeChallenge };
      }
      getToken(codeOrOptions, callback) {
        const options2 = typeof codeOrOptions === "string" ? { code: codeOrOptions } : codeOrOptions;
        if (callback) {
          this.getTokenAsync(options2).then((r5) => callback(null, r5.tokens, r5.res), (e4) => callback(e4, null, e4.response));
        } else {
          return this.getTokenAsync(options2);
        }
      }
      async getTokenAsync(options2) {
        const url3 = 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: url3,
          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 url3 = 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: url3,
            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(url3) {
        const headers = (await this.getRequestMetadataAsync(url3)).headers;
        return headers;
      }
      async getRequestMetadataAsync(url3) {
        url3;
        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 (err2) {
          const e4 = err2;
          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 url3 = new URL(this.endpoints.oauth2RevokeUrl);
        url3.searchParams.append("token", token2);
        return url3;
      }
      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 isReadableStream2 = res.config.data instanceof stream5.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream2 && mayRequireRefresh) {
              await this.refreshAccessTokenAsync();
              return this.requestAsync(opts, true);
            } else if (!reAuthRetried && isAuthErr && !isReadableStream2 && 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 info2 = Object.assign({
          expiry_date: (/* @__PURE__ */ new Date()).getTime() + data.expires_in * 1e3,
          scopes: data.scope.split(" ")
        }, data);
        delete info2.expires_in;
        delete info2.scope;
        return info2;
      }
      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 url3;
        switch (format4) {
          case CertificateFormat.PEM:
            url3 = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();
            break;
          case CertificateFormat.JWK:
            url3 = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();
            break;
          default:
            throw new Error(`Unsupported certificate format ${format4}`);
        }
        try {
          const opts = {
            ..._OAuth2Client.RETRY_CONFIG,
            url: url3
          };
          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 url3 = this.endpoints.oauth2IapPublicKeyUrl.toString();
        try {
          const opts = {
            ..._OAuth2Client.RETRY_CONFIG,
            url: url3
          };
          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(jwt2, certs, requiredAudience, issuers, maxExpiry) {
        const crypto18 = (0, crypto_1.createCrypto)();
        if (!maxExpiry) {
          maxExpiry = _OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;
        }
        const segments = jwt2.split(".");
        if (segments.length !== 3) {
          throw new Error("Wrong number of segments in token: " + jwt2);
        }
        const signed = segments[0] + "." + segments[1];
        let signature = segments[2];
        let envelope;
        let payload;
        try {
          envelope = JSON.parse(crypto18.decodeBase64StringUtf8(segments[0]));
        } catch (err2) {
          if (err2 instanceof Error) {
            err2.message = `Can't parse token envelope: ${segments[0]}': ${err2.message}`;
          }
          throw err2;
        }
        if (!envelope) {
          throw new Error("Can't parse token envelope: " + segments[0]);
        }
        try {
          payload = JSON.parse(crypto18.decodeBase64StringUtf8(segments[1]));
        } catch (err2) {
          if (err2 instanceof Error) {
            err2.message = `Can't parse token payload '${segments[0]}`;
          }
          throw err2;
        }
        if (!payload) {
          throw new Error("Can't parse token payload: " + segments[1]);
        }
        if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {
          throw new Error("No pem found for envelope: " + JSON.stringify(envelope));
        }
        const cert = certs[envelope.kid];
        if (envelope.alg === "ES256") {
          signature = formatEcdsa.joseToDer(signature, "ES256").toString("base64");
        }
        const verified = await crypto18.verify(cert, signed, signature);
        if (!verified) {
          throw new Error("Invalid token signature: " + jwt2);
        }
        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 env6 = GCPEnv.NONE;
      if (isAppEngine()) {
        env6 = GCPEnv.APP_ENGINE;
      } else if (isCloudFunction()) {
        env6 = GCPEnv.CLOUD_FUNCTIONS;
      } else if (await isComputeEngine()) {
        if (await isKubernetesEngine()) {
          env6 = GCPEnv.KUBERNETES_ENGINE;
        } else if (isCloudRun()) {
          env6 = GCPEnv.CLOUD_RUN;
        } else if (isCloudRunJob()) {
          env6 = GCPEnv.CLOUD_RUN_JOBS;
        } else {
          env6 = GCPEnv.COMPUTE_ENGINE;
        }
      } else {
        env6 = GCPEnv.NONE;
      }
      return env6;
    }
    __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 fs142 = _interopRequireWildcard(__require("fs"));
    var _gaxios = require_src40();
    var jws = _interopRequireWildcard(require_jws());
    var path150 = _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, i4, 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) && ((i4 = (o3 = Object.defineProperty) && Object.getOwnPropertyDescriptor(e5, _t3)) && (i4.get || i4.set) ? o3(f5, _t3, i4) : 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 i4 = _toPrimitive2(t5, "string");
      return "symbol" == _typeof2(i4) ? i4 : i4 + "";
    }
    __name(_toPropertyKey2, "_toPropertyKey");
    function _toPrimitive2(t5, r5) {
      if ("object" != _typeof2(t5) || !t5) return t5;
      var e4 = t5[Symbol.toPrimitive];
      if (void 0 !== e4) {
        var i4 = e4.call(t5, r5 || "default");
        if ("object" != _typeof2(i4)) return i4;
        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 i4(r6, n4, o4, i5) {
        var c5 = n4 && n4.prototype instanceof Generator ? n4 : Generator, u3 = Object.create(c5.prototype);
        return _regeneratorDefine2(u3, "_invoke", function(r7, n5, o5) {
          var i6, c6, u4, f6 = 0, p2 = o5 || [], y2 = false, G3 = { p: 0, n: 0, v: e4, a: d2, f: d2.bind(e4, 4), d: /* @__PURE__ */ __name(function d3(t6, r8) {
            return i6 = t6, c6 = 0, u4 = e4, G3.n = r8, a2;
          }, "d") };
          function d2(r8, n6) {
            for (c6 = r8, u4 = n6, t5 = 0; !y2 && f6 && !o6 && t5 < p2.length; t5++) {
              var o6, i7 = p2[t5], d3 = G3.p, l3 = i7[2];
              r8 > 3 ? (o6 = l3 === n6) && (u4 = i7[(c6 = i7[4]) ? 5 : (c6 = 3, 3)], i7[4] = i7[5] = e4) : i7[0] <= d3 && ((o6 = r8 < 2 && d3 < i7[1]) ? (c6 = 0, G3.v = n6, G3.n = i7[1]) : d3 < l3 && (o6 = r8 < 3 || i7[0] > n6 || n6 > l3) && (i7[4] = r8, i7[5] = n6, G3.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; ) {
              i6 || (c6 ? c6 < 3 ? (c6 > 1 && (G3.n = -1), d2(c6, u4)) : G3.n = u4 : G3.v = u4);
              try {
                if (f6 = 2, i6) {
                  if (c6 || (o6 = "next"), t5 = i6[o6]) {
                    if (!(t5 = t5.call(i6, 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 = i6["return"]) && t5.call(i6), c6 < 2 && (u4 = TypeError("The iterator does not provide a '" + o6 + "' method"), c6 = 1);
                  i6 = e4;
                } else if ((t5 = (y2 = G3.n < 0) ? u4 : r7.call(n5, G3)) !== a2) break;
              } catch (t6) {
                i6 = e4, c6 = 1, u4 = t6;
              } finally {
                f6 = 1;
              }
            }
            return { value: t5, done: y2 };
          };
        }(r6, o4, i5), true), u3;
      }
      __name(i4, "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: i4, m: f5 };
      }, "_regenerator"))();
    }
    __name(_regenerator, "_regenerator");
    function _regeneratorDefine2(e4, r5, n3, t5) {
      var i4 = Object.defineProperty;
      try {
        i4({}, "", {});
      } catch (e5) {
        i4 = 0;
      }
      _regeneratorDefine2 = /* @__PURE__ */ __name(function _regeneratorDefine(e5, r6, n4, t6) {
        if (r6) i4 ? i4(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 i4 = n3[a2](c4), u2 = i4.value;
      } catch (n4) {
        return void e4(n4);
      }
      i4.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 readFile25 = fs142.readFile ? (0, _util.promisify)(fs142.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, body2, privateKey, clientEmail, _privateKey, _t2;
            return _regenerator().w(function(_context2) {
              while (1) switch (_context2.n) {
                case 0:
                  ext2 = path150.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 readFile25(keyFile, "utf8");
                case 2:
                  key = _context2.v;
                  body2 = JSON.parse(key);
                  privateKey = body2.private_key;
                  clientEmail = body2.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 readFile25(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 url3;
        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:
              url3 = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;
              _context5.n = 2;
              return this.transporter.request({
                url: url3,
                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, body2, 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;
              body2 = _t2.response && (_response = _t2.response) !== null && _response !== void 0 && _response.data ? (_response2 = _t2.response) === null || _response2 === void 0 ? void 0 : _response2.data : {};
              if (body2.error) {
                desc2 = body2.error_description ? ": ".concat(body2.error_description) : "";
                _t2.message = "".concat(body2.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(email3, key, keyId, eagerRefreshThresholdMillis) {
        this.email = email3;
        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(url3, scopes) {
        let cacheKey = url3;
        if (scopes && Array.isArray(scopes) && scopes.length) {
          cacheKey = url3 ? `${url3}_${scopes.join("_")}` : `${scopes.join("_")}`;
        } else if (typeof scopes === "string") {
          cacheKey = url3 ? `${url3}_${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(url3, additionalClaims, scopes) {
        const key = this.getCachedKey(url3, 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: url3,
            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(json3) {
        if (!json3) {
          throw new Error("Must pass in a JSON object containing the service account auth settings.");
        }
        if (!json3.client_email) {
          throw new Error("The incoming JSON object does not contain a client_email field");
        }
        if (!json3.private_key) {
          throw new Error("The incoming JSON object does not contain a private_key field");
        }
        this.email = json3.client_email;
        this.key = json3.private_key;
        this.keyId = json3.private_key_id;
        this.projectId = json3.project_id;
      }
      fromStream(inputStream, callback) {
        if (callback) {
          this.fromStreamAsync(inputStream).then(() => callback(), callback);
        } else {
          return this.fromStreamAsync(inputStream);
        }
      }
      fromStreamAsync(inputStream) {
        return new Promise((resolve42, 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);
              resolve42();
            } catch (err2) {
              reject(err2);
            }
          });
        });
      }
    };
    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 jwt2 = new _JWT(this);
        jwt2.scopes = scopes;
        return jwt2;
      }
      /**
       * Obtains the metadata to be sent with the request.
       *
       * @param url the URI being authorized.
       */
      async getRequestMetadataAsync(url3) {
        url3 = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url3;
        const useSelfSignedJWT = !this.hasUserScopes() && url3 || 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 (!url3) {
              scopes = this.defaultScopes;
            }
            const useScopes = this.useJWTAccessWithScope || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;
            const headers = await this.access.getRequestHeaders(
              url3 ?? 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(url3);
        } 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(json3) {
        if (!json3) {
          throw new Error("Must pass in a JSON object containing the service account auth settings.");
        }
        if (!json3.client_email) {
          throw new Error("The incoming JSON object does not contain a client_email field");
        }
        if (!json3.private_key) {
          throw new Error("The incoming JSON object does not contain a private_key field");
        }
        this.email = json3.client_email;
        this.key = json3.private_key;
        this.keyId = json3.private_key_id;
        this.projectId = json3.project_id;
        this.quotaProjectId = json3.quota_project_id;
        this.universeDomain = json3.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((resolve42, 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);
              resolve42();
            } 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(json3) {
        if (!json3) {
          throw new Error("Must pass in a JSON object containing the user refresh token");
        }
        if (json3.type !== "authorized_user") {
          throw new Error('The incoming JSON object does not have the "authorized_user" type');
        }
        if (!json3.client_id) {
          throw new Error("The incoming JSON object does not contain a client_id field");
        }
        if (!json3.client_secret) {
          throw new Error("The incoming JSON object does not contain a client_secret field");
        }
        if (!json3.refresh_token) {
          throw new Error("The incoming JSON object does not contain a refresh_token field");
        }
        this._clientId = json3.client_id;
        this._clientSecret = json3.client_secret;
        this._refreshToken = json3.refresh_token;
        this.credentials.refresh_token = json3.refresh_token;
        this.quotaProjectId = json3.quota_project_id;
        this.universeDomain = json3.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((resolve42, 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 resolve42();
            } catch (err2) {
              return reject(err2);
            }
          });
        });
      }
      /**
       * Create a UserRefreshClient credentials instance using the given input
       * options.
       * @param json The input object.
       */
      static fromJSON(json3) {
        const client = new _UserRefreshClient();
        client.fromJSON(json3);
        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 name4 = `projects/-/serviceAccounts/${this.targetPrincipal}`;
        const u2 = `${this.endpoint}/v1/${name4}:signBlob`;
        const body2 = {
          delegates: this.delegates,
          payload: Buffer.from(blobToSign).toString("base64")
        };
        const res = await this.sourceClient.request({
          ..._Impersonated.RETRY_CONFIG,
          url: u2,
          data: body2,
          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 name4 = "projects/-/serviceAccounts/" + this.targetPrincipal;
          const u2 = `${this.endpoint}/v1/${name4}:generateAccessToken`;
          const body2 = {
            delegates: this.delegates,
            scope: this.targetScopes,
            lifetime: this.lifetime + "s"
          };
          const res = await this.sourceClient.request({
            ..._Impersonated.RETRY_CONFIG,
            url: u2,
            data: body2,
            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 (error40) {
          if (!(error40 instanceof Error))
            throw error40;
          let status = 0;
          let message = "";
          if (error40 instanceof gaxios_1.GaxiosError) {
            status = error40?.response?.data?.error?.status;
            message = error40?.response?.data?.error?.message;
          }
          if (status && message) {
            error40.message = `${status}: unable to impersonate: ${message}`;
            throw error40;
          } else {
            error40.message = `unable to impersonate: ${error40}`;
            throw error40;
          }
        }
      }
      /**
       * 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 name4 = `projects/-/serviceAccounts/${this.targetPrincipal}`;
        const u2 = `${this.endpoint}/v1/${name4}:generateIdToken`;
        const body2 = {
          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: body2,
          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, err2) {
      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 (err2) {
        const keys = Object.keys(err2);
        if (err2.stack) {
          keys.push("stack");
        }
        keys.forEach((key) => {
          if (key !== "message") {
            Object.defineProperty(newError, key, {
              value: err2[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 (error40) {
          if (error40 instanceof gaxios_1.GaxiosError && error40.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error40.response.data,
              // Preserve other fields from the original error.
              error40
            );
          }
          throw error40;
        }
      }
    };
    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 stream5 = __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 isReadableStream2 = res.config.data instanceof stream5.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream2 && 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 fs142 = __require("fs");
    var readFile25 = (0, util_1.promisify)(fs142.readFile ?? (() => {
    }));
    var realpath3 = (0, util_1.promisify)(fs142.realpath ?? (() => {
    }));
    var lstat6 = (0, util_1.promisify)(fs142.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 (err2) {
          if (err2 instanceof Error) {
            err2.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err2.message}`;
          }
          throw err2;
        }
        let subjectToken;
        const rawText = await readFile25(parsedFilePath, { encoding: "utf8" });
        if (this.formatType === "text") {
          subjectToken = rawText;
        } else if (this.formatType === "json" && this.subjectTokenFieldName) {
          const json3 = JSON.parse(rawText);
          subjectToken = json3[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 fs142 = __require("fs");
    var crypto_1 = __require("crypto");
    var https9 = __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 https9.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 fs142.promises.readFile(configPath, "utf8");
        } catch (err2) {
          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 fs142.promises.readFile(certPath);
          new crypto_1.X509Certificate(cert);
        } catch (err2) {
          const message = err2 instanceof Error ? err2.message : String(err2);
          throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`);
        }
        try {
          key = await fs142.promises.readFile(keyPath);
          (0, crypto_1.createPrivateKey)(key);
        } catch (err2) {
          const message = err2 instanceof Error ? err2.message : String(err2);
          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 fs142.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 (err2) {
              const message = err2 instanceof Error ? err2.message : String(err2);
              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 (err2) {
          if (err2 instanceof InvalidConfigurationError)
            throw err2;
          const message = err2 instanceof Error ? err2.message : String(err2);
          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 file2 = credentialSourceOpts.get("file");
          const url3 = credentialSourceOpts.get("url");
          const certificate = credentialSourceOpts.get("certificate");
          const headers = credentialSourceOpts.get("headers");
          if (file2 && url3 || url3 && certificate || file2 && certificate) {
            throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');
          } else if (file2) {
            this.credentialSourceType = "file";
            this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({
              filePath: file2,
              formatType,
              subjectTokenFieldName: formatSubjectTokenFieldName
            });
          } else if (url3) {
            this.credentialSourceType = "url";
            this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({
              url: url3,
              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 url3 = 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(url3);
        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: url3,
          method,
          headers
        };
        if (requestPayload !== void 0) {
          awsSignedReq.body = requestPayload;
        }
        return awsSignedReq;
      }
    };
    exports2.AwsRequestSigner = AwsRequestSigner;
    async function sign(crypto18, key, msg) {
      return await crypto18.signWithHmacSha256(key, msg);
    }
    __name(sign, "sign");
    async function getSigningKey(crypto18, key, dateStamp, region, serviceName) {
      const kDate = await sign(crypto18, `AWS4${key}`, dateStamp);
      const kRegion = await sign(crypto18, kDate, region);
      const kService = await sign(crypto18, kRegion, serviceName);
      const kSigning = await sign(crypto18, kService, "aws4_request");
      return kSigning;
    }
    __name(getSigningKey, "getSigningKey");
    async function generateAuthenticationHeaderMap(options2) {
      const additionalAmzHeaders = 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 fs142 = __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((resolve42, 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", (err2) => {
            output += err2;
          });
          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 resolve42(response);
              } catch (error40) {
                if (error40 instanceof executable_response_1.ExecutableResponseError) {
                  return reject(error40);
                }
                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 fs142.promises.realpath(this.outputFile);
        } catch {
          return void 0;
        }
        if (!(await fs142.promises.lstat(filePath)).isFile()) {
          return void 0;
        }
        const responseString = await fs142.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 (error40) {
          if (error40 instanceof executable_response_1.ExecutableResponseError) {
            throw error40;
          }
          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 i4 = 0; i4 < components.length; i4++) {
          if (components[i4][0] === '"' && components[i4].slice(-1) === '"') {
            components[i4] = components[i4].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 stream5 = __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 (error40) {
          if (error40 instanceof gaxios_1.GaxiosError && error40.response) {
            throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(
              error40.response.data,
              // Preserve other fields from the original error.
              error40
            );
          }
          throw error40;
        }
      }
    };
    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 isReadableStream2 = res.config.data instanceof stream5.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream2 && 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 fs142 = __require("fs");
    var gaxios_1 = require_src40();
    var gcpMetadata = require_src42();
    var os59 = __require("os");
    var path150 = __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 = path150.join(home, ".config");
          }
        }
        if (location) {
          location = path150.join(location, "gcloud", "application_default_credentials.json");
          if (!fs142.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 = fs142.realpathSync(filePath);
          if (!fs142.lstatSync(filePath).isFile()) {
            throw new Error();
          }
        } catch (err2) {
          if (err2 instanceof Error) {
            err2.message = `The file at ${filePath} does not exist, or it is not a file. ${err2.message}`;
          }
          throw err2;
        }
        const readStream2 = fs142.createReadStream(filePath);
        return this.fromStream(readStream2, 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(json3) {
        if (!json3) {
          throw new Error("Must pass in a JSON object containing an  impersonated refresh token");
        }
        if (json3.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
          throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`);
        }
        if (!json3.source_credentials) {
          throw new Error("The incoming JSON object does not contain a source_credentials field");
        }
        if (!json3.service_account_impersonation_url) {
          throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");
        }
        const sourceClient = this.fromJSON(json3.source_credentials);
        if (json3.service_account_impersonation_url?.length > 256) {
          throw new RangeError(`Target principal is too long: ${json3.service_account_impersonation_url}`);
        }
        const targetPrincipal = /(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(json3.service_account_impersonation_url)?.groups?.target;
        if (!targetPrincipal) {
          throw new RangeError(`Cannot extract target principal from ${json3.service_account_impersonation_url}`);
        }
        const targetScopes = (this.scopes || json3.scopes || this.defaultScopes) ?? [];
        return new impersonated_1.Impersonated({
          ...json3,
          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(json3, options2 = {}) {
        let client;
        const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options2).get("universe_domain");
        if (json3.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) {
          client = new refreshclient_1.UserRefreshClient(options2);
          client.fromJSON(json3);
        } else if (json3.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {
          client = this.fromImpersonatedJSON(json3);
        } else if (json3.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {
          client = externalclient_1.ExternalAccountClient.fromJSON({
            ...json3,
            ...options2
          });
          client.scopes = this.getAnyScopes();
        } else if (json3.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) {
          client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({
            ...json3,
            ...options2
          });
        } else {
          options2.scopes = this.scopes;
          client = new jwtclient_1.JWT(options2);
          this.setGapicJWTValues(client);
          client.fromJSON(json3);
        }
        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(json3, options2) {
        const client = this.fromJSON(json3, options2);
        this.jsonContent = json3;
        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((resolve42, 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 resolve42(r5);
              } catch (err2) {
                if (!this.keyFilename)
                  throw err2;
                const client = new jwtclient_1.JWT({
                  ...this.clientOptions,
                  keyFile: this.keyFilename
                });
                this.cachedCredential = client;
                this.setGapicJWTValues(client);
                return resolve42(client);
              }
            } catch (err2) {
              return reject(err2);
            }
          });
        });
      }
      /**
       * 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 = os59.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((resolve42) => {
          (0, child_process_1.exec)("gcloud config config-helper --format json", (err2, stdout2) => {
            if (!err2 && stdout2) {
              try {
                const projectId = JSON.parse(stdout2).configuration.properties.core.project;
                resolve42(projectId);
                return;
              } catch (e4) {
              }
            }
            resolve42(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 = path150.resolve(this.keyFilename);
          const stream5 = fs142.createReadStream(filePath);
          return await this.fromStreamAsync(stream5, 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(url3) {
        const client = await this.getClient();
        return client.getRequestHeaders(url3);
      }
      /**
       * 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 url3 = opts.url;
        const client = await this.getClient();
        const headers = await client.getRequestHeaders(url3);
        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(...args2) {
        const client = await this.getClient();
        return client.fetch(...args2);
      }
      /**
       * 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 crypto18 = (0, crypto_1.createCrypto)();
        if (client instanceof jwtclient_1.JWT && client.key) {
          const sign = await crypto18.sign(client.key, data);
          return sign;
        }
        const creds = await this.getCredentials();
        if (!creds.client_email) {
          throw new Error("Cannot sign data without `client_email`.");
        }
        return this.signBlob(crypto18, creds.client_email, data, endpoint);
      }
      async signBlob(crypto18, emailOrUniqueId, data, endpoint) {
        const url3 = new URL(endpoint + `${emailOrUniqueId}:signBlob`);
        const res = await this.request({
          method: "POST",
          url: url3.href,
          data: {
            payload: crypto18.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 stream5 = __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 isReadableStream2 = res.config.data instanceof stream5.Readable;
            const isAuthErr = statusCode === 401 || statusCode === 403;
            if (!reAuthRetried && isAuthErr && !isReadableStream2 && 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 constants5 = __require("constants");
    var origCwd = process.cwd;
    var cwd6 = null;
    var platform15 = process.env.GRACEFUL_FS_PLATFORM || process.platform;
    process.cwd = function() {
      if (!cwd6)
        cwd6 = origCwd.call(process);
      return cwd6;
    };
    try {
      process.cwd();
    } catch (er2) {
    }
    if (typeof process.chdir === "function") {
      chdir = process.chdir;
      process.chdir = function(d2) {
        cwd6 = null;
        chdir.call(process, d2);
      };
      if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
    }
    var chdir;
    module2.exports = patch;
    function patch(fs142) {
      if (constants5.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
        patchLchmod(fs142);
      }
      if (!fs142.lutimes) {
        patchLutimes(fs142);
      }
      fs142.chown = chownFix(fs142.chown);
      fs142.fchown = chownFix(fs142.fchown);
      fs142.lchown = chownFix(fs142.lchown);
      fs142.chmod = chmodFix(fs142.chmod);
      fs142.fchmod = chmodFix(fs142.fchmod);
      fs142.lchmod = chmodFix(fs142.lchmod);
      fs142.chownSync = chownFixSync(fs142.chownSync);
      fs142.fchownSync = chownFixSync(fs142.fchownSync);
      fs142.lchownSync = chownFixSync(fs142.lchownSync);
      fs142.chmodSync = chmodFixSync(fs142.chmodSync);
      fs142.fchmodSync = chmodFixSync(fs142.fchmodSync);
      fs142.lchmodSync = chmodFixSync(fs142.lchmodSync);
      fs142.stat = statFix(fs142.stat);
      fs142.fstat = statFix(fs142.fstat);
      fs142.lstat = statFix(fs142.lstat);
      fs142.statSync = statFixSync(fs142.statSync);
      fs142.fstatSync = statFixSync(fs142.fstatSync);
      fs142.lstatSync = statFixSync(fs142.lstatSync);
      if (fs142.chmod && !fs142.lchmod) {
        fs142.lchmod = function(path150, mode, cb) {
          if (cb) process.nextTick(cb);
        };
        fs142.lchmodSync = function() {
        };
      }
      if (fs142.chown && !fs142.lchown) {
        fs142.lchown = function(path150, uid, gid, cb) {
          if (cb) process.nextTick(cb);
        };
        fs142.lchownSync = function() {
        };
      }
      if (platform15 === "win32") {
        fs142.rename = typeof fs142.rename !== "function" ? fs142.rename : function(fs$rename) {
          function rename2(from, to, cb) {
            var start2 = 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() - start2 < 6e4) {
                setTimeout(function() {
                  fs142.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(rename2, "rename");
          if (Object.setPrototypeOf) Object.setPrototypeOf(rename2, fs$rename);
          return rename2;
        }(fs142.rename);
      }
      fs142.read = typeof fs142.read !== "function" ? fs142.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(fs142, fd, buffer, offset, length, position, callback);
              }
              callback_.apply(this, arguments);
            }, "callback");
          }
          return fs$read.call(fs142, fd, buffer, offset, length, position, callback);
        }
        __name(read3, "read");
        if (Object.setPrototypeOf) Object.setPrototypeOf(read3, fs$read);
        return read3;
      }(fs142.read);
      fs142.readSync = typeof fs142.readSync !== "function" ? fs142.readSync : /* @__PURE__ */ function(fs$readSync) {
        return function(fd, buffer, offset, length, position) {
          var eagCounter = 0;
          while (true) {
            try {
              return fs$readSync.call(fs142, fd, buffer, offset, length, position);
            } catch (er2) {
              if (er2.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                continue;
              }
              throw er2;
            }
          }
        };
      }(fs142.readSync);
      function patchLchmod(fs143) {
        fs143.lchmod = function(path150, mode, callback) {
          fs143.open(
            path150,
            constants5.O_WRONLY | constants5.O_SYMLINK,
            mode,
            function(err2, fd) {
              if (err2) {
                if (callback) callback(err2);
                return;
              }
              fs143.fchmod(fd, mode, function(err3) {
                fs143.close(fd, function(err22) {
                  if (callback) callback(err3 || err22);
                });
              });
            }
          );
        };
        fs143.lchmodSync = function(path150, mode) {
          var fd = fs143.openSync(path150, constants5.O_WRONLY | constants5.O_SYMLINK, mode);
          var threw = true;
          var ret;
          try {
            ret = fs143.fchmodSync(fd, mode);
            threw = false;
          } finally {
            if (threw) {
              try {
                fs143.closeSync(fd);
              } catch (er2) {
              }
            } else {
              fs143.closeSync(fd);
            }
          }
          return ret;
        };
      }
      __name(patchLchmod, "patchLchmod");
      function patchLutimes(fs143) {
        if (constants5.hasOwnProperty("O_SYMLINK") && fs143.futimes) {
          fs143.lutimes = function(path150, at2, mt2, cb) {
            fs143.open(path150, constants5.O_SYMLINK, function(er2, fd) {
              if (er2) {
                if (cb) cb(er2);
                return;
              }
              fs143.futimes(fd, at2, mt2, function(er3) {
                fs143.close(fd, function(er22) {
                  if (cb) cb(er3 || er22);
                });
              });
            });
          };
          fs143.lutimesSync = function(path150, at2, mt2) {
            var fd = fs143.openSync(path150, constants5.O_SYMLINK);
            var ret;
            var threw = true;
            try {
              ret = fs143.futimesSync(fd, at2, mt2);
              threw = false;
            } finally {
              if (threw) {
                try {
                  fs143.closeSync(fd);
                } catch (er2) {
                }
              } else {
                fs143.closeSync(fd);
              }
            }
            return ret;
          };
        } else if (fs143.futimes) {
          fs143.lutimes = function(_a7, _b2, _c2, cb) {
            if (cb) process.nextTick(cb);
          };
          fs143.lutimesSync = function() {
          };
        }
      }
      __name(patchLutimes, "patchLutimes");
      function chmodFix(orig) {
        if (!orig) return orig;
        return function(target, mode, cb) {
          return orig.call(fs142, 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(fs142, 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(fs142, 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(fs142, 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(fs142, target, options2, callback) : orig.call(fs142, target, callback);
        };
      }
      __name(statFix, "statFix");
      function statFixSync(orig) {
        if (!orig) return orig;
        return function(target, options2) {
          var stats = options2 ? orig.call(fs142, target, options2) : orig.call(fs142, 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(fs142) {
      return {
        ReadStream: ReadStream2,
        WriteStream: WriteStream2
      };
      function ReadStream2(path150, options2) {
        if (!(this instanceof ReadStream2)) return new ReadStream2(path150, options2);
        Stream9.call(this);
        var self2 = this;
        this.path = path150;
        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;
        }
        fs142.open(this.path, this.flags, this.mode, function(err2, fd) {
          if (err2) {
            self2.emit("error", err2);
            self2.readable = false;
            return;
          }
          self2.fd = fd;
          self2.emit("open", fd);
          self2._read();
        });
      }
      __name(ReadStream2, "ReadStream");
      function WriteStream2(path150, options2) {
        if (!(this instanceof WriteStream2)) return new WriteStream2(path150, options2);
        Stream9.call(this);
        this.path = path150;
        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 = fs142.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 getPrototypeOf2 = 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__: getPrototypeOf2(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 fs142 = __require("fs");
    var polyfills = require_polyfills();
    var legacy = require_legacy_streams();
    var clone4 = require_clone();
    var util5 = __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 noop11() {
    }
    __name(noop11, "noop");
    function publishQueue(context2, queue2) {
      Object.defineProperty(context2, gracefulQueue, {
        get: /* @__PURE__ */ __name(function() {
          return queue2;
        }, "get")
      });
    }
    __name(publishQueue, "publishQueue");
    var debug3 = noop11;
    if (util5.debuglog)
      debug3 = util5.debuglog("gfs4");
    else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
      debug3 = /* @__PURE__ */ __name(function() {
        var m3 = util5.format.apply(util5, arguments);
        m3 = "GFS4: " + m3.split(/\n/).join("\nGFS4: ");
        console.error(m3);
      }, "debug");
    if (!fs142[gracefulQueue]) {
      queue = globalThis[gracefulQueue] || [];
      publishQueue(fs142, queue);
      fs142.close = function(fs$close) {
        function close(fd, cb) {
          return fs$close.call(fs142, fd, function(err2) {
            if (!err2) {
              resetQueue();
            }
            if (typeof cb === "function")
              cb.apply(this, arguments);
          });
        }
        __name(close, "close");
        Object.defineProperty(close, previousSymbol, {
          value: fs$close
        });
        return close;
      }(fs142.close);
      fs142.closeSync = function(fs$closeSync) {
        function closeSync2(fd) {
          fs$closeSync.apply(fs142, arguments);
          resetQueue();
        }
        __name(closeSync2, "closeSync");
        Object.defineProperty(closeSync2, previousSymbol, {
          value: fs$closeSync
        });
        return closeSync2;
      }(fs142.closeSync);
      if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
        process.on("exit", function() {
          debug3(fs142[gracefulQueue]);
          __require("assert").equal(fs142[gracefulQueue].length, 0);
        });
      }
    }
    var queue;
    if (!globalThis[gracefulQueue]) {
      publishQueue(globalThis, fs142[gracefulQueue]);
    }
    module2.exports = patch(clone4(fs142));
    if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs142.__patched) {
      module2.exports = patch(fs142);
      fs142.__patched = true;
    }
    function patch(fs143) {
      polyfills(fs143);
      fs143.gracefulify = patch;
      fs143.createReadStream = createReadStream4;
      fs143.createWriteStream = createWriteStream7;
      var fs$readFile = fs143.readFile;
      fs143.readFile = readFile25;
      function readFile25(path150, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$readFile(path150, options2, cb);
        function go$readFile(path151, options3, cb2, startTime) {
          return fs$readFile(path151, options3, function(err2) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([go$readFile, [path151, options3, cb2], err2, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$readFile, "go$readFile");
      }
      __name(readFile25, "readFile");
      var fs$writeFile = fs143.writeFile;
      fs143.writeFile = writeFile24;
      function writeFile24(path150, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$writeFile(path150, data, options2, cb);
        function go$writeFile(path151, data2, options3, cb2, startTime) {
          return fs$writeFile(path151, data2, options3, function(err2) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([go$writeFile, [path151, data2, options3, cb2], err2, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$writeFile, "go$writeFile");
      }
      __name(writeFile24, "writeFile");
      var fs$appendFile = fs143.appendFile;
      if (fs$appendFile)
        fs143.appendFile = appendFile;
      function appendFile(path150, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$appendFile(path150, data, options2, cb);
        function go$appendFile(path151, data2, options3, cb2, startTime) {
          return fs$appendFile(path151, data2, options3, function(err2) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([go$appendFile, [path151, data2, options3, cb2], err2, 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 = fs143.copyFile;
      if (fs$copyFile)
        fs143.copyFile = copyFile3;
      function copyFile3(src, dest, flags2, cb) {
        if (typeof flags2 === "function") {
          cb = flags2;
          flags2 = 0;
        }
        return go$copyFile(src, dest, flags2, cb);
        function go$copyFile(src2, dest2, flags3, cb2, startTime) {
          return fs$copyFile(src2, dest2, flags3, function(err2) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([go$copyFile, [src2, dest2, flags3, cb2], err2, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$copyFile, "go$copyFile");
      }
      __name(copyFile3, "copyFile");
      var fs$readdir = fs143.readdir;
      fs143.readdir = readdir16;
      var noReaddirOptionVersions = /^v[0-5]\./;
      function readdir16(path150, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        var go$readdir = noReaddirOptionVersions.test(process.version) ? /* @__PURE__ */ __name(function go$readdir2(path151, options3, cb2, startTime) {
          return fs$readdir(path151, fs$readdirCallback(
            path151,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir") : /* @__PURE__ */ __name(function go$readdir2(path151, options3, cb2, startTime) {
          return fs$readdir(path151, options3, fs$readdirCallback(
            path151,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir");
        return go$readdir(path150, options2, cb);
        function fs$readdirCallback(path151, options3, cb2, startTime) {
          return function(err2, files) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([
                go$readdir,
                [path151, options3, cb2],
                err2,
                startTime || Date.now(),
                Date.now()
              ]);
            else {
              if (files && files.sort)
                files.sort();
              if (typeof cb2 === "function")
                cb2.call(this, err2, files);
            }
          };
        }
        __name(fs$readdirCallback, "fs$readdirCallback");
      }
      __name(readdir16, "readdir");
      if (process.version.substr(0, 4) === "v0.8") {
        var legStreams = legacy(fs143);
        ReadStream2 = legStreams.ReadStream;
        WriteStream2 = legStreams.WriteStream;
      }
      var fs$ReadStream = fs143.ReadStream;
      if (fs$ReadStream) {
        ReadStream2.prototype = Object.create(fs$ReadStream.prototype);
        ReadStream2.prototype.open = ReadStream$open;
      }
      var fs$WriteStream = fs143.WriteStream;
      if (fs$WriteStream) {
        WriteStream2.prototype = Object.create(fs$WriteStream.prototype);
        WriteStream2.prototype.open = WriteStream$open;
      }
      Object.defineProperty(fs143, "ReadStream", {
        get: /* @__PURE__ */ __name(function() {
          return ReadStream2;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          ReadStream2 = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      Object.defineProperty(fs143, "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(fs143, "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(fs143, "FileWriteStream", {
        get: /* @__PURE__ */ __name(function() {
          return FileWriteStream;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          FileWriteStream = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      function ReadStream2(path150, 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(err2, fd) {
          if (err2) {
            if (that.autoClose)
              that.destroy();
            that.emit("error", err2);
          } else {
            that.fd = fd;
            that.emit("open", fd);
            that.read();
          }
        });
      }
      __name(ReadStream$open, "ReadStream$open");
      function WriteStream2(path150, 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(err2, fd) {
          if (err2) {
            that.destroy();
            that.emit("error", err2);
          } else {
            that.fd = fd;
            that.emit("open", fd);
          }
        });
      }
      __name(WriteStream$open, "WriteStream$open");
      function createReadStream4(path150, options2) {
        return new fs143.ReadStream(path150, options2);
      }
      __name(createReadStream4, "createReadStream");
      function createWriteStream7(path150, options2) {
        return new fs143.WriteStream(path150, options2);
      }
      __name(createWriteStream7, "createWriteStream");
      var fs$open = fs143.open;
      fs143.open = open4;
      function open4(path150, flags2, mode, cb) {
        if (typeof mode === "function")
          cb = mode, mode = null;
        return go$open(path150, flags2, mode, cb);
        function go$open(path151, flags3, mode2, cb2, startTime) {
          return fs$open(path151, flags3, mode2, function(err2, fd) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([go$open, [path151, flags3, mode2, cb2], err2, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$open, "go$open");
      }
      __name(open4, "open");
      return fs143;
    }
    __name(patch, "patch");
    function enqueue(elem) {
      debug3("ENQUEUE", elem[0].name, elem[1]);
      fs142[gracefulQueue].push(elem);
      retry();
    }
    __name(enqueue, "enqueue");
    var retryTimer;
    function resetQueue() {
      var now = Date.now();
      for (var i4 = 0; i4 < fs142[gracefulQueue].length; ++i4) {
        if (fs142[gracefulQueue][i4].length > 2) {
          fs142[gracefulQueue][i4][3] = now;
          fs142[gracefulQueue][i4][4] = now;
        }
      }
      retry();
    }
    __name(resetQueue, "resetQueue");
    function retry() {
      clearTimeout(retryTimer);
      retryTimer = void 0;
      if (fs142[gracefulQueue].length === 0)
        return;
      var elem = fs142[gracefulQueue].shift();
      var fn = elem[0];
      var args2 = elem[1];
      var err2 = elem[2];
      var startTime = elem[3];
      var lastTime = elem[4];
      if (startTime === void 0) {
        debug3("RETRY", fn.name, args2);
        fn.apply(null, args2);
      } else if (Date.now() - startTime >= 6e4) {
        debug3("TIMEOUT", fn.name, args2);
        var cb = args2.pop();
        if (typeof cb === "function")
          cb.call(null, err2);
      } 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, args2);
          fn.apply(null, args2.concat([startTime]));
        } else {
          fs142[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 parse17 = require_parse9();
    var diff4 = /* @__PURE__ */ __name((version1, version2) => {
      const v1 = parse17(version1, null, true);
      const v2 = parse17(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 = encode6;
    exports2.safe = safe;
    exports2.unsafe = unsafe;
    var eol = typeof process !== "undefined" && process.platform === "win32" ? "\r\n" : "\n";
    function encode6(obj, opt) {
      var children = [];
      var out2 = "";
      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) {
            out2 += safe(k2 + "[]") + separator + safe(item) + "\n";
          });
        } else if (val && typeof val === "object")
          children.push(k2);
        else
          out2 += safe(k2) + separator + safe(val) + eol;
      });
      if (opt.section && out2.length)
        out2 = "[" + safe(opt.section) + "]" + eol + out2;
      children.forEach(function(k2, _2, __) {
        var nk = dotSplit(k2).join("\\.");
        var section = (opt.section ? opt.section + "." : "") + nk;
        var child = encode6(obj[k2], {
          section,
          whitespace: opt.whitespace
        });
        if (out2.length && child.length)
          out2 += eol;
        out2 += child;
      });
      return out2;
    }
    __name(encode6, "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 out2 = {};
      var p2 = out2;
      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 = out2[section] = out2[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(out2).filter(function(k2, _2, __) {
        if (!out2[k2] || typeof out2[k2] !== "object" || Array.isArray(out2[k2]))
          return false;
        var parts2 = dotSplit(k2);
        var p3 = out2;
        var l3 = parts2.pop();
        var nl2 = l3.replace(/\\\./g, ".");
        parts2.forEach(function(part, _3, __2) {
          if (part === "__proto__")
            return;
          if (!p3[part] || typeof p3[part] !== "object")
            p3[part] = {};
          p3 = p3[part];
        });
        if (p3 === out2 && nl2 === l3)
          return false;
        p3[nl2] = out2[k2];
        return true;
      }).forEach(function(del, _2, __) {
        delete out2[del];
      });
      return out2;
    }
    __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 i4 = 0, l3 = val.length; i4 < l3; i4++) {
          var c4 = val.charAt(i4);
          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, start2, end) {
      return str2.slice(start2, 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 i4 = 0; i4 < str2.length; i4++) {
        currentChar = str2[i4];
        nextChar = str2[i4 + 1];
        if (!insideComment && currentChar === '"') {
          var escaped = str2[i4 - 1] === "\\" && str2[i4 - 2] !== "\\";
          if (!escaped) {
            insideString = !insideString;
          }
        }
        if (insideString) {
          continue;
        }
        if (!insideComment && currentChar + nextChar === "//") {
          ret += str2.slice(offset, i4);
          offset = i4;
          insideComment = singleComment;
          i4++;
        } else if (insideComment === singleComment && currentChar + nextChar === "\r\n") {
          i4++;
          insideComment = false;
          ret += strip2(str2, offset, i4);
          offset = i4;
          continue;
        } else if (insideComment === singleComment && currentChar === "\n") {
          insideComment = false;
          ret += strip2(str2, offset, i4);
          offset = i4;
        } else if (!insideComment && currentChar + nextChar === "/*") {
          ret += str2.slice(offset, i4);
          offset = i4;
          insideComment = multiComment;
          i4++;
          continue;
        } else if (insideComment === multiComment && currentChar + nextChar === "*/") {
          i4++;
          insideComment = false;
          ret += strip2(str2, offset, i4 + 1);
          offset = i4 + 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 fs142 = __require("fs");
    var ini3 = require_ini();
    var path150 = __require("path");
    var stripJsonComments6 = require_strip_json_comments2();
    var parse17 = exports2.parse = function(content) {
      if (/^\s*{/.test(content))
        return JSON.parse(stripJsonComments6(content));
      return ini3.parse(content);
    };
    var file2 = exports2.file = function() {
      var args2 = [].slice.call(arguments).filter(function(arg) {
        return arg != null;
      });
      for (var i4 in args2)
        if ("string" !== typeof args2[i4])
          return;
      var file3 = path150.join.apply(null, args2);
      var content;
      try {
        return fs142.readFileSync(file3, "utf-8");
      } catch (err2) {
        return;
      }
    };
    var json3 = exports2.json = function() {
      var content = file2.apply(null, arguments);
      return content ? parse17(content) : null;
    };
    var env6 = exports2.env = function(prefix, env7) {
      env7 = env7 || process.env;
      var obj = {};
      var l3 = prefix.length;
      for (var k2 in env7) {
        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, i4) {
            if (!_subkey || typeof cursor !== "object")
              return;
            if (i4 === keypath.length - 1)
              cursor[_subkey] = env7[k2];
            if (cursor[_subkey] === void 0)
              cursor[_subkey] = {};
            cursor = cursor[_subkey];
          }, "_buildSubObj"));
        }
      }
      return obj;
    };
    var find = exports2.find = function() {
      var rel = path150.join.apply(null, [].slice.call(arguments));
      function find2(start2, rel2) {
        var file3 = path150.join(start2, rel2);
        try {
          fs142.statSync(file3);
          return file3;
        } catch (err2) {
          if (path150.dirname(start2) !== start2)
            return find2(path150.dirname(start2), 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 args2 = Array.prototype.slice.call(arguments, 1);
      var val, src, clone4;
      args2.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 isNumber4(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(isNumber4, "isNumber");
    function isConstructorOrProto(obj, key) {
      return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
    }
    __name(isConstructorOrProto, "isConstructorOrProto");
    module2.exports = function(args2, opts) {
      if (!opts) {
        opts = {};
      }
      var flags2 = {
        bools: {},
        strings: {},
        unknownFn: null
      };
      if (typeof opts.unknown === "function") {
        flags2.unknownFn = opts.unknown;
      }
      if (typeof opts.boolean === "boolean" && opts.boolean) {
        flags2.allBools = true;
      } else {
        [].concat(opts.boolean).filter(Boolean).forEach(function(key2) {
          flags2.bools[key2] = true;
        });
      }
      var aliases = {};
      function aliasIsBoolean(key2) {
        return aliases[key2].some(function(x3) {
          return flags2.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) {
        flags2.strings[key2] = true;
        if (aliases[key2]) {
          [].concat(aliases[key2]).forEach(function(k2) {
            flags2.strings[k2] = true;
          });
        }
      });
      var defaults4 = opts.default || {};
      var argv = { _: [] };
      function argDefined(key2, arg2) {
        return flags2.allBools && /^--[^=]+$/.test(arg2) || flags2.strings[key2] || flags2.bools[key2] || aliases[key2];
      }
      __name(argDefined, "argDefined");
      function setKey(obj, keys, value2) {
        var o3 = obj;
        for (var i5 = 0; i5 < keys.length - 1; i5++) {
          var key2 = keys[i5];
          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 || flags2.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 && flags2.unknownFn && !argDefined(key2, arg2)) {
          if (flags2.unknownFn(arg2) === false) {
            return;
          }
        }
        var value2 = !flags2.strings[key2] && isNumber4(val) ? Number(val) : val;
        setKey(argv, key2.split("."), value2);
        (aliases[key2] || []).forEach(function(x3) {
          setKey(argv, x3.split("."), value2);
        });
      }
      __name(setArg, "setArg");
      Object.keys(flags2.bools).forEach(function(key2) {
        setArg(key2, defaults4[key2] === void 0 ? false : defaults4[key2]);
      });
      var notFlags = [];
      if (args2.indexOf("--") !== -1) {
        notFlags = args2.slice(args2.indexOf("--") + 1);
        args2 = args2.slice(0, args2.indexOf("--"));
      }
      for (var i4 = 0; i4 < args2.length; i4++) {
        var arg = args2[i4];
        var key;
        var next;
        if (/^--.+=/.test(arg)) {
          var m3 = arg.match(/^--([^=]+)=([\s\S]*)$/);
          key = m3[1];
          var value = m3[2];
          if (flags2.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 = args2[i4 + 1];
          if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !flags2.bools[key] && !flags2.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
            setArg(key, next, arg);
            i4 += 1;
          } else if (/^(true|false)$/.test(next)) {
            setArg(key, next === "true", arg);
            i4 += 1;
          } else {
            setArg(key, flags2.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], flags2.strings[letters[j2]] ? "" : true, arg);
            }
          }
          key = arg.slice(-1)[0];
          if (!broken && key !== "-") {
            if (args2[i4 + 1] && !/^(-|--)[^-]/.test(args2[i4 + 1]) && !flags2.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
              setArg(key, args2[i4 + 1], arg);
              i4 += 1;
            } else if (args2[i4 + 1] && /^(true|false)$/.test(args2[i4 + 1])) {
              setArg(key, args2[i4 + 1] === "true", arg);
              i4 += 1;
            } else {
              setArg(key, flags2.strings[key] ? "" : true, arg);
            }
          }
        } else {
          if (!flags2.unknownFn || flags2.unknownFn(arg) !== false) {
            argv._.push(flags2.strings._ || !isNumber4(arg) ? arg : Number(arg));
          }
          if (opts.stopEarly) {
            argv._.push.apply(argv._, args2.slice(i4 + 1));
            break;
          }
        }
      }
      Object.keys(defaults4).forEach(function(k2) {
        if (!hasKey2(argv, k2.split("."))) {
          setKey(argv, k2.split("."), defaults4[k2]);
          (aliases[k2] || []).forEach(function(x3) {
            setKey(argv, x3.split("."), defaults4[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 join71 = __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(name4, defaults4, argv, parse17) {
      if ("string" !== typeof name4)
        throw new Error("rc(name): name *must* be string");
      if (!argv)
        argv = require_minimist()(process.argv.slice(2));
      defaults4 = ("string" === typeof defaults4 ? cc.json(defaults4) : defaults4) || {};
      parse17 = parse17 || cc.parse;
      var env6 = cc.env(name4 + "_");
      var configs = [defaults4];
      var configFiles = [];
      function addConfigFile(file2) {
        if (configFiles.indexOf(file2) >= 0) return;
        var fileConfig = cc.file(file2);
        if (fileConfig) {
          configs.push(parse17(fileConfig));
          configFiles.push(file2);
        }
      }
      __name(addConfigFile, "addConfigFile");
      if (!win2)
        [
          join71(etc, name4, "config"),
          join71(etc, name4 + "rc")
        ].forEach(addConfigFile);
      if (home)
        [
          join71(home, ".config", name4, "config"),
          join71(home, ".config", name4),
          join71(home, "." + name4, "config"),
          join71(home, "." + name4 + "rc")
        ].forEach(addConfigFile);
      addConfigFile(cc.find("." + name4 + "rc"));
      if (env6.config) addConfigFile(env6.config);
      if (argv.config) addConfigFile(argv.config);
      return deepExtend.apply(null, configs.concat([
        env6,
        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 constants5 = __require("constants");
    var origCwd = process.cwd;
    var cwd6 = null;
    var platform15 = process.env.GRACEFUL_FS_PLATFORM || process.platform;
    process.cwd = function() {
      if (!cwd6)
        cwd6 = origCwd.call(process);
      return cwd6;
    };
    try {
      process.cwd();
    } catch (er2) {
    }
    if (typeof process.chdir === "function") {
      chdir = process.chdir;
      process.chdir = function(d2) {
        cwd6 = null;
        chdir.call(process, d2);
      };
      if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
    }
    var chdir;
    module2.exports = patch;
    function patch(fs142) {
      if (constants5.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
        patchLchmod(fs142);
      }
      if (!fs142.lutimes) {
        patchLutimes(fs142);
      }
      fs142.chown = chownFix(fs142.chown);
      fs142.fchown = chownFix(fs142.fchown);
      fs142.lchown = chownFix(fs142.lchown);
      fs142.chmod = chmodFix(fs142.chmod);
      fs142.fchmod = chmodFix(fs142.fchmod);
      fs142.lchmod = chmodFix(fs142.lchmod);
      fs142.chownSync = chownFixSync(fs142.chownSync);
      fs142.fchownSync = chownFixSync(fs142.fchownSync);
      fs142.lchownSync = chownFixSync(fs142.lchownSync);
      fs142.chmodSync = chmodFixSync(fs142.chmodSync);
      fs142.fchmodSync = chmodFixSync(fs142.fchmodSync);
      fs142.lchmodSync = chmodFixSync(fs142.lchmodSync);
      fs142.stat = statFix(fs142.stat);
      fs142.fstat = statFix(fs142.fstat);
      fs142.lstat = statFix(fs142.lstat);
      fs142.statSync = statFixSync(fs142.statSync);
      fs142.fstatSync = statFixSync(fs142.fstatSync);
      fs142.lstatSync = statFixSync(fs142.lstatSync);
      if (fs142.chmod && !fs142.lchmod) {
        fs142.lchmod = function(path150, mode, cb) {
          if (cb) process.nextTick(cb);
        };
        fs142.lchmodSync = function() {
        };
      }
      if (fs142.chown && !fs142.lchown) {
        fs142.lchown = function(path150, uid, gid, cb) {
          if (cb) process.nextTick(cb);
        };
        fs142.lchownSync = function() {
        };
      }
      if (platform15 === "win32") {
        fs142.rename = typeof fs142.rename !== "function" ? fs142.rename : function(fs$rename) {
          function rename2(from, to, cb) {
            var start2 = Date.now();
            var backoff = 0;
            fs$rename(from, to, /* @__PURE__ */ __name(function CB(er2) {
              if (er2 && (er2.code === "EACCES" || er2.code === "EPERM") && Date.now() - start2 < 6e4) {
                setTimeout(function() {
                  fs142.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(rename2, "rename");
          if (Object.setPrototypeOf) Object.setPrototypeOf(rename2, fs$rename);
          return rename2;
        }(fs142.rename);
      }
      fs142.read = typeof fs142.read !== "function" ? fs142.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(fs142, fd, buffer, offset, length, position, callback);
              }
              callback_.apply(this, arguments);
            }, "callback");
          }
          return fs$read.call(fs142, fd, buffer, offset, length, position, callback);
        }
        __name(read3, "read");
        if (Object.setPrototypeOf) Object.setPrototypeOf(read3, fs$read);
        return read3;
      }(fs142.read);
      fs142.readSync = typeof fs142.readSync !== "function" ? fs142.readSync : /* @__PURE__ */ function(fs$readSync) {
        return function(fd, buffer, offset, length, position) {
          var eagCounter = 0;
          while (true) {
            try {
              return fs$readSync.call(fs142, fd, buffer, offset, length, position);
            } catch (er2) {
              if (er2.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                continue;
              }
              throw er2;
            }
          }
        };
      }(fs142.readSync);
      function patchLchmod(fs143) {
        fs143.lchmod = function(path150, mode, callback) {
          fs143.open(
            path150,
            constants5.O_WRONLY | constants5.O_SYMLINK,
            mode,
            function(err2, fd) {
              if (err2) {
                if (callback) callback(err2);
                return;
              }
              fs143.fchmod(fd, mode, function(err3) {
                fs143.close(fd, function(err22) {
                  if (callback) callback(err3 || err22);
                });
              });
            }
          );
        };
        fs143.lchmodSync = function(path150, mode) {
          var fd = fs143.openSync(path150, constants5.O_WRONLY | constants5.O_SYMLINK, mode);
          var threw = true;
          var ret;
          try {
            ret = fs143.fchmodSync(fd, mode);
            threw = false;
          } finally {
            if (threw) {
              try {
                fs143.closeSync(fd);
              } catch (er2) {
              }
            } else {
              fs143.closeSync(fd);
            }
          }
          return ret;
        };
      }
      __name(patchLchmod, "patchLchmod");
      function patchLutimes(fs143) {
        if (constants5.hasOwnProperty("O_SYMLINK") && fs143.futimes) {
          fs143.lutimes = function(path150, at2, mt2, cb) {
            fs143.open(path150, constants5.O_SYMLINK, function(er2, fd) {
              if (er2) {
                if (cb) cb(er2);
                return;
              }
              fs143.futimes(fd, at2, mt2, function(er3) {
                fs143.close(fd, function(er22) {
                  if (cb) cb(er3 || er22);
                });
              });
            });
          };
          fs143.lutimesSync = function(path150, at2, mt2) {
            var fd = fs143.openSync(path150, constants5.O_SYMLINK);
            var ret;
            var threw = true;
            try {
              ret = fs143.futimesSync(fd, at2, mt2);
              threw = false;
            } finally {
              if (threw) {
                try {
                  fs143.closeSync(fd);
                } catch (er2) {
                }
              } else {
                fs143.closeSync(fd);
              }
            }
            return ret;
          };
        } else if (fs143.futimes) {
          fs143.lutimes = function(_a7, _b2, _c2, cb) {
            if (cb) process.nextTick(cb);
          };
          fs143.lutimesSync = function() {
          };
        }
      }
      __name(patchLutimes, "patchLutimes");
      function chmodFix(orig) {
        if (!orig) return orig;
        return function(target, mode, cb) {
          return orig.call(fs142, 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(fs142, 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(fs142, 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(fs142, 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(fs142, target, options2, callback) : orig.call(fs142, target, callback);
        };
      }
      __name(statFix, "statFix");
      function statFixSync(orig) {
        if (!orig) return orig;
        return function(target, options2) {
          var stats = options2 ? orig.call(fs142, target, options2) : orig.call(fs142, 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(fs142) {
      return {
        ReadStream: ReadStream2,
        WriteStream: WriteStream2
      };
      function ReadStream2(path150, options2) {
        if (!(this instanceof ReadStream2)) return new ReadStream2(path150, options2);
        Stream9.call(this);
        var self2 = this;
        this.path = path150;
        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;
        }
        fs142.open(this.path, this.flags, this.mode, function(err2, fd) {
          if (err2) {
            self2.emit("error", err2);
            self2.readable = false;
            return;
          }
          self2.fd = fd;
          self2.emit("open", fd);
          self2._read();
        });
      }
      __name(ReadStream2, "ReadStream");
      function WriteStream2(path150, options2) {
        if (!(this instanceof WriteStream2)) return new WriteStream2(path150, options2);
        Stream9.call(this);
        this.path = path150;
        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 = fs142.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 getPrototypeOf2 = 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__: getPrototypeOf2(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 fs142 = __require("fs");
    var polyfills = require_polyfills2();
    var legacy = require_legacy_streams2();
    var clone4 = require_clone2();
    var util5 = __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 noop11() {
    }
    __name(noop11, "noop");
    function publishQueue(context2, queue2) {
      Object.defineProperty(context2, gracefulQueue, {
        get: /* @__PURE__ */ __name(function() {
          return queue2;
        }, "get")
      });
    }
    __name(publishQueue, "publishQueue");
    var debug3 = noop11;
    if (util5.debuglog)
      debug3 = util5.debuglog("gfs4");
    else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
      debug3 = /* @__PURE__ */ __name(function() {
        var m3 = util5.format.apply(util5, arguments);
        m3 = "GFS4: " + m3.split(/\n/).join("\nGFS4: ");
        console.error(m3);
      }, "debug");
    if (!fs142[gracefulQueue]) {
      queue = globalThis[gracefulQueue] || [];
      publishQueue(fs142, queue);
      fs142.close = function(fs$close) {
        function close(fd, cb) {
          return fs$close.call(fs142, fd, function(err2) {
            if (!err2) {
              resetQueue();
            }
            if (typeof cb === "function")
              cb.apply(this, arguments);
          });
        }
        __name(close, "close");
        Object.defineProperty(close, previousSymbol, {
          value: fs$close
        });
        return close;
      }(fs142.close);
      fs142.closeSync = function(fs$closeSync) {
        function closeSync2(fd) {
          fs$closeSync.apply(fs142, arguments);
          resetQueue();
        }
        __name(closeSync2, "closeSync");
        Object.defineProperty(closeSync2, previousSymbol, {
          value: fs$closeSync
        });
        return closeSync2;
      }(fs142.closeSync);
      if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
        process.on("exit", function() {
          debug3(fs142[gracefulQueue]);
          __require("assert").equal(fs142[gracefulQueue].length, 0);
        });
      }
    }
    var queue;
    if (!globalThis[gracefulQueue]) {
      publishQueue(globalThis, fs142[gracefulQueue]);
    }
    module2.exports = patch(clone4(fs142));
    if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs142.__patched) {
      module2.exports = patch(fs142);
      fs142.__patched = true;
    }
    function patch(fs143) {
      polyfills(fs143);
      fs143.gracefulify = patch;
      fs143.createReadStream = createReadStream4;
      fs143.createWriteStream = createWriteStream7;
      var fs$readFile = fs143.readFile;
      fs143.readFile = readFile25;
      function readFile25(path150, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$readFile(path150, options2, cb);
        function go$readFile(path151, options3, cb2, startTime) {
          return fs$readFile(path151, options3, function(err2) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([go$readFile, [path151, options3, cb2], err2, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$readFile, "go$readFile");
      }
      __name(readFile25, "readFile");
      var fs$writeFile = fs143.writeFile;
      fs143.writeFile = writeFile24;
      function writeFile24(path150, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$writeFile(path150, data, options2, cb);
        function go$writeFile(path151, data2, options3, cb2, startTime) {
          return fs$writeFile(path151, data2, options3, function(err2) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([go$writeFile, [path151, data2, options3, cb2], err2, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$writeFile, "go$writeFile");
      }
      __name(writeFile24, "writeFile");
      var fs$appendFile = fs143.appendFile;
      if (fs$appendFile)
        fs143.appendFile = appendFile;
      function appendFile(path150, data, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        return go$appendFile(path150, data, options2, cb);
        function go$appendFile(path151, data2, options3, cb2, startTime) {
          return fs$appendFile(path151, data2, options3, function(err2) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([go$appendFile, [path151, data2, options3, cb2], err2, 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 = fs143.copyFile;
      if (fs$copyFile)
        fs143.copyFile = copyFile3;
      function copyFile3(src, dest, flags2, cb) {
        if (typeof flags2 === "function") {
          cb = flags2;
          flags2 = 0;
        }
        return go$copyFile(src, dest, flags2, cb);
        function go$copyFile(src2, dest2, flags3, cb2, startTime) {
          return fs$copyFile(src2, dest2, flags3, function(err2) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([go$copyFile, [src2, dest2, flags3, cb2], err2, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$copyFile, "go$copyFile");
      }
      __name(copyFile3, "copyFile");
      var fs$readdir = fs143.readdir;
      fs143.readdir = readdir16;
      var noReaddirOptionVersions = /^v[0-5]\./;
      function readdir16(path150, options2, cb) {
        if (typeof options2 === "function")
          cb = options2, options2 = null;
        var go$readdir = noReaddirOptionVersions.test(process.version) ? /* @__PURE__ */ __name(function go$readdir2(path151, options3, cb2, startTime) {
          return fs$readdir(path151, fs$readdirCallback(
            path151,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir") : /* @__PURE__ */ __name(function go$readdir2(path151, options3, cb2, startTime) {
          return fs$readdir(path151, options3, fs$readdirCallback(
            path151,
            options3,
            cb2,
            startTime
          ));
        }, "go$readdir");
        return go$readdir(path150, options2, cb);
        function fs$readdirCallback(path151, options3, cb2, startTime) {
          return function(err2, files) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([
                go$readdir,
                [path151, options3, cb2],
                err2,
                startTime || Date.now(),
                Date.now()
              ]);
            else {
              if (files && files.sort)
                files.sort();
              if (typeof cb2 === "function")
                cb2.call(this, err2, files);
            }
          };
        }
        __name(fs$readdirCallback, "fs$readdirCallback");
      }
      __name(readdir16, "readdir");
      if (process.version.substr(0, 4) === "v0.8") {
        var legStreams = legacy(fs143);
        ReadStream2 = legStreams.ReadStream;
        WriteStream2 = legStreams.WriteStream;
      }
      var fs$ReadStream = fs143.ReadStream;
      if (fs$ReadStream) {
        ReadStream2.prototype = Object.create(fs$ReadStream.prototype);
        ReadStream2.prototype.open = ReadStream$open;
      }
      var fs$WriteStream = fs143.WriteStream;
      if (fs$WriteStream) {
        WriteStream2.prototype = Object.create(fs$WriteStream.prototype);
        WriteStream2.prototype.open = WriteStream$open;
      }
      Object.defineProperty(fs143, "ReadStream", {
        get: /* @__PURE__ */ __name(function() {
          return ReadStream2;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          ReadStream2 = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      Object.defineProperty(fs143, "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(fs143, "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(fs143, "FileWriteStream", {
        get: /* @__PURE__ */ __name(function() {
          return FileWriteStream;
        }, "get"),
        set: /* @__PURE__ */ __name(function(val) {
          FileWriteStream = val;
        }, "set"),
        enumerable: true,
        configurable: true
      });
      function ReadStream2(path150, 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(err2, fd) {
          if (err2) {
            if (that.autoClose)
              that.destroy();
            that.emit("error", err2);
          } else {
            that.fd = fd;
            that.emit("open", fd);
            that.read();
          }
        });
      }
      __name(ReadStream$open, "ReadStream$open");
      function WriteStream2(path150, 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(err2, fd) {
          if (err2) {
            that.destroy();
            that.emit("error", err2);
          } else {
            that.fd = fd;
            that.emit("open", fd);
          }
        });
      }
      __name(WriteStream$open, "WriteStream$open");
      function createReadStream4(path150, options2) {
        return new fs143.ReadStream(path150, options2);
      }
      __name(createReadStream4, "createReadStream");
      function createWriteStream7(path150, options2) {
        return new fs143.WriteStream(path150, options2);
      }
      __name(createWriteStream7, "createWriteStream");
      var fs$open = fs143.open;
      fs143.open = open4;
      function open4(path150, flags2, mode, cb) {
        if (typeof mode === "function")
          cb = mode, mode = null;
        return go$open(path150, flags2, mode, cb);
        function go$open(path151, flags3, mode2, cb2, startTime) {
          return fs$open(path151, flags3, mode2, function(err2, fd) {
            if (err2 && (err2.code === "EMFILE" || err2.code === "ENFILE"))
              enqueue([go$open, [path151, flags3, mode2, cb2], err2, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
        __name(go$open, "go$open");
      }
      __name(open4, "open");
      return fs143;
    }
    __name(patch, "patch");
    function enqueue(elem) {
      debug3("ENQUEUE", elem[0].name, elem[1]);
      fs142[gracefulQueue].push(elem);
      retry();
    }
    __name(enqueue, "enqueue");
    var retryTimer;
    function resetQueue() {
      var now = Date.now();
      for (var i4 = 0; i4 < fs142[gracefulQueue].length; ++i4) {
        if (fs142[gracefulQueue][i4].length > 2) {
          fs142[gracefulQueue][i4][3] = now;
          fs142[gracefulQueue][i4][4] = now;
        }
      }
      retry();
    }
    __name(resetQueue, "resetQueue");
    function retry() {
      clearTimeout(retryTimer);
      retryTimer = void 0;
      if (fs142[gracefulQueue].length === 0)
        return;
      var elem = fs142[gracefulQueue].shift();
      var fn = elem[0];
      var args2 = elem[1];
      var err2 = elem[2];
      var startTime = elem[3];
      var lastTime = elem[4];
      if (startTime === void 0) {
        debug3("RETRY", fn.name, args2);
        fn.apply(null, args2);
      } else if (Date.now() - startTime >= 6e4) {
        debug3("TIMEOUT", fn.name, args2);
        var cb = args2.pop();
        if (typeof cb === "function")
          cb.call(null, err2);
      } 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, args2);
          fn.apply(null, args2.concat([startTime]));
        } else {
          fs142[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 (err2) {
        if (err2.code === "ENOENT")
          return void 0;
        throw err2;
      }
    }
    __name(readCAFileSync, "readCAFileSync");
    exports2.readCAFileSync = readCAFileSync;
  }
});

// node_modules/@pnpm/network.ca-file/dist/index.js
var require_dist9 = __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 i4 in this.list[0]) k2.push(i4);
        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 i4 = 0, l3 = this.list.length; i4 < l3; i4++) {
          setProto(this.list[i4], this.list[i4 + 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 = encode6;
    exports2.safe = safe;
    exports2.unsafe = unsafe;
    var eol = typeof process !== "undefined" && process.platform === "win32" ? "\r\n" : "\n";
    function encode6(obj, opt) {
      var children = [];
      var out2 = "";
      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) {
            out2 += safe(k2 + "[]") + separator + safe(item) + "\n";
          });
        } else if (val && typeof val === "object")
          children.push(k2);
        else
          out2 += safe(k2) + separator + safe(val) + eol;
      });
      if (opt.section && out2.length)
        out2 = "[" + safe(opt.section) + "]" + eol + out2;
      children.forEach(function(k2, _2, __) {
        var nk = dotSplit(k2).join("\\.");
        var section = (opt.section ? opt.section + "." : "") + nk;
        var child = encode6(obj[k2], {
          section,
          whitespace: opt.whitespace
        });
        if (out2.length && child.length)
          out2 += eol;
        out2 += child;
      });
      return out2;
    }
    __name(encode6, "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 out2 = {};
      var p2 = out2;
      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 = out2[section] = out2[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(out2).filter(function(k2, _2, __) {
        if (!out2[k2] || typeof out2[k2] !== "object" || Array.isArray(out2[k2]))
          return false;
        var parts2 = dotSplit(k2);
        var p3 = out2;
        var l3 = parts2.pop();
        var nl2 = l3.replace(/\\\./g, ".");
        parts2.forEach(function(part, _3, __2) {
          if (part === "__proto__")
            return;
          if (!p3[part] || typeof p3[part] !== "object")
            p3[part] = {};
          p3 = p3[part];
        });
        if (p3 === out2 && nl2 === l3)
          return false;
        p3[nl2] = out2[k2];
        return true;
      }).forEach(function(del, _2, __) {
        delete out2[del];
      });
      return out2;
    }
    __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 i4 = 0, l3 = val.length; i4 < l3; i4++) {
          var c4 = val.charAt(i4);
          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 path150 = __require("path");
    var fs142 = __require("fs");
    var ini3 = require_ini2();
    var EE3 = __require("events").EventEmitter;
    var url3 = __require("url");
    var http9 = __require("http");
    var exports2 = module2.exports = function() {
      var args2 = [].slice.call(arguments), conf = new ConfigChain();
      while (args2.length) {
        var a2 = args2.shift();
        if (a2) conf.push("string" === typeof a2 ? json3(a2) : a2);
      }
      return conf;
    };
    var find = exports2.find = function() {
      var rel = path150.join.apply(null, [].slice.call(arguments));
      function find2(start2, rel2) {
        var file2 = path150.join(start2, rel2);
        try {
          fs142.statSync(file2);
          return file2;
        } catch (err2) {
          if (path150.dirname(start2) !== start2)
            return find2(path150.dirname(start2), rel2);
        }
      }
      __name(find2, "find");
      return find2(__dirname, rel);
    };
    var parse17 = exports2.parse = function(content, file2, 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 json3 = exports2.json = function() {
      var args2 = [].slice.call(arguments).filter(function(arg) {
        return arg != null;
      });
      var file2 = path150.join.apply(null, args2);
      var content;
      try {
        content = fs142.readFileSync(file2, "utf-8");
      } catch (err2) {
        return;
      }
      return parse17(content, file2, "json");
    };
    var env6 = exports2.env = function(prefix, env7) {
      env7 = env7 || process.env;
      var obj = {};
      var l3 = prefix.length;
      for (var k2 in env7) {
        if (k2.indexOf(prefix) === 0)
          obj[k2.substring(l3)] = env7[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 i4 = 0, l3 = this.list.length; i4 < l3; i4++) {
          delete this.list[i4][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++;
      fs142.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(file2, type, name4) {
      name4 = name4 || file2;
      var marker = { __source__: name4 };
      this.sources[name4] = { path: file2, type };
      this.push(marker);
      this._await();
      fs142.readFile(file2, "utf8", function(er2, data) {
        if (er2) this.emit("error", er2);
        this.addString(data, file2, type, marker);
      }.bind(this));
      return this;
    };
    ConfigChain.prototype.addEnv = function(prefix, env7, name4) {
      name4 = name4 || "env";
      var data = exports2.env(prefix, env7);
      this.sources[name4] = { data, source: env7, prefix };
      return this.add(data, name4);
    };
    ConfigChain.prototype.addUrl = function(req, type, name4) {
      this._await();
      var href = url3.format(req);
      name4 = name4 || href;
      var marker = { __source__: name4 };
      this.sources[name4] = { href, type };
      this.push(marker);
      http9.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, file2, type, marker) {
      data = this.parse(data, file2, type);
      this.add(data, marker);
      return this;
    };
    ConfigChain.prototype.add = function(data, marker) {
      if (marker && typeof marker === "object") {
        var i4 = this.list.indexOf(marker);
        if (i4 === -1) {
          return this.emit("error", new Error("bad marker"));
        }
        this.splice(i4, 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 normalize13(x3);
      }
      const firstPart = x3.substr(0, colonIndex);
      const secondPart = x3.substr(colonIndex + 1);
      return `${normalize13(firstPart)}:${normalize13(secondPart)}`;
    };
    function normalize13(s5) {
      s5 = s5.toLowerCase();
      if (s5 === "_authtoken") return "_authToken";
      let r5 = s5[0];
      for (let i4 = 1; i4 < s5.length; i4++) {
        r5 += s5[i4] === "_" ? "-" : s5[i4];
      }
      return r5;
    }
    __name(normalize13, "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, env6) {
      return settingValue.replace(ENV_EXPR, replaceEnvMatch.bind(null, env6));
    }
    __name(envReplace, "envReplace");
    exports2.envReplace = envReplace;
    function replaceEnvMatch(env6, orig, escape7, name4) {
      if (escape7.length % 2) {
        return orig.slice((escape7.length + 1) / 2);
      }
      const envValue = getEnvValue(env6, name4);
      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(env6, name4) {
      const matched = name4.match(ENV_VALUE);
      if (!matched)
        return env6[name4];
      const [, variableName, colon, fallback] = matched;
      if (Object.prototype.hasOwnProperty.call(env6, variableName)) {
        return !env6[variableName] && colon ? fallback : env6[variableName];
      }
      return fallback;
    }
    __name(getEnvValue, "getEnvValue");
  }
});

// node_modules/@pnpm/config.env-replace/dist/index.js
var require_dist10 = __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 fs142 = __require("fs");
    var path150 = __require("path");
    var { envReplace } = require_dist10();
    var parseKey = /* @__PURE__ */ __name((key) => {
      if (typeof key !== "string") {
        return key;
      }
      return envReplace(key, process.env);
    }, "parseKey");
    var parseField2 = /* @__PURE__ */ __name((types7, field, key) => {
      if (typeof field !== "string") {
        return field;
      }
      const typeList = [].concat(types7[key]);
      const isPath = typeList.indexOf(path150) !== -1;
      const isBool = typeList.indexOf(Boolean) !== -1;
      const isString3 = typeList.indexOf(String) !== -1;
      const isNumber4 = typeList.indexOf(Number) !== -1;
      field = `${field}`.trim();
      if (/^".*"$/.test(field)) {
        try {
          field = JSON.parse(field);
        } catch (error40) {
          throw new Error(`Failed parsing JSON config key ${key}: ${field}`);
        }
      }
      if (isBool && !isString3 && 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 = path150.resolve(process.env.HOME, field.substr(2));
        }
        field = path150.resolve(field);
      }
      if (isNumber4 && !isNaN(field)) {
        field = Number(field);
      }
      return field;
    }, "parseField");
    var findPrefix = /* @__PURE__ */ __name((name4) => {
      name4 = path150.resolve(name4);
      let walkedUp = false;
      while (path150.basename(name4) === "node_modules") {
        name4 = path150.dirname(name4);
        walkedUp = true;
      }
      if (walkedUp) {
        return name4;
      }
      const find = /* @__PURE__ */ __name((name5, original) => {
        const regex3 = /^[a-zA-Z]:(\\|\/)?$/;
        if (name5 === "/" || process.platform === "win32" && regex3.test(name5)) {
          return original;
        }
        try {
          const files = fs142.readdirSync(name5);
          if (files.includes("node_modules") || files.includes("package.json") || files.includes("package.json5") || files.includes("package.yaml") || files.includes("pnpm-workspace.yaml")) {
            return name5;
          }
          const dirname37 = path150.dirname(name5);
          if (dirname37 === name5) {
            return original;
          }
          return find(dirname37, original);
        } catch (error40) {
          if (name5 === original) {
            if (error40.code === "ENOENT") {
              return original;
            }
            throw error40;
          }
          return original;
        }
      }, "find");
      return find(name4, name4);
    }, "findPrefix");
    exports2.envReplace = envReplace;
    exports2.findPrefix = findPrefix;
    exports2.parseField = parseField2;
    exports2.parseKey = parseKey;
  }
});

// node_modules/@pnpm/npm-conf/lib/types.js
var require_types11 = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/types.js"(exports2) {
    "use strict";
    init_esbuild_shims();
    var path150 = __require("path");
    var Stream9 = __require("stream").Stream;
    var url3 = __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: path150,
      cache: path150,
      "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: path150,
      "global-style": Boolean,
      group: [Number, String],
      "https-proxy": [null, url3],
      "user-agent": String,
      "ham-it-up": Boolean,
      "heading": String,
      "if-present": Boolean,
      "ignore-prepublish": Boolean,
      "ignore-scripts": Boolean,
      "init-module": path150,
      "init-author-name": String,
      "init-author-email": String,
      "init-author-url": ["", url3],
      "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: path150,
      production: Boolean,
      progress: Boolean,
      proxy: [null, false, url3],
      provenance: Boolean,
      // allow proxy to be disabled explicitly
      "read-only": Boolean,
      "rebuild-bundle": Boolean,
      registry: [null, url3],
      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: path150,
      unicode: Boolean,
      "unsafe-perm": Boolean,
      usage: Boolean,
      user: [Number, String],
      userconfig: path150,
      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_dist9();
    var fs142 = __require("fs");
    var path150 = __require("path");
    var { ConfigChain } = require_config_chain();
    var envKeyToSetting = require_envKeyToSetting();
    var util5 = 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 = util5.parseField.bind(null, types7 || require_types11());
      }
      // 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 = util5.parseKey(key);
            if (substKey !== key) {
              delete data[key];
            }
            data[substKey] = this._parseField(value, substKey);
          }
        } catch (error40) {
          throw error40;
        }
        return super.add(data, marker);
      }
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L306-L319
      addFile(file2, name4) {
        name4 = name4 || file2;
        const marker = { __source__: name4 };
        this.sources[name4] = { path: file2, type: "ini" };
        this.push(marker);
        this._await();
        try {
          const contents = fs142.readFileSync(file2, "utf8");
          this.addString(contents, file2, "ini", marker);
        } catch (error40) {
          if (error40.code === "ENOENT") {
            this.add({}, marker);
          } else if (error40.code !== "EISDIR") {
            return `Issue while reading "${file2}". ${error40.message}`;
          }
        }
      }
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L341-L357
      addEnv(env6) {
        env6 = env6 || process.env;
        const conf = {};
        Object.keys(env6).filter((x3) => /^npm_config_/i.test(x3)).forEach((x3) => {
          if (!env6[x3]) {
            return;
          }
          const key = envKeyToSetting(x3.substr(11));
          const rawVal = env6[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 path150.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 = path150.resolve(cli.prefix);
        } else {
          try {
            const prefix = util5.findPrefix(process.cwd());
            p2 = prefix;
          } catch (error40) {
            throw error40;
          }
        }
        return p2;
      }
      // https://github.com/npm/cli/blob/latest/lib/config/load-cafile.js
      loadCAFile(file2) {
        if (!file2) {
          return;
        }
        const ca = readCAFileSync(file2);
        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 = path150.resolve(this.get("prefix"));
        try {
          const stats = fs142.statSync(prefix);
          defConf.user = stats.uid;
        } catch (error40) {
          if (error40.code === "ENOENT") {
            return;
          }
          throw error40;
        }
      }
    };
    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 os59 = __require("os");
    var path150 = __require("path");
    var temp = os59.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 = os59.homedir();
    if (home) {
      process.env.HOME = home;
    } else {
      home = path150.resolve(temp, "npm-" + uidOrPid);
    }
    var cacheExtra = process.platform === "win32" ? "npm-cache" : ".npm";
    var cacheRoot = process.platform === "win32" && process.env.APPDATA || home;
    var cache5 = path150.resolve(cacheRoot, cacheExtra);
    var defaults4;
    var globalPrefix;
    Object.defineProperty(exports2, "defaults", {
      get: /* @__PURE__ */ __name(function() {
        if (defaults4) return defaults4;
        if (process.env.PREFIX) {
          globalPrefix = process.env.PREFIX;
        } else if (process.platform === "win32") {
          globalPrefix = path150.dirname(process.execPath);
        } else {
          globalPrefix = path150.dirname(path150.dirname(process.execPath));
          if (process.env.DESTDIR) {
            globalPrefix = path150.join(process.env.DESTDIR, globalPrefix);
          }
        }
        defaults4 = {
          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: path150.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": path150.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: path150.resolve(home, ".npmrc"),
          umask: process.umask ? process.umask() : umask.fromString("022"),
          version: false,
          versions: false,
          viewer: process.platform === "win32" ? "browser" : "man",
          _exit: true
        };
        return defaults4;
      }, "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 path150 = __require("path");
    var Conf = require_conf();
    var _defaults2 = require_defaults4();
    module2.exports = (opts, types7, defaults4) => {
      const conf = new Conf(Object.assign({}, _defaults2.defaults, defaults4), 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 (error40) {
          failedToLoadBuiltInConfig = true;
        }
        if (npmPath) {
          warnings.push(conf.addFile(path150.resolve(path150.dirname(npmPath), "..", "npmrc"), "builtin"));
        }
      }
      conf.addEnv();
      conf.loadPrefix();
      const projectConf = path150.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 = path150.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 = path150.resolve(conf.get("prefix"), "etc");
        conf.root.globalconfig = path150.resolve(etc, "npmrc");
        conf.root.globalignorefile = path150.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(path150) {
      return path150[path150.length - 1] === "/" ? path150 : path150 + "/";
    }
    __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 parse17 = require_parse9();
    var prerelease = /* @__PURE__ */ __name((version2, options2) => {
      const parsed = parse17(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 parse17 = 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 parse17(`${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_range2 = __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 i4 = 0; i4 < this.set.length; i4++) {
            if (i4 > 0) {
              this.formatted += "||";
            }
            const comps = this.set[i4];
            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 i4 = 0; i4 < this.set.length; i4++) {
          if (testSet(this.set[i4], 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((set2, version2, options2) => {
      for (let i4 = 0; i4 < set2.length; i4++) {
        if (!set2[i4].test(version2)) {
          return false;
        }
      }
      if (version2.prerelease.length && !options2.includePrerelease) {
        for (let i4 = 0; i4 < set2.length; i4++) {
          debug3(set2[i4].semver);
          if (set2[i4].semver === Comparator.ANY) {
            continue;
          }
          if (set2[i4].semver.prerelease.length > 0) {
            const allowed = set2[i4].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_range2();
  }
});

// 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_range2();
    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_range2();
    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_range2();
    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_range2();
    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_range2();
    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 i4 = 0; i4 < range.set.length; ++i4) {
        const comparators = range.set[i4];
        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_range2();
    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_range2();
    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 i4 = 0; i4 < range.set.length; ++i4) {
        const comparators = range.set[i4];
        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_range2();
    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 set2 = [];
      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) {
            set2.push([first2, prev]);
          }
          prev = null;
          first2 = null;
        }
      }
      if (first2) {
        set2.push([first2, null]);
      }
      const ranges2 = [];
      for (const [min, max] of set2) {
        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_range2();
    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 constants5 = require_constants13();
    var SemVer = require_semver2();
    var identifiers = require_identifiers();
    var parse17 = 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_range2();
    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: parse17,
      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: constants5.SEMVER_SPEC_VERSION,
      RELEASE_TYPES: constants5.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: hasOwnProperty3 } = Object.prototype;
    var encode6 = /* @__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 out2 = "";
      const arraySuffix = opt.bracketedArray ? "[]" : "";
      for (const k2 of keys) {
        const val = obj[k2];
        if (val && Array.isArray(val)) {
          for (const item of val) {
            out2 += safe(`${k2}${arraySuffix}`).padEnd(padToChars, " ") + separator + safe(item) + eol;
          }
        } else if (val && typeof val === "object") {
          children.push(k2);
        } else {
          out2 += safe(k2).padEnd(padToChars, " ") + separator + safe(val) + eol;
        }
      }
      if (opt.section && out2.length) {
        out2 = "[" + safe(opt.section) + "]" + (opt.newline ? eol + eol : eol) + out2;
      }
      for (const k2 of children) {
        const nk = splitSections(k2, ".").join("\\.");
        const section = (opt.section ? opt.section + "." : "") + nk;
        const child = encode6(obj[k2], {
          ...opt,
          section
        });
        if (out2.length && child.length) {
          out2 += eol;
        }
        out2 += child;
      }
      return out2;
    }, "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 out2 = /* @__PURE__ */ Object.create(null);
      let p2 = out2;
      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 = out2[section] = out2[section] || /* @__PURE__ */ Object.create(null);
          continue;
        }
        const keyRaw = unsafe(match2[2]);
        let isArray3;
        if (opt.bracketedArray) {
          isArray3 = keyRaw.length > 2 && keyRaw.slice(-2) === "[]";
        } else {
          duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1;
          isArray3 = duplicates[keyRaw] > 1;
        }
        const key = isArray3 ? 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 (isArray3) {
          if (!hasOwnProperty3.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(out2)) {
        if (!hasOwnProperty3.call(out2, k2) || typeof out2[k2] !== "object" || Array.isArray(out2[k2])) {
          continue;
        }
        const parts2 = splitSections(k2, ".");
        p2 = out2;
        const l3 = parts2.pop();
        const nl2 = l3.replace(/\\\./g, ".");
        for (const part of parts2) {
          if (part === "__proto__") {
            continue;
          }
          if (!hasOwnProperty3.call(p2, part) || typeof p2[part] !== "object") {
            p2[part] = /* @__PURE__ */ Object.create(null);
          }
          p2 = p2[part];
        }
        if (p2 === out2 && nl2 === l3) {
          continue;
        }
        p2[nl2] = out2[k2];
        remove2.push(k2);
      }
      for (const del of remove2) {
        delete out2[del];
      }
      return out2;
    }, "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 i4 = 0, l3 = val.length; i4 < l3; i4++) {
          const c4 = val.charAt(i4);
          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: encode6,
      encode: encode6,
      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 stripAnsi4 = 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 = stripAnsi4(string4);
      if (string4.length === 0) {
        return 0;
      }
      string4 = string4.replace(emojiRegex7(), "  ");
      let width = 0;
      for (let i4 = 0; i4 < string4.length; i4++) {
        const code2 = string4.codePointAt(i4);
        if (code2 <= 31 || code2 >= 127 && code2 <= 159) {
          continue;
        }
        if (code2 >= 768 && code2 <= 879) {
          continue;
        }
        if (code2 > 65535) {
          i4++;
        }
        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 pad2 = 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(pad2) + 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/utils/startupProfiler.ts
init_esbuild_shims();
import * as fs2 from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { performance as performance2 } from "node:perf_hooks";
var enabled = false;
var t0 = 0;
var processUptimeAtT0Ms = 0;
var checkpoints = [];
var finalized = false;
function initStartupProfiler() {
  resetStartupProfiler();
  if (process.env["QWEN_CODE_PROFILE_STARTUP"] !== "1") {
    return;
  }
  if (!process.env["SANDBOX"]) {
    return;
  }
  enabled = true;
  finalized = false;
  processUptimeAtT0Ms = Math.round(process.uptime() * 1e3 * 100) / 100;
  t0 = performance2.now();
  checkpoints = [];
}
__name(initStartupProfiler, "initStartupProfiler");
function profileCheckpoint(name4) {
  if (!enabled) return;
  checkpoints.push({ name: name4, timestamp: performance2.now() });
}
__name(profileCheckpoint, "profileCheckpoint");
function getStartupReport() {
  if (!enabled || checkpoints.length === 0) return null;
  const phases = [];
  let prev = t0;
  for (const cp3 of checkpoints) {
    phases.push({
      name: cp3.name,
      startMs: Math.round((prev - t0) * 100) / 100,
      durationMs: Math.round((cp3.timestamp - prev) * 100) / 100
    });
    prev = cp3.timestamp;
  }
  const lastTimestamp = checkpoints[checkpoints.length - 1].timestamp;
  return {
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    sessionId: "unknown",
    processUptimeAtT0Ms,
    totalMs: Math.round((lastTimestamp - t0) * 100) / 100,
    phases,
    nodeVersion: process.version,
    platform: process.platform,
    arch: process.arch
  };
}
__name(getStartupReport, "getStartupReport");
function finalizeStartupProfile(sessionId) {
  if (!enabled || finalized) return;
  finalized = true;
  const report = getStartupReport();
  if (!report) return;
  if (sessionId) {
    report.sessionId = sessionId;
  }
  try {
    const dir = path.join(os.homedir(), ".qwen", "startup-perf");
    fs2.mkdirSync(dir, { recursive: true });
    const filename = `${report.timestamp.replace(/[:.]/g, "-")}-${report.sessionId}.json`;
    const filepath = path.join(dir, filename);
    fs2.writeFileSync(filepath, JSON.stringify(report, null, 2), "utf-8");
    process.stderr.write(`Startup profile written to: ${filepath}
`);
  } catch {
    process.stderr.write("Warning: Failed to write startup profile report\n");
  }
}
__name(finalizeStartupProfile, "finalizeStartupProfile");
function resetStartupProfiler() {
  enabled = false;
  t0 = 0;
  processUptimeAtT0Ms = 0;
  checkpoints = [];
  finalized = false;
}
__name(resetStartupProfiler, "resetStartupProfiler");

// packages/cli/src/gemini.tsx
init_esbuild_shims();
init_dist4();

// 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 process25 from "node:process";

// node_modules/ink/build/ink.js
init_esbuild_shims();
var import_react13 = __toESM(require_react(), 1);
import process24 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(func2, 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) {
      func2.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(...args2) {
    if (signal?.aborted) {
      return;
    }
    pendingThis = this;
    pendingArgs = args2;
    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(func2, 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(...args2) {
    result = func2.apply(this, args2);
    pendingAt = null;
  }, debounceMs, { edges });
  const debounced = /* @__PURE__ */ __name(function(...args2) {
    if (maxWait != null) {
      if (pendingAt === null) {
        pendingAt = Date.now();
      }
      if (Date.now() - pendingAt >= maxWait) {
        result = func2.apply(this, args2);
        pendingAt = Date.now();
        _debounced.cancel();
        _debounced.schedule();
        return result;
      }
    }
    _debounced.apply(this, args2);
    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(func2, throttleMs = 0, options2 = {}) {
  const { leading = true, trailing = true } = options2;
  return debounce2(func2, 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 process15 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 platform11 = globalThis.navigator?.userAgentData?.platform;
var isMacOs = platform11 === "macOS" || globalThis.navigator?.platform === "MacIntel" || globalThis.navigator?.userAgent?.includes(" Mac ") === true || globalThis.process?.platform === "darwin";
var isWindows6 = platform11 === "Windows" || globalThis.navigator?.platform === "Win32" || globalThis.process?.platform === "win32";
var isLinux2 = platform11 === "Linux" || globalThis.navigator?.platform?.startsWith("Linux") === true || globalThis.navigator?.userAgent?.includes(" Linux ") === true || globalThis.process?.platform === "linux";
var isIos = platform11 === "iOS" || globalThis.navigator?.platform === "MacIntel" && globalThis.navigator?.maxTouchPoints > 1 || /iPad|iPhone|iPod/.test(globalThis.navigator?.platform);
var isAndroid = platform11 === "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 && process15.env.TERM_PROGRAM === "Apple_Terminal";
var isWindows7 = !isBrowser && process15.platform === "win32";
var cwdFunction = isBrowser ? () => {
  throw new Error("`process.cwd()` only works in Node.js, not the browser.");
} : process15.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 i4 = 0; i4 < count; i4++) {
    clear += eraseLine + (i4 < 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, url3) => [
  OSC,
  "8",
  SEP,
  SEP,
  url3,
  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((cwd6 = cwdFunction()) => `${OSC}50;CurrentDir=${cwd6}${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 filter5 = /* @__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" || !filter5(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 stdout2 = new PassThrough4();
  const stderr = new PassThrough4();
  stdout2.write = (data) => {
    callback("stdout", data);
  };
  stderr.write = (data) => {
    callback("stderr", data);
  };
  const internalConsole = new console.Console(stdout2, 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_constants35 = __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 noExitRuntime2 = 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, C3, ka, D2, E2, la, ma;
    function na() {
      var a2 = fa.buffer;
      ia = a2;
      h3.HEAP8 = ja = new Int8Array(a2);
      h3.HEAP16 = C3 = 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, G3 = 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 C3[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 = C3[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) C3[b2 >> 1] = a2.charCodeAt(e4), b2 += 2;
      C3[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 = C3;
            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), G3 && (e4 = G3, G3 = 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;
    G3 = /* @__PURE__ */ __name(function Lb() {
      Kb || Mb();
      Kb || (G3 = 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(prototype2, name4, fn) {
    const original = prototype2[name4];
    prototype2[name4] = function() {
      for (var _len = arguments.length, args2 = new Array(_len), _key = 0; _key < _len; _key++) {
        args2[_key] = arguments[_key];
      }
      return fn.call(this, original, ...args2);
    };
  }
  __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, args2 = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args2[_key2 - 1] = arguments[_key2];
      }
      const value = args2.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, ...args2, asNumber2);
      } else {
        return methods[unit].call(this, ...args2);
      }
    });
  }
  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 = stripAnsi2(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 matches2 = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches2) {
          return [0, 0, 0];
        }
        let [colorString] = matches2;
        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((url3) => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${url3}${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(stripAnsi2(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_constants34 = __toESM(require_constants12(), 1);
import process16 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 = stripAnsi2(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 matches2 = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches2) {
          return [0, 0, 0];
        }
        let [colorString] = matches2;
        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 = stripAnsi2(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 (process16.env["DEV"] === "true") {
  try {
    await Promise.resolve().then(() => (init_devtools(), devtools_exports));
  } catch (error40) {
    if (error40.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 error40;
    }
  }
}
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_constants34.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((instance2) => instance2, "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_constants34.NoEventPriority) {
      return currentUpdatePriority;
    }
    return import_constants34.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 matches2 = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches2) {
          return [0, 0, 0];
        }
        let [colorString] = matches2;
        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 process17 from "node:process";
import os32 from "node:os";
import tty from "node:tty";
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process17.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: env2 } = process17;
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 env2) {
    if (env2.FORCE_COLOR === "true") {
      return 1;
    }
    if (env2.FORCE_COLOR === "false") {
      return 0;
    }
    return env2.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env2.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 env2 && "AGENT_NAME" in env2) {
    return 1;
  }
  if (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min = forceColor || 0;
  if (env2.TERM === "dumb") {
    return min;
  }
  if (process17.platform === "win32") {
    const osRelease = os32.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env2) {
    if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env2)) {
      return 3;
    }
    if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env2) || env2.CI_NAME === "codeship") {
      return 1;
    }
    return min;
  }
  if ("TEAMCITY_VERSION" in env2) {
    return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env2.TEAMCITY_VERSION) ? 1 : 0;
  }
  if (env2.COLORTERM === "truecolor") {
    return 3;
  }
  if (env2.TERM === "xterm-kitty") {
    return 3;
  }
  if (env2.TERM === "xterm-ghostty") {
    return 3;
  }
  if (env2.TERM === "wezterm") {
    return 3;
  }
  if ("TERM_PROGRAM" in env2) {
    const version2 = Number.parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env2.TERM_PROGRAM) {
      case "iTerm.app": {
        return version2 >= 3 ? 3 : 2;
      }
      case "Apple_Terminal": {
        return 2;
      }
    }
  }
  if (/-256(color)?$/i.test(env2.TERM)) {
    return 2;
  }
  if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env2.TERM)) {
    return 1;
  }
  if ("COLORTERM" in env2) {
    return 1;
  }
  return min;
}
__name(_supportsColor, "_supportsColor");
function createSupportsColor(stream5, options2 = {}) {
  const level = _supportsColor(stream5, {
    streamIsTTY: stream5 && stream5.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 chalk10 = /* @__PURE__ */ __name((...strings) => strings.join(" "), "chalk");
  applyOptions(chalk10, options2);
  Object.setPrototypeOf(chalk10, createChalk.prototype);
  return chalk10;
}, "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_2) => {
  if (model === "rgb") {
    if (level === "ansi16m") {
      return ansi_styles_default3[type].ansi16m(...arguments_2);
    }
    if (level === "ansi256") {
      return ansi_styles_default3[type].ansi256(ansi_styles_default3.rgbToAnsi256(...arguments_2));
    }
    return ansi_styles_default3[type].ansi(ansi_styles_default3.rgbToAnsi(...arguments_2));
  }
  if (model === "hex") {
    return getModelAnsi("rgb", level, type, ...ansi_styles_default3.hexToRgb(...arguments_2));
  }
  return ansi_styles_default3[type][model](...arguments_2);
}, "getModelAnsi");
var usedModels = ["rgb", "hex", "ansi256"];
for (const model of usedModels) {
  styles5[model] = {
    get() {
      const { level } = this;
      return function(...arguments_2) {
        const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_2), 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_2) {
        const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_2), 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_2) => applyStyle(builder, arguments_2.length === 1 ? "" + arguments_2[0] : arguments_2.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 matches2 = ansiRegex2.exec(color);
    if (!matches2) {
      return str2;
    }
    const value = Number(matches2[1]);
    return type === "foreground" ? source_default.ansi256(value)(str2) : source_default.bgAnsi256(value)(str2);
  }
  if (color.startsWith("rgb")) {
    const matches2 = rgbRegex.exec(color);
    if (!matches2) {
      return str2;
    }
    const firstValue = Number(matches2[1]);
    const secondValue = Number(matches2[2]);
    const thirdValue = Number(matches2[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 matches2 = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches2) {
          return [0, 0, 0];
        }
        let [colorString] = matches2;
        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 [start2, end] of ansi_styles_default4.codes) {
  endCodesSet.add(ansi_styles_default4.color.ansi(end));
  endCodesMap.set(ansi_styles_default4.color.ansi(start2), 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 tokenize5(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(tokenize5, "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, start2, end) {
  const tokens = tokenize5(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 >= start2) {
        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 matches2 = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches2) {
          return [0, 0, 0];
        }
        let [colorString] = matches2;
        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 [start2, end] of ansi_styles_default5.codes) {
  endCodesSet2.add(ansi_styles_default5.color.ansi(end));
  endCodesMap2.set(ansi_styles_default5.color.ansi(start2), 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 i4 = 0; i4 < chars.length; i4++) {
    const char = chars[i4];
    if (i4 === 0) {
      ret += ansiCodesToString(char.styles);
    } else {
      ret += ansiCodesToString(diffAnsiCodes(chars[i4 - 1].styles, char.styles));
    }
    ret += char.value;
    if (i4 === 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 tokenize6(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(tokenize6, "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(tokenize6(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 process19 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 process18 from "node:process";
var restoreCursor = (0, import_onetime.default)(() => {
  (0, import_signal_exit.default)(() => {
    process18.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 = process19.stderr) => {
  if (!writableStream.isTTY) {
    return;
  }
  isHidden = false;
  writableStream.write("\x1B[?25h");
};
cliCursor.hide = (writableStream = process19.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 create3 = /* @__PURE__ */ __name((stream5, { 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;
    stream5.write(base_exports.eraseLines(previousLineCount) + output);
    previousLineCount = output.split("\n").length;
  }, "render");
  render3.clear = () => {
    stream5.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: create3 };
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 EventEmitter10 } from "node:events";
import process23 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 EventEmitter9 } from "node:events";
import process20 from "node:process";
var StdinContext = (0, import_react3.createContext)({
  stdin: process20.stdin,
  // eslint-disable-next-line @typescript-eslint/naming-convention
  internal_eventEmitter: new EventEmitter9(),
  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 process21 from "node:process";
var StdoutContext = (0, import_react4.createContext)({
  stdout: process21.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 process22 from "node:process";
var StderrContext = (0, import_react5.createContext)({
  stderr: process22.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 fs100 from "node:fs";
import { cwd as cwd2 } 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((path150) => {
  return path150?.replace(`file://${cwd2()}/`, "");
}, "cleanupPath");
var stackUtils = new import_stack_utils.default({
  cwd: cwd2(),
  internals: import_stack_utils.default.nodeInternals()
});
function ErrorOverview({ error: error40 }) {
  const stack = error40.stack ? error40.stack.split("\n").slice(1) : void 0;
  const origin2 = stack ? stackUtils.parseLine(stack[0]) : void 0;
  const filePath = cleanupPath(origin2?.file);
  let excerpt;
  let lineWidth = 0;
  if (filePath && origin2?.line && fs100.existsSync(filePath)) {
    const sourceCode = fs100.readFileSync(filePath, "utf8");
    excerpt = dist_default4(sourceCode, origin2.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,
        " ",
        error40.message
      )
    ),
    origin2 && filePath && import_react11.default.createElement(
      Box_default,
      { marginTop: 1 },
      import_react11.default.createElement(
        Text3,
        { dimColor: true },
        filePath,
        ":",
        origin2.line,
        ":",
        origin2.column
      )
    ),
    origin2 && 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 !== origin2.line, backgroundColor: line === origin2.line ? "red" : void 0, color: line === origin2.line ? "white" : void 0, "aria-label": line === origin2.line ? `Line ${line}, error` : `Line ${line}` },
          String(line).padStart(lineWidth, " "),
          ":"
        )
      ),
      import_react11.default.createElement(Text3, { key: line, backgroundColor: line === origin2.line ? "red" : void 0, color: line === origin2.line ? "white" : void 0 }, " " + value)
    ))),
    error40.stack && import_react11.default.createElement(Box_default, { marginTop: 1, flexDirection: "column" }, error40.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(error40) {
    return { error: error40 };
  }
  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 EventEmitter10();
  // 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(error40) {
    this.handleExit(error40);
  }
  handleSetRawMode = /* @__PURE__ */ __name((isEnabled2) => {
    const { stdin: stdin2 } = this.props;
    if (!this.isRawModeSupported()) {
      if (stdin2 === process23.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");
      }
    }
    stdin2.setEncoding("utf8");
    if (isEnabled2) {
      if (this.rawModeEnabledCount === 0) {
        stdin2.ref();
        stdin2.setRawMode(true);
        stdin2.addListener("readable", this.handleReadable);
      }
      this.rawModeEnabledCount++;
      return;
    }
    if (--this.rawModeEnabledCount === 0) {
      stdin2.setRawMode(false);
      stdin2.removeListener("readable", this.handleReadable);
      stdin2.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((error40) => {
    if (this.isRawModeSupported()) {
      this.handleSetRawMode(false);
    }
    this.props.onExit(error40);
  }, "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 ?? process24.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_constants35.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 (process24.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(error40) {
    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 (error40 instanceof Error) {
      this.rejectExitPromise(error40);
    } else {
      this.resolveExitPromise();
    }
  }
  async waitUntilExit() {
    this.exitPromise ||= new Promise((resolve42, reject) => {
      this.resolveExitPromise = resolve42;
      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((stream5, data) => {
      if (stream5 === "stdout") {
        this.writeToStdout(data);
      }
      if (stream5 === "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: process25.stdout,
    stdin: process25.stdin,
    stderr: process25.stderr,
    debug: false,
    exitOnCtrlC: true,
    patchConsole: true,
    ...getOptions(options2)
  };
  const instance2 = getInstance(inkOptions.stdout, () => new Ink(inkOptions));
  instance2.render(node);
  return {
    rerender: instance2.render,
    unmount() {
      instance2.unmount();
    },
    waitUntilExit: instance2.waitUntilExit,
    cleanup: /* @__PURE__ */ __name(() => instances_default.delete(inkOptions.stdout), "cleanup"),
    clear: instance2.clear
  };
}, "render");
var render_default = render2;
var getOptions = /* @__PURE__ */ __name((stdout2 = {}) => {
  if (stdout2 instanceof Stream6) {
    return {
      stdout: stdout2,
      stdin: process25.stdin
    };
  }
  return stdout2;
}, "getOptions");
var getInstance = /* @__PURE__ */ __name((stdout2, createInstance3) => {
  let instance2 = instances_default.get(stdout2);
  if (!instance2) {
    instance2 = createInstance3();
    instances_default.set(stdout2, instance2);
  }
  return instance2;
}, "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_react192 = __toESM(require_react(), 1);
import dns2 from "node:dns";
import os58 from "node:os";
import { basename as basename33 } from "node:path";
import v8 from "node:v8";

// packages/cli/src/config/auth.ts
init_esbuild_shims();
init_dist4();

// packages/cli/src/config/settings.ts
init_esbuild_shims();
var dotenv2 = __toESM(require_main(), 1);
init_dist4();
var import_strip_json_comments2 = __toESM(require_strip_json_comments(), 1);
import * as fs107 from "node:fs";
import * as path100 from "node:path";
import { homedir as homedir20, platform as platform12 } from "node:os";
import process26 from "node:process";

// 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();
init_dist4();
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 debugLogger104 = 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];
  }
  debugLogger104.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(name4, type, rawMappings, colors, semanticColors) {
    this.name = name4;
    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,
        code: this.colors.LightBlue
      },
      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?.code ?? 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,
      code: customTheme.text?.code ?? colors.LightBlue
    },
    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(name4) {
  return name4.trim().length > 0 && name4.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();
init_dist4();
var import_strip_json_comments = __toESM(require_strip_json_comments(), 1);
init_stdioHelpers();
import * as fs101 from "node:fs";
import * as path97 from "node:path";
import { homedir as homedir18 } from "node:os";
var TRUSTED_FOLDERS_FILENAME = "trustedFolders.json";
var SETTINGS_DIRECTORY_NAME = ".qwen";
var USER_SETTINGS_DIR = path97.join(homedir18(), SETTINGS_DIRECTORY_NAME);
function getTrustedFoldersPath() {
  if (process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"]) {
    return process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"];
  }
  return path97.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(([path150, trustLevel]) => ({
      path: path150,
      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(path97.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 (path97.normalize(location) === path97.normalize(untrustedPath)) {
        return false;
      }
    }
    return void 0;
  }
  setValue(path150, trustLevel) {
    this.user.config[path150] = trustLevel;
    saveTrustedFolders(this.user);
  }
};
var loadedTrustedFolders;
function loadTrustedFolders() {
  if (loadedTrustedFolders) {
    return loadedTrustedFolders;
  }
  const errors = [];
  let userConfig = {};
  const userPath = getTrustedFoldersPath();
  try {
    if (fs101.existsSync(userPath)) {
      const content = fs101.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 (error40) {
    errors.push({
      message: getErrorMessage(error40),
      path: userPath
    });
  }
  loadedTrustedFolders = new LoadedTrustedFolders(
    { path: userPath, config: userConfig },
    errors
  );
  return loadedTrustedFolders;
}
__name(loadTrustedFolders, "loadTrustedFolders");
function saveTrustedFolders(trustedFoldersFile) {
  try {
    const dirPath = path97.dirname(trustedFoldersFile.path);
    if (!fs101.existsSync(dirPath)) {
      fs101.mkdirSync(dirPath, { recursive: true });
    }
    fs101.writeFileSync(
      trustedFoldersFile.path,
      JSON.stringify(trustedFoldersFile.config, null, 2),
      { encoding: "utf-8", mode: 384 }
    );
  } catch (error40) {
    writeStderrLine("Error saving trusted folders file.");
    writeStderrLine(error40 instanceof Error ? error40.message : String(error40));
  }
}
__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(
      (error40) => `Error in ${error40.path}: ${error40.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/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/config/settingsSchema.ts
init_esbuild_shims();
init_dist4();
init_languages();
var TOGGLE_TYPES = /* @__PURE__ */ new Set([
  "boolean",
  "enum"
]);
var HOOK_DEFINITION_ITEMS = {
  type: "object",
  description: "A hook definition with an optional matcher and a list of hook configurations.",
  properties: {
    matcher: {
      type: "string",
      description: "An optional matcher pattern to filter when this hook definition applies."
    },
    sequential: {
      type: "boolean",
      description: "Whether the hooks should be executed sequentially instead of in parallel."
    },
    hooks: {
      type: "array",
      description: "The list of hook configurations to execute.",
      required: true,
      items: {
        type: "object",
        description: "A hook configuration entry that defines a hook to execute.",
        properties: {
          type: {
            type: "string",
            description: 'The type of hook. Note: "function" type is only available via SDK registration, not settings.json.',
            enum: ["command", "http"],
            required: true
          },
          command: {
            type: "string",
            description: 'The command to execute when the hook is triggered. Required for "command" type.'
          },
          url: {
            type: "string",
            description: 'The URL to send the POST request to. Required for "http" type.'
          },
          headers: {
            type: "object",
            description: "HTTP headers to include in the request. Supports env var interpolation ($VAR, ${VAR}).",
            additionalProperties: { type: "string" }
          },
          allowedEnvVars: {
            type: "array",
            description: "List of environment variables allowed for interpolation in headers and URL.",
            items: { type: "string" }
          },
          name: {
            type: "string",
            description: "An optional name for the hook."
          },
          description: {
            type: "string",
            description: "An optional description of what the hook does."
          },
          timeout: {
            type: "number",
            description: "Timeout in seconds for the hook execution."
          },
          env: {
            type: "object",
            description: "Environment variables to set when executing the hook command.",
            additionalProperties: { type: "string" }
          },
          async: {
            type: "boolean",
            description: 'Whether to execute the hook asynchronously (non-blocking, for "command" type only).'
          },
          once: {
            type: "boolean",
            description: 'Whether to execute the hook only once per session (for "http" type).'
          },
          statusMessage: {
            type: "string",
            description: "A message to display while the hook is executing."
          },
          shell: {
            type: "string",
            description: "The shell to use for command execution.",
            enum: ["bash", "powershell"]
          }
        }
      }
    }
  }
};
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 */
  },
  // Channels configuration (Telegram, Discord, etc.)
  channels: {
    type: "object",
    label: "Channels",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Configuration for messaging channels.",
    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
      },
      showSessionRecap: {
        type: "boolean",
        label: "Show Session Recap",
        category: "General",
        requiresRestart: false,
        // Off by default — an ambient background LLM call isn't something
        // users should be opted into silently, especially when `fastModel`
        // is unset and the call would land on the main coding model.
        // Manual `/recap` works regardless.
        default: false,
        description: 'Auto-show a one-line "where you left off" recap when returning to the terminal after being away. Off by default. Use /recap to trigger manually regardless of this setting.',
        showInDialog: true
      },
      sessionRecapAwayThresholdMinutes: {
        type: "number",
        label: "Session Recap Away Threshold (minutes)",
        category: "General",
        requiresRestart: false,
        default: 5,
        description: "How many minutes the terminal must be blurred before an auto-recap fires on the next focus-in. Matches Claude Code's default of 5 minutes; raise if you briefly alt-tab and do not want recaps to pile up.",
        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" }
        ]
      }
    }
  },
  dualOutput: {
    type: "object",
    label: "Dual Output",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Dual-output sidecar mode: emit structured JSON events to a second channel while the TUI renders normally on stdout. See docs/users/features/dual-output.md. CLI flags take precedence over these settings.",
    showInDialog: false,
    properties: {
      jsonFile: {
        type: "string",
        label: "JSON Event File",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "File path for structured JSON event output. Equivalent to --json-file. Ignored if --json-fd or --json-file is also set.",
        showInDialog: false
      },
      inputFile: {
        type: "string",
        label: "Remote Input File",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "File path for remote input commands (JSONL). Equivalent to --input-file. Ignored if --input-file is also set.",
        showInDialog: false
      }
    }
  },
  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
      },
      statusLine: {
        type: "object",
        label: "Status Line",
        category: "UI",
        requiresRestart: false,
        default: void 0,
        description: "Custom status line display configuration. Optional `refreshInterval` (seconds, >= 1) re-runs the command on a timer so external data stays fresh.",
        showInDialog: false
      },
      customThemes: {
        type: "object",
        label: "Custom Themes",
        category: "UI",
        requiresRestart: false,
        default: {},
        description: "Custom theme definitions.",
        showInDialog: false
      },
      hideWindowTitle: {
        type: "boolean",
        label: "Hide Window Title",
        category: "UI",
        requiresRestart: true,
        default: false,
        description: "Hide the window title bar",
        showInDialog: 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. Choosing "Start new chat session" suppresses the dialog for that project until the project summary changes.',
        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
      },
      enableFollowupSuggestions: {
        type: "boolean",
        label: "Enable Follow-up Suggestions",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Show context-aware follow-up suggestions after task completion. Press Tab or Right Arrow to accept, Enter to accept and submit.",
        showInDialog: true
      },
      enableCacheSharing: {
        type: "boolean",
        label: "Enable Cache Sharing for Suggestions",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Use cache-aware forked queries for suggestion generation. Reduces cost on providers that support prefix caching (experimental).",
        showInDialog: false
      },
      enableSpeculation: {
        type: "boolean",
        label: "Enable Speculative Execution",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Speculatively execute accepted suggestions before submission. Results appear instantly when you accept (experimental).",
        showInDialog: false
      },
      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
      },
      compactMode: {
        type: "boolean",
        label: "Compact Mode",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).",
        showInDialog: true
      },
      shellOutputMaxLines: {
        type: "number",
        label: "Shell Output Max Lines",
        category: "UI",
        requiresRestart: false,
        default: 5,
        description: "Max number of shell output lines shown inline. Set to 0 to disable the cap and show full output. The hidden line count is still surfaced via the `+N lines` indicator.",
        showInDialog: true
      }
    }
  },
  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
  },
  fastModel: {
    type: "string",
    label: "Fast Model",
    category: "Model",
    requiresRestart: false,
    default: "",
    description: "Model used for generating prompt suggestions and speculative execution. Leave empty to use the main model. A smaller/faster model (e.g., qwen3-coder-flash) reduces latency and cost.",
    showInDialog: true
  },
  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
      },
      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: true,
        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
          },
          splitToolMedia: {
            type: "boolean",
            label: "Split Tool Result Media",
            category: "Generation Configuration",
            requiresRestart: false,
            default: false,
            description: 'When true, media (images / audio / video / files) returned by MCP tool calls is split into a follow-up user message instead of being embedded in the tool message. Required for strict OpenAI-compatible servers (e.g., LM Studio) that reject non-text content on `role: "tool"` messages with HTTP 400 "Invalid \'messages\' in payload". Default false preserves the prior behavior for permissive providers. See QwenLM/qwen-code#3616.',
            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
      },
      clearContextOnIdle: {
        type: "object",
        label: "Clear Context On Idle",
        category: "Context",
        requiresRestart: false,
        default: {},
        description: "Settings for clearing stale context after idle periods. Use -1 to disable a threshold.",
        showInDialog: false,
        properties: {
          toolResultsThresholdMinutes: {
            type: "number",
            label: "Tool Results Idle Threshold (minutes)",
            category: "Context",
            requiresRestart: false,
            default: 60,
            description: "Minutes of inactivity before clearing old tool result content. Use -1 to disable.",
            showInDialog: false
          },
          toolResultsNumToKeep: {
            type: "number",
            label: "Tool Results Number To Keep",
            category: "Context",
            requiresRestart: false,
            default: 5,
            description: "Number of most-recent compactable tool results to preserve when clearing. Floor at 1.",
            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
          }
        }
      }
    }
  },
  memory: {
    type: "object",
    label: "Memory",
    category: "Memory",
    requiresRestart: false,
    default: {},
    description: "Settings for managed auto-memory.",
    showInDialog: false,
    properties: {
      enableManagedAutoMemory: {
        type: "boolean",
        label: "Enable Managed Auto-Memory",
        category: "Memory",
        requiresRestart: false,
        default: true,
        description: "Enable background extraction of memories from conversations.",
        showInDialog: false
      },
      enableManagedAutoDream: {
        type: "boolean",
        label: "Enable Managed Auto-Dream",
        category: "Memory",
        requiresRestart: false,
        default: false,
        description: "Enable automatic consolidation (dream) of collected memories.",
        showInDialog: false
      }
    }
  },
  slashCommands: {
    type: "object",
    label: "Slash Commands",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Configuration for slash commands exposed by the CLI. Useful for locking down the command surface in multi-tenant or enterprise deployments.",
    showInDialog: false,
    properties: {
      disabled: {
        type: "array",
        label: "Disabled Slash Commands",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: 'Slash command names to hide and refuse to execute. Matched case-insensitively against the final command name (for extension commands this is the disambiguated form, e.g. "myext.deploy"). Merged as a union across settings scopes, so workspace settings can add to but not remove entries defined in system/user settings.',
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      }
    }
  },
  permissions: {
    type: "object",
    label: "Permissions",
    category: "Tools",
    requiresRestart: true,
    default: {},
    description: "Permission rules controlling tool usage. Rules are evaluated in priority order: deny > ask > allow.",
    showInDialog: false,
    properties: {
      allow: {
        type: "array",
        label: "Allow Rules",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: 'Tools or commands that are auto-approved without confirmation. Examples: "ShellTool", "Bash(git *)", "ReadFileTool".',
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      ask: {
        type: "array",
        label: "Ask Rules",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Tools or commands that always require user confirmation. Takes precedence over allow rules.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      deny: {
        type: "array",
        label: "Deny Rules",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: 'Tools or commands that are always blocked. Highest priority rule. Examples: "ShellTool", "Bash(rm -rf *)".',
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      }
    }
  },
  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
      },
      sandboxImage: {
        type: "string",
        label: "Sandbox Image",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Sandbox image URI used by Docker/Podman when --sandbox-image and QWEN_SANDBOX_IMAGE are not set.",
        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: true,
            description: "Use node-pty for an interactive shell experience. Falls back to child_process if PTY is unavailable.",
            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
          }
        }
      },
      // Legacy tool permission fields – kept for backward compatibility.
      // Use permissions.{allow,ask,deny} instead.
      core: {
        type: "array",
        label: "Core Tools (deprecated)",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Deprecated. Use permissions.allow instead.",
        showInDialog: false
      },
      allowed: {
        type: "array",
        label: "Allowed Tools (deprecated)",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "Deprecated. Use permissions.allow instead.",
        showInDialog: false
      },
      exclude: {
        type: "array",
        label: "Exclude Tools (deprecated)",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Deprecated. Use permissions.deny instead.",
        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
      },
      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,
        mergeStrategy: "concat" /* CONCAT */
      },
      excluded: {
        type: "array",
        label: "Exclude MCP Servers",
        category: "MCP",
        requiresRestart: true,
        default: void 0,
        description: "A list of MCP servers to exclude.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */
      }
    }
  },
  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
          }
        }
      },
      allowedHttpHookUrls: {
        type: "array",
        label: "Allowed HTTP Hook URLs",
        category: "Security",
        requiresRestart: false,
        default: [],
        description: "Whitelist of URL patterns for HTTP hooks. Supports * wildcard. If empty, all URLs are allowed (subject to SSRF protection).",
        showInDialog: false,
        items: {
          type: "string",
          description: "URL pattern (supports * wildcard)"
        }
      }
    }
  },
  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
      },
      runtimeOutputDir: {
        type: "string",
        label: "Runtime Output Directory",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "Custom directory for runtime output (temp files, debug logs, session data, todos, etc.). Config files remain at ~/.qwen. Env var QWEN_RUNTIME_DIR takes priority.",
        showInDialog: false
      }
    }
  },
  agents: {
    type: "object",
    label: "Agents",
    category: "Advanced",
    requiresRestart: false,
    default: {},
    description: "Settings for multi-agent collaboration features (Arena, Team, Swarm).",
    showInDialog: false,
    properties: {
      displayMode: {
        type: "enum",
        label: "Display Mode",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: 'Display mode for multi-agent sessions. Currently only "in-process" is supported.',
        showInDialog: false,
        options: [
          { value: "in-process", label: "In-process" }
          // { value: 'tmux', label: 'tmux' },
          // { value: 'iterm2', label: 'iTerm2' },
        ]
      },
      arena: {
        type: "object",
        label: "Arena",
        category: "Advanced",
        requiresRestart: false,
        default: {},
        description: "Settings for Arena (multi-model competitive execution).",
        showInDialog: false,
        properties: {
          worktreeBaseDir: {
            type: "string",
            label: "Worktree Base Directory",
            category: "Advanced",
            requiresRestart: true,
            default: void 0,
            description: "Custom base directory for Arena worktrees. Defaults to ~/.qwen/arena.",
            showInDialog: false
          },
          preserveArtifacts: {
            type: "boolean",
            label: "Preserve Arena Artifacts",
            category: "Advanced",
            requiresRestart: false,
            default: false,
            description: "When enabled, Arena worktrees and session state files are preserved after the session ends or the main agent exits.",
            showInDialog: true
          },
          maxRoundsPerAgent: {
            type: "number",
            label: "Max Rounds Per Agent",
            category: "Advanced",
            requiresRestart: false,
            default: void 0,
            description: "Maximum number of rounds (turns) each agent can execute. No limit if unset.",
            showInDialog: false
          },
          timeoutSeconds: {
            type: "number",
            label: "Timeout (seconds)",
            category: "Advanced",
            requiresRestart: false,
            default: void 0,
            description: "Total timeout in seconds for the Arena session. No limit if unset.",
            showInDialog: false
          }
        }
      },
      team: {
        type: "object",
        label: "Team",
        category: "Advanced",
        requiresRestart: false,
        default: {},
        description: "Settings for Agent Team (role-based collaborative execution). Reserved for future use.",
        showInDialog: false
      },
      swarm: {
        type: "object",
        label: "Swarm",
        category: "Advanced",
        requiresRestart: false,
        default: {},
        description: "Settings for Agent Swarm (parallel sub-agent execution). Reserved for future use.",
        showInDialog: false
      }
    }
  },
  disableAllHooks: {
    type: "boolean",
    label: "Disable All Hooks",
    category: "Advanced",
    requiresRestart: true,
    // Future enhancement: consider supporting mid-session toggle for better UX
    default: false,
    description: "Temporarily disable all hooks without deleting configurations. Default is false (hooks enabled).",
    showInDialog: false
  },
  hooks: {
    type: "object",
    label: "Hooks",
    category: "Advanced",
    requiresRestart: false,
    default: {},
    description: "Hook event configurations for extending CLI behavior at various lifecycle points.",
    showInDialog: false,
    properties: {
      UserPromptSubmit: {
        type: "array",
        label: "Before Agent Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute before agent processing. Can modify prompts or inject context.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      Stop: {
        type: "array",
        label: "After Agent Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute after agent processing. Can post-process responses or log interactions.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      Notification: {
        type: "array",
        label: "Notification Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when notifications are sent.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PreToolUse: {
        type: "array",
        label: "Pre Tool Use Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute before tool execution.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PostToolUse: {
        type: "array",
        label: "Post Tool Use Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute after successful tool execution.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PostToolUseFailure: {
        type: "array",
        label: "Post Tool Use Failure Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when tool execution fails. ",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SessionStart: {
        type: "array",
        label: "Session Start Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a new session starts or resumes.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SessionEnd: {
        type: "array",
        label: "Session End Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a session ends.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PreCompact: {
        type: "array",
        label: "Pre Compact Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute before conversation compaction.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SubagentStart: {
        type: "array",
        label: "Subagent Start Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a subagent (Task tool call) is started.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SubagentStop: {
        type: "array",
        label: "Subagent Stop Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute right before a subagent (Task tool call) concludes its response.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PermissionRequest: {
        type: "array",
        label: "Permission Request Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a permission dialog is displayed.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      }
    }
  },
  experimental: {
    type: "object",
    label: "Experimental",
    category: "Experimental",
    requiresRestart: true,
    default: {},
    description: "Settings to enable experimental features.",
    showInDialog: false,
    properties: {
      cron: {
        type: "boolean",
        label: "Enable Cron/Loop Tools",
        category: "Experimental",
        requiresRestart: true,
        default: false,
        description: "Enable in-session cron/loop tools (experimental). When enabled, the model can create recurring prompts using cron_create, cron_list, and cron_delete tools. Can also be enabled via QWEN_CODE_ENABLE_CRON=1 environment variable.",
        showInDialog: true
      },
      emitToolUseSummaries: {
        type: "boolean",
        label: "Tool Use Summaries",
        category: "Experimental",
        requiresRestart: false,
        default: true,
        description: "Generate a short LLM-based label after each tool batch completes. In compact mode the label replaces the generic `Tool \xD7 N` header; in full mode it appears as a dim `\u25CF <label>` line below the tool group. Requires a fast model to be configured; runs in parallel with the next API call so latency is hidden. Currently affects interactive CLI rendering only \u2014 SDK / non-interactive emission of the `tool_use_summary` message is not yet wired (the message factory is exported for a follow-up PR). Can be overridden with QWEN_CODE_EMIT_TOOL_USE_SUMMARIES=0 or =1.",
        showInDialog: true
      }
    }
  }
};
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/settingsUtils.ts
init_esbuild_shims();
import * as fs104 from "node:fs";
init_i18n();

// packages/cli/src/utils/languageUtils.ts
init_esbuild_shims();
init_dist4();
init_i18n();
import * as fs103 from "node:fs";
import * as path99 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 path99.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} -->

## Rule
You MUST always respond in **${language}** regardless of the user's input language.
This is a mandatory requirement, not a preference.

## Exception
If the user **explicitly** requests a response in a specific language (e.g., "please reply in English", "\u7528\u4E2D\u6587\u56DE\u7B54"), switch to the user's requested language for the remainder of the conversation.

## 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)

## 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 (!fs103.existsSync(filePath)) {
    return null;
  }
  try {
    const content = fs103.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 = path99.dirname(filePath);
  fs103.mkdirSync(dir, { recursive: true });
  fs103.writeFileSync(filePath, content, "utf-8");
}
__name(writeOutputLanguageFile, "writeOutputLanguageFile");
function updateOutputLanguageFile(settingValue) {
  const resolved = resolveOutputLanguage(settingValue);
  writeOutputLanguageFile(resolved);
}
__name(updateOutputLanguageFile, "updateOutputLanguageFile");
function initializeLlmOutputLanguage(outputLanguage) {
  const currentFileLanguage = readOutputLanguageFromFile();
  if (currentFileLanguage) {
    return;
  }
  const resolved = resolveOutputLanguage(outputLanguage);
  writeOutputLanguageFile(resolved);
}
__name(initializeLlmOutputLanguage, "initializeLlmOutputLanguage");

// packages/cli/src/utils/settingsUtils.ts
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, path150) {
  const [first2, ...rest] = path150;
  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 getNestedProperty(obj, path150) {
  return getNestedValue(obj, path150.split("."));
}
__name(getNestedProperty, "getNestedProperty");
function getEffectiveValue(key, settings, mergedSettings) {
  const definition = getSettingDefinition(key);
  if (!definition) {
    return void 0;
  }
  const path150 = key.split(".");
  let value = getNestedValue(settings, path150);
  if (value !== void 0) {
    return value;
  }
  value = getNestedValue(mergedSettings, path150);
  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 path150 = key.split(".");
  const value = getNestedValue(scopeSettings, path150);
  return value !== void 0;
}
__name(settingExistsInScope, "settingExistsInScope");
function setNestedPropertyForce(obj, path150, value) {
  const keys = path150.split(".");
  const lastKey = keys.pop();
  if (!lastKey) return;
  let current = obj;
  for (const key of keys) {
    if (!current[key] || typeof current[key] !== "object") {
      current[key] = {};
    }
    current = current[key];
  }
  current[lastKey] = value;
}
__name(setNestedPropertyForce, "setNestedPropertyForce");
function setNestedPropertySafe(obj, path150, value) {
  const keys = path150.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(setNestedPropertySafe, "setNestedPropertySafe");
function deleteNestedPropertySafe(obj, path150) {
  const keys = path150.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(deleteNestedPropertySafe, "deleteNestedPropertySafe");
function setPendingSettingValue(key, value, pendingSettings) {
  const newSettings = JSON.parse(JSON.stringify(pendingSettings));
  setNestedPropertyForce(newSettings, key, value);
  return newSettings;
}
__name(setPendingSettingValue, "setPendingSettingValue");
function setPendingSettingValueAny(key, value, pendingSettings) {
  const newSettings = structuredClone(pendingSettings);
  setNestedPropertyForce(newSettings, key, 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 path150 = settingKey.split(".");
    const value = getNestedValue(
      pendingSettings,
      path150
    );
    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 (fs104.existsSync(filePath)) {
      const backupPath = `${filePath}.orig`;
      if (!fs104.existsSync(backupPath)) {
        fs104.renameSync(filePath, backupPath);
        return true;
      }
    }
  } catch (_e2) {
  }
  return false;
}
__name(backupSettingsFile, "backupSettingsFile");

// 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, path150 = []) {
  for (const key of Object.keys(source2)) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      continue;
    }
    const newPath = [...path150, 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);
init_stdioHelpers();
import * as fs105 from "node:fs";
function updateSettingsFilePreservingFormat(filePath, updates) {
  if (!fs105.existsSync(filePath)) {
    fs105.writeFileSync(filePath, JSON.stringify(updates, null, 2), "utf-8");
    return true;
  }
  const originalContent = fs105.readFileSync(filePath, "utf-8");
  let parsed;
  try {
    parsed = (0, import_comment_json.parse)(originalContent);
  } catch (error40) {
    writeStderrLine("Error parsing settings file.");
    writeStderrLine(error40 instanceof Error ? error40.message : String(error40));
    writeStderrLine(
      "Settings file may be corrupted. Please check the JSON syntax."
    );
    return false;
  }
  const updatedStructure = applyUpdates(parsed, updates);
  const updatedContent = (0, import_comment_json.stringify)(updatedStructure, null, 2);
  try {
    (0, import_comment_json.parse)(updatedContent);
  } catch (validationError) {
    writeStderrLine(
      "Error: Refusing to write settings file \u2014 the result would not be valid JSON."
    );
    writeStderrLine(
      validationError instanceof Error ? validationError.message : String(validationError)
    );
    return false;
  }
  fs105.writeFileSync(filePath, updatedContent, "utf-8");
  return true;
}
__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/migration/index.ts
init_esbuild_shims();

// packages/cli/src/config/migration/scheduler.ts
init_esbuild_shims();
init_dist4();
var debugLogger105 = createDebugLogger("SETTINGS_MIGRATION");
function formatScope(scope) {
  if (scope === "SystemDefaults") {
    return "system default";
  }
  return scope.toLowerCase();
}
__name(formatScope, "formatScope");
var MigrationScheduler = class {
  /**
   * Creates a new MigrationScheduler with the given migrations.
   *
   * @param migrations - Array of migrations in execution order (typically ascending version)
   * @param scope - The scope of settings being migrated
   */
  constructor(migrations, scope) {
    this.migrations = migrations;
    this.scope = scope;
  }
  static {
    __name(this, "MigrationScheduler");
  }
  /**
   * Executes the migration chain on the given settings.
   *
   * Iterates through all registered migrations in order. For each migration:
   * 1. Calls `shouldMigrate` with the current settings
   * 2. If true, calls `migrate` to transform the settings
   * 3. Records the execution
   *
   * The scheduler itself has no version awareness - all version detection
   * is delegated to the individual migrations.
   *
   * @param settings - The settings object to migrate
   * @returns MigrationResult containing the final settings, version, and execution log
   */
  migrate(settings) {
    debugLogger105.debug("MigrationScheduler: Starting migration chain");
    let current = settings;
    const executed = [];
    const allWarnings = [];
    for (const migration of this.migrations) {
      try {
        if (migration.shouldMigrate(current)) {
          debugLogger105.debug(
            `MigrationScheduler: Executing migration ${migration.fromVersion} \u2192 ${migration.toVersion}`
          );
          const formattedScope = formatScope(this.scope);
          const result = migration.migrate(current, formattedScope);
          current = result.settings;
          allWarnings.push(...result.warnings);
          executed.push({
            fromVersion: migration.fromVersion,
            toVersion: migration.toVersion
          });
          debugLogger105.debug(
            `MigrationScheduler: Migration ${migration.fromVersion} \u2192 ${migration.toVersion} completed successfully`
          );
        }
      } catch (error40) {
        debugLogger105.error(
          `MigrationScheduler: Migration ${migration.fromVersion} \u2192 ${migration.toVersion} failed:`,
          error40
        );
        throw error40;
      }
    }
    const finalVersion = current["$version"] ?? 1;
    debugLogger105.debug(
      `MigrationScheduler: Migration chain complete. Final version: ${finalVersion}, Executed: ${executed.length} migrations`
    );
    return {
      settings: current,
      finalVersion,
      executedMigrations: executed,
      warnings: allWarnings
    };
  }
};

// packages/cli/src/config/migration/versions/v1-to-v2.ts
init_esbuild_shims();

// packages/cli/src/config/migration/versions/v1-to-v2-shared.ts
init_esbuild_shims();
var V1_TO_V2_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",
  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 V2_CONTAINER_KEYS = /* @__PURE__ */ new Set([
  "ui",
  "tools",
  "mcp",
  "advanced",
  "model",
  "general",
  "context",
  "security",
  "ide",
  "privacy",
  "telemetry",
  "extensions"
]);
var V1_TO_V2_PRESERVE_DISABLE_MAP = {
  disableAutoUpdate: "general.disableAutoUpdate",
  disableUpdateNag: "general.disableUpdateNag",
  disableLoadingPhrases: "ui.accessibility.disableLoadingPhrases",
  disableFuzzySearch: "context.fileFiltering.disableFuzzySearch",
  disableCacheControl: "model.generationConfig.disableCacheControl"
};
var CONSOLIDATED_DISABLE_KEYS = /* @__PURE__ */ new Set([
  "disableAutoUpdate",
  "disableUpdateNag"
]);
var V1_INDICATOR_KEYS = [
  // From V1_TO_V2_MIGRATION_MAP - keys that map to different paths in V2
  "theme",
  "model",
  "autoAccept",
  "hideTips",
  "vimMode",
  "checkpointing",
  "accessibility",
  "allowedTools",
  "allowMCPServers",
  "autoConfigureMaxOldSpaceSize",
  "bugCommand",
  "chatCompression",
  "coreTools",
  "contextFileName",
  "customThemes",
  "customWittyPhrases",
  "debugKeystrokeLogging",
  "dnsResolutionOrder",
  "enforcedAuthType",
  "excludeTools",
  "excludeMCPServers",
  "excludedProjectEnvVars",
  "fileFiltering",
  "folderTrustFeature",
  "folderTrust",
  "hasSeenIdeIntegrationNudge",
  "hideWindowTitle",
  "showStatusInTitle",
  "showLineNumbers",
  "showCitations",
  "ideMode",
  "includeDirectories",
  "loadMemoryFromIncludeDirectories",
  "maxSessionTurns",
  "mcpServerCommand",
  "memoryImportFormat",
  "preferredEditor",
  "sandbox",
  "selectedAuthType",
  "shouldUseNodePtyShell",
  "shellPager",
  "shellShowColor",
  "skipNextSpeakerCheck",
  "toolDiscoveryCommand",
  "toolCallCommand",
  "usageStatisticsEnabled",
  "useExternalAuth",
  "useRipgrep",
  "enableWelcomeBack",
  "approvalMode",
  "sessionTokenLimit",
  "contentGenerator",
  "skipLoopDetection",
  "skipStartupContext",
  "enableOpenAILogging",
  "tavilyApiKey",
  // From V1_TO_V2_PRESERVE_DISABLE_MAP - disable* keys that get nested in V2
  "disableAutoUpdate",
  "disableUpdateNag",
  "disableLoadingPhrases",
  "disableFuzzySearch",
  "disableCacheControl"
];

// packages/cli/src/config/migration/versions/v1-to-v2.ts
var V1ToV2Migration = class {
  static {
    __name(this, "V1ToV2Migration");
  }
  fromVersion = 1;
  toVersion = 2;
  /**
   * Determines whether this migration should execute.
   *
   * Decision strategy:
   * - Hard-stop when `$version` is a number >= 2 (already V2+).
   * - Otherwise, scan indicator keys and trigger only when at least one indicator is
   *   still in legacy top-level shape (primitive/array/null).
   *
   * Mixed-shape tolerance:
   * - Files that are partially migrated are supported; V2-like object-valued indicators
   *   are ignored while legacy-shaped indicators can still trigger migration.
   */
  shouldMigrate(settings) {
    if (typeof settings !== "object" || settings === null) {
      return false;
    }
    const s5 = settings;
    const version2 = s5["$version"];
    if (typeof version2 === "number" && version2 >= 2) {
      return false;
    }
    return V1_INDICATOR_KEYS.some((key) => {
      if (!(key in s5)) {
        return false;
      }
      const value = s5[key];
      if (typeof value === "object" && value !== null && !Array.isArray(value)) {
        return false;
      }
      return true;
    });
  }
  /**
   * Performs non-destructive V1 -> V2 transformation.
   *
   * Detailed strategy:
   * 1) Relocate known V1 keys using `V1_TO_V2_MIGRATION_MAP`.
   *    - If a source value is already an object and maps to a child path of itself
   *      (partial V2 shape), merge child properties into target path.
   * 2) Relocate disable* keys into V2 disable* locations.
   *    - Consolidated keys (`disableAutoUpdate`, `disableUpdateNag`): normalize to
   *      boolean with stable-compatible presence semantics (`value === true`).
   *    - Other disable* keys: migrate only boolean values.
   * 3) Preserve `mcpServers` top-level placement.
   * 4) Carry over remaining keys:
   *    - If a key is parent of migrated nested paths, merge unprocessed object children.
   *    - If parent value is non-object, preserve that scalar/array/null as-is.
   *    - Otherwise copy untouched key/value.
   * 5) Stamp `$version = 2`.
   *
   * The method is pure with respect to input mutation.
   */
  migrate(settings, _scope) {
    if (typeof settings !== "object" || settings === null) {
      throw new Error("Settings must be an object");
    }
    const source2 = settings;
    const result = {};
    const processedKeys = /* @__PURE__ */ new Set();
    const warnings = [];
    for (const [v1Key, v2Path] of Object.entries(V1_TO_V2_MIGRATION_MAP)) {
      if (v1Key in source2) {
        const value = source2[v1Key];
        if (V2_CONTAINER_KEYS.has(v1Key) && typeof value === "object" && value !== null && !Array.isArray(value)) {
          result[v1Key] = value;
          processedKeys.add(v1Key);
          continue;
        }
        if (typeof value === "object" && value !== null && !Array.isArray(value) && v2Path.startsWith(v1Key + ".")) {
          for (const [nestedKey, nestedValue] of Object.entries(value)) {
            setNestedPropertySafe(
              result,
              `${v2Path}.${nestedKey}`,
              nestedValue
            );
          }
        } else {
          setNestedPropertySafe(result, v2Path, value);
        }
        processedKeys.add(v1Key);
      }
    }
    for (const [v1Key, v2Path] of Object.entries(
      V1_TO_V2_PRESERVE_DISABLE_MAP
    )) {
      if (v1Key in source2) {
        const value = source2[v1Key];
        if (CONSOLIDATED_DISABLE_KEYS.has(v1Key)) {
          setNestedPropertySafe(result, v2Path, value === true);
        } else if (typeof value === "boolean") {
          setNestedPropertySafe(result, v2Path, value);
        }
        processedKeys.add(v1Key);
      }
    }
    if ("mcpServers" in source2) {
      result["mcpServers"] = source2["mcpServers"];
      processedKeys.add("mcpServers");
    }
    for (const key of Object.keys(source2)) {
      if (!processedKeys.has(key)) {
        const isParentOfMigratedPath = Array.from(processedKeys).some(
          (processedKey) => {
            const v2Path = V1_TO_V2_MIGRATION_MAP[processedKey] || V1_TO_V2_PRESERVE_DISABLE_MAP[processedKey];
            if (!v2Path) return false;
            return v2Path.startsWith(key + ".");
          }
        );
        if (isParentOfMigratedPath) {
          const existingValue = source2[key];
          if (typeof existingValue === "object" && existingValue !== null && !Array.isArray(existingValue)) {
            for (const [nestedKey, nestedValue] of Object.entries(
              existingValue
            )) {
              const fullNestedPath = `${key}.${nestedKey}`;
              const wasProcessed = Array.from(processedKeys).some(
                (processedKey) => {
                  const v2Path = V1_TO_V2_MIGRATION_MAP[processedKey] || V1_TO_V2_PRESERVE_DISABLE_MAP[processedKey];
                  return v2Path === fullNestedPath;
                }
              );
              if (!wasProcessed) {
                setNestedPropertySafe(result, fullNestedPath, nestedValue);
              }
            }
          } else {
            result[key] = source2[key];
          }
        } else {
          result[key] = source2[key];
        }
      }
    }
    result["$version"] = 2;
    return { settings: result, warnings };
  }
};
var v1ToV2Migration = new V1ToV2Migration();

// packages/cli/src/config/migration/versions/v2-to-v3.ts
init_esbuild_shims();
var V2_TO_V3_BOOLEAN_MAP = {
  "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 normalizeDisableValue(value) {
  if (value === void 0) {
    return { isPresent: false, isValid: false };
  }
  if (typeof value === "boolean") {
    return { isPresent: true, isValid: true, booleanValue: value };
  }
  if (typeof value === "string") {
    const normalized2 = value.trim().toLowerCase();
    if (normalized2 === "true") {
      return { isPresent: true, isValid: true, booleanValue: true };
    }
    if (normalized2 === "false") {
      return { isPresent: true, isValid: true, booleanValue: false };
    }
  }
  return { isPresent: true, isValid: false };
}
__name(normalizeDisableValue, "normalizeDisableValue");
var V2ToV3Migration = class {
  static {
    __name(this, "V2ToV3Migration");
  }
  fromVersion = 2;
  toVersion = 3;
  /**
   * Migration trigger rule.
   *
   * Execute only when `$version === 2`.
   * This includes V2 files with no migratable disable* booleans so that version
   * metadata still advances to 3.
   */
  shouldMigrate(settings) {
    if (typeof settings !== "object" || settings === null) {
      return false;
    }
    const s5 = settings;
    return s5["$version"] === 2;
  }
  /**
   * Applies V2 -> V3 transformation with deterministic deprecated-key cleanup.
   *
   * Detailed strategy:
   * 1) Clone input.
   * 2) Process consolidated paths first:
   *    - Inspect each source path.
   *    - Normalize each present value (boolean / coercible string / invalid).
   *    - Always delete present deprecated source key.
   *    - Valid normalized values contribute to aggregate.
   *    - Invalid values emit warnings.
   *    - Emit consolidated target when at least one valid source was consumed.
   * 3) Process remaining one-to-one mappings:
   *    - For each unmapped source, normalize value.
   *    - If valid -> delete old key and write inverted target.
   *    - If invalid -> delete old key and emit warning.
   * 4) Set `$version = 3`.
   *
   * Guarantees:
   * - Input object is not mutated.
   * - Valid migration and invalid cleanup are deterministic.
   * - Deprecated disable* keys are not retained after migration.
   */
  migrate(settings, scope) {
    if (typeof settings !== "object" || settings === null) {
      throw new Error("Settings must be an object");
    }
    const result = structuredClone(settings);
    const processedPaths = /* @__PURE__ */ new Set();
    const warnings = [];
    for (const [newPath, oldPaths] of Object.entries(CONSOLIDATED_V2_PATHS)) {
      let hasAnyDisable = false;
      let hasAnyBooleanValue = false;
      for (const oldPath of oldPaths) {
        const oldValue = getNestedProperty(result, oldPath);
        const normalized2 = normalizeDisableValue(oldValue);
        if (!normalized2.isPresent) {
          continue;
        }
        deleteNestedPropertySafe(result, oldPath);
        processedPaths.add(oldPath);
        if (normalized2.isValid) {
          hasAnyBooleanValue = true;
          if (normalized2.booleanValue === true) {
            hasAnyDisable = true;
          }
        } else {
          warnings.push(
            `Removed deprecated setting '${oldPath}' from ${scope} settings because the value is invalid. Expected boolean.`
          );
        }
      }
      if (hasAnyBooleanValue) {
        setNestedPropertySafe(result, newPath, !hasAnyDisable);
      }
    }
    for (const [oldPath, newPath] of Object.entries(V2_TO_V3_BOOLEAN_MAP)) {
      if (processedPaths.has(oldPath)) {
        continue;
      }
      const oldValue = getNestedProperty(result, oldPath);
      const normalized2 = normalizeDisableValue(oldValue);
      if (!normalized2.isPresent) {
        continue;
      }
      deleteNestedPropertySafe(result, oldPath);
      if (normalized2.isValid) {
        setNestedPropertySafe(result, newPath, !normalized2.booleanValue);
      } else {
        warnings.push(
          `Removed deprecated setting '${oldPath}' from ${scope} settings because the value is invalid. Expected boolean or string "true"/"false".`
        );
      }
    }
    result["$version"] = 3;
    return { settings: result, warnings };
  }
};
var v2ToV3Migration = new V2ToV3Migration();

// packages/cli/src/config/migration/index.ts
var ALL_MIGRATIONS = [v1ToV2Migration, v2ToV3Migration];
function runMigrations(settings, scope) {
  const scheduler = new MigrationScheduler([...ALL_MIGRATIONS], scope);
  return scheduler.migrate(settings);
}
__name(runMigrations, "runMigrations");
function needsMigration(settings) {
  if (typeof settings !== "object" || settings === null) {
    return false;
  }
  const s5 = settings;
  const version2 = s5["$version"];
  const hasApplicableMigration = ALL_MIGRATIONS.some(
    (migration) => migration.shouldMigrate(settings)
  );
  if (typeof version2 === "number") {
    if (version2 >= SETTINGS_VERSION) {
      return false;
    }
    return hasApplicableMigration;
  }
  return hasApplicableMigration;
}
__name(needsMigration, "needsMigration");

// packages/cli/src/utils/writeWithBackup.ts
init_esbuild_shims();
import * as fs106 from "node:fs";
function writeWithBackupSync(targetPath, content, options2 = {}) {
  const { backupSuffix = ".orig", encoding = "utf-8" } = options2;
  const tempPath = `${targetPath}.tmp`;
  const backupPath = `${targetPath}${backupSuffix}`;
  try {
    if (fs106.existsSync(tempPath)) {
      fs106.unlinkSync(tempPath);
    }
  } catch (_e2) {
  }
  try {
    fs106.writeFileSync(tempPath, content, { encoding });
    if (fs106.existsSync(targetPath)) {
      const targetStat = fs106.statSync(targetPath);
      if (targetStat.isDirectory()) {
        try {
          fs106.unlinkSync(tempPath);
        } catch (_e2) {
        }
        throw new Error(
          `Cannot write to '${targetPath}' because it is a directory`
        );
      }
      try {
        fs106.renameSync(targetPath, backupPath);
      } catch (backupError) {
        try {
          fs106.unlinkSync(tempPath);
        } catch (_e2) {
        }
        throw new Error(
          `Failed to backup existing file: ${backupError instanceof Error ? backupError.message : String(backupError)}`
        );
      }
    }
    try {
      fs106.renameSync(tempPath, targetPath);
    } catch (renameError) {
      let restoreFailedMessage;
      let backupExisted = false;
      if (fs106.existsSync(backupPath)) {
        backupExisted = true;
        try {
          fs106.renameSync(backupPath, targetPath);
        } catch (restoreError) {
          restoreFailedMessage = restoreError instanceof Error ? restoreError.message : String(restoreError);
        }
      }
      const writeFailureMessage = renameError instanceof Error ? renameError.message : String(renameError);
      if (restoreFailedMessage) {
        throw new Error(
          `Failed to write file: ${writeFailureMessage}. Automatic restore failed: ${restoreFailedMessage}. Manual recovery may be required using backup file '${backupPath}'.`
        );
      }
      if (backupExisted) {
        throw new Error(
          `Failed to write file: ${writeFailureMessage}. Target was automatically restored from backup '${backupPath}'.`
        );
      }
      throw new Error(
        `Failed to write file: ${writeFailureMessage}. No backup file was available for restoration.`
      );
    }
  } catch (error40) {
    try {
      if (fs106.existsSync(tempPath)) {
        fs106.unlinkSync(tempPath);
      }
    } catch (_e2) {
    }
    throw error40;
  }
}
__name(writeWithBackupSync, "writeWithBackupSync");

// packages/cli/src/config/settings.ts
var debugLogger106 = createDebugLogger("SETTINGS");
function getMergeStrategyForPath(path150) {
  let current = void 0;
  let currentSchema = getSettingsSchema();
  for (const key of path150) {
    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 = path100.dirname(USER_SETTINGS_PATH);
var DEFAULT_EXCLUDED_ENV_VARS = ["DEBUG", "DEBUG_MODE"];
var SETTINGS_VERSION = 3;
var SETTINGS_VERSION_KEY = "$version";
function getSystemSettingsPath() {
  if (process26.env["QWEN_CODE_SYSTEM_SETTINGS_PATH"]) {
    return process26.env["QWEN_CODE_SYSTEM_SETTINGS_PATH"];
  }
  if (platform12() === "darwin") {
    return "/Library/Application Support/QwenCode/settings.json";
  } else if (platform12() === "win32") {
    return "C:\\ProgramData\\qwen-code\\settings.json";
  } else {
    return "/etc/qwen-code/settings.json";
  }
}
__name(getSystemSettingsPath, "getSystemSettingsPath");
function getSystemDefaultsPath() {
  if (process26.env["QWEN_CODE_SYSTEM_DEFAULTS_PATH"]) {
    return process26.env["QWEN_CODE_SYSTEM_DEFAULTS_PATH"];
  }
  return path100.join(
    path100.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 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(V1_TO_V2_MIGRATION_MAP)) {
    if (oldKey === newPath) {
      continue;
    }
    if (!(oldKey in settings)) {
      continue;
    }
    const oldValue = settings[oldKey];
    if (V2_CONTAINER_KEYS.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;
    }
    debugLogger106.warn(
      `Unknown setting '${key}' will be ignored in ${settingsFilePath}.`
    );
  }
  return warnings;
}
__name(getSettingsFileKeyWarnings, "getSettingsFileKeyWarnings");
function isPlainObject6(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
__name(isPlainObject6, "isPlainObject");
function hasAnyProviderEntries(modelProviders) {
  if (!isPlainObject6(modelProviders)) {
    return false;
  }
  return Object.values(modelProviders).some(
    (providerModels) => Array.isArray(providerModels) && providerModels.length > 0
  );
}
__name(hasAnyProviderEntries, "hasAnyProviderEntries");
function getModelProvidersOverrideWarnings(loadedSettings) {
  if (!loadedSettings.isTrusted) {
    return [];
  }
  const userOriginal = loadedSettings.user.originalSettings;
  const workspaceOriginal = loadedSettings.workspace.originalSettings;
  if (!hasOwnModelProviders(userOriginal) || !hasOwnModelProviders(workspaceOriginal)) {
    return [];
  }
  const userModelProviders = userOriginal["modelProviders"];
  const workspaceModelProviders = workspaceOriginal["modelProviders"];
  const workspaceIsEmptyModelProviders = isPlainObject6(workspaceModelProviders) && Object.keys(workspaceModelProviders).length === 0;
  if (!workspaceIsEmptyModelProviders || !hasAnyProviderEntries(userModelProviders)) {
    return [];
  }
  return [
    `Warning: '${loadedSettings.workspace.path}' defines an empty 'modelProviders' object. This has no effect with current merge behavior, but may indicate a configuration error. If REPLACE semantics are introduced for 'modelProviders' in the future, this would override user-level model providers in '${loadedSettings.user.path}'.`
  ];
}
__name(getModelProvidersOverrideWarnings, "getModelProvidersOverrideWarnings");
function getSettingsWarnings(loadedSettings) {
  const warningSet = /* @__PURE__ */ new Set();
  for (const warning of loadedSettings.migrationWarnings) {
    warningSet.add(`Warning: ${warning}`);
  }
  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);
    }
  }
  for (const warning of getModelProvidersOverrideWarnings(loadedSettings)) {
    warningSet.add(warning);
  }
  return [...warningSet];
}
__name(getSettingsWarnings, "getSettingsWarnings");
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, migrationWarnings = []) {
    this.system = system;
    this.systemDefaults = systemDefaults;
    this.user = user;
    this.workspace = workspace;
    this.isTrusted = isTrusted;
    this.migratedInMemorScopes = migratedInMemorScopes;
    this.migrationWarnings = migrationWarnings;
    this._merged = this.computeMergedSettings();
  }
  system;
  systemDefaults;
  user;
  workspace;
  isTrusted;
  migratedInMemorScopes;
  migrationWarnings;
  _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);
    setNestedPropertySafe(settingsFile.settings, key, value);
    setNestedPropertySafe(settingsFile.originalSettings, key, value);
    this._merged = this.computeMergedSettings();
    saveSettings(settingsFile, createSettingsUpdate(key, value));
  }
  /**
   * Get user-level hooks from user settings (not merged with workspace).
   * These hooks should always be loaded regardless of folder trust.
   */
  getUserHooks() {
    return this.user.settings.hooks;
  }
  /**
   * Get project-level hooks from workspace settings (not merged).
   * Returns undefined if workspace is not trusted (hooks filtered out).
   */
  getProjectHooks() {
    if (!this.isTrusted) {
      return void 0;
    }
    return this.workspace.settings.hooks;
  }
};
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 = homedir20();
  const isTrusted = isWorkspaceTrusted(settings).isTrusted;
  const userLevelPaths = /* @__PURE__ */ new Set([
    path100.normalize(path100.join(homeDir, ".env")),
    path100.normalize(path100.join(homeDir, QWEN_DIR, ".env"))
  ]);
  const canUseEnvFile = /* @__PURE__ */ __name((filePath) => isTrusted !== false || userLevelPaths.has(path100.normalize(filePath)), "canUseEnvFile");
  let currentDir = path100.resolve(startDir);
  while (true) {
    const geminiEnvPath = path100.join(currentDir, QWEN_DIR, ".env");
    if (fs107.existsSync(geminiEnvPath) && canUseEnvFile(geminiEnvPath)) {
      return geminiEnvPath;
    }
    const envPath = path100.join(currentDir, ".env");
    if (fs107.existsSync(envPath) && canUseEnvFile(envPath)) {
      return envPath;
    }
    const parentDir = path100.dirname(currentDir);
    if (parentDir === currentDir || !parentDir) {
      const homeGeminiEnvPath = path100.join(homeDir, QWEN_DIR, ".env");
      if (fs107.existsSync(homeGeminiEnvPath)) {
        return homeGeminiEnvPath;
      }
      const homeEnvPath = path100.join(homeDir, ".env");
      if (fs107.existsSync(homeEnvPath)) {
        return homeEnvPath;
      }
      return null;
    }
    currentDir = parentDir;
  }
}
__name(findEnvFile, "findEnvFile");
function setUpCloudShellEnvironment(envFilePath) {
  if (envFilePath && fs107.existsSync(envFilePath)) {
    const envFileContent = fs107.readFileSync(envFilePath);
    const parsedEnv = dotenv2.parse(envFileContent);
    if (parsedEnv["GOOGLE_CLOUD_PROJECT"]) {
      process26.env["GOOGLE_CLOUD_PROJECT"] = parsedEnv["GOOGLE_CLOUD_PROJECT"];
    } else {
      process26.env["GOOGLE_CLOUD_PROJECT"] = "cloudshell-gca";
    }
  } else {
    process26.env["GOOGLE_CLOUD_PROJECT"] = "cloudshell-gca";
  }
}
__name(setUpCloudShellEnvironment, "setUpCloudShellEnvironment");
function loadEnvironment(settings) {
  const envFilePath = findEnvFile(settings, process26.cwd());
  if (process26.env["CLOUD_SHELL"] === "true") {
    setUpCloudShellEnvironment(envFilePath);
  }
  if (envFilePath) {
    try {
      const envFileContent = fs107.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(process26.env, key)) {
            process26.env[key] = parsedEnv[key];
          }
        }
      }
    } catch (_e2) {
    }
  }
  if (settings.env) {
    for (const [key, value] of Object.entries(settings.env)) {
      if (!Object.hasOwn(process26.env, key) && typeof value === "string") {
        process26.env[key] = value;
      }
    }
  }
}
__name(loadEnvironment, "loadEnvironment");
function loadSettings(workspaceDir = process26.cwd()) {
  let systemSettings = {};
  let systemDefaultSettings = {};
  let userSettings = {};
  let workspaceSettings = {};
  const settingsErrors = [];
  const systemSettingsPath = getSystemSettingsPath();
  const systemDefaultsPath = getSystemDefaultsPath();
  const migratedInMemorScopes = /* @__PURE__ */ new Set();
  const resolvedWorkspaceDir = path100.resolve(workspaceDir);
  const resolvedHomeDir = path100.resolve(homedir20());
  let realWorkspaceDir = resolvedWorkspaceDir;
  try {
    realWorkspaceDir = fs107.realpathSync(resolvedWorkspaceDir);
  } catch (_e2) {
  }
  const realHomeDir = fs107.realpathSync(resolvedHomeDir);
  const workspaceSettingsPath = new Storage(
    workspaceDir
  ).getWorkspaceSettingsPath();
  const loadAndMigrate = /* @__PURE__ */ __name((filePath, scope) => {
    try {
      if (fs107.existsSync(filePath)) {
        let content = fs107.readFileSync(filePath, "utf-8");
        let rawSettings;
        let recoveryWarning;
        try {
          rawSettings = JSON.parse((0, import_strip_json_comments2.default)(content));
        } catch (parseError) {
          const backupPath = `${filePath}.orig`;
          if (fs107.existsSync(backupPath)) {
            debugLogger106.warn(
              `Settings file ${filePath} has invalid JSON (${getErrorMessage(parseError)}). Attempting recovery from backup ${backupPath}.`
            );
            try {
              const backupContent = fs107.readFileSync(backupPath, "utf-8");
              const backupSettings = JSON.parse(
                (0, import_strip_json_comments2.default)(backupContent)
              );
              fs107.writeFileSync(filePath, backupContent, "utf-8");
              content = backupContent;
              rawSettings = backupSettings;
              const recoveryMsg = `Settings file ${filePath} had invalid JSON and was recovered from backup ${backupPath}. Some recent settings changes may have been lost.`;
              debugLogger106.warn(recoveryMsg);
              recoveryWarning = recoveryMsg;
            } catch (backupError) {
              debugLogger106.warn(
                `Failed to recover from backup ${backupPath}: ${getErrorMessage(backupError)}. Falling back to empty settings.`
              );
            }
          }
          if (!rawSettings) {
            const corruptedPath = `${filePath}.corrupted.${Date.now()}`;
            let warningMsg;
            try {
              fs107.renameSync(filePath, corruptedPath);
              warningMsg = `Settings file ${filePath} has invalid JSON and was renamed to ${corruptedPath}. Your settings have been reset. To recover, fix the JSON in ${corruptedPath} and rename it back.`;
            } catch (renameError) {
              debugLogger106.error(
                `Failed to rename corrupted settings file: ${getErrorMessage(renameError)}`
              );
              warningMsg = `Settings file ${filePath} has invalid JSON. Your settings have been reset. Please fix the JSON in ${filePath} manually.`;
            }
            debugLogger106.warn(warningMsg);
            return {
              settings: {},
              migrationWarnings: [warningMsg]
            };
          }
        }
        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;
        const hasVersionKey = SETTINGS_VERSION_KEY in settingsObject;
        const versionValue = settingsObject[SETTINGS_VERSION_KEY];
        const hasInvalidVersion = hasVersionKey && typeof versionValue !== "number";
        const hasLegacyNumericVersion = typeof versionValue === "number" && versionValue < SETTINGS_VERSION;
        let migrationWarnings;
        const persistSettingsObject = /* @__PURE__ */ __name((warningPrefix) => {
          try {
            writeWithBackupSync(
              filePath,
              JSON.stringify(settingsObject, null, 2)
            );
          } catch (e4) {
            debugLogger106.error(`${warningPrefix}: ${getErrorMessage(e4)}`);
          }
        }, "persistSettingsObject");
        if (needsMigration(settingsObject)) {
          const migrationResult = runMigrations(settingsObject, scope);
          if (migrationResult.executedMigrations.length > 0) {
            settingsObject = migrationResult.settings;
            migrationWarnings = migrationResult.warnings;
            persistSettingsObject("Error migrating settings file on disk");
          } else if (hasLegacyNumericVersion || hasInvalidVersion) {
            settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
            debugLogger106.warn(
              `Settings version metadata in ${filePath} could not be migrated by any registered migration. Normalizing ${SETTINGS_VERSION_KEY} to ${SETTINGS_VERSION}.`
            );
            persistSettingsObject("Error normalizing settings version on disk");
          }
        } else if (!hasVersionKey || hasInvalidVersion || hasLegacyNumericVersion) {
          settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
          persistSettingsObject("Error normalizing settings version on disk");
        }
        const allWarnings = [
          ...recoveryWarning ? [recoveryWarning] : [],
          ...migrationWarnings ?? []
        ];
        return {
          settings: settingsObject,
          rawJson: content,
          migrationWarnings: allWarnings.length > 0 ? allWarnings : migrationWarnings
        };
      }
    } catch (error40) {
      settingsErrors.push({
        message: getErrorMessage(error40),
        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(
      (error40) => `Error in ${error40.path}: ${error40.message}`
    );
    throw new FatalConfigError(
      `${errorMessages.join("\n")}
Please fix the configuration file(s) and try again.`
    );
  }
  const allMigrationWarnings = [
    ...systemResult.migrationWarnings ?? [],
    ...systemDefaultsResult.migrationWarnings ?? [],
    ...userResult.migrationWarnings ?? [],
    ...workspaceResult.migrationWarnings ?? []
  ];
  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,
    allMigrationWarnings
  );
}
__name(loadSettings, "loadSettings");
function createSettingsUpdate(key, value) {
  const root = {};
  setNestedPropertySafe(root, key, value);
  return root;
}
__name(createSettingsUpdate, "createSettingsUpdate");
function saveSettings(settingsFile, updates = settingsFile.originalSettings) {
  try {
    const dirPath = path100.dirname(settingsFile.path);
    if (!fs107.existsSync(dirPath)) {
      fs107.mkdirSync(dirPath, { recursive: true });
    }
    updateSettingsFilePreservingFormat(settingsFile.path, updates);
  } catch (error40) {
    debugLogger106.error("Error saving user settings file.");
    debugLogger106.error(error40 instanceof Error ? error40.message : String(error40));
    throw error40;
  }
}
__name(saveSettings, "saveSettings");

// packages/cli/src/config/auth.ts
init_i18n();
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);
  const resolvedApiKey = config2?.getModelsConfig().getGenerationConfig()?.apiKey;
  if (resolvedApiKey) {
    return {
      hasKey: true,
      checkedEnvKey: modelConfig?.envKey ?? DEFAULT_ENV_KEYS[authType],
      isExplicitEnvKey: !!modelConfig?.envKey
    };
  }
  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 t4(
      "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider."
    );
  }
  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();
init_dist4();

// packages/cli/src/commands/extensions.tsx
init_esbuild_shims();

// packages/cli/src/commands/extensions/install.ts
init_esbuild_shims();
init_dist4();

// packages/cli/src/utils/errors.ts
init_esbuild_shims();
init_dist4();

// packages/cli/src/utils/cleanup.ts
init_esbuild_shims();
init_dist4();
import { promises as fs108 } from "node:fs";
import { join as join50 } from "node:path";
var cleanupFunctions = [];
function registerCleanup(fn) {
  cleanupFunctions.push(fn);
}
__name(registerCleanup, "registerCleanup");
var PER_CLEANUP_TIMEOUT_MS = 2e3;
var OVERALL_CLEANUP_TIMEOUT_MS = 5e3;
function withTimeout(promise2, ms) {
  return new Promise((resolve42) => {
    const timer = setTimeout(() => resolve42(void 0), ms);
    timer.unref?.();
    promise2.then(
      (value) => {
        clearTimeout(timer);
        resolve42(value);
      },
      () => {
        clearTimeout(timer);
        resolve42(void 0);
      }
    );
  });
}
__name(withTimeout, "withTimeout");
async function runExitCleanup(options2 = {}) {
  const perFn = options2._testPerFnTimeoutMs ?? PER_CLEANUP_TIMEOUT_MS;
  const overall = options2._testOverallTimeoutMs ?? OVERALL_CLEANUP_TIMEOUT_MS;
  const drain = (async () => {
    for (const fn of cleanupFunctions) {
      try {
        await withTimeout(Promise.resolve().then(fn), perFn);
      } catch (_2) {
      }
    }
  })();
  let wallClockTimer;
  const wallClock = new Promise((resolve42) => {
    wallClockTimer = setTimeout(() => resolve42(), overall);
    wallClockTimer.unref?.();
  });
  try {
    await Promise.race([drain, wallClock]);
  } finally {
    if (wallClockTimer) clearTimeout(wallClockTimer);
    cleanupFunctions.length = 0;
  }
}
__name(runExitCleanup, "runExitCleanup");
async function cleanupCheckpoints() {
  const storage = new Storage(process.cwd());
  const tempDir = storage.getProjectTempDir();
  const checkpointsDir = join50(tempDir, "checkpoints");
  try {
    await fs108.rm(checkpointsDir, { recursive: true, force: true });
  } catch {
  }
}
__name(cleanupCheckpoints, "cleanupCheckpoints");

// packages/cli/src/utils/errors.ts
init_stdioHelpers();
var debugLogger107 = createDebugLogger("CLI_ERRORS");
function getErrorMessage4(error40) {
  if (error40 instanceof Error) {
    return error40.message;
  }
  if (error40 !== null && typeof error40 === "object" && "message" in error40 && typeof error40.message === "string") {
    return error40.message;
  }
  if (error40 !== null && typeof error40 === "object") {
    try {
      const stringified = JSON.stringify(error40);
      return stringified ?? String(error40);
    } catch {
      return String(error40);
    }
  }
  return String(error40);
}
__name(getErrorMessage4, "getErrorMessage");
function extractErrorCode(error40) {
  const errorWithCode = error40;
  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");
var exiting = false;
async function exitAfterCleanup(code2) {
  if (exiting) return new Promise(() => {
  });
  exiting = true;
  await runExitCleanup();
  return process.exit(code2);
}
__name(exitAfterCleanup, "exitAfterCleanup");
async function handleError(error40, config2, customErrorCode) {
  const errorMessage = parseAndFormatApiError(
    error40,
    config2.getContentGeneratorConfig()?.authType
  );
  if (config2.getOutputFormat() === OutputFormat.JSON) {
    const formatter = new JsonFormatter();
    const errorCode = customErrorCode ?? extractErrorCode(error40);
    const formattedError = formatter.formatError(
      error40 instanceof Error ? error40 : new Error(getErrorMessage4(error40)),
      errorCode
    );
    writeStderrLine(formattedError);
    return exitAfterCleanup(getNumericExitCode(errorCode));
  } else {
    writeStderrLine(errorMessage);
    await runExitCleanup();
    throw error40;
  }
}
__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);
  }
  debugLogger107.error(
    `Error executing tool ${toolName}: ${resultDisplay || toolError.message}`
  );
}
__name(handleToolError, "handleToolError");
async 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);
  } else {
    writeStderrLine(cancellationError.message);
  }
  return exitAfterCleanup(cancellationError.exitCode);
}
__name(handleCancellationError, "handleCancellationError");
async 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);
  } else {
    writeStderrLine(maxTurnsError.message);
  }
  return exitAfterCleanup(maxTurnsError.exitCode);
}
__name(handleMaxTurnsExceededError, "handleMaxTurnsExceededError");

// packages/cli/src/commands/extensions/install.ts
init_stdioHelpers();

// packages/cli/src/commands/extensions/consent.ts
init_esbuild_shims();
var import_chalk4 = __toESM(require_source(), 1);
var import_prompts6 = __toESM(require_prompts3(), 1);
init_i18n();
init_stdioHelpers();
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((plugin4) => ({
    title: import_chalk4.default.green(import_chalk4.default.bold(`[${plugin4.name}]`)),
    value: plugin4.name
  }));
  const response = await (0, import_prompts6.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((resolve42) => {
    rl.question(prompt, (answer) => {
      rl.close();
      resolve42(["y", ""].includes(answer.trim().toLowerCase()));
    });
  });
}
__name(promptForConsentNonInteractive, "promptForConsentNonInteractive");
async function promptForConsentInteractive(prompt, addExtensionUpdateConfirmationRequest) {
  return new Promise((resolve42) => {
    addExtensionUpdateConfirmationRequest({
      prompt,
      onConfirm: /* @__PURE__ */ __name((resolvedConfirmed) => {
        resolve42(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
init_i18n();
async function handleInstall(args2) {
  try {
    const installMetadata = await parseInstallSource(args2.source);
    if (installMetadata.type !== "git" && installMetadata.type !== "github-release" && installMetadata.type !== "npm") {
      if (args2.ref || args2.autoUpdate) {
        throw new Error(
          t4(
            "--ref and --auto-update are not applicable for marketplace extensions."
          )
        );
      }
    }
    if (installMetadata.type === "npm" && args2.ref) {
      throw new Error(
        t4(
          "--ref is not applicable for npm extensions. Use @version suffix instead (e.g. @scope/package@1.2.0)."
        )
      );
    }
    if (installMetadata.type !== "npm" && args2.registry) {
      throw new Error(t4("--registry is only applicable for npm extensions."));
    }
    if (installMetadata.type === "npm" && args2.registry) {
      installMetadata.registryUrl = args2.registry;
    }
    const requestConsent = args2.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: args2.ref,
        autoUpdate: args2.autoUpdate,
        allowPreRelease: args2.allowPreRelease
      },
      requestConsent
    );
    writeStdoutLine(
      t4('Extension "{{name}}" installed successfully and enabled.', {
        name: extension.name
      })
    );
  } catch (error40) {
    writeStderrLine(getErrorMessage4(error40));
    process.exit(1);
  }
}
__name(handleInstall, "handleInstall");
var installCommand = {
  command: "install <source>",
  describe: t4(
    "Installs an extension from a git repository URL, local path, scoped npm package (@scope/name), 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("registry", {
    describe: t4("Custom npm registry URL (only for npm extensions)."),
    type: "string"
  }).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"],
      registry: argv["registry"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions/uninstall.ts
init_esbuild_shims();
init_stdioHelpers();
init_dist4();
init_i18n();
async function handleUninstall(args2) {
  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(args2.name, false);
    writeStdoutLine(
      t4('Extension "{{name}}" successfully uninstalled.', { name: args2.name })
    );
  } catch (error40) {
    writeStderrLine(getErrorMessage4(error40));
    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();
init_stdioHelpers();

// packages/cli/src/commands/extensions/utils.ts
init_esbuild_shims();
init_dist4();
var import_chalk5 = __toESM(require_source(), 1);
init_i18n();
import * as os33 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 cwd6 = workspaceDir;
  const userEnabled = extensionManager.isEnabled(
    extension.config.name,
    os33.homedir()
  );
  const workspaceEnabled = extensionManager.isEnabled(
    extension.config.name,
    cwd6
  );
  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
init_i18n();
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 (error40) {
    writeStderrLine(getErrorMessage4(error40));
    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();
init_stdioHelpers();

// 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
init_dist4();
init_i18n();
var updateOutput = /* @__PURE__ */ __name((info2) => t4(
  'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.',
  {
    name: info2.name,
    oldVersion: info2.originalVersion,
    newVersion: info2.updatedVersion
  }
), "updateOutput");
async function handleUpdate(args2) {
  const extensionManager = await getExtensionManager();
  const extensions = extensionManager.getLoadedExtensions();
  if (args2.name) {
    try {
      const extension = extensions.find(
        (extension2) => extension2.name === args2.name
      );
      if (!extension) {
        writeStdoutLine(
          t4('Extension "{{name}}" not found.', { name: args2.name })
        );
        return;
      }
      if (!extension.installMetadata) {
        writeStdoutLine(
          t4(
            'Unable to install extension "{{name}}" due to missing install metadata',
            { name: args2.name }
          )
        );
        return;
      }
      const updateState = await checkForExtensionUpdate(
        extension,
        extensionManager
      );
      if (updateState !== "update available" /* UPDATE_AVAILABLE */) {
        writeStdoutLine(
          t4('Extension "{{name}}" is already up to date.', { name: args2.name })
        );
        return;
      }
      const updatedExtensionInfo = await extensionManager.updateExtension(
        extension,
        updateState,
        () => {
        }
      );
      if (updatedExtensionInfo.originalVersion !== updatedExtensionInfo.updatedVersion) {
        writeStdoutLine(
          t4(
            'Extension "{{name}}" successfully updated: {{oldVersion}} \u2192 {{newVersion}}.',
            {
              name: args2.name,
              oldVersion: updatedExtensionInfo.originalVersion,
              newVersion: updatedExtensionInfo.updatedVersion
            }
          )
        );
      } else {
        writeStdoutLine(
          t4('Extension "{{name}}" is already up to date.', { name: args2.name })
        );
      }
    } catch (error40) {
      writeStderrLine(getErrorMessage4(error40));
    }
  }
  if (args2.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(
        (info2) => info2.originalVersion !== info2.updatedVersion
      );
      if (updateInfos.length === 0) {
        writeStdoutLine(t4("No extensions to update."));
        return;
      }
      writeStdoutLine(updateInfos.map((info2) => updateOutput(info2)).join("\n"));
    } catch (error40) {
      writeStderrLine(getErrorMessage4(error40));
    }
  }
}
__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(...args2) {
    const cols = this.div(...args2);
    cols.span = true;
  }
  resetOutput() {
    this.rows = [];
  }
  div(...args2) {
    if (args2.length === 0) {
      this.div("");
    }
    if (this.wrap && this.shouldApplyLayoutDSL(...args2) && typeof args2[0] === "string") {
      return this.applyLayoutDSL(args2[0]);
    }
    const cols = args2.map((arg) => {
      if (typeof arg === "string") {
        return this.colFromString(arg);
      }
      return arg;
    });
    this.rows.push(cols);
    return cols;
  }
  shouldApplyLayoutDSL(...args2) {
    return args2.length === 1 && typeof args2[0] === "string" && /[\t\n]/.test(args2[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, i4) => {
        return {
          text: r5.trim(),
          padding: this.measurePadding(r5),
          width: i4 === 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 i4 = 0; i4 < c4; i4++) {
          if (rrow[i4] === 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, i4) => {
      if (w2 === void 0) {
        return Math.max(unsetWidth, _minWidth(row[i4]));
      }
      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 stripAnsi3(str2) {
  return str2.replace(ansi, "");
}
__name(stripAnsi3, "stripAnsi");
function wrap(str2, width) {
  const [start2, end] = str2.match(ansi) || ["", ""];
  str2 = stripAnsi3(str2);
  let wrapped = "";
  for (let i4 = 0; i4 < str2.length; i4++) {
    if (i4 !== 0 && i4 % width === 0) {
      wrapped += "\n";
    }
    wrapped += str2.charAt(i4);
  }
  if (start2 && end) {
    wrapped = `${start2}${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: stripAnsi3,
    wrap
  });
}
__name(ui, "ui");

// node_modules/escalade/sync/index.mjs
init_esbuild_shims();
import { dirname as dirname28, resolve as resolve30 } from "path";
import { readdirSync as readdirSync4, statSync as statSync9 } from "fs";
function sync_default(start2, callback) {
  let dir = resolve30(".", start2);
  let tmp, stats = statSync9(dir);
  if (!stats.isDirectory()) {
    dir = dirname28(dir);
  }
  while (true) {
    tmp = callback(dir, readdirSync4(dir));
    if (tmp) return resolve30(dir, tmp);
    dir = dirname28(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 readFileSync22 } from "fs";
import { fileURLToPath as fileURLToPath11 } from "url";

// node_modules/yargs-parser/build/lib/index.js
init_esbuild_shims();
import { format } from "util";
import { normalize as normalize10, resolve as resolve31 } 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 i4 = leadingHyphens ? leadingHyphens[0].length : 0; i4 < str2.length; i4++) {
      let chr = str2.charAt(i4);
      if (nextChrUpper) {
        nextChrUpper = false;
        chr = chr.toUpperCase();
      }
      if (i4 !== 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 i4 = 0; i4 < str2.length; i4++) {
    const chrLower = lowercase2.charAt(i4);
    const chrString = str2.charAt(i4);
    if (chrLower !== chrString && i4 > 0) {
      notCamelcase += `${joinString}${lowercase2.charAt(i4)}`;
    } 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 i4 = 0;
  let prevC = null;
  let c4 = null;
  let opening = null;
  const args2 = [];
  for (let ii = 0; ii < argString.length; ii++) {
    prevC = c4;
    c4 = argString.charAt(ii);
    if (c4 === " " && !opening) {
      if (!(prevC === " ")) {
        i4++;
      }
      continue;
    }
    if (c4 === opening) {
      opening = null;
    } else if ((c4 === "'" || c4 === '"') && !opening) {
      opening = c4;
    }
    if (!args2[i4])
      args2[i4] = "";
    args2[i4] += c4;
  }
  return args2;
}
__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 args2 = 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 defaults4 = 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 flags2 = {
      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) {
        flags2[assignment][key] = true;
      }
      flags2.arrays[key] = true;
      flags2.keys.push(key);
    });
    [].concat(opts.boolean || []).filter(Boolean).forEach(function(key) {
      flags2.bools[key] = true;
      flags2.keys.push(key);
    });
    [].concat(opts.string || []).filter(Boolean).forEach(function(key) {
      flags2.strings[key] = true;
      flags2.keys.push(key);
    });
    [].concat(opts.number || []).filter(Boolean).forEach(function(key) {
      flags2.numbers[key] = true;
      flags2.keys.push(key);
    });
    [].concat(opts.count || []).filter(Boolean).forEach(function(key) {
      flags2.counts[key] = true;
      flags2.keys.push(key);
    });
    [].concat(opts.normalize || []).filter(Boolean).forEach(function(key) {
      flags2.normalize[key] = true;
      flags2.keys.push(key);
    });
    if (typeof opts.narg === "object") {
      Object.entries(opts.narg).forEach(([key, value]) => {
        if (typeof value === "number") {
          flags2.nargs[key] = value;
          flags2.keys.push(key);
        }
      });
    }
    if (typeof opts.coerce === "object") {
      Object.entries(opts.coerce).forEach(([key, value]) => {
        if (typeof value === "function") {
          flags2.coercions[key] = value;
          flags2.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) {
          flags2.configs[key] = true;
        });
      } else if (typeof opts.config === "object") {
        Object.entries(opts.config).forEach(([key, value]) => {
          if (typeof value === "boolean" || typeof value === "function") {
            flags2.configs[key] = value;
          }
        });
      }
    }
    extendAliases(opts.key, aliases, opts.default, flags2.arrays);
    Object.keys(defaults4).forEach(function(key) {
      (flags2.aliases[key] || []).forEach(function(alias) {
        defaults4[alias] = defaults4[key];
      });
    });
    let error40 = null;
    checkConfiguration();
    let notFlags = [];
    const argv = Object.assign(/* @__PURE__ */ Object.create(null), { _: [] });
    const argvReturn = {};
    for (let i4 = 0; i4 < args2.length; i4++) {
      const arg = args2[i4];
      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], flags2.arrays)) {
            i4 = eatArray(i4, m3[1], args2, m3[2]);
          } else if (checkAllAliases(m3[1], flags2.nargs) !== false) {
            i4 = eatNargs(i4, m3[1], args2, 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, flags2.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, flags2.arrays)) {
            i4 = eatArray(i4, key, args2);
          } else if (checkAllAliases(key, flags2.nargs) !== false) {
            i4 = eatNargs(i4, key, args2);
          } else {
            next = args2[i4 + 1];
            if (next !== void 0 && (!next.match(/^-/) || next.match(negative)) && !checkAllAliases(key, flags2.bools) && !checkAllAliases(key, flags2.counts)) {
              setArg(key, next);
              i4++;
            } else if (/^(true|false)$/.test(next)) {
              setArg(key, next);
              i4++;
            } 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 = args2[i4 + 1];
        m3 = arg.match(/^-(.\..+)/);
        if (m3 !== null && Array.isArray(m3) && m3.length >= 2) {
          key = m3[1];
          if (next !== void 0 && !next.match(/^-/) && !checkAllAliases(key, flags2.bools) && !checkAllAliases(key, flags2.counts)) {
            setArg(key, next);
            i4++;
          } 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, flags2.arrays)) {
              i4 = eatArray(i4, key, args2, value);
            } else if (checkAllAliases(key, flags2.nargs) !== false) {
              i4 = eatNargs(i4, key, args2, 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, flags2.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, flags2.arrays)) {
            i4 = eatArray(i4, key, args2);
          } else if (checkAllAliases(key, flags2.nargs) !== false) {
            i4 = eatNargs(i4, key, args2);
          } else {
            next = args2[i4 + 1];
            if (next !== void 0 && (!/^(-|--)[^-]/.test(next) || next.match(negative)) && !checkAllAliases(key, flags2.bools) && !checkAllAliases(key, flags2.counts)) {
              setArg(key, next);
              i4++;
            } else if (/^(true|false)$/.test(next)) {
              setArg(key, next);
              i4++;
            } else {
              setArg(key, defaultValue(key));
            }
          }
        }
      } else if (arg.match(/^-[0-9]$/) && arg.match(negative) && checkAllAliases(arg.slice(1), flags2.bools)) {
        key = arg.slice(1);
        setArg(key, defaultValue(key));
      } else if (arg === "--") {
        notFlags = args2.slice(i4 + 1);
        break;
      } else if (configuration["halt-at-non-option"]) {
        notFlags = args2.slice(i4);
        break;
      } else {
        pushPositional(arg);
      }
    }
    applyEnvVars(argv, true);
    applyEnvVars(argv, false);
    setConfig(argv);
    setConfigObjects();
    applyDefaultsAndAliases(argv, flags2.aliases, defaults4, true);
    applyCoercions(argv);
    if (configuration["set-placeholder-key"])
      setPlaceholderKeys(argv);
    Object.keys(flags2.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(i4, key, args3, argAfterEqualSign) {
      let ii;
      let toEat = checkAllAliases(key, flags2.nargs);
      toEat = typeof toEat !== "number" || isNaN(toEat) ? 1 : toEat;
      if (toEat === 0) {
        if (!isUndefined3(argAfterEqualSign)) {
          error40 = Error(__("Argument unexpected for: %s", key));
        }
        setArg(key, defaultValue(key));
        return i4;
      }
      let available = isUndefined3(argAfterEqualSign) ? 0 : 1;
      if (configuration["nargs-eats-options"]) {
        if (args3.length - (i4 + 1) + available < toEat) {
          error40 = Error(__("Not enough arguments following: %s", key));
        }
        available = toEat;
      } else {
        for (ii = i4 + 1; ii < args3.length; ii++) {
          if (!args3[ii].match(/^-[^0-9]/) || args3[ii].match(negative) || isUnknownOptionAsArg(args3[ii]))
            available++;
          else
            break;
        }
        if (available < toEat)
          error40 = Error(__("Not enough arguments following: %s", key));
      }
      let consumed = Math.min(available, toEat);
      if (!isUndefined3(argAfterEqualSign) && consumed > 0) {
        setArg(key, argAfterEqualSign);
        consumed--;
      }
      for (ii = i4 + 1; ii < consumed + i4 + 1; ii++) {
        setArg(key, args3[ii]);
      }
      return i4 + consumed;
    }
    __name(eatNargs, "eatNargs");
    function eatArray(i4, key, args3, argAfterEqualSign) {
      let argsToSet = [];
      let next = argAfterEqualSign || args3[i4 + 1];
      const nargsCount = checkAllAliases(key, flags2.nargs);
      if (checkAllAliases(key, flags2.bools) && !/^(true|false)$/.test(next)) {
        argsToSet.push(true);
      } else if (isUndefined3(next) || isUndefined3(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) {
        if (defaults4[key] !== void 0) {
          const defVal = defaults4[key];
          argsToSet = Array.isArray(defVal) ? defVal : [defVal];
        }
      } else {
        if (!isUndefined3(argAfterEqualSign)) {
          argsToSet.push(processValue(key, argAfterEqualSign, true));
        }
        for (let ii = i4 + 1; ii < args3.length; ii++) {
          if (!configuration["greedy-arrays"] && argsToSet.length > 0 || nargsCount && typeof nargsCount === "number" && argsToSet.length >= nargsCount)
            break;
          next = args3[ii];
          if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
            break;
          i4 = ii;
          argsToSet.push(processValue(key, next, inputIsString));
        }
      }
      if (typeof nargsCount === "number" && (nargsCount && argsToSet.length < nargsCount || isNaN(nargsCount) && argsToSet.length === 0)) {
        error40 = Error(__("Not enough arguments following: %s", key));
      }
      setArg(key, argsToSet);
      return i4;
    }
    __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 (flags2.aliases[key]) {
        flags2.aliases[key].forEach(function(x3) {
          const keyProperties = x3.split(".");
          setKey(argv, keyProperties, value);
        });
      }
      if (splitKey.length > 1 && configuration["dot-notation"]) {
        ;
        (flags2.aliases[splitKey[0]] || []).forEach(function(x3) {
          let keyProperties = x3.split(".");
          const a2 = [].concat(splitKey);
          a2.shift();
          keyProperties = keyProperties.concat(a2);
          if (!(flags2.aliases[key] || []).includes(keyProperties.join("."))) {
            setKey(argv, keyProperties, value);
          }
        });
      }
      if (checkAllAliases(key, flags2.normalize) && !checkAllAliases(key, flags2.arrays)) {
        const keys = [key].concat(flags2.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 (!(flags2.aliases[key] && flags2.aliases[key].length)) {
        flags2.aliases[key] = [alias];
        newAliases[alias] = true;
      }
      if (!(flags2.aliases[alias] && flags2.aliases[alias].length)) {
        addNewAlias(alias, key);
      }
    }
    __name(addNewAlias, "addNewAlias");
    function processValue(key, val, shouldStripQuotes) {
      if (shouldStripQuotes) {
        val = stripQuotes(val);
      }
      if (checkAllAliases(key, flags2.bools) || checkAllAliases(key, flags2.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, flags2.counts) && (isUndefined3(value) || typeof value === "boolean")) {
        value = increment();
      }
      if (checkAllAliases(key, flags2.normalize) && checkAllAliases(key, flags2.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, flags2.strings) && !checkAllAliases(key, flags2.bools) && !Array.isArray(value)) {
        const shouldCoerceNumber = looksLikeNumber(value) && configuration["parse-numbers"] && Number.isSafeInteger(Math.floor(parseFloat(`${value}`)));
        if (shouldCoerceNumber || !isUndefined3(value) && checkAllAliases(key, flags2.numbers)) {
          value = Number(value);
        }
      }
      return value;
    }
    __name(maybeCoerceNumber, "maybeCoerceNumber");
    function setConfig(argv2) {
      const configLookup = /* @__PURE__ */ Object.create(null);
      applyDefaultsAndAliases(configLookup, flags2.aliases, defaults4);
      Object.keys(flags2.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 = flags2.configs[configKey];
            if (typeof resolveConfig === "function") {
              try {
                config2 = resolveConfig(resolvedConfigPath);
              } catch (e4) {
                config2 = e4;
              }
              if (config2 instanceof Error) {
                error40 = config2;
                return;
              }
            } else {
              config2 = mixin2.require(resolvedConfigPath);
            }
            setConfigObject(config2);
          } catch (ex) {
            if (ex.name === "PermissionDenied")
              error40 = ex;
            else if (argv2[configKey])
              error40 = 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, flags2.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 env6 = mixin2.env();
      Object.keys(env6).forEach(function(envVar) {
        if (prefix === "" || envVar.lastIndexOf(prefix, 0) === 0) {
          const keys = envVar.split("__").map(function(key, i4) {
            if (i4 === 0) {
              key = key.substring(prefix.length);
            }
            return camelCase(key);
          });
          if ((configOnly && flags2.configs[keys.join(".")] || !configOnly) && !hasKey2(argv2, keys)) {
            setArg(keys.join("."), env6[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, flags2.coercions);
          if (typeof coerce2 === "function") {
            try {
              const value = maybeCoerceNumber(key, coerce2(argv2[key]));
              [].concat(flags2.aliases[key] || [], key).forEach((ali) => {
                applied.add(ali);
                argv2[ali] = value;
              });
            } catch (err2) {
              error40 = err2;
            }
          }
        }
      });
    }
    __name(applyCoercions, "applyCoercions");
    function setPlaceholderKeys(argv2) {
      flags2.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, defaults5, canLog = false) {
      Object.keys(defaults5).forEach(function(key) {
        if (!hasKey2(obj, key.split("."))) {
          setKey(obj, key.split("."), defaults5[key]);
          if (canLog)
            defaulted[key] = true;
          (aliases2[key] || []).forEach(function(x3) {
            if (hasKey2(obj, x3.split(".")))
              return;
            setKey(obj, x3.split("."), defaults5[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("."), flags2.arrays);
      const isValueArray = Array.isArray(value);
      let duplicate = configuration["duplicate-arguments-array"];
      if (!duplicate && checkAllAliases(key, flags2.nargs)) {
        duplicate = true;
        if (!isUndefined3(o3[key]) && flags2.nargs[key] === 1 || Array.isArray(o3[key]) && o3[key].length === flags2.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, flags2.counts) || checkAllAliases(key, flags2.bools))) {
        o3[key] = [o3[key], value];
      } else {
        o3[key] = value;
      }
    }
    __name(setKey, "setKey");
    function extendAliases(...args3) {
      args3.forEach(function(obj) {
        Object.keys(obj || {}).forEach(function(key) {
          if (flags2.aliases[key])
            return;
          flags2.aliases[key] = [].concat(aliases[key] || []);
          flags2.aliases[key].concat(key).forEach(function(x3) {
            if (/-/.test(x3) && configuration["camel-case-expansion"]) {
              const c4 = camelCase(x3);
              if (c4 !== key && flags2.aliases[key].indexOf(c4) === -1) {
                flags2.aliases[key].push(c4);
                newAliases[c4] = true;
              }
            }
          });
          flags2.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 && flags2.aliases[key].indexOf(c4) === -1) {
                flags2.aliases[key].push(c4);
                newAliases[c4] = true;
              }
            }
          });
          flags2.aliases[key].forEach(function(x3) {
            flags2.aliases[x3] = [key].concat(flags2.aliases[key].filter(function(y2) {
              return x3 !== y2;
            }));
          });
        });
      });
    }
    __name(extendAliases, "extendAliases");
    function checkAllAliases(key, flag) {
      const toCheck = [].concat(flags2.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(flags2);
      const toCheck = [].concat(flagsKeys.map((k2) => flags2[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, flags2.bools) && !checkAllAliases(key, flags2.counts) && `${key}` in defaults4) {
        return defaults4[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, flags2.strings))
        type = DefaultValuesForTypeKey.STRING;
      else if (checkAllAliases(key, flags2.numbers))
        type = DefaultValuesForTypeKey.NUMBER;
      else if (checkAllAliases(key, flags2.bools))
        type = DefaultValuesForTypeKey.BOOLEAN;
      else if (checkAllAliases(key, flags2.arrays))
        type = DefaultValuesForTypeKey.ARRAY;
      return type;
    }
    __name(guessType2, "guessType");
    function isUndefined3(num) {
      return num === void 0;
    }
    __name(isUndefined3, "isUndefined");
    function checkConfiguration() {
      Object.keys(flags2.counts).find((key) => {
        if (checkAllAliases(key, flags2.arrays)) {
          error40 = Error(__("Invalid configuration: %s, opts.count excludes opts.array.", key));
          return true;
        } else if (checkAllAliases(key, flags2.nargs)) {
          error40 = Error(__("Invalid configuration: %s, opts.count excludes opts.narg.", key));
          return true;
        }
        return false;
      });
    }
    __name(checkConfiguration, "checkConfiguration");
    return {
      aliases: Object.assign({}, flags2.aliases),
      argv: Object.assign(argvReturn, argv),
      configuration,
      defaulted: Object.assign({}, defaulted),
      error: error40,
      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 i4 = 0; i4 < aliasArrays.length; i4++) {
      for (let ii = i4 + 1; ii < aliasArrays.length; ii++) {
        const intersect = aliasArrays[i4].filter(function(v2) {
          return aliasArrays[ii].indexOf(v2) !== -1;
        });
        if (intersect.length) {
          aliasArrays[i4] = aliasArrays[i4].concat(aliasArrays[ii]);
          aliasArrays.splice(ii, 1);
          change = true;
          break;
        }
      }
    }
  }
  aliasArrays.forEach(function(aliasArray) {
    aliasArray = aliasArray.filter(function(v2, i4, self2) {
      return self2.indexOf(v2) === i4;
    });
    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 readFileSync20 } 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 env3 = process ? process.env : {};
var parser5 = new YargsParser({
  cwd: process.cwd,
  env: /* @__PURE__ */ __name(() => {
    return env3;
  }, "env"),
  format,
  normalize: normalize10,
  resolve: resolve31,
  // TODO: figure  out a  way to combine ESM and CJS coverage, such  that
  // we can exercise all the lines below:
  require: /* @__PURE__ */ __name((path150) => {
    if (typeof __require !== "undefined") {
      return __require(path150);
    } else if (path150.match(/\.json$/)) {
      return JSON.parse(readFileSync20(path150, "utf8"));
    } else {
      throw Error("only .json config files are supported in ESM");
    }
  }, "require")
});
var yargsParser = /* @__PURE__ */ __name(function Parser5(args2, opts) {
  const result = parser5.parse(args2.slice(), opts);
  return result.argv;
}, "Parser");
yargsParser.detailed = function(args2, opts) {
  return parser5.parse(args2.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 basename21, dirname as dirname29, extname as extname6, relative as relative12, resolve as resolve33 } 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 readFileSync21, statSync as statSync10, writeFile as writeFile18 } from "fs";
import { format as format2 } from "util";
import { resolve as resolve32 } from "path";
var node_default = {
  fs: {
    readFileSync: readFileSync21,
    writeFile: writeFile18
  },
  format: format2,
  resolve: resolve32,
  exists: /* @__PURE__ */ __name((file2) => {
    try {
      return statSync10(file2).isFile();
    } catch (err2) {
      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 = [];
  }
  __(...args2) {
    if (typeof arguments[0] !== "string") {
      return this._taggedLiteral(arguments[0], ...arguments);
    }
    const str2 = args2.shift();
    let cb = /* @__PURE__ */ __name(function() {
    }, "cb");
    if (typeof args2[args2.length - 1] === "function")
      cb = args2.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(args2));
  }
  __n() {
    const args2 = Array.prototype.slice.call(arguments);
    const singular = args2.shift();
    const plural = args2.shift();
    const quantity = args2.shift();
    let cb = /* @__PURE__ */ __name(function() {
    }, "cb");
    if (typeof args2[args2.length - 1] === "function")
      cb = args2.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(args2));
  }
  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(parts2, ...args2) {
    let str2 = "";
    parts2.forEach(function(part, i4) {
      const arg = args2[i4 + 1];
      str2 += part;
      if (typeof arg !== "undefined") {
        str2 += "%s";
      }
    });
    return this.__.apply(this, [str2].concat([].slice.call(args2, 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(err2) {
      _this.writeQueue.shift();
      if (_this.writeQueue.length > 0)
        _this._processWriteQueue();
      cb(err2);
    });
  }
  _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 (err2) {
      if (err2 instanceof SyntaxError) {
        err2.message = "syntax error in " + languageFile;
      }
      if (err2.code === "ENOENT")
        localeLookup = {};
      else
        throw err2;
    }
    this.cache[this.locale] = localeLookup;
  }
  _resolveLocaleFile(directory, locale) {
    let file2 = shim.resolve(directory, "./", locale + ".json");
    if (this.fallbackToLanguage && !this._fileExistsSync(file2) && ~locale.lastIndexOf("_")) {
      const languageFile = shim.resolve(directory, "./", locale.split("_")[0] + ".json");
      if (this._fileExistsSync(languageFile))
        file2 = languageFile;
    }
    return file2;
  }
  _fileExistsSync(file2) {
    return shim.exists(file2);
  }
};
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 = fileURLToPath11(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: basename21,
    dirname: dirname29,
    extname: extname6,
    relative: relative12,
    resolve: resolve33
  },
  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: readFileSync22,
  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: resolve33(__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, i4) => {
    let variadic = false;
    cmd2 = cmd2.replace(/\s/g, "");
    if (/\.+[\]>]/.test(cmd2) && i4 === 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 parseArgs2() {
    return typeof arg1 === "object" ? [{ demanded: [], optional: [] }, arg1, arg2] : [
      parseCommand(`cmd ${arg1}`),
      arg2,
      arg3
    ];
  }
  __name(parseArgs2, "parseArgs");
  try {
    let position = 0;
    const [parsed, callerArguments, _length2] = parseArgs2();
    const args2 = [].slice.call(callerArguments);
    while (args2.length && args2[args2.length - 1] === void 0)
      args2.pop();
    const length = _length2 || args2.length;
    if (length < parsed.demanded.length) {
      throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args2.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 = args2.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 (args2.length === 0)
        return;
      const arg = args2.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 (err2) {
    console.warn(err2.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 i4 = 0; i4 < callback.length; i4++) {
        if (typeof callback[i4] !== "function") {
          throw Error("middleware must be a function");
        }
        const m3 = callback[i4];
        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 = (err2) => {
  throw err2;
}) {
  try {
    const result = isFunction3(getResult) ? getResult() : getResult;
    return isPromise(result) ? result.then((result2) => resultHandler(result2)) : resultHandler(result);
  } catch (err2) {
    return errorHandler(err2);
  }
}
__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 i4 = 0, files = Object.keys(__require.cache), mod2; i4 < files.length; i4++) {
    mod2 = __require.cache[files[i4]];
    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((error40) => {
          try {
            yargs.getInternalMethods().getUsageInstance().fail(null, error40);
          } 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: defaults4 } = yargs.getOptions();
    return Object.prototype.hasOwnProperty.call(defaults4, key) || Object.prototype.hasOwnProperty.call(defaults4, 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 test2 of [describe, description, desc2]) {
      if (typeof test2 === "string" || test2 === false)
        return test2;
      assertNotStrictEqual(test2, 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 = {}, filter5 = () => true) {
  const obj = {};
  objectKeys(original).forEach((key) => {
    if (filter5(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 stream5 = _stream;
    if (stream5._handle && stream5.isTTY && typeof stream5._handle.setBlocking === "function") {
      stream5._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 [enabled2, message] = typeof arg1 === "string" ? [true, arg1] : [arg1, arg2];
    if (yargs.getInternalMethods().isGlobalContext()) {
      globalFailMessage = message;
    }
    failMessage = message;
    showHelpOnFail = enabled2;
    return self2;
  }, "showHelpOnFailFn");
  let failureOutput = false;
  self2.fail = /* @__PURE__ */ __name(function fail(msg, err2) {
    const logger6 = yargs.getInternalMethods().getLoggerInstance();
    if (fails.length) {
      for (let i4 = fails.length - 1; i4 >= 0; --i4) {
        const fail2 = fails[i4];
        if (isBoolean(fail2)) {
          if (err2)
            throw err2;
          else if (msg)
            throw Error(msg);
        } else {
          fail2(msg, err2, self2);
        }
      }
    } else {
      if (yargs.getExitProcess())
        setBlocking(true);
      if (!failureOutput) {
        failureOutput = true;
        if (showHelpOnFail) {
          yargs.showHelp("error");
          logger6.error();
        }
        if (msg || err2)
          logger6.error(msg || err2);
        const globalOrCommandFailMessage = failMessage || globalFailMessage;
        if (globalOrCommandFailMessage) {
          if (msg || err2)
            logger6.error("");
          logger6.error(globalOrCommandFailMessage);
        }
      }
      err2 = err2 || new YError(msg);
      if (yargs.getExitProcess()) {
        return yargs.exit(1);
      } else if (yargs.getInternalMethods().hasParseCallback()) {
        return yargs.exit(1, err2);
      } else {
        throw err2;
      }
    }
  }, "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(getText3(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 i4 = 0, aliasKey; (aliasKey = aliasKeys[i4]) !== void 0; i4++) {
          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: getText3(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} ${getText3(v2[0])}` : getText3(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 sep13 = separator || ", ";
    const array2 = [].concat(values);
    if (!values || !array2.length)
      return string4;
    array2.forEach((value) => {
      if (string4.length)
        string4 += sep13;
      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 getText3(text) {
  return isIndentedText(text) ? text.text : text;
}
__name(getText3, "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(args2, argv, current, done) {
    const handlers = this.command.getCommandHandlers();
    for (let i4 = 0, ii = args2.length; i4 < ii; ++i4) {
      if (handlers[args2[i4]] && handlers[args2[i4]].builder) {
        const builder = handlers[args2[i4]].builder;
        if (isCommandBuilderCallback(builder)) {
          this.indexAfterLastReset = i4 + 1;
          const y2 = this.yargs.getInternalMethods().reset();
          builder(y2, true);
          return y2.argv;
        }
      }
    }
    const completions = [];
    this.commandCompletions(completions, args2, current);
    this.optionCompletions(completions, args2, argv, current);
    this.choicesFromOptionsCompletions(completions, args2, argv, current);
    this.choicesFromPositionalsCompletions(completions, args2, argv, current);
    done(null, completions);
  }
  commandCompletions(completions, args2, current) {
    const parentCommands = this.yargs.getInternalMethods().getContext().commands;
    if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current && !this.previousArgHasChoices(args2)) {
      this.usage.getCommands().forEach((usageCommand) => {
        const commandName = parseCommand(usageCommand[0]).cmd;
        if (args2.indexOf(commandName) === -1) {
          if (!this.zshShell) {
            completions.push(commandName);
          } else {
            const desc2 = usageCommand[1] || "";
            completions.push(commandName.replace(/:/g, "\\:") + ":" + desc2);
          }
        }
      });
    }
  }
  optionCompletions(completions, args2, argv, current) {
    if ((current.match(/^-/) || current === "" && completions.length === 0) && !this.previousArgHasChoices(args2)) {
      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(args2, key, negable)) {
          this.completeOptionKey(key, completions, current, negable && !!options2.default[key]);
        }
      });
    }
  }
  choicesFromOptionsCompletions(completions, args2, argv, current) {
    if (this.previousArgHasChoices(args2)) {
      const choices = this.getPreviousArgChoices(args2);
      if (choices && choices.length > 0) {
        completions.push(...choices.map((c4) => c4.replace(/:/g, "\\:")));
      }
    }
  }
  choicesFromPositionalsCompletions(completions, args2, argv, current) {
    if (current === "" && completions.length > 0 && this.previousArgHasChoices(args2)) {
      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(args2) {
    if (args2.length < 1)
      return;
    let previousArg = args2[args2.length - 1];
    let filter5 = "";
    if (!previousArg.startsWith("-") && args2.length > 1) {
      filter5 = previousArg;
      previousArg = args2[args2.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) => !filter5 || choice2.startsWith(filter5));
    }
  }
  previousArgHasChoices(args2) {
    const choices = this.getPreviousArgChoices(args2);
    return choices !== void 0 && choices.length > 0;
  }
  argsContainKey(args2, key, negable) {
    const argsContains = /* @__PURE__ */ __name((s5) => args2.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(args2, 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((err2) => {
          this.shim.process.nextTick(() => {
            done(err2, void 0);
          });
        });
      }
      return done(null, result);
    } else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
      return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args2, argv, current, onCompleted), (completions) => {
        done(null, completions);
      });
    } else {
      return this.customCompletionFunction(current, argv, (completions) => {
        done(null, completions);
      });
    }
  }
  getCompletion(args2, done) {
    const current = args2.length ? args2[args2.length - 1] : "";
    const argv = this.yargs.parse(args2, true);
    const completionFunction = this.customCompletionFunction ? (argv2) => this.customCompletion(args2, argv2, current, done) : (argv2) => this.defaultCompletion(args2, argv2, current, done);
    return isPromise(argv) ? argv.then(completionFunction) : completionFunction(argv);
  }
  generateCompletionScript($0, cmd) {
    let script = this.zshShell ? completionZshTemplate : completionShTemplate;
    const name4 = this.shim.path.basename($0);
    if ($0.match(/\.js$/))
      $0 = `./${$0}`;
    script = script.replace(/{{app_name}}/g, name4);
    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 i4;
  for (i4 = 0; i4 <= b2.length; i4++) {
    matrix[i4] = [i4];
  }
  let j2;
  for (j2 = 0; j2 <= a2.length; j2++) {
    matrix[0][j2] = j2;
  }
  for (i4 = 1; i4 <= b2.length; i4++) {
    for (j2 = 1; j2 <= a2.length; j2++) {
      if (b2.charAt(i4 - 1) === a2.charAt(j2 - 1)) {
        matrix[i4][j2] = matrix[i4 - 1][j2 - 1];
      } else {
        if (i4 > 1 && j2 > 1 && b2.charAt(i4 - 2) === a2.charAt(j2 - 1) && b2.charAt(i4 - 1) === a2.charAt(j2 - 2)) {
          matrix[i4][j2] = matrix[i4 - 2][j2 - 2] + 1;
        } else {
          matrix[i4][j2] = Math.min(matrix[i4 - 1][j2 - 1] + 1, Math.min(matrix[i4][j2 - 1] + 1, matrix[i4 - 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((i4) => self2.implies(key, i4));
      } 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((i4) => self2.conflicts(key, i4));
      } 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 i4 = 0, candidate; (candidate = potentialCommands[i4]) !== void 0; i4++) {
      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, cwd6, mergeExtends, _shim) {
  shim2 = _shim;
  let defaultConfig2 = {};
  if (Object.prototype.hasOwnProperty.call(config2, "extends")) {
    if (typeof config2.extends !== "string")
      return defaultConfig2;
    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(cwd6, config2.extends);
    }
    checkForCircularExtends(pathToDefault);
    previouslyVisitedConfigs.push(pathToDefault);
    defaultConfig2 = isPath ? JSON.parse(shim2.readFileSync(pathToDefault, "utf8")) : __require(config2.extends);
    delete config2.extends;
    defaultConfig2 = applyExtends(defaultConfig2, shim2.path.dirname(pathToDefault), mergeExtends, shim2);
  }
  previouslyVisitedConfigs = [];
  return mergeExtends ? mergeDeep(defaultConfig2, config2) : Object.assign({}, defaultConfig2, config2);
}
__name(applyExtends, "applyExtends");
function checkForCircularExtends(cfgPath) {
  if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
    throw new YError(`Circular extended configurations: '${cfgPath}'.`);
  }
}
__name(checkForCircularExtends, "checkForCircularExtends");
function getPathToDefaultConfig(cwd6, pathToExtend) {
  return shim2.path.resolve(cwd6, pathToExtend);
}
__name(getPathToDefaultConfig, "getPathToDefaultConfig");
function mergeDeep(config1, config2) {
  const target = {};
  function isObject5(obj) {
    return obj && typeof obj === "object" && !Array.isArray(obj);
  }
  __name(isObject5, "isObject");
  Object.assign(target, config1);
  for (const key of Object.keys(config2)) {
    if (isObject5(config2[key]) && isObject5(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 = [], cwd6 = _shim.process.cwd(), parentRequire) => {
    const yargs = new YargsInstance(processArgs, cwd6, 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 = [], cwd6, 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, cwd6, "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;
      }, (err2) => {
        __classPrivateFieldGet11(this, _YargsInstance_usage, "f").fail(err2.message ? err2.message : err2.toString(), err2);
        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;
      }, (err2) => {
        throw new YError(err2.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, err2) {
    __classPrivateFieldSet9(this, _YargsInstance_hasOutput, true, "f");
    __classPrivateFieldSet9(this, _YargsInstance_exitError, err2, "f");
    if (__classPrivateFieldGet11(this, _YargsInstance_exitProcess, "f"))
      __classPrivateFieldGet11(this, _YargsInstance_shim, "f").process.exit(code2);
  }
  exitProcess(enabled2 = true) {
    argsert("[boolean]", [enabled2], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_exitProcess, enabled2, "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(args2, done) {
    argsert("<array> [function]", [args2, done], arguments.length);
    if (!done) {
      return new Promise((resolve42, reject) => {
        __classPrivateFieldGet11(this, _YargsInstance_completion, "f").getCompletion(args2, (err2, completions) => {
          if (err2)
            reject(err2);
          else
            resolve42(completions);
        });
      });
    } else {
      return __classPrivateFieldGet11(this, _YargsInstance_completion, "f").getCompletion(args2, 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 parse17 = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet11(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
        if (isPromise(parse17)) {
          return parse17.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(args2, shortCircuit, _parseFn) {
    argsert("[string|array] [function|boolean|object] [function]", [args2, shortCircuit, _parseFn], arguments.length);
    this[kFreeze]();
    if (typeof args2 === "undefined") {
      args2 = __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, args2, "f");
    if (__classPrivateFieldGet11(this, _YargsInstance_parseFn, "f"))
      __classPrivateFieldSet9(this, _YargsInstance_exitProcess, false, "f");
    const parsed = this[kRunYargsParserAndExecuteCommands](args2, !!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((err2) => {
        if (__classPrivateFieldGet11(this, _YargsInstance_parseFn, "f")) {
          __classPrivateFieldGet11(this, _YargsInstance_parseFn, "f")(err2, this.parsed.argv, __classPrivateFieldGet11(this, _YargsInstance_output, "f"));
        }
        throw err2;
      }).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(args2, shortCircuit, _parseFn) {
    const maybePromise = this.parse(args2, shortCircuit, _parseFn);
    return !isPromise(maybePromise) ? Promise.resolve(maybePromise) : maybePromise;
  }
  parseSync(args2, shortCircuit, _parseFn) {
    const maybePromise = this.parse(args2, 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 parse17 = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet11(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
        if (isPromise(parse17)) {
          parse17.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(enabled2, message) {
    argsert("[boolean|string] [string]", [enabled2, message], arguments.length);
    __classPrivateFieldGet11(this, _YargsInstance_usage, "f").showHelpOnFail(enabled2, 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(enabled2) {
    argsert("[boolean]", [enabled2], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_strict, enabled2 !== false, "f");
    return this;
  }
  strictCommands(enabled2) {
    argsert("[boolean]", [enabled2], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_strictCommands, enabled2 !== false, "f");
    return this;
  }
  strictOptions(enabled2) {
    argsert("[boolean]", [enabled2], arguments.length);
    __classPrivateFieldSet9(this, _YargsInstance_strictOptions, enabled2 !== 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((...args2) => {
        if (!this[kHasParseCallback]())
          console.log(...args2);
        __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") + args2.join(" "), "f");
      }, "log"),
      error: /* @__PURE__ */ __name((...args2) => {
        if (!this[kHasParseCallback]())
          console.error(...args2);
        __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") + args2.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 args2 = argv["--"] ? argv["--"] : argv._;
    for (let i4 = 0, arg; (arg = args2[i4]) !== void 0; i4++) {
      if (__classPrivateFieldGet11(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
        args2[i4] = 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, set2) {
    this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), "key", key, set2);
    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](args2, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) {
    let skipValidation = !!calledFromCommand || helpOnly;
    args2 = args2 || __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(args2, 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 i4 = commandIndex || 0, cmd; argv._[i4] !== void 0; i4++) {
            cmd = String(argv._[i4]);
            if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet11(this, _YargsInstance_completionCommand, "f")) {
              const innerArgv = __classPrivateFieldGet11(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i4 + 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);
        args2 = [].concat(args2);
        const completionArgs = args2.slice(args2.indexOf(`--${__classPrivateFieldGet11(this, _YargsInstance_completion, "f").completionKey}`) + 1);
        __classPrivateFieldGet11(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err2, completions) => {
          if (err2)
            throw new YError(err2.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 (err2) {
      if (err2 instanceof YError)
        __classPrivateFieldGet11(this, _YargsInstance_usage, "f").fail(err2.message, err2);
      else
        throw err2;
    }
    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
init_stdioHelpers();
init_i18n();
async function handleDisable(args2) {
  const extensionManager = await getExtensionManager();
  try {
    if (args2.scope?.toLowerCase() === "workspace") {
      extensionManager.disableExtension(args2.name, "Workspace" /* Workspace */);
    } else {
      extensionManager.disableExtension(args2.name, "User" /* User */);
    }
    writeStdoutLine(
      t4('Extension "{{name}}" successfully disabled for scope "{{scope}}".', {
        name: args2.name,
        scope: args2.scope || "User" /* User */
      })
    );
  } catch (error40) {
    writeStderrLine(getErrorMessage4(error40));
    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();
init_dist4();
init_stdioHelpers();
init_i18n();
async function handleEnable(args2) {
  const extensionManager = await getExtensionManager();
  try {
    if (args2.scope?.toLowerCase() === "workspace") {
      extensionManager.enableExtension(args2.name, "Workspace" /* Workspace */);
    } else {
      extensionManager.enableExtension(args2.name, "User" /* User */);
    }
    if (args2.scope) {
      writeStdoutLine(
        t4('Extension "{{name}}" successfully enabled for scope "{{scope}}".', {
          name: args2.name,
          scope: args2.scope
        })
      );
    } else {
      writeStdoutLine(
        t4('Extension "{{name}}" successfully enabled in all scopes.', {
          name: args2.name
        })
      );
    }
  } catch (error40) {
    throw new FatalConfigError(getErrorMessage(error40));
  }
}
__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();
init_dist4();
init_stdioHelpers();
init_i18n();
async function handleLink(args2) {
  try {
    const installMetadata = {
      source: args2.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 (error40) {
    writeStderrLine(getErrorMessage4(error40));
    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 access9, cp as cp2, mkdir as mkdir14, readdir as readdir13, writeFile as writeFile19 } from "node:fs/promises";
import { join as join51, dirname as dirname30, basename as basename22 } from "node:path";
import { fileURLToPath as fileURLToPath12 } from "node:url";
init_stdioHelpers();
var __filename3 = fileURLToPath12(import.meta.url);
var __dirname5 = dirname30(__filename3);
var EXAMPLES_PATH = join51(__dirname5, "examples");
async function pathExists(path150) {
  try {
    await access9(path150);
    return true;
  } catch (_e2) {
    return false;
  }
}
__name(pathExists, "pathExists");
async function createDirectory(path150) {
  if (await pathExists(path150)) {
    throw new Error(`Path already exists: ${path150}`);
  }
  await mkdir14(path150, { recursive: true });
}
__name(createDirectory, "createDirectory");
async function copyDirectory2(template, path150) {
  await createDirectory(path150);
  const examplePath = join51(EXAMPLES_PATH, template);
  const entries = await readdir13(examplePath, { withFileTypes: true });
  for (const entry of entries) {
    const srcPath = join51(examplePath, entry.name);
    const destPath = join51(path150, entry.name);
    await cp2(srcPath, destPath, { recursive: true });
  }
}
__name(copyDirectory2, "copyDirectory");
async function handleNew(args2) {
  try {
    if (args2.template) {
      await copyDirectory2(args2.template, args2.path);
      writeStdoutLine(
        `Successfully created new extension from template "${args2.template}" at ${args2.path}.`
      );
    } else {
      await createDirectory(args2.path);
      const extensionName = basename22(args2.path);
      const manifest = {
        name: extensionName,
        version: "1.0.0"
      };
      await writeFile19(
        join51(args2.path, "qwen-extension.json"),
        JSON.stringify(manifest, null, 2)
      );
      writeStdoutLine(`Successfully created new extension at ${args2.path}.`);
    }
    writeStdoutLine(
      `You can install this using "qwen extensions link ${args2.path}" to test it out.`
    );
  } catch (error40) {
    writeStderrLine(getErrorMessage4(error40));
    throw error40;
  }
}
__name(handleNew, "handleNew");
async function getBoilerplateChoices() {
  const entries = await readdir13(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 (args2) => {
    await handleNew({
      path: args2["path"],
      template: args2["template"]
    });
  }, "handler")
};

// packages/cli/src/commands/extensions/settings.ts
init_esbuild_shims();
init_dist4();
init_i18n();
init_stdioHelpers();
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 (args2) => {
    const { name: name4, setting, scope } = args2;
    const extensionManager = await getExtensionManager();
    if (!extensionManager) return;
    const extensions = extensionManager.getLoadedExtensions();
    if (!extensions || extensions.length === 0) return;
    const extension = extensions.find((e4) => e4.name === name4);
    if (!extension) {
      writeStdoutLine(t4('Extension "{{name}}" not found.', { name: name4 }));
      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 (args2) => {
    const { name: name4 } = args2;
    const extensionManager = await getExtensionManager();
    if (!extensionManager) return;
    const extensions = extensionManager.getLoadedExtensions();
    if (!extensions || extensions.length === 0) return;
    const extension = extensions.find((e4) => e4.name === name4);
    if (!extension) {
      writeStdoutLine(t4('Extension "{{name}}" not found.', { name: name4 }));
      return;
    }
    if (!extension || !extension.settings || extension.settings.length === 0) {
      writeStdoutLine(
        t4('Extension "{{name}}" has no settings to configure.', { name: name4 })
      );
      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: name4 }));
    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/commands/hooks.tsx
init_esbuild_shims();
init_dist4();
var debugLogger108 = createDebugLogger("HOOKS_UI");
var hooksCommand = {
  command: "hooks",
  aliases: ["hook"],
  describe: "Manage Qwen Code hooks (use /hooks in interactive mode).",
  builder: /* @__PURE__ */ __name((yargs) => yargs.version(false).help(false), "builder"),
  handler: /* @__PURE__ */ __name(() => {
    debugLogger108.debug(
      "Use /hooks in interactive mode to manage hooks with the UI."
    );
    process.exit(0);
  }, "handler")
};

// packages/cli/src/commands/auth.ts
init_esbuild_shims();

// packages/cli/src/commands/auth/handler.ts
init_esbuild_shims();
init_dist4();
init_stdioHelpers();
init_i18n();

// packages/cli/src/constants/codingPlan.ts
init_esbuild_shims();
import { createHash as createHash7 } from "node:crypto";
var CODING_PLAN_ENV_KEY2 = "BAILIAN_CODING_PLAN_API_KEY";
function computeCodingPlanVersion2(template) {
  const templateString2 = JSON.stringify(template);
  return createHash7("sha256").update(templateString2).digest("hex");
}
__name(computeCodingPlanVersion2, "computeCodingPlanVersion");
function generateCodingPlanTemplate2(region) {
  if (region === "china" /* CHINA */) {
    return [
      {
        id: "qwen3.5-plus",
        name: "[ModelStudio Coding Plan] qwen3.5-plus",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY2,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 1e6
        }
      },
      {
        id: "qwen3.6-plus",
        name: "[ModelStudio Coding Plan] qwen3.6-plus",
        description: "Currently available to Pro subscribers only.",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY2,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 1e6
        }
      },
      {
        id: "glm-5",
        name: "[ModelStudio Coding Plan] glm-5",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY2,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 202752
        }
      },
      {
        id: "kimi-k2.5",
        name: "[ModelStudio Coding Plan] kimi-k2.5",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY2,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 262144
        }
      },
      {
        id: "MiniMax-M2.5",
        name: "[ModelStudio Coding Plan] MiniMax-M2.5",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY2,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 196608
        }
      },
      {
        id: "qwen3-coder-plus",
        name: "[ModelStudio Coding Plan] qwen3-coder-plus",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY2,
        generationConfig: {
          contextWindowSize: 1e6
        }
      },
      {
        id: "qwen3-coder-next",
        name: "[ModelStudio Coding Plan] qwen3-coder-next",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY2,
        generationConfig: {
          contextWindowSize: 262144
        }
      },
      {
        id: "qwen3-max-2026-01-23",
        name: "[ModelStudio Coding Plan] qwen3-max-2026-01-23",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY2,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 262144
        }
      },
      {
        id: "glm-4.7",
        name: "[ModelStudio Coding Plan] glm-4.7",
        baseUrl: "https://coding.dashscope.aliyuncs.com/v1",
        envKey: CODING_PLAN_ENV_KEY2,
        generationConfig: {
          extra_body: {
            enable_thinking: true
          },
          contextWindowSize: 202752
        }
      }
    ];
  }
  return [
    {
      id: "qwen3.5-plus",
      name: "[ModelStudio Coding Plan for Global/Intl] qwen3.5-plus",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY2,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 1e6
      }
    },
    {
      id: "qwen3.6-plus",
      name: "[ModelStudio Coding Plan for Global/Intl] qwen3.6-plus",
      description: "Currently available to Pro subscribers only.",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY2,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 1e6
      }
    },
    {
      id: "qwen3-coder-plus",
      name: "[ModelStudio Coding Plan for Global/Intl] qwen3-coder-plus",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY2,
      generationConfig: {
        contextWindowSize: 1e6
      }
    },
    {
      id: "qwen3-coder-next",
      name: "[ModelStudio Coding Plan for Global/Intl] qwen3-coder-next",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY2,
      generationConfig: {
        contextWindowSize: 262144
      }
    },
    {
      id: "qwen3-max-2026-01-23",
      name: "[ModelStudio Coding Plan for Global/Intl] qwen3-max-2026-01-23",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY2,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 262144
      }
    },
    {
      id: "glm-4.7",
      name: "[ModelStudio Coding Plan for Global/Intl] glm-4.7",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY2,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 202752
      }
    },
    {
      id: "glm-5",
      name: "[ModelStudio Coding Plan for Global/Intl] glm-5",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY2,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 202752
      }
    },
    {
      id: "MiniMax-M2.5",
      name: "[ModelStudio Coding Plan for Global/Intl] MiniMax-M2.5",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY2,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 196608
      }
    },
    {
      id: "kimi-k2.5",
      name: "[ModelStudio Coding Plan for Global/Intl] kimi-k2.5",
      baseUrl: "https://coding-intl.dashscope.aliyuncs.com/v1",
      envKey: CODING_PLAN_ENV_KEY2,
      generationConfig: {
        extra_body: {
          enable_thinking: true
        },
        contextWindowSize: 262144
      }
    }
  ];
}
__name(generateCodingPlanTemplate2, "generateCodingPlanTemplate");
function getCodingPlanConfig2(region) {
  const template = generateCodingPlanTemplate2(region);
  const baseUrl = region === "china" /* CHINA */ ? "https://coding.dashscope.aliyuncs.com/v1" : "https://coding-intl.dashscope.aliyuncs.com/v1";
  return {
    template,
    baseUrl,
    version: computeCodingPlanVersion2(template)
  };
}
__name(getCodingPlanConfig2, "getCodingPlanConfig");
function isCodingPlanConfig2(baseUrl, envKey) {
  if (!baseUrl || !envKey) {
    return false;
  }
  if (envKey !== CODING_PLAN_ENV_KEY2) {
    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(isCodingPlanConfig2, "isCodingPlanConfig");

// packages/cli/src/commands/auth/interactiveSelector.ts
init_esbuild_shims();
init_i18n();
import { stdin, stdout } from "node:process";
var InteractiveSelector = class {
  constructor(options2, prompt = t4("Select an option:")) {
    this.options = options2;
    this.prompt = prompt;
  }
  static {
    __name(this, "InteractiveSelector");
  }
  selectedIndex = 0;
  isListening = false;
  /**
   * Shows the interactive menu and waits for user selection
   */
  async select() {
    return new Promise((resolve42, reject) => {
      this.isListening = true;
      this.renderMenu();
      if (!stdin.setRawMode) {
        reject(
          new Error(
            t4("Raw mode not available. Please run in an interactive terminal.")
          )
        );
        return;
      }
      const wasRaw = stdin.isRaw;
      stdin.setRawMode(true);
      stdin.resume();
      stdin.setEncoding("utf8");
      const onData = /* @__PURE__ */ __name((chunk) => {
        if (!this.isListening) return;
        for (const char of chunk) {
          switch (char) {
            case "":
              stdin.removeListener("data", onData);
              stdin.setRawMode(wasRaw);
              reject(new Error("Interrupted"));
              return;
            case "\r":
            // Enter
            case "\n":
              stdin.removeListener("data", onData);
              stdin.setRawMode(wasRaw);
              resolve42(this.options[this.selectedIndex].value);
              return;
            case "\x1B":
              break;
            default:
              break;
          }
        }
        if (chunk.startsWith("\x1B")) {
          if (chunk === "\x1B[A") {
            this.moveUp();
          } else if (chunk === "\x1B[B") {
            this.moveDown();
          } else if (chunk === "\x1B[C") {
          } else if (chunk === "\x1B[D") {
          }
        }
      }, "onData");
      stdin.on("data", onData);
    });
  }
  /**
   * Renders the menu to stdout
   */
  renderMenu() {
    const totalLines = this.calculateTotalLines();
    if (totalLines > 0) {
      stdout.write(`\x1B[${totalLines}A\x1B[J`);
    }
    stdout.write(`${this.prompt}

`);
    this.options.forEach((option2, index) => {
      const isSelected = index === this.selectedIndex;
      const indicator = isSelected ? "> " : "  ";
      const color = isSelected ? "\x1B[36m" : "\x1B[0m";
      const reset = "\x1B[0m";
      let line = `${indicator}${color}${option2.label}`;
      if (option2.description) {
        line += ` - ${option2.description}`;
      }
      line += `${reset}
`;
      stdout.write(line);
    });
    stdout.write(
      `
${t4("(Use \u2191 \u2193 arrows to navigate, Enter to select, Ctrl+C to exit)\n")}`
    );
  }
  /**
   * Calculates the total number of lines to clear
   */
  calculateTotalLines() {
    return 4 + this.options.length;
  }
  /**
   * Moves selection up
   */
  moveUp() {
    this.selectedIndex = (this.selectedIndex - 1 + this.options.length) % this.options.length;
    this.renderMenu();
  }
  /**
   * Moves selection down
   */
  moveDown() {
    this.selectedIndex = (this.selectedIndex + 1) % this.options.length;
    this.renderMenu();
  }
};

// packages/cli/src/constants/alibabaStandardApiKey.ts
init_esbuild_shims();
var DASHSCOPE_STANDARD_API_KEY_ENV_KEY = "DASHSCOPE_API_KEY";
var ALIBABA_STANDARD_API_KEY_ENDPOINTS = {
  "cn-beijing": "https://dashscope.aliyuncs.com/compatible-mode/v1",
  "sg-singapore": "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
  "us-virginia": "https://dashscope-us.aliyuncs.com/compatible-mode/v1",
  "cn-hongkong": "https://cn-hongkong.dashscope.aliyuncs.com/compatible-mode/v1"
};

// packages/cli/src/commands/auth/openrouterOAuth.ts
init_esbuild_shims();
init_open();
init_dist4();
import { createServer as createServer2 } from "node:http";
import { createHash as createHash8, randomBytes as randomBytes7 } from "node:crypto";
var OPENROUTER_ENV_KEY = "OPENROUTER_API_KEY";
var OPENROUTER_DEFAULT_MODEL = "openai/gpt-4o-mini";
var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
var OPENROUTER_OAUTH_AUTHORIZE_URL = "https://openrouter.ai/auth";
var OPENROUTER_OAUTH_EXCHANGE_URL = "https://openrouter.ai/api/v1/auth/keys";
var OPENROUTER_MODELS_URL = "https://openrouter.ai/api/v1/models";
var OPENROUTER_OAUTH_CALLBACK_URL = "http://localhost:3000/openrouter/callback";
var OPENROUTER_CODE_CHALLENGE_METHOD = "S256";
var OPENROUTER_OAUTH_TIMEOUT_MS = 5 * 60 * 1e3;
var OPENROUTER_MINIMUM_TEXT_MODELS = 1;
var OPENROUTER_DEFAULT_MODELS = [
  {
    id: "openai/gpt-4o-mini",
    name: "OpenRouter \xB7 GPT-4o mini",
    baseUrl: OPENROUTER_BASE_URL,
    envKey: OPENROUTER_ENV_KEY
  },
  {
    id: "anthropic/claude-3.7-sonnet",
    name: "OpenRouter \xB7 Claude 3.7 Sonnet",
    baseUrl: OPENROUTER_BASE_URL,
    envKey: OPENROUTER_ENV_KEY
  },
  {
    id: "google/gemini-2.5-flash",
    name: "OpenRouter \xB7 Gemini 2.5 Flash",
    baseUrl: OPENROUTER_BASE_URL,
    envKey: OPENROUTER_ENV_KEY
  }
];
function toBase64Url(input) {
  return input.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
__name(toBase64Url, "toBase64Url");
function createPkcePair() {
  const codeVerifier = toBase64Url(randomBytes7(32));
  const codeChallenge = toBase64Url(
    createHash8("sha256").update(codeVerifier).digest()
  );
  return { codeVerifier, codeChallenge };
}
__name(createPkcePair, "createPkcePair");
function buildOpenRouterAuthorizationUrl(params) {
  const url3 = new URL(OPENROUTER_OAUTH_AUTHORIZE_URL);
  url3.searchParams.set("callback_url", params.callbackUrl);
  url3.searchParams.set("code_challenge", params.codeChallenge);
  url3.searchParams.set("state", params.state);
  url3.searchParams.set(
    "code_challenge_method",
    params.codeChallengeMethod || OPENROUTER_CODE_CHALLENGE_METHOD
  );
  if (typeof params.limit === "number") {
    url3.searchParams.set("limit", String(params.limit));
  }
  return url3.toString();
}
__name(buildOpenRouterAuthorizationUrl, "buildOpenRouterAuthorizationUrl");
function createOAuthState() {
  return toBase64Url(randomBytes7(32));
}
__name(createOAuthState, "createOAuthState");
function createOpenRouterOAuthSession(callbackUrl = OPENROUTER_OAUTH_CALLBACK_URL, pkcePair = createPkcePair(), state = createOAuthState()) {
  return {
    callbackUrl,
    codeVerifier: pkcePair.codeVerifier,
    state,
    authorizationUrl: buildOpenRouterAuthorizationUrl({
      callbackUrl,
      codeChallenge: pkcePair.codeChallenge,
      state,
      codeChallengeMethod: OPENROUTER_CODE_CHALLENGE_METHOD
    })
  };
}
__name(createOpenRouterOAuthSession, "createOpenRouterOAuthSession");
function startOAuthCallbackListener(callbackUrl = OPENROUTER_OAUTH_CALLBACK_URL, timeoutMs = OPENROUTER_OAUTH_TIMEOUT_MS, expectedState) {
  const parsedUrl = new URL(callbackUrl);
  if (parsedUrl.protocol !== "http:") {
    throw new Error(
      "Only http localhost callback URLs are currently supported."
    );
  }
  let server;
  let timeout2;
  let settled = false;
  const close = /* @__PURE__ */ __name(async () => {
    if (timeout2) {
      clearTimeout(timeout2);
      timeout2 = void 0;
    }
    if (!server) {
      return;
    }
    await new Promise((resolve42, reject) => {
      server.close((error40) => {
        if (error40) {
          reject(error40);
          return;
        }
        resolve42();
      });
    });
    server = void 0;
  }, "close");
  let resolveReady;
  let rejectReady;
  const ready = new Promise((resolve42, reject) => {
    resolveReady = resolve42;
    rejectReady = reject;
  });
  let resolveCode;
  let rejectCode;
  const waitForCode = new Promise((resolve42, reject) => {
    resolveCode = resolve42;
    rejectCode = reject;
  });
  const finish = /* @__PURE__ */ __name((action, payload) => {
    if (settled) {
      return;
    }
    settled = true;
    if (action === "resolve") {
      resolveCode(payload);
    } else {
      rejectCode(payload);
    }
    void close().catch(() => void 0);
  }, "finish");
  server = createServer2((req, res) => {
    const requestUrl = new URL(req.url || "/", parsedUrl.origin);
    if (requestUrl.pathname !== parsedUrl.pathname) {
      res.statusCode = 404;
      res.end("Not found");
      return;
    }
    const error40 = requestUrl.searchParams.get("error");
    if (error40) {
      res.statusCode = 400;
      res.setHeader("Content-Type", "text/plain; charset=utf-8");
      res.end(`OpenRouter authorization failed: ${error40}`);
      void finish(
        "reject",
        new Error(`OpenRouter authorization failed: ${error40}`)
      );
      return;
    }
    const callbackState = requestUrl.searchParams.get("state");
    if (expectedState && callbackState !== expectedState) {
      res.statusCode = 400;
      res.setHeader("Content-Type", "text/plain; charset=utf-8");
      res.end("Invalid OAuth state.");
      void finish(
        "reject",
        new Error("Invalid OAuth state from OpenRouter callback.")
      );
      return;
    }
    const code2 = requestUrl.searchParams.get("code");
    if (!code2) {
      res.statusCode = 400;
      res.setHeader("Content-Type", "text/plain; charset=utf-8");
      res.end("Missing authorization code.");
      void finish(
        "reject",
        new Error("Missing authorization code from OpenRouter callback.")
      );
      return;
    }
    res.statusCode = 200;
    res.setHeader("Content-Type", "text/html; charset=utf-8");
    res.end(
      "<html><body><h1>OpenRouter authentication complete.</h1><p>You can return to Qwen Code.</p></body></html>"
    );
    void finish("resolve", code2);
  });
  server.once("error", (error40) => {
    rejectReady(error40 instanceof Error ? error40 : new Error(String(error40)));
    void finish(
      "reject",
      error40 instanceof Error ? error40 : new Error(String(error40))
    );
  });
  const port = parsedUrl.port ? Number(parsedUrl.port) : 80;
  server.listen(port, parsedUrl.hostname, () => {
    resolveReady();
  });
  timeout2 = setTimeout(() => {
    void finish(
      "reject",
      new Error("Timed out waiting for OpenRouter OAuth callback.")
    );
  }, timeoutMs);
  return {
    ready,
    waitForCode,
    close
  };
}
__name(startOAuthCallbackListener, "startOAuthCallbackListener");
function buildOpenRouterHeaders() {
  return {
    Accept: "application/json",
    "Content-Type": "application/json",
    "HTTP-Referer": "https://github.com/QwenLM/qwen-code.git",
    "X-OpenRouter-Title": "Qwen Code"
  };
}
__name(buildOpenRouterHeaders, "buildOpenRouterHeaders");
var OPENROUTER_MODEL_PRIORITY_PREFIXES = ["qwen/", "glm/", "minimax/"];
var OPENROUTER_RECOMMENDED_MODEL_LIMIT = 16;
var OPENROUTER_FREE_MODEL_ID_HINT = ":free";
function getPreferredOpenRouterModelId(models) {
  return models.find((model) => model.id === OPENROUTER_DEFAULT_MODEL)?.id || models[0]?.id;
}
__name(getPreferredOpenRouterModelId, "getPreferredOpenRouterModelId");
function isOpenRouterFreeModelId(modelId) {
  const normalizedId = modelId.toLowerCase();
  return normalizedId.includes(OPENROUTER_FREE_MODEL_ID_HINT) || normalizedId === "openrouter/free";
}
__name(isOpenRouterFreeModelId, "isOpenRouterFreeModelId");
function getOpenRouterModelPriority(modelId) {
  const normalizedId = modelId.toLowerCase();
  const matchedIndex = OPENROUTER_MODEL_PRIORITY_PREFIXES.findIndex(
    (prefix) => normalizedId.startsWith(prefix)
  );
  return matchedIndex === -1 ? OPENROUTER_MODEL_PRIORITY_PREFIXES.length : matchedIndex;
}
__name(getOpenRouterModelPriority, "getOpenRouterModelPriority");
function isOpenRouterFreeConfig(model) {
  return isOpenRouterFreeModelId(model.id);
}
__name(isOpenRouterFreeConfig, "isOpenRouterFreeConfig");
function compareOpenRouterModels(a2, b2) {
  const freeDiff = Number(isOpenRouterFreeConfig(b2)) - Number(isOpenRouterFreeConfig(a2));
  if (freeDiff !== 0) {
    return freeDiff;
  }
  const priorityDiff = getOpenRouterModelPriority(a2.id) - getOpenRouterModelPriority(b2.id);
  if (priorityDiff !== 0) {
    return priorityDiff;
  }
  return a2.id.localeCompare(b2.id);
}
__name(compareOpenRouterModels, "compareOpenRouterModels");
function toOpenRouterModelConfig(model) {
  if (!model.id) {
    return null;
  }
  const outputModalities = model.architecture?.output_modalities || [];
  const supportsTextOutput = outputModalities.length ? outputModalities.includes("text") : true;
  if (!supportsTextOutput) {
    return null;
  }
  const inputModalities = model.architecture?.input_modalities || [];
  const supportsVision = inputModalities.includes("image");
  return {
    id: model.id,
    name: model.name ? `OpenRouter \xB7 ${model.name}` : `OpenRouter \xB7 ${model.id}`,
    baseUrl: OPENROUTER_BASE_URL,
    envKey: OPENROUTER_ENV_KEY,
    capabilities: supportsVision ? { vision: true } : void 0,
    generationConfig: typeof model.context_length === "number" ? { contextWindowSize: model.context_length } : void 0
  };
}
__name(toOpenRouterModelConfig, "toOpenRouterModelConfig");
function chooseRepresentativeModel(models, predicate, selectedIds) {
  return models.find((model) => predicate(model) && !selectedIds.has(model.id));
}
__name(chooseRepresentativeModel, "chooseRepresentativeModel");
function addRecommendedModel(target, model, selectedIds, limit2) {
  if (!model || selectedIds.has(model.id) || target.length >= limit2) {
    return;
  }
  target.push(model);
  selectedIds.add(model.id);
}
__name(addRecommendedModel, "addRecommendedModel");
function selectRecommendedOpenRouterModels(models, limit2 = OPENROUTER_RECOMMENDED_MODEL_LIMIT) {
  if (models.length <= limit2) {
    return models;
  }
  const sorted2 = [...models].sort(compareOpenRouterModels);
  const recommended = [];
  const selectedIds = /* @__PURE__ */ new Set();
  const freeModels = sorted2.filter((model) => isOpenRouterFreeConfig(model));
  for (const model of freeModels.slice(0, Math.min(limit2, 6))) {
    addRecommendedModel(recommended, model, selectedIds, limit2);
  }
  for (const prefix of OPENROUTER_MODEL_PRIORITY_PREFIXES) {
    addRecommendedModel(
      recommended,
      chooseRepresentativeModel(
        sorted2,
        (model) => model.id.toLowerCase().startsWith(prefix),
        selectedIds
      ),
      selectedIds,
      limit2
    );
  }
  for (const family of ["anthropic/", "google/", "openai/"]) {
    addRecommendedModel(
      recommended,
      chooseRepresentativeModel(
        sorted2,
        (model) => model.id.toLowerCase().startsWith(family),
        selectedIds
      ),
      selectedIds,
      limit2
    );
  }
  addRecommendedModel(
    recommended,
    chooseRepresentativeModel(
      sorted2,
      (model) => model.capabilities?.vision === true,
      selectedIds
    ),
    selectedIds,
    limit2
  );
  addRecommendedModel(
    recommended,
    chooseRepresentativeModel(
      sorted2,
      (model) => (model.generationConfig?.contextWindowSize || 0) >= 1e6,
      selectedIds
    ),
    selectedIds,
    limit2
  );
  for (const model of sorted2) {
    if (recommended.length >= limit2) {
      break;
    }
    addRecommendedModel(recommended, model, selectedIds, limit2);
  }
  return recommended;
}
__name(selectRecommendedOpenRouterModels, "selectRecommendedOpenRouterModels");
function isOpenRouterConfig(config2) {
  return (config2.baseUrl || "").includes("openrouter.ai");
}
__name(isOpenRouterConfig, "isOpenRouterConfig");
function mergeOpenRouterConfigs(existingConfigs, openRouterModels = OPENROUTER_DEFAULT_MODELS) {
  const nonOpenRouterConfigs = existingConfigs.filter(
    (existing) => !isOpenRouterConfig(existing)
  );
  return [...openRouterModels, ...nonOpenRouterConfigs];
}
__name(mergeOpenRouterConfigs, "mergeOpenRouterConfigs");
async function applyOpenRouterModelsConfiguration(params) {
  const { settings, config: config2, apiKey, reloadConfig } = params;
  const persistScope = getPersistScopeForModelSelection(settings);
  settings.setValue(persistScope, `env.${OPENROUTER_ENV_KEY}`, apiKey);
  process.env[OPENROUTER_ENV_KEY] = apiKey;
  const existingConfigs = settings.merged.modelProviders?.[AuthType2.USE_OPENAI] || [];
  const openRouterCatalog = await getOpenRouterModelsWithFallback();
  const openRouterModels = selectRecommendedOpenRouterModels(openRouterCatalog);
  const updatedConfigs = mergeOpenRouterConfigs(
    existingConfigs,
    openRouterModels
  );
  settings.setValue(
    persistScope,
    `modelProviders.${AuthType2.USE_OPENAI}`,
    updatedConfigs
  );
  settings.setValue(
    persistScope,
    "security.auth.selectedType",
    AuthType2.USE_OPENAI
  );
  const activeModelId = getPreferredOpenRouterModelId(updatedConfigs);
  if (activeModelId) {
    settings.setValue(persistScope, "model.name", activeModelId);
  }
  if (reloadConfig) {
    const updatedModelProviders = {
      ...settings.merged.modelProviders,
      [AuthType2.USE_OPENAI]: updatedConfigs
    };
    config2.reloadModelProvidersConfig(updatedModelProviders);
  }
  return {
    updatedConfigs,
    activeModelId,
    persistScope
  };
}
__name(applyOpenRouterModelsConfiguration, "applyOpenRouterModelsConfiguration");
async function fetchOpenRouterModels() {
  const response = await fetch(OPENROUTER_MODELS_URL, {
    method: "GET",
    headers: buildOpenRouterHeaders()
  });
  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(
      `OpenRouter models request failed (${response.status}): ${errorText}`
    );
  }
  const data = await response.json();
  const records = Array.isArray(data.data) ? data.data : [];
  const models = records.map((record2) => toOpenRouterModelConfig(record2)).filter((model) => model !== null).sort(compareOpenRouterModels);
  if (models.length < OPENROUTER_MINIMUM_TEXT_MODELS) {
    throw new Error(
      "OpenRouter models request returned no usable text models."
    );
  }
  return models;
}
__name(fetchOpenRouterModels, "fetchOpenRouterModels");
async function getOpenRouterModelsWithFallback() {
  try {
    return await fetchOpenRouterModels();
  } catch {
    return OPENROUTER_DEFAULT_MODELS;
  }
}
__name(getOpenRouterModelsWithFallback, "getOpenRouterModelsWithFallback");
async function exchangeAuthCodeForApiKey(params) {
  const response = await fetch(OPENROUTER_OAUTH_EXCHANGE_URL, {
    method: "POST",
    headers: buildOpenRouterHeaders(),
    body: JSON.stringify({
      code: params.code,
      code_verifier: params.codeVerifier,
      code_challenge_method: OPENROUTER_CODE_CHALLENGE_METHOD
    })
  });
  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(
      `OpenRouter API key exchange failed (${response.status}): ${errorText}`
    );
  }
  const data = await response.json();
  if (!data.key) {
    throw new Error(
      "OpenRouter API key exchange succeeded but no key was returned."
    );
  }
  return {
    apiKey: data.key,
    userId: data.user_id
  };
}
__name(exchangeAuthCodeForApiKey, "exchangeAuthCodeForApiKey");
async function runOpenRouterOAuthLogin(callbackUrl = OPENROUTER_OAUTH_CALLBACK_URL, deps = {}) {
  const session = deps.session || createOpenRouterOAuthSession(callbackUrl);
  const {
    callbackUrl: effectiveCallbackUrl,
    codeVerifier,
    state,
    authorizationUrl: authUrl
  } = session;
  const openBrowser = deps.openBrowser || open_default;
  const startListener = deps.startListener || startOAuthCallbackListener;
  const exchangeApiKey = deps.exchangeApiKey || exchangeAuthCodeForApiKey;
  const now = deps.now || Date.now;
  const signalTarget = deps.signalTarget || process;
  const abortSignal = deps.abortSignal;
  const listener = startListener(
    effectiveCallbackUrl,
    OPENROUTER_OAUTH_TIMEOUT_MS,
    state
  );
  let cleanupSignalHandlers = /* @__PURE__ */ __name(() => {
  }, "cleanupSignalHandlers");
  let cleanupAbortListener = /* @__PURE__ */ __name(() => {
  }, "cleanupAbortListener");
  try {
    await listener.ready;
    await openBrowser(authUrl);
    const waitForCancel = new Promise((_2, reject) => {
      const handleSignal = /* @__PURE__ */ __name((signal) => {
        reject(
          new Error(
            `OpenRouter OAuth cancelled by user (${signal}) while waiting for browser authorization.`
          )
        );
      }, "handleSignal");
      signalTarget.once("SIGINT", handleSignal);
      signalTarget.once("SIGTERM", handleSignal);
      cleanupSignalHandlers = /* @__PURE__ */ __name(() => {
        signalTarget.removeListener("SIGINT", handleSignal);
        signalTarget.removeListener("SIGTERM", handleSignal);
      }, "cleanupSignalHandlers");
    });
    const waitForAbort = new Promise((_2, reject) => {
      if (!abortSignal) {
        return;
      }
      const handleAbort = /* @__PURE__ */ __name(() => {
        reject(new DOMException("OpenRouter OAuth cancelled.", "AbortError"));
      }, "handleAbort");
      if (abortSignal.aborted) {
        handleAbort();
        return;
      }
      abortSignal.addEventListener("abort", handleAbort, { once: true });
      cleanupAbortListener = /* @__PURE__ */ __name(() => {
        abortSignal.removeEventListener("abort", handleAbort);
      }, "cleanupAbortListener");
    });
    const waitStartMs = now();
    const code2 = await Promise.race([
      listener.waitForCode,
      waitForCancel,
      waitForAbort
    ]);
    cleanupSignalHandlers();
    cleanupAbortListener();
    const authorizationCodeWaitMs = now() - waitStartMs;
    const exchangeStartMs = now();
    const exchangeResult = await exchangeApiKey({ code: code2, codeVerifier });
    const apiKeyExchangeMs = now() - exchangeStartMs;
    return {
      ...exchangeResult,
      authorizationUrl: authUrl,
      authorizationCodeWaitMs,
      apiKeyExchangeMs
    };
  } finally {
    cleanupSignalHandlers();
    cleanupAbortListener();
    void listener.close().catch(() => void 0);
  }
}
__name(runOpenRouterOAuthLogin, "runOpenRouterOAuthLogin");

// packages/cli/src/commands/auth/handler.ts
function formatElapsedTime(startMs) {
  return `${((Date.now() - startMs) / 1e3).toFixed(2)}s`;
}
__name(formatElapsedTime, "formatElapsedTime");
function createMinimalArgv() {
  return {
    query: void 0,
    model: void 0,
    sandbox: void 0,
    sandboxImage: void 0,
    debug: void 0,
    prompt: void 0,
    promptInteractive: void 0,
    yolo: void 0,
    bare: void 0,
    approvalMode: void 0,
    telemetry: void 0,
    checkpointing: void 0,
    telemetryTarget: void 0,
    telemetryOtlpEndpoint: void 0,
    telemetryOtlpProtocol: void 0,
    telemetryLogPrompts: void 0,
    telemetryOutfile: void 0,
    allowedMcpServerNames: void 0,
    mcpConfig: void 0,
    allowedTools: void 0,
    acp: void 0,
    experimentalAcp: void 0,
    experimentalLsp: void 0,
    extensions: [],
    listExtensions: void 0,
    openaiLogging: void 0,
    openaiApiKey: void 0,
    openaiBaseUrl: void 0,
    openaiLoggingDir: void 0,
    proxy: void 0,
    includeDirectories: void 0,
    screenReader: void 0,
    inputFormat: void 0,
    outputFormat: void 0,
    includePartialMessages: void 0,
    chatRecording: void 0,
    continue: void 0,
    resume: void 0,
    sessionId: void 0,
    maxSessionTurns: void 0,
    coreTools: void 0,
    excludeTools: void 0,
    disabledSlashCommands: void 0,
    authType: void 0,
    channel: void 0,
    systemPrompt: void 0,
    appendSystemPrompt: void 0
  };
}
__name(createMinimalArgv, "createMinimalArgv");
async function loadAuthConfig(settings) {
  return loadCliConfig(
    settings.merged,
    createMinimalArgv(),
    process.cwd(),
    [],
    {
      userHooks: settings.getUserHooks(),
      projectHooks: settings.getProjectHooks()
    }
  );
}
__name(loadAuthConfig, "loadAuthConfig");
async function handleQwenAuth(command2, options2) {
  try {
    const settings = loadSettings();
    const config2 = await loadAuthConfig(settings);
    if (command2 === "qwen-oauth") {
      await handleQwenOAuth(config2, settings);
    } else if (command2 === "coding-plan") {
      await handleCodePlanAuth(config2, settings, options2);
    } else if (command2 === "openrouter") {
      await handleOpenRouterAuth(config2, settings, options2);
    }
    writeStdoutLine(t4("Authentication completed successfully."));
    process.exit(0);
  } catch (error40) {
    writeStderrLine(getErrorMessage(error40));
    process.exit(1);
  }
}
__name(handleQwenAuth, "handleQwenAuth");
async function handleQwenOAuth(config2, settings) {
  writeStdoutLine(t4("Starting Qwen OAuth authentication..."));
  try {
    await config2.refreshAuth(AuthType2.QWEN_OAUTH);
    const authTypeScope = getPersistScopeForModelSelection(settings);
    settings.setValue(
      authTypeScope,
      "security.auth.selectedType",
      AuthType2.QWEN_OAUTH
    );
    writeStdoutLine(t4("Successfully authenticated with Qwen OAuth."));
    process.exit(0);
  } catch (error40) {
    writeStderrLine(
      t4("Failed to authenticate with Qwen OAuth: {{error}}", {
        error: getErrorMessage(error40)
      })
    );
    process.exit(1);
  }
}
__name(handleQwenOAuth, "handleQwenOAuth");
async function handleCodePlanAuth(config2, settings, options2) {
  const { region, key } = options2;
  let selectedRegion;
  let selectedKey;
  if (region && key) {
    selectedRegion = region.toLowerCase() === "global" ? "global" /* GLOBAL */ : "china" /* CHINA */;
    selectedKey = key;
  } else {
    selectedRegion = await promptForRegion();
    selectedKey = await promptForKey();
  }
  writeStdoutLine(t4("Processing Alibaba Cloud Coding Plan authentication..."));
  try {
    const { template, version: version2 } = getCodingPlanConfig2(selectedRegion);
    const authTypeScope = getPersistScopeForModelSelection(settings);
    const settingsFile = settings.forScope(authTypeScope);
    backupSettingsFile(settingsFile.path);
    settings.setValue(authTypeScope, `env.${CODING_PLAN_ENV_KEY2}`, selectedKey);
    process.env[CODING_PLAN_ENV_KEY2] = selectedKey;
    const newConfigs = template.map((templateConfig) => ({
      ...templateConfig,
      envKey: CODING_PLAN_ENV_KEY2
    }));
    const existingConfigs = settings.merged.modelProviders?.[AuthType2.USE_OPENAI] || [];
    const nonCodingPlanConfigs = existingConfigs.filter(
      (existing) => !isCodingPlanConfig2(existing.baseUrl, existing.envKey)
    );
    const updatedConfigs = [...newConfigs, ...nonCodingPlanConfigs];
    settings.setValue(
      authTypeScope,
      `modelProviders.${AuthType2.USE_OPENAI}`,
      updatedConfigs
    );
    settings.setValue(
      authTypeScope,
      "security.auth.selectedType",
      AuthType2.USE_OPENAI
    );
    settings.setValue(authTypeScope, "codingPlan.region", selectedRegion);
    settings.setValue(authTypeScope, "codingPlan.version", version2);
    if (updatedConfigs.length > 0 && updatedConfigs[0]?.id) {
      settings.setValue(
        authTypeScope,
        "model.name",
        updatedConfigs[0].id
      );
    }
    await config2.refreshAuth(AuthType2.USE_OPENAI);
    writeStdoutLine(
      t4("Successfully authenticated with Alibaba Cloud Coding Plan.")
    );
  } catch (error40) {
    writeStderrLine(
      t4("Failed to authenticate with Coding Plan: {{error}}", {
        error: getErrorMessage(error40)
      })
    );
    process.exit(1);
  }
}
__name(handleCodePlanAuth, "handleCodePlanAuth");
async function handleOpenRouterAuth(config2, settings, options2) {
  writeStdoutLine(t4("Processing OpenRouter authentication..."));
  try {
    const authStartMs = Date.now();
    let selectedKey = options2.key;
    if (!selectedKey) {
      const oauthStartMs = Date.now();
      const oauthSession = createOpenRouterOAuthSession();
      writeStdoutLine(
        t4(
          "Starting OpenRouter OAuth in your browser. If needed, open this link manually: {{authorizationUrl}}",
          {
            authorizationUrl: oauthSession.authorizationUrl
          }
        )
      );
      const oauthResult = await runOpenRouterOAuthLogin(void 0, {
        session: oauthSession
      });
      writeStdoutLine(
        t4("Waited for OpenRouter browser authorization in {{elapsed}}.", {
          elapsed: typeof oauthResult.authorizationCodeWaitMs === "number" ? `${(oauthResult.authorizationCodeWaitMs / 1e3).toFixed(2)}s` : formatElapsedTime(oauthStartMs)
        })
      );
      writeStdoutLine(
        t4("Exchanged OpenRouter auth code for API key in {{elapsed}}.", {
          elapsed: typeof oauthResult.apiKeyExchangeMs === "number" ? `${(oauthResult.apiKeyExchangeMs / 1e3).toFixed(2)}s` : formatElapsedTime(oauthStartMs)
        })
      );
      writeStdoutLine(
        t4("OpenRouter OAuth callback completed in {{elapsed}}.", {
          elapsed: formatElapsedTime(oauthStartMs)
        })
      );
      selectedKey = oauthResult.apiKey;
    }
    if (!selectedKey) {
      throw new Error(
        "OpenRouter authentication completed without an API key."
      );
    }
    const authTypeScope = getPersistScopeForModelSelection(settings);
    const settingsFile = settings.forScope(authTypeScope);
    backupSettingsFile(settingsFile.path);
    const modelsStartMs = Date.now();
    await applyOpenRouterModelsConfiguration({
      settings,
      config: config2,
      apiKey: selectedKey,
      reloadConfig: true
    });
    writeStdoutLine(
      t4("Fetched OpenRouter models in {{elapsed}}.", {
        elapsed: formatElapsedTime(modelsStartMs)
      })
    );
    const refreshStartMs = Date.now();
    await config2.refreshAuth(AuthType2.USE_OPENAI);
    writeStdoutLine(
      t4("Refreshed OpenRouter auth in {{elapsed}}.", {
        elapsed: formatElapsedTime(refreshStartMs)
      })
    );
    writeStdoutLine(
      t4("Total OpenRouter setup time: {{elapsed}}.", {
        elapsed: formatElapsedTime(authStartMs)
      })
    );
    writeStdoutLine(t4("Successfully configured OpenRouter."));
  } catch (error40) {
    writeStderrLine(
      t4("Failed to configure OpenRouter: {{error}}", {
        error: getErrorMessage(error40)
      })
    );
    process.exit(1);
  }
}
__name(handleOpenRouterAuth, "handleOpenRouterAuth");
async function promptForRegion() {
  const selector = new InteractiveSelector(
    [
      {
        value: "china" /* CHINA */,
        label: t4("\u4E2D\u56FD (China)"),
        description: t4("\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)")
      },
      {
        value: "global" /* GLOBAL */,
        label: t4("Global"),
        description: t4("Alibaba Cloud (alibabacloud.com)")
      }
    ],
    t4("Select region for Coding Plan:")
  );
  return await selector.select();
}
__name(promptForRegion, "promptForRegion");
async function promptForInput(promptText, options2 = {}) {
  const { mask = false, defaultValue } = options2;
  const stdin2 = process.stdin;
  const stdout2 = process.stdout;
  stdout2.write(promptText);
  const wasRaw = stdin2.isRaw;
  if (stdin2.setRawMode) {
    stdin2.setRawMode(true);
  }
  stdin2.resume();
  return new Promise((resolve42, reject) => {
    let input = "";
    const onData = /* @__PURE__ */ __name((chunk) => {
      for (const char of chunk) {
        switch (char) {
          case "\r":
          // Enter
          case "\n":
            stdin2.removeListener("data", onData);
            if (stdin2.setRawMode) {
              stdin2.setRawMode(wasRaw);
            }
            stdout2.write("\n");
            resolve42(
              defaultValue !== void 0 && !input ? defaultValue : input
            );
            return;
          case "":
            stdin2.removeListener("data", onData);
            if (stdin2.setRawMode) {
              stdin2.setRawMode(wasRaw);
            }
            stdout2.write("^C\n");
            reject(new Error("Interrupted"));
            return;
          case "\b":
          // Backspace
          case "\x7F":
            if (input.length > 0) {
              input = input.slice(0, -1);
              stdout2.write("\x1B[D \x1B[D");
            }
            break;
          default:
            input += char;
            stdout2.write(mask ? "*" : char);
            break;
        }
      }
    }, "onData");
    stdin2.on("data", onData);
  });
}
__name(promptForInput, "promptForInput");
async function promptForKey(promptText = t4("Enter your Coding Plan API key: ")) {
  return promptForInput(promptText, { mask: true });
}
__name(promptForKey, "promptForKey");
async function runInteractiveAuth() {
  const selector = new InteractiveSelector(
    [
      {
        value: "openrouter",
        label: t4("OpenRouter"),
        description: t4(
          "API key setup \xB7 OpenAI-compatible provider via OpenRouter"
        )
      },
      {
        value: "coding-plan",
        label: t4("Alibaba Cloud Coding Plan"),
        description: t4(
          "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models"
        )
      },
      {
        value: "api-key",
        label: t4("API Key"),
        description: t4("Bring your own API key")
      },
      {
        value: "qwen-oauth",
        label: t4("Qwen OAuth"),
        description: t4("Discontinued \u2014 switch to Coding Plan or API Key")
      }
    ],
    t4("Select authentication method:")
  );
  let choice2 = await selector.select();
  while (choice2 === "qwen-oauth") {
    writeStdoutLine(
      t4(
        "\n\u26A0 Qwen OAuth free tier was discontinued on 2026-04-15. Please select another option.\n"
      )
    );
    choice2 = await selector.select();
  }
  if (choice2 === "coding-plan") {
    await handleQwenAuth("coding-plan", {});
  } else if (choice2 === "api-key") {
    await handleApiKeyAuth();
  } else if (choice2 === "openrouter") {
    await handleQwenAuth("openrouter", {});
  }
}
__name(runInteractiveAuth, "runInteractiveAuth");
async function handleApiKeyAuth() {
  try {
    const selector = new InteractiveSelector(
      [
        {
          value: "alibaba-standard",
          label: t4("Alibaba Cloud ModelStudio Standard API Key"),
          description: t4("Quick setup for Model Studio (China/International)")
        },
        {
          value: "custom",
          label: t4("Custom API Key"),
          description: t4(
            "For other OpenAI / Anthropic / Gemini-compatible providers"
          )
        }
      ],
      t4("Select API key type:")
    );
    const choice2 = await selector.select();
    if (choice2 === "alibaba-standard") {
      await handleAlibabaStandardApiKeyAuth();
    } else if (choice2 === "custom") {
      handleCustomApiKeyAuth();
    }
  } catch (error40) {
    writeStderrLine(getErrorMessage(error40));
    process.exit(1);
  }
}
__name(handleApiKeyAuth, "handleApiKeyAuth");
async function handleAlibabaStandardApiKeyAuth() {
  try {
    const settings = loadSettings();
    const config2 = await loadAuthConfig(settings);
    const region = await promptForStandardRegion();
    const apiKey = await promptForKey(t4("Enter your API key: "));
    const trimmedApiKey = apiKey.trim();
    if (!trimmedApiKey) {
      writeStderrLine(t4("API key cannot be empty."));
      process.exit(1);
    }
    const modelIdsInput = await promptForModelIds();
    const modelIds = modelIdsInput.split(",").map((id) => id.trim()).filter(
      (id, index, array2) => id.length > 0 && array2.indexOf(id) === index
    );
    if (modelIds.length === 0) {
      writeStderrLine(t4("Model IDs cannot be empty."));
      process.exit(1);
    }
    writeStdoutLine(
      t4("Processing Alibaba Cloud ModelStudio Standard API Key...")
    );
    const baseUrl = ALIBABA_STANDARD_API_KEY_ENDPOINTS[region];
    const persistScope = getPersistScopeForModelSelection(settings);
    const settingsFile = settings.forScope(persistScope);
    backupSettingsFile(settingsFile.path);
    settings.setValue(
      persistScope,
      `env.${DASHSCOPE_STANDARD_API_KEY_ENV_KEY}`,
      trimmedApiKey
    );
    process.env[DASHSCOPE_STANDARD_API_KEY_ENV_KEY] = trimmedApiKey;
    const newConfigs = modelIds.map((modelId) => ({
      id: modelId,
      name: `[ModelStudio Standard] ${modelId}`,
      baseUrl,
      envKey: DASHSCOPE_STANDARD_API_KEY_ENV_KEY
    }));
    const existingConfigs = settings.merged.modelProviders?.[AuthType2.USE_OPENAI] || [];
    const nonReplacedConfigs = existingConfigs.filter(
      (existing) => (
        // Filter out old Alibaba Standard entries
        !(existing.envKey === DASHSCOPE_STANDARD_API_KEY_ENV_KEY && typeof existing.baseUrl === "string" && Object.values(ALIBABA_STANDARD_API_KEY_ENDPOINTS).includes(
          existing.baseUrl
        )) && // Filter out Coding Plan entries (their key will be cleared)
        !isCodingPlanConfig2(existing.baseUrl, existing.envKey)
      )
    );
    const updatedConfigs = [...newConfigs, ...nonReplacedConfigs];
    settings.setValue(
      persistScope,
      `modelProviders.${AuthType2.USE_OPENAI}`,
      updatedConfigs
    );
    settings.setValue(
      persistScope,
      "security.auth.selectedType",
      AuthType2.USE_OPENAI
    );
    settings.setValue(persistScope, "model.name", modelIds[0]);
    delete process.env[CODING_PLAN_ENV_KEY2];
    settings.setValue(persistScope, `env.${CODING_PLAN_ENV_KEY2}`, "");
    settings.setValue(persistScope, "codingPlan.region", "");
    settings.setValue(persistScope, "codingPlan.version", "");
    const updatedModelProviders = {
      ...settings.merged.modelProviders,
      [AuthType2.USE_OPENAI]: updatedConfigs
    };
    config2.reloadModelProvidersConfig(updatedModelProviders);
    await config2.refreshAuth(AuthType2.USE_OPENAI);
    writeStdoutLine(
      t4(
        "Successfully configured Alibaba Cloud ModelStudio Standard API Key with {{modelCount}} model(s).",
        { modelCount: String(modelIds.length) }
      )
    );
    process.exit(0);
  } catch (error40) {
    writeStderrLine(getErrorMessage(error40));
    process.exit(1);
  }
}
__name(handleAlibabaStandardApiKeyAuth, "handleAlibabaStandardApiKeyAuth");
function handleCustomApiKeyAuth() {
  writeStdoutLine(
    t4(
      "\nYou can configure your API key and models in settings.json.\nRefer to the documentation for setup instructions:\n  https://qwenlm.github.io/qwen-code-docs/en/users/configuration/model-providers/\n"
    )
  );
  process.exit(0);
}
__name(handleCustomApiKeyAuth, "handleCustomApiKeyAuth");
async function promptForStandardRegion() {
  const selector = new InteractiveSelector(
    [
      {
        value: "cn-beijing",
        label: t4("China (Beijing)"),
        description: ALIBABA_STANDARD_API_KEY_ENDPOINTS["cn-beijing"]
      },
      {
        value: "sg-singapore",
        label: t4("Singapore"),
        description: ALIBABA_STANDARD_API_KEY_ENDPOINTS["sg-singapore"]
      },
      {
        value: "us-virginia",
        label: t4("US (Virginia)"),
        description: ALIBABA_STANDARD_API_KEY_ENDPOINTS["us-virginia"]
      },
      {
        value: "cn-hongkong",
        label: t4("China (Hong Kong)"),
        description: ALIBABA_STANDARD_API_KEY_ENDPOINTS["cn-hongkong"]
      }
    ],
    t4("Select region:")
  );
  return await selector.select();
}
__name(promptForStandardRegion, "promptForStandardRegion");
async function promptForModelIds() {
  const defaultModels = "qwen3.5-plus,glm-5,kimi-k2.5";
  return promptForInput(
    t4("Enter model IDs (comma-separated, default: {{default}}): ", {
      default: defaultModels
    }),
    { defaultValue: defaultModels }
  );
}
__name(promptForModelIds, "promptForModelIds");
async function showAuthStatus() {
  try {
    const settings = loadSettings();
    const mergedSettings = settings.merged;
    writeStdoutLine(t4("\n=== Authentication Status ===\n"));
    const selectedType = mergedSettings.security?.auth?.selectedType;
    if (!selectedType) {
      writeStdoutLine(t4("\u26A0\uFE0F  No authentication method configured.\n"));
      writeStdoutLine(t4("Run one of the following commands to get started:\n"));
      writeStdoutLine(
        t4("  qwen auth openrouter      - Configure OpenRouter API key")
      );
      writeStdoutLine(
        t4(
          "  qwen auth coding-plan    - Authenticate with Alibaba Cloud Coding Plan"
        )
      );
      writeStdoutLine(
        t4("  qwen auth api-key        - Authenticate with an API key")
      );
      writeStdoutLine(
        t4(
          "  qwen auth qwen-oauth     - Authenticate with Qwen OAuth (discontinued)\n"
        )
      );
      writeStdoutLine(t4("Or simply run:"));
      writeStdoutLine(
        t4("  qwen auth                - Interactive authentication setup\n")
      );
      process.exit(0);
    }
    if (selectedType === AuthType2.QWEN_OAUTH) {
      writeStdoutLine(t4("\u2713 Authentication Method: Qwen OAuth"));
      writeStdoutLine(t4("  Type: Free tier (discontinued 2026-04-15)"));
      writeStdoutLine(t4("  Limit: No longer available"));
      writeStdoutLine(t4("  Models: Qwen latest models"));
      writeStdoutLine(
        t4("\n  \u26A0 Run /auth to switch to Coding Plan or another provider.\n")
      );
    } else if (selectedType === AuthType2.USE_OPENAI) {
      const codingPlanRegion = mergedSettings.codingPlan?.region;
      const codingPlanVersion = mergedSettings.codingPlan?.version;
      const modelName = mergedSettings.model?.name;
      const openAiProviders = mergedSettings.modelProviders?.[AuthType2.USE_OPENAI] || [];
      const activeConfig = modelName ? openAiProviders.find((c4) => c4.id === modelName) : openAiProviders[0];
      const isActiveOpenRouter = activeConfig ? isOpenRouterConfig(activeConfig) : false;
      const providerCodingPlanRegion = isCodingPlanConfig2(
        activeConfig?.baseUrl,
        activeConfig?.envKey
      );
      const detectedCodingPlanRegion = activeConfig ? providerCodingPlanRegion : !modelName ? codingPlanRegion : false;
      const isActiveStandard = activeConfig && activeConfig.envKey === DASHSCOPE_STANDARD_API_KEY_ENV_KEY && typeof activeConfig.baseUrl === "string" && Object.values(ALIBABA_STANDARD_API_KEY_ENDPOINTS).includes(
        activeConfig.baseUrl
      );
      const hasOpenRouterApiKey = !!process.env[OPENROUTER_ENV_KEY] || !!mergedSettings.env?.[OPENROUTER_ENV_KEY];
      if (isActiveOpenRouter) {
        if (hasOpenRouterApiKey) {
          writeStdoutLine(t4("\u2713 Authentication Method: OpenRouter"));
          if (modelName) {
            writeStdoutLine(
              t4("  Current Model: {{model}}", { model: modelName })
            );
          }
          writeStdoutLine(t4("  Status: API key configured\n"));
        } else {
          writeStdoutLine(
            t4("\u26A0\uFE0F  Authentication Method: OpenRouter (Incomplete)")
          );
          writeStdoutLine(
            t4("  Issue: API key not found in environment or settings\n")
          );
          writeStdoutLine(t4("  Run `qwen auth openrouter` to re-configure.\n"));
        }
      } else if (detectedCodingPlanRegion) {
        const hasCodingPlanKey = !!process.env[CODING_PLAN_ENV_KEY2] || !!mergedSettings.env?.[CODING_PLAN_ENV_KEY2];
        if (hasCodingPlanKey) {
          writeStdoutLine(
            t4("\u2713 Authentication Method: Alibaba Cloud Coding Plan")
          );
          const displayRegion = codingPlanRegion || detectedCodingPlanRegion;
          if (displayRegion) {
            const regionDisplay = displayRegion === "china" /* CHINA */ ? t4("\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC") : t4("Global - Alibaba Cloud");
            writeStdoutLine(
              t4("  Region: {{region}}", { region: regionDisplay })
            );
          }
          if (modelName) {
            writeStdoutLine(
              t4("  Current Model: {{model}}", { model: modelName })
            );
          }
          if (codingPlanVersion) {
            writeStdoutLine(
              t4("  Config Version: {{version}}", {
                version: codingPlanVersion.substring(0, 8) + "..."
              })
            );
          }
          writeStdoutLine(t4("  Status: API key configured\n"));
        } else {
          writeStdoutLine(
            t4(
              "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)"
            )
          );
          writeStdoutLine(
            t4("  Issue: API key not found in environment or settings\n")
          );
          writeStdoutLine(
            t4("  Run `qwen auth coding-plan` to re-configure.\n")
          );
        }
      } else if (isActiveStandard) {
        const hasStandardKey = !!process.env[DASHSCOPE_STANDARD_API_KEY_ENV_KEY] || !!mergedSettings.env?.[DASHSCOPE_STANDARD_API_KEY_ENV_KEY];
        if (hasStandardKey) {
          writeStdoutLine(
            t4(
              "\u2713 Authentication Method: Alibaba Cloud ModelStudio Standard API Key"
            )
          );
          if (modelName) {
            writeStdoutLine(
              t4("  Current Model: {{model}}", { model: modelName })
            );
          }
          writeStdoutLine(t4("  Status: API key configured\n"));
        } else {
          writeStdoutLine(
            t4(
              "\u26A0\uFE0F  Authentication Method: Alibaba Cloud ModelStudio Standard API Key (Incomplete)"
            )
          );
          writeStdoutLine(
            t4("  Issue: API key not found in environment or settings\n")
          );
          writeStdoutLine(t4("  Run `qwen auth api-key` to re-configure.\n"));
        }
      } else if (activeConfig) {
        let hasApiKey;
        if (activeConfig.envKey) {
          hasApiKey = !!process.env[activeConfig.envKey] || !!mergedSettings.env?.[activeConfig.envKey];
        } else {
          hasApiKey = !!process.env["OPENAI_API_KEY"] || !!mergedSettings.env?.["OPENAI_API_KEY"] || !!mergedSettings.security?.auth?.apiKey;
        }
        if (hasApiKey) {
          writeStdoutLine(
            t4("\u2713 Authentication Method: OpenAI-compatible Provider")
          );
          if (modelName) {
            writeStdoutLine(
              t4("  Current Model: {{model}}", { model: modelName })
            );
          }
          const baseUrl = activeConfig.baseUrl || mergedSettings.security?.auth?.baseUrl;
          if (baseUrl) {
            writeStdoutLine(t4("  Base URL: {{baseUrl}}", { baseUrl }));
          }
          writeStdoutLine(t4("  Status: API key configured\n"));
        } else {
          writeStdoutLine(
            t4(
              "\u26A0\uFE0F  Authentication Method: OpenAI-compatible Provider (Incomplete)"
            )
          );
          writeStdoutLine(
            t4("  Issue: API key not found in environment or settings\n")
          );
          writeStdoutLine(t4("  Run `qwen auth` to re-configure.\n"));
        }
      } else {
        const hasCodingPlanKey = !!process.env[CODING_PLAN_ENV_KEY2] || !!mergedSettings.env?.[CODING_PLAN_ENV_KEY2];
        const hasGenericApiKey = !!process.env["OPENAI_API_KEY"] || !!mergedSettings.env?.["OPENAI_API_KEY"] || !!mergedSettings.security?.auth?.apiKey;
        const hasCodingPlanMetadata = !modelName && (!!codingPlanRegion || !!codingPlanVersion);
        if (hasGenericApiKey) {
          writeStdoutLine(
            t4("\u2713 Authentication Method: OpenAI-compatible Provider")
          );
          if (modelName) {
            writeStdoutLine(
              t4("  Current Model: {{model}}", { model: modelName })
            );
          }
          const baseUrl = mergedSettings.security?.auth?.baseUrl;
          if (baseUrl) {
            writeStdoutLine(t4("  Base URL: {{baseUrl}}", { baseUrl }));
          }
          writeStdoutLine(t4("  Status: API key configured\n"));
        } else if (hasCodingPlanKey) {
          writeStdoutLine(
            t4("\u2713 Authentication Method: Alibaba Cloud Coding Plan")
          );
          if (codingPlanRegion) {
            const regionDisplay = codingPlanRegion === "china" /* CHINA */ ? t4("\u4E2D\u56FD (China) - \u963F\u91CC\u4E91\u767E\u70BC") : t4("Global - Alibaba Cloud");
            writeStdoutLine(
              t4("  Region: {{region}}", { region: regionDisplay })
            );
          }
          if (modelName) {
            writeStdoutLine(
              t4("  Current Model: {{model}}", { model: modelName })
            );
          }
          if (codingPlanVersion) {
            writeStdoutLine(
              t4("  Config Version: {{version}}", {
                version: codingPlanVersion.substring(0, 8) + "..."
              })
            );
          }
          writeStdoutLine(t4("  Status: API key configured\n"));
        } else if (hasCodingPlanMetadata) {
          writeStdoutLine(
            t4(
              "\u26A0\uFE0F  Authentication Method: Alibaba Cloud Coding Plan (Incomplete)"
            )
          );
          writeStdoutLine(
            t4("  Issue: API key not found in environment or settings\n")
          );
          writeStdoutLine(
            t4("  Run `qwen auth coding-plan` to re-configure.\n")
          );
        } else {
          writeStdoutLine(
            t4(
              "\u26A0\uFE0F  Authentication Method: OpenAI-compatible Provider (Incomplete)"
            )
          );
          writeStdoutLine(
            t4("  Issue: API key not found in environment or settings\n")
          );
          writeStdoutLine(t4("  Run `qwen auth` to re-configure.\n"));
        }
      }
    } else {
      writeStdoutLine(
        t4("\u2713 Authentication Method: {{type}}", { type: selectedType })
      );
      writeStdoutLine(t4("  Status: Configured\n"));
    }
    process.exit(0);
  } catch (error40) {
    writeStderrLine(
      t4("Failed to check authentication status: {{error}}", {
        error: getErrorMessage(error40)
      })
    );
    process.exit(1);
  }
}
__name(showAuthStatus, "showAuthStatus");

// packages/cli/src/commands/auth.ts
init_i18n();
var qwenOauthCommand = {
  command: "qwen-oauth",
  describe: t4("Authenticate using Qwen OAuth"),
  handler: /* @__PURE__ */ __name(async () => {
    await handleQwenAuth("qwen-oauth", {});
  }, "handler")
};
var codePlanCommand = {
  command: "coding-plan",
  describe: t4("Authenticate using Alibaba Cloud Coding Plan"),
  builder: /* @__PURE__ */ __name((yargs) => yargs.option("region", {
    alias: "r",
    describe: t4("Region for Coding Plan (china/global)"),
    type: "string"
  }).option("key", {
    alias: "k",
    describe: t4("API key for Coding Plan"),
    type: "string"
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    const region = argv["region"];
    const key = argv["key"];
    if (region && key) {
      await handleQwenAuth("coding-plan", { region, key });
    } else {
      await handleQwenAuth("coding-plan", {});
    }
  }, "handler")
};
var apiKeyCommand = {
  command: "api-key",
  describe: t4("Authenticate using an API key"),
  handler: /* @__PURE__ */ __name(async () => {
    await handleApiKeyAuth();
  }, "handler")
};
var openRouterCommand = {
  command: "openrouter",
  describe: t4("Authenticate using OpenRouter API key setup"),
  builder: /* @__PURE__ */ __name((yargs) => yargs.option("key", {
    alias: "k",
    describe: t4("API key for OpenRouter"),
    type: "string"
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    const key = argv["key"];
    await handleQwenAuth("openrouter", { key });
  }, "handler")
};
var statusCommand = {
  command: "status",
  describe: t4("Show current authentication status"),
  handler: /* @__PURE__ */ __name(async () => {
    await showAuthStatus();
  }, "handler")
};
var authCommand = {
  command: "auth",
  describe: t4(
    "Configure Qwen authentication with OpenRouter, Coding Plan, API Key, or Qwen-OAuth"
  ),
  builder: /* @__PURE__ */ __name((yargs) => yargs.command(qwenOauthCommand).command(codePlanCommand).command(openRouterCommand).command(apiKeyCommand).command(statusCommand).demandCommand(0).version(false), "builder"),
  handler: /* @__PURE__ */ __name(async () => {
    await runInteractiveAuth();
  }, "handler")
};

// packages/cli/src/utils/modelConfigUtils.ts
init_esbuild_shims();
init_dist4();
var AUTH_ENV_MODEL_VARS = {
  [AuthType2.USE_OPENAI]: ["OPENAI_MODEL", "QWEN_MODEL"],
  [AuthType2.USE_GEMINI]: ["GEMINI_MODEL"],
  [AuthType2.USE_VERTEX_AI]: ["GOOGLE_MODEL"],
  [AuthType2.USE_ANTHROPIC]: ["ANTHROPIC_MODEL"],
  [AuthType2.QWEN_OAUTH]: []
};
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 env6 = inputs.env ?? process.env;
  const authType = selectedAuthType;
  let resolvedModel;
  let sourceEnvVar;
  if (argv.model) {
    resolvedModel = argv.model;
  } else if (settings.model?.name) {
    resolvedModel = settings.model.name;
  } else if (authType && AUTH_ENV_MODEL_VARS[authType]) {
    for (const envVar of AUTH_ENV_MODEL_VARS[authType]) {
      if (env6[envVar]) {
        resolvedModel = env6[envVar];
        sourceEnvVar = envVar;
        break;
      }
    }
  }
  let modelProvider;
  if (resolvedModel && authType && settings.modelProviders) {
    const providers = settings.modelProviders[authType];
    if (providers && Array.isArray(providers)) {
      modelProvider = providers.find((p2) => p2.id === resolvedModel);
    }
  }
  const allModelEnvVars = Object.values(AUTH_ENV_MODEL_VARS).flat();
  const filteredEnv = { ...env6 };
  if (sourceEnvVar) {
    for (const envVar of allModelEnvVars) {
      if (envVar !== sourceEnvVar) {
        delete filteredEnv[envVar];
      }
    }
  } else {
    for (const envVar of allModelEnvVars) {
      delete filteredEnv[envVar];
    }
  }
  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: filteredEnv
  };
  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
var import_strip_json_comments3 = __toESM(require_strip_json_comments(), 1);
import * as fs110 from "node:fs";
import * as path111 from "node:path";
import { homedir as homedir28 } from "node:os";

// packages/cli/src/utils/resolvePath.ts
init_esbuild_shims();
import * as os34 from "node:os";
import * as path101 from "node:path";
function resolvePath3(p2) {
  if (!p2) {
    return "";
  }
  let expandedPath = p2;
  if (p2.toLowerCase().startsWith("%userprofile%")) {
    expandedPath = os34.homedir() + p2.substring("%userprofile%".length);
  } else if (p2 === "~" || p2.startsWith("~/")) {
    expandedPath = os34.homedir() + p2.substring(1);
  }
  return path101.normalize(expandedPath);
}
__name(resolvePath3, "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 path104 from "node:path";

// node_modules/find-up-simple/index.js
init_esbuild_shims();
import process27 from "node:process";
import fsPromises3 from "node:fs/promises";
import { fileURLToPath as fileURLToPath13 } from "node:url";
import path102 from "node:path";
var toPath = /* @__PURE__ */ __name((urlOrPath) => urlOrPath instanceof URL ? fileURLToPath13(urlOrPath) : urlOrPath, "toPath");
async function findUp(name4, {
  cwd: cwd6 = process27.cwd(),
  type = "file",
  stopAt
} = {}) {
  let directory = path102.resolve(toPath(cwd6) ?? "");
  const { root } = path102.parse(directory);
  stopAt = path102.resolve(directory, toPath(stopAt ?? root));
  const isAbsoluteName = path102.isAbsolute(name4);
  while (directory) {
    const filePath = isAbsoluteName ? name4 : path102.join(directory, name4);
    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 = path102.dirname(directory);
  }
}
__name(findUp, "findUp");

// node_modules/read-pkg/index.js
init_esbuild_shims();
import fsPromises4 from "node:fs/promises";
import path103 from "node:path";

// node_modules/parse-json/index.js
init_esbuild_shims();
var import_code_frame = __toESM(require_lib7(), 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 (error40) {
    throw new JSONError({
      jsonParseError: error40,
      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 fileURLToPath14 } from "node:url";
function toPath2(urlOrPath) {
  return urlOrPath instanceof URL ? fileURLToPath14(urlOrPath) : urlOrPath;
}
__name(toPath2, "toPath");

// node_modules/read-pkg/index.js
var getPackagePath = /* @__PURE__ */ __name((cwd6) => path103.resolve(toPath2(cwd6) ?? ".", "package.json"), "getPackagePath");
var _readPackage = /* @__PURE__ */ __name((file2, normalize13) => {
  const json3 = typeof file2 === "string" ? parseJson(file2) : file2;
  if (normalize13) {
    (0, import_normalize_package_data.default)(json3);
  }
  return json3;
}, "_readPackage");
async function readPackage({ cwd: cwd6, normalize: normalize13 = true } = {}) {
  const packageFile = await fsPromises4.readFile(getPackagePath(cwd6), "utf8");
  return _readPackage(packageFile, normalize13);
}
__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: path104.dirname(filePath) }),
    path: filePath
  };
}
__name(readPackageUp, "readPackageUp");

// packages/cli/src/utils/package.ts
import { fileURLToPath as fileURLToPath15 } from "node:url";
import path105 from "node:path";
var __filename4 = fileURLToPath15(import.meta.url);
var __dirname6 = path105.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.15.6";
}
__name(getCliVersion, "getCliVersion");

// packages/cli/src/config/sandboxConfig.ts
init_esbuild_shims();
init_dist4();
var import_command_exists = __toESM(require_command_exists2(), 1);
import * as os35 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["QWEN_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 QWEN_SANDBOX)`
    );
  }
  if (os35.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(
      "QWEN_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in QWEN_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["QWEN_SANDBOX_IMAGE"] ?? settings.tools?.sandboxImage ?? 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 EventEmitter11 } from "node:events";
var appEvents = new EventEmitter11();

// packages/cli/src/commands/mcp.ts
init_esbuild_shims();

// packages/cli/src/commands/mcp/add.ts
init_esbuild_shims();
init_stdioHelpers();
async function addMcpServer(name4, commandOrUrl, args2, options2) {
  const {
    scope,
    transport,
    env: env6,
    header,
    timeout: timeout2,
    trust,
    description,
    includeTools,
    excludeTools,
    oauthClientId,
    oauthClientSecret,
    oauthRedirectUri,
    oauthAuthorizationUrl,
    oauthTokenUrl,
    oauthScopes
  } = 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 scopes = oauthScopes?.flatMap((s5) => s5.split(",")).map((s5) => s5.trim()).filter(Boolean);
  const hasOAuth = Boolean(
    oauthClientId || oauthClientSecret || oauthRedirectUri || oauthAuthorizationUrl || oauthTokenUrl || scopes && scopes.length > 0
  );
  if (hasOAuth && transport === "stdio") {
    writeStderrLine(
      "Error: OAuth options (--oauth-*) are only supported with --transport sse or --transport http."
    );
    process.exit(1);
  }
  const oauthConfig = hasOAuth ? {
    enabled: true,
    ...oauthClientId && { clientId: oauthClientId },
    ...oauthClientSecret && { clientSecret: oauthClientSecret },
    ...oauthRedirectUri && { redirectUri: oauthRedirectUri },
    ...oauthAuthorizationUrl && {
      authorizationUrl: oauthAuthorizationUrl
    },
    ...oauthTokenUrl && { tokenUrl: oauthTokenUrl },
    ...scopes && scopes.length > 0 && { scopes }
  } : void 0;
  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,
        oauth: oauthConfig
      };
      break;
    case "http":
      newServer = {
        httpUrl: commandOrUrl,
        headers,
        timeout: timeout2,
        trust,
        description,
        includeTools,
        excludeTools,
        oauth: oauthConfig
      };
      break;
    case "stdio":
    default:
      newServer = {
        command: commandOrUrl,
        args: args2?.map(String),
        env: env6?.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[name4];
  if (isExistingServer) {
    writeStdoutLine(
      `MCP server "${name4}" is already configured within ${scope} settings.`
    );
  }
  mcpServers[name4] = newServer;
  settings.setValue(settingsScope, "mcpServers", mcpServers);
  if (isExistingServer) {
    writeStdoutLine(`MCP server "${name4}" updated in ${scope} settings.`);
  } else {
    writeStdoutLine(
      `MCP server "${name4}" 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,
    nargs: 1
  }).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,
    nargs: 1
  }).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
  }).option("oauth-client-id", {
    describe: "OAuth client ID for MCP server authentication",
    type: "string"
  }).option("oauth-client-secret", {
    describe: "OAuth client secret for MCP server authentication",
    type: "string"
  }).option("oauth-redirect-uri", {
    describe: "OAuth redirect URI (e.g., https://your-server.com/oauth/callback). Defaults to localhost for local setups.",
    type: "string"
  }).option("oauth-authorization-url", {
    describe: "OAuth authorization URL",
    type: "string"
  }).option("oauth-token-url", {
    describe: "OAuth token URL",
    type: "string"
  }).option("oauth-scopes", {
    describe: "OAuth scopes (comma-separated)",
    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"],
        oauthClientId: argv["oauthClientId"],
        oauthClientSecret: argv["oauthClientSecret"],
        oauthRedirectUri: argv["oauthRedirectUri"],
        oauthAuthorizationUrl: argv["oauthAuthorizationUrl"],
        oauthTokenUrl: argv["oauthTokenUrl"],
        oauthScopes: argv["oauthScopes"]
      }
    );
  }, "handler")
};

// packages/cli/src/commands/mcp/remove.ts
init_esbuild_shims();
init_stdioHelpers();
init_dist4();
async function removeMcpServer(name4, 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[name4]) {
    writeStdoutLine(`Server "${name4}" not found in ${scope} settings.`);
    return;
  }
  delete mcpServers[name4];
  settings.setValue(settingsScope, "mcpServers", mcpServers);
  try {
    const tokenStorage = new MCPOAuthTokenStorage();
    await tokenStorage.deleteCredentials(name4);
  } catch {
  }
  writeStdoutLine(`Server "${name4}" 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();
init_stdioHelpers();
init_dist4();

// 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: _enum2(["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 = _enum2(["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 = _enum2(["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: _enum2(["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 = _enum2(["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: _enum2(["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: _enum2(["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(_enum2(["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(_enum2(["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: _enum2(["email", "uri", "date", "date-time"]).optional(),
  default: string2().optional()
});
var NumberSchemaSchema2 = object2({
  type: _enum2(["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: _enum2(["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 error40 = new McpError2(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
                    resolver(error40);
                  }
                } 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 (error40) {
          throw new McpError2(ErrorCode2.InvalidParams, `Failed to list tasks: ${error40 instanceof Error ? error40.message : String(error40)}`);
        }
      });
      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 (error40) {
          if (error40 instanceof McpError2) {
            throw error40;
          }
          throw new McpError2(ErrorCode2.InvalidRequest, `Failed to cancel task: ${error40 instanceof Error ? error40.message : String(error40)}`);
        }
      });
    }
  }
  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 info2 = this._timeoutInfo.get(messageId);
    if (!info2)
      return false;
    const totalElapsed = Date.now() - info2.startTime;
    if (info2.maxTotalTimeout && totalElapsed >= info2.maxTotalTimeout) {
      this._timeoutInfo.delete(messageId);
      throw McpError2.fromError(ErrorCode2.RequestTimeout, "Maximum total timeout exceeded", {
        maxTotalTimeout: info2.maxTotalTimeout,
        totalElapsed
      });
    }
    clearTimeout(info2.timeoutId);
    info2.timeoutId = setTimeout(info2.onTimeout, info2.timeout);
    return true;
  }
  _cleanupTimeout(messageId) {
    const info2 = this._timeoutInfo.get(messageId);
    if (info2) {
      clearTimeout(info2.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 = (error40) => {
      _onerror2?.(error40);
      this._onerror(error40);
    };
    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 error40 = McpError2.fromError(ErrorCode2.ConnectionClosed, "Connection closed");
    this._transport = void 0;
    this.onclose?.();
    for (const handler of responseHandlers.values()) {
      handler(error40);
    }
  }
  _onerror(error40) {
    this.onerror?.(error40);
  }
  _onnotification(notification) {
    const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
    if (handler === void 0) {
      return;
    }
    Promise.resolve().then(() => handler(notification)).catch((error40) => this._onerror(new Error(`Uncaught error in notification handler: ${error40}`)));
  }
  _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((error40) => this._onerror(new Error(`Failed to enqueue error response: ${error40}`)));
      } else {
        capturedTransport?.send(errorResponse).catch((error40) => this._onerror(new Error(`Failed to send an error response: ${error40}`)));
      }
      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 (error40) => {
      if (abortController.signal.aborted) {
        return;
      }
      const errorResponse = {
        jsonrpc: "2.0",
        id: request4.id,
        error: {
          code: Number.isSafeInteger(error40["code"]) ? error40["code"] : ErrorCode2.InternalError,
          message: error40.message ?? "Internal error",
          ...error40["data"] !== void 0 && { data: error40["data"] }
        }
      };
      if (relatedTaskId && this._taskMessageQueue) {
        await this._enqueueTaskMessage(relatedTaskId, {
          type: "error",
          message: errorResponse,
          timestamp: Date.now()
        }, capturedTransport?.sessionId);
      } else {
        await capturedTransport?.send(errorResponse);
      }
    }).catch((error40) => this._onerror(new Error(`Failed to send response: ${error40}`))).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 (error40) {
        this._responseHandlers.delete(messageId);
        this._progressHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        responseHandler(error40);
        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 error40 = new McpError2(response.error.code, response.error.message, response.error.data);
        resolver(error40);
      }
      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 error40 = McpError2.fromError(response.error.code, response.error.message, response.error.data);
      handler(error40);
    }
  }
  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 (error40) {
        yield {
          type: "error",
          error: error40 instanceof McpError2 ? error40 : new McpError2(ErrorCode2.InternalError, String(error40))
        };
      }
      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((resolve42) => setTimeout(resolve42, pollInterval));
        options2?.signal?.throwIfAborted();
      }
    } catch (error40) {
      yield {
        type: "error",
        error: error40 instanceof McpError2 ? error40 : new McpError2(ErrorCode2.InternalError, String(error40))
      };
    }
  }
  /**
   * 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((resolve42, reject) => {
      const earlyReject = /* @__PURE__ */ __name((error40) => {
        reject(error40);
      }, "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((error41) => this._onerror(new Error(`Failed to send cancellation: ${error41}`)));
        const error40 = reason instanceof McpError2 ? reason : new McpError2(ErrorCode2.RequestTimeout, String(reason));
        reject(error40);
      }, "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 {
            resolve42(parseResult.data);
          }
        } catch (error40) {
          reject(error40);
        }
      });
      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((error40) => {
          this._cleanupTimeout(messageId);
          reject(error40);
        });
      } else {
        this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error40) => {
          this._cleanupTimeout(messageId);
          reject(error40);
        });
      }
    });
  }
  /**
   * 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((error40) => this._onerror(error40));
      });
      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((resolve42, reject) => {
      if (signal.aborted) {
        reject(new McpError2(ErrorCode2.InvalidRequest, "Request cancelled"));
        return;
      }
      const timeoutId = setTimeout(resolve42, 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 isPlainObject7(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
__name(isPlainObject7, "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 (isPlainObject7(baseValue) && isPlainObject7(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_dist(), 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 stream5 = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
    const validator = clientInternal.getToolOutputValidator(params.name);
    for await (const message of stream5) {
      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 (error40) {
            if (error40 instanceof McpError2) {
              yield { type: "error", error: error40 };
              return;
            }
            yield {
              type: "error",
              error: new McpError2(ErrorCode2.InvalidParams, `Failed to validate structured content: ${error40 instanceof Error ? error40.message : String(error40)}`)
            };
            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 (error40) {
      void this.close();
      throw error40;
    }
  }
  /**
   * 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 (error40) {
          if (error40 instanceof McpError2) {
            throw error40;
          }
          throw new McpError2(ErrorCode2.InvalidParams, `Failed to validate structured content: ${error40 instanceof Error ? error40.message : String(error40)}`);
        }
      }
    }
    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 error40 = e4 instanceof Error ? e4 : new Error(String(e4));
        onChanged(error40, 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 statusIndicator2 = "";
    let statusText = "";
    switch (status) {
      case MCPServerStatus.CONNECTED:
        statusIndicator2 = COLOR_GREEN + "\u2713" + RESET_COLOR;
        statusText = "Connected";
        break;
      case MCPServerStatus.CONNECTING:
        statusIndicator2 = COLOR_YELLOW + "\u2026" + RESET_COLOR;
        statusText = "Connecting";
        break;
      case MCPServerStatus.DISCONNECTED:
      default:
        statusIndicator2 = 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(`${statusIndicator2} ${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/reconnect.ts
init_esbuild_shims();
init_stdioHelpers();
init_dist4();
async function getMcpServersFromConfig2(extensionManager) {
  const settings = loadSettings();
  const extManager = extensionManager ?? new ExtensionManager({
    isWorkspaceTrusted: !!isWorkspaceTrusted(settings.merged),
    telemetrySettings: settings.merged.telemetry
  });
  if (!extensionManager) {
    await extManager.refreshCache();
  }
  const extensions = extManager.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(getMcpServersFromConfig2, "getMcpServersFromConfig");
async function createMinimalConfig() {
  const settings = loadSettings();
  const cwd6 = process.cwd();
  const fileService = new FileDiscoveryService(cwd6);
  const config2 = new Config({
    sessionId: "mcp-reconnect",
    targetDir: cwd6,
    cwd: cwd6,
    debugMode: false,
    mcpServers: settings.merged.mcpServers || {},
    fileDiscoveryService: fileService,
    mcpServerCommand: settings.merged.mcp?.serverCommand
  });
  await config2.initialize();
  return config2;
}
__name(createMinimalConfig, "createMinimalConfig");
function createReconnectError(message, exitCode = 1) {
  const error40 = new Error(message);
  error40.exitCode = exitCode;
  return error40;
}
__name(createReconnectError, "createReconnectError");
async function reconnectMcpServer(serverName) {
  const mcpServers = await getMcpServersFromConfig2();
  if (!mcpServers[serverName]) {
    throw createReconnectError(
      `Error: Server "${serverName}" not found in configuration.`
    );
  }
  writeStdoutLine(`Reconnecting to server "${serverName}"...`);
  try {
    const config2 = await createMinimalConfig();
    const toolRegistry = config2.getToolRegistry();
    await toolRegistry.discoverToolsForServer(serverName);
    writeStdoutLine(`Successfully reconnected to server "${serverName}".`);
    await config2.shutdown();
  } catch (error40) {
    const message = error40 instanceof Error ? error40.message : String(error40);
    throw createReconnectError(
      `Failed to reconnect to server "${serverName}": ${message}`
    );
  }
}
__name(reconnectMcpServer, "reconnectMcpServer");
async function reconnectAllMcpServers() {
  const settings = loadSettings();
  const extensionManager = new ExtensionManager({
    isWorkspaceTrusted: !!isWorkspaceTrusted(settings.merged),
    telemetrySettings: settings.merged.telemetry
  });
  await extensionManager.refreshCache();
  const mcpServers = await getMcpServersFromConfig2(extensionManager);
  const serverNames = Object.keys(mcpServers);
  if (serverNames.length === 0) {
    writeStdoutLine("No MCP servers configured.");
    return;
  }
  writeStdoutLine("Reconnecting to all MCP servers...\n");
  let config2;
  try {
    config2 = await createMinimalConfig();
    const toolRegistry = config2.getToolRegistry();
    for (const serverName of serverNames) {
      try {
        await toolRegistry.discoverToolsForServer(serverName);
        writeStdoutLine(`\u2713 ${serverName}: Reconnected successfully`);
      } catch (error40) {
        const message = error40 instanceof Error ? error40.message : String(error40);
        writeStdoutLine(`\u2717 ${serverName}: Failed - ${message}`);
      }
    }
  } finally {
    if (config2) {
      await config2.shutdown();
    }
  }
}
__name(reconnectAllMcpServers, "reconnectAllMcpServers");
var reconnectCommand = {
  command: "reconnect [server-name]",
  describe: "Reconnect MCP server(s)",
  builder: /* @__PURE__ */ __name((yargs) => yargs.usage("Usage: qwen mcp reconnect [options] [server-name]").positional("server-name", {
    describe: "Name of the server to reconnect",
    type: "string"
  }).option("all", {
    alias: "a",
    describe: "Reconnect all configured servers",
    type: "boolean",
    default: false
  }).conflicts("server-name", "all").check((argv) => {
    const serverName = argv["server-name"];
    const all4 = argv["all"];
    if (!serverName && !all4) {
      throw new Error(
        "Please specify a server name or use --all to reconnect all servers."
      );
    }
    return true;
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    const serverName = argv["server-name"];
    const all4 = argv["all"];
    try {
      if (all4) {
        await reconnectAllMcpServers();
      } else if (serverName) {
        await reconnectMcpServer(serverName);
      }
    } catch (error40) {
      const message = error40 instanceof Error ? error40.message : String(error40);
      const exitCode = error40?.exitCode ?? 1;
      writeStderrLine(message);
      process.exit(exitCode);
    }
  }, "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).command(reconnectCommand).demandCommand(1, "You need at least one command before continuing.").version(false), "builder"),
  handler: /* @__PURE__ */ __name(() => {
  }, "handler")
};

// packages/cli/src/commands/channel.ts
init_esbuild_shims();

// packages/cli/src/commands/channel/start.ts
init_esbuild_shims();
var import_undici4 = __toESM(require_undici2(), 1);
init_dist4();
import * as path109 from "node:path";
import * as os38 from "node:os";
init_stdioHelpers();
init_dist5();

// packages/cli/src/commands/channel/channel-registry.ts
init_esbuild_shims();
var registry2 = /* @__PURE__ */ new Map();
var builtinsPromise = null;
function ensureBuiltins() {
  if (!builtinsPromise) {
    builtinsPromise = (async () => {
      const [telegram, weixin, dingtalk] = await Promise.all([
        Promise.resolve().then(() => (init_dist7(), dist_exports2)),
        Promise.resolve().then(() => (init_dist8(), dist_exports3)),
        Promise.resolve().then(() => (init_dist10(), dist_exports4))
      ]);
      for (const mod2 of [telegram, weixin, dingtalk]) {
        registry2.set(mod2.plugin.channelType, mod2.plugin);
      }
    })();
  }
  return builtinsPromise;
}
__name(ensureBuiltins, "ensureBuiltins");
function registerPlugin(plugin4) {
  if (registry2.has(plugin4.channelType)) {
    throw new Error(
      `Channel type "${plugin4.channelType}" is already registered.`
    );
  }
  registry2.set(plugin4.channelType, plugin4);
}
__name(registerPlugin, "registerPlugin");
async function getPlugin(channelType) {
  await ensureBuiltins();
  return registry2.get(channelType);
}
__name(getPlugin, "getPlugin");
async function supportedTypes() {
  await ensureBuiltins();
  return [...registry2.keys()];
}
__name(supportedTypes, "supportedTypes");

// packages/cli/src/commands/channel/config-utils.ts
init_esbuild_shims();
import * as path107 from "node:path";
function resolveEnvVars(value) {
  if (value.startsWith("$")) {
    const envName = value.substring(1);
    const envValue = process.env[envName];
    if (!envValue) {
      throw new Error(
        `Environment variable ${envName} is not set (referenced as ${value})`
      );
    }
    return envValue;
  }
  return value;
}
__name(resolveEnvVars, "resolveEnvVars");
function findCliEntryPath() {
  const mainModule = process.argv[1];
  if (mainModule) {
    return path107.resolve(mainModule);
  }
  throw new Error("Cannot determine CLI entry path");
}
__name(findCliEntryPath, "findCliEntryPath");
async function parseChannelConfig(name4, rawConfig) {
  if (!rawConfig["type"]) {
    throw new Error(`Channel "${name4}" is missing required field "type".`);
  }
  const channelType = rawConfig["type"];
  const plugin4 = await getPlugin(channelType);
  if (!plugin4) {
    const types7 = await supportedTypes();
    throw new Error(
      `Channel type "${channelType}" is not supported. Available: ${types7.join(", ")}`
    );
  }
  for (const field of plugin4.requiredConfigFields ?? []) {
    if (!rawConfig[field]) {
      throw new Error(
        `Channel "${name4}" (${channelType}) requires "${field}".`
      );
    }
  }
  const token2 = rawConfig["token"] ? resolveEnvVars(rawConfig["token"]) : "";
  const clientId = rawConfig["clientId"] ? resolveEnvVars(rawConfig["clientId"]) : void 0;
  const clientSecret = rawConfig["clientSecret"] ? resolveEnvVars(rawConfig["clientSecret"]) : void 0;
  return {
    ...rawConfig,
    type: channelType,
    token: token2,
    clientId,
    clientSecret,
    senderPolicy: rawConfig["senderPolicy"] || "allowlist",
    allowedUsers: rawConfig["allowedUsers"] || [],
    sessionScope: rawConfig["sessionScope"] || "user",
    cwd: rawConfig["cwd"] || process.cwd(),
    approvalMode: rawConfig["approvalMode"],
    instructions: rawConfig["instructions"],
    model: rawConfig["model"],
    groupPolicy: rawConfig["groupPolicy"] || "disabled",
    groups: rawConfig["groups"] || {}
  };
}
__name(parseChannelConfig, "parseChannelConfig");

// packages/cli/src/commands/channel/pidfile.ts
init_esbuild_shims();
import {
  existsSync as existsSync34,
  readFileSync as readFileSync27,
  writeFileSync as writeFileSync22,
  mkdirSync as mkdirSync19,
  unlinkSync as unlinkSync6
} from "node:fs";
import * as path108 from "node:path";
import * as os37 from "node:os";
function pidFilePath() {
  return path108.join(os37.homedir(), ".qwen", "channels", "service.pid");
}
__name(pidFilePath, "pidFilePath");
function isProcessAlive(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}
__name(isProcessAlive, "isProcessAlive");
function readServiceInfo() {
  const filePath = pidFilePath();
  if (!existsSync34(filePath)) return null;
  let info2;
  try {
    info2 = JSON.parse(readFileSync27(filePath, "utf-8"));
  } catch {
    try {
      unlinkSync6(filePath);
    } catch {
    }
    return null;
  }
  if (!isProcessAlive(info2.pid)) {
    try {
      unlinkSync6(filePath);
    } catch {
    }
    return null;
  }
  return info2;
}
__name(readServiceInfo, "readServiceInfo");
function writeServiceInfo(channels) {
  const filePath = pidFilePath();
  const dir = path108.dirname(filePath);
  if (!existsSync34(dir)) {
    mkdirSync19(dir, { recursive: true });
  }
  const info2 = {
    pid: process.pid,
    startedAt: (/* @__PURE__ */ new Date()).toISOString(),
    channels
  };
  writeFileSync22(filePath, JSON.stringify(info2, null, 2), "utf-8");
}
__name(writeServiceInfo, "writeServiceInfo");
function removeServiceInfo() {
  const filePath = pidFilePath();
  if (existsSync34(filePath)) {
    try {
      unlinkSync6(filePath);
    } catch {
    }
  }
}
__name(removeServiceInfo, "removeServiceInfo");
function signalService(pid, signal = "SIGTERM") {
  try {
    process.kill(pid, signal);
    return true;
  } catch {
    return false;
  }
}
__name(signalService, "signalService");
async function waitForExit(pid, timeoutMs = 5e3, pollMs = 200) {
  const start2 = Date.now();
  while (Date.now() - start2 < timeoutMs) {
    if (!isProcessAlive(pid)) return true;
    await new Promise((r5) => setTimeout(r5, pollMs));
  }
  return !isProcessAlive(pid);
}
__name(waitForExit, "waitForExit");

// packages/cli/src/commands/channel/start.ts
var MAX_CRASH_RESTARTS = 3;
var CRASH_WINDOW_MS = 5 * 60 * 1e3;
var RESTART_DELAY_MS = 3e3;
function resolveProxy(cliProxy) {
  const proxyUrl = normalizeProxyUrl(
    cliProxy || process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"]
  );
  if (proxyUrl) {
    (0, import_undici4.setGlobalDispatcher)(new import_undici4.ProxyAgent(proxyUrl));
  }
  return proxyUrl;
}
__name(resolveProxy, "resolveProxy");
function sessionsPath() {
  return path109.join(os38.homedir(), ".qwen", "channels", "sessions.json");
}
__name(sessionsPath, "sessionsPath");
function loadChannelsConfig() {
  const settings = loadSettings(process.cwd());
  const channels = settings.merged.channels;
  return channels || {};
}
__name(loadChannelsConfig, "loadChannelsConfig");
async function loadChannelsFromExtensions() {
  let loaded = 0;
  try {
    const extensionManager = await getExtensionManager();
    const extensions = extensionManager.getLoadedExtensions().filter((e4) => e4.isActive && e4.channels);
    for (const ext2 of extensions) {
      for (const [channelType, channelDef] of Object.entries(ext2.channels)) {
        if (await getPlugin(channelType)) {
          writeStderrLine(
            `[Extensions] Skipping channel "${channelType}" from "${ext2.name}": type already registered`
          );
          continue;
        }
        const entryPath = path109.join(ext2.path, channelDef.entry);
        try {
          const module2 = await import(entryPath);
          const plugin4 = module2.plugin;
          if (!plugin4 || typeof plugin4.createChannel !== "function") {
            writeStderrLine(
              `[Extensions] "${ext2.name}": channel entry point does not export a valid plugin object`
            );
            continue;
          }
          if (plugin4.channelType !== channelType) {
            writeStderrLine(
              `[Extensions] "${ext2.name}": channelType mismatch \u2014 manifest says "${channelType}", plugin says "${plugin4.channelType}"`
            );
            continue;
          }
          registerPlugin(plugin4);
          loaded++;
          writeStdoutLine(
            `[Extensions] Loaded channel "${channelType}" from "${ext2.name}"`
          );
        } catch (err2) {
          writeStderrLine(
            `[Extensions] Failed to load channel "${channelType}" from "${ext2.name}": ${err2 instanceof Error ? err2.message : String(err2)}`
          );
        }
      }
    }
  } catch (err2) {
    writeStderrLine(
      `[Extensions] Failed to load extensions: ${err2 instanceof Error ? err2.message : String(err2)}`
    );
  }
  return loaded;
}
__name(loadChannelsFromExtensions, "loadChannelsFromExtensions");
async function createChannel(name4, config2, bridge, options2) {
  const channelPlugin = await getPlugin(config2.type);
  if (!channelPlugin) {
    throw new Error(`Unknown channel type: "${config2.type}".`);
  }
  return channelPlugin.createChannel(name4, config2, bridge, options2);
}
__name(createChannel, "createChannel");
function registerToolCallDispatch(bridge, router, channels) {
  bridge.on("toolCall", (event) => {
    const target = router.getTarget(event.sessionId);
    if (target) {
      const channel = channels.get(target.channelName);
      if (channel) {
        channel.onToolCall(target.chatId, event);
      }
    }
  });
}
__name(registerToolCallDispatch, "registerToolCallDispatch");
function checkDuplicateInstance() {
  const existing = readServiceInfo();
  if (existing) {
    writeStderrLine(
      `Error: Channel service is already running (PID ${existing.pid}, started ${existing.startedAt}).`
    );
    writeStderrLine('Use "qwen channel stop" to stop it first.');
    process.exit(1);
  }
}
__name(checkDuplicateInstance, "checkDuplicateInstance");
async function startSingle(name4, proxy2) {
  checkDuplicateInstance();
  const channelsConfig = loadChannelsConfig();
  await loadChannelsFromExtensions();
  if (!channelsConfig[name4]) {
    writeStderrLine(
      `Error: Channel "${name4}" not found in settings. Add it to channels.${name4} in settings.json.`
    );
    process.exit(1);
  }
  let config2;
  try {
    config2 = await parseChannelConfig(
      name4,
      channelsConfig[name4]
    );
  } catch (err2) {
    writeStderrLine(
      `Error: ${err2 instanceof Error ? err2.message : String(err2)}`
    );
    process.exit(1);
  }
  const cliEntryPath = findCliEntryPath();
  let shuttingDown = false;
  const crashTimestamps = [];
  const bridgeOpts = { cliEntryPath, cwd: config2.cwd, model: config2.model };
  let bridge = new AcpBridge(bridgeOpts);
  await bridge.start();
  const router = new SessionRouter(
    bridge,
    config2.cwd,
    config2.sessionScope,
    sessionsPath()
  );
  const channels = /* @__PURE__ */ new Map();
  const channel = await createChannel(name4, config2, bridge, { router, proxy: proxy2 });
  channels.set(name4, channel);
  registerToolCallDispatch(bridge, router, channels);
  try {
    await channel.connect();
  } catch (err2) {
    writeStderrLine(
      `Error: ${err2 instanceof Error ? err2.message : String(err2)}`
    );
    bridge.stop();
    process.exit(1);
  }
  writeServiceInfo([name4]);
  writeStdoutLine(`[Channel] "${name4}" is running. Press Ctrl+C to stop.`);
  const attachDisconnectHandler = /* @__PURE__ */ __name((b2) => {
    b2.on("disconnected", async () => {
      if (shuttingDown) return;
      const now = Date.now();
      crashTimestamps.push(now);
      const recentCrashes = crashTimestamps.filter(
        (ts) => now - ts < CRASH_WINDOW_MS
      );
      if (recentCrashes.length > MAX_CRASH_RESTARTS) {
        writeStderrLine(
          `[Channel] Bridge crashed ${recentCrashes.length} times in ${CRASH_WINDOW_MS / 1e3}s. Giving up.`
        );
        channel.disconnect();
        router.clearAll();
        removeServiceInfo();
        process.exit(1);
      }
      writeStderrLine(
        `[Channel] Bridge crashed (${recentCrashes.length}/${MAX_CRASH_RESTARTS} in window). Restarting in ${RESTART_DELAY_MS / 1e3}s...`
      );
      await new Promise((r5) => setTimeout(r5, RESTART_DELAY_MS));
      try {
        bridge = new AcpBridge(bridgeOpts);
        await bridge.start();
        router.setBridge(bridge);
        channel.setBridge(bridge);
        registerToolCallDispatch(bridge, router, channels);
        attachDisconnectHandler(bridge);
        const result = await router.restoreSessions();
        writeStdoutLine(
          `[Channel] Bridge restarted. Sessions restored: ${result.restored}, failed: ${result.failed}`
        );
      } catch (err2) {
        writeStderrLine(
          `[Channel] Failed to restart bridge: ${err2 instanceof Error ? err2.message : String(err2)}`
        );
      }
    });
  }, "attachDisconnectHandler");
  attachDisconnectHandler(bridge);
  const shutdown = /* @__PURE__ */ __name(() => {
    shuttingDown = true;
    writeStdoutLine("\n[Channel] Shutting down...");
    channel.disconnect();
    bridge.stop();
    router.clearAll();
    removeServiceInfo();
    process.exit(0);
  }, "shutdown");
  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);
  await new Promise(() => {
  });
}
__name(startSingle, "startSingle");
async function startAll(proxy2) {
  checkDuplicateInstance();
  const channelsConfig = loadChannelsConfig();
  await loadChannelsFromExtensions();
  if (Object.keys(channelsConfig).length === 0) {
    writeStderrLine(
      'Error: No channels configured in settings.json. Add entries under "channels".'
    );
    process.exit(1);
  }
  const parsed = [];
  for (const [name4, raw2] of Object.entries(channelsConfig)) {
    try {
      parsed.push({
        name: name4,
        config: await parseChannelConfig(name4, raw2)
      });
    } catch (err2) {
      writeStderrLine(
        `Error in channel "${name4}": ${err2 instanceof Error ? err2.message : String(err2)}`
      );
      process.exit(1);
    }
  }
  const cliEntryPath = findCliEntryPath();
  const defaultCwd = process.cwd();
  let shuttingDown = false;
  const crashTimestamps = [];
  const models = [
    ...new Set(parsed.map((p2) => p2.config.model).filter(Boolean))
  ];
  if (models.length > 1) {
    writeStderrLine(
      `[Channel] Warning: Multiple models configured (${models.join(", ")}). Shared bridge will use "${models[0]}".`
    );
  }
  const bridgeOpts = {
    cliEntryPath,
    cwd: defaultCwd,
    model: models[0]
  };
  let bridge = new AcpBridge(bridgeOpts);
  await bridge.start();
  const router = new SessionRouter(bridge, defaultCwd, "user", sessionsPath());
  for (const { name: name4, config: config2 } of parsed) {
    router.setChannelScope(name4, config2.sessionScope);
  }
  const channels = /* @__PURE__ */ new Map();
  writeStdoutLine(
    `[Channel] Starting ${parsed.length} channel(s): ${parsed.map((p2) => p2.name).join(", ")}`
  );
  for (const { name: name4, config: config2 } of parsed) {
    channels.set(
      name4,
      await createChannel(name4, config2, bridge, { router, proxy: proxy2 })
    );
  }
  registerToolCallDispatch(bridge, router, channels);
  let connectedCount = 0;
  for (const [name4, channel] of channels) {
    try {
      await channel.connect();
      connectedCount++;
      writeStdoutLine(`[Channel] "${name4}" connected.`);
    } catch (err2) {
      writeStderrLine(
        `[Channel] Failed to connect "${name4}": ${err2 instanceof Error ? err2.message : String(err2)}`
      );
    }
  }
  if (connectedCount === 0) {
    writeStderrLine("[Channel] No channels connected. Exiting.");
    bridge.stop();
    process.exit(1);
  }
  writeServiceInfo(parsed.map((p2) => p2.name));
  writeStdoutLine(
    `[Channel] Running ${connectedCount} channel(s). Press Ctrl+C to stop.`
  );
  const attachDisconnectHandler = /* @__PURE__ */ __name((b2) => {
    b2.on("disconnected", async () => {
      if (shuttingDown) return;
      const now = Date.now();
      crashTimestamps.push(now);
      const recentCrashes = crashTimestamps.filter(
        (ts) => now - ts < CRASH_WINDOW_MS
      );
      if (recentCrashes.length > MAX_CRASH_RESTARTS) {
        writeStderrLine(
          `[Channel] Bridge crashed ${recentCrashes.length} times in ${CRASH_WINDOW_MS / 1e3}s. Giving up.`
        );
        for (const channel of channels.values()) {
          try {
            channel.disconnect();
          } catch {
          }
        }
        router.clearAll();
        removeServiceInfo();
        process.exit(1);
      }
      writeStderrLine(
        `[Channel] Bridge crashed (${recentCrashes.length}/${MAX_CRASH_RESTARTS} in window). Restarting in ${RESTART_DELAY_MS / 1e3}s...`
      );
      await new Promise((r5) => setTimeout(r5, RESTART_DELAY_MS));
      try {
        bridge = new AcpBridge(bridgeOpts);
        await bridge.start();
        router.setBridge(bridge);
        for (const channel of channels.values()) {
          channel.setBridge(bridge);
        }
        registerToolCallDispatch(bridge, router, channels);
        attachDisconnectHandler(bridge);
        const result = await router.restoreSessions();
        writeStdoutLine(
          `[Channel] Bridge restarted. Sessions restored: ${result.restored}, failed: ${result.failed}`
        );
      } catch (err2) {
        writeStderrLine(
          `[Channel] Failed to restart bridge: ${err2 instanceof Error ? err2.message : String(err2)}`
        );
      }
    });
  }, "attachDisconnectHandler");
  attachDisconnectHandler(bridge);
  const shutdown = /* @__PURE__ */ __name(() => {
    shuttingDown = true;
    writeStdoutLine("\n[Channel] Shutting down...");
    for (const [name4, channel] of channels) {
      try {
        channel.disconnect();
        writeStdoutLine(`[Channel] "${name4}" disconnected.`);
      } catch {
      }
    }
    bridge.stop();
    router.clearAll();
    removeServiceInfo();
    process.exit(0);
  }, "shutdown");
  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);
  await new Promise(() => {
  });
}
__name(startAll, "startAll");
var startCommand = {
  command: "start [name]",
  describe: "Start channels (all if no name given, or a single named channel)",
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    type: "string",
    describe: "Channel name (omit to start all configured channels)"
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    const proxy2 = resolveProxy(
      argv["proxy"]
    );
    if (argv.name) {
      await startSingle(argv.name, proxy2);
    } else {
      await startAll(proxy2);
    }
  }, "handler")
};

// packages/cli/src/commands/channel/stop.ts
init_esbuild_shims();
init_stdioHelpers();
var stopCommand = {
  command: "stop",
  describe: "Stop the running channel service",
  handler: /* @__PURE__ */ __name(async () => {
    const info2 = readServiceInfo();
    if (!info2) {
      writeStdoutLine("No channel service is running.");
      process.exit(0);
    }
    writeStdoutLine(`Stopping channel service (PID ${info2.pid})...`);
    if (!signalService(info2.pid, "SIGTERM")) {
      writeStderrLine(
        "Failed to send signal \u2014 process may have already exited."
      );
      removeServiceInfo();
      process.exit(0);
    }
    const exited = await waitForExit(info2.pid, 5e3);
    if (exited) {
      removeServiceInfo();
      writeStdoutLine("Service stopped.");
    } else {
      writeStderrLine(
        "Service did not exit within 5 seconds. Sending SIGKILL..."
      );
      signalService(info2.pid, "SIGKILL");
      await waitForExit(info2.pid, 2e3);
      removeServiceInfo();
      writeStdoutLine("Service killed.");
    }
    process.exit(0);
  }, "handler")
};

// packages/cli/src/commands/channel/status.ts
init_esbuild_shims();
init_stdioHelpers();
import { existsSync as existsSync35, readFileSync as readFileSync28 } from "node:fs";
import * as path110 from "node:path";
import * as os39 from "node:os";
function formatUptime(startedAt) {
  const ms = Date.now() - new Date(startedAt).getTime();
  const seconds = Math.floor(ms / 1e3);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  if (days > 0) return `${days}d ${hours % 24}h ${minutes % 60}m`;
  if (hours > 0) return `${hours}h ${minutes % 60}m`;
  if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
  return `${seconds}s`;
}
__name(formatUptime, "formatUptime");
var statusCommand2 = {
  command: "status",
  describe: "Show channel service status",
  handler: /* @__PURE__ */ __name(async () => {
    const info2 = readServiceInfo();
    if (!info2) {
      writeStdoutLine("No channel service is running.");
      process.exit(0);
    }
    writeStdoutLine(`Channel service: running (PID ${info2.pid})`);
    writeStdoutLine(`Uptime:          ${formatUptime(info2.startedAt)}`);
    writeStdoutLine("");
    const sessionsPath2 = path110.join(
      os39.homedir(),
      ".qwen",
      "channels",
      "sessions.json"
    );
    const sessionCounts = /* @__PURE__ */ new Map();
    if (existsSync35(sessionsPath2)) {
      try {
        const entries = JSON.parse(
          readFileSync28(sessionsPath2, "utf-8")
        );
        for (const entry of Object.values(entries)) {
          const name4 = entry.target.channelName;
          sessionCounts.set(name4, (sessionCounts.get(name4) || 0) + 1);
        }
      } catch {
      }
    }
    const nameWidth = Math.max(15, ...info2.channels.map((c4) => c4.length + 2));
    writeStdoutLine(`${"Channel".padEnd(nameWidth)}Sessions`);
    writeStdoutLine(`${"-".repeat(nameWidth)}--------`);
    for (const name4 of info2.channels) {
      const count = sessionCounts.get(name4) || 0;
      writeStdoutLine(`${name4.padEnd(nameWidth)}${count}`);
    }
    process.exit(0);
  }, "handler")
};

// packages/cli/src/commands/channel/pairing.ts
init_esbuild_shims();
init_dist5();
init_stdioHelpers();
var pairingListCommand = {
  command: "list <name>",
  describe: "List pending pairing requests for a channel",
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    type: "string",
    describe: "Channel name",
    demandOption: true
  }), "builder"),
  handler: /* @__PURE__ */ __name((argv) => {
    const store = new PairingStore(argv.name);
    const pending = store.listPending();
    if (pending.length === 0) {
      writeStdoutLine("No pending pairing requests.");
      return;
    }
    writeStdoutLine(`Pending pairing requests for "${argv.name}":
`);
    for (const req of pending) {
      const ago = Math.round((Date.now() - req.createdAt) / 6e4);
      writeStdoutLine(
        `  Code: ${req.code}  Sender: ${req.senderName} (${req.senderId})  ${ago}m ago`
      );
    }
  }, "handler")
};
var pairingApproveCommand = {
  command: "approve <name> <code>",
  describe: "Approve a pending pairing request",
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("name", {
    type: "string",
    describe: "Channel name",
    demandOption: true
  }).positional("code", {
    type: "string",
    describe: "Pairing code",
    demandOption: true
  }), "builder"),
  handler: /* @__PURE__ */ __name((argv) => {
    const store = new PairingStore(argv.name);
    const request4 = store.approve(argv.code);
    if (!request4) {
      writeStderrLine(
        `No pending request found for code "${argv.code.toUpperCase()}". It may have expired.`
      );
      process.exit(1);
    }
    writeStdoutLine(
      `Approved: ${request4.senderName} (${request4.senderId}) can now use channel "${argv.name}".`
    );
  }, "handler")
};

// packages/cli/src/commands/channel/configure.ts
init_esbuild_shims();
init_stdioHelpers();
init_accounts();

// packages/channels/weixin/dist/login.js
init_esbuild_shims();
init_api2();
async function startLogin(apiBaseUrl) {
  const resp = await fetch(`${apiBaseUrl}/ilink/bot/get_bot_qrcode?bot_type=3`);
  if (!resp.ok) {
    throw new Error(`Failed to get QR code: HTTP ${resp.status}`);
  }
  const data = await resp.json();
  if (!data.qrcode) {
    throw new Error("No qrcode in response");
  }
  if (data.qrcode_img_content) {
    process.stderr.write(`QR code URL: ${data.qrcode_img_content}
Scan this URL with WeChat.
`);
  }
  process.stderr.write("Scan the QR code with WeChat to connect.\n");
  return data.qrcode;
}
__name(startLogin, "startLogin");
async function waitForLogin(params) {
  const { apiBaseUrl, timeoutMs = 48e4 } = params;
  let currentQrcodeId = params.qrcodeId;
  const deadline = Date.now() + timeoutMs;
  let retryCount = 0;
  while (Date.now() < deadline) {
    try {
      const controller = new AbortController();
      const timeout2 = setTimeout(() => controller.abort(), 6e4);
      const resp = await fetch(`${apiBaseUrl}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(currentQrcodeId)}`, {
        headers: buildHeaders2(),
        signal: controller.signal
      });
      clearTimeout(timeout2);
      if (!resp.ok)
        throw new Error(`HTTP ${resp.status}`);
      const data = await resp.json();
      switch (data.status) {
        case "confirmed":
          return {
            connected: true,
            token: data.bot_token,
            baseUrl: data.baseurl,
            userId: data.ilink_user_id,
            message: "Connected to WeChat successfully!"
          };
        case "scaned":
          process.stderr.write("QR code scanned, waiting for confirmation...\n");
          break;
        case "expired":
          retryCount++;
          if (retryCount >= 3) {
            return {
              connected: false,
              message: "QR code expired after maximum retries."
            };
          }
          process.stderr.write("QR code expired, refreshing...\n");
          currentQrcodeId = await startLogin(apiBaseUrl);
          break;
        default:
          break;
      }
    } catch (err2) {
      if (err2 instanceof Error && err2.name === "AbortError") {
        continue;
      }
      throw err2;
    }
    await new Promise((r5) => setTimeout(r5, 1e3));
  }
  return { connected: false, message: "Login timed out." };
}
__name(waitForLogin, "waitForLogin");

// packages/cli/src/commands/channel/configure.ts
var configureWeixinCommand = {
  command: "configure-weixin [action]",
  describe: "Configure WeChat channel (login via QR code)",
  builder: /* @__PURE__ */ __name((yargs) => yargs.positional("action", {
    type: "string",
    describe: '"clear" to remove stored credentials, omit to login'
  }), "builder"),
  handler: /* @__PURE__ */ __name(async (argv) => {
    const { action } = argv;
    if (action === "clear") {
      clearAccount();
      writeStdoutLine("WeChat credentials cleared.");
      return;
    }
    if (action === "status") {
      const account = loadAccount();
      if (account) {
        writeStdoutLine(`WeChat account configured (saved ${account.savedAt})`);
        writeStdoutLine(`  Base URL: ${account.baseUrl}`);
        if (account.userId) {
          writeStdoutLine(`  User ID: ${account.userId}`);
        }
      } else {
        writeStdoutLine("WeChat account not configured.");
      }
      return;
    }
    const existing = loadAccount();
    if (existing) {
      writeStdoutLine(
        `Existing WeChat credentials found (saved ${existing.savedAt}).`
      );
      writeStdoutLine("Re-running login will overwrite them.\n");
    }
    const baseUrl = DEFAULT_BASE_URL;
    writeStdoutLine("Starting WeChat QR code login...\n");
    try {
      const qrcodeId = await startLogin(baseUrl);
      const result = await waitForLogin({ qrcodeId, apiBaseUrl: baseUrl });
      if (result.connected && result.token) {
        saveAccount({
          token: result.token,
          baseUrl: result.baseUrl || baseUrl,
          userId: result.userId,
          savedAt: (/* @__PURE__ */ new Date()).toISOString()
        });
        writeStdoutLine("\n" + result.message);
        writeStdoutLine(
          "Credentials saved. You can now start a weixin channel with:"
        );
        writeStdoutLine("  qwen channel start <name>");
      } else {
        writeStderrLine("\n" + result.message);
        process.exit(1);
      }
    } catch (err2) {
      writeStderrLine(
        `Login failed: ${err2 instanceof Error ? err2.message : String(err2)}`
      );
      process.exit(1);
    }
  }, "handler")
};

// packages/cli/src/commands/channel.ts
var pairingCommand = {
  command: "pairing",
  describe: "Manage DM pairing requests",
  builder: /* @__PURE__ */ __name((yargs) => yargs.command(pairingListCommand).command(pairingApproveCommand).demandCommand(1, "You need at least one command before continuing.").version(false), "builder"),
  handler: /* @__PURE__ */ __name(() => {
  }, "handler")
};
var channelCommand = {
  command: "channel",
  describe: "Manage messaging channels (Telegram, Discord, etc.)",
  builder: /* @__PURE__ */ __name((yargs) => yargs.command(startCommand).command(stopCommand).command(statusCommand2).command(pairingCommand).command(configureWeixinCommand).demandCommand(1, "You need at least one command before continuing.").version(false), "builder"),
  handler: /* @__PURE__ */ __name(() => {
  }, "handler")
};

// packages/cli/src/config/config.ts
init_stdioHelpers();
var SESSION_ID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}(-agent-[a-zA-Z0-9_.-]+)?$/i;
function isValidSessionId(value) {
  return SESSION_ID_REGEX.test(value);
}
__name(isValidSessionId, "isValidSessionId");
var debugLogger109 = 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("bare", {
    type: "boolean",
    description: "Minimal mode: skip implicit startup auto-discovery and only honor explicitly provided CLI inputs.",
    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("system-prompt", {
      type: "string",
      description: "Override the main session system prompt for this run. Can be combined with --append-system-prompt."
    }).option("append-system-prompt", {
      type: "string",
      description: "Append instructions to the main session system prompt for this run. Can be combined with --system-prompt."
    }).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("mcp-config", {
      type: "string",
      description: 'MCP server configuration as JSON string or file path. Can be a path to a JSON file or inline JSON with {"mcpServers": {...}} format.'
    }).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", {
      alias: "add-dir",
      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("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("json-fd", {
      type: "number",
      description: "File descriptor for structured JSON event output (dual output mode). The TUI renders normally on stdout while JSON events are written to this fd. The caller must provide this fd via spawn stdio configuration."
    }).option("json-file", {
      type: "string",
      description: "File path for structured JSON event output (dual output mode). Can be a regular file, FIFO (named pipe), or /dev/fd/N."
    }).option("input-file", {
      type: "string",
      description: "File path for receiving remote input commands (bidirectional sync). An external process writes JSONL commands; the TUI watches and processes them."
    }).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("disabled-slash-commands", {
      type: "array",
      string: true,
      description: "Slash command names to hide/disable (comma-separated or repeated). Merged with the `slashCommands.disabled` setting and QWEN_DISABLED_SLASH_COMMANDS. Matched case-insensitively against the final command name.",
      coerce: /* @__PURE__ */ __name((names) => names.flatMap((n3) => n3.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.sandboxImage" 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, err2, yargs) => {
      writeStderrLine(msg || err2?.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"] && !isValidSessionId(argv["sessionId"])) {
        return `Invalid --session-id: "${argv["sessionId"]}". Must be a valid UUID (e.g., "123e4567-e89b-12d3-a456-426614174000").`;
      }
      if (argv["jsonFd"] != null && argv["jsonFile"] != null) {
        return "--json-fd and --json-file are mutually exclusive. Use one or the other.";
      }
      return true;
    })
  ).command(mcpCommand).command(extensionsCommand).command(authCommand).command(hooksCommand).command(channelCommand);
  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" || result._[0] === "hooks" || result._[0] === "channel")) {
    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", contextRuleExcludes = []) {
  const realCwd = fs110.realpathSync(path111.resolve(currentWorkingDirectory));
  const realHome = fs110.realpathSync(path111.resolve(homedir28()));
  const isHomeDirectory = realCwd === realHome;
  const effectiveCwd = isHomeDirectory ? "" : currentWorkingDirectory;
  return loadServerHierarchicalMemory(
    effectiveCwd,
    includeDirectoriesToReadGemini,
    fileService,
    extensionContextFilePaths,
    folderTrust,
    memoryImportFormat,
    contextRuleExcludes
  );
}
__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");
function validateMcpServerConfig(config2) {
  if (typeof config2 !== "object" || config2 === null || Array.isArray(config2)) {
    return false;
  }
  return Object.values(config2).every(
    (server) => typeof server === "object" && server !== null
  );
}
__name(validateMcpServerConfig, "validateMcpServerConfig");
function parseMcpConfig(mcpConfigArg) {
  if (!mcpConfigArg) {
    return null;
  }
  try {
    let parsed;
    if (fs110.existsSync(mcpConfigArg)) {
      debugLogger109.debug(`Reading MCP config from file: ${mcpConfigArg}`);
      const content = fs110.readFileSync(mcpConfigArg, "utf-8");
      parsed = JSON.parse((0, import_strip_json_comments3.default)(content));
    } else {
      debugLogger109.debug("Parsing MCP config as JSON string");
      parsed = JSON.parse(mcpConfigArg);
    }
    let servers;
    if (typeof parsed === "object" && parsed !== null && "mcpServers" in parsed && typeof parsed.mcpServers === "object") {
      servers = parsed.mcpServers;
    } else {
      servers = parsed;
    }
    if (!validateMcpServerConfig(servers)) {
      throw new Error(
        "Invalid MCP server configuration format. Expected an object with server names as keys."
      );
    }
    debugLogger109.debug(
      `Loaded ${Object.keys(servers).length} MCP server(s) from --mcp-config`
    );
    return servers;
  } catch (error40) {
    const errorMessage = error40 instanceof Error ? error40.message : String(error40);
    throw new FatalConfigError(
      `Invalid MCP configuration provided via --mcp-config: ${errorMessage}`
    );
  }
}
__name(parseMcpConfig, "parseMcpConfig");
async function loadCliConfig(settings, argv, cwd6 = process.cwd(), overrideExtensions, hooksConfig) {
  const debugMode = isDebugMode(argv);
  const bareMode = isBareMode(argv.bare);
  Storage.setRuntimeBaseDir(settings.advanced?.runtimeOutputDir, cwd6);
  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(getAllGeminiMdFilenames());
  }
  const projectStorage = new Storage(cwd6);
  const projectOutputLanguagePath = path111.join(
    projectStorage.getQwenDir(),
    "output-language.md"
  );
  const globalOutputLanguagePath = path111.join(
    Storage.getGlobalQwenDir(),
    "output-language.md"
  );
  let outputLanguageFilePath;
  if (!bareMode) {
    if (fs110.existsSync(projectOutputLanguagePath)) {
      outputLanguageFilePath = projectOutputLanguagePath;
    } else if (fs110.existsSync(globalOutputLanguagePath)) {
      outputLanguageFilePath = globalOutputLanguagePath;
    }
  }
  const fileService = new FileDiscoveryService(cwd6);
  const includeDirectories = (bareMode ? [] : settings.context?.includeDirectories ?? []).map(resolvePath3).concat((argv.includeDirectories || []).map(resolvePath3));
  const lspEnabled = !bareMode && 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 (!bareMode && 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 (err2) {
    if (err2 instanceof FatalConfigError) {
      throw new FatalConfigError(
        `Invalid telemetry configuration: ${err2.message}.`
      );
    }
    throw err2;
  }
  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 resolvedCoreTools = [
    ...bareMode ? [] : argv.coreTools ?? [],
    ...bareMode ? [] : settings.tools?.core ?? []
  ];
  const mergedAllow = [
    ...bareMode ? [] : settings.permissions?.allow ?? [],
    ...bareMode ? [] : settings.tools?.allowed ?? []
  ];
  const mergedAsk = [
    ...bareMode ? [] : settings.permissions?.ask ?? []
  ];
  const mergedDeny = [
    ...bareMode ? [] : settings.permissions?.deny ?? [],
    ...bareMode ? [] : settings.tools?.exclude ?? []
  ];
  for (const t5 of argv.allowedTools ?? []) {
    if (t5 && !mergedAllow.includes(t5)) mergedAllow.push(t5);
  }
  for (const t5 of argv.excludeTools ?? []) {
    if (t5 && !mergedDeny.includes(t5)) mergedDeny.push(t5);
  }
  const disabledSlashCommands = [];
  const seenDisabled = /* @__PURE__ */ new Set();
  const addDisabled = /* @__PURE__ */ __name((value) => {
    if (!value) return;
    const trimmed2 = value.trim();
    if (!trimmed2) return;
    const key = trimmed2.toLowerCase();
    if (!seenDisabled.has(key)) {
      seenDisabled.add(key);
      disabledSlashCommands.push(trimmed2);
    }
  }, "addDisabled");
  for (const name4 of settings.slashCommands?.disabled ?? []) addDisabled(name4);
  for (const name4 of argv.disabledSlashCommands ?? []) addDisabled(name4);
  for (const name4 of (process.env["QWEN_DISABLED_SLASH_COMMANDS"] ?? "").split(
    ","
  )) {
    addDisabled(name4);
  }
  const isExplicitlyAllowed = /* @__PURE__ */ __name((toolName) => {
    const name4 = toolName;
    if (mergedAllow.some((rule) => {
      const openParen = rule.indexOf("(");
      const ruleName = openParen === -1 ? rule.trim() : rule.substring(0, openParen).trim();
      return ruleName === name4;
    })) {
      return true;
    }
    if (resolvedCoreTools.length > 0) {
      return isToolEnabled(toolName, resolvedCoreTools, []);
    }
    return false;
  }, "isExplicitlyAllowed");
  const isAcpMode = argv.acp || argv.experimentalAcp;
  if (!bareMode && !interactive && !isAcpMode && inputFormat !== InputFormat.STREAM_JSON) {
    const denyUnlessAllowed = /* @__PURE__ */ __name((toolName) => {
      if (!isExplicitlyAllowed(toolName)) {
        const name4 = toolName;
        if (!mergedDeny.includes(name4)) mergedDeny.push(name4);
      }
    }, "denyUnlessAllowed");
    switch (approvalMode) {
      case ApprovalMode.PLAN:
      case ApprovalMode.DEFAULT:
        denyUnlessAllowed(ToolNames.SHELL);
        denyUnlessAllowed(ToolNames.EDIT);
        denyUnlessAllowed(ToolNames.WRITE_FILE);
        break;
      case ApprovalMode.AUTO_EDIT:
        denyUnlessAllowed(ToolNames.SHELL);
        break;
      case ApprovalMode.YOLO:
        break;
      default:
        break;
    }
  }
  let allowedMcpServers;
  let excludedMcpServers;
  if (argv.allowedMcpServerNames) {
    allowedMcpServers = new Set(argv.allowedMcpServerNames.filter(Boolean));
    excludedMcpServers = void 0;
  } else if (!bareMode) {
    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 || (bareMode ? void 0 : 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(
    bareMode ? {} : 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(cwd6);
    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(cwd6);
    const exists3 = await sessionService.sessionExists(argv["sessionId"]);
    if (exists3) {
      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: cwd6,
    includeDirectories,
    loadMemoryFromIncludeDirectories: bareMode ? includeDirectories.length > 0 : settings.context?.loadFromIncludeDirectories ?? false,
    importFormat: settings.context?.importFormat || "tree",
    debugMode,
    question,
    systemPrompt: argv.systemPrompt,
    appendSystemPrompt: argv.appendSystemPrompt,
    // Legacy fields – kept for backward compatibility with getCoreTools() etc.
    coreTools: bareMode ? void 0 : argv.coreTools || settings.tools?.core || void 0,
    allowedTools: bareMode ? argv.allowedTools || void 0 : argv.allowedTools || settings.tools?.allowed || void 0,
    excludeTools: mergedDeny,
    disabledSlashCommands: disabledSlashCommands.length > 0 ? disabledSlashCommands : void 0,
    // New unified permissions (PermissionManager source of truth).
    permissions: {
      allow: mergedAllow.length > 0 ? mergedAllow : void 0,
      ask: mergedAsk.length > 0 ? mergedAsk : void 0,
      deny: mergedDeny.length > 0 ? mergedDeny : void 0
    },
    // Permission rule persistence callback (writes to settings files).
    onPersistPermissionRule: /* @__PURE__ */ __name(async (scope, ruleType, rule) => {
      const currentSettings = loadSettings(cwd6);
      const settingScope = scope === "project" ? "Workspace" /* Workspace */ : "User" /* User */;
      const key = `permissions.${ruleType}`;
      const currentRules = currentSettings.forScope(settingScope).settings.permissions?.[ruleType] ?? [];
      if (!currentRules.includes(rule)) {
        currentSettings.setValue(settingScope, key, [...currentRules, rule]);
      }
    }, "onPersistPermissionRule"),
    toolDiscoveryCommand: bareMode ? void 0 : settings.tools?.discoveryCommand,
    toolCallCommand: bareMode ? void 0 : settings.tools?.callCommand,
    mcpServerCommand: bareMode ? void 0 : settings.mcp?.serverCommand,
    mcpServers: bareMode ? {} : (() => {
      const base = settings.mcpServers || {};
      const cliMcpServers = parseMcpConfig(argv.mcpConfig);
      return cliMcpServers ? { ...base, ...cliMcpServers } : base;
    })(),
    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,
    clearContextOnIdle: settings.context?.clearContextOnIdle,
    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: cwd6,
    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,
    cronEnabled: settings.experimental?.cron ?? false,
    emitToolUseSummaries: settings.experimental?.emitToolUseSummaries ?? true,
    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,
    bareMode,
    allowedHttpHookUrls: bareMode ? [] : settings.security?.allowedHttpHookUrls ?? [],
    cliVersion: await getCliVersion(),
    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 ?? true,
    skipStartupContext: settings.model?.skipStartupContext ?? false,
    truncateToolOutputThreshold: settings.tools?.truncateToolOutputThreshold,
    truncateToolOutputLines: settings.tools?.truncateToolOutputLines,
    eventEmitter: appEvents,
    gitCoAuthor: settings.general?.gitCoAuthor,
    output: {
      format: outputSettingsFormat
    },
    enableManagedAutoMemory: bareMode ? false : settings.memory?.enableManagedAutoMemory ?? true,
    enableManagedAutoDream: settings.memory?.enableManagedAutoDream ?? false,
    fastModel: settings.fastModel || void 0,
    // Use separated hooks if provided, otherwise fall back to merged hooks
    userHooks: bareMode ? void 0 : hooksConfig?.userHooks ?? settings.hooks,
    projectHooks: bareMode ? void 0 : hooksConfig?.projectHooks,
    hooks: bareMode ? void 0 : settings.hooks,
    // Keep for backward compatibility
    disableAllHooks: bareMode ? true : settings.disableAllHooks ?? false,
    channel: argv.channel,
    // CLI flag wins over settings.json. `--json-fd` is fd-only (no settings
    // equivalent — fd passing is a spawn-time concern). `--json-file` and
    // `--input-file` fall back to settings.dualOutput.* when the flag is
    // absent.
    jsonFd: argv.jsonFd,
    jsonFile: argv.jsonFile ?? settings.dualOutput?.jsonFile,
    inputFile: argv.inputFile ?? settings.dualOutput?.inputFile,
    // 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,
    lsp: {
      enabled: lspEnabled
    },
    agents: settings.agents ? {
      displayMode: settings.agents.displayMode,
      arena: settings.agents.arena ? {
        worktreeBaseDir: settings.agents.arena.worktreeBaseDir,
        preserveArtifacts: settings.agents.arena.preserveArtifacts ?? false
      } : void 0
    } : void 0
  });
  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 (err2) {
      debugLogger109.warn("Failed to initialize native LSP service:", err2);
    }
  }
  return config2;
}
__name(loadCliConfig, "loadCliConfig");

// packages/cli/src/core/initializer.ts
init_esbuild_shims();
init_dist4();

// packages/cli/src/core/auth.ts
init_esbuild_shims();
init_dist4();
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,
    code: lightTheme.LightBlue
  },
  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,
    code: darkTheme.LightBlue
  },
  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,
    code: ansiTheme.LightBlue
  },
  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 fs111 from "node:fs";
import * as path112 from "node:path";
import * as os40 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: "",
    code: ""
  },
  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
init_dist4();
import process29 from "node:process";

// packages/cli/src/ui/themes/detect-terminal-theme.ts
init_esbuild_shims();
init_dist4();
import { execSync as execSync6 } from "node:child_process";
import process28 from "node:process";
var debugLogger110 = createDebugLogger("THEME_DETECT");
var OSC11_TIMEOUT_MS = 200;
function hexComponent(hex) {
  const max = 16 ** hex.length - 1;
  return parseInt(hex, 16) / max;
}
__name(hexComponent, "hexComponent");
function parseOscRgb(data) {
  const rgbMatch = /^rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i.exec(data);
  if (rgbMatch) {
    return {
      r: hexComponent(rgbMatch[1]),
      g: hexComponent(rgbMatch[2]),
      b: hexComponent(rgbMatch[3])
    };
  }
  const hashMatch = /^#([0-9a-f]+)$/i.exec(data);
  if (hashMatch && hashMatch[1].length % 3 === 0) {
    const hex = hashMatch[1];
    const n3 = hex.length / 3;
    return {
      r: hexComponent(hex.slice(0, n3)),
      g: hexComponent(hex.slice(n3, 2 * n3)),
      b: hexComponent(hex.slice(2 * n3))
    };
  }
  return void 0;
}
__name(parseOscRgb, "parseOscRgb");
function themeFromOscColor(data) {
  const rgb = parseOscRgb(data);
  if (!rgb) return void 0;
  const luminance = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b;
  return luminance > 0.5 ? "light" : "dark";
}
__name(themeFromOscColor, "themeFromOscColor");
function detectOsc11Theme() {
  if (!process28.stdin.isTTY || !process28.stdout.isTTY) {
    return Promise.resolve(void 0);
  }
  return new Promise((resolve42) => {
    const stdin2 = process28.stdin;
    let resolved = false;
    let buffer = "";
    const finish = /* @__PURE__ */ __name((result) => {
      if (resolved) return;
      resolved = true;
      clearTimeout(timer);
      stdin2.removeListener("data", onData);
      resolve42(result);
    }, "finish");
    const timer = setTimeout(() => finish(void 0), OSC11_TIMEOUT_MS);
    const onData = /* @__PURE__ */ __name((data) => {
      buffer += data.toString();
      const match2 = /\x1b\]11;(.*?)(?:\x07|\x1b\\)/.exec(buffer);
      if (match2) {
        finish(themeFromOscColor(match2[1]));
      }
    }, "onData");
    stdin2.on("data", onData);
    process28.stdout.write("\x1B]11;?\x07");
  });
}
__name(detectOsc11Theme, "detectOsc11Theme");
function detectMacOSTheme() {
  if (process28.platform !== "darwin") {
    return void 0;
  }
  try {
    const result = execSync6("defaults read -g AppleInterfaceStyle", {
      encoding: "utf-8",
      timeout: 3e3,
      stdio: ["pipe", "pipe", "pipe"]
    }).trim();
    return result.toLowerCase() === "dark" ? "dark" : "light";
  } catch (error40) {
    const err2 = error40;
    const stderr = typeof err2.stderr === "string" ? err2.stderr : err2.stderr?.toString?.() ?? "";
    const message = err2.message ?? "";
    if (/does not exist/i.test(stderr) || /does not exist/i.test(message)) {
      return "light";
    }
    return void 0;
  }
}
__name(detectMacOSTheme, "detectMacOSTheme");
function detectFromColorFgBg() {
  const colorFgBg = process28.env["COLORFGBG"];
  if (!colorFgBg) {
    return void 0;
  }
  const parts2 = colorFgBg.split(";");
  const bgStr = parts2[parts2.length - 1];
  if (bgStr === void 0) {
    return void 0;
  }
  const bg = parseInt(bgStr, 10);
  if (isNaN(bg)) {
    return void 0;
  }
  if (bg === 7 || bg >= 9 && bg <= 15) {
    return "light";
  }
  return "dark";
}
__name(detectFromColorFgBg, "detectFromColorFgBg");
function detectTerminalTheme() {
  const colorFgBgResult = detectFromColorFgBg();
  if (colorFgBgResult) {
    debugLogger110.info(`Detected theme from COLORFGBG: ${colorFgBgResult}`);
    return colorFgBgResult;
  }
  const macResult = detectMacOSTheme();
  if (macResult) {
    debugLogger110.info(
      `Detected theme from macOS system appearance: ${macResult}`
    );
    return macResult;
  }
  debugLogger110.info("Could not detect terminal theme, defaulting to dark");
  return "dark";
}
__name(detectTerminalTheme, "detectTerminalTheme");
async function detectTerminalThemeAsync() {
  const colorFgBgResult = detectFromColorFgBg();
  if (colorFgBgResult) {
    debugLogger110.info(
      `Detected theme from COLORFGBG (async path): ${colorFgBgResult}`
    );
    return colorFgBgResult;
  }
  const osc11Result = await detectOsc11Theme();
  if (osc11Result) {
    debugLogger110.info(
      `Detected theme from OSC 11 background query: ${osc11Result}`
    );
    return osc11Result;
  }
  const macResult = detectMacOSTheme();
  if (macResult) {
    debugLogger110.info(
      `Detected theme from macOS system appearance: ${macResult}`
    );
    return macResult;
  }
  debugLogger110.info("Could not detect terminal theme, defaulting to dark");
  return "dark";
}
__name(detectTerminalThemeAsync, "detectTerminalThemeAsync");

// packages/cli/src/ui/themes/theme-manager.ts
var debugLogger111 = createDebugLogger("THEME_MANAGER");
var DEFAULT_THEME = QwenDark;
var AUTO_THEME_NAME = "auto";
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 [name4, customThemeConfig] of Object.entries(
      customThemesSettings
    )) {
      const validation2 = validateCustomTheme(customThemeConfig);
      if (validation2.isValid) {
        if (validation2.warning) {
          debugLogger111.warn(`Theme "${name4}": ${validation2.warning}`);
        }
        const themeWithDefaults = {
          ...DEFAULT_THEME.colors,
          ...customThemeConfig,
          name: customThemeConfig.name || name4,
          type: "custom"
        };
        try {
          const theme2 = createCustomTheme(themeWithDefaults);
          this.customThemes.set(name4, theme2);
        } catch (error40) {
          debugLogger111.warn(`Failed to load custom theme "${name4}":`, error40);
        }
      } else {
        debugLogger111.warn(`Invalid custom theme "${name4}": ${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.
   *   If themeName is 'auto', detects the terminal theme and selects
   *   Qwen Dark or Qwen Light accordingly.
   * @returns True if the theme was successfully set, false otherwise.
   */
  setActiveTheme(themeName) {
    if (themeName === AUTO_THEME_NAME) {
      this.activeTheme = this.resolveAutoTheme();
      debugLogger111.info(`Auto-detected theme: ${this.activeTheme.name}`);
      return true;
    }
    const theme2 = this.findThemeByName(themeName);
    if (!theme2) {
      return false;
    }
    this.activeTheme = theme2;
    return true;
  }
  /**
   * Cached auto-detection result. Populated by the async probe at startup
   * (which includes OSC 11) and reused by subsequent sync resolutions so
   * reselecting Auto in the /theme dialog never contradicts what was shown
   * when the app first rendered.
   */
  cachedAutoDetection;
  /**
   * Detects the terminal's dark/light preference (synchronous) and returns
   * the corresponding Qwen theme.
   * Used by the theme dialog for instant preview. Prefers the cached
   * async-detected value when available so we stay consistent with the
   * OSC 11 probe performed at startup.
   */
  resolveAutoTheme() {
    const detected = this.cachedAutoDetection ?? detectTerminalTheme();
    return detected === "light" ? QwenLight : QwenDark;
  }
  /**
   * Asynchronous auto-detection that includes an OSC 11 probe.
   * Intended for startup where a short async delay (~200 ms) is acceptable.
   * The resolved value is cached so later sync resolutions (e.g. the /theme
   * dialog reselecting Auto) stay in sync with what the probe detected.
   */
  async resolveAutoThemeAsync() {
    const detected = await detectTerminalThemeAsync();
    this.cachedAutoDetection = detected;
    this.activeTheme = detected === "light" ? QwenLight : QwenDark;
    debugLogger111.info(`Auto-detected theme (async): ${this.activeTheme.name}`);
  }
  /**
   * 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(".") || path112.isAbsolute(themeName);
  }
  loadThemeFromFile(themePath) {
    try {
      const canonicalPath = fs111.realpathSync(path112.resolve(themePath));
      if (this.customThemes.has(canonicalPath)) {
        return this.customThemes.get(canonicalPath);
      }
      const homeDir = path112.resolve(os40.homedir());
      if (!canonicalPath.startsWith(homeDir)) {
        debugLogger111.warn(
          `Theme file at "${themePath}" is outside your home directory. Only load themes from trusted sources.`
        );
        return void 0;
      }
      const themeContent = fs111.readFileSync(canonicalPath, "utf-8");
      const customThemeConfig = JSON.parse(themeContent);
      const validation2 = validateCustomTheme(customThemeConfig);
      if (!validation2.isValid) {
        debugLogger111.warn(
          `Invalid custom theme from file "${themePath}": ${validation2.error}`
        );
        return void 0;
      }
      if (validation2.warning) {
        debugLogger111.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 (error40) {
      if (!(error40 instanceof Error && "code" in error40 && error40.code === "ENOENT")) {
        debugLogger111.warn(
          `Could not load theme from file "${themePath}":`,
          error40
        );
      }
      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
init_i18n();
function validateTheme(settings) {
  const effectiveTheme = settings.merged.ui?.theme;
  if (effectiveTheme && effectiveTheme !== AUTO_THEME_NAME && !themeManager.findThemeByName(effectiveTheme)) {
    return t4('Theme "{{themeName}}" not found.', {
      themeName: effectiveTheme
    });
  }
  return null;
}
__name(validateTheme, "validateTheme");

// packages/cli/src/core/initializer.ts
init_i18n();
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);
  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();
init_dist4();
import { spawn as spawn10 } 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 BTW_COMMAND_RE = /^[/?]btw(?:\s|$)/;
var isBtwCommand = /* @__PURE__ */ __name((query) => {
  const trimmed2 = query.trim();
  return trimmed2.length > 0 && BTW_COMMAND_RE.test(trimmed2);
}, "isBtwCommand");
var debugLogger112 = createDebugLogger("COMMAND_UTILS");
var copyToClipboard = /* @__PURE__ */ __name(async (text) => {
  const run2 = /* @__PURE__ */ __name((cmd, args2, options2) => new Promise((resolve42, reject) => {
    const child = options2 ? spawn10(cmd, args2, options2) : spawn10(cmd, args2);
    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 resolve42();
      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 run2("cmd", ["/c", `chcp ${CodePage.UTF8} >nul && clip`]);
    case "darwin":
      return run2("pbcopy", []);
    case "linux":
      try {
        await run2("xclip", ["-selection", "clipboard"], linuxOptions);
      } catch (primaryError) {
        try {
          await run2("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";
      debugLogger112.warn(
        `Unknown platform: ${process.platform}. Attempting to open URLs with: ${openCmd}.`
      );
      break;
  }
  return openCmd;
}, "getUrlOpenCommand");
function findMidInputSlashCommand(input, cursorOffset) {
  if (input.startsWith("/")) return null;
  const beforeCursor = input.slice(0, cursorOffset);
  const match2 = beforeCursor.match(/\s\/([a-zA-Z0-9_:-]*)$/);
  if (!match2 || match2.index === void 0) return null;
  const slashPos = match2.index + 1;
  const textAfterSlash = input.slice(slashPos + 1);
  const commandMatch = textAfterSlash.match(/^[a-zA-Z0-9_:-]*/);
  const fullCommand = commandMatch ? commandMatch[0] : "";
  if (cursorOffset !== slashPos + 1 + fullCommand.length) return null;
  return {
    token: "/" + fullCommand,
    startPos: slashPos,
    partialCommand: input.slice(slashPos + 1, cursorOffset)
  };
}
__name(findMidInputSlashCommand, "findMidInputSlashCommand");
function getBestSlashCommandMatch(partialCommand, commands) {
  if (!partialCommand) return null;
  const query = partialCommand.toLowerCase();
  let best = null;
  for (const cmd of commands) {
    if (!cmd.modelInvocable) continue;
    const name4 = cmd.name.toLowerCase();
    if (name4.startsWith(query) && name4 !== query) {
      const suffix = cmd.name.slice(partialCommand.length);
      if (!best || cmd.name < best.fullCommand) {
        best = { suffix, fullCommand: cmd.name };
      }
    }
  }
  return best;
}
__name(getBestSlashCommandMatch, "getBestSlashCommandMatch");

// packages/cli/src/nonInteractiveCli.ts
init_dist4();

// packages/cli/src/nonInteractive/io/JsonOutputAdapter.ts
init_esbuild_shims();

// packages/cli/src/nonInteractive/io/BaseJsonOutputAdapter.ts
init_esbuild_shims();
init_dist4();
import { randomUUID as randomUUID18 } from "node:crypto";

// packages/cli/src/utils/nonInteractiveHelpers.ts
init_esbuild_shims();
init_dist4();

// 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();
init_types21();
var parseSlashCommand = /* @__PURE__ */ __name((query, commands) => {
  const trimmed2 = query.trim();
  const parts2 = trimmed2.substring(1).trim().split(/\s+/);
  const commandPath = parts2.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 args2 = parts2.slice(pathIndex).join(" ");
  return { commandToExecute, args: args2, canonicalPath };
}, "parseSlashCommand");

// packages/cli/src/nonInteractiveCliCommands.ts
init_dist4();

// packages/cli/src/services/CommandService.ts
init_esbuild_shims();
init_dist4();

// packages/cli/src/services/commandUtils.ts
init_esbuild_shims();
init_types21();
function getEffectiveSupportedModes(cmd) {
  if (cmd.supportedModes !== void 0) {
    return cmd.supportedModes;
  }
  switch (cmd.kind) {
    case "built-in" /* BUILT_IN */:
      return ["interactive"];
    case "file" /* FILE */:
    case "skill" /* SKILL */:
    case "mcp-prompt" /* MCP_PROMPT */:
      return ["interactive", "non_interactive", "acp"];
    default:
      return ["interactive"];
  }
}
__name(getEffectiveSupportedModes, "getEffectiveSupportedModes");
function filterCommandsForMode(commands, mode) {
  return commands.filter(
    (cmd) => getEffectiveSupportedModes(cmd).includes(mode)
  );
}
__name(filterCommandsForMode, "filterCommandsForMode");

// packages/cli/src/services/CommandService.ts
var debugLogger113 = 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.
   * @param disabledNames Optional set of command names to exclude. Matched
   *   case-insensitively against the final (post-rename) command name. Intended
   *   for settings- or flag-driven denylists that gate the CLI surface (see
   *   `slashCommands.disabled` and `--disabled-slash-commands`).
   * @returns A promise that resolves to a new, fully initialized `CommandService` instance.
   */
  static async create(loaders, signal, disabledNames) {
    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 {
        debugLogger113.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
      });
    }
    if (disabledNames && disabledNames.size > 0) {
      const normalizedDisabled = /* @__PURE__ */ new Set();
      for (const entry of disabledNames) {
        const trimmed2 = entry.trim();
        if (trimmed2) normalizedDisabled.add(trimmed2.toLowerCase());
      }
      if (normalizedDisabled.size > 0) {
        for (const [name4, cmd] of Array.from(commandMap.entries())) {
          const matchesPrimary = normalizedDisabled.has(name4.toLowerCase());
          const matchesAlias = (cmd.altNames ?? []).some(
            (a2) => normalizedDisabled.has(a2.toLowerCase())
          );
          if (matchesPrimary || matchesAlias) {
            commandMap.delete(name4);
          }
        }
      }
    }
    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;
  }
  /**
   * Returns commands available in the specified execution mode.
   * Hidden commands are excluded.
   */
  getCommandsForMode(mode) {
    return Object.freeze(
      filterCommandsForMode(
        this.commands.filter((cmd) => !cmd.hidden),
        mode
      )
    );
  }
  /**
   * Returns commands that the model is allowed to invoke (modelInvocable === true).
   * Hidden commands are excluded.
   */
  getModelInvocableCommands() {
    return this.commands.filter(
      (cmd) => !cmd.hidden && cmd.modelInvocable === true
    );
  }
};

// packages/cli/src/services/BuiltinCommandLoader.ts
init_esbuild_shims();

// packages/cli/src/ui/commands/aboutCommand.ts
init_esbuild_shims();
init_types21();
init_types22();

// packages/cli/src/utils/systemInfo.ts
init_esbuild_shims();
import process30 from "node:process";
import os41 from "node:os";
import { execSync as execSync7 } from "node:child_process";
init_dist4();

// 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 formatTokenCount = /* @__PURE__ */ __name((count) => {
  if (count < 1e3) {
    return `${count}`;
  }
  if (count < 1e4) {
    return `${(count / 1e3).toFixed(1)}k`;
  }
  return `${Math.floor(count / 1e3)}k`;
}, "formatTokenCount");
var formatDuration = /* @__PURE__ */ __name((milliseconds, options2) => {
  if (milliseconds <= 0) {
    return "0s";
  }
  if (milliseconds < 1e3) {
    return `${Math.round(milliseconds)}ms`;
  }
  const totalSeconds = milliseconds / 1e3;
  if (totalSeconds < 60) {
    const formatted = totalSeconds.toFixed(1);
    if (options2?.hideTrailingZeros && formatted.endsWith(".0")) {
      return `${formatted.slice(0, -2)}s`;
    }
    return `${formatted}s`;
  }
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor(totalSeconds % 3600 / 60);
  const seconds = Math.floor(totalSeconds % 60);
  const parts2 = [];
  if (hours > 0) {
    parts2.push(`${hours}h`);
  }
  if (minutes > 0) {
    parts2.push(`${minutes}m`);
  }
  if (seconds > 0) {
    parts2.push(`${seconds}s`);
  }
  if (parts2.length === 0) {
    if (hours > 0) return `${hours}h`;
    if (minutes > 0) return `${minutes}m`;
    return `${seconds}s`;
  }
  return parts2.join(" ");
}, "formatDuration");

// packages/cli/src/generated/git-commit.ts
init_esbuild_shims();
var GIT_COMMIT_INFO = "cf5f447fd";

// packages/cli/src/utils/systemInfo.ts
async function getNpmVersion() {
  try {
    return execSync7("npm --version", { encoding: "utf-8" }).trim();
  } catch {
    return "unknown";
  }
}
__name(getNpmVersion, "getNpmVersion");
async function getGitVersion() {
  try {
    return execSync7("git --version", { encoding: "utf-8" }).trim();
  } catch {
    return "unknown";
  }
}
__name(getGitVersion, "getGitVersion");
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 = os41.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 proxy2 = context2.services.config?.getProxy();
  return {
    cliVersion,
    osPlatform,
    osArch,
    osRelease,
    nodeVersion: nodeVersion2,
    npmVersion,
    sandboxEnv,
    modelVersion,
    selectedAuthType,
    ideClient,
    sessionId,
    proxy: proxy2
  };
}
__name(getSystemInfo, "getSystemInfo");
async function getExtendedSystemInfo(context2) {
  const baseInfo2 = await getSystemInfo(context2);
  const memoryUsage = formatMemoryUsage2(process30.memoryUsage().rss);
  const sandboxEnv = getSandboxEnv(true);
  const contentGeneratorConfig = baseInfo2.selectedAuthType === AuthType2.USE_OPENAI || baseInfo2.selectedAuthType === AuthType2.USE_ANTHROPIC ? context2.services.config?.getContentGeneratorConfig() : void 0;
  const baseUrl = contentGeneratorConfig?.baseUrl;
  const apiKeyEnvKey = contentGeneratorConfig?.apiKeyEnvKey;
  const gitCommit = GIT_COMMIT_INFO && !["N/A"].includes(GIT_COMMIT_INFO) ? GIT_COMMIT_INFO : void 0;
  const fastModel = context2.services.settings?.merged?.fastModel || void 0;
  return {
    ...baseInfo2,
    sandboxEnv,
    memoryUsage,
    baseUrl,
    apiKeyEnvKey,
    gitCommit,
    fastModel
  };
}
__name(getExtendedSystemInfo, "getExtendedSystemInfo");

// packages/cli/src/ui/commands/aboutCommand.ts
init_i18n();
var aboutCommand = {
  name: "status",
  altNames: ["about"],
  get description() {
    return t4("show version info");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: /* @__PURE__ */ __name(async (context2) => {
    const systemInfo = await getExtendedSystemInfo(context2);
    if (context2.executionMode !== "interactive") {
      const lines = [
        `Qwen Code v${systemInfo.cliVersion}`,
        `Model: ${systemInfo.modelVersion}`,
        `Fast Model: ${systemInfo.fastModel ?? "not set"}`,
        `Auth: ${systemInfo.selectedAuthType}`,
        `Platform: ${systemInfo.osPlatform} ${systemInfo.osArch} (${systemInfo.osRelease})`,
        `Node.js: ${systemInfo.nodeVersion}`,
        `Session: ${systemInfo.sessionId}`,
        ...systemInfo.gitCommit ? [`Git commit: ${systemInfo.gitCommit}`] : [],
        ...systemInfo.ideClient ? [`IDE: ${systemInfo.ideClient}`] : []
      ];
      return {
        type: "message",
        messageType: "info",
        content: lines.join("\n")
      };
    }
    const aboutItem = {
      type: "about" /* ABOUT */,
      systemInfo
    };
    context2.ui.addItem(aboutItem, Date.now());
    return;
  }, "action")
};

// packages/cli/src/ui/commands/tasksCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
function statusLabel(entry) {
  switch (entry.status) {
    case "completed":
      return `completed (exit ${entry.exitCode ?? "?"})`;
    case "failed":
      return `failed: ${entry.error ?? "unknown error"}`;
    case "cancelled":
      return "cancelled";
    case "running":
      return "running";
    default:
      return entry.status;
  }
}
__name(statusLabel, "statusLabel");
var tasksCommand = {
  name: "tasks",
  get description() {
    return t4("List background tasks");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: /* @__PURE__ */ __name(async (context2) => {
    const { config: config2 } = context2.services;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: "Config not available."
      };
    }
    const entries = config2.getBackgroundShellRegistry().getAll();
    if (entries.length === 0) {
      return {
        type: "message",
        messageType: "info",
        content: "No background shells."
      };
    }
    const now = Date.now();
    const lines = [
      `Background shells (${entries.length} total)`,
      ""
    ];
    for (const entry of entries) {
      const endTime = entry.endTime ?? now;
      const runtime = formatDuration(endTime - entry.startTime, {
        hideTrailingZeros: true
      });
      const pidPart = entry.pid !== void 0 ? ` pid=${entry.pid}` : "";
      lines.push(
        `[${entry.shellId}] ${statusLabel(entry)}  ${runtime}${pidPart}  ${entry.command}`
      );
      lines.push(`            output: ${entry.outputPath}`);
    }
    return {
      type: "message",
      messageType: "info",
      content: lines.join("\n")
    };
  }, "action")
};

// packages/cli/src/ui/commands/agentsCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var agentsCommand = {
  name: "agents",
  get description() {
    return t4("Manage subagents for specialized task delegation.");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  subCommands: [
    {
      name: "manage",
      get description() {
        return t4("Manage existing subagents (view, edit, delete).");
      },
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive"],
      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 */,
      supportedModes: ["interactive"],
      action: /* @__PURE__ */ __name(() => ({
        type: "dialog",
        dialog: "subagent_create"
      }), "action")
    }
  ]
};

// packages/cli/src/ui/commands/arenaCommand.ts
init_esbuild_shims();
init_types21();
init_dist4();
init_types22();
function parseArenaArgs(args2) {
  const modelsMatch = args2.match(/--models\s+(\S+)/);
  let models = [];
  let task = args2;
  if (modelsMatch) {
    const modelStrings = modelsMatch[1].split(",").filter(Boolean);
    models = modelStrings.map((str2) => {
      const colonIndex = str2.indexOf(":");
      if (colonIndex > 0) {
        return {
          authType: str2.substring(0, colonIndex),
          modelId: str2.substring(colonIndex + 1)
        };
      }
      return { modelId: str2 };
    });
    task = task.replace(/--models\s+\S+/, "").trim();
  }
  task = task.replace(/^["']|["']$/g, "").trim();
  return { models, task };
}
__name(parseArenaArgs, "parseArenaArgs");
var debugLogger114 = createDebugLogger("ARENA_COMMAND");
function buildArenaExecutionInput(parsed, config2) {
  if (!parsed.task) {
    return {
      type: "message",
      messageType: "error",
      content: 'Usage: /arena start --models model1,model2 <task>\n\nOptions:\n  --models [authType:]model1,[authType:]model2\n                            Models to compete (required, at least 2)\n                            Format: authType:modelId or just modelId\n\nExamples:\n  /arena start --models openai:gpt-4o,anthropic:claude-3 "implement sorting"\n  /arena start --models qwen-coder-plus,kimi-for-coding "fix the bug"'
    };
  }
  if (parsed.models.length < 2) {
    return {
      type: "message",
      messageType: "error",
      content: "Arena requires at least 2 models. Use --models model1,model2 to specify.\nFormat: [authType:]modelId (e.g., openai:gpt-4o or just gpt-4o)"
    };
  }
  const contentGeneratorConfig = config2.getContentGeneratorConfig();
  const defaultAuthType = contentGeneratorConfig?.authType ?? AuthType2.USE_OPENAI;
  const modelsConfig = config2.getModelsConfig();
  const models = parsed.models.map((parsedModel) => {
    const authType = parsedModel.authType ?? defaultAuthType;
    const registryModels = modelsConfig.getAvailableModelsForAuthType(authType);
    const resolved = registryModels.find((m3) => m3.id === parsedModel.modelId);
    return {
      modelId: parsedModel.modelId,
      authType,
      displayName: resolved?.label ?? parsedModel.modelId
    };
  });
  return {
    task: parsed.task,
    models,
    approvalMode: config2.getApprovalMode()
  };
}
__name(buildArenaExecutionInput, "buildArenaExecutionInput");
function recordArenaItem(config2, item) {
  try {
    const chatRecorder = config2.getChatRecordingService();
    if (!chatRecorder) return;
    chatRecorder.recordSlashCommand({
      phase: "result",
      rawCommand: "/arena",
      outputHistoryItems: [{ ...item }]
    });
  } catch {
    debugLogger114.error("Failed to record arena history item");
  }
}
__name(recordArenaItem, "recordArenaItem");
function executeArenaCommand(config2, ui2, input) {
  let chatHistory;
  try {
    const fullHistory = config2.getGeminiClient().getHistory();
    chatHistory = stripStartupContext(fullHistory);
  } catch {
    debugLogger114.debug("Could not retrieve chat history for arena agents");
  }
  const manager = new ArenaManager(config2);
  const emitter = manager.getEventEmitter();
  const detachListeners = [];
  const agentLabels = /* @__PURE__ */ new Map();
  const addArenaMessage = /* @__PURE__ */ __name((type, text) => {
    ui2.addItem({ type, text }, Date.now());
  }, "addArenaMessage");
  const addAndRecordArenaMessage = /* @__PURE__ */ __name((type, text) => {
    const item = { type, text };
    ui2.addItem(item, Date.now());
    recordArenaItem(config2, item);
  }, "addAndRecordArenaMessage");
  const handleSessionStart = /* @__PURE__ */ __name((event) => {
    const modelList = event.models.map((model, index) => `  ${index + 1}. ${model.modelId}`).join("\n");
    addArenaMessage(
      "info" /* INFO */,
      `Arena started with ${event.models.length} agents on task: "${event.task}"
Models:
${modelList}`
    );
  }, "handleSessionStart");
  const handleAgentStart = /* @__PURE__ */ __name((event) => {
    agentLabels.set(event.agentId, event.model.modelId);
    debugLogger114.debug(
      `Arena agent started: ${event.model.modelId} (${event.agentId})`
    );
  }, "handleAgentStart");
  const handleSessionUpdate = /* @__PURE__ */ __name((event) => {
    const attachHintPrefix = "To view agent panes, run: ";
    if (event.message.startsWith(attachHintPrefix)) {
      const command2 = event.message.slice(attachHintPrefix.length).trim();
      addAndRecordArenaMessage(
        "info" /* INFO */,
        `Arena panes are running in tmux. Attach with: \`${command2}\``
      );
      return;
    }
    if (event.type === "success") {
      addAndRecordArenaMessage("success" /* SUCCESS */, event.message);
    } else if (event.type === "info") {
      addAndRecordArenaMessage("info" /* INFO */, event.message);
    } else {
      addAndRecordArenaMessage("warning" /* WARNING */, event.message);
    }
  }, "handleSessionUpdate");
  const handleAgentError = /* @__PURE__ */ __name((event) => {
    const label = agentLabels.get(event.agentId) || event.agentId;
    addAndRecordArenaMessage(
      "error" /* ERROR */,
      `[${label}] failed: ${event.error}`
    );
  }, "handleAgentError");
  const buildAgentCardData = /* @__PURE__ */ __name((result) => ({
    label: result.model.modelId,
    status: result.status,
    durationMs: result.stats.durationMs,
    totalTokens: result.stats.totalTokens,
    inputTokens: result.stats.inputTokens,
    outputTokens: result.stats.outputTokens,
    toolCalls: result.stats.toolCalls,
    successfulToolCalls: result.stats.successfulToolCalls,
    failedToolCalls: result.stats.failedToolCalls,
    rounds: result.stats.rounds,
    error: result.error,
    diff: result.diff,
    diffSummary: result.diffSummary,
    modifiedFiles: result.modifiedFiles,
    approachSummary: result.approachSummary
  }), "buildAgentCardData");
  const handleAgentComplete = /* @__PURE__ */ __name((event) => {
    if (!isTerminalStatus(event.result.status)) {
      return;
    }
    const agent = buildAgentCardData(event.result);
    const item = {
      type: "arena_agent_complete",
      agent
    };
    ui2.addItem(item, Date.now());
    recordArenaItem(config2, item);
  }, "handleAgentComplete");
  const handleSessionError = /* @__PURE__ */ __name((event) => {
    addAndRecordArenaMessage("error" /* ERROR */, `${event.error}`);
  }, "handleSessionError");
  const handleSessionComplete = /* @__PURE__ */ __name((event) => {
    const item = {
      type: "arena_session_complete",
      sessionStatus: event.result.status,
      task: event.result.task,
      totalDurationMs: event.result.totalDurationMs ?? 0,
      agents: event.result.agents.map(buildAgentCardData)
    };
    ui2.addItem(item, Date.now());
    recordArenaItem(config2, item);
  }, "handleSessionComplete");
  emitter.on(ArenaEventType.SESSION_START, handleSessionStart);
  detachListeners.push(
    () => emitter.off(ArenaEventType.SESSION_START, handleSessionStart)
  );
  emitter.on(ArenaEventType.AGENT_START, handleAgentStart);
  detachListeners.push(
    () => emitter.off(ArenaEventType.AGENT_START, handleAgentStart)
  );
  emitter.on(ArenaEventType.SESSION_UPDATE, handleSessionUpdate);
  detachListeners.push(
    () => emitter.off(ArenaEventType.SESSION_UPDATE, handleSessionUpdate)
  );
  emitter.on(ArenaEventType.AGENT_ERROR, handleAgentError);
  detachListeners.push(
    () => emitter.off(ArenaEventType.AGENT_ERROR, handleAgentError)
  );
  emitter.on(ArenaEventType.AGENT_COMPLETE, handleAgentComplete);
  detachListeners.push(
    () => emitter.off(ArenaEventType.AGENT_COMPLETE, handleAgentComplete)
  );
  emitter.on(ArenaEventType.SESSION_ERROR, handleSessionError);
  detachListeners.push(
    () => emitter.off(ArenaEventType.SESSION_ERROR, handleSessionError)
  );
  emitter.on(ArenaEventType.SESSION_COMPLETE, handleSessionComplete);
  detachListeners.push(
    () => emitter.off(ArenaEventType.SESSION_COMPLETE, handleSessionComplete)
  );
  config2.setArenaManager(manager);
  const cols = process.stdout.columns || 120;
  const rows = Math.max((process.stdout.rows || 40) - 2, 1);
  const lifecycle = manager.start({
    task: input.task,
    models: input.models,
    cols,
    rows,
    approvalMode: input.approvalMode,
    chatHistory
  }).then(
    () => {
      debugLogger114.debug("Arena agents settled");
    },
    (error40) => {
      const message = error40 instanceof Error ? error40.message : String(error40);
      addAndRecordArenaMessage("error" /* ERROR */, `${message}`);
      debugLogger114.error("Arena session failed:", error40);
      config2.setArenaManager(null);
      for (const detach of detachListeners) {
        detach();
      }
    }
  );
  manager.setLifecyclePromise(lifecycle);
}
__name(executeArenaCommand, "executeArenaCommand");
var arenaCommand = {
  name: "arena",
  description: "Manage Arena sessions",
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  subCommands: [
    {
      name: "start",
      description: "Start an Arena session with multiple models competing on the same task",
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive"],
      action: /* @__PURE__ */ __name(async (context2, args2) => {
        const executionMode = context2.executionMode ?? "interactive";
        if (executionMode !== "interactive") {
          return {
            type: "message",
            messageType: "error",
            content: "Arena is not supported in non-interactive mode. Use interactive mode to start an Arena session."
          };
        }
        const { services, ui: ui2 } = context2;
        const { config: config2 } = services;
        if (!config2) {
          return {
            type: "message",
            messageType: "error",
            content: "Configuration not available."
          };
        }
        const existingManager = config2.getArenaManager();
        if (existingManager) {
          return {
            type: "message",
            messageType: "error",
            content: "An Arena session exists. Use /arena stop or /arena select to end it before starting a new one."
          };
        }
        const parsed = parseArenaArgs(args2);
        if (parsed.models.length === 0) {
          return {
            type: "dialog",
            dialog: "arena_start"
          };
        }
        const executionInput = buildArenaExecutionInput(parsed, config2);
        if ("type" in executionInput) {
          return executionInput;
        }
        executeArenaCommand(config2, ui2, executionInput);
      }, "action")
    },
    {
      name: "stop",
      description: "Stop the current Arena session",
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive"],
      action: /* @__PURE__ */ __name(async (context2) => {
        const executionMode = context2.executionMode ?? "interactive";
        if (executionMode !== "interactive") {
          return {
            type: "message",
            messageType: "error",
            content: "Arena is not supported in non-interactive mode. Use interactive mode to stop an Arena session."
          };
        }
        const { config: config2 } = context2.services;
        if (!config2) {
          return {
            type: "message",
            messageType: "error",
            content: "Configuration not available."
          };
        }
        const manager = config2.getArenaManager();
        if (!manager) {
          return {
            type: "message",
            messageType: "error",
            content: "No running Arena session found."
          };
        }
        return {
          type: "dialog",
          dialog: "arena_stop"
        };
      }, "action")
    },
    {
      name: "status",
      description: "Show the current Arena session status",
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive"],
      action: /* @__PURE__ */ __name(async (context2) => {
        const executionMode = context2.executionMode ?? "interactive";
        if (executionMode !== "interactive") {
          return {
            type: "message",
            messageType: "error",
            content: "Arena is not supported in non-interactive mode."
          };
        }
        const { config: config2 } = context2.services;
        if (!config2) {
          return {
            type: "message",
            messageType: "error",
            content: "Configuration not available."
          };
        }
        const manager = config2.getArenaManager();
        if (!manager) {
          return {
            type: "message",
            messageType: "error",
            content: "No Arena session found. Start one with /arena start."
          };
        }
        return {
          type: "dialog",
          dialog: "arena_status"
        };
      }, "action")
    },
    {
      name: "select",
      altNames: ["choose"],
      description: "Select a model result and merge its diff into the current workspace",
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive"],
      action: /* @__PURE__ */ __name(async (context2, args2) => {
        const executionMode = context2.executionMode ?? "interactive";
        if (executionMode !== "interactive") {
          return {
            type: "message",
            messageType: "error",
            content: "Arena is not supported in non-interactive mode."
          };
        }
        const { config: config2 } = context2.services;
        if (!config2) {
          return {
            type: "message",
            messageType: "error",
            content: "Configuration not available."
          };
        }
        const manager = config2.getArenaManager();
        if (!manager) {
          return {
            type: "message",
            messageType: "error",
            content: "No arena session found. Start one with /arena start."
          };
        }
        const sessionStatus = manager.getSessionStatus();
        if (sessionStatus === ArenaSessionStatus.RUNNING || sessionStatus === ArenaSessionStatus.INITIALIZING) {
          return {
            type: "message",
            messageType: "error",
            content: "Arena session is still running. Wait for it to complete or use /arena stop first."
          };
        }
        const trimmedArgs = args2.trim();
        if (trimmedArgs === "--discard") {
          if (!context2.overwriteConfirmed) {
            return {
              type: "confirm_action",
              prompt: "Discard all Arena results and clean up worktrees?",
              originalInvocation: {
                raw: context2.invocation?.raw || "/arena select --discard"
              }
            };
          }
          await config2.cleanupArenaRuntime(true);
          return {
            type: "message",
            messageType: "info",
            content: "Arena results discarded. All worktrees cleaned up."
          };
        }
        const agents = manager.getAgentStates();
        const hasSuccessful = agents.some((a2) => isSuccessStatus(a2.status));
        if (!hasSuccessful) {
          return {
            type: "message",
            messageType: "error",
            content: "No successful agent results to select from. All agents failed or were cancelled.\nUse /arena stop to end the session."
          };
        }
        if (trimmedArgs) {
          const matchingAgent = agents.find(
            (a2) => isSuccessStatus(a2.status) && a2.model.modelId.toLowerCase() === trimmedArgs.toLowerCase()
          );
          if (!matchingAgent) {
            return {
              type: "message",
              messageType: "error",
              content: `No idle agent found matching "${trimmedArgs}".`
            };
          }
          const label = matchingAgent.model.modelId;
          const result = await manager.applyAgentResult(matchingAgent.agentId);
          if (!result.success) {
            return {
              type: "message",
              messageType: "error",
              content: `Failed to apply changes from ${label}: ${result.error}`
            };
          }
          await config2.cleanupArenaRuntime(true);
          return {
            type: "message",
            messageType: "info",
            content: `Applied changes from ${label} to workspace. Arena session complete.`
          };
        }
        return {
          type: "dialog",
          dialog: "arena_select"
        };
      }, "action")
    }
  ]
};

// packages/cli/src/ui/commands/approvalModeCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
init_dist4();
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 */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    const mode = parseApprovalModeArg(args2);
    if (!args2.trim()) {
      return {
        type: "dialog",
        dialog: "approval-mode"
      };
    }
    if (!mode) {
      return {
        type: "message",
        messageType: "error",
        content: t4('Invalid approval mode "{{arg}}". Valid modes: {{modes}}', {
          arg: args2.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();
init_types21();
init_i18n();
var authCommand2 = {
  name: "auth",
  altNames: ["login"],
  get description() {
    return t4("Configure authentication information for login");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name((_context, _args) => ({
    type: "dialog",
    dialog: "auth"
  }), "action")
};

// packages/cli/src/ui/commands/btwCommand.ts
init_esbuild_shims();
init_types21();
init_types22();
init_i18n();
init_dist4();
function formatBtwError(error40) {
  return t4("Failed to answer btw question: {{error}}", {
    error: error40 instanceof Error ? error40.message : String(error40 || "Unknown error")
  });
}
__name(formatBtwError, "formatBtwError");
function buildBtwPrompt(question) {
  return [
    "<system-reminder>",
    "This is a side question from the user. Answer directly in a single response.",
    "",
    "CRITICAL CONSTRAINTS:",
    "- You have NO tools available \u2014 you cannot read files, run commands, or take any actions.",
    "- You can ONLY use information already present in the conversation context.",
    "- NEVER promise to look something up or investigate further.",
    "- If you do not know the answer, say so.",
    "- The main conversation is NOT interrupted; you are a separate, lightweight fork.",
    "</system-reminder>",
    "",
    question
  ].join("\n");
}
__name(buildBtwPrompt, "buildBtwPrompt");
function getBtwCacheSafeParams(context2) {
  const geminiClient = context2.services.config?.getGeminiClient();
  if (geminiClient && typeof geminiClient === "object" && typeof geminiClient.getChat === "function" && typeof geminiClient.getHistory === "function") {
    const chat = geminiClient.getChat();
    if (chat && typeof chat === "object" && typeof chat.getGenerationConfig === "function") {
      const generationConfig = chat.getGenerationConfig();
      if (generationConfig) {
        const fullHistory = geminiClient.getHistory(true);
        const maxHistoryEntries = 40;
        const history = fullHistory.length > maxHistoryEntries ? fullHistory.slice(-maxHistoryEntries) : fullHistory;
        return {
          generationConfig,
          history,
          model: context2.services.config?.getModel() ?? "",
          version: 0
        };
      }
    }
  }
  return getCacheSafeParams();
}
__name(getBtwCacheSafeParams, "getBtwCacheSafeParams");
async function askBtw(context2, question, abortSignal) {
  const { config: config2 } = context2.services;
  if (!config2) throw new Error("Config not loaded");
  const cacheSafeParams = getBtwCacheSafeParams(context2);
  if (!cacheSafeParams)
    throw new Error(t4("No conversation context available for /btw"));
  const result = await runForkedAgent({
    config: config2,
    userMessage: buildBtwPrompt(question),
    cacheSafeParams,
    abortSignal
  });
  return result.text || t4("No response received.");
}
__name(askBtw, "askBtw");
var btwCommand = {
  name: "btw",
  get description() {
    return t4(
      "Ask a quick side question without affecting the main conversation"
    );
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    const question = args2.trim();
    if (!question) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Please provide a question. Usage: /btw <your question>")
      };
    }
    const { config: config2 } = context2.services;
    const { ui: ui2 } = context2;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config not loaded.")
      };
    }
    const model = config2.getModel();
    if (!model) {
      return {
        type: "message",
        messageType: "error",
        content: t4("No model configured.")
      };
    }
    ui2.cancelBtw();
    const btwAbortController = new AbortController();
    const btwSignal = btwAbortController.signal;
    ui2.btwAbortControllerRef.current = btwAbortController;
    const pendingItem = {
      type: "btw" /* BTW */,
      btw: {
        question,
        answer: "",
        isPending: true
      }
    };
    ui2.setBtwItem(pendingItem);
    void askBtw(context2, question, btwSignal).then((answer) => {
      if (btwSignal.aborted) return;
      ui2.btwAbortControllerRef.current = null;
      const completedItem = {
        type: "btw" /* BTW */,
        btw: {
          question,
          answer,
          isPending: false
        }
      };
      ui2.setBtwItem(completedItem);
    }).catch((error40) => {
      if (btwSignal.aborted) return;
      ui2.btwAbortControllerRef.current = null;
      ui2.setBtwItem(null);
      ui2.addItem(
        {
          type: "error" /* ERROR */,
          text: formatBtwError(error40)
        },
        Date.now()
      );
    });
  }, "action")
};

// packages/cli/src/ui/commands/bugCommand.ts
init_esbuild_shims();
init_open();
init_types21();
init_types22();

// packages/cli/src/utils/systemInfoFields.ts
init_esbuild_shims();
init_i18n();
init_dist4();
function getSystemInfoFields(info2) {
  const fields = [];
  addField(fields, t4("Qwen Code"), formatCliVersion(info2));
  addField(fields, t4("Runtime"), formatRuntime(info2));
  addField(fields, t4("IDE Client"), info2.ideClient);
  addField(fields, t4("OS"), formatOs(info2));
  addField(fields, t4("Auth"), formatAuth(info2));
  addField(fields, t4("Base URL"), formatBaseUrl(info2));
  addField(fields, t4("Model"), info2.modelVersion);
  addField(fields, t4("Fast Model"), info2.fastModel || info2.modelVersion);
  addField(fields, t4("Session ID"), info2.sessionId);
  addField(fields, t4("Sandbox"), info2.sandboxEnv);
  addField(fields, t4("Proxy"), formatProxy(info2.proxy));
  addField(fields, t4("Memory Usage"), info2.memoryUsage);
  return fields;
}
__name(getSystemInfoFields, "getSystemInfoFields");
function addField(fields, label, value) {
  if (value) {
    fields.push({ label, value });
  }
}
__name(addField, "addField");
function formatCliVersion(info2) {
  if (!info2.cliVersion) {
    return "";
  }
  if (!info2.gitCommit) {
    return info2.cliVersion;
  }
  return `${info2.cliVersion} (${info2.gitCommit})`;
}
__name(formatCliVersion, "formatCliVersion");
function formatRuntime(info2) {
  if (!info2.nodeVersion && !info2.npmVersion) {
    return "";
  }
  const node = info2.nodeVersion ? `Node.js ${info2.nodeVersion}` : "";
  const npm = info2.npmVersion ? `npm ${info2.npmVersion}` : "";
  return joinParts([node, npm], " / ");
}
__name(formatRuntime, "formatRuntime");
function formatOs(info2) {
  return joinParts(
    [info2.osPlatform, info2.osArch, formatOsRelease(info2.osRelease)],
    " "
  ).trim();
}
__name(formatOs, "formatOs");
function formatOsRelease(release3) {
  if (!release3) {
    return "";
  }
  return `(${release3})`;
}
__name(formatOsRelease, "formatOsRelease");
function formatAuth(info2) {
  if (!info2.selectedAuthType) {
    return "";
  }
  if (isCodingPlanConfig(info2.baseUrl, info2.apiKeyEnvKey)) {
    return t4("Alibaba Cloud Coding Plan");
  }
  if (info2.selectedAuthType.startsWith("oauth") || info2.selectedAuthType === "qwen-oauth") {
    return "Qwen OAuth";
  }
  return `API Key - ${info2.selectedAuthType}`;
}
__name(formatAuth, "formatAuth");
function formatBaseUrl(info2) {
  if (!info2.selectedAuthType || !info2.baseUrl) {
    return "";
  }
  if (info2.selectedAuthType.startsWith("oauth") || info2.selectedAuthType === "qwen-oauth") {
    return "";
  }
  return info2.baseUrl;
}
__name(formatBaseUrl, "formatBaseUrl");
function formatProxy(proxy2) {
  if (!proxy2) {
    return "no proxy";
  }
  return redactProxy(proxy2);
}
__name(formatProxy, "formatProxy");
function redactProxy(proxy2) {
  try {
    const url3 = new URL(proxy2);
    if (url3.username || url3.password) {
      url3.username = url3.username ? "***" : "";
      url3.password = url3.password ? "***" : "";
    }
    return url3.toString();
  } catch {
    return proxy2.replace(/\/\/[^/]*@/, "//***@");
  }
}
__name(redactProxy, "redactProxy");
function joinParts(parts2, separator) {
  return parts2.filter((part) => part).join(separator);
}
__name(joinParts, "joinParts");

// packages/cli/src/ui/commands/bugCommand.ts
init_i18n();
var bugCommand = {
  name: "bug",
  get description() {
    return t4("submit a bug report");
  },
  kind: "built-in" /* BUILT_IN */,
  argumentHint: "<description>",
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    const bugDescription = (args2 || "").trim();
    const systemInfo = await getExtendedSystemInfo(context2);
    const fields = getSystemInfoFields(systemInfo);
    const info2 = 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(`
${info2}
`));
    const bugReportItem = {
      type: "info" /* INFO */,
      text: "To submit your bug report, please open the following URL in your browser:",
      linkUrl: bugReportUrl,
      linkText: "Open GitHub bug report form"
    };
    context2.ui.addItem(bugReportItem, Date.now());
    try {
      await open_default(bugReportUrl);
    } catch (error40) {
      const errorMessage = error40 instanceof Error ? error40.message : String(error40);
      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();
init_types21();
init_i18n();
init_dist4();
var clearCommand = {
  name: "clear",
  altNames: ["reset", "new"],
  get description() {
    return t4("Clear conversation history and free up context");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: /* @__PURE__ */ __name(async (context2, _args) => {
    const { config: config2 } = context2.services;
    if (config2) {
      config2.getHookSystem()?.fireSessionEndEvent(SessionEndReason.Clear).catch((err2) => {
        config2.getDebugLogger().warn(`SessionEnd hook failed: ${err2}`);
      });
      const newSessionId = config2.startNewSession();
      uiTelemetryService.reset();
      const skillTool = config2.getToolRegistry()?.getAllTools().find((tool) => tool.name === ToolNames.SKILL);
      if (skillTool && "clearLoadedSkills" in skillTool) {
        skillTool.clearLoadedSkills();
      }
      if (newSessionId && context2.session.startNewSession) {
        context2.session.startNewSession(newSessionId);
      }
      context2.ui.clear();
      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."));
      }
      config2.getHookSystem()?.fireSessionStartEvent(
        SessionStartSource.Clear,
        config2.getModel() ?? "",
        String(config2.getApprovalMode())
      ).catch((err2) => {
        config2.getDebugLogger().warn(`SessionStart hook failed: ${err2}`);
      });
    } else {
      context2.ui.setDebugMessage(t4("Starting a new session and clearing."));
      context2.ui.clear();
    }
    if (context2.executionMode !== "interactive") {
      return {
        type: "message",
        messageType: "info",
        content: "Context cleared. Previous messages are no longer in context."
      };
    }
    return;
  }, "action")
};

// packages/cli/src/ui/commands/deleteCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var deleteCommand = {
  name: "delete",
  kind: "built-in" /* BUILT_IN */,
  get description() {
    return t4("Delete a previous session");
  },
  action: /* @__PURE__ */ __name(async () => ({
    type: "dialog",
    dialog: "delete"
  }), "action")
};

// packages/cli/src/ui/commands/compressCommand.ts
init_esbuild_shims();
init_types22();
init_types21();
init_i18n();
var compressCommand = {
  name: "compress",
  altNames: ["summarize"],
  get description() {
    return t4("Compresses the context by replacing it with a summary.");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  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/services/BuiltinCommandLoader.ts
init_contextCommand();

// packages/cli/src/ui/commands/copyCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var copyCommand = {
  name: "copy",
  get description() {
    return t4("Copy the last result or code snippet to clipboard");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  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 (error40) {
        const message = error40 instanceof Error ? error40.message : String(error40);
        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();
init_types21();
init_types22();
init_i18n();
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 */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: /* @__PURE__ */ __name(async (context2) => {
    const langPath = getCurrentLanguage()?.startsWith("zh") ? "zh" : "en";
    const docsUrl = `https://qwenlm.github.io/qwen-code-docs/${langPath}`;
    if (context2.executionMode !== "interactive") {
      return {
        type: "message",
        messageType: "info",
        content: `Qwen Code documentation: ${docsUrl}`
      };
    }
    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);
    }
    return;
  }, "action")
};

// packages/cli/src/ui/commands/doctorCommand.ts
init_esbuild_shims();
init_types21();

// packages/cli/src/utils/doctorChecks.ts
init_esbuild_shims();
import process32 from "node:process";
import os42 from "node:os";
init_dist4();
init_i18n();
var MIN_NODE_MAJOR = 20;
function checkNodeVersion() {
  const version2 = process32.version;
  const major2 = parseInt(version2.replace(/^v/, "").split(".")[0], 10);
  if (isNaN(major2) || major2 < MIN_NODE_MAJOR) {
    return {
      category: t4("System"),
      name: t4("Node.js version"),
      status: "fail",
      message: version2,
      detail: t4("Node.js v{{min}}+ is required. Current: {{version}}", {
        min: String(MIN_NODE_MAJOR),
        version: version2
      })
    };
  }
  return {
    category: t4("System"),
    name: t4("Node.js version"),
    status: "pass",
    message: version2
  };
}
__name(checkNodeVersion, "checkNodeVersion");
async function checkNpmVersion() {
  const version2 = await getNpmVersion();
  if (version2 === "unknown") {
    return {
      category: t4("System"),
      name: t4("npm version"),
      status: "warn",
      message: t4("not found"),
      detail: t4("npm is not available. Some features may not work.")
    };
  }
  return {
    category: t4("System"),
    name: t4("npm version"),
    status: "pass",
    message: version2
  };
}
__name(checkNpmVersion, "checkNpmVersion");
function checkPlatform() {
  return {
    category: t4("System"),
    name: t4("Platform"),
    status: "pass",
    message: `${process32.platform}/${process32.arch} (${os42.release()})`
  };
}
__name(checkPlatform, "checkPlatform");
function checkAuth(context2) {
  const authType = context2.services.config?.getAuthType();
  if (!authType) {
    return {
      category: t4("Authentication"),
      name: t4("API key"),
      status: "fail",
      message: t4("not configured"),
      detail: t4("Run /auth to configure authentication.")
    };
  }
  const error40 = validateAuthMethod(
    authType,
    context2.services.config ?? void 0
  );
  if (error40) {
    return {
      category: t4("Authentication"),
      name: t4("API key"),
      status: "fail",
      message: t4("invalid ({{authType}})", { authType }),
      detail: error40
    };
  }
  return {
    category: t4("Authentication"),
    name: t4("API key"),
    status: "pass",
    message: t4("configured ({{authType}})", { authType })
  };
}
__name(checkAuth, "checkAuth");
async function checkApiClient(context2) {
  const config2 = context2.services.config;
  if (!config2) {
    return {
      category: t4("Authentication"),
      name: t4("API client"),
      status: "fail",
      message: t4("config not loaded")
    };
  }
  try {
    const client = config2.getGeminiClient();
    if (client.isInitialized()) {
      return {
        category: t4("Authentication"),
        name: t4("API client"),
        status: "pass",
        message: t4("client initialized")
      };
    }
    return {
      category: t4("Authentication"),
      name: t4("API client"),
      status: "warn",
      message: t4("client not initialized"),
      detail: t4("The API client has not been initialized yet.")
    };
  } catch (error40) {
    const errorMsg = error40 instanceof Error ? error40.message : String(error40);
    return {
      category: t4("Authentication"),
      name: t4("API client"),
      status: "warn",
      message: t4("error"),
      detail: errorMsg
    };
  }
}
__name(checkApiClient, "checkApiClient");
function checkSettings(context2) {
  const settings = context2.services.settings;
  if (!settings) {
    return {
      category: t4("Configuration"),
      name: t4("Settings"),
      status: "fail",
      message: t4("not loaded"),
      detail: t4(
        "Settings could not be loaded. Check your settings files for syntax errors."
      )
    };
  }
  return {
    category: t4("Configuration"),
    name: t4("Settings"),
    status: "pass",
    message: t4("loaded")
  };
}
__name(checkSettings, "checkSettings");
function checkModel(context2) {
  const model = context2.services.config?.getModel();
  if (!model) {
    return {
      category: t4("Configuration"),
      name: t4("Model"),
      status: "fail",
      message: t4("not configured"),
      detail: t4("Run /model to select a model.")
    };
  }
  return {
    category: t4("Configuration"),
    name: t4("Model"),
    status: "pass",
    message: model
  };
}
__name(checkModel, "checkModel");
function checkMcpServers(context2) {
  const config2 = context2.services.config;
  const servers = config2?.getMcpServers();
  if (!servers || Object.keys(servers).length === 0) {
    return [
      {
        category: t4("MCP Servers"),
        name: t4("MCP servers"),
        status: "pass",
        message: t4("none configured")
      }
    ];
  }
  if (context2.executionMode !== "interactive") {
    return Object.keys(servers).map((name4) => ({
      category: t4("MCP Servers"),
      name: name4,
      status: "pass",
      message: config2?.isMcpServerDisabled(name4) ? t4("disabled") : t4("configured (not checked in non-interactive mode)")
    }));
  }
  return Object.keys(servers).map((name4) => {
    if (config2?.isMcpServerDisabled(name4)) {
      return {
        category: t4("MCP Servers"),
        name: name4,
        status: "pass",
        message: t4("disabled")
      };
    }
    const status = getMCPServerStatus(name4);
    switch (status) {
      case MCPServerStatus.CONNECTED:
        return {
          category: t4("MCP Servers"),
          name: name4,
          status: "pass",
          message: t4("connected")
        };
      case MCPServerStatus.CONNECTING:
        return {
          category: t4("MCP Servers"),
          name: name4,
          status: "warn",
          message: t4("connecting"),
          detail: t4("Server is still starting up.")
        };
      case MCPServerStatus.DISCONNECTED:
      default:
        return {
          category: t4("MCP Servers"),
          name: name4,
          status: "fail",
          message: t4("disconnected"),
          detail: t4(
            "Check that the server process is running and configuration is correct."
          )
        };
    }
  });
}
__name(checkMcpServers, "checkMcpServers");
function checkToolRegistry(context2) {
  const registry3 = context2.services.config?.getToolRegistry();
  if (!registry3) {
    return {
      category: t4("Tools"),
      name: t4("Tool registry"),
      status: "fail",
      message: t4("not loaded")
    };
  }
  const count = registry3.getAllTools().length;
  return {
    category: t4("Tools"),
    name: t4("Tool registry"),
    status: "pass",
    message: t4("{{count}} tools registered", { count: String(count) })
  };
}
__name(checkToolRegistry, "checkToolRegistry");
async function checkRipgrep(context2) {
  try {
    const useBuiltin = context2.services.config?.getUseBuiltinRipgrep() ?? false;
    const result = await canUseRipgrep(useBuiltin);
    if (result) {
      return {
        category: t4("Tools"),
        name: t4("Ripgrep"),
        status: "pass",
        message: t4("available")
      };
    }
    return {
      category: t4("Tools"),
      name: t4("Ripgrep"),
      status: "warn",
      message: t4("not available"),
      detail: t4(
        "Install ripgrep for faster file search: https://github.com/BurntSushi/ripgrep"
      )
    };
  } catch {
    return {
      category: t4("Tools"),
      name: t4("Ripgrep"),
      status: "warn",
      message: t4("check failed")
    };
  }
}
__name(checkRipgrep, "checkRipgrep");
async function checkGit(context2) {
  if (context2.services.git) {
    return {
      category: t4("Git"),
      name: t4("Git"),
      status: "pass",
      message: t4("available")
    };
  }
  const version2 = await getGitVersion();
  if (version2 === "unknown") {
    return {
      category: t4("Git"),
      name: t4("Git"),
      status: "warn",
      message: t4("not available"),
      detail: t4("Git features will be limited.")
    };
  }
  return {
    category: t4("Git"),
    name: t4("Git"),
    status: "pass",
    message: version2
  };
}
__name(checkGit, "checkGit");
async function runDoctorChecks(context2) {
  const [npmResult, ripgrepResult, apiClientResult, gitResult] = await Promise.all([
    checkNpmVersion(),
    checkRipgrep(context2),
    checkApiClient(context2),
    checkGit(context2)
  ]);
  return [
    // System
    checkNodeVersion(),
    npmResult,
    checkPlatform(),
    // Authentication
    checkAuth(context2),
    apiClientResult,
    // Configuration
    checkSettings(context2),
    checkModel(context2),
    // MCP Servers
    ...checkMcpServers(context2),
    // Tools
    checkToolRegistry(context2),
    ripgrepResult,
    // Git
    gitResult
  ];
}
__name(runDoctorChecks, "runDoctorChecks");

// packages/cli/src/ui/commands/doctorCommand.ts
init_i18n();
var doctorCommand = {
  name: "doctor",
  get description() {
    return t4("Run installation and environment diagnostics");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: /* @__PURE__ */ __name(async (context2) => {
    const executionMode = context2.executionMode ?? "interactive";
    const abortSignal = context2.abortSignal;
    if (executionMode === "interactive") {
      context2.ui.setPendingItem({
        type: "info",
        text: t4("Running diagnostics...")
      });
    }
    try {
      const checks = await runDoctorChecks(context2);
      if (abortSignal?.aborted) {
        return;
      }
      const summary = {
        pass: checks.filter((c4) => c4.status === "pass").length,
        warn: checks.filter((c4) => c4.status === "warn").length,
        fail: checks.filter((c4) => c4.status === "fail").length
      };
      if (executionMode === "interactive") {
        const doctorItem = {
          type: "doctor",
          checks,
          summary
        };
        context2.ui.addItem(doctorItem, Date.now());
        return;
      }
      return {
        type: "message",
        messageType: summary.fail > 0 ? "error" : "info",
        content: JSON.stringify({ checks, summary }, null, 2)
      };
    } finally {
      if (executionMode === "interactive") {
        context2.ui.setPendingItem(null);
      }
    }
  }, "action")
};

// packages/cli/src/ui/commands/directoryCommand.tsx
init_esbuild_shims();
init_types21();
init_types22();
init_dist4();
init_i18n();
import * as fs112 from "node:fs";
import * as os43 from "node:os";
import * as path113 from "node:path";
function expandHomeDir(p2) {
  if (!p2) {
    return "";
  }
  let expandedPath = p2;
  if (p2.toLowerCase().startsWith("%userprofile%")) {
    expandedPath = os43.homedir() + p2.substring("%userprofile%".length);
  } else if (p2 === "~" || p2.startsWith("~/")) {
    expandedPath = os43.homedir() + p2.substring(1);
  }
  return path113.normalize(expandedPath);
}
__name(expandHomeDir, "expandHomeDir");
function findExistingWorkspaceDirectory(directory, existingDirectories) {
  if (existingDirectories.has(directory)) {
    return directory;
  }
  try {
    const absolutePath = path113.isAbsolute(directory) ? directory : path113.resolve(directory);
    const resolvedDirectory = fs112.realpathSync(absolutePath);
    if (existingDirectories.has(resolvedDirectory)) {
      return resolvedDirectory;
    }
  } catch {
  }
  return void 0;
}
__name(findExistingWorkspaceDirectory, "findExistingWorkspaceDirectory");
function getDirPathCompletions(partialArg) {
  const lastComma = partialArg.lastIndexOf(",");
  const prefix = lastComma >= 0 ? partialArg.substring(0, lastComma + 1) : "";
  const partial2 = lastComma >= 0 ? partialArg.substring(lastComma + 1).trimStart() : partialArg;
  const trimmed2 = partial2.trim();
  if (!trimmed2) return [];
  const expanded = trimmed2.startsWith("~") ? trimmed2.replace(/^~/, os43.homedir()) : trimmed2;
  const endsWithSep = expanded.endsWith("/") || expanded.endsWith(path113.sep);
  const searchDir = endsWithSep ? expanded : path113.dirname(expanded);
  const namePrefix = endsWithSep ? "" : path113.basename(expanded);
  try {
    return fs112.readdirSync(searchDir, { withFileTypes: true }).filter(
      (e4) => e4.isDirectory() && e4.name.startsWith(namePrefix) && !e4.name.startsWith(".")
    ).map((e4) => prefix + path113.join(searchDir, e4.name)).slice(0, 8);
  } catch {
    return [];
  }
}
__name(getDirPathCompletions, "getDirPathCompletions");
var directoryCommand = {
  name: "directory",
  altNames: ["dir"],
  get description() {
    return t4("Manage workspace directories");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  subCommands: [
    {
      name: "add",
      get description() {
        return t4(
          "Add directories to the workspace. Use comma to separate multiple paths"
        );
      },
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive"],
      completion: /* @__PURE__ */ __name(async (_context, partialArg) => getDirPathCompletions(partialArg), "completion"),
      action: /* @__PURE__ */ __name(async (context2, args2) => {
        const {
          ui: { addItem },
          services: { config: config2, settings }
        } = context2;
        const [...rest] = args2.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 alreadyAdded = [];
        const errors = [];
        for (const pathToAdd of pathsToAdd) {
          const directory = expandHomeDir(pathToAdd.trim());
          const directoriesBeforeAdd = new Set(
            workspaceContext.getDirectories()
          );
          try {
            workspaceContext.addDirectory(directory);
            const acceptedDirectories = workspaceContext.getDirectories().filter((dir) => !directoriesBeforeAdd.has(dir));
            if (acceptedDirectories.length > 0) {
              added.push(...acceptedDirectories);
            } else {
              const existingDirectory = findExistingWorkspaceDirectory(
                directory,
                directoriesBeforeAdd
              );
              if (existingDirectory) {
                alreadyAdded.push(existingDirectory);
              }
            }
          } catch (e4) {
            const error40 = e4;
            errors.push(
              t4("Error adding '{{path}}': {{error}}", {
                path: pathToAdd.trim(),
                error: error40.message
              })
            );
          }
        }
        if (added.length > 0) {
          try {
            const existingIncludeDirectories = settings.workspace.originalSettings.context?.includeDirectories ?? [];
            const includeDirectories = Array.from(
              /* @__PURE__ */ new Set([...existingIncludeDirectories, ...added])
            );
            settings.setValue(
              "Workspace" /* Workspace */,
              "context.includeDirectories",
              includeDirectories
            );
          } catch (error40) {
            errors.push(
              t4("Error saving directories to workspace settings: {{error}}", {
                error: error40.message
              })
            );
          }
        }
        if (added.length > 0) {
          try {
            if (config2.shouldLoadMemoryFromIncludeDirectories()) {
              const {
                memoryContent,
                fileCount,
                conditionalRules,
                projectRoot
              } = await loadServerHierarchicalMemory(
                config2.getWorkingDir(),
                [...config2.getWorkspaceContext().getDirectories(), ...added],
                config2.getFileService(),
                config2.getExtensionContextFilePaths(),
                config2.getFolderTrust(),
                context2.services.settings.merged.context?.importFormat || "tree",
                // Use setting or default to 'tree'
                config2.getContextRuleExcludes()
              );
              config2.setUserMemory(memoryContent);
              config2.setGeminiMdFileCount(fileCount);
              config2.setConditionalRulesRegistry(
                new ConditionalRulesRegistry(conditionalRules, projectRoot)
              );
              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 (error40) {
            errors.push(
              t4("Error refreshing memory: {{error}}", {
                error: error40.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 (alreadyAdded.length > 0) {
          const directories = Array.from(new Set(alreadyAdded));
          addItem(
            {
              type: "info" /* INFO */,
              text: t4("Directories already in workspace:\n- {{directories}}", {
                directories: directories.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 */,
      supportedModes: ["interactive"],
      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();
init_types21();
init_i18n();
var editorCommand = {
  name: "editor",
  get description() {
    return t4("set external editor preference");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(() => ({
    type: "dialog",
    dialog: "editor"
  }), "action")
};

// packages/cli/src/ui/commands/exportCommand.ts
init_esbuild_shims();
init_types21();
init_dist4();
import * as fs113 from "node:fs/promises";
import path114 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 randomUUID17 } 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.
   * If a message rewriter is configured, updates pass through it first
   * (original messages are sent as-is, rewritten versions are appended).
   */
  async sendUpdate(update2) {
    if (this.ctx.messageRewriter) {
      return this.ctx.messageRewriter.interceptUpdate(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 StopHookLoop event when Stop hooks create a loop.
   * This informs the client that Stop hooks have been executed multiple times.
   *
   * @param iterationCount - The current iteration count
   * @param reasons - Array of reasons from each Stop hook execution
   * @param stopHookCount - Number of Stop hooks that were executed
   */
  async emitStopHookLoop(iterationCount, reasons, stopHookCount) {
    await this.sendUpdate({
      sessionUpdate: "agent_message_chunk",
      content: { type: "text", text: "" },
      _meta: {
        stopHookLoop: {
          iterationCount,
          reasons,
          stopHookCount
        }
      }
    });
  }
  /**
   * 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 = {
      inputTokens: usageMetadata.promptTokenCount ?? 0,
      outputTokens: usageMetadata.candidatesTokenCount ?? 0,
      totalTokens: usageMetadata.totalTokenCount ?? 0,
      thoughtTokens: usageMetadata.thoughtsTokenCount,
      cachedReadTokens: 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, args2) {
    const fromDisplay = this.extractFromResultDisplay(resultDisplay);
    if (fromDisplay) return fromDisplay;
    if (args2 && Array.isArray(args2["todos"])) {
      return args2["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
init_dist4();
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, error40, subagentMeta) {
    await this.sendUpdate({
      sessionUpdate: "tool_call_update",
      toolCallId: callId,
      status: "failed",
      content: [
        { type: "content", content: { type: "text", text: error40.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 === ToolNames.TODO_WRITE;
  }
  /**
   * Checks if a tool name is the ExitPlanModeTool.
   */
  isExitPlanModeTool(toolName) {
    return toolName === ToolNames.EXIT_PLAN_MODE;
  }
  /**
   * 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, args2) {
    const toolRegistry = this.config.getToolRegistry();
    const tool = toolRegistry.getTool(toolName);
    let title = tool?.displayName ?? toolName;
    let locations = [];
    let kind2 = "other";
    if (tool && args2) {
      try {
        const invocation = tool.build(args2);
        title = `${title}: ${invocation.getDescription()}`;
        locations = invocation.toolLocations().map((loc) => ({
          path: loc.path,
          line: loc.line ?? null
        }));
        kind2 = this.mapToolKind(tool.kind, toolName);
      } catch {
        if (typeof args2["description"] === "string") {
          title = `${title}: ${args2["description"]}`;
        }
        if (tool.kind) {
          kind2 = this.mapToolKind(tool.kind, toolName);
        }
      }
    }
    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(parts2) {
    const result = [];
    for (const part of parts2) {
      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.subtype === "notification" || record2.subtype === "cron") {
          const displayText = record2.systemPayload?.displayText;
          if (displayText) {
            await this.messageEmitter.emitUserMessage(
              displayText,
              record2.timestamp
            );
          }
          break;
        }
        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;
      case "system":
        if (record2.subtype === "slash_command") {
          await this.replaySlashCommandResult(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 AgentResultDisplay 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);
    }
  }
  /**
   * Replays a slash_command system record by re-emitting its output as an
   * agent message chunk. This allows Zed to reconstruct the correct turn
   * structure (user → agent) on session resume without polluting model context.
   */
  async replaySlashCommandResult(record2) {
    const payload = record2.systemPayload;
    if (payload?.phase !== "result" || !payload.outputHistoryItems?.length) {
      return;
    }
    for (const item of payload.outputHistoryItems) {
      const text = typeof item["text"] === "string" ? item["text"] : "";
      if (text) {
        await this.messageEmitter.emitAgentMessage(
          text.replace(/\n/g, "  \n"),
          record2.timestamp
        );
      }
    }
  }
  /**
   * 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
function extractToolNameFromRecord(record2) {
  if (!record2.message?.parts) {
    return void 0;
  }
  for (const part of record2.message.parts) {
    if ("functionResponse" in part && part.functionResponse?.name) {
      return part.functionResponse.name;
    }
  }
  return void 0;
}
__name(extractToolNameFromRecord, "extractToolNameFromRecord");
function extractFunctionResponseId(record2) {
  if (!record2.message?.parts) {
    return void 0;
  }
  for (const part of record2.message.parts) {
    if ("functionResponse" in part && part.functionResponse?.id) {
      return part.functionResponse.id;
    }
  }
  return void 0;
}
__name(extractFunctionResponseId, "extractFunctionResponseId");
function normalizeFunctionCallArgs(args2) {
  if (args2 && typeof args2 === "object") {
    return args2;
  }
  if (typeof args2 === "string") {
    try {
      const parsed = JSON.parse(args2);
      if (parsed && typeof parsed === "object") {
        return parsed;
      }
    } catch {
    }
  }
  return void 0;
}
__name(normalizeFunctionCallArgs, "normalizeFunctionCallArgs");
function buildToolCallArgsIndex(records) {
  const byId = /* @__PURE__ */ new Map();
  const byName = /* @__PURE__ */ new Map();
  for (const record2 of records) {
    if (record2.type !== "assistant" || !record2.message?.parts) continue;
    for (const part of record2.message.parts) {
      if (!("functionCall" in part) || !part.functionCall?.name) continue;
      const normalizedArgs = normalizeFunctionCallArgs(part.functionCall.args);
      if (!normalizedArgs) continue;
      const toolName = part.functionCall.name;
      const callId = typeof part.functionCall.id === "string" ? part.functionCall.id : null;
      if (callId) {
        byId.set(callId, normalizedArgs);
      }
      const queue = byName.get(toolName) ?? [];
      queue.push(normalizedArgs);
      byName.set(toolName, queue);
    }
  }
  return { byId, byName };
}
__name(buildToolCallArgsIndex, "buildToolCallArgsIndex");
function calculateFileStats(records) {
  const argsIndex = buildToolCallArgsIndex(records);
  const byNameCursor = /* @__PURE__ */ new Map();
  const stats = {
    filesWritten: 0,
    linesAdded: 0,
    linesRemoved: 0,
    writtenFilePaths: /* @__PURE__ */ new Set()
  };
  for (const record2 of records) {
    if (record2.type !== "tool_result" || !record2.toolCallResult) continue;
    const toolName = extractToolNameFromRecord(record2);
    const callId = record2.toolCallResult.callId ?? extractFunctionResponseId(record2);
    const argsFromId = callId && argsIndex.byId.has(callId) ? argsIndex.byId.get(callId) : void 0;
    let args2 = argsFromId;
    if (!args2 && toolName) {
      const queue = argsIndex.byName.get(toolName);
      if (queue && queue.length > 0) {
        const cursor = byNameCursor.get(toolName) ?? 0;
        args2 = queue[cursor];
        byNameCursor.set(toolName, cursor + 1);
      }
    }
    const { resultDisplay } = record2.toolCallResult;
    if (resultDisplay && typeof resultDisplay === "object" && "fileName" in resultDisplay) {
      const display = resultDisplay;
      const hasOriginalContent = "originalContent" in display;
      const hasNewContent = "newContent" in display;
      let filePath;
      if (typeof display.fileName === "string") {
        filePath = args2?.["file_path"] || display.fileName;
      } else {
        filePath = "unknown";
      }
      if (hasOriginalContent || hasNewContent) {
        stats.filesWritten++;
        stats.writtenFilePaths.add(filePath);
        if (display.diffStat) {
          stats.linesAdded += display.diffStat.model_added_lines ?? 0;
          stats.linesRemoved += display.diffStat.model_removed_lines ?? 0;
        } else {
          const oldText = String(display.originalContent ?? "");
          const newText = String(display.newContent ?? "");
          const oldLines = oldText.split("\n").filter((line) => line.length > 0).length;
          const newLines = newText.split("\n").filter((line) => line.length > 0).length;
          stats.linesAdded += newLines;
          stats.linesRemoved += oldLines;
        }
      }
    }
  }
  return stats;
}
__name(calculateFileStats, "calculateFileStats");
function extractTaskToolTokens(record2) {
  if (record2.type !== "tool_result" || !record2.toolCallResult?.resultDisplay) {
    return 0;
  }
  const { resultDisplay } = record2.toolCallResult;
  if (typeof resultDisplay === "object" && "type" in resultDisplay && resultDisplay.type === "task_execution" && "executionSummary" in resultDisplay) {
    const summary = resultDisplay.executionSummary;
    if (typeof summary.totalTokens === "number") {
      return summary.totalTokens;
    }
    return (summary.inputTokens ?? 0) + (summary.outputTokens ?? 0) + (summary.thoughtTokens ?? 0) + (summary.cachedTokens ?? 0);
  }
  return 0;
}
__name(extractTaskToolTokens, "extractTaskToolTokens");
function calculateTokenStats(records) {
  let totalTokens = 0;
  let lastValidRecord = null;
  for (const record2 of records) {
    if (record2.type === "assistant") {
      if (record2.usageMetadata) {
        totalTokens += record2.usageMetadata.totalTokenCount ?? 0;
      }
      if (record2.usageMetadata?.totalTokenCount !== void 0 && record2.contextWindowSize !== void 0) {
        lastValidRecord = {
          totalTokenCount: record2.usageMetadata.totalTokenCount,
          contextWindowSize: record2.contextWindowSize
        };
      }
    }
    const taskTokens = extractTaskToolTokens(record2);
    if (taskTokens > 0) {
      totalTokens += taskTokens;
    }
  }
  if (lastValidRecord) {
    const percent = lastValidRecord.totalTokenCount / lastValidRecord.contextWindowSize * 100;
    return {
      totalTokens,
      contextUsagePercent: Math.round(percent * 10) / 10,
      contextWindowSize: lastValidRecord.contextWindowSize
    };
  }
  const lastAssistantRecord = [...records].reverse().find((r5) => r5.type === "assistant" && r5.contextWindowSize !== void 0);
  return {
    totalTokens,
    contextWindowSize: lastAssistantRecord?.contextWindowSize
  };
}
__name(calculateTokenStats, "calculateTokenStats");
async function extractMetadata(conversation, config2) {
  const { sessionId, startTime, messages } = conversation;
  const firstRecord = messages[0];
  const cwd6 = firstRecord?.cwd ?? "";
  const gitBranch = firstRecord?.gitBranch;
  let gitRepo;
  if (cwd6) {
    const { getGitRepoName: getGitRepoName2 } = await Promise.resolve().then(() => (init_dist4(), dist_exports));
    gitRepo = getGitRepoName2(cwd6);
  }
  let model;
  for (const record2 of messages) {
    if (record2.type === "assistant" && record2.model) {
      model = record2.model;
      break;
    }
  }
  const channel = config2.getChannel?.();
  const promptCount = messages.filter((m3) => m3.type === "user").length;
  const fileStats = calculateFileStats(messages);
  const tokenStats = calculateTokenStats(messages);
  return {
    sessionId,
    startTime,
    exportTime: (/* @__PURE__ */ new Date()).toISOString(),
    cwd: cwd6,
    gitRepo,
    gitBranch,
    model,
    channel,
    promptCount,
    contextUsagePercent: tokenStats.contextUsagePercent,
    contextWindowSize: tokenStats.contextWindowSize,
    totalTokens: tokenStats.totalTokens,
    filesWritten: fileStats.writtenFilePaths.size,
    linesAdded: fileStats.linesAdded,
    linesRemoved: fileStats.linesRemoved,
    uniqueFiles: Array.from(fileStats.writtenFilePaths)
  };
}
__name(extractMetadata, "extractMetadata");
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": {
        const usageMeta = update2._meta;
        const usageMetadata = usageMeta?.usage ? {
          promptTokenCount: usageMeta.usage.inputTokens,
          candidatesTokenCount: usageMeta.usage.outputTokens,
          totalTokenCount: usageMeta.usage.totalTokens,
          thoughtsTokenCount: usageMeta.usage.thoughtTokens,
          cachedContentTokenCount: usageMeta.usage.cachedReadTokens
        } : void 0;
        this.handleMessageChunk(
          "assistant",
          update2.content,
          "assistant",
          usageMetadata
        );
        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 ?? randomUUID17();
  }
  handleMessageChunk(role, content, messageRole = role, usageMetadata) {
    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 });
      if (usageMetadata && role === "assistant") {
        this.currentMessage.usageMetadata = usageMetadata;
      }
    } else {
      this.currentMessage = {
        type: role,
        role: messageRole,
        parts: [{ text: content.text }],
        timestamp: Date.now(),
        ...usageMetadata && role === "assistant" ? { usageMetadata } : {}
      };
    }
  }
  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 uuid3 = this.getMessageUuid();
    this.messages.push({
      uuid: uuid3,
      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 uuid3 = 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: uuid3,
      sessionId: this.sessionId,
      timestamp,
      type: "tool_call",
      toolCall: {
        toolCallId: uuid3,
        // 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 uuid3 = this.getMessageUuid();
    const exportMessage = {
      uuid: uuid3,
      sessionId: this.sessionId,
      timestamp: this.getMessageTimestamp(),
      type: this.currentMessage.type,
      message: {
        role: this.currentMessage.role,
        parts: this.currentMessage.parts
      }
    };
    if (this.currentMessage.type === "assistant" && this.currentMessage.usageMetadata) {
      exportMessage.usageMetadata = this.currentMessage.usageMetadata;
    }
    this.messages.push(exportMessage);
    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();
  const metadata2 = await extractMetadata(conversation, config2);
  return {
    sessionId: conversation.sessionId,
    startTime: conversation.startTime,
    messages,
    metadata: metadata2
  };
}
__name(collectSessionData, "collectSessionData");

// packages/cli/src/ui/utils/export/normalize.ts
init_esbuild_shims();
init_dist4();
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);
    }
  });
  const assistantMessageIndexByUuid = /* @__PURE__ */ new Map();
  normalized2.forEach((message, index) => {
    if (message.type === "assistant") {
      assistantMessageIndexByUuid.set(message.uuid, 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);
  }
  for (const record2 of originalRecords) {
    if (record2.type !== "assistant") continue;
    if (!record2.usageMetadata) continue;
    const existingIndex = assistantMessageIndexByUuid.get(record2.uuid);
    if (existingIndex !== void 0) {
      if (!normalized2[existingIndex].usageMetadata) {
        normalized2[existingIndex].usageMetadata = record2.usageMetadata;
      }
    }
  }
  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 = extractToolNameFromRecord2(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 extractToolNameFromRecord2(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(extractToolNameFromRecord2, "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, args2) {
  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 && args2) {
    try {
      const invocation = tool.build(args2);
      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 === ToolNames.EXIT_PLAN_MODE) {
    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(parts2) {
  const content = [];
  for (const part of parts2) {
    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 = [];
  const metadata2 = sessionData.metadata;
  lines.push("# Chat Session Export\n");
  lines.push(`- **Session ID**: \`${sanitizeText(sessionData.sessionId)}\``);
  lines.push(`- **Start Time**: ${sanitizeText(sessionData.startTime)}`);
  lines.push(
    `- **Exported**: ${sanitizeText(metadata2?.exportTime ?? (/* @__PURE__ */ new Date()).toISOString())}`
  );
  lines.push("");
  if (metadata2?.cwd) {
    lines.push(`- **Working Directory**: \`${sanitizeText(metadata2.cwd)}\``);
  }
  if (metadata2?.gitRepo) {
    lines.push(`- **Git Repository**: ${sanitizeText(metadata2.gitRepo)}`);
  }
  if (metadata2?.gitBranch) {
    lines.push(`- **Git Branch**: \`${sanitizeText(metadata2.gitBranch)}\``);
  }
  lines.push("");
  if (metadata2?.model) {
    lines.push(`- **Model**: ${sanitizeText(metadata2.model)}`);
  }
  if (metadata2?.channel) {
    lines.push(`- **Channel**: ${sanitizeText(metadata2.channel)}`);
  }
  if (metadata2?.promptCount !== void 0) {
    lines.push(`- **Prompt Count**: ${metadata2.promptCount}`);
  }
  lines.push("");
  if (metadata2?.totalTokens !== void 0) {
    lines.push(`- **Total Tokens**: ${metadata2.totalTokens}`);
  }
  if (metadata2?.contextWindowSize !== void 0) {
    lines.push(`- **Context Window Size**: ${metadata2.contextWindowSize}`);
  }
  if (metadata2?.contextUsagePercent !== void 0) {
    lines.push(`- **Context Usage**: ${metadata2.contextUsagePercent}%`);
  }
  lines.push("");
  if (metadata2?.filesWritten !== void 0) {
    lines.push(`- **Files Written**: ${metadata2.filesWritten}`);
  }
  if (metadata2?.linesAdded !== void 0) {
    lines.push(`- **Lines Added**: ${metadata2.linesAdded}`);
  }
  if (metadata2?.linesRemoved !== void 0) {
    lines.push(`- **Lines Removed**: ${metadata2.linesRemoved}`);
  }
  if (metadata2?.uniqueFiles && metadata2.uniqueFiles.length > 0) {
    lines.push("");
    lines.push("<details>");
    lines.push(
      `<summary><strong>Unique Files Referenced (${metadata2.uniqueFiles.length})</strong></summary>`
    );
    lines.push("");
    for (const file2 of metadata2.uniqueFiles) {
      lines.push(`- \`${sanitizeText(file2)}\``);
    }
    lines.push("</details>");
  }
  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 path150 = item["path"];
        const diffText = item["newText"];
        lines.push(`
*Diff for \`${sanitizeText(path150)}\`:*`);
        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 matches2 = (value ?? "").match(/`+/g);
  const maxRun = matches2 ? Math.max(...matches2.map((match2) => match2.length)) : 0;
  const fenceLength = Math.max(3, maxRun + 1);
  return "`".repeat(fenceLength);
}
__name(buildFence, "buildFence");
function getLanguageFromPath(path150) {
  const ext2 = path150.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/src/index.ts
init_esbuild_shims();

// packages/web-templates/src/generated/insightTemplate.ts
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/src/generated/exportHtmlTemplate.ts
init_esbuild_shims();
var HTML_TEMPLATE = '<!doctype html>\n<html lang="en" class="dark">\n  <head>\n    <meta charset="UTF-8" />\n    <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n    <link\n      rel="icon"\n      type="image/svg+xml"\n      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"\n    />\n    <script\n      crossorigin\n      src="https://unpkg.com/react@18.2.0/umd/react.production.min.js"\n    ></script>\n    <script\n      crossorigin\n      src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.production.min.js"\n    ></script>\n    <script>\n      const withKey = (props, key) =>\n        key == null ? props : Object.assign({}, props, { key });\n      const jsx = (type, props, key) =>\n        React.createElement(type, withKey(props, key));\n      const jsxRuntime = {\n        Fragment: React.Fragment,\n        jsx,\n        jsxs: jsx,\n        jsxDEV: jsx,\n      };\n      window.ReactJSXRuntime = jsxRuntime;\n      window[\'react/jsx-runtime\'] = jsxRuntime;\n      window[\'react/jsx-dev-runtime\'] = jsxRuntime;\n    </script>\n    <script src="https://unpkg.com/@qwen-code/webui@latest/dist/index.umd.js"></script>\n    <link\n      rel="stylesheet"\n      href="https://unpkg.com/@qwen-code/webui@latest/dist/styles.css"\n    />\n    <title>Qwen Code Chat Export</title>\n    <style>\n      @font-face {\n        font-family: "Press Start 2P";\n        font-style: normal;\n        font-weight: 400;\n        font-display: swap;\n        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");\n      }\n      :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}::-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}}.content-wrapper{display:flex;width:100%;max-width:1600px;height:calc(100vh - 73px)}.chat-container{flex:1;min-width:0;overflow-y:auto;padding:24px;box-sizing:border-box}.metadata-sidebar{width:320px;min-width:320px;padding:12px;border-right:1px solid var(--border-color);background-color:var(--bg-secondary);display:flex;flex-direction:column;gap:12px;overflow-y:auto;height:100%;box-sizing:border-box}.metadata-section{display:flex;flex-direction:column;gap:8px}.metadata-section-title{font-size:10px;font-weight:600;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.05em;margin:0;padding-bottom:4px;border-bottom:1px solid var(--border-color)}.metadata-section-small{margin-top:auto;padding-top:12px;border-top:1px solid var(--border-color)}.metadata-item{display:flex;flex-direction:column;gap:2px}.metadata-item-empty{font-size:12px;color:#71717a;margin:0;padding:4px 0}.metadata-content{display:flex;flex-direction:column;gap:2px;min-width:0}.metadata-content .metadata-label{font-size:10px;color:#71717a}.metadata-content .metadata-value{font-size:12px;color:var(--text-primary);word-break:break-all;line-height:1.3;cursor:pointer}.metadata-content .metadata-value.multiline{white-space:pre-wrap}.metadata-content .metadata-value.text-green{color:#22c55e}.metadata-content .metadata-value.text-red{color:#ef4444}.metadata-value-with-copy{display:flex;align-items:center;gap:8px}.metadata-value-with-copy .metadata-value{flex:1;min-width:0}.copy-button{display:inline-flex;align-items:center;justify-content:center;padding:4px;background:transparent;border:1px solid var(--border-color, #3f3f46);border-radius:4px;color:var(--text-secondary, #a1a1aa);cursor:pointer;transition:all .15s ease;flex-shrink:0}.copy-button:hover{background:var(--bg-hover, #27272a);color:var(--text-primary, #f4f4f5);border-color:var(--border-hover, #52525b)}.copy-button:active{transform:scale(.95)}@media (max-width: 1024px){.metadata-sidebar{width:320px;min-width:320px;padding:10px}}@media (max-width: 768px){.content-wrapper{flex-direction:column;height:auto}.chat-container{height:auto;min-height:50vh}.metadata-sidebar{width:100%;min-width:100%;height:auto;max-height:none;border-right:none;border-top:1px solid var(--border-color);padding:12px;gap:12px}.metadata-section{flex-direction:row;flex-wrap:wrap;gap:12px}.metadata-section-title{width:100%;border-bottom:none;padding-bottom:0}.metadata-item{flex:1;min-width:140px}.metadata-section-small{margin-top:0;padding-top:0;border-top:none}}.modal-overlay{position:fixed;inset:0;z-index:1000;background-color:#0009;display:flex;align-items:center;justify-content:center;padding:24px}.modal-container{background-color:var(--bg-secondary);border:1px solid var(--border-color);border-radius:12px;width:100%;max-width:800px;max-height:80vh;display:flex;flex-direction:column;box-shadow:0 25px 50px -12px #00000080}.modal-header{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--border-color);flex-shrink:0}.modal-title{font-size:13px;color:var(--text-secondary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.modal-close{background:none;border:none;color:var(--text-secondary);cursor:pointer;font-size:16px;padding:4px 8px;border-radius:6px;line-height:1;transition:background-color .15s,color .15s}.modal-close:hover{background-color:var(--border-color);color:var(--text-primary)}.modal-content{margin:0;padding:16px;overflow:auto;font-size:13px;line-height:1.6;color:var(--text-primary);white-space:pre-wrap;word-break:break-word}\n    </style>\n  </head>\n  <body>\n    <div id="app"></div>\n\n    <script id="chat-data" type="application/json"></script>\n    <script>\n      (()=>{var m=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 141.38 140">\n  <path\n    fill="#000000"\n    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"\n  />\n</svg>\n`;var i=window.React,u=({state:e,onClose:t})=>(i.useEffect(()=>{if(e.visible){let a=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=a}}},[e.visible]),e.visible?i.createElement("div",{className:"modal-overlay",onClick:t},i.createElement("div",{className:"modal-container",onClick:a=>a.stopPropagation()},i.createElement("div",{className:"modal-header"},i.createElement("span",{className:"modal-title font-mono"},e.fileName),i.createElement("button",{className:"modal-close",onClick:t,"aria-label":"Close"},"\\u2715")),i.createElement("pre",{className:"modal-content"},e.content))):null),b=()=>{let[e,t]=i.useState({visible:!1,content:"",fileName:""}),a=i.useCallback((r,s="temp")=>{t({visible:!0,content:r,fileName:s})},[]),l=i.useCallback(()=>{t(r=>({...r,visible:!1}))},[]);return{modalState:e,openModal:a,closeModal:l}};var P=window.React,h=()=>{let{modalState:e,openModal:t,closeModal:a}=b();return{platformContext:P.useMemo(()=>({platform:"web",postMessage:r=>{console.log("Posted message:",r)},onMessage:r=>(window.addEventListener("message",r),()=>window.removeEventListener("message",r)),openFile:r=>{console.log("Opening file:",r)},openTempFile:t,getResourceUrl:()=>{},features:{canOpenFile:!1,canOpenTempFile:!0,canCopy:!0}}),[t]),modalState:e,closeModal:a}};var o=({label:e,value:t,valueClass:a})=>t==null||t===""?null:React.createElement("div",{className:"metadata-item"},React.createElement("div",{className:"metadata-content"},React.createElement("span",{className:"metadata-label"},e),React.createElement("span",{className:`metadata-value ${a||""}`,title:typeof t=="string"?t:void 0},t)));var v=e=>!!e&&typeof e=="object",w=()=>{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),{}}};var y=e=>{if(!e)return"-";try{return new Date(e).toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch(t){return e}},M=e=>{if(!e)return"-";try{let a=new Date(e).getTime();if(Number.isNaN(a))return"-";let r=Math.max(0,new Date().getTime()-a),s=Math.floor(r/1e3),d=Math.floor(s/60),c=Math.floor(d/60),p=Math.floor(c/24),f=Math.floor(p/7),x=Math.floor(p/30),g=Math.floor(p/365);return s<60?"just now":d<60?`${d} minute${d===1?"":"s"} ago`:c<24?`${c} hour${c===1?"":"s"} ago`:p<7?`${p} day${p===1?"":"s"} ago`:f<4?`${f} week${f===1?"":"s"} ago`:x<12?`${x} month${x===1?"":"s"} ago`:`${g} year${g===1?"":"s"} ago`}catch(t){return"-"}};var k=e=>{if(e!=null)return e>=1e6?`${(e/1e6).toFixed(e%1e6===0?0:1)}m`:e>=1e3?`${(e/1e3).toFixed(e%1e3===0?0:1)}k`:e.toString()};var C=({metadata:e})=>React.createElement("aside",{className:"metadata-sidebar"},React.createElement("div",{className:"metadata-section"},React.createElement("h3",{className:"metadata-section-title"},"Session Info"),React.createElement(o,{label:"Session created",value:M(e.startTime)}),React.createElement(o,{label:"Project",value:e.cwd,valueClass:"multiline"}),e.gitRepo&&React.createElement(o,{label:"Repository",value:e.gitRepo}),e.gitBranch&&React.createElement(o,{label:"Branch",value:e.gitBranch}),e.model&&React.createElement(o,{label:"Model",value:e.model}),e.channel&&React.createElement(o,{label:"Channel",value:e.channel})),React.createElement("div",{className:"metadata-section"},React.createElement("h3",{className:"metadata-section-title"},"Statistics"),React.createElement(o,{label:"Prompts",value:e.promptCount}),e.contextUsagePercent!==void 0&&e.contextWindowSize!==void 0&&React.createElement(o,{label:"Context",value:`${e.contextUsagePercent>100?">100":e.contextUsagePercent}% of ${k(e.contextWindowSize)}`,valueClass:e.contextUsagePercent>100?"text-red":void 0}),e.totalTokens!==void 0&&React.createElement(o,{label:"Tokens",value:e.totalTokens.toLocaleString()})),React.createElement("div",{className:"metadata-section"},React.createElement("h3",{className:"metadata-section-title"},"File Operations"),e.filesWritten!==void 0&&e.filesWritten>0&&React.createElement(o,{label:"Files modified",value:e.filesWritten}),e.linesAdded!==void 0&&e.linesAdded>0&&React.createElement(o,{label:"Added",value:`+${e.linesAdded}`,valueClass:"text-green"}),e.linesRemoved!==void 0&&e.linesRemoved>0&&React.createElement(o,{label:"Removed",value:`-${e.linesRemoved}`,valueClass:"text-red"}),(e.filesWritten===void 0||e.filesWritten===0)&&(e.linesAdded===void 0||e.linesAdded===0)&&(e.linesRemoved===void 0||e.linesRemoved===0)&&React.createElement("p",{className:"metadata-item metadata-item-empty"},"No file changes")),React.createElement("div",{className:"metadata-section metadata-section-small"},React.createElement(o,{label:"Session ID",value:e.sessionId,valueClass:"font-mono"}),React.createElement(o,{label:"Export Time",value:y(e.exportTime)})));var z=window.ReactDOM,n=window.React,{ChatViewer:$,PlatformProvider:D}=QwenCodeWebUI,T=m?m.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)"\'):m,j=()=>{let e=w(),a=(Array.isArray(e.messages)?e.messages:[]).filter(v).filter(c=>c.type!=="system"),l=e.metadata,{platformContext:r,modalState:s,closeModal:d}=h();return n.createElement("div",{className:"page-wrapper"},n.createElement("header",{className:"header"},n.createElement("div",{className:"header-left"},n.createElement("div",{className:"logo-icon","aria-hidden":"true",dangerouslySetInnerHTML:{__html:T}}),n.createElement("div",{className:"logo"},n.createElement("div",{className:"logo-text","data-text":"QWEN"},n.createElement("span",{className:"logo-text-inner"},"QWEN"))))),n.createElement("div",{className:"content-wrapper"},n.createElement("div",{className:"chat-container"},n.createElement(D,{value:r},n.createElement($,{messages:a,autoScroll:!1,theme:"dark"}))),l&&n.createElement(C,{metadata:l})),n.createElement(u,{state:s,onClose:d}))},N=document.getElementById("app");N?z.createRoot(N).render(n.createElement(j,null)):console.error("App container not found.");})();;\n    </script>\n  </body>\n</html>\n';

// packages/cli/src/ui/utils/export/formatters/html.ts
function escapeJsonForHtml(json3) {
  return json3.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 = [];
  const sourceMetadata = sessionData.metadata;
  const metadata2 = {
    type: "session_metadata",
    sessionId: sessionData.sessionId,
    startTime: sessionData.startTime
  };
  if (sourceMetadata?.exportTime) {
    metadata2["exportTime"] = sourceMetadata.exportTime;
  }
  if (sourceMetadata?.cwd) {
    metadata2["cwd"] = sourceMetadata.cwd;
  }
  if (sourceMetadata?.gitRepo) {
    metadata2["gitRepo"] = sourceMetadata.gitRepo;
  }
  if (sourceMetadata?.gitBranch) {
    metadata2["gitBranch"] = sourceMetadata.gitBranch;
  }
  if (sourceMetadata?.model) {
    metadata2["model"] = sourceMetadata.model;
  }
  if (sourceMetadata?.channel) {
    metadata2["channel"] = sourceMetadata.channel;
  }
  if (sourceMetadata?.promptCount !== void 0) {
    metadata2["promptCount"] = sourceMetadata.promptCount;
  }
  if (sourceMetadata?.contextUsagePercent !== void 0) {
    metadata2["contextUsagePercent"] = sourceMetadata.contextUsagePercent;
  }
  if (sourceMetadata?.contextWindowSize !== void 0) {
    metadata2["contextWindowSize"] = sourceMetadata.contextWindowSize;
  }
  if (sourceMetadata?.totalTokens !== void 0) {
    metadata2["totalTokens"] = sourceMetadata.totalTokens;
  }
  if (sourceMetadata?.filesWritten !== void 0) {
    metadata2["filesWritten"] = sourceMetadata.filesWritten;
  }
  if (sourceMetadata?.linesAdded !== void 0) {
    metadata2["linesAdded"] = sourceMetadata.linesAdded;
  }
  if (sourceMetadata?.linesRemoved !== void 0) {
    metadata2["linesRemoved"] = sourceMetadata.linesRemoved;
  }
  if (sourceMetadata?.uniqueFiles && sourceMetadata.uniqueFiles.length > 0) {
    metadata2["uniqueFiles"] = sourceMetadata.uniqueFiles;
  }
  lines.push(JSON.stringify(metadata2));
  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
init_i18n();
async function exportMarkdownAction(context2) {
  const { services } = context2;
  const { config: config2 } = services;
  if (!config2) {
    return {
      type: "message",
      messageType: "error",
      content: "Configuration not available."
    };
  }
  const cwd6 = config2.getWorkingDir() || config2.getProjectRoot();
  if (!cwd6) {
    return {
      type: "message",
      messageType: "error",
      content: "Could not determine current working directory."
    };
  }
  try {
    const sessionService = new SessionService(cwd6);
    const sessionId = config2.getSessionId();
    const sessionData = await sessionService.loadSession(sessionId);
    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 = path114.join(cwd6, filename);
    await fs113.writeFile(filepath, markdown2, "utf-8");
    return {
      type: "message",
      messageType: "info",
      content: `Session exported to markdown: ${filename}`
    };
  } catch (error40) {
    return {
      type: "message",
      messageType: "error",
      content: `Failed to export session: ${error40 instanceof Error ? error40.message : String(error40)}`
    };
  }
}
__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 cwd6 = config2.getWorkingDir() || config2.getProjectRoot();
  if (!cwd6) {
    return {
      type: "message",
      messageType: "error",
      content: "Could not determine current working directory."
    };
  }
  try {
    const sessionService = new SessionService(cwd6);
    const sessionId = config2.getSessionId();
    const sessionData = await sessionService.loadSession(sessionId);
    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 = path114.join(cwd6, filename);
    await fs113.writeFile(filepath, html2, "utf-8");
    return {
      type: "message",
      messageType: "info",
      content: `Session exported to HTML: ${filename}`
    };
  } catch (error40) {
    return {
      type: "message",
      messageType: "error",
      content: `Failed to export session: ${error40 instanceof Error ? error40.message : String(error40)}`
    };
  }
}
__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 cwd6 = config2.getWorkingDir() || config2.getProjectRoot();
  if (!cwd6) {
    return {
      type: "message",
      messageType: "error",
      content: "Could not determine current working directory."
    };
  }
  try {
    const sessionService = new SessionService(cwd6);
    const sessionId = config2.getSessionId();
    const sessionData = await sessionService.loadSession(sessionId);
    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 json3 = toJson(normalizedData);
    const filename = generateExportFilename("json");
    const filepath = path114.join(cwd6, filename);
    await fs113.writeFile(filepath, json3, "utf-8");
    return {
      type: "message",
      messageType: "info",
      content: `Session exported to JSON: ${filename}`
    };
  } catch (error40) {
    return {
      type: "message",
      messageType: "error",
      content: `Failed to export session: ${error40 instanceof Error ? error40.message : String(error40)}`
    };
  }
}
__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 cwd6 = config2.getWorkingDir() || config2.getProjectRoot();
  if (!cwd6) {
    return {
      type: "message",
      messageType: "error",
      content: "Could not determine current working directory."
    };
  }
  try {
    const sessionService = new SessionService(cwd6);
    const sessionId = config2.getSessionId();
    const sessionData = await sessionService.loadSession(sessionId);
    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 = path114.join(cwd6, filename);
    await fs113.writeFile(filepath, jsonl, "utf-8");
    return {
      type: "message",
      messageType: "info",
      content: `Session exported to JSONL: ${filename}`
    };
  } catch (error40) {
    return {
      type: "message",
      messageType: "error",
      content: `Failed to export session: ${error40 instanceof Error ? error40.message : String(error40)}`
    };
  }
}
__name(exportJsonlAction, "exportJsonlAction");
var exportCommand = {
  name: "export",
  get description() {
    return t4("Export current session message history to a file");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: exportHtmlAction,
  subCommands: [
    {
      name: "html",
      get description() {
        return t4("Export session to HTML format");
      },
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive", "non_interactive", "acp"],
      action: exportHtmlAction
    },
    {
      name: "md",
      get description() {
        return t4("Export session to markdown format");
      },
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive", "non_interactive", "acp"],
      action: exportMarkdownAction
    },
    {
      name: "json",
      get description() {
        return t4("Export session to JSON format");
      },
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive", "non_interactive", "acp"],
      action: exportJsonAction
    },
    {
      name: "jsonl",
      get description() {
        return t4("Export session to JSONL format (one message per line)");
      },
      kind: "built-in" /* BUILT_IN */,
      supportedModes: ["interactive", "non_interactive", "acp"],
      action: exportJsonlAction
    }
  ]
};

// packages/cli/src/ui/commands/extensionsCommand.ts
init_esbuild_shims();
init_types22();
init_types21();
init_i18n();
init_dist4();
init_open();
var debugLogger115 = createDebugLogger("EXTENSIONS_COMMAND");
var EXTENSION_EXPLORE_URL = {
  Gemini: "https://geminicli.com/extensions/",
  ClaudeCode: "https://claudemarketplaces.com/"
};
async function exploreAction(context2, args2) {
  const source2 = args2.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(_context, _args) {
  return {
    type: "dialog",
    dialog: "extensions_manage"
  };
}
__name(listAction, "listAction");
async function installAction(context2, args2) {
  const extensionManager = context2.services.config?.getExtensionManager();
  if (!(extensionManager instanceof ExtensionManager)) {
    debugLogger115.error(
      `Cannot ${context2.invocation?.name} extensions in this environment`
    );
    return;
  }
  const source2 = args2.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 (error40) {
    context2.ui.addItem(
      {
        type: "error" /* ERROR */,
        text: t4('Failed to install extension from "{{source}}": {{error}}', {
          source: source2,
          error: getErrorMessage4(error40)
        })
      },
      Date.now()
    );
    return;
  }
}
__name(installAction, "installAction");
async function completeExtensionsExplore(context2, partialArg) {
  const suggestions = Object.keys(EXTENSION_EXPLORE_URL).filter(
    (name4) => name4.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 */,
  supportedModes: ["interactive"],
  action: exploreAction,
  completion: completeExtensionsExplore
};
var manageExtensionsCommand = {
  name: "manage",
  get description() {
    return t4("Manage installed extensions");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: listAction
};
var installCommand2 = {
  name: "install",
  get description() {
    return t4("Install an extension from a git repo or local path");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: installAction
};
var extensionsCommand2 = {
  name: "extensions",
  get description() {
    return t4("Manage extensions");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  subCommands: [
    manageExtensionsCommand,
    installCommand2,
    exploreExtensionsCommand
  ],
  action: /* @__PURE__ */ __name(async (context2, args2) => (
    // Default to list if no subcommand is provided
    manageExtensionsCommand.action(context2, args2)
  ), "action")
};

// packages/cli/src/ui/commands/helpCommand.ts
init_esbuild_shims();
init_types21();
init_types22();
init_i18n();
var helpCommand = {
  name: "help",
  altNames: ["?"],
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  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/hooksCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
function formatHookSource(source2) {
  switch (source2) {
    case "project":
      return t4("Project");
    case "user":
      return t4("User");
    case "system":
      return t4("System");
    case "extensions":
      return t4("Extension");
    case "session":
      return t4("Session (temporary)");
    default:
      return source2;
  }
}
__name(formatHookSource, "formatHookSource");
var listCommand4 = {
  name: "list",
  get description() {
    return t4("List all configured hooks");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(async (context2, _args) => {
    const { config: config2 } = context2.services;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config not loaded.")
      };
    }
    const hookSystem = config2.getHookSystem();
    if (!hookSystem) {
      return {
        type: "message",
        messageType: "info",
        content: t4(
          "Hooks are not enabled. Enable hooks in settings to use this feature."
        )
      };
    }
    const registry3 = hookSystem.getRegistry();
    const configHooks = registry3.getAllHooks();
    const sessionId = config2.getSessionId();
    const sessionHooksManager = hookSystem.getSessionHooksManager();
    const sessionHooks = sessionId ? sessionHooksManager.getAllSessionHooks(sessionId) : [];
    const totalHooks = configHooks.length + sessionHooks.length;
    if (totalHooks === 0) {
      return {
        type: "message",
        messageType: "info",
        content: t4(
          "No hooks configured. Add hooks in your settings.json file or invoke a skill with hooks."
        )
      };
    }
    const hooksByEvent = /* @__PURE__ */ new Map();
    for (const hook of configHooks) {
      const eventName = hook.eventName;
      if (!hooksByEvent.has(eventName)) {
        hooksByEvent.set(eventName, []);
      }
      hooksByEvent.get(eventName).push({ hook, isSession: false });
    }
    for (const hook of sessionHooks) {
      const eventName = hook.eventName;
      if (!hooksByEvent.has(eventName)) {
        hooksByEvent.set(eventName, []);
      }
      hooksByEvent.get(eventName).push({ hook, isSession: true });
    }
    let output = `**Configured Hooks (${totalHooks} total)**

`;
    for (const [eventName, hooks] of hooksByEvent) {
      output += `### ${eventName}
`;
      for (const { hook, isSession } of hooks) {
        let name4;
        let source2;
        let matcher;
        let config3;
        if (isSession) {
          const sessionHook = hook;
          config3 = sessionHook.config;
          name4 = config3.name || (config3.type === "command" ? config3.command : void 0) || (config3.type === "http" ? config3.url : void 0) || "unnamed";
          source2 = formatHookSource("session");
          matcher = sessionHook.matcher ? ` (matcher: ${sessionHook.matcher})` : "";
        } else {
          const configHook = hook;
          config3 = configHook.config;
          name4 = config3.name || (config3.type === "command" ? config3.command : void 0) || (config3.type === "http" ? config3.url : void 0) || "unnamed";
          source2 = formatHookSource(configHook.source);
          matcher = configHook.matcher ? ` (matcher: ${configHook.matcher})` : "";
        }
        output += `- **${name4}** [${source2}]${matcher}
`;
      }
      output += "\n";
    }
    return {
      type: "message",
      messageType: "info",
      content: output
    };
  }, "action")
};
var hooksCommand2 = {
  name: "hooks",
  get description() {
    return t4("Manage Qwen Code hooks");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    const executionMode = context2.executionMode ?? "interactive";
    if (executionMode === "interactive") {
      return {
        type: "dialog",
        dialog: "hooks"
      };
    }
    const result = await listCommand4.action?.(context2, args2);
    return result ?? { type: "message", messageType: "info", content: "" };
  }, "action")
};

// packages/cli/src/ui/commands/ideCommand.ts
init_esbuild_shims();
init_dist4();
init_dist4();
init_types21();
import path115 from "node:path";
init_i18n();
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 file2 of openFiles) {
    const basename34 = path115.basename(file2.path);
    basenameCounts.set(basename34, (basenameCounts.get(basename34) || 0) + 1);
  }
  const fileList = openFiles.map((file2) => {
    const basename34 = path115.basename(file2.path);
    const isDuplicate = (basenameCounts.get(basename34) || 0) > 1;
    const parentDir = path115.basename(path115.dirname(file2.path));
    const displayName = isDuplicate ? `${basename34} (/${parentDir})` : basename34;
    return `  - ${displayName}${file2.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 */,
      supportedModes: ["interactive"],
      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 */,
    supportedModes: ["interactive"],
    subCommands: []
  };
  const statusCommand3 = {
    name: "status",
    get description() {
      return t4("check status of IDE integration");
    },
    kind: "built-in" /* BUILT_IN */,
    supportedModes: ["interactive"],
    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 */,
    supportedModes: ["interactive"],
    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 i4 = 0; i4 < 10; i4++) {
          await setIdeModeAndSyncConnection(context2.services.config, true);
          if (ideClient.getConnectionStatus().status === IDEConnectionStatus.Connected) {
            break;
          }
          await new Promise((resolve42) => setTimeout(resolve42, 500));
        }
        const { messageType, content } = getIdeStatusMessage(ideClient);
        if (messageType === "error") {
          context2.ui.addItem(
            {
              type: messageType,
              text: `Failed to automatically enable IDE integration. To fix this, run the CLI in a new terminal window.`
            },
            Date.now()
          );
        } else {
          context2.ui.addItem(
            {
              type: messageType,
              text: content
            },
            Date.now()
          );
        }
      }
    }, "action")
  };
  const enableCommand2 = {
    name: "enable",
    get description() {
      return t4("enable IDE integration");
    },
    kind: "built-in" /* BUILT_IN */,
    supportedModes: ["interactive"],
    action: /* @__PURE__ */ __name(async (context2) => {
      context2.services.settings.setValue(
        "User" /* User */,
        "ide.enabled",
        true
      );
      await setIdeModeAndSyncConnection(context2.services.config, true);
      const { messageType, content } = getIdeStatusMessage(ideClient);
      context2.ui.addItem(
        {
          type: messageType,
          text: content
        },
        Date.now()
      );
    }, "action")
  };
  const disableCommand2 = {
    name: "disable",
    get description() {
      return t4("disable IDE integration");
    },
    kind: "built-in" /* BUILT_IN */,
    supportedModes: ["interactive"],
    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 = [statusCommand3, disableCommand2];
  } else {
    ideSlashCommand.subCommands = [
      enableCommand2,
      statusCommand3,
      installCommand3
    ];
  }
  return ideSlashCommand;
}, "ideCommand");

// packages/cli/src/services/BuiltinCommandLoader.ts
init_dist4();

// packages/cli/src/ui/commands/initCommand.ts
init_esbuild_shims();
init_dist4();
init_types21();
import * as fs114 from "node:fs";
import * as path116 from "node:path";
var import_react27 = __toESM(require_react(), 1);
init_i18n();
var initCommand = {
  name: "init",
  get description() {
    return t4("Analyzes the project and creates a tailored QWEN.md file.");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  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 = path116.join(targetDir, contextFileName);
    try {
      if (fs114.existsSync(contextFilePath)) {
        try {
          const existing = fs114.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 {
        fs114.writeFileSync(contextFilePath, "", "utf8");
        context2.ui.addItem(
          {
            type: "info",
            text: `Empty ${contextFileName} created. Now analyzing the project to populate it.`
          },
          Date.now()
        );
      } catch (err2) {
        return {
          type: "message",
          messageType: "error",
          content: `Failed to create ${contextFileName}: ${err2 instanceof Error ? err2.message : String(err2)}`
        };
      }
    } catch (error40) {
      return {
        type: "message",
        messageType: "error",
        content: `Unexpected error preparing ${contextFileName}: ${error40 instanceof Error ? error40.message : String(error40)}`
      };
    }
    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();
init_types21();
init_i18n();
init_languages();
init_dist4();
var debugLogger116 = 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 (error40) {
      debugLogger116.warn("Failed to save language setting:", error40);
    }
  }
  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 (error40) {
        debugLogger116.warn("Failed to save output language setting:", error40);
      }
    }
    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 (error40) {
    return {
      type: "message",
      messageType: "error",
      content: t4(
        "Failed to generate LLM output language rule file: {{error}}",
        {
          error: error40 instanceof Error ? error40.message : String(error40)
        }
      )
    };
  }
}
__name(setOutputLanguage, "setOutputLanguage");
var languageCommand = {
  name: "language",
  get description() {
    return t4("View or change the language setting");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    if (!context2.services.config) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Configuration not available.")
      };
    }
    const trimmedArgs = args2.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 */,
      supportedModes: ["interactive", "non_interactive", "acp"],
      action: /* @__PURE__ */ __name(async (context2, args2) => {
        const trimmedArgs = args2.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 */,
          supportedModes: ["interactive", "non_interactive", "acp"],
          action: /* @__PURE__ */ __name(async (context2, args2) => {
            if (args2.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 */,
      supportedModes: ["interactive", "non_interactive", "acp"],
      action: /* @__PURE__ */ __name(async (context2, args2) => {
        const trimmedArgs = args2.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();
init_types21();
init_i18n();
var mcpCommand2 = {
  name: "mcp",
  get description() {
    return t4("Open MCP management dialog");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(async () => ({
    type: "dialog",
    dialog: "mcp"
  }), "action")
};

// packages/cli/src/ui/commands/dreamCommand.ts
init_esbuild_shims();
init_dist4();
init_i18n();
init_types21();
import * as path117 from "node:path";
var dreamCommand = {
  name: "dream",
  get description() {
    return t4("Consolidate managed auto-memory topic files.");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2) => {
    const config2 = context2.services.config;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config not loaded.")
      };
    }
    const projectRoot = config2.getProjectRoot();
    const memoryRoot = getAutoMemoryRoot(projectRoot);
    const transcriptDir = path117.join(
      new Storage(projectRoot).getProjectDir(),
      "chats"
    );
    const prompt = config2.getMemoryManager().buildConsolidationPrompt(memoryRoot, transcriptDir);
    return {
      type: "submit_prompt",
      content: prompt,
      onComplete: /* @__PURE__ */ __name(async () => {
        await config2.getMemoryManager().writeDreamManualRun(projectRoot, config2.getSessionId());
      }, "onComplete")
    };
  }, "action")
};

// packages/cli/src/ui/commands/forgetCommand.ts
init_esbuild_shims();
init_i18n();
init_types21();
var forgetCommand = {
  name: "forget",
  get description() {
    return t4("Remove matching entries from managed auto-memory.");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    const query = args2.trim();
    if (!query) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Usage: /forget <memory text to remove>")
      };
    }
    const config2 = context2.services.config;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config not loaded.")
      };
    }
    const selection = await config2.getMemoryManager().selectForgetCandidates(config2.getProjectRoot(), query, { config: config2 });
    const result = await config2.getMemoryManager().forgetMatches(config2.getProjectRoot(), selection.matches);
    return {
      type: "message",
      messageType: "info",
      content: result.systemMessage ?? t4("No managed auto-memory entries matched: {{query}}", { query })
    };
  }, "action")
};

// packages/cli/src/ui/commands/memoryCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var memoryCommand = {
  name: "memory",
  get description() {
    return t4("Open the memory manager.");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(async () => ({
    type: "dialog",
    dialog: "memory"
  }), "action")
};

// packages/cli/src/ui/commands/modelCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var modelCommand = {
  name: "model",
  completionPriority: 100,
  get description() {
    return t4("Switch the model for this session (--fast for suggestion model)");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  completion: /* @__PURE__ */ __name(async (_context, partialArg) => {
    if (partialArg && "--fast".startsWith(partialArg)) {
      return [
        {
          value: "--fast",
          description: t4(
            "Set a lighter model for prompt suggestions and speculative execution"
          )
        }
      ];
    }
    return null;
  }, "completion"),
  action: /* @__PURE__ */ __name(async (context2) => {
    const { services } = context2;
    const { config: config2, settings } = services;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Configuration not available.")
      };
    }
    const args2 = context2.invocation?.args?.trim() ?? "";
    if (args2.startsWith("--fast")) {
      const modelName = args2.replace("--fast", "").trim();
      if (!modelName) {
        if (context2.executionMode !== "interactive") {
          const fastModel = context2.services.settings?.merged?.fastModel ?? "not set";
          return {
            type: "message",
            messageType: "info",
            content: `Current fast model: ${fastModel}
Use "/model --fast <model-id>" to set fast model.`
          };
        }
        return {
          type: "dialog",
          dialog: "fast-model"
        };
      }
      if (!settings) {
        return {
          type: "message",
          messageType: "error",
          content: t4("Settings service not available.")
        };
      }
      settings.setValue(
        getPersistScopeForModelSelection(settings),
        "fastModel",
        modelName
      );
      config2.setFastModel(modelName);
      return {
        type: "message",
        messageType: "info",
        content: t4("Fast Model") + ": " + modelName
      };
    }
    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.")
      };
    }
    if (context2.executionMode !== "interactive") {
      const modelName = args2.trim();
      if (modelName) {
        if (!settings) {
          return {
            type: "message",
            messageType: "error",
            content: t4("Settings service not available.")
          };
        }
        settings.setValue(
          getPersistScopeForModelSelection(settings),
          "model.name",
          modelName
        );
        await config2.setModel(modelName);
        return {
          type: "message",
          messageType: "info",
          content: t4("Model") + ": " + modelName
        };
      }
      const currentModel = config2.getModel() ?? "unknown";
      return {
        type: "message",
        messageType: "info",
        content: `Current model: ${currentModel}
Use "/model <model-id>" to switch models or "/model --fast <model-id>" to set the fast model.`
      };
    }
    return {
      type: "dialog",
      dialog: "model"
    };
  }, "action")
};

// packages/cli/src/ui/commands/manageModelsCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var manageModelsCommand = {
  name: "manage-models",
  get description() {
    return t4(
      "Browse dynamic model catalogs and choose which models stay enabled locally"
    );
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(() => ({
    type: "dialog",
    dialog: "manage-models"
  }), "action")
};

// packages/cli/src/ui/commands/rememberCommand.ts
init_esbuild_shims();
init_dist4();
init_i18n();
init_types21();
var rememberCommand = {
  name: "remember",
  get description() {
    return t4("Save a durable memory to the memory system.");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name((context2, args2) => {
    const fact = args2.trim();
    if (!fact) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Usage: /remember <text to remember>")
      };
    }
    const config2 = context2.services.config;
    const useManagedMemory = config2?.getManagedAutoMemoryEnabled() ?? false;
    if (useManagedMemory) {
      const memoryDir = config2 ? getAutoMemoryRoot(config2.getProjectRoot()) : void 0;
      const dirHint = memoryDir ? ` Save it to \`${memoryDir}\`.` : "";
      return {
        type: "submit_prompt",
        content: `Please save the following to your memory system.${dirHint} Choose the most appropriate memory type (user, feedback, project, or reference) based on the content:

${fact}`
      };
    }
    return {
      type: "submit_prompt",
      content: `Please save the following fact to memory (e.g. append to QWEN.md in the project root):

${fact}`
    };
  }, "action")
};

// packages/cli/src/ui/commands/planCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
init_dist4();
var planCommand = {
  name: "plan",
  get description() {
    return t4("Switch to plan mode or exit plan mode");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    const { config: config2 } = context2.services;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Configuration is not available.")
      };
    }
    const trimmedArgs = args2.trim();
    const currentMode = config2.getApprovalMode();
    if (trimmedArgs === "exit") {
      if (currentMode !== ApprovalMode.PLAN) {
        return {
          type: "message",
          messageType: "error",
          content: t4('Not in plan mode. Use "/plan" to enter plan mode first.')
        };
      }
      try {
        config2.setApprovalMode(config2.getPrePlanMode());
      } catch (e4) {
        return {
          type: "message",
          messageType: "error",
          content: e4.message
        };
      }
      return {
        type: "message",
        messageType: "info",
        content: t4("Exited plan mode. Previous approval mode restored.")
      };
    }
    if (currentMode !== ApprovalMode.PLAN) {
      try {
        config2.setApprovalMode(ApprovalMode.PLAN);
      } catch (e4) {
        return {
          type: "message",
          messageType: "error",
          content: e4.message
        };
      }
      if (trimmedArgs) {
        return {
          type: "submit_prompt",
          content: [{ text: trimmedArgs }]
        };
      }
      return {
        type: "message",
        messageType: "info",
        content: t4(
          "Enabled plan mode. The agent will analyze and plan without executing tools."
        )
      };
    }
    if (trimmedArgs) {
      return {
        type: "submit_prompt",
        content: [{ text: trimmedArgs }]
      };
    }
    return {
      type: "message",
      messageType: "info",
      content: t4('Already in plan mode. Use "/plan exit" to exit plan mode.')
    };
  }, "action")
};

// packages/cli/src/ui/commands/permissionsCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var permissionsCommand = {
  name: "permissions",
  get description() {
    return t4("Manage permission rules");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(() => ({
    type: "dialog",
    dialog: "permissions"
  }), "action")
};

// packages/cli/src/ui/commands/trustCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var trustCommand = {
  name: "trust",
  get description() {
    return t4("Manage folder trust settings");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(() => ({
    type: "dialog",
    dialog: "trust"
  }), "action")
};

// packages/cli/src/ui/commands/quitCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var quitCommand = {
  name: "quit",
  altNames: ["exit"],
  get description() {
    return t4("exit the cli");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  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/recapCommand.ts
init_esbuild_shims();
init_types21();
init_dist4();
init_i18n();
var recapCommand = {
  name: "recap",
  kind: "built-in" /* BUILT_IN */,
  get description() {
    return t4("Generate a one-line session recap now");
  },
  action: /* @__PURE__ */ __name(async (context2) => {
    const { config: config2 } = context2.services;
    const abortSignal = context2.abortSignal ?? new AbortController().signal;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config not loaded.")
      };
    }
    if (context2.executionMode === "interactive") {
      const turnInFlight = !context2.ui.isIdleRef.current || context2.ui.pendingItem !== null;
      if (turnInFlight) {
        return {
          type: "message",
          messageType: "error",
          content: t4(
            "Cannot run /recap while another operation is in progress."
          )
        };
      }
    }
    const recap = await generateSessionRecap(config2, abortSignal);
    if (abortSignal.aborted) return;
    if (!recap) {
      return {
        type: "message",
        messageType: "info",
        content: t4("Not enough conversation context for a recap yet.")
      };
    }
    if (context2.executionMode === "interactive") {
      const item = {
        type: "away_recap",
        text: recap.text
      };
      context2.ui.addItem(item, Date.now());
      return;
    }
    return { type: "message", messageType: "info", content: recap.text };
  }, "action")
};

// packages/cli/src/ui/commands/renameCommand.ts
init_esbuild_shims();
init_dist4();
init_types21();
init_i18n();
var MAX_TITLE_LENGTH = SESSION_TITLE_MAX_LENGTH;
function extractConversationText(history) {
  const texts = [];
  for (let i4 = history.length - 1; i4 >= 0 && texts.length < 6; i4--) {
    const content = history[i4];
    const role = content.role === "user" ? "User" : "Assistant";
    for (const part of content.parts ?? []) {
      if ("text" in part && part.text) {
        texts.unshift(`${role}: ${part.text}`);
        break;
      }
    }
  }
  const joined = texts.join("\n");
  return joined.length > 1e3 ? joined.slice(-1e3) : joined;
}
__name(extractConversationText, "extractConversationText");
async function generateKebabTitle(config2, signal) {
  try {
    const history = config2.getGeminiClient().getHistory(true);
    const conversationText = extractConversationText(history);
    if (!conversationText) {
      return null;
    }
    const model = config2.getFastModel() ?? config2.getModel();
    const response = await config2.getContentGenerator().generateContent(
      {
        model,
        contents: [
          {
            role: "user",
            parts: [{ text: conversationText }]
          }
        ],
        config: {
          systemInstruction: {
            role: "user",
            parts: [
              {
                text: 'Generate a short kebab-case name (2-4 words) that captures the main topic of this conversation. Use lowercase words separated by hyphens. Examples: "fix-login-bug", "add-auth-feature", "refactor-api-client". Reply with ONLY the kebab-case name, nothing else.'
              }
            ]
          },
          abortSignal: signal
        }
      },
      "rename_generate_title"
    );
    const text = getResponseText(response)?.trim();
    if (!text) {
      return null;
    }
    const cleaned = stripTerminalControlSequences(text).split("\n")[0].replace(/["`']/g, "").trim();
    return cleaned.length > 0 && cleaned.length <= MAX_TITLE_LENGTH ? cleaned : null;
  } catch {
    return null;
  }
}
__name(generateKebabTitle, "generateKebabTitle");
function autoFailureMessage(reason) {
  switch (reason) {
    case "no_fast_model":
      return t4(
        "/rename --auto requires a fast model. Configure one with `/model --fast <model>`."
      );
    case "empty_history":
      return t4(
        "No conversation to title yet \u2014 send at least one message first."
      );
    case "empty_result":
      return t4(
        "The fast model returned no usable title. Try `/rename <name>` to set one yourself."
      );
    case "aborted":
      return t4("Title generation was cancelled.");
    case "model_error":
      return t4(
        "The fast model could not generate a title (rate limit, auth, or network error). Check debug log or try again."
      );
    case "no_client":
      return t4("Session is still initializing \u2014 try again in a moment.");
    default:
      return t4("Could not generate a title.");
  }
}
__name(autoFailureMessage, "autoFailureMessage");
function parseArgs(raw2) {
  const trimmed2 = raw2.trim().replace(/[\r\n]+/g, " ");
  if (!trimmed2) return { auto: false, positional: "" };
  const parts2 = trimmed2.split(/\s+/);
  let auto2 = false;
  let unknownFlag;
  let flagsDone = false;
  const rest = [];
  for (const p2 of parts2) {
    if (!flagsDone && p2 === "--") {
      flagsDone = true;
      continue;
    }
    if (!flagsDone && p2.startsWith("--")) {
      if (p2.toLowerCase() === "--auto") {
        auto2 = true;
        continue;
      }
      if (!unknownFlag) unknownFlag = p2;
      continue;
    }
    rest.push(p2);
  }
  return { auto: auto2, positional: rest.join(" "), unknownFlag };
}
__name(parseArgs, "parseArgs");
var renameCommand = {
  name: "rename",
  altNames: ["tag"],
  kind: "built-in" /* BUILT_IN */,
  get description() {
    return t4(
      "Rename the current conversation. --auto lets the fast model pick a title."
    );
  },
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    const { config: config2 } = context2.services;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config is not available.")
      };
    }
    const { auto: auto2, positional, unknownFlag } = parseArgs(args2);
    if (unknownFlag) {
      return {
        type: "message",
        messageType: "error",
        content: t4(
          'Unknown flag "{{flag}}". Supported: --auto. To use this as a literal name, run `/rename -- {{flag}}`.',
          { flag: unknownFlag }
        )
      };
    }
    let name4 = positional;
    let titleSource = "manual";
    if (auto2) {
      if (!config2.getFastModel()) {
        return {
          type: "message",
          messageType: "error",
          content: t4(
            "/rename --auto requires a fast model. Configure one with `/model --fast <model>`."
          )
        };
      }
      if (positional) {
        return {
          type: "message",
          messageType: "error",
          content: t4(
            "/rename --auto does not take a name. Use `/rename <name>` to set a name yourself."
          )
        };
      }
      const dots = [".", "..", "..."];
      let dotIndex = 0;
      const baseText = t4("Regenerating session title");
      context2.ui.setPendingItem({
        type: "info",
        text: baseText + dots[dotIndex]
      });
      const timer = setInterval(() => {
        dotIndex = (dotIndex + 1) % dots.length;
        context2.ui.setPendingItem({
          type: "info",
          text: baseText + dots[dotIndex]
        });
      }, 500);
      let outcome;
      try {
        outcome = await tryGenerateSessionTitle(
          config2,
          context2.abortSignal ?? new AbortController().signal
        );
      } finally {
        clearInterval(timer);
        context2.ui.setPendingItem(null);
      }
      if (!outcome.ok) {
        return {
          type: "message",
          messageType: "error",
          content: autoFailureMessage(outcome.reason)
        };
      }
      name4 = outcome.title;
      titleSource = "auto";
    } else if (!name4) {
      const dots = [".", "..", "..."];
      let dotIndex = 0;
      const baseText = t4("Generating session name");
      context2.ui.setPendingItem({
        type: "info",
        text: baseText + dots[dotIndex]
      });
      const timer = setInterval(() => {
        dotIndex = (dotIndex + 1) % dots.length;
        context2.ui.setPendingItem({
          type: "info",
          text: baseText + dots[dotIndex]
        });
      }, 500);
      let generated;
      try {
        generated = await generateKebabTitle(config2, context2.abortSignal);
      } finally {
        clearInterval(timer);
        context2.ui.setPendingItem(null);
      }
      if (!generated) {
        return {
          type: "message",
          messageType: "error",
          content: t4("Could not generate a title. Usage: /rename <name>")
        };
      }
      name4 = generated;
    }
    if (name4.length > MAX_TITLE_LENGTH) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Name is too long. Maximum {{max}} characters.", {
          max: String(MAX_TITLE_LENGTH)
        })
      };
    }
    const chatRecordingService = config2.getChatRecordingService();
    if (chatRecordingService) {
      const ok2 = chatRecordingService.recordCustomTitle(name4, titleSource);
      if (!ok2) {
        return {
          type: "message",
          messageType: "error",
          content: t4("Failed to rename session.")
        };
      }
    } else {
      const sessionId = config2.getSessionId();
      const sessionService = config2.getSessionService();
      const success2 = await sessionService.renameSession(
        sessionId,
        name4,
        titleSource
      );
      if (!success2) {
        return {
          type: "message",
          messageType: "error",
          content: t4("Failed to rename session.")
        };
      }
    }
    context2.ui.setSessionName(name4);
    return {
      type: "message",
      messageType: "info",
      content: t4('Session renamed to "{{name}}"', { name: name4 })
    };
  }, "action")
};

// packages/cli/src/ui/commands/restoreCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
import * as fs115 from "node:fs/promises";
import path118 from "node:path";
async function restoreAction(context2, args2) {
  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 fs115.mkdir(checkpointDir, { recursive: true });
    const files = await fs115.readdir(checkpointDir);
    const jsonFiles = files.filter((file2) => file2.endsWith(".json"));
    if (!args2) {
      if (jsonFiles.length === 0) {
        return {
          type: "message",
          messageType: "info",
          content: "No restorable tool calls found."
        };
      }
      const truncatedFiles = jsonFiles.map((file2) => {
        const components = file2.split(".");
        if (components.length <= 1) {
          return file2;
        }
        components.pop();
        return components.join(".");
      });
      const fileList = truncatedFiles.join("\n");
      return {
        type: "message",
        messageType: "info",
        content: `Available tool calls to restore:

${fileList}`
      };
    }
    const selectedFile = args2.endsWith(".json") ? args2 : `${args2}.json`;
    if (!jsonFiles.includes(selectedFile)) {
      return {
        type: "message",
        messageType: "error",
        content: `File not found: ${selectedFile}`
      };
    }
    const filePath = path118.join(checkpointDir, selectedFile);
    const data = await fs115.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 (error40) {
    return {
      type: "message",
      messageType: "error",
      content: `Could not read restorable tool calls. This is the error: ${error40}`
    };
  }
}
__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 fs115.readdir(checkpointDir);
    return files.filter((file2) => file2.endsWith(".json")).map((file2) => file2.replace(".json", ""));
  } catch (_err) {
    return [];
  }
}
__name(completion2, "completion");
var restoreCommand = /* @__PURE__ */ __name((config2) => {
  if (!config2?.getCheckpointingEnabled()) {
    return null;
  }
  return {
    name: "restore",
    get description() {
      return t4(
        "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 */,
    supportedModes: ["interactive"],
    action: restoreAction,
    completion: completion2
  };
}, "restoreCommand");

// packages/cli/src/ui/commands/resumeCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var resumeCommand = {
  name: "resume",
  altNames: ["continue"],
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  get description() {
    return t4("Resume a previous session");
  },
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    const arg = args2.trim();
    if (!arg) {
      return { type: "dialog", dialog: "resume" };
    }
    const { config: config2 } = context2.services;
    if (!config2) {
      return {
        type: "message",
        messageType: "error",
        content: t4("Config is not available.")
      };
    }
    if (isValidSessionId(arg)) {
      const sessionService2 = config2.getSessionService();
      const exists3 = await sessionService2.sessionExists(arg);
      if (exists3) {
        return { type: "dialog", dialog: "resume", sessionId: arg };
      }
      return {
        type: "message",
        messageType: "error",
        content: t4('No session found with ID "{{id}}".', { id: arg })
      };
    }
    const sessionService = config2.getSessionService();
    const matches2 = await sessionService.findSessionsByTitle(arg);
    if (matches2.length === 1) {
      return {
        type: "dialog",
        dialog: "resume",
        sessionId: matches2[0].sessionId
      };
    }
    if (matches2.length > 1) {
      return { type: "dialog", dialog: "resume", matchedSessions: matches2 };
    }
    return {
      type: "message",
      messageType: "error",
      content: t4('No session found with title "{{title}}".', { title: arg })
    };
  }, "action")
};

// packages/cli/src/ui/commands/rewindCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var rewindCommand = {
  name: "rewind",
  altNames: ["rollback"],
  get description() {
    return t4("Rewind conversation to a previous turn");
  },
  kind: "built-in" /* BUILT_IN */,
  action: /* @__PURE__ */ __name(async () => ({
    type: "dialog",
    dialog: "rewind"
  }), "action")
};

// packages/cli/src/ui/commands/settingsCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var settingsCommand2 = {
  name: "settings",
  get description() {
    return t4("View and edit Qwen Code settings");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name((_context, _args) => ({
    type: "dialog",
    dialog: "settings"
  }), "action")
};

// packages/cli/src/ui/commands/skillsCommand.ts
init_esbuild_shims();
init_types21();
init_types22();
init_i18n();
init_fzf_es();
init_dist4();
var debugLogger117 = createDebugLogger("SKILLS_COMMAND");
var skillsCommand = {
  name: "skills",
  get description() {
    return t4("List available skills.");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "acp"],
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    const rawArgs = args2?.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 matches2 = await getSkillMatches(skills, normalizedPartial);
    return matches2.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 (error40) {
    debugLogger117.error("[skillsCommand] Fuzzy match failed:", error40);
    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();
init_types22();
init_types21();
init_i18n();
var statsCommand = {
  name: "stats",
  altNames: ["usage"],
  get description() {
    return t4("check session stats. Usage: /stats [model|tools]");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: /* @__PURE__ */ __name((context2) => {
    const now = /* @__PURE__ */ new Date();
    const { sessionStartTime } = context2.session.stats;
    if (!sessionStartTime) {
      if (context2.executionMode !== "interactive") {
        return {
          type: "message",
          messageType: "error",
          content: t4(
            "Session start time is unavailable, cannot calculate stats."
          )
        };
      }
      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();
    if (context2.executionMode !== "interactive") {
      const { promptCount, metrics: metrics2 } = context2.session.stats;
      let totalPromptTokens = 0;
      let totalCandidateTokens = 0;
      let totalRequests = 0;
      for (const modelMetrics of Object.values(metrics2.models)) {
        totalPromptTokens += modelMetrics.tokens.prompt;
        totalCandidateTokens += modelMetrics.tokens.candidates;
        totalRequests += modelMetrics.api.totalRequests;
      }
      return {
        type: "message",
        messageType: "info",
        content: [
          `Session duration: ${formatDuration(wallDuration)}`,
          `Prompts: ${promptCount}`,
          `API requests: ${totalRequests}`,
          `Tokens \u2014 prompt: ${totalPromptTokens}, output: ${totalCandidateTokens}`,
          `Tool calls: ${metrics2.tools.totalCalls} (${metrics2.tools.totalSuccess} ok, ${metrics2.tools.totalFail} fail)`,
          `Files: +${metrics2.files.totalLinesAdded} / -${metrics2.files.totalLinesRemoved} lines`
        ].join("\n")
      };
    }
    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 */,
      supportedModes: ["interactive", "non_interactive", "acp"],
      action: /* @__PURE__ */ __name((context2) => {
        if (context2.executionMode !== "interactive") {
          const { metrics: metrics2 } = context2.session.stats;
          const lines = [];
          for (const [modelName, modelMetrics] of Object.entries(
            metrics2.models
          )) {
            lines.push(
              `${modelName}: prompt=${modelMetrics.tokens.prompt}, output=${modelMetrics.tokens.candidates}, cached=${modelMetrics.tokens.cached}`
            );
          }
          if (lines.length === 0) {
            lines.push("No model usage data yet.");
          }
          return {
            type: "message",
            messageType: "info",
            content: lines.join("\n")
          };
        }
        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 */,
      supportedModes: ["interactive", "non_interactive", "acp"],
      action: /* @__PURE__ */ __name((context2) => {
        if (context2.executionMode !== "interactive") {
          const { metrics: metrics2 } = context2.session.stats;
          const { tools } = metrics2;
          const toolNames = Object.keys(tools.byName);
          const content = toolNames.length > 0 ? [
            `Tool calls: ${tools.totalCalls} total (${tools.totalSuccess} ok, ${tools.totalFail} fail)`,
            ...toolNames.map((name4) => `  ${name4}`)
          ].join("\n") : "No tool usage data yet.";
          return { type: "message", messageType: "info", content };
        }
        context2.ui.addItem(
          {
            type: "tool_stats" /* TOOL_STATS */
          },
          Date.now()
        );
      }, "action")
    }
  ]
};

// packages/cli/src/ui/commands/summaryCommand.ts
init_esbuild_shims();
init_types21();
init_dist4();
init_i18n();
import * as fsPromises5 from "fs/promises";
import path119 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 */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  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 parts2 = response.candidates?.[0]?.content?.parts;
      const markdownSummary = parts2?.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 = path119.join(projectRoot, ".qwen");
      try {
        await fsPromises5.mkdir(qwenDir, { recursive: true });
      } catch (_err) {
      }
      const summaryPath = path119.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((error40) => t4("Failed to generate project context summary: {{error}}", {
      error: error40 instanceof Error ? error40.message : String(error40)
    }), "formatErrorMessage");
    const failInteractive = /* @__PURE__ */ __name((error40) => {
      if (executionMode !== "interactive") {
        return;
      }
      if (abortSignal?.aborted) {
        return;
      }
      ui2.setPendingItem(null);
      ui2.addItem(
        {
          type: "error",
          text: `\u274C ${formatErrorMessage(error40)}`
        },
        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 (error40) {
          failInteractive(error40);
          yield {
            messageType: "error",
            content: formatErrorMessage(error40)
          };
        }
      }, "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 (error40) {
      failInteractive(error40);
      return {
        type: "message",
        messageType: "error",
        content: formatErrorMessage(error40)
      };
    }
  }, "action")
};

// packages/cli/src/ui/commands/terminalSetupCommand.ts
init_esbuild_shims();
init_types21();

// packages/cli/src/ui/utils/terminalSetup.ts
init_esbuild_shims();
import { promises as fs116 } from "node:fs";
import * as os44 from "node:os";
import * as path120 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((resolve42) => {
    if (!process.stdin.isTTY || !process.stdout.isTTY) {
      detectionComplete = true;
      resolve42(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);
      const drainHandler = /* @__PURE__ */ __name(() => {
      }, "drainHandler");
      process.stdin.on("data", drainHandler);
      setTimeout(() => {
        process.stdin.removeListener("data", drainHandler);
        if (!originalRawMode) {
          process.stdin.setRawMode(false);
        }
        detectionComplete = true;
        resolve42(false);
      }, 100);
    }, "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);
          process.on("SIGINT", disableProtocol);
        }
        detectionComplete = true;
        resolve42(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 disableKittyProtocol() {
  disableProtocol();
}
__name(disableKittyProtocol, "disableKittyProtocol");
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
init_i18n();
init_dist4();
var debugLogger118 = createDebugLogger("TERMINAL_SETUP");
var execAsync2 = promisify9(exec3);
function stripJsonComments4(content) {
  return content.replace(/^\s*\/\/.*$/gm, "");
}
__name(stripJsonComments4, "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 (os44.platform() !== "win32") {
    try {
      const { stdout: stdout2 } = await execAsync2("ps -o comm= -p $PPID");
      const parentName = stdout2.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 (error40) {
      debugLogger118.debug("Parent process detection failed:", error40);
    }
  }
  return null;
}
__name(detectTerminal, "detectTerminal");
async function backupFile(filePath) {
  try {
    const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
    const backupPath = `${filePath}.backup.${timestamp}`;
    await fs116.copyFile(filePath, backupPath);
  } catch (error40) {
    debugLogger118.warn(`Failed to create backup of ${filePath}:`, error40);
  }
}
__name(backupFile, "backupFile");
function getVSCodeStyleConfigDir(appName) {
  const platform15 = os44.platform();
  if (platform15 === "darwin") {
    return path120.join(
      os44.homedir(),
      "Library",
      "Application Support",
      appName,
      "User"
    );
  } else if (platform15 === "win32") {
    if (!process.env["APPDATA"]) {
      return null;
    }
    return path120.join(process.env["APPDATA"], appName, "User");
  } else {
    return path120.join(os44.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 = path120.join(configDir, "keybindings.json");
  try {
    await fs116.mkdir(configDir, { recursive: true });
    let keybindings = [];
    try {
      const content = await fs116.readFile(keybindingsFile, "utf8");
      await backupFile(keybindingsFile);
      try {
        const cleanContent = stripJsonComments4(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 fs116.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 (error40) {
    return {
      success: false,
      message: t4("Failed to configure {{terminalName}}.", { terminalName }) + "\n" + t4("File: {{file}}", { file: keybindingsFile }) + "\n" + t4("Error: {{error}}", { error: String(error40) })
    };
  }
}
__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
init_i18n();
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 */,
  supportedModes: ["interactive"],
  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 (error40) {
      return {
        type: "message",
        content: t4("Failed to configure terminal: {{error}}", {
          error: String(error40)
        }),
        messageType: "error"
      };
    }
  }, "action")
};

// packages/cli/src/ui/commands/themeCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var themeCommand = {
  name: "theme",
  get description() {
    return t4("change the theme");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name((_context, _args) => ({
    type: "dialog",
    dialog: "theme"
  }), "action")
};

// packages/cli/src/ui/commands/toolsCommand.ts
init_esbuild_shims();
init_types21();
init_types22();
init_i18n();
var toolsCommand = {
  name: "tools",
  get description() {
    return t4("list available Qwen Code tools. Usage: /tools [desc]");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name(async (context2, args2) => {
    const subCommand = args2?.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();
init_types21();
init_i18n();
var vimCommand = {
  name: "vim",
  get description() {
    return t4("toggle vim mode on/off");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  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 path121 from "node:path";
import * as fs117 from "node:fs";
import { Writable as Writable2 } from "node:stream";

// packages/cli/src/utils/gitUtils.ts
init_esbuild_shims();
var import_undici5 = __toESM(require_undici2(), 1);
init_dist4();
import { execSync as execSync8 } from "node:child_process";
var debugLogger119 = createDebugLogger("GIT");
var isGitHubRepository = /* @__PURE__ */ __name(() => {
  try {
    const remotes = (execSync8("git remote -v", {
      encoding: "utf-8"
    }) || "").trim();
    const pattern = /github\.com/;
    return pattern.test(remotes);
  } catch (_error) {
    debugLogger119.debug(`Failed to get git remote:`, _error);
    return false;
  }
}, "isGitHubRepository");
var getGitRepoRoot = /* @__PURE__ */ __name(() => {
  const gitRepoRoot = (execSync8("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 (proxy2) => {
  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: proxy2 ? new import_undici5.ProxyAgent(proxy2) : 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) {
    debugLogger119.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 = execSync8("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 parts2 = parsedUrl.pathname.split("/").filter((part) => part !== "");
  if (parts2.length !== 2 || !parts2[0] || !parts2[1]) {
    throw new Error(
      `Owner & repo could not be extracted from remote URL: ${remoteUrl}`
    );
  }
  return { owner: parts2[0], repo: parts2[1].replace(/\.git$/, "") };
}
__name(getGitHubRepoInfo, "getGitHubRepoInfo");

// packages/cli/src/ui/commands/setupGithubCommand.ts
init_types21();
init_i18n();
init_dist4();
var debugLogger120 = 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((url3) => `${openCmd} "${url3}"`);
  return commands;
}
__name(getOpenUrlsCommands, "getOpenUrlsCommands");
async function updateGitignore(gitRepoRoot) {
  const gitignoreEntries = [".qwen/", "gha-creds-*.json"];
  const gitignorePath = path121.join(gitRepoRoot, ".gitignore");
  try {
    let existingContent = "";
    let fileExists2 = true;
    try {
      existingContent = await fs117.promises.readFile(gitignorePath, "utf8");
    } catch (_error) {
      fileExists2 = false;
    }
    if (!fileExists2) {
      const contentToWrite = gitignoreEntries.join("\n") + "\n";
      await fs117.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 fs117.promises.appendFile(gitignorePath, contentToAdd);
      }
    }
  } catch (error40) {
    debugLogger120.debug("Failed to update .gitignore:", error40);
  }
}
__name(updateGitignore, "updateGitignore");
var setupGithubCommand = {
  name: "setup-github",
  get description() {
    return t4("Set up GitHub Actions");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  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) {
      debugLogger120.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 proxy2 = context2?.services?.config?.getProxy();
    const releaseTag = await getLatestGitHubRelease(proxy2);
    const readmeUrl = `https://github.com/QwenLM/qwen-code-action/blob/${releaseTag}/README.md#quick-start`;
    const githubWorkflowsDir = path121.join(gitRepoRoot, ".github", "workflows");
    try {
      await fs117.promises.mkdir(githubWorkflowsDir, { recursive: true });
    } catch (_error) {
      debugLogger120.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: proxy2 ? new import_undici6.ProxyAgent(proxy2) : 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 body2 = response.body;
          if (!body2) {
            throw new Error(
              `Empty body while downloading ${endpoint}: ${response.status} - ${response.statusText}`
            );
          }
          const destination = path121.resolve(
            githubWorkflowsDir,
            path121.basename(workflow)
          );
          const fileStream = fs117.createWriteStream(destination, {
            mode: 420,
            // -rw-r--r--, user(rw), group(r), other(r)
            flags: "w",
            // write and overwrite
            flush: true
          });
          await body2.pipeTo(Writable2.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();
init_types21();
init_types22();
init_i18n();
import { join as join66 } from "path";

// packages/cli/src/services/insight/generators/StaticInsightGenerator.ts
init_esbuild_shims();
import fs119 from "fs/promises";
import path123 from "path";

// packages/cli/src/services/insight/generators/DataProcessor.ts
init_esbuild_shims();
init_dist4();
import fs118 from "fs/promises";
import path122 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 run2 = /* @__PURE__ */ __name(async (function_, resolve42, arguments_2) => {
    const result = (async () => function_(...arguments_2))();
    resolve42(result);
    try {
      await result;
    } catch {
    }
    next();
  }, "run");
  const enqueue = /* @__PURE__ */ __name((function_, resolve42, reject, arguments_2) => {
    const queueItem = { reject };
    new Promise((internalResolve) => {
      queueItem.run = internalResolve;
      queue.enqueue(queueItem);
    }).then(run2.bind(void 0, function_, resolve42, arguments_2));
    if (activeCount < concurrency) {
      resumeNext();
    }
  }, "enqueue");
  const generator = /* @__PURE__ */ __name((function_, ...arguments_2) => new Promise((resolve42, reject) => {
    enqueue(function_, resolve42, reject, arguments_2);
  }), "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 promises9 = Array.from(iterable, (value, index) => this(function_, value, index));
        return Promise.all(promises9);
      }
    }
  });
  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
init_dist4();
var logger4 = 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(date5) {
    return date5.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 (error40) {
      logger4.error(
        `Failed to analyze session ${records[0]?.sessionId}:`,
        error40
      );
      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 i4 = 1; i4 < dateObjects.length; i4++) {
      const nextDate = new Date(dateObjects[i4]);
      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;
    }
    logger4.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 (error40) {
        logger4.error("Failed to generate insight:", error40);
        return void 0;
      }
    }, "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
          )
        )
      ]);
      logger4.debug(
        JSON.stringify(
          {
            impressiveWorkflows,
            projectAreas,
            futureOpportunities,
            frictionPoints,
            memorableMoment,
            improvements,
            interactionStyle,
            atAGlance
          },
          null,
          2
        )
      );
      return {
        impressiveWorkflows,
        projectAreas,
        futureOpportunities,
        frictionPoints,
        memorableMoment,
        improvements,
        interactionStyle,
        atAGlance
      };
    } catch (e4) {
      logger4.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 fs118.readdir(baseDir);
      for (const projectDir of projectDirs) {
        const projectPath = path122.join(baseDir, projectDir);
        const stats = await fs118.stat(projectPath);
        if (stats.isDirectory()) {
          const chatsDir = path122.join(projectPath, "chats");
          try {
            const files = await fs118.readdir(chatsDir);
            const chatFiles = files.filter((file2) => file2.endsWith(".jsonl"));
            for (const file2 of chatFiles) {
              const filePath = path122.join(chatsDir, file2);
              try {
                const fileStats = await fs118.stat(filePath);
                allChatFiles.push({ path: filePath, mtime: fileStats.mtimeMs });
              } catch (e4) {
                logger4.error(`Failed to stat file ${filePath}:`, e4);
              }
            }
          } catch (error40) {
            if (error40.code !== "ENOENT") {
              logger4.error(
                `Error reading chats directory for project ${projectDir}: ${error40}`
              );
            }
            continue;
          }
        }
      }
    } catch (error40) {
      if (error40.code === "ENOENT") {
        logger4.info(`Base directory does not exist: ${baseDir}`);
      } else {
        logger4.error(`Error reading base directory: ${error40}`);
      }
    }
    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 i4 = 0; i4 < totalFiles; i4 += BATCH_SIZE) {
      const batchEnd = Math.min(i4 + BATCH_SIZE, totalFiles);
      const batch = files.slice(i4, 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 name4 = part.functionCall.name;
                  toolUsage[name4] = (toolUsage[name4] || 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 (error40) {
          logger4.error(
            `Failed to process metrics for file ${fileInfo.path}:`,
            error40
          );
        }
      }
      if (onProgress) {
        const percentComplete = batchEnd / totalFiles;
        const overallProgress = 10 + Math.round(percentComplete * 10);
        onProgress(
          `Crunching the numbers (${batchEnd}/${totalFiles})`,
          overallProgress
        );
      }
      await new Promise((resolve42) => setTimeout(resolve42, 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 start2 = sessionStartTimes[sessionId];
      const end = sessionEndTimes[sessionId];
      const durationMs = end.getTime() - start2.getTime();
      const durationMinutes = Math.round(durationMs / (1e3 * 60));
      totalDurationMs += durationMs;
      if (durationMinutes > longestWorkDuration) {
        longestWorkDuration = durationMinutes;
        longestWorkDate = this.formatDate(start2);
      }
    }
    const totalHours = Math.round(totalDurationMs / (1e3 * 60 * 60));
    let latestActiveTime = null;
    let latestTimestamp = /* @__PURE__ */ new Date(0);
    for (const dateStr in heatmap) {
      const date5 = new Date(dateStr);
      if (date5 > latestTimestamp) {
        latestTimestamp = date5;
        latestActiveTime = date5.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) {
        logger4.error(
          `Error reading session file ${fileInfo.path} for facet eligibility:`,
          e4
        );
      }
    }
    logger4.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 = path122.join(
                facetsOutputDir,
                `${sessionId}.json`
              );
              try {
                const existingData = await fs118.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") {
                  logger4.warn(
                    `Failed to read existing facet for ${sessionId}, regenerating:`,
                    readError
                  );
                }
              }
            }
          }
          const facet = await this.analyzeSession(records);
          if (facet && facetsOutputDir) {
            try {
              const facetPath = path122.join(
                facetsOutputDir,
                `${facet.session_id}.json`
              );
              await fs118.writeFile(
                facetPath,
                JSON.stringify(facet, null, 2),
                "utf-8"
              );
            } catch (writeError) {
              logger4.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) {
          logger4.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
init_dist4();
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 = path123.join(Storage.getRuntimeBaseDir(), "insights");
    await fs119.mkdir(outputDir, { recursive: true });
    return outputDir;
  }
  // Generate timestamped filename with collision detection
  async generateOutputPath(outputDir) {
    const now = /* @__PURE__ */ new Date();
    const date5 = now.toISOString().split("T")[0];
    const time3 = now.toTimeString().slice(0, 8).replace(/:/g, "");
    let outputPath = path123.join(outputDir, `insight-${date5}.html`);
    try {
      await fs119.access(outputPath);
      outputPath = path123.join(outputDir, `insight-${date5}-${time3}.html`);
    } catch {
    }
    return outputPath;
  }
  async updateInsightSymlink(outputDir, targetPath) {
    const latestPath = path123.join(outputDir, "insight.html");
    await updateSymlink(latestPath, targetPath);
  }
  // Generate the static insight HTML file
  async generateStaticInsight(baseDir, onProgress) {
    const outputDir = await this.ensureOutputDirectory();
    const facetsDir = path123.join(outputDir, "facets");
    await fs119.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 fs119.writeFile(outputPath, html2, "utf-8");
    await this.updateInsightSymlink(outputDir, outputPath);
    return outputPath;
  }
};

// packages/cli/src/ui/commands/insightCommand.ts
init_dist4();
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 */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: /* @__PURE__ */ __name(async (context2) => {
    try {
      context2.ui.setDebugMessage(t4("Generating insights..."));
      const projectsDir = join66(Storage.getRuntimeBaseDir(), "projects");
      if (!context2.services.config) {
        if (context2.executionMode !== "interactive") {
          return {
            type: "message",
            messageType: "error",
            content: "Config service is not available."
          };
        }
        throw new Error("Config service is not available");
      }
      const insightGenerator = new StaticInsightGenerator(
        context2.services.config
      );
      if (context2.executionMode === "non_interactive") {
        try {
          const outputPath2 = await insightGenerator.generateStaticInsight(
            projectsDir,
            () => {
            }
          );
          return {
            type: "message",
            messageType: "info",
            content: t4("Insight report generated at: {{path}}", {
              path: outputPath2
            })
          };
        } catch (error40) {
          return {
            type: "message",
            messageType: "error",
            content: t4("Failed to generate insights: {{error}}", {
              error: error40.message
            })
          };
        }
      }
      if (context2.executionMode === "acp") {
        const pendingMessages = [];
        let isComplete = false;
        let resume = null;
        const flushResume = /* @__PURE__ */ __name(() => {
          const resolve42 = resume;
          if (!resolve42) {
            return;
          }
          resume = null;
          resolve42();
        }, "flushResume");
        const pushMessage = /* @__PURE__ */ __name((message) => {
          pendingMessages.push(message);
          flushResume();
        }, "pushMessage");
        const streamMessages = /* @__PURE__ */ __name(async function* () {
          while (!isComplete || pendingMessages.length > 0) {
            if (pendingMessages.length === 0) {
              await new Promise((resolve42) => {
                resume = resolve42;
              });
            }
            while (pendingMessages.length > 0) {
              const message = pendingMessages.shift();
              if (message) {
                yield message;
              }
            }
          }
        }, "streamMessages");
        void (async () => {
          try {
            pushMessage({
              messageType: "info",
              content: t4("This may take a couple minutes. Sit tight!")
            });
            pushMessage({
              messageType: "info",
              content: encodeInsightProgressMessage(
                t4("Starting insight generation..."),
                0
              )
            });
            const outputPath2 = await insightGenerator.generateStaticInsight(
              projectsDir,
              (stage, progress, detail) => {
                pushMessage({
                  messageType: "info",
                  content: encodeInsightProgressMessage(
                    stage,
                    progress,
                    detail
                  )
                });
              }
            );
            pushMessage({
              messageType: "info",
              content: encodeInsightReadyMessage(outputPath2)
            });
          } catch (error40) {
            pushMessage({
              messageType: "error",
              content: t4("Failed to generate insights: {{error}}", {
                error: error40.message
              })
            });
            logger5.error("Insight generation error:", error40);
          } finally {
            isComplete = true;
            flushResume();
          }
        })();
        return {
          type: "stream_messages",
          messages: streamMessages()
        };
      }
      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."));
      return;
    } catch (error40) {
      context2.ui.setPendingItem(null);
      if (context2.executionMode !== "interactive") {
        return {
          type: "message",
          messageType: "error",
          content: `Failed to generate insights: ${error40.message}`
        };
      }
      context2.ui.addItem(
        {
          type: "error" /* ERROR */,
          text: t4("Failed to generate insights: {{error}}", {
            error: error40.message
          })
        },
        Date.now()
      );
      logger5.error("Insight generation error:", error40);
      return;
    }
    return;
  }, "action")
};

// packages/cli/src/ui/commands/statuslineCommand.ts
init_esbuild_shims();
init_types21();
init_i18n();
var statuslineCommand = {
  name: "statusline",
  get description() {
    return t4("Set up Qwen Code's status line UI");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive"],
  action: /* @__PURE__ */ __name((_context, args2) => {
    const prompt = args2.trim() || "Configure my statusLine from my shell PS1 configuration";
    return {
      type: "submit_prompt",
      content: [
        {
          text: `Use the Agent tool with subagent_type: "statusline-setup" and this prompt:

${prompt}`
        }
      ]
    };
  }, "action")
};

// packages/cli/src/services/BuiltinCommandLoader.ts
var builtinDebugLogger = createDebugLogger("BUILTIN_COMMAND_LOADER");
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) {
    let resolvedIdeCommand = null;
    try {
      resolvedIdeCommand = await ideCommand();
    } catch (error40) {
      builtinDebugLogger.warn(
        "Failed to load IDE command:",
        error40 instanceof Error ? error40.message : String(error40)
      );
    }
    const allDefinitions = [
      aboutCommand,
      agentsCommand,
      tasksCommand,
      arenaCommand,
      approvalModeCommand,
      authCommand2,
      btwCommand,
      bugCommand,
      clearCommand,
      compressCommand,
      contextCommand,
      copyCommand,
      deleteCommand,
      docsCommand,
      doctorCommand,
      directoryCommand,
      editorCommand,
      exportCommand,
      extensionsCommand2,
      helpCommand,
      hooksCommand2,
      resolvedIdeCommand,
      initCommand,
      languageCommand,
      mcpCommand2,
      ...this.config?.getManagedAutoMemoryEnabled() ? [dreamCommand, forgetCommand] : [],
      memoryCommand,
      modelCommand,
      manageModelsCommand,
      rememberCommand,
      planCommand,
      permissionsCommand,
      ...this.config?.getFolderTrust() ? [trustCommand] : [],
      quitCommand,
      recapCommand,
      renameCommand,
      restoreCommand(this.config),
      resumeCommand,
      rewindCommand,
      skillsCommand,
      statsCommand,
      summaryCommand,
      themeCommand,
      toolsCommand,
      settingsCommand2,
      vimCommand,
      setupGithubCommand,
      terminalSetupCommand,
      insightCommand,
      statuslineCommand
    ];
    return allDefinitions.filter((cmd) => cmd !== null).map((cmd) => ({
      ...cmd,
      source: "builtin-command",
      sourceLabel: "Built-in",
      modelInvocable: false,
      userInvocable: cmd.userInvocable ?? true
    }));
  }
};

// packages/cli/src/services/BundledSkillLoader.ts
init_esbuild_shims();
init_dist4();
init_types21();
var debugLogger121 = createDebugLogger("BUNDLED_SKILL_LOADER");
var BundledSkillLoader = class {
  constructor(config2) {
    this.config = config2;
  }
  static {
    __name(this, "BundledSkillLoader");
  }
  async loadCommands(_signal) {
    if (this.config?.getBareMode?.()) {
      debugLogger121.debug("Bare mode enabled, skipping bundled skills");
      return [];
    }
    const skillManager = this.config?.getSkillManager();
    if (!skillManager) {
      debugLogger121.debug("SkillManager not available, skipping bundled skills");
      return [];
    }
    try {
      const allSkills = await skillManager.listSkills({ level: "bundled" });
      const cronEnabled = this.config?.isCronEnabled() ?? false;
      const skills = allSkills.filter((skill) => {
        if (!cronEnabled && skill.allowedTools?.some((t5) => t5.startsWith("cron_"))) {
          debugLogger121.debug(
            `Hiding skill "${skill.name}" because cron is not enabled`
          );
          return false;
        }
        return true;
      });
      debugLogger121.debug(
        `Loaded ${skills.length} bundled skill(s) as slash commands`
      );
      return skills.map((skill) => ({
        name: skill.name,
        description: skill.description,
        kind: "skill" /* SKILL */,
        source: "bundled-skill",
        sourceLabel: "Skill",
        modelInvocable: !skill.disableModelInvocation,
        argumentHint: skill.argumentHint,
        whenToUse: skill.whenToUse,
        action: /* @__PURE__ */ __name(async (context2, _args) => {
          let body2 = skill.body;
          const modelId = this.config?.getModel()?.trim() || "";
          if (body2.includes("{{model}}") || body2.includes("YOUR_MODEL_ID")) {
            body2 = body2.replaceAll("{{model}}", modelId);
            body2 = body2.replaceAll("YOUR_MODEL_ID", modelId);
            if (modelId) {
              body2 = `YOUR_MODEL_ID="${modelId}"

${body2}`;
            }
          }
          const content = context2.invocation?.args ? appendToLastTextPart([{ text: body2 }], context2.invocation.raw) : [{ text: body2 }];
          return {
            type: "submit_prompt",
            content
          };
        }, "action")
      }));
    } catch (error40) {
      debugLogger121.error("Failed to load bundled skills:", error40);
      return [];
    }
  }
};

// packages/cli/src/services/FileCommandLoader.ts
init_esbuild_shims();
var import_toml2 = __toESM(require_toml(), 1);
init_esm13();
init_zod();
init_dist4();
import { promises as fs120 } from "node:fs";
import * as fsSync5 from "node:fs";
import path125 from "node:path";

// packages/cli/src/services/markdown-command-parser.ts
init_esbuild_shims();
init_zod();
init_dist4();
var MarkdownCommandDefSchema = external_exports.object({
  frontmatter: external_exports.object({
    description: external_exports.string().optional(),
    "argument-hint": external_exports.string().optional(),
    when_to_use: external_exports.string().optional(),
    "disable-model-invocation": external_exports.boolean().optional()
  }).passthrough().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 normalizedContent = normalizeContent(content);
  const frontmatterRegex = /^---\n(?:([\s\S]*?)\n)?---(?:\n|$)([\s\S]*)$/;
  const match2 = normalizedContent.match(frontmatterRegex);
  if (!match2) {
    return {
      prompt: normalizedContent.trim()
    };
  }
  const [, frontmatterYaml = "", body2] = match2;
  let frontmatter;
  if (frontmatterYaml.trim()) {
    try {
      frontmatter = parse8(frontmatterYaml);
    } catch (error40) {
      throw new Error(
        `Failed to parse YAML frontmatter: ${error40 instanceof Error ? error40.message : String(error40)}`
      );
    }
  }
  return {
    frontmatter,
    prompt: body2.trim()
  };
}
__name(parseMarkdownCommand, "parseMarkdownCommand");

// packages/cli/src/services/command-factory.ts
init_esbuild_shims();
init_dist4();
init_types21();
import path124 from "node:path";

// packages/cli/src/services/prompt-processors/argumentProcessor.ts
init_esbuild_shims();
init_dist4();
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();
init_dist4();

// 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);
    let userArgsForArgumentsPlaceholder = userArgsRaw.replace(
      /^'([\s\S]*?)'$/,
      "$1"
    );
    const argumentSafety = checkArgumentSafety(userArgsForArgumentsPlaceholder);
    if (!argumentSafety.isSafe) {
      userArgsForArgumentsPlaceholder = userArgsEscaped;
    }
    const resolvedInjections = injections.map(
      (injection) => {
        const command2 = injection.content;
        if (command2 === "") {
          return { ...injection, resolvedCommand: void 0 };
        }
        const resolvedCommand = command2.replaceAll(SHORTHAND_ARGS_PLACEHOLDER, userArgsEscaped).replaceAll("$ARGUMENTS", userArgsForArgumentsPlaceholder);
        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 } = await checkCommandPermissions(command2, config2, sessionShellAllowlist);
      const pm = config2.getPermissionManager?.();
      const isAllowedBySettings = pm ? await pm.isCommandAllowed(command2) === "allow" : false;
      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();
init_dist4();
init_types22();
var debugLogger122 = 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 (error40) {
          const message = error40 instanceof Error ? error40.message : String(error40);
          const uiMessage = `Failed to inject content for '@{${pathStr}}': ${message}`;
          debugLogger122.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 debugLogger123 = createDebugLogger("COMMAND_FACTORY");
function createSlashCommandFromDefinition(filePath, baseDir, definition, extensionName, fileExtension) {
  const relativePathWithExt = path124.relative(baseDir, filePath);
  const relativePath = relativePathWithExt.substring(
    0,
    relativePathWithExt.length - fileExtension.length
  );
  const baseCommandName = relativePath.split(path124.sep).map((segment) => segment.replaceAll(":", "_")).join(":");
  const defaultDescription = `Custom command from ${path124.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,
    source: extensionName ? "plugin-command" : "skill-dir-command",
    sourceLabel: extensionName ? `Plugin: ${extensionName}` : "Custom",
    modelInvocable: definition.disableModelInvocation ? false : !extensionName || !!(definition.description || definition.whenToUse),
    argumentHint: definition.argumentHint,
    whenToUse: definition.whenToUse,
    action: /* @__PURE__ */ __name(async (context2, _args) => {
      if (!context2.invocation) {
        debugLogger123.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 debugLogger124 = 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) {
    if (this.config?.getBareMode?.()) {
      debugLogger124.debug("Bare mode enabled, skipping auto-discovered commands");
      return [];
    }
    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(
          (file2) => this.parseAndAdaptTomlFile(
            path125.join(dirInfo.path, file2),
            dirInfo.path,
            dirInfo.extensionName
          )
        );
        const mdCommandPromises = mdFiles.map(
          (file2) => this.parseAndAdaptMarkdownFile(
            path125.join(dirInfo.path, file2),
            dirInfo.path,
            dirInfo.extensionName
          )
        );
        const commands = (await Promise.all([...tomlCommandPromises, ...mdCommandPromises])).filter((cmd) => cmd !== null);
        allCommands.push(...commands);
      } catch (error40) {
        const isEnoent = error40.code === "ENOENT";
        const isAbortError3 = error40 instanceof Error && error40.name === "AbortError";
        if (!isEnoent && !isAbortError3) {
          debugLogger124.error(
            `[FileCommandLoader] Error loading commands from ${dirInfo.path}:`,
            error40
          );
        }
      }
    }
    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 = path125.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) => path125.isAbsolute(cmdPath) ? cmdPath : path125.join(ext2.path, cmdPath)
          ).filter((cmdPath) => {
            try {
              return fsSync5.existsSync(cmdPath);
            } catch {
              return false;
            }
          });
        }
      }
    } catch (error40) {
      debugLogger124.warn(
        `Failed to read extension config for ${ext2.name}:`,
        error40
      );
    }
    const defaultPath = path125.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 fs120.readFile(filePath, "utf-8");
    } catch (error40) {
      debugLogger124.error(
        `[FileCommandLoader] Failed to read file ${filePath}:`,
        error40 instanceof Error ? error40.message : String(error40)
      );
      return null;
    }
    let parsed;
    try {
      parsed = import_toml2.default.parse(fileContent);
    } catch (error40) {
      debugLogger124.error(
        `[FileCommandLoader] Failed to parse TOML file ${filePath}:`,
        error40 instanceof Error ? error40.message : String(error40)
      );
      return null;
    }
    const validationResult = TomlCommandDefSchema.safeParse(parsed);
    if (!validationResult.success) {
      debugLogger124.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 fs120.readFile(filePath, "utf-8");
    } catch (error40) {
      debugLogger124.error(
        `[FileCommandLoader] Failed to read file ${filePath}:`,
        error40 instanceof Error ? error40.message : String(error40)
      );
      return null;
    }
    let parsed;
    try {
      parsed = parseMarkdownCommand(fileContent);
    } catch (error40) {
      debugLogger124.error(
        `[FileCommandLoader] Failed to parse Markdown file ${filePath}:`,
        error40 instanceof Error ? error40.message : String(error40)
      );
      return null;
    }
    const validationResult = MarkdownCommandDefSchema.safeParse(parsed);
    if (!validationResult.success) {
      debugLogger124.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,
      whenToUse: validDef.frontmatter?.when_to_use,
      argumentHint: validDef.frontmatter?.["argument-hint"],
      disableModelInvocation: validDef.frontmatter?.["disable-model-invocation"]
    };
    return createSlashCommandFromDefinition(
      filePath,
      baseDir,
      definition,
      extensionName,
      ".md"
    );
  }
};

// packages/cli/src/services/SkillCommandLoader.ts
init_esbuild_shims();
init_dist4();
init_types21();
var debugLogger125 = createDebugLogger("SKILL_COMMAND_LOADER");
var SkillCommandLoader = class {
  constructor(config2) {
    this.config = config2;
  }
  static {
    __name(this, "SkillCommandLoader");
  }
  async loadCommands(_signal) {
    if (this.config?.getBareMode?.()) {
      debugLogger125.debug("Bare mode enabled, skipping skill commands");
      return [];
    }
    const skillManager = this.config?.getSkillManager();
    if (!skillManager) {
      debugLogger125.debug("SkillManager not available, skipping skill commands");
      return [];
    }
    try {
      const [userSkills, projectSkills, extensionSkills] = await Promise.all([
        skillManager.listSkills({ level: "user" }),
        skillManager.listSkills({ level: "project" }),
        skillManager.listSkills({ level: "extension" })
      ]);
      const allSkills = [...userSkills, ...projectSkills, ...extensionSkills];
      debugLogger125.debug(
        `Loaded ${userSkills.length} user + ${projectSkills.length} project + ${extensionSkills.length} extension skill(s) as slash commands`
      );
      return allSkills.map((skill) => {
        const isExtension = skill.level === "extension";
        const modelInvocable = skill.disableModelInvocation ? false : isExtension ? !!(skill.description || skill.whenToUse) : true;
        const sourceLabel = isExtension ? `Extension: ${skill.extensionName ?? "unknown"}` : skill.level === "project" ? "Project" : "User";
        return {
          name: skill.name,
          description: skill.description,
          kind: "skill" /* SKILL */,
          source: isExtension ? "plugin-command" : "skill-dir-command",
          sourceLabel,
          modelInvocable,
          argumentHint: skill.argumentHint,
          whenToUse: skill.whenToUse,
          action: /* @__PURE__ */ __name(async (context2, _args) => {
            const body2 = skill.body;
            const content = context2.invocation?.args ? appendToLastTextPart([{ text: body2 }], context2.invocation.raw) : [{ text: body2 }];
            return {
              type: "submit_prompt",
              content
            };
          }, "action")
        };
      });
    } catch (error40) {
      debugLogger125.error("Failed to load skill commands:", error40);
      return [];
    }
  }
};

// packages/cli/src/nonInteractiveCliCommands.ts
init_types21();

// 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"),
    btwItem: null,
    setBtwItem: /* @__PURE__ */ __name((_item) => {
    }, "setBtwItem"),
    cancelBtw: /* @__PURE__ */ __name(() => {
    }, "cancelBtw"),
    btwAbortControllerRef: { current: null },
    isIdleRef: { current: true },
    toggleVimEnabled: /* @__PURE__ */ __name(async () => false, "toggleVimEnabled"),
    setGeminiMdFileCount: /* @__PURE__ */ __name((_count) => {
    }, "setGeminiMdFileCount"),
    reloadCommands: /* @__PURE__ */ __name(() => {
    }, "reloadCommands"),
    setSessionName: /* @__PURE__ */ __name(() => {
    }, "setSessionName"),
    extensionsUpdateState: /* @__PURE__ */ new Map(),
    dispatchExtensionStateUpdate: /* @__PURE__ */ __name((_action) => {
    }, "dispatchExtensionStateUpdate"),
    addConfirmUpdateExtensionRequest: /* @__PURE__ */ __name((_request) => {
    }, "addConfirmUpdateExtensionRequest")
  };
}
__name(createNonInteractiveUI, "createNonInteractiveUI");

// packages/cli/src/nonInteractiveCliCommands.ts
init_i18n();
var debugLogger126 = createDebugLogger("NON_INTERACTIVE_COMMANDS");
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");
var handleSlashCommand = /* @__PURE__ */ __name(async (rawQuery, abortController, config2, settings) => {
  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 allLoaders = [
    new BuiltinCommandLoader(config2),
    new BundledSkillLoader(config2),
    new SkillCommandLoader(config2),
    new FileCommandLoader(config2)
  ];
  const disabledSlashCommandsRaw = config2.getDisabledSlashCommands();
  const disabledNameSet = /* @__PURE__ */ new Set();
  for (const name4 of disabledSlashCommandsRaw) {
    const trimmed3 = name4.trim();
    if (trimmed3) disabledNameSet.add(trimmed3.toLowerCase());
  }
  const isDisabled = /* @__PURE__ */ __name((cmd) => disabledNameSet.has(cmd.name.toLowerCase()) || (cmd.altNames ?? []).some((a2) => disabledNameSet.has(a2.toLowerCase())), "isDisabled");
  const commandService = await CommandService.create(
    allLoaders,
    abortController.signal
  );
  config2.setModelInvocableCommandsProvider(
    () => commandService.getModelInvocableCommands().map((cmd) => ({
      name: cmd.name,
      description: typeof cmd.description === "string" ? cmd.description : cmd.description
    }))
  );
  config2.setModelInvocableCommandsExecutor(
    async (name4, args3 = "") => {
      const commands = commandService.getModelInvocableCommands();
      const cmd = commands.find((c4) => c4.name === name4);
      if (!cmd?.action) return null;
      const minimalContext = {
        executionMode,
        invocation: {
          raw: args3 ? `/${name4} ${args3}` : `/${name4}`,
          name: name4,
          args: args3
        },
        services: { config: config2, settings, git: void 0, logger: null }
      };
      const result2 = await cmd.action(minimalContext, args3);
      if (!result2 || result2.type !== "submit_prompt") return null;
      const content = result2.content;
      if (typeof content === "string") return content;
      if (Array.isArray(content)) {
        return content.map(
          (p2) => typeof p2 === "string" ? p2 : p2.text ?? ""
        ).join("");
      }
      return null;
    }
  );
  const allCommands = commandService.getCommands();
  const filteredCommands = commandService.getCommandsForMode(executionMode).filter((cmd) => !isDisabled(cmd));
  const { commandToExecute, args: args2 } = parseSlashCommand(
    rawQuery,
    filteredCommands
  );
  if (!commandToExecute) {
    const { commandToExecute: knownCommand } = parseSlashCommand(
      rawQuery,
      allCommands
    );
    if (knownCommand) {
      const typedToken = rawQuery.trim().substring(1).trim().split(/\s+/)[0] ?? knownCommand.name;
      if (isDisabled(knownCommand)) {
        return {
          type: "unsupported",
          reason: t4(
            'The command "/{{command}}" is disabled by the current configuration.',
            { command: typedToken }
          ),
          originalType: "filtered_command"
        };
      }
      return {
        type: "unsupported",
        reason: t4('The command "/{{command}}" is not supported in this mode.', {
          command: typedToken
        }),
        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: args2
    }
  };
  const result = await commandToExecute.action(context2, args2);
  if (!result) {
    return {
      type: "message",
      messageType: "info",
      content: "Command executed successfully."
    };
  }
  return handleCommandResult(result);
}, "handleSlashCommand");
var getAvailableCommands = /* @__PURE__ */ __name(async (config2, abortSignal, mode = "acp") => {
  try {
    const loaders = [
      new BuiltinCommandLoader(config2),
      new BundledSkillLoader(config2),
      new SkillCommandLoader(config2),
      new FileCommandLoader(config2)
    ];
    const disabledSlashCommands = config2.getDisabledSlashCommands();
    const commandService = await CommandService.create(
      loaders,
      abortSignal,
      disabledSlashCommands.length > 0 ? new Set(disabledSlashCommands) : void 0
    );
    return commandService.getCommandsForMode(mode);
  } catch (error40) {
    debugLogger126.error("Error loading available commands:", error40);
    return [];
  }
}, "getAvailableCommands");

// packages/cli/src/utils/nonInteractiveHelpers.ts
var debugLogger127 = createDebugLogger("NON_INTERACTIVE");
function normalizePartList(parts2) {
  if (!parts2) {
    return [];
  }
  if (typeof parts2 === "string") {
    return [{ text: parts2 }];
  }
  if (Array.isArray(parts2)) {
    return parts2.map(
      (part) => typeof part === "string" ? { text: part } : part
    );
  }
  return [parts2];
}
__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 parts2 = [];
    for (const block2 of content) {
      if (!block2 || typeof block2 !== "object" || !("type" in block2)) {
        continue;
      }
      if (block2.type === "text" && "text" in block2 && block2.text) {
        parts2.push({ text: block2.text });
      } else {
        parts2.push({ text: JSON.stringify(block2) });
      }
    }
    return parts2.length > 0 ? parts2 : 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) {
  const controller = new AbortController();
  try {
    const commands = await getAvailableCommands(
      config2,
      controller.signal,
      "non_interactive"
    );
    return commands.map((cmd) => cmd.name).sort();
  } catch (error40) {
    debugLogger127.error(
      "[buildSystemMessage] Failed to load slash commands:",
      error40
    );
    return [];
  } finally {
    controller.abort();
  }
}
__name(loadSlashCommandNames, "loadSlashCommandNames");
async function buildSystemMessage(config2, sessionId, permissionMode) {
  const toolRegistry = config2.getToolRegistry();
  const tools = toolRegistry ? toolRegistry.getAllToolNames() : [];
  const mcpServers = config2.getMcpServers();
  const mcpServerList = mcpServers ? Object.keys(mcpServers).map((name4) => ({
    name: name4,
    status: getMCPServerStatus(name4)
  })) : [];
  const slashCommands = await loadSlashCommandNames(config2);
  let agentNames = [];
  try {
    const subagentManager = config2.getSubagentManager();
    const subagents = await subagentManager.listSubagents();
    agentNames = subagents.map((subagent) => subagent.name);
  } catch (error40) {
    debugLogger127.error("[buildSystemMessage] Failed to load subagents:", error40);
  }
  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, adapter2) {
  const handler = /* @__PURE__ */ __name((_callId, output) => {
    if (isMcpToolProgressData(output)) {
      adapter2.emitToolProgress(request4, output);
    }
  }, "handler");
  return { handler };
}
__name(createToolProgressHandler, "createToolProgressHandler");
function createAgentToolProgressHandler(config2, agentToolCallId, adapter2) {
  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 (adapter2.processSubagentToolCall) {
        adapter2.processSubagentToolCall(toolCallToEmit, agentToolCallId);
        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 adapter2 && typeof adapter2.emitToolResult === "function") {
      adapter2.emitToolResult(request4, response, agentToolCallId);
    } else {
      adapter2.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 (!adapter2.processSubagentToolCall || !adapter2.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");
          adapter2.emitSubagentErrorResult(errorMessage, 0, agentToolCallId);
        }
      }
      if (!previous && taskDisplay.taskPrompt && !config2.isInteractive() && (config2.getOutputFormat() === OutputFormat.JSON || config2.getOutputFormat() === OutputFormat.STREAM_JSON)) {
        adapter2.emitUserMessage(
          [{ text: taskDisplay.taskPrompt }],
          agentToolCallId
        );
      }
      previousTaskStates.set(callId, taskDisplay);
    }
  }, "outputUpdateHandler");
  return {
    handler: outputUpdateHandler
  };
}
__name(createAgentToolProgressHandler, "createAgentToolProgressHandler");
function functionResponsePartsToString(parts2) {
  return parts2.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(metadata2) {
    const usage2 = {
      input_tokens: 0,
      output_tokens: 0
    };
    if (!metadata2) {
      return usage2;
    }
    if (typeof metadata2.promptTokenCount === "number") {
      usage2.input_tokens = metadata2.promptTokenCount;
    }
    if (typeof metadata2.candidatesTokenCount === "number") {
      usage2.output_tokens = metadata2.candidatesTokenCount;
    }
    if (typeof metadata2.cachedContentTokenCount === "number") {
      usage2.cache_read_input_tokens = metadata2.cachedContentTokenCount;
    }
    if (typeof metadata2.totalTokenCount === "number") {
      usage2.total_tokens = metadata2.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;
    }
    const index = state.blocks.length - 1;
    if (!state.openBlocks.has(index)) {
      return;
    }
    if (lastBlock.type === "text" || lastBlock.type === "thinking") {
      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 = randomUUID18();
    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);
    if (state.messageStarted) {
      this.emitMessageImpl(message);
    }
    return message;
  }
  /**
   * Emits a control-plane message (control_request / control_response).
   * Only meaningful in streaming adapters; batch adapters inherit this
   * no-op since control messages are not collected into the final array.
   */
  emitControlMessageImpl(_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);
    return this.finalizeAssistantMessageInternal(state, parentToolUseId);
  }
  /**
   * 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 parts2 = [];
    if (subject && subject.length > 0) {
      parts2.push(subject);
    }
    if (description && description.length > 0) {
      parts2.push(description);
    }
    const fragment = parts2.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(parts2, parentToolUseId) {
    const content = partsToContentBlock(parts2);
    const message = {
      type: "user",
      uuid: randomUUID18(),
      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: randomUUID18(),
      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: randomUUID18(),
      session_id: this.getSessionId(),
      parent_tool_use_id: null,
      data
    };
    this.emitMessageImpl(systemMessage);
  }
  /**
   * Emits a `can_use_tool` permission control_request so an external consumer
   * can approve or deny the tool call. Pairs with {@link emitControlResponse}.
   */
  emitPermissionRequest(requestId, toolName, toolUseId, input, blockedPath = null) {
    const message = {
      type: "control_request",
      request_id: requestId,
      request: {
        subtype: "can_use_tool",
        tool_name: toolName,
        tool_use_id: toolUseId,
        input,
        permission_suggestions: null,
        blocked_path: blockedPath
      }
    };
    this.emitControlMessageImpl(message);
  }
  /**
   * Emits a control_response carrying a permission approval result.
   * Used both to mirror TUI-native resolutions back to external consumers
   * and to acknowledge externally-supplied confirmation_responses.
   */
  emitControlResponse(requestId, allowed) {
    const message = {
      type: "control_response",
      response: {
        subtype: "success",
        request_id: requestId,
        response: { allowed }
      }
    };
    this.emitControlMessageImpl(message);
  }
  /**
   * Emits a control_response with subtype `error`. Used to reject an
   * external confirmation_response that cannot be honored (unknown
   * request_id, tool call already resolved, etc.) so the consumer can
   * surface or retry, instead of waiting forever for an implicit ack.
   */
  emitControlError(requestId, errorMessage) {
    const message = {
      type: "control_response",
      response: {
        subtype: "error",
        request_id: requestId,
        error: errorMessage
      }
    };
    this.emitControlMessageImpl(message);
  }
  /**
   * 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 = randomUUID18();
    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 success2 = {
        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) {
        success2.stats = options2.stats;
      }
      return success2;
    }
  }
  /**
   * 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: randomUUID18(),
      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(parts2) {
  const blocks = [];
  let currentTextBlock = null;
  for (const part of parts2) {
    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 error40 = part.functionResponse.response["error"];
      return typeof error40 === "string" ? error40 : String(error40);
    }
  }
  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() {
    return this.finalizeAssistantMessageInternal(
      this.mainAgentMessageState,
      null
    );
  }
  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 json3 = JSON.stringify(this.messages);
      process.stdout.write(`${json3}
`);
    }
  }
  emitMessage(message) {
    this.messages.push(message);
  }
};

// packages/cli/src/nonInteractive/io/StreamJsonOutputAdapter.ts
init_esbuild_shims();
import { randomUUID as randomUUID19 } from "node:crypto";
var StreamJsonOutputAdapter = class extends BaseJsonOutputAdapter {
  constructor(config2, includePartialMessages, outputStream) {
    super(config2);
    this.includePartialMessages = includePartialMessages;
    this.outputStream = outputStream ?? process.stdout;
  }
  static {
    __name(this, "StreamJsonOutputAdapter");
  }
  mainTurnMessageStartEmitted = false;
  outputStream;
  /**
   * Emits message immediately to the output stream (stream mode).
   */
  emitMessageImpl(message) {
    if (typeof message === "object" && message !== null && "type" in message && message.type === "assistant") {
      this.updateLastAssistantMessage(message);
    }
    this.outputStream.write(`${JSON.stringify(message)}
`);
  }
  /**
   * Control-plane messages (control_request / control_response) share the
   * same transport as data messages in stream mode.
   */
  emitControlMessageImpl(message) {
    this.outputStream.write(`${JSON.stringify(message)}
`);
  }
  /**
   * Stream mode emits stream events when includePartialMessages is enabled.
   */
  shouldEmitStreamEvents() {
    return this.includePartialMessages;
  }
  startAssistantMessage() {
    this.mainTurnMessageStartEmitted = false;
    super.startAssistantMessage();
  }
  finalizeAssistantMessage() {
    const message = this.finalizeAssistantMessageInternal(
      this.mainAgentMessageState,
      null
    );
    if (this.mainTurnMessageStartEmitted && this.includePartialMessages) {
      const partial2 = {
        type: "stream_event",
        uuid: randomUUID19(),
        session_id: this.getSessionId(),
        parent_tool_use_id: null,
        event: { type: "message_stop" }
      };
      this.emitMessageImpl(partial2);
    }
    this.mainTurnMessageStartEmitted = false;
    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 once per turn for the main agent (guarded by mainTurnMessageStartEmitted),
   * so block-type transitions inside a single turn do not produce spurious message_start events.
   */
  onEnsureMessageStarted(state, parentToolUseId) {
    if (parentToolUseId === null && !this.mainTurnMessageStartEmitted) {
      this.mainTurnMessageStartEmitted = true;
      this.emitStreamEventIfEnabled(
        {
          type: "message_start",
          message: {
            id: state.messageId,
            role: "assistant",
            model: this.config.getModel(),
            content: []
          }
        },
        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: randomUUID19(),
      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 partial2 = {
      type: "stream_event",
      uuid: randomUUID19(),
      session_id: this.getSessionId(),
      parent_tool_use_id: parentToolUseId,
      event
    };
    this.emitMessageImpl(partial2);
  }
};

// packages/cli/src/ui/hooks/atCommandProcessor.ts
init_esbuild_shims();
init_dist4();
init_types22();
import * as fs121 from "node:fs/promises";
import * as path126 from "node:path";
function parseAllAtCommands(query) {
  const parts2 = [];
  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) {
        parts2.push({ type: "text", content: query.substring(currentIndex) });
      }
      break;
    }
    if (atIndex > currentIndex) {
      parts2.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);
    parts2.push({ type: "atPath", content: atPath });
    currentIndex = pathEndIndex;
  }
  return parts2.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 = path126.isAbsolute(pathName) ? pathName : path126.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 = path126.resolve(dir, pathName);
        const stats = await fs121.stat(absolutePath);
        if (stats.isDirectory()) {
          currentPathSpec = pathName;
          onDebugMessage(`Path ${pathName} resolved to directory.`);
        } else {
          onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`);
        }
        resolvedSuccessfully = true;
      } catch (error40) {
        if (isNodeError(error40) && error40.code === "ENOENT") {
          sawNotFound = true;
          continue;
        } else {
          onDebugMessage(
            `Error stating path ${pathName}: ${getErrorMessage(error40)}. 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 i4 = 0; i4 < commandParts.length; i4++) {
    const part = commandParts[i4];
    if (part.type === "text") {
      initialQueryText += part.content;
    } else {
      const resolvedSpec = atPathToResolvedSpecMap.get(part.content);
      if (i4 > 0 && initialQueryText.length > 0 && !initialQueryText.endsWith(" ")) {
        const prevPart = commandParts[i4 - 1];
        if (prevPart.type === "text" || prevPart.type === "atPath" && atPathToResolvedSpecMap.has(prevPart.content)) {
          initialQueryText += " ";
        }
      }
      if (resolvedSpec) {
        initialQueryText += `@${resolvedSpec}`;
      } else {
        if (i4 > 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 parts2 = Array.isArray(result.contentParts) ? result.contentParts : [result.contentParts];
    const toolCallDisplays = result.files.map(
      (file2, index) => ({
        callId: `client-read-${userMessageTimestamp}-${index}`,
        name: file2.isDirectory ? "Read Directory" : "Read File",
        description: file2.isDirectory ? `Read directory ${path126.basename(file2.filePath)}` : `Read file ${path126.basename(file2.filePath)}`,
        status: file2.error ? "Error" /* Error */ : "Success" /* Success */,
        resultDisplay: file2.error ? `Failed to read ${path126.basename(file2.filePath)}: ${file2.error}` : void 0,
        confirmationDetails: void 0
      })
    );
    const processedQueryParts = [{ text: initialQueryText }];
    if (parts2.length > 0 && !result.error) {
      for (const part of parts2) {
        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 (error40) {
    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(error40)}`,
      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 debugLogger128 = createDebugLogger("NON_INTERACTIVE_CLI");
var LOOP_TYPE_LABELS = {
  [LoopType.CONSECUTIVE_IDENTICAL_TOOL_CALLS]: "the model repeated the same tool call with identical arguments",
  [LoopType.CHANTING_IDENTICAL_SENTENCES]: "the model repeated the same sentence in its output",
  [LoopType.REPETITIVE_THOUGHTS]: "the model repeated the same reasoning thought",
  [LoopType.READ_FILE_LOOP]: "the model spent too many consecutive calls reading files without making progress",
  [LoopType.ACTION_STAGNATION]: "the model kept calling the same tool without making progress"
};
function emitLoopDetectedMessage(config2, loopType) {
  if (config2.getOutputFormat() !== OutputFormat.TEXT) {
    return;
  }
  const reason = loopType ? LOOP_TYPE_LABELS[loopType] : void 0;
  const detail = reason ? ` (${loopType}: ${reason})` : "";
  process.stderr.write(
    `Loop detection halted the run${detail}. Set the \`model.skipLoopDetection\` setting to true to disable.
`
  );
}
__name(emitLoopDetectedMessage, "emitLoopDetectedMessage");
async function emitNonInteractiveFinalMessage(params) {
  const { message, isError, adapter: adapter2, config: config2 } = params;
  adapter2.startAssistantMessage();
  adapter2.processEvent({
    type: GeminiEventType.Content,
    value: message
  });
  adapter2.finalizeAssistantMessage();
  const metrics2 = uiTelemetryService.getMetrics();
  const usage2 = computeUsageFromMetrics(metrics2);
  const outputFormat = config2.getOutputFormat();
  const stats = outputFormat === OutputFormat.JSON ? uiTelemetryService.getMetrics() : void 0;
  adapter2.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 adapter2;
    const outputFormat = config2.getOutputFormat();
    if (options2.adapter) {
      adapter2 = options2.adapter;
    } else if (outputFormat === OutputFormat.STREAM_JSON) {
      adapter2 = new StreamJsonOutputAdapter(
        config2,
        config2.getIncludePartialMessages()
      );
    } else {
      adapter2 = new JsonOutputAdapter(config2);
    }
    const sessionId = config2.getSessionId();
    const permissionMode = config2.getApprovalMode();
    let turnCount = 0;
    let totalApiDurationMs = 0;
    const startTime = Date.now();
    const geminiClient = config2.getGeminiClient();
    const abortController = options2.abortController ?? new AbortController();
    let pipeBroken = false;
    const stdoutErrorHandler = /* @__PURE__ */ __name((err2) => {
      if (err2.code === "EPIPE" && !pipeBroken) {
        pipeBroken = true;
        process.stdout.destroy();
      }
    }, "stdoutErrorHandler");
    const shutdownHandler = /* @__PURE__ */ __name(() => {
      debugLogger128.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
      );
      adapter2.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: adapter2,
                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: adapter2,
                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 }];
      const localQueue = [];
      const registry3 = config2.getBackgroundTaskRegistry();
      registry3.setNotificationCallback((displayText, modelText, meta) => {
        localQueue.push({
          displayText,
          modelText,
          sendMessageType: SendMessageType.Notification,
          sdkNotification: {
            task_id: meta.agentId,
            tool_use_id: meta.toolUseId,
            status: meta.status,
            usage: meta.stats ? {
              total_tokens: meta.stats.totalTokens,
              tool_uses: meta.stats.toolUses,
              duration_ms: meta.stats.durationMs
            } : void 0
          }
        });
      });
      registry3.setRegisterCallback((entry) => {
        adapter2.emitSystemMessage("task_started", {
          task_id: entry.agentId,
          tool_use_id: entry.toolUseId,
          description: entry.description,
          subagent_type: entry.subagentType
        });
      });
      let isFirstTurn = true;
      let modelOverride;
      while (true) {
        turnCount++;
        if (config2.getMaxSessionTurns() >= 0 && turnCount > config2.getMaxSessionTurns()) {
          await handleMaxTurnsExceededError(config2);
        }
        const toolCallRequests = [];
        const apiStartTime = Date.now();
        const responseStream = geminiClient.sendMessageStream(
          currentMessages[0]?.parts || [],
          abortController.signal,
          prompt_id,
          {
            type: isFirstTurn ? SendMessageType.UserQuery : SendMessageType.ToolResult,
            modelOverride
          }
        );
        isFirstTurn = false;
        adapter2.startAssistantMessage();
        for await (const event of responseStream) {
          if (abortController.signal.aborted) {
            await handleCancellationError(config2);
          }
          adapter2.processEvent(event);
          if (event.type === GeminiEventType.ToolCallRequest) {
            toolCallRequests.push(event.value);
          }
          if (event.type === GeminiEventType.LoopDetected) {
            emitLoopDetectedMessage(config2, event.value?.loopType);
          }
          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);
          }
        }
        adapter2.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 isAgentTool = finalRequestInfo.name === "agent";
            const { handler: outputUpdateHandler } = isAgentTool ? createAgentToolProgressHandler(
              config2,
              finalRequestInfo.callId,
              adapter2
            ) : createToolProgressHandler(finalRequestInfo, adapter2);
            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
              );
            }
            adapter2.emitToolResult(finalRequestInfo, toolResponse);
            if (toolResponse.responseParts) {
              toolResponseParts.push(...toolResponse.responseParts);
            }
            if ("modelOverride" in toolResponse) {
              modelOverride = toolResponse.modelOverride;
            }
          }
          currentMessages = [{ role: "user", parts: toolResponseParts }];
        } else {
          const emitNotificationToSdk = /* @__PURE__ */ __name((item) => {
            if (item.sendMessageType !== SendMessageType.Notification) return;
            adapter2.emitUserMessage([{ text: item.displayText }]);
            if (item.sdkNotification) {
              adapter2.emitSystemMessage(
                "task_notification",
                item.sdkNotification
              );
            }
          }, "emitNotificationToSdk");
          const drainOneItem = /* @__PURE__ */ __name(async () => {
            if (localQueue.length === 0) return;
            const item = localQueue.shift();
            emitNotificationToSdk(item);
            turnCount++;
            if (config2.getMaxSessionTurns() >= 0 && turnCount > config2.getMaxSessionTurns()) {
              await handleMaxTurnsExceededError(config2);
            }
            const inputFormat = typeof config2.getInputFormat === "function" ? config2.getInputFormat() : InputFormat.TEXT;
            const toolCallUpdateCallback = inputFormat === InputFormat.STREAM_JSON && options2.controlService ? options2.controlService.permission.getToolCallUpdateCallback() : void 0;
            let itemMessages = [
              { role: "user", parts: [{ text: item.modelText }] }
            ];
            let itemIsFirstTurn = true;
            let itemModelOverride;
            while (true) {
              const itemToolCallRequests = [];
              const itemApiStartTime = Date.now();
              const itemStream = geminiClient.sendMessageStream(
                itemMessages[0]?.parts || [],
                abortController.signal,
                prompt_id,
                {
                  type: itemIsFirstTurn ? item.sendMessageType : SendMessageType.ToolResult,
                  modelOverride: itemModelOverride,
                  ...itemIsFirstTurn && {
                    notificationDisplayText: item.displayText
                  }
                }
              );
              itemIsFirstTurn = false;
              adapter2.startAssistantMessage();
              for await (const event of itemStream) {
                if (abortController.signal.aborted) {
                  adapter2.finalizeAssistantMessage();
                  return;
                }
                adapter2.processEvent(event);
                if (event.type === GeminiEventType.ToolCallRequest) {
                  itemToolCallRequests.push(event.value);
                }
                if (event.type === GeminiEventType.LoopDetected) {
                  emitLoopDetectedMessage(config2, event.value?.loopType);
                }
                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);
                }
              }
              adapter2.finalizeAssistantMessage();
              totalApiDurationMs += Date.now() - itemApiStartTime;
              if (itemToolCallRequests.length > 0) {
                const itemToolResponseParts = [];
                for (const requestInfo of itemToolCallRequests) {
                  const isAgentTool = requestInfo.name === "agent";
                  const { handler: outputUpdateHandler } = isAgentTool ? createAgentToolProgressHandler(
                    config2,
                    requestInfo.callId,
                    adapter2
                  ) : createToolProgressHandler(requestInfo, adapter2);
                  const toolResponse = await executeToolCall(
                    config2,
                    requestInfo,
                    abortController.signal,
                    {
                      outputUpdateHandler,
                      ...toolCallUpdateCallback && {
                        onToolCallsUpdate: toolCallUpdateCallback
                      }
                    }
                  );
                  if (toolResponse.error) {
                    handleToolError(
                      requestInfo.name,
                      toolResponse.error,
                      config2,
                      toolResponse.errorType || "TOOL_EXECUTION_ERROR",
                      typeof toolResponse.resultDisplay === "string" ? toolResponse.resultDisplay : void 0
                    );
                  }
                  adapter2.emitToolResult(requestInfo, toolResponse);
                  if (toolResponse.responseParts) {
                    itemToolResponseParts.push(...toolResponse.responseParts);
                  }
                  if ("modelOverride" in toolResponse) {
                    itemModelOverride = toolResponse.modelOverride;
                  }
                }
                itemMessages = [{ role: "user", parts: itemToolResponseParts }];
              } else {
                break;
              }
            }
          }, "drainOneItem");
          let drainPromise = null;
          const drainLocalQueue = /* @__PURE__ */ __name(() => {
            if (drainPromise) return drainPromise;
            const p2 = (async () => {
              while (localQueue.length > 0) {
                await drainOneItem();
              }
            })();
            drainPromise = p2;
            void p2.finally(() => {
              if (drainPromise === p2) drainPromise = null;
            });
            return p2;
          }, "drainLocalQueue");
          const scheduler = !config2.isCronEnabled() ? null : config2.getCronScheduler();
          if (scheduler && scheduler.size > 0) {
            await new Promise((resolve42, reject) => {
              const onAbort = /* @__PURE__ */ __name(() => {
                scheduler.stop();
                resolve42();
              }, "onAbort");
              if (abortController.signal.aborted) {
                onAbort();
                return;
              }
              abortController.signal.addEventListener("abort", onAbort, {
                once: true
              });
              const checkCronDone = /* @__PURE__ */ __name(() => {
                if (scheduler.size === 0 && !drainPromise) {
                  abortController.signal.removeEventListener("abort", onAbort);
                  scheduler.stop();
                  resolve42();
                }
              }, "checkCronDone");
              const onDrainError = /* @__PURE__ */ __name((err2) => {
                abortController.signal.removeEventListener("abort", onAbort);
                scheduler.stop();
                reject(err2);
              }, "onDrainError");
              scheduler.start((job) => {
                const label = job.prompt.slice(0, 40);
                localQueue.push({
                  displayText: `Cron: ${label}`,
                  modelText: job.prompt,
                  sendMessageType: SendMessageType.Cron
                });
                drainLocalQueue().then(checkCronDone, onDrainError);
              });
              checkCronDone();
            });
          }
          while (true) {
            if (abortController.signal.aborted) {
              registry3.abortAll();
              while (localQueue.length > 0) {
                emitNotificationToSdk(localQueue.shift());
              }
              await handleCancellationError(config2);
            }
            await drainLocalQueue();
            if (!registry3.hasUnfinalizedTasks() && localQueue.length === 0)
              break;
            await new Promise((r5) => setTimeout(r5, 100));
          }
          const metrics2 = uiTelemetryService.getMetrics();
          const usage2 = computeUsageFromMetrics(metrics2);
          const stats = outputFormat === OutputFormat.JSON ? uiTelemetryService.getMetrics() : void 0;
          adapter2.emitResult({
            isError: false,
            durationMs: Date.now() - startTime,
            apiDurationMs: totalApiDurationMs,
            numTurns: turnCount,
            usage: usage2,
            stats
          });
          return;
        }
      }
    } catch (error40) {
      try {
        adapter2.finalizeAssistantMessage();
      } catch {
      }
      const message = error40 instanceof Error ? error40.message : String(error40);
      const metrics2 = uiTelemetryService.getMetrics();
      const usage2 = computeUsageFromMetrics(metrics2);
      const stats = outputFormat === OutputFormat.JSON ? uiTelemetryService.getMetrics() : void 0;
      adapter2.emitResult({
        isError: true,
        durationMs: Date.now() - startTime,
        apiDurationMs: totalApiDurationMs,
        numTurns: turnCount,
        errorMessage: message,
        usage: usage2,
        stats
      });
      await handleError(error40, config2);
    } finally {
      const reg = config2.getBackgroundTaskRegistry();
      reg.setNotificationCallback(void 0);
      reg.setRegisterCallback(void 0);
      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();
init_dist4();

// packages/cli/src/nonInteractive/io/StreamJsonInputReader.ts
init_esbuild_shims();
import { createInterface } from "node:readline/promises";
import process33 from "node:process";
var StreamJsonParseError = class extends Error {
  static {
    __name(this, "StreamJsonParseError");
  }
};
var StreamJsonInputReader = class {
  static {
    __name(this, "StreamJsonInputReader");
  }
  input;
  constructor(input = process33.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 (error40) {
      if (error40 instanceof StreamJsonParseError) {
        throw error40;
      }
      const reason = error40 instanceof Error ? error40.message : String(error40);
      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();
init_dist4();
import { randomUUID as randomUUID20 } from "node:crypto";
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
var BaseController = class {
  static {
    __name(this, "BaseController");
  }
  context;
  registry;
  controllerName;
  debugLogger;
  constructor(context2, registry3, controllerName) {
    this.context = context2;
    this.registry = registry3;
    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 (error40) {
      this.registry.deregisterIncomingRequest(requestId);
      throw error40;
    }
  }
  /**
   * 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 = randomUUID20();
    return new Promise((resolve42, 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);
        }
        resolve42(response);
      }, "wrappedResolve");
      const wrappedReject = /* @__PURE__ */ __name((error40) => {
        if (signal) {
          signal.removeEventListener("abort", abortHandler);
        }
        reject(error40);
      }, "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 (error40) {
        if (signal) {
          signal.removeEventListener("abort", abortHandler);
        }
        this.registry.deregisterOutgoingRequest(requestId);
        reject(error40);
      }
    });
  }
  /**
   * Cleanup resources
   */
  cleanup() {
  }
};

// packages/cli/src/nonInteractive/control/controllers/systemController.ts
init_dist4();
var debugLogger129 = 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);
      case "get_context_usage":
        return this.handleGetContextUsage(
          payload,
          signal
        );
      default:
        throw new Error(`Unsupported request subtype in SystemController`);
    }
  }
  async handleGetContextUsage(payload, signal) {
    if (signal.aborted) {
      throw new Error("Request aborted");
    }
    try {
      const mod2 = await Promise.resolve().then(() => (init_contextCommand(), contextCommand_exports));
      if (signal.aborted) {
        throw new Error("Request aborted");
      }
      if (typeof mod2.collectContextData !== "function") {
        throw new Error("collectContextData is not available");
      }
      const showDetails = payload.show_details ?? false;
      const contextUsageItem = await mod2.collectContextData(
        this.context.config,
        showDetails
      );
      if (signal.aborted) {
        throw new Error("Request aborted");
      }
      const { type: _type2, ...contextData } = contextUsageItem;
      return {
        subtype: "get_context_usage",
        ...contextData
      };
    } catch (error40) {
      const errorMessage = error40 instanceof Error ? error40.message : "Failed to get context usage";
      debugLogger129.error(
        "[SystemController] Failed to get context usage:",
        error40
      );
      throw new Error(errorMessage);
    }
  }
  /**
   * 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 name4 = typeof wireConfig?.name === "string" && wireConfig.name.trim().length ? wireConfig.name : key;
        this.context.sdkMcpServers.add(name4);
        sdkServers[name4] = 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);
          debugLogger129.debug(
            `[SystemController] Added ${sdkServerCount} SDK MCP servers to config`
          );
        } catch (error40) {
          debugLogger129.error(
            "[SystemController] Failed to add SDK MCP servers:",
            error40
          );
        }
      }
    }
    if (payload.mcpServers && typeof payload.mcpServers === "object" && payload.mcpServers !== null) {
      const externalServers = {};
      for (const [name4, serverConfig] of Object.entries(payload.mcpServers)) {
        const normalized2 = this.normalizeMcpServerConfig(
          name4,
          serverConfig
        );
        if (normalized2) {
          externalServers[name4] = normalized2;
        }
      }
      const externalCount = Object.keys(externalServers).length;
      if (externalCount > 0) {
        try {
          this.context.config.addMcpServers(externalServers);
          debugLogger129.debug(
            `[SystemController] Added ${externalCount} external MCP servers to config`
          );
        } catch (error40) {
          debugLogger129.error(
            "[SystemController] Failed to add external MCP servers:",
            error40
          );
        }
      }
    }
    if (payload.agents && Array.isArray(payload.agents)) {
      try {
        this.context.config.setSessionSubagents(payload.agents);
        debugLogger129.debug(
          `[SystemController] Added ${payload.agents.length} session subagents to config`
        );
      } catch (error40) {
        debugLogger129.error(
          "[SystemController] Failed to add session subagents:",
          error40
        );
      }
    }
    const capabilities = this.buildControlCapabilities();
    debugLogger129.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",
      can_get_context_usage: true,
      // 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") {
      debugLogger129.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:
        debugLogger129.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) {
      debugLogger129.debug("[SystemController] Interrupt signal triggered");
    }
    debugLogger129.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);
      debugLogger129.info(`[SystemController] Model switched to: ${model}`);
      return {
        subtype: "set_model",
        model
      };
    } catch (error40) {
      const errorMessage = error40 instanceof Error ? error40.message : "Failed to set model";
      debugLogger129.error(
        `[SystemController] Failed to set model ${model}:`,
        error40
      );
      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,
        "non_interactive"
      );
      if (signal.aborted) {
        return [];
      }
      return commands.map((cmd) => cmd.name).sort();
    } catch (error40) {
      if (signal.aborted) {
        return [];
      }
      debugLogger129.error(
        "[SystemController] Failed to load slash commands:",
        error40
      );
      return [];
    }
  }
};

// packages/cli/src/nonInteractive/control/controllers/permissionController.ts
init_esbuild_shims();
init_dist4();
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 (error40) {
      behavior = "deny";
      message = error40 instanceof Error ? `Failed to evaluate tool permission: ${error40.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 registry3 = registryProvider.getToolRegistry();
        if (registry3 && typeof registry3.getTool === "function" && !registry3.getTool(toolName)) {
          return {
            allowed: false,
            message: `Tool "${toolName}" is not registered.`
          };
        }
      }
      return { allowed: true };
    } catch (error40) {
      return {
        allowed: false,
        message: `Failed to check tool registry: ${error40 instanceof Error ? error40.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 (error40) {
      this.debugLogger.error(
        "[PermissionController] Outgoing permission failed:",
        error40
      );
      const errorMessage = error40 instanceof Error ? error40.message : String(error40);
      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
init_dist4();
var debugLogger130 = 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 (error40) {
      const errorMessage = error40 instanceof Error ? error40.message : String(error40);
      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) {
      debugLogger130.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");
        debugLogger130.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");
        }
      }
      debugLogger130.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) {
      debugLogger130.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() {
    debugLogger130.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, resolve42, reject, timeoutId) {
    this.pendingOutgoingRequests.set(requestId, {
      controller,
      resolve: resolve42,
      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) {
        debugLogger130.warn(
          `[ControlDispatcher] Timeout waiting for ${this.pendingIncomingRequests.size} pending incoming requests`
        );
        break;
      }
      await new Promise((resolve42) => setTimeout(resolve42, pollIntervalMs));
    }
    if (this.pendingIncomingRequests.size === 0) {
      debugLogger130.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":
      case "get_context_usage":
        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, error40) {
    const controlResponse = {
      type: "control_response",
      response: {
        subtype: "error",
        request_id: requestId,
        error: error40
      }
    };
    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 debugLogger131 = 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((resolve42, reject) => {
      this.initializationResolve = () => {
        resolve42();
        this.initializationResolve = null;
        this.initializationReject = null;
      };
      this.initializationReject = (error40) => {
        reject(error40);
        this.initializationResolve = null;
        this.initializationReject = null;
      };
    });
  }
  getNextPromptId() {
    this.promptIdCounter++;
    return `${this.sessionId}########${this.promptIdCounter}`;
  }
  async ensureConfigInitialized(options2) {
    if (this.configInitialized) {
      return;
    }
    debugLogger131.debug("[Session] Initializing config");
    try {
      await this.config.initialize(options2);
      this.configInitialized = true;
    } catch (error40) {
      debugLogger131.error("[Session] Failed to initialize config:", error40);
      throw error40;
    }
  }
  /**
   * Mark initialization as complete
   */
  completeInitialization() {
    if (this.initializationResolve) {
      debugLogger131.debug("[Session] Initialization complete");
      this.initializationResolve();
      this.initializationResolve = null;
      this.initializationReject = null;
    }
  }
  /**
   * Mark initialization as failed
   */
  failInitialization(error40) {
    if (this.initializationReject) {
      debugLogger131.error("[Session] Initialization failed:", error40);
      this.initializationReject(error40);
      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;
      }
      debugLogger131.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 (error40) {
      debugLogger131.error("[Session] SDK mode initialization failed:", error40);
      this.failInitialization(
        error40 instanceof Error ? error40 : new Error(String(error40))
      );
    }
  }
  /**
   * 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 (error40) {
      debugLogger131.error("[Session] Direct mode initialization failed:", error40);
      this.failInitialization(
        error40 instanceof Error ? error40 : new Error(String(error40))
      );
    }
  }
  /**
   * 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) {
      debugLogger131.warn("[Session] Control system not enabled");
      return;
    }
    void dispatcher.dispatch(request4).catch((error40) => {
      debugLogger131.error("[Session] Control request dispatch error:", error40);
    });
  }
  /**
   * 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) {
      debugLogger131.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 (error40) {
      debugLogger131.error("[Session] Query execution error:", error40);
    }
  }
  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 (error40) {
        debugLogger131.error("[Session] Error processing user message:", error40);
        this.emitErrorResult(error40);
      }
    }
  }
  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(error40, numTurns = 0, durationMs = 0, apiDurationMs = 0) {
    const message = error40 instanceof Error ? error40.message : String(error40);
    this.outputAdapter.emitResult({
      isError: true,
      errorMessage: message,
      durationMs,
      apiDurationMs,
      numTurns,
      usage: void 0
    });
  }
  handleInterrupt() {
    debugLogger131.info("[Session] Interrupt requested");
    this.abortController.abort();
  }
  setupSignalHandlers() {
    this.shutdownHandler = () => {
      debugLogger131.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 (error40) {
      debugLogger131.error(
        "[Session] Initialization error during shutdown:",
        error40
      );
    }
    if (this.dispatcher) {
      const pendingCount = this.dispatcher.getPendingIncomingRequestCount();
      if (pendingCount > 0) {
        debugLogger131.debug(
          `[Session] Waiting for ${pendingCount} pending control request handlers`
        );
      }
      await this.dispatcher.waitForPendingIncomingRequests();
    }
    while (this.processingPromise) {
      debugLogger131.debug("[Session] Waiting for user message processing");
      try {
        await this.processingPromise;
      } catch (error40) {
        debugLogger131.error("[Session] Error in user message processing:", error40);
      }
    }
  }
  async shutdown() {
    debugLogger131.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 {
      debugLogger131.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)) {
            debugLogger131.warn(
              "[Session] Unknown message type:",
              JSON.stringify(message, null, 2)
            );
          }
          if (this.isShuttingDown) {
            break;
          }
        }
      } catch (streamError) {
        debugLogger131.error("[Session] Stream reading error:", streamError);
        throw streamError;
      }
      if (this.dispatcher) {
        this.dispatcher.markInputClosed();
      }
      await this.waitForAllPendingWork();
      await this.shutdown();
    } catch (error40) {
      debugLogger131.error("[Session] Error:", error40);
      await this.shutdown();
      throw error40;
    } finally {
      this.cleanupSignalHandlers();
    }
  }
};
function extractUserMessageText(message) {
  const content = message.message.content;
  if (typeof content === "string") {
    return content;
  }
  if (Array.isArray(content)) {
    const parts2 = 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 parts2.length > 0 ? parts2.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_react189 = __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_react33 = __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;
  }, []);
  const truncateToItem = (0, import_react28.useCallback)((itemId) => {
    setHistory((prev) => {
      const index = prev.findIndex((h3) => h3.id === itemId);
      return index === -1 ? prev : prev.slice(0, index);
    });
  }, []);
  return (0, import_react28.useMemo)(
    () => ({
      history,
      addItem,
      updateItem,
      clearItems,
      loadHistory,
      truncateToItem
    }),
    [history, addItem, updateItem, clearItems, loadHistory, truncateToItem]
  );
}
__name(useHistory, "useHistory");

// packages/cli/src/ui/hooks/useIdeTrustListener.ts
init_esbuild_shims();
var import_react30 = __toESM(require_react(), 1);
init_dist4();

// 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);
init_dist4();
init_i18n();
function useCodingPlanUpdates(settings, config2, addItem) {
  const [updateRequest, setUpdateRequest] = (0, import_react31.useState)();
  const executeUpdate = (0, import_react31.useCallback)(
    async (region = CodingPlanRegion.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 } = getCodingPlanConfig(region);
        const newConfigs = template.map((templateConfig) => ({
          ...templateConfig,
          envKey: CODING_PLAN_ENV_KEY
        }));
        const updatedConfigs = [
          ...newConfigs,
          ...nonCodingPlanConfigs
        ];
        const previousModel = config2.getModel();
        const previousModelStillAvailable = newConfigs.some(
          (cfg) => cfg.id === previousModel
        );
        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();
        if (previousModelStillAvailable && activeModel === previousModel) {
          addItem(
            {
              type: "info",
              text: t4("{{region}} configuration updated successfully.", {
                region: t4("Alibaba Cloud Coding Plan")
              })
            },
            Date.now()
          );
        } else {
          addItem(
            {
              type: "info",
              text: t4(
                '{{region}} configuration updated successfully. Model switched to "{{model}}".',
                { region: t4("Alibaba Cloud Coding Plan"), model: activeModel }
              )
            },
            Date.now()
          );
        }
        addItem(
          {
            type: "info",
            text: t4(
              "Tip: Use /model to switch between available Coding Plan models."
            )
          },
          Date.now()
        );
        return true;
      } catch (error40) {
        const errorMessage = error40 instanceof Error ? error40.message : String(error40);
        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 ?? CodingPlanRegion.CHINA;
    const savedVersion = mergedSettings.codingPlan?.version;
    if (!savedVersion) {
      return;
    }
    const currentVersion2 = getCodingPlanConfig(region).version;
    if (savedVersion !== currentVersion2) {
      setUpdateRequest({
        prompt: t4(
          "New model configurations are available for {{region}}. Update now?",
          { region: t4("Alibaba Cloud Coding Plan") }
        ),
        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/hooks/useArenaCommand.ts
init_esbuild_shims();
var import_react32 = __toESM(require_react(), 1);
function useArenaCommand() {
  const [activeArenaDialog, setActiveArenaDialog] = (0, import_react32.useState)(null);
  const openArenaDialog = (0, import_react32.useCallback)(
    (type) => {
      setActiveArenaDialog(type);
    },
    []
  );
  const closeArenaDialog = (0, import_react32.useCallback)(() => {
    setActiveArenaDialog(null);
  }, []);
  return {
    activeArenaDialog,
    openArenaDialog,
    closeArenaDialog
  };
}
__name(useArenaCommand, "useArenaCommand");

// packages/cli/src/ui/contexts/UIStateContext.tsx
var UIStateContext = (0, import_react33.createContext)(null);
var useUIState = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react33.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_react34 = __toESM(require_react(), 1);
var StreamingContext = (0, import_react34.createContext)(
  void 0
);
var useStreamingContext = /* @__PURE__ */ __name(() => {
  const context2 = import_react34.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_react73 = __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 = stripAnsi2(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 i4 = 0; i4 < str2.length; i4++) {
    if (str2.charCodeAt(i4) > 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, start2, end) {
  const arr = toCodePoints(str2).slice(start2, end);
  return arr.join("");
}
__name(cpSlice, "cpSlice");
function stripUnsafeCharacters(str2) {
  const strippedAnsi = stripAnsi2(str2);
  const strippedVT = stripVTControlCharacters(strippedAnsi);
  return toCodePoints(strippedVT).filter((char) => {
    const code2 = char.codePointAt(0);
    if (code2 === void 0) return false;
    if (code2 === 9 || 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");
function sliceTextByVisualHeight(text, maxHeight, maxWidth, options2 = {}) {
  if (maxHeight === void 0) {
    return { text, hiddenLinesCount: 0 };
  }
  const targetMaxHeight = Math.max(
    Math.round(maxHeight),
    options2.minHeight ?? 1
  );
  const visibleContentHeight = Math.max(
    1,
    targetMaxHeight - (options2.reservedRows ?? 0)
  );
  const visualWidth = Math.max(1, Math.floor(maxWidth));
  const overflowDirection = options2.overflowDirection ?? "top";
  const visibleLines = [];
  let visualLineCount = 0;
  let currentLine = "";
  let currentLineWidth = 0;
  const appendVisibleLine = /* @__PURE__ */ __name((line) => {
    visualLineCount += 1;
    if (overflowDirection === "bottom") {
      if (visibleLines.length < visibleContentHeight) {
        visibleLines.push(line);
      }
      return;
    }
    visibleLines.push(line);
    if (visibleLines.length > visibleContentHeight) {
      visibleLines.shift();
    }
  }, "appendVisibleLine");
  const flushCurrentLine = /* @__PURE__ */ __name(() => {
    appendVisibleLine(currentLine);
    currentLine = "";
    currentLineWidth = 0;
  }, "flushCurrentLine");
  for (const char of toCodePoints(text)) {
    if (char === "\n") {
      flushCurrentLine();
      continue;
    }
    const charWidth = Math.max(getCachedStringWidth(char), 1);
    if (currentLineWidth > 0 && currentLineWidth + charWidth > visualWidth) {
      flushCurrentLine();
    }
    currentLine += char;
    currentLineWidth += charWidth;
  }
  flushCurrentLine();
  if (visualLineCount <= visibleContentHeight) {
    return { text, hiddenLinesCount: 0 };
  }
  return {
    text: visibleLines.join("\n"),
    hiddenLinesCount: visualLineCount - visibleContentHeight
  };
}
__name(sliceTextByVisualHeight, "sliceTextByVisualHeight");
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 i4 = 0; i4 < obj.length; i4++) {
      const value = obj[i4];
      const escapedValue = escapeAnsiCtrlCodes(value);
      if (escapedValue !== value) {
        if (newArr === null) {
          newArr = [...obj];
        }
        newArr[i4] = 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");
var SENSITIVE_PATTERNS = [
  // API keys with common prefixes
  {
    pattern: /(sk-[a-zA-Z0-9]{20,})/g,
    replacement: "sk-***REDACTED***"
  },
  {
    pattern: /(api[_-]?key[_-]?[=:]\s*)[a-zA-Z0-9_-]{20,}/gi,
    replacement: "$1***REDACTED***"
  },
  // Bearer tokens
  {
    pattern: /(Bearer\s+)[a-zA-Z0-9._-]+/gi,
    replacement: "$1***REDACTED***"
  },
  // Generic tokens
  {
    pattern: /(token[_-]?[=:]\s*)[a-zA-Z0-9._-]{10,}/gi,
    replacement: "$1***REDACTED***"
  },
  // Passwords in connection strings or assignments
  {
    pattern: /(password[_-]?[=:]\s*)[^\s]+/gi,
    replacement: "$1***REDACTED***"
  },
  {
    pattern: /(pwd[_-]?[=:]\s*)[^\s]+/gi,
    replacement: "$1***REDACTED***"
  },
  // AWS keys
  {
    pattern: /(AKIA[A-Z0-9]{16})/g,
    replacement: "***REDACTED***"
  },
  // Generic secret patterns
  {
    pattern: /(secret[_-]?[=:]\s*)[a-zA-Z0-9._-]{10,}/gi,
    replacement: "$1***REDACTED***"
  }
];
function sanitizeSensitiveText(text, maxLength = 200) {
  let result = text;
  for (const { pattern, replacement } of SENSITIVE_PATTERNS) {
    result = result.replace(pattern, replacement);
  }
  if (result.length > maxLength) {
    if (maxLength <= 3) {
      return result.slice(0, maxLength);
    }
    return result.slice(0, maxLength - 3) + "...";
  }
  return result;
}
__name(sanitizeSensitiveText, "sanitizeSensitiveText");

// packages/cli/src/ui/components/messages/ConversationMessages.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/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/utils/CodeColorizer.tsx
init_esbuild_shims();
var import_react37 = __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 json2(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(json2, "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(name4, begin, relevance) {
    return {
      className: name4,
      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(...args2) {
  const joined = args2.map((x3) => source(x3)).join("");
  return joined;
}
__name(concat, "concat");
function stripOptionsFromArgs(args2) {
  const opts = args2[args2.length - 1];
  if (typeof opts === "object" && opts.constructor === Object) {
    args2.splice(args2.length - 1, 1);
    return opts;
  } else {
    return {};
  }
}
__name(stripOptionsFromArgs, "stripOptionsFromArgs");
function either(...args2) {
  const opts = stripOptionsFromArgs(args2);
  const joined = "(" + (opts.capture ? "" : "?:") + args2.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 yaml2(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(yaml2, "yaml");

// node_modules/lowlight/lib/common.js
var grammars = {
  arduino,
  bash,
  c: c3,
  cpp,
  csharp,
  css,
  diff: diff3,
  go,
  graphql,
  ini,
  java,
  javascript,
  json: json2,
  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: yaml2
};

// 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 name4 = subset[index];
      if (!high.getLanguage(name4)) continue;
      const current = highlight(name4, 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 name4;
      for (name4 in grammarsOrName) {
        if (Object.hasOwn(grammarsOrName, name4)) {
          high.registerLanguage(name4, grammarsOrName[name4]);
        }
      }
    }
  }
  __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, name4) {
    const current = this.stack[this.stack.length - 1];
    const results = (
      /** @type {Array<ElementContent>} */
      other2.root.children
    );
    if (name4) {
      current.children.push({
        type: "element",
        tagName: "span",
        properties: { className: [name4] },
        children: results
      });
    } else {
      current.children.push(...results);
    }
  }
  /**
   * @param {string} name
   *   Name to add.
   * @returns {undefined}
   *   Nothing.
   */
  openNode(name4) {
    const self2 = this;
    const className = name4.split(".").map(function(d2, i4) {
      return i4 ? d2 + "_".repeat(i4) : 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_react36 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/OverflowContext.tsx
init_esbuild_shims();
var import_react35 = __toESM(require_react(), 1);
var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
var OverflowStateContext = (0, import_react35.createContext)(
  void 0
);
var OverflowActionsContext = (0, import_react35.createContext)(
  void 0
);
var useOverflowState = /* @__PURE__ */ __name(() => (0, import_react35.useContext)(OverflowStateContext), "useOverflowState");
var useOverflowActions = /* @__PURE__ */ __name(() => (0, import_react35.useContext)(OverflowActionsContext), "useOverflowActions");
var OverflowProvider = /* @__PURE__ */ __name(({
  children
}) => {
  const [overflowingIds, setOverflowingIds] = (0, import_react35.useState)(/* @__PURE__ */ new Set());
  const addOverflowingId = (0, import_react35.useCallback)((id) => {
    setOverflowingIds((prevIds) => {
      if (prevIds.has(id)) {
        return prevIds;
      }
      const newIds = new Set(prevIds);
      newIds.add(id);
      return newIds;
    });
  }, []);
  const removeOverflowingId = (0, import_react35.useCallback)((id) => {
    setOverflowingIds((prevIds) => {
      if (!prevIds.has(id)) {
        return prevIds;
      }
      const newIds = new Set(prevIds);
      newIds.delete(id);
      return newIds;
    });
  }, []);
  const stateValue = (0, import_react35.useMemo)(
    () => ({
      overflowingIds
    }),
    [overflowingIds]
  );
  const actionsValue = (0, import_react35.useMemo)(
    () => ({
      addOverflowingId,
      removeOverflowingId
    }),
    [addOverflowingId, removeOverflowingId]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(OverflowStateContext.Provider, { value: stateValue, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(OverflowActionsContext.Provider, { value: actionsValue, children }) });
}, "OverflowProvider");

// packages/cli/src/ui/components/shared/MaxSizedBox.tsx
init_dist4();
var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
var enableDebugLog = false;
var debugLogger132 = 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_react36.default.isValidElement(element)) {
    debugLogger132.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 (error40) {
    debugLogger132.error("Error while trying to get file name:", error40);
  }
  debugLogger132.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_react36.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_react36.default.isValidElement(element)) {
      return;
    }
    if (element.type === import_react36.Fragment) {
      import_react36.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_react36.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_react36.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_runtime2.jsx)(Box_default, { children: line.length > 0 ? line.map((segment, segIndex) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text3, { ...segment.props, children: segment.text }, segIndex)) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text3, { children: " " }) }, index));
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(Box_default, { flexDirection: "column", width: maxWidth, flexShrink: 0, children: [
    totalHiddenLines > 0 && overflowDirection === "top" && /* @__PURE__ */ (0, import_jsx_runtime2.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_runtime2.jsxs)(Text3, { color: theme.text.secondary, wrap: "truncate", children: [
      "... last ",
      totalHiddenLines,
      " line",
      totalHiddenLines === 1 ? "" : "s",
      " ",
      "hidden ..."
    ] })
  ] });
}, "MaxSizedBox");
function visitBoxRow(element) {
  if (!import_react36.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_react36.default.isValidElement(element2)) {
      debugReportError("Invalid element.", element2);
      return;
    }
    if (element2.type === import_react36.Fragment) {
      import_react36.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_react36.default.Children.forEach(
      children,
      (child) => visitRowChild(child, mergedProps)
    );
  }
  __name(visitRowChild, "visitRowChild");
  import_react36.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
init_dist4();
var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
var lowlight = createLowlight(grammars);
var debugLogger133 = createDebugLogger("CODE_COLORIZER");
function renderHastNode(node, theme2, inheritedColor) {
  if (node.type === "text") {
    const color = inheritedColor || theme2.defaultColor;
    return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text3, { color, children: node.value });
  }
  if (node.type === "element") {
    const nodeClasses = node.properties?.["className"] || [];
    let elementColor = void 0;
    for (let i4 = nodeClasses.length - 1; i4 >= 0; i4--) {
      const color = theme2.getInkColor(nodeClasses[i4]);
      if (color) {
        elementColor = color;
        break;
      }
    }
    const colorToPassDown = elementColor || inheritedColor;
    const children = node.children?.map(
      (child, index) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react37.default.Fragment, { children: renderHastNode(child, theme2, colorToPassDown) }, index)
    );
    return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react37.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_runtime3.jsx)(import_react37.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, tabWidth = 4) {
  const codeToHighlight = code2.replace(/\n$/, "").replace(/\t/g, " ".repeat(tabWidth));
  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_runtime3.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_runtime3.jsxs)(Box_default, { children: [
            showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text3, { color: activeTheme.colors.Gray, children: `${String(index + 1 + hiddenLinesCount).padStart(
              padWidth,
              " "
            )} ` }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text3, { color: activeTheme.defaultColor, wrap: "wrap", children: contentToRender })
          ] }, index);
        })
      }
    );
  } catch (error40) {
    debugLogger133.error(
      `[colorizeCode] Error highlighting code for language "${language}":`,
      error40
    );
    const lines = codeToHighlight.split("\n");
    const padWidth = String(lines.length).length;
    return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
      MaxSizedBox,
      {
        maxHeight: availableHeight,
        maxWidth,
        overflowDirection: "top",
        children: lines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(Box_default, { children: [
          showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text3, { color: activeTheme.defaultColor, children: `${String(index + 1).padStart(padWidth, " ")} ` }),
          /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text3, { color: activeTheme.colors.Gray, children: line })
        ] }, index))
      }
    );
  }
}
__name(colorizeCode, "colorizeCode");

// packages/cli/src/ui/utils/TableRenderer.tsx
init_esbuild_shims();
init_strip_ansi();
var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
var MIN_COLUMN_WIDTH = 3;
var MAX_ROW_LINES = 4;
var SAFETY_MARGIN = 4;
var INK_COLOR_TO_ANSI = {
  black: 30,
  red: 31,
  green: 32,
  yellow: 33,
  blue: 34,
  magenta: 35,
  cyan: 36,
  white: 37,
  gray: 90,
  grey: 90,
  blackbright: 90,
  redbright: 91,
  greenbright: 92,
  yellowbright: 93,
  bluebright: 94,
  magentabright: 95,
  cyanbright: 96,
  whitebright: 97
};
var HEX_COLOR_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
function getColorCode(color) {
  if (!color) return "";
  if (color.startsWith("#")) {
    if (!HEX_COLOR_RE.test(color)) return "";
    const hex = color.length === 4 ? color[1] + color[1] + color[2] + color[2] + color[3] + color[3] : color.slice(1);
    const r5 = parseInt(hex.slice(0, 2), 16);
    const g2 = parseInt(hex.slice(2, 4), 16);
    const b2 = parseInt(hex.slice(4, 6), 16);
    return `\x1B[38;2;${r5};${g2};${b2}m`;
  }
  const code2 = INK_COLOR_TO_ANSI[color.toLowerCase()];
  if (code2 !== void 0) return `\x1B[${code2}m`;
  return "";
}
__name(getColorCode, "getColorCode");
function applyColor(text, color) {
  const code2 = getColorCode(color);
  if (!code2) return text;
  return `${code2}${text}\x1B[39m`;
}
__name(applyColor, "applyColor");
function recolorAfterResets(text, colorCode) {
  const fgReset = "\x1B[39m";
  const fullReset = "\x1B[0m";
  return text.split(fgReset).join(fgReset + colorCode).split(fullReset).join(fullReset + colorCode);
}
__name(recolorAfterResets, "recolorAfterResets");
var ansiFmt = {
  bold: /* @__PURE__ */ __name((t5) => `\x1B[1m${t5}\x1B[22m`, "bold"),
  italic: /* @__PURE__ */ __name((t5) => `\x1B[3m${t5}\x1B[23m`, "italic"),
  underline: /* @__PURE__ */ __name((t5) => `\x1B[4m${t5}\x1B[24m`, "underline"),
  strikethrough: /* @__PURE__ */ __name((t5) => `\x1B[9m${t5}\x1B[29m`, "strikethrough")
};
function renderMarkdownToAnsi(text) {
  const inlineRegex = /(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g;
  let result = "";
  let lastIndex = 0;
  let match2;
  while ((match2 = inlineRegex.exec(text)) !== null) {
    result += text.slice(lastIndex, match2.index);
    const fullMatch = match2[0];
    let rendered = null;
    if (fullMatch.startsWith("**") && fullMatch.endsWith("**") && fullMatch.length > 4) {
      rendered = ansiFmt.bold(fullMatch.slice(2, -2));
    } else if (fullMatch.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)
    )) {
      rendered = ansiFmt.italic(fullMatch.slice(1, -1));
    } else if (fullMatch.startsWith("~~") && fullMatch.endsWith("~~") && fullMatch.length > 4) {
      rendered = ansiFmt.strikethrough(fullMatch.slice(2, -2));
    } else if (fullMatch.startsWith("`") && fullMatch.endsWith("`") && fullMatch.length > 1) {
      const codeMatch = fullMatch.match(/^(`+)(.+?)\1$/s);
      if (codeMatch?.[2]) {
        rendered = applyColor(codeMatch[2], theme.text.code);
      }
    } else if (fullMatch.startsWith("[") && fullMatch.includes("](") && fullMatch.endsWith(")")) {
      const linkMatch = fullMatch.match(/\[(.*?)\]\((.*?)\)/);
      if (linkMatch) {
        rendered = `${linkMatch[1]} ${applyColor(`(${linkMatch[2]})`, theme.text.link)}`;
      }
    } else if (fullMatch.startsWith("<u>") && fullMatch.endsWith("</u>") && fullMatch.length > 7) {
      rendered = ansiFmt.underline(fullMatch.slice(3, -4));
    } else if (/^https?:\/\//.test(fullMatch)) {
      rendered = applyColor(fullMatch, theme.text.link);
    }
    result += rendered ?? fullMatch;
    lastIndex = inlineRegex.lastIndex;
  }
  result += text.slice(lastIndex);
  return result;
}
__name(renderMarkdownToAnsi, "renderMarkdownToAnsi");
function padAligned(content, displayWidth, targetWidth, align2) {
  const padding = Math.max(0, targetWidth - displayWidth);
  if (align2 === "center") {
    const leftPad = Math.floor(padding / 2);
    return " ".repeat(leftPad) + content + " ".repeat(padding - leftPad);
  }
  if (align2 === "right") {
    return " ".repeat(padding) + content;
  }
  return content + " ".repeat(padding);
}
__name(padAligned, "padAligned");
function wrapText2(text, width, options2) {
  if (width <= 0) return [text];
  const trimmedText = text.trimEnd();
  const wrapped = wrapAnsi(trimmedText, width, {
    hard: options2?.hard ?? false,
    trim: false,
    wordWrap: true
  });
  const lines = wrapped.split("\n");
  while (lines.length > 1 && lines[lines.length - 1].length === 0) {
    lines.pop();
  }
  return lines.length > 0 ? lines : [""];
}
__name(wrapText2, "wrapText");
var TableRenderer = /* @__PURE__ */ __name(({
  headers,
  rows,
  contentWidth,
  aligns
}) => {
  const colCount = headers.length;
  if (colCount === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Box_default, {});
  }
  const computeMetrics = /* @__PURE__ */ __name((text) => {
    const rendered = renderMarkdownToAnsi(text);
    const visible = stripAnsi2(rendered);
    const words = visible.split(/\s+/).filter((w2) => w2.length > 0);
    return {
      rendered,
      renderedWidth: getCachedStringWidth(visible),
      minWordWidth: words.length > 0 ? Math.max(
        ...words.map((w2) => getCachedStringWidth(w2)),
        MIN_COLUMN_WIDTH
      ) : MIN_COLUMN_WIDTH
    };
  }, "computeMetrics");
  const headerMetrics = headers.map((h3) => computeMetrics(h3));
  const rowMetrics = rows.map(
    (row) => Array.from({ length: colCount }, (_2, i4) => computeMetrics(row[i4] || ""))
  );
  const minColumnWidths = headers.map((_2, colIndex) => {
    let maxMin = headerMetrics[colIndex].minWordWidth;
    for (const row of rowMetrics) {
      maxMin = Math.max(maxMin, row[colIndex].minWordWidth);
    }
    return maxMin;
  });
  const idealWidths = headers.map((_2, colIndex) => {
    let maxIdeal = Math.max(
      headerMetrics[colIndex].renderedWidth,
      MIN_COLUMN_WIDTH
    );
    for (const row of rowMetrics) {
      maxIdeal = Math.max(maxIdeal, row[colIndex].renderedWidth);
    }
    return maxIdeal;
  });
  const borderOverhead = 1 + colCount * 3;
  const availableWidth = Math.max(
    contentWidth - borderOverhead - SAFETY_MARGIN,
    colCount * MIN_COLUMN_WIDTH
  );
  const totalMin = minColumnWidths.reduce((sum, w2) => sum + w2, 0);
  const totalIdeal = idealWidths.reduce((sum, w2) => sum + w2, 0);
  let needsHardWrap = false;
  let columnWidths;
  if (totalIdeal <= availableWidth) {
    columnWidths = idealWidths;
  } else if (totalMin <= availableWidth) {
    const extraSpace = availableWidth - totalMin;
    const overflows = idealWidths.map(
      (ideal, i4) => ideal - minColumnWidths[i4]
    );
    const totalOverflow = overflows.reduce((sum, o3) => sum + o3, 0);
    columnWidths = minColumnWidths.map((min, i4) => {
      if (totalOverflow === 0) return min;
      const extra = Math.floor(overflows[i4] / totalOverflow * extraSpace);
      return min + extra;
    });
  } else {
    needsHardWrap = true;
    const scaleFactor = availableWidth / totalMin;
    columnWidths = minColumnWidths.map(
      (w2) => Math.max(Math.floor(w2 * scaleFactor), MIN_COLUMN_WIDTH)
    );
    let excess = columnWidths.reduce((s5, w2) => s5 + w2, 0) - availableWidth;
    while (excess > 0) {
      const maxW = Math.max(...columnWidths);
      if (maxW <= MIN_COLUMN_WIDTH) break;
      const idx = columnWidths.indexOf(maxW);
      const reduction = Math.min(excess, maxW - MIN_COLUMN_WIDTH);
      columnWidths[idx] = maxW - reduction;
      excess -= reduction;
    }
  }
  function calculateMaxRowLines() {
    let maxLines = 1;
    for (let i4 = 0; i4 < colCount; i4++) {
      const wrapped = wrapText2(headerMetrics[i4].rendered, columnWidths[i4], {
        hard: needsHardWrap
      });
      maxLines = Math.max(maxLines, wrapped.length);
    }
    for (const row of rowMetrics) {
      for (let i4 = 0; i4 < colCount; i4++) {
        const wrapped = wrapText2(row[i4].rendered, columnWidths[i4], {
          hard: needsHardWrap
        });
        maxLines = Math.max(maxLines, wrapped.length);
      }
    }
    return maxLines;
  }
  __name(calculateMaxRowLines, "calculateMaxRowLines");
  const maxRowLines = calculateMaxRowLines();
  const useVerticalFormat = maxRowLines > MAX_ROW_LINES;
  const getAlign = /* @__PURE__ */ __name((colIndex) => aligns?.[colIndex] ?? "left", "getAlign");
  function renderBorderLine(type) {
    const [left3, mid, cross, right3] = {
      top: ["\u250C", "\u2500", "\u252C", "\u2510"],
      middle: ["\u251C", "\u2500", "\u253C", "\u2524"],
      bottom: ["\u2514", "\u2500", "\u2534", "\u2518"]
    }[type];
    let line = left3;
    columnWidths.forEach((width, colIndex) => {
      line += mid.repeat(width + 2);
      line += colIndex < columnWidths.length - 1 ? cross : right3;
    });
    return applyColor(line, theme.border.default);
  }
  __name(renderBorderLine, "renderBorderLine");
  function renderRowLines(renderedCells, isHeader) {
    const cellLines = renderedCells.map(
      (cell, colIndex) => wrapText2(cell, columnWidths[colIndex], { hard: needsHardWrap })
    );
    const maxLines = Math.max(...cellLines.map((l3) => l3.length), 1);
    const offsets = cellLines.map((l3) => Math.floor((maxLines - l3.length) / 2));
    const borderPipe = applyColor("\u2502", theme.border.default);
    const result = [];
    for (let lineIdx = 0; lineIdx < maxLines; lineIdx++) {
      let line = borderPipe;
      for (let colIndex = 0; colIndex < colCount; colIndex++) {
        const lines = cellLines[colIndex];
        const offset = offsets[colIndex];
        const contentLineIdx = lineIdx - offset;
        const lineText = contentLineIdx >= 0 && contentLineIdx < lines.length ? lines[contentLineIdx] : "";
        const width = columnWidths[colIndex];
        const displayWidth = getCachedStringWidth(stripAnsi2(lineText));
        const align2 = aligns?.[colIndex] != null ? getAlign(colIndex) : isHeader ? "center" : "left";
        const padded = padAligned(lineText, displayWidth, width, align2);
        if (isHeader) {
          const linkCode = getColorCode(theme.text.link);
          const recolored = linkCode ? recolorAfterResets(padded, linkCode) : padded;
          const styledPadded = applyColor(
            ansiFmt.bold(recolored),
            theme.text.link
          );
          line += " " + styledPadded + " " + borderPipe;
        } else {
          const primaryCode = getColorCode(theme.text.primary);
          const recolored = primaryCode ? recolorAfterResets(padded, primaryCode) : padded;
          const styledCell = primaryCode ? applyColor(recolored, theme.text.primary) : recolored;
          line += " " + styledCell + " " + borderPipe;
        }
      }
      result.push(line);
    }
    return result;
  }
  __name(renderRowLines, "renderRowLines");
  function renderVerticalFormat() {
    const lines = [];
    const separatorWidth = Math.max(Math.min(contentWidth - 1, 40), 0);
    const separator = separatorWidth > 0 ? "\u2500".repeat(separatorWidth) : "";
    rowMetrics.forEach((row, rowIndex) => {
      if (rowIndex > 0) {
        lines.push(separator);
      }
      for (let colIndex = 0; colIndex < colCount; colIndex++) {
        const rawLabel = headers[colIndex] ?? `Column ${colIndex + 1}`;
        const label = renderMarkdownToAnsi(rawLabel);
        const value = row[colIndex].rendered.trim().replace(/\n+/g, " ").replace(/\s+/g, " ").trim();
        const linkCode = getColorCode(theme.text.link);
        const recoloredLabel = linkCode ? recolorAfterResets(`${label}:`, linkCode) : `${label}:`;
        const primaryCode = getColorCode(theme.text.primary);
        const styledValue = primaryCode ? applyColor(
          recolorAfterResets(value, primaryCode),
          theme.text.primary
        ) : value;
        lines.push(
          `${applyColor(ansiFmt.bold(recoloredLabel), theme.text.link)} ${styledValue}`
        );
      }
    });
    return lines.join("\n");
  }
  __name(renderVerticalFormat, "renderVerticalFormat");
  if (useVerticalFormat) {
    return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Box_default, { marginY: 1, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text3, { children: renderVerticalFormat() }) });
  }
  const headerRendered = headerMetrics.map((m3) => m3.rendered);
  const tableLines = [];
  tableLines.push(renderBorderLine("top"));
  tableLines.push(...renderRowLines(headerRendered, true));
  tableLines.push(renderBorderLine("middle"));
  rowMetrics.forEach((row, rowIndex) => {
    tableLines.push(
      ...renderRowLines(
        row.map((m3) => m3.rendered),
        false
      )
    );
    if (rowIndex < rows.length - 1) {
      tableLines.push(renderBorderLine("middle"));
    }
  });
  tableLines.push(renderBorderLine("bottom"));
  const maxLineWidth = Math.max(
    ...tableLines.map((line) => getCachedStringWidth(stripAnsi2(line)))
  );
  if (maxLineWidth > contentWidth - SAFETY_MARGIN) {
    return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Box_default, { marginY: 1, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text3, { children: renderVerticalFormat() }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Box_default, { flexDirection: "column", marginY: 1, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text3, { children: tableLines.join("\n") }) });
}, "TableRenderer");

// packages/cli/src/ui/utils/InlineMarkdownRenderer.tsx
init_esbuild_shims();
var import_react38 = __toESM(require_react(), 1);
init_dist4();
var import_jsx_runtime5 = __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 debugLogger134 = createDebugLogger("INLINE_MARKDOWN");
var RenderInlineInternal = /* @__PURE__ */ __name(({
  text,
  textColor = theme.text.primary
}) => {
  if (!/[*_~`<[https?:]/.test(text)) {
    return /* @__PURE__ */ (0, import_jsx_runtime5.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_runtime5.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_runtime5.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_runtime5.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_runtime5.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_runtime5.jsx)(Text3, { color: theme.text.code, children: codeMatch[2] }, key);
        }
      } else if (fullMatch.startsWith("[") && fullMatch.includes("](") && fullMatch.endsWith(")")) {
        const linkMatch = fullMatch.match(/\[(.*?)\]\((.*?)\)/);
        if (linkMatch) {
          const linkText = linkMatch[1];
          const url3 = linkMatch[2];
          renderedNode = /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(Text3, { children: [
            linkText,
            /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(Text3, { color: theme.text.link, children: [
              " (",
              url3,
              ")"
            ] })
          ] }, 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_runtime5.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_runtime5.jsx)(Text3, { color: theme.text.link, children: fullMatch }, key);
      }
    } catch (e4) {
      debugLogger134.error("Error parsing inline markdown part:", fullMatch, e4);
      renderedNode = null;
    }
    nodes.push(renderedNode ?? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text3, { children: fullMatch }, key));
    lastIndex = inlineRegex.lastIndex;
  }
  if (lastIndex < text.length) {
    nodes.push(/* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text3, { children: text.slice(lastIndex) }, `t-${lastIndex}`));
  }
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_jsx_runtime5.Fragment, { children: nodes.filter((node) => node !== null) });
}, "RenderInlineInternal");
var RenderInline = import_react38.default.memo(RenderInlineInternal);

// packages/cli/src/ui/utils/MarkdownDisplay.tsx
var import_jsx_runtime6 = __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_runtime6.jsx)(import_jsx_runtime6.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 parseTableAligns = /* @__PURE__ */ __name((line) => line.split(/(?<!\\)\|/).map((cell) => cell.trim()).filter((cell) => cell.length > 0).map((cell) => {
    const startsWithColon = cell.startsWith(":");
    const endsWithColon = cell.endsWith(":");
    if (startsWithColon && endsWithColon) return "center";
    if (endsWithColon) return "right";
    return "left";
  }), "parseTableAligns");
  const contentBlocks = [];
  let inCodeBlock = false;
  let lastLineEmpty = true;
  let codeBlockContent = [];
  let codeBlockLang = null;
  let codeBlockFence = "";
  let inTable = false;
  let tableRows = [];
  let tableHeaders = [];
  let tableAligns = [];
  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_runtime6.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) {
      const potentialHeaders = tableRowMatch[1].split(/(?<!\\)\|/).map((cell) => cell.trim().replaceAll("\\|", "|"));
      const nextLine = index + 1 < lines.length ? lines[index + 1] : "";
      const sepMatch = nextLine.match(tableSeparatorRegex);
      const sepColCount = sepMatch ? nextLine.split(/(?<!\\)\|/).map((c4) => c4.trim()).filter((c4) => c4.length > 0).length : 0;
      if (sepMatch && sepColCount === potentialHeaders.length) {
        inTable = true;
        tableHeaders = potentialHeaders;
        tableRows = [];
      } else {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { wrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(RenderInline, { text: line, textColor }) }) }, key)
        );
      }
    } else if (inTable && tableSeparatorMatch) {
      tableAligns = parseTableAligns(line);
    } else if (inTable && tableRowMatch) {
      const cells = tableRowMatch[1].split(/(?<!\\)\|/).map((cell) => cell.trim().replaceAll("\\|", "|"));
      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_runtime6.jsx)(
            RenderTable,
            {
              headers: tableHeaders,
              rows: tableRows,
              contentWidth,
              aligns: tableAligns
            },
            `table-${contentBlocks.length}`
          )
        );
      }
      inTable = false;
      tableRows = [];
      tableHeaders = [];
      tableAligns = [];
      if (line.trim().length > 0) {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { wrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(RenderInline, { text: line, textColor }) }) }, key)
        );
      }
    } else if (hrMatch) {
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime6.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_runtime6.jsx)(Text3, { bold: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(RenderInline, { text: headerText, textColor }) });
          break;
        case 2:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { bold: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(RenderInline, { text: headerText, textColor }) });
          break;
        case 3:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { bold: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(RenderInline, { text: headerText, textColor }) });
          break;
        case 4:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { italic: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(RenderInline, { text: headerText, textColor }) });
          break;
        default:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(RenderInline, { text: headerText, textColor }) });
          break;
      }
      if (headerNode) addContentBlock(/* @__PURE__ */ (0, import_jsx_runtime6.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_runtime6.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_runtime6.jsx)(
          RenderListItem,
          {
            itemText,
            type: "ol",
            marker,
            leadingWhitespace,
            textColor
          },
          key
        )
      );
    } else {
      if (line.trim().length === 0 && !inCodeBlock) {
        if (!lastLineEmpty) {
          contentBlocks.push(
            /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { height: EMPTY_LINE_HEIGHT }, `spacer-${index}`)
          );
          lastLineEmpty = true;
        }
      } else {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { wrap: "wrap", color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(RenderInline, { text: line, textColor }) }) }, key)
        );
      }
    }
  });
  if (inCodeBlock) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
        RenderCodeBlock,
        {
          content: codeBlockContent,
          lang: codeBlockLang,
          isPending,
          availableTerminalHeight,
          contentWidth
        },
        "line-eof"
      )
    );
  }
  if (inTable && tableHeaders.length > 0 && tableRows.length > 0) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
        RenderTable,
        {
          headers: tableHeaders,
          rows: tableRows,
          contentWidth,
          aligns: tableAligns
        },
        `table-${contentBlocks.length}`
      )
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.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_runtime6.jsx)(Box_default, { paddingLeft: CODE_BLOCK_PREFIX_PADDING, children: /* @__PURE__ */ (0, import_jsx_runtime6.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_runtime6.jsxs)(Box_default, { paddingLeft: CODE_BLOCK_PREFIX_PADDING, flexDirection: "column", children: [
        colorizedTruncatedCode,
        /* @__PURE__ */ (0, import_jsx_runtime6.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_runtime6.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_runtime6.jsxs)(
    Box_default,
    {
      paddingLeft: indentation + LIST_ITEM_PREFIX_PADDING,
      flexDirection: "row",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { color: textColor, children: prefix }) }),
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexGrow: LIST_ITEM_TEXT_FLEX_GROW, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text3, { wrap: "wrap", color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(RenderInline, { text: itemText, textColor }) }) })
      ]
    }
  );
}, "RenderListItemInternal");
var RenderListItem = import_react39.default.memo(RenderListItemInternal);
var RenderTableInternal = /* @__PURE__ */ __name(({
  headers,
  rows,
  contentWidth,
  aligns
}) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
  TableRenderer,
  {
    headers,
    rows,
    contentWidth,
    aligns
  }
), "RenderTableInternal");
var RenderTable = import_react39.default.memo(RenderTableInternal);
var MarkdownDisplay = import_react39.default.memo(MarkdownDisplayInternal);

// 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/ConversationMessages.tsx
var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
function getPrefixWidth(prefix) {
  return stringWidth4(prefix) + 1;
}
__name(getPrefixWidth, "getPrefixWidth");
var PrefixedTextMessage = /* @__PURE__ */ __name(({
  text,
  prefix,
  prefixColor,
  textColor,
  ariaLabel,
  marginTop = 0,
  alignSelf
}) => {
  const prefixWidth = getPrefixWidth(prefix);
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
    Box_default,
    {
      flexDirection: "row",
      paddingY: 0,
      marginTop,
      alignSelf,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text3, { color: prefixColor, "aria-label": ariaLabel, children: prefix }) }),
        /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text3, { wrap: "wrap", color: textColor, children: text }) })
      ]
    }
  );
}, "PrefixedTextMessage");
var PrefixedMarkdownMessage = /* @__PURE__ */ __name(({
  text,
  prefix,
  prefixColor,
  isPending,
  availableTerminalHeight,
  contentWidth,
  ariaLabel,
  textColor
}) => {
  const prefixWidth = getPrefixWidth(prefix);
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text3, { color: prefixColor, "aria-label": ariaLabel, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
      MarkdownDisplay,
      {
        text,
        isPending,
        availableTerminalHeight,
        contentWidth: contentWidth - prefixWidth,
        textColor
      }
    ) })
  ] });
}, "PrefixedMarkdownMessage");
var ContinuationMarkdownMessage = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  contentWidth,
  basePrefix,
  textColor
}) => {
  const prefixWidth = getPrefixWidth(basePrefix);
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { flexDirection: "column", paddingLeft: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
    MarkdownDisplay,
    {
      text,
      isPending,
      availableTerminalHeight,
      contentWidth: contentWidth - prefixWidth,
      textColor
    }
  ) });
}, "ContinuationMarkdownMessage");
var UserMessage = /* @__PURE__ */ __name(({ text }) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
  PrefixedTextMessage,
  {
    text,
    prefix: ">",
    prefixColor: theme.text.accent,
    textColor: theme.text.accent,
    ariaLabel: SCREEN_READER_USER_PREFIX,
    alignSelf: "flex-start"
  }
), "UserMessage");
var UserShellMessage = /* @__PURE__ */ __name(({ text }) => {
  const commandToDisplay = text.startsWith("!") ? text.substring(1) : text;
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
    PrefixedTextMessage,
    {
      text: commandToDisplay,
      prefix: "$",
      prefixColor: theme.text.link,
      textColor: theme.text.primary
    }
  );
}, "UserShellMessage");
var AssistantMessage = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  contentWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
  PrefixedMarkdownMessage,
  {
    text,
    prefix: "\u2726",
    prefixColor: theme.text.accent,
    ariaLabel: SCREEN_READER_MODEL_PREFIX,
    isPending,
    availableTerminalHeight,
    contentWidth
  }
), "AssistantMessage");
var AssistantMessageContent = /* @__PURE__ */ __name(({ text, isPending, availableTerminalHeight, contentWidth }) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
  ContinuationMarkdownMessage,
  {
    text,
    isPending,
    availableTerminalHeight,
    contentWidth,
    basePrefix: "\u2726"
  }
), "AssistantMessageContent");
var ThinkMessage = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  contentWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
  PrefixedMarkdownMessage,
  {
    text,
    prefix: "\u2726",
    prefixColor: theme.text.secondary,
    isPending,
    availableTerminalHeight,
    contentWidth,
    textColor: theme.text.secondary
  }
), "ThinkMessage");
var ThinkMessageContent = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  contentWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
  ContinuationMarkdownMessage,
  {
    text,
    isPending,
    availableTerminalHeight,
    contentWidth,
    basePrefix: "\u2726",
    textColor: theme.text.secondary
  }
), "ThinkMessageContent");

// packages/cli/src/ui/components/messages/ToolGroupMessage.tsx
init_esbuild_shims();
var import_react67 = __toESM(require_react(), 1);
init_types22();

// packages/cli/src/ui/components/messages/ToolMessage.tsx
init_esbuild_shims();
var import_react65 = __toESM(require_react(), 1);
init_types22();

// packages/cli/src/ui/components/messages/DiffRenderer.tsx
init_esbuild_shims();
import crypto16 from "node:crypto";
var import_jsx_runtime8 = __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_runtime8.jsx)(Text3, { color: theme.status.warning, children: "No diff content." });
  }
  const parsedLines = parseDiffWithLineNumbers(diffContent);
  if (parsedLines.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        padding: 1,
        children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text3, { dimColor: true, children: "No changes detected." })
      }
    );
  }
  if (screenReaderEnabled) {
    return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { flexDirection: "column", children: parsedLines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime8.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,
      tabWidth
    );
  } 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_runtime8.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        padding: 1,
        children: /* @__PURE__ */ (0, import_jsx_runtime8.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-${crypto16.createHash("sha1").update(JSON.stringify(parsedLines)).digest("hex")}`;
  let lastLineNumber = null;
  const MAX_CONTEXT_LINES_WITHOUT_GAP = 5;
  return /* @__PURE__ */ (0, import_jsx_runtime8.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_runtime8.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime8.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_runtime8.jsxs)(Box_default, { flexDirection: "row", children: [
            showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime8.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_runtime8.jsxs)(import_jsx_runtime8.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(Text3, { children: [
                prefixSymbol,
                " "
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text3, { wrap: "wrap", children: colorizeLine(displayContent, language) })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
              Text3,
              {
                backgroundColor: line.type === "add" ? theme.background.diff.added : theme.background.diff.removed,
                wrap: "wrap",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime8.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_runtime9 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_HEIGHT = 24;
var AnsiOutputText = /* @__PURE__ */ __name(({
  data,
  availableTerminalHeight,
  maxWidth
}) => {
  const lastLines = data.slice(
    -(availableTerminalHeight && availableTerminalHeight > 0 ? availableTerminalHeight : DEFAULT_HEIGHT)
  );
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(MaxSizedBox, { maxHeight: availableTerminalHeight, maxWidth, children: lastLines.map((line, lineIndex) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { children: line.length > 0 ? line.map((token2, tokenIndex) => /* @__PURE__ */ (0, import_jsx_runtime9.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,
      wrap: "truncate",
      children: token2.text
    },
    tokenIndex
  )) : null }, lineIndex)) });
}, "AnsiOutputText");
var ShellStatsBar = /* @__PURE__ */ __name(({
  totalLines,
  totalBytes,
  displayHeight = DEFAULT_HEIGHT
}) => {
  const parts2 = [];
  if (totalLines && totalLines > displayHeight) {
    parts2.push(`+${totalLines - displayHeight} lines`);
  }
  if (totalBytes && totalBytes > 0) {
    parts2.push(formatMemoryUsage2(totalBytes));
  }
  if (parts2.length === 0) return null;
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { flexDirection: "row", gap: 1, children: parts2.map((part, i4) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text3, { color: theme.text.secondary, children: part }, i4)) });
}, "ShellStatsBar");

// 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_runtime10 = __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_runtime10.jsx)(Box_default, { flexDirection: "column", children: todos.map((todo) => /* @__PURE__ */ (0, import_jsx_runtime10.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_runtime10.jsxs)(Box_default, { flexDirection: "row", minHeight: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { width: 3, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text3, { color: itemColor, children: statusIcon }) }),
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime10.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_react44 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useSelectionList.ts
init_esbuild_shims();
var import_react43 = __toESM(require_react(), 1);
init_dist4();

// packages/cli/src/ui/hooks/useKeypress.ts
init_esbuild_shims();
var import_react42 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/KeypressContext.tsx
init_esbuild_shims();
init_dist4();
var import_react41 = __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();
init_dist4();
import * as fs122 from "node:fs/promises";
import * as path127 from "node:path";
var debugLogger135 = 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) {
    debugLogger135.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 (error40) {
    debugLogger135.error("Error checking clipboard for image:", error40);
    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 = path127.join(baseDir, "clipboard");
    await fs122.mkdir(tempDir, { recursive: true });
    const timestamp = (/* @__PURE__ */ new Date()).getTime();
    const tempFilePath = path127.join(tempDir, `clipboard-${timestamp}.png`);
    const imageData = clipboard.getImageData();
    const buffer = imageData.data;
    if (!buffer) {
      return null;
    }
    await fs122.writeFile(tempFilePath, buffer);
    return tempFilePath;
  } catch (error40) {
    debugLogger135.error("Error saving clipboard image:", error40);
    return null;
  }
}
__name(saveClipboardImage, "saveClipboardImage");
async function cleanupOldClipboardImages(targetDir) {
  try {
    const baseDir = targetDir || process.cwd();
    const tempDir = path127.join(baseDir, "clipboard");
    const files = await fs122.readdir(tempDir);
    const MAX_IMAGES = 100;
    const CLEANUP_COUNT = 50;
    const imageFiles = [];
    for (const file2 of files) {
      if (file2.startsWith("clipboard-") && (file2.endsWith(".png") || file2.endsWith(".jpg") || file2.endsWith(".webp") || file2.endsWith(".heic") || file2.endsWith(".heif") || file2.endsWith(".tiff") || file2.endsWith(".gif") || file2.endsWith(".bmp"))) {
        const filePath = path127.join(tempDir, file2);
        const stats = await fs122.stat(filePath);
        imageFiles.push({
          name: file2,
          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 file2 of filesToRemove) {
        await fs122.unlink(file2.path);
      }
    }
  } catch {
  }
}
__name(cleanupOldClipboardImages, "cleanupOldClipboardImages");

// packages/cli/src/ui/hooks/useFocus.ts
init_esbuild_shims();
var import_react40 = __toESM(require_react(), 1);
var ENABLE_FOCUS_REPORTING = "\x1B[?1004h";
var DISABLE_FOCUS_REPORTING = "\x1B[?1004l";
var FOCUS_IN = "\x1B[I";
var FOCUS_OUT = "\x1B[O";
var useFocus = /* @__PURE__ */ __name(() => {
  const { stdin: stdin2 } = use_stdin_default();
  const { stdout: stdout2 } = use_stdout_default();
  const [isFocused, setIsFocused] = (0, import_react40.useState)(true);
  (0, import_react40.useEffect)(() => {
    const handleData = /* @__PURE__ */ __name((data) => {
      const sequence = data.toString();
      const lastFocusIn = sequence.lastIndexOf(FOCUS_IN);
      const lastFocusOut = sequence.lastIndexOf(FOCUS_OUT);
      if (lastFocusIn > lastFocusOut) {
        setIsFocused(true);
      } else if (lastFocusOut > lastFocusIn) {
        setIsFocused(false);
      }
    }, "handleData");
    stdout2?.write(ENABLE_FOCUS_REPORTING);
    stdin2?.on("data", handleData);
    return () => {
      stdout2?.write(DISABLE_FOCUS_REPORTING);
      stdin2?.removeListener("data", handleData);
    };
  }, [stdin2, stdout2]);
  useKeypress(
    (_2) => {
      if (!isFocused) {
        setIsFocused(true);
      }
    },
    { isActive: true }
  );
  return isFocused;
}, "useFocus");

// packages/cli/src/ui/contexts/KeypressContext.tsx
var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
var ESC2 = "\x1B";
var PASTE_MODE_PREFIX = `${ESC2}[200~`;
var PASTE_MODE_SUFFIX = `${ESC2}[201~`;
var KITTY_SEQUENCE_TIMEOUT_MS = 200;
var PASTE_IDLE_TIMEOUT_MS = 1e3;
var KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR = {
  57399: "0",
  57400: "1",
  57401: "2",
  57402: "3",
  57403: "4",
  57404: "5",
  57405: "6",
  57406: "7",
  57407: "8",
  57408: "9",
  57409: ".",
  57410: "/",
  57411: "*",
  57412: "-",
  57413: "+",
  // 57414 is keypad Enter - handled separately via CSI~ sequence
  57415: "=",
  57416: ","
};
var KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME = {
  57417: "left",
  57418: "right",
  57419: "up",
  57420: "down",
  57421: "pageup",
  57422: "pagedown",
  57423: "home",
  57424: "end",
  57425: "insert",
  57426: "delete"
};
var KeypressContext = (0, import_react41.createContext)(
  void 0
);
var debugLogger136 = createDebugLogger("KEYPRESS");
function useKeypressContext() {
  const context2 = (0, import_react41.useContext)(KeypressContext);
  if (!context2) {
    throw new Error(
      "useKeypressContext must be used within a KeypressProvider"
    );
  }
  return context2;
}
__name(useKeypressContext, "useKeypressContext");
function KeypressProvider({
  children,
  kittyProtocolEnabled,
  pasteWorkaround = false,
  config: config2,
  debugKeystrokeLogging,
  initialCapturedInput
}) {
  const { stdin: stdin2, setRawMode } = use_stdin_default();
  const subscribers = (0, import_react41.useRef)(/* @__PURE__ */ new Set()).current;
  const subscribe = (0, import_react41.useCallback)(
    (handler) => {
      subscribers.add(handler);
    },
    [subscribers]
  );
  const unsubscribe = (0, import_react41.useCallback)(
    (handler) => {
      subscribers.delete(handler);
    },
    [subscribers]
  );
  (0, import_react41.useEffect)(() => {
    const wasRaw = stdin2.isRaw;
    if (wasRaw === false) {
      setRawMode(true);
    }
    const capturedInput = initialCapturedInput ?? Buffer.alloc(0);
    const keypressStream = new PassThrough5();
    let usePassthrough = false;
    if (pasteWorkaround) {
      usePassthrough = true;
    }
    let isPaste = false;
    let pasteBuffer = Buffer.alloc(0);
    let pasteAlreadyFlushed = false;
    let pasteIdleTimeout = null;
    const kittySequenceBufferRef = { current: "" };
    let kittySequenceTimeout = null;
    let backslashTimeout = null;
    let waitingForEnterAfterBackslash = false;
    let rawDataBuffer = Buffer.alloc(0);
    let rawFlushTimeout = null;
    const updateKittyBuffer = /* @__PURE__ */ __name((value) => {
      kittySequenceBufferRef.current = value;
    }, "updateKittyBuffer");
    const clearKittyTimeout = /* @__PURE__ */ __name(() => {
      if (kittySequenceTimeout) {
        clearTimeout(kittySequenceTimeout);
        kittySequenceTimeout = null;
      }
    }, "clearKittyTimeout");
    const startKittyTimeout = /* @__PURE__ */ __name(() => {
      clearKittyTimeout();
      kittySequenceTimeout = setTimeout(() => {
        if (kittySequenceBufferRef.current) {
          while (kittySequenceBufferRef.current) {
            const parsed = parseKittyPrefix(kittySequenceBufferRef.current);
            if (parsed) {
              kittySequenceBufferRef.current = kittySequenceBufferRef.current.slice(parsed.length);
              broadcast(parsed.key);
              continue;
            }
            const plain = parsePlainTextPrefix(kittySequenceBufferRef.current);
            if (plain) {
              kittySequenceBufferRef.current = kittySequenceBufferRef.current.slice(plain.length);
              broadcast(plain.key);
              continue;
            }
            break;
          }
          if (kittySequenceBufferRef.current) {
            if (debugKeystrokeLogging) {
              debugLogger136.debug(
                "[DEBUG] Kitty buffer timeout, clearing:",
                kittySequenceBufferRef.current
              );
            }
            kittySequenceBufferRef.current = "";
          }
        }
      }, KITTY_SEQUENCE_TIMEOUT_MS);
    }, "startKittyTimeout");
    const clearKittyBufferAndTimeout = /* @__PURE__ */ __name(() => {
      clearKittyTimeout();
      kittySequenceBufferRef.current = "";
    }, "clearKittyBufferAndTimeout");
    const clearPasteIdleTimeout = /* @__PURE__ */ __name(() => {
      if (pasteIdleTimeout) {
        clearTimeout(pasteIdleTimeout);
        pasteIdleTimeout = null;
      }
    }, "clearPasteIdleTimeout");
    const forceFlushStuckPaste = /* @__PURE__ */ __name(() => {
      clearPasteIdleTimeout();
      if (!isPaste && pasteBuffer.length === 0) return;
      const buffered = pasteBuffer.toString();
      isPaste = false;
      pasteBuffer = Buffer.alloc(0);
      pasteAlreadyFlushed = true;
      if (buffered.length > 0) {
        broadcast({
          name: "",
          ctrl: false,
          meta: false,
          shift: false,
          paste: true,
          sequence: buffered
        });
      }
    }, "forceFlushStuckPaste");
    const startPasteIdleTimeout = /* @__PURE__ */ __name(() => {
      clearPasteIdleTimeout();
      pasteIdleTimeout = setTimeout(
        forceFlushStuckPaste,
        PASTE_IDLE_TIMEOUT_MS
      );
    }, "startPasteIdleTimeout");
    const createPrintableKey = /* @__PURE__ */ __name((char) => {
      const printableName = char === " " ? "space" : /^[A-Za-z]$/.test(char) ? char.toLowerCase() : char;
      return {
        name: printableName,
        ctrl: false,
        meta: false,
        shift: false,
        paste: false,
        sequence: char,
        kittyProtocol: true
      };
    }, "createPrintableKey");
    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 name4 = symbolToName[sym] || "";
        if (!name4) return null;
        return {
          key: {
            name: name4,
            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+)*(?:;(\\d+)(?::\\d+)*)?(?:;\\d+)?([u~])`
      );
      m3 = buffer.match(csiUPrefix);
      if (m3) {
        const keyCode = parseInt(m3[1], 10);
        let modifiers = m3[2] ? parseInt(m3[2], 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[3];
        if (terminator === "~") {
          let name5 = null;
          switch (keyCode) {
            case 1:
              name5 = "home";
              break;
            case 2:
              name5 = "insert";
              break;
            case 3:
              name5 = "delete";
              break;
            case 4:
              name5 = "end";
              break;
            case 5:
              name5 = "pageup";
              break;
            case 6:
              name5 = "pagedown";
              break;
            default:
              break;
          }
          if (name5) {
            return {
              key: {
                name: name5,
                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 name4 = kittyKeyCodeToName[keyCode];
        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
          };
        }
        if (!ctrl) {
          const keypadChar = KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR[keyCode];
          if (keypadChar) {
            return {
              key: {
                name: keypadChar,
                ctrl: false,
                meta: alt,
                shift,
                paste: false,
                sequence: keypadChar,
                kittyProtocol: true
              },
              length: m3[0].length
            };
          }
        }
        const keypadName = KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME[keyCode];
        if (keypadName) {
          return {
            key: {
              name: keypadName,
              ctrl,
              meta: alt,
              shift,
              paste: false,
              sequence: buffer.slice(0, m3[0].length),
              kittyProtocol: true
            },
            length: m3[0].length
          };
        }
        if (terminator === "u" && !ctrl && keyCode >= 32 && keyCode !== 127 && keyCode <= 1114111 && !(keyCode >= 57344 && keyCode <= 63743)) {
          return {
            key: {
              ...createPrintableKey(String.fromCodePoint(keyCode)),
              meta: alt,
              shift
            },
            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 name4 = nameMap[sym];
        return {
          key: {
            name: name4,
            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 getCompleteCsiSequenceLength = /* @__PURE__ */ __name((buffer) => {
      if (!buffer.startsWith(`${ESC2}[`)) {
        return null;
      }
      for (let i4 = 2; i4 < buffer.length; i4++) {
        const code2 = buffer.charCodeAt(i4);
        if (code2 >= 64 && code2 <= 126) {
          return i4 + 1;
        }
        if (code2 < 32 || code2 > 63) {
          return 0;
        }
      }
      return null;
    }, "getCompleteCsiSequenceLength");
    const parsePlainTextPrefix = /* @__PURE__ */ __name((buffer) => {
      if (!buffer || buffer.startsWith(ESC2)) {
        return null;
      }
      const [char] = Array.from(buffer);
      if (!char) {
        return null;
      }
      return {
        key: createPrintableKey(char),
        length: char.length
      };
    }, "parsePlainTextPrefix");
    const broadcast = /* @__PURE__ */ __name((key) => {
      for (const handler of subscribers) {
        handler(key);
      }
    }, "broadcast");
    const TERMINAL_RESPONSE_RE = /^\x1b\[[?>][\d;]*[uc]$/;
    const handleKeypress = /* @__PURE__ */ __name(async (_2, key) => {
      if (TERMINAL_RESPONSE_RE.test(key.sequence)) {
        return;
      }
      if (key.sequence === FOCUS_IN || key.sequence === FOCUS_OUT) {
        return;
      }
      const isCtrlCKey = key.ctrl && key.name === "c" || key.sequence === `${ESC2}${KITTY_CTRL_C}`;
      if (isCtrlCKey) {
        if (isPaste || pasteBuffer.length > 0) {
          isPaste = false;
          pasteBuffer = Buffer.alloc(0);
          pasteAlreadyFlushed = true;
          clearPasteIdleTimeout();
        }
        if (kittySequenceBufferRef.current && debugKeystrokeLogging) {
          debugLogger136.debug(
            "[DEBUG] Kitty buffer cleared on Ctrl+C:",
            kittySequenceBufferRef.current
          );
        }
        clearKittyBufferAndTimeout();
        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 (key.name === "paste-start") {
        isPaste = true;
        pasteAlreadyFlushed = false;
        startPasteIdleTimeout();
        return;
      }
      if (key.name === "paste-end") {
        clearPasteIdleTimeout();
        if (pasteAlreadyFlushed) {
          pasteAlreadyFlushed = false;
          isPaste = false;
          pasteBuffer = Buffer.alloc(0);
          return;
        }
        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)]);
        startPasteIdleTimeout();
        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 (kittyProtocolEnabled) {
        if (kittySequenceBufferRef.current || 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)) {
          updateKittyBuffer(kittySequenceBufferRef.current + key.sequence);
          startKittyTimeout();
          if (debugKeystrokeLogging) {
            debugLogger136.debug(
              "[DEBUG] Kitty buffer accumulating:",
              kittySequenceBufferRef.current
            );
          }
          let bufferedInputHandled = false;
          while (kittySequenceBufferRef.current) {
            const parsed = parseKittyPrefix(kittySequenceBufferRef.current);
            if (parsed) {
              if (debugKeystrokeLogging) {
                const parsedSequence = kittySequenceBufferRef.current.slice(
                  0,
                  parsed.length
                );
                if (kittySequenceBufferRef.current.length > parsed.length) {
                  debugLogger136.debug(
                    "[DEBUG] Kitty sequence parsed successfully (prefix):",
                    parsedSequence
                  );
                } else {
                  debugLogger136.debug(
                    "[DEBUG] Kitty sequence parsed successfully:",
                    parsedSequence
                  );
                }
              }
              updateKittyBuffer(
                kittySequenceBufferRef.current.slice(parsed.length)
              );
              if (!kittySequenceBufferRef.current) {
                clearKittyTimeout();
              }
              broadcast(parsed.key);
              bufferedInputHandled = true;
              continue;
            }
            const completeUnsupportedCsiLength = getCompleteCsiSequenceLength(
              kittySequenceBufferRef.current
            );
            if (completeUnsupportedCsiLength) {
              if (debugKeystrokeLogging) {
                debugLogger136.debug(
                  "[DEBUG] Dropping unsupported complete CSI sequence:",
                  kittySequenceBufferRef.current.slice(
                    0,
                    completeUnsupportedCsiLength
                  )
                );
              }
              updateKittyBuffer(
                kittySequenceBufferRef.current.slice(
                  completeUnsupportedCsiLength
                )
              );
              if (!kittySequenceBufferRef.current) {
                clearKittyTimeout();
              }
              bufferedInputHandled = true;
              continue;
            }
            const plainTextPrefix = parsePlainTextPrefix(
              kittySequenceBufferRef.current
            );
            if (plainTextPrefix) {
              if (debugKeystrokeLogging) {
                debugLogger136.debug(
                  "[DEBUG] Recovered plain text after kitty sequence:",
                  plainTextPrefix.key.sequence
                );
              }
              updateKittyBuffer(
                kittySequenceBufferRef.current.slice(plainTextPrefix.length)
              );
              if (!kittySequenceBufferRef.current) {
                clearKittyTimeout();
              }
              broadcast(plainTextPrefix.key);
              bufferedInputHandled = true;
              continue;
            }
            const nextStart = kittySequenceBufferRef.current.indexOf(
              `${ESC2}[`,
              1
            );
            if (nextStart > 0) {
              if (debugKeystrokeLogging) {
                debugLogger136.debug(
                  "[DEBUG] Skipping incomplete/invalid CSI prefix:",
                  kittySequenceBufferRef.current.slice(0, nextStart)
                );
              }
              updateKittyBuffer(
                kittySequenceBufferRef.current.slice(nextStart)
              );
              if (!kittySequenceBufferRef.current) {
                clearKittyTimeout();
              }
              bufferedInputHandled = true;
              continue;
            }
            break;
          }
          if (bufferedInputHandled) return;
          if (config2?.getDebugMode() || debugKeystrokeLogging) {
            const codes = Array.from(kittySequenceBufferRef.current).map(
              (ch) => ch.charCodeAt(0)
            );
            debugLogger136.warn("Kitty sequence buffer has char codes:", codes);
          }
          if (kittySequenceBufferRef.current.length > MAX_KITTY_SEQUENCE_LENGTH) {
            if (debugKeystrokeLogging) {
              debugLogger136.debug(
                "[DEBUG] Kitty buffer overflow, clearing:",
                kittySequenceBufferRef.current
              );
            }
            if (config2) {
              const event = new KittySequenceOverflowEvent(
                kittySequenceBufferRef.current.length,
                kittySequenceBufferRef.current
              );
              logKittySequenceOverflow(config2, event);
            }
            clearKittyBufferAndTimeout();
          } 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((name4 = "", sequence = "") => ({
      name: name4,
      ctrl: false,
      meta: false,
      shift: false,
      paste: false,
      sequence
    }), "createPasteKeyEvent");
    const shouldFlushRawDataAsPaste = /* @__PURE__ */ __name((data) => {
      const hasReturn = data.includes(13);
      const hasEmbeddedTab = data.length > 1 && data.includes(9);
      const isSingleReturn = data.length <= 2 && hasReturn;
      return !isSingleReturn && (hasReturn || hasEmbeddedTab);
    }, "shouldFlushRawDataAsPaste");
    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 (isPaste || !shouldFlushRawDataAsPaste(rawDataBuffer)) {
        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);
      stdin2.on("data", handleRawKeypress);
    } else {
      rl = readline3.createInterface({ input: stdin2, escapeCodeTimeout: 0 });
      readline3.emitKeypressEvents(stdin2, rl);
      stdin2.on("keypress", handleKeypress);
    }
    let replayPending = false;
    if (capturedInput.length > 0) {
      debugLogger136.debug(
        `Replaying ${capturedInput.length} bytes of captured input`
      );
      replayPending = true;
      setImmediate(() => {
        if (!replayPending) return;
        try {
          stdin2.emit("data", capturedInput);
        } catch (err2) {
          debugLogger136.error("Failed to replay captured input:", err2);
        }
      });
    }
    return () => {
      replayPending = false;
      if (usePassthrough) {
        keypressStream.removeListener("keypress", handleKeypress);
        stdin2.removeListener("data", handleRawKeypress);
      } else {
        stdin2.removeListener("keypress", handleKeypress);
      }
      rl.close();
      if (wasRaw === false) {
        setRawMode(false);
      }
      if (backslashTimeout) {
        clearTimeout(backslashTimeout);
        backslashTimeout = null;
      }
      clearKittyBufferAndTimeout();
      clearPasteIdleTimeout();
      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);
      }
    };
  }, [
    stdin2,
    setRawMode,
    kittyProtocolEnabled,
    debugKeystrokeLogging,
    pasteWorkaround,
    config2,
    subscribers,
    initialCapturedInput
  ]);
  return /* @__PURE__ */ (0, import_jsx_runtime11.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_react42.useEffect)(() => {
    if (!isActive) {
      return;
    }
    subscribe(onKeypress);
    return () => {
      unsubscribe(onKeypress);
    };
  }, [isActive, onKeypress, subscribe, unsubscribe]);
}
__name(useKeypress, "useKeypress");

// packages/cli/src/ui/hooks/useSelectionList.ts
var debugLogger137 = 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 i4 = 0; i4 < len; i4++) {
    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 i4 = 0; i4 < items.length; i4++) {
      if (items[i4].key === initialKey && !items[i4].disabled) {
        return i4;
      }
    }
  }
  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");
var areItemsStructurallyEqual = /* @__PURE__ */ __name((a2, b2) => {
  if (a2 === b2) {
    return true;
  }
  if (a2.length !== b2.length) {
    return false;
  }
  for (let i4 = 0; i4 < a2.length; i4++) {
    if (a2[i4]?.key !== b2[i4]?.key || a2[i4]?.disabled !== b2[i4]?.disabled) {
      return false;
    }
  }
  return true;
}, "areItemsStructurallyEqual");
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 initialIndexChanged = initialIndex !== state.initialIndex;
      const activeKey = !initialIndexChanged && state.activeIndex !== state.initialIndex ? state.items[state.activeIndex]?.key : void 0;
      const targetIndex = computeInitialIndex(initialIndex, items, activeKey);
      const itemsStructurallyEqual = areItemsStructurallyEqual(
        items,
        state.items
      );
      if (!initialIndexChanged && targetIndex === state.activeIndex && itemsStructurallyEqual) {
        return state;
      }
      return {
        ...state,
        items: itemsStructurallyEqual ? state.items : items,
        activeIndex: targetIndex,
        initialIndex,
        pendingHighlight: false
      };
    }
    case "CLEAR_PENDING_FLAGS": {
      return {
        ...state,
        pendingHighlight: false,
        pendingSelect: false
      };
    }
    default: {
      const exhaustiveCheck = action;
      debugLogger137.error(`Unknown selection list action: ${exhaustiveCheck}`);
      return state;
    }
  }
}
__name(selectionListReducer, "selectionListReducer");
function useSelectionList({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showNumbers = false
}) {
  const [state, dispatch] = (0, import_react43.useReducer)(selectionListReducer, {
    activeIndex: computeInitialIndex(initialIndex, items),
    initialIndex,
    pendingHighlight: false,
    pendingSelect: false,
    items
  });
  const numberInputRef = (0, import_react43.useRef)("");
  const numberInputTimer = (0, import_react43.useRef)(null);
  (0, import_react43.useEffect)(() => {
    dispatch({ type: "INITIALIZE", payload: { initialIndex, items } });
  }, [initialIndex, items]);
  (0, import_react43.useEffect)(() => {
    let needsClear = false;
    if (state.pendingHighlight && items[state.activeIndex]) {
      onHighlight?.(items[state.activeIndex].value);
      needsClear = true;
    }
    if (state.pendingSelect && items[state.activeIndex]) {
      const currentItem = items[state.activeIndex];
      if (currentItem && !currentItem.disabled) {
        onSelect(currentItem.value);
      }
      needsClear = true;
    }
    if (needsClear) {
      dispatch({ type: "CLEAR_PENDING_FLAGS" });
    }
  }, [
    state.pendingHighlight,
    state.pendingSelect,
    state.activeIndex,
    items,
    onHighlight,
    onSelect
  ]);
  (0, import_react43.useEffect)(
    () => () => {
      if (numberInputTimer.current) {
        clearTimeout(numberInputTimer.current);
      }
    },
    []
  );
  useKeypress(
    (key) => {
      const { sequence, name: name4 } = key;
      const isNumeric = showNumbers && /^[0-9]$/.test(sequence);
      if (!isNumeric && numberInputTimer.current) {
        clearTimeout(numberInputTimer.current);
        numberInputRef.current = "";
      }
      if (name4 === "k" || name4 === "up") {
        dispatch({ type: "MOVE_UP", payload: { items } });
        return;
      }
      if (name4 === "j" || name4 === "down") {
        dispatch({ type: "MOVE_DOWN", payload: { items } });
        return;
      }
      if (name4 === "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_runtime12 = __toESM(require_jsx_runtime(), 1);
function BaseSelectionList({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showNumbers = true,
  showScrollArrows = false,
  maxItemsToShow: maxItemsToShow2 = 10,
  itemGap = 0,
  renderItem
}) {
  const { activeIndex } = useSelectionList({
    items,
    initialIndex,
    onSelect,
    onHighlight,
    isFocused,
    showNumbers
  });
  const [scrollOffset, setScrollOffset] = (0, import_react44.useState)(0);
  (0, import_react44.useEffect)(() => {
    const newScrollOffset = Math.max(
      0,
      Math.min(activeIndex - maxItemsToShow2 + 1, items.length - maxItemsToShow2)
    );
    if (activeIndex < scrollOffset) {
      setScrollOffset(activeIndex);
    } else if (activeIndex >= scrollOffset + maxItemsToShow2) {
      setScrollOffset(newScrollOffset);
    }
  }, [activeIndex, items.length, scrollOffset, maxItemsToShow2]);
  const visibleItems = items.slice(scrollOffset, scrollOffset + maxItemsToShow2);
  const numberColumnWidth = String(items.length).length;
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(Box_default, { flexDirection: "column", gap: itemGap, children: [
    showScrollArrows && /* @__PURE__ */ (0, import_jsx_runtime12.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_runtime12.jsxs)(Box_default, { alignItems: "flex-start", children: [
        /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
          Text3,
          {
            color: isSelected ? theme.status.success : theme.text.primary,
            "aria-hidden": true,
            children: isSelected ? "\u203A" : " "
          }
        ) }),
        showNumbers && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
          Box_default,
          {
            marginRight: 1,
            flexShrink: 0,
            minWidth: itemNumberText.length,
            "aria-state": { checked: isSelected },
            children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text3, { color: numberColor, children: itemNumberText })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Box_default, { flexGrow: 1, children: renderItem(item, {
          isSelected,
          titleColor,
          numberColor
        }) })
      ] }, item.key);
    }),
    showScrollArrows && /* @__PURE__ */ (0, import_jsx_runtime12.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_runtime13 = __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_runtime13.jsx)(
    BaseSelectionList,
    {
      items,
      initialIndex,
      onSelect,
      onHighlight,
      isFocused,
      showNumbers,
      showScrollArrows,
      maxItemsToShow: maxItemsToShow2,
      renderItem: (item, { titleColor }) => {
        if (item.themeNameDisplay && item.themeTypeDisplay) {
          return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(Text3, { color: titleColor, wrap: "truncate", children: [
            item.themeNameDisplay,
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text3, { color: theme.text.secondary, children: item.themeTypeDisplay })
          ] }, item.key);
        }
        return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text3, { color: titleColor, wrap: "truncate", children: item.label });
      }
    }
  );
}
__name(RadioButtonSelect, "RadioButtonSelect");

// packages/cli/src/ui/components/subagents/create/LocationSelector.tsx
init_i18n();
var import_jsx_runtime14 = __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_runtime14.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime14.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();
init_i18n();
var import_jsx_runtime15 = __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_runtime15.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime15.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);

// node_modules/ink-spinner/build/index.js
init_esbuild_shims();
var import_react45 = __toESM(require_react(), 1);
var import_cli_spinners = __toESM(require_cli_spinners(), 1);
function Spinner({ type = "dots" }) {
  const [frame, setFrame] = (0, import_react45.useState)(0);
  const spinner = import_cli_spinners.default[type];
  (0, import_react45.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_react45.default.createElement(Text3, null, spinner.frames[frame]);
}
__name(Spinner, "Spinner");
var build_default = Spinner;

// packages/cli/src/ui/components/subagents/create/DescriptionInput.tsx
init_dist4();

// 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["RETRY_LAST"] = "retryLast";
  Command2["TOGGLE_COMPACT_MODE"] = "toggleCompactMode";
  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 }],
  ["retryLast" /* RETRY_LAST */]: [{ key: "y", ctrl: true }],
  ["toggleCompactMode" /* TOGGLE_COMPACT_MODE */]: [{ key: "o", 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);
init_dist4();
import { spawnSync as spawnSync4 } from "node:child_process";
import fs123 from "node:fs";
import os45 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 i4 = col + 1;
  while (i4 < lineCodePoints.length && isCombiningMark(lineCodePoints[i4])) {
    i4++;
  }
  return i4 >= lineCodePoints.length || !isWordCharStrict(lineCodePoints[i4]);
}
__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 i4 = 0; i4 < count; i4++) {
        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 i4 = 0; i4 < count; i4++) {
        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 i4 = 0; i4 < count; i4++) {
        const wordEnd = findNextWordAcrossLines(lines, row, col, false);
        if (wordEnd) {
          endRow = wordEnd.row;
          endCol = wordEnd.col + 1;
          if (i4 < 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 i4 = 0; i4 < count; i4++) {
        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 i4 = 0; i4 < count; i4++) {
        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 i4 = 0; i4 < count; i4++) {
        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 i4 = 0; i4 < count; i4++) {
        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 i4 = 0; i4 < count; i4++) {
        if (i4 === 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 debugLogger138 = createDebugLogger("TEXT_BUFFER");
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 CJK_CHAR_REGEX = /[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/;
var isCjkChar = /* @__PURE__ */ __name((char) => CJK_CHAR_REGEX.test(char), "isCjkChar");
var WORD_BOUNDARIES_CACHE_MAX = 500;
var SEGMENTER_LENGTH_LIMIT = 1500;
var wordBoundariesCache = null;
var segmenter5 = null;
function ensureSegmenterLoaded() {
  if (segmenter5 !== null) return;
  try {
    segmenter5 = new Intl.Segmenter("zh", { granularity: "word" });
    debugLogger138.info("Intl.Segmenter: initialized successfully");
  } catch (err2) {
    debugLogger138.warn("Intl.Segmenter: failed to initialize", err2);
    segmenter5 = false;
  }
}
__name(ensureSegmenterLoaded, "ensureSegmenterLoaded");
function charByCharFallback(line) {
  const codePoints = toCodePoints(line);
  const fallback = [];
  for (let i4 = 0; i4 < codePoints.length; i4++) {
    if (isCjkChar(codePoints[i4])) {
      fallback.push({ start: i4, end: i4 + 1 });
    }
  }
  return fallback;
}
__name(charByCharFallback, "charByCharFallback");
function evictCacheIfNeeded() {
  if (wordBoundariesCache && wordBoundariesCache.size >= WORD_BOUNDARIES_CACHE_MAX) {
    const firstKey = wordBoundariesCache.keys().next().value;
    if (firstKey !== void 0) {
      wordBoundariesCache.delete(firstKey);
    }
  }
}
__name(evictCacheIfNeeded, "evictCacheIfNeeded");
function getWordBoundaries(line, codePoints) {
  const cps = codePoints ?? toCodePoints(line);
  if (cps.length > SEGMENTER_LENGTH_LIMIT) {
    if (!wordBoundariesCache) wordBoundariesCache = /* @__PURE__ */ new Map();
    if (wordBoundariesCache.has(line)) return wordBoundariesCache.get(line);
    const fallback = charByCharFallback(line);
    evictCacheIfNeeded();
    wordBoundariesCache.set(line, fallback);
    return fallback;
  }
  if (!wordBoundariesCache) wordBoundariesCache = /* @__PURE__ */ new Map();
  const cached2 = wordBoundariesCache.get(line);
  if (cached2) {
    return cached2;
  }
  ensureSegmenterLoaded();
  if (!segmenter5) {
    const fallback = charByCharFallback(line);
    evictCacheIfNeeded();
    wordBoundariesCache.set(line, fallback);
    return fallback;
  }
  try {
    const segments = segmenter5.segment(line);
    const cpToStrIdx = [];
    let strIdx = 0;
    for (let i4 = 0; i4 < cps.length; i4++) {
      cpToStrIdx[i4] = strIdx;
      strIdx += cps[i4].length;
    }
    const boundaries = [];
    for (const { index, segment, isWordLike } of segments) {
      const trimmedSegment = segment.trim();
      if (!isWordLike && trimmedSegment.length === 0) {
        continue;
      }
      if (isWordLike && segment.includes(".")) {
        let currentOffset = index;
        const parts2 = segment.split(/(\.)/);
        for (const part of parts2) {
          if (part.length === 0) continue;
          const partStartCpIdx = binarySearchCpIndex(cpToStrIdx, currentOffset);
          const partEndStrPos = currentOffset + part.length;
          const partEndCpIdxRaw = binarySearchCpIndex(
            cpToStrIdx,
            partEndStrPos
          );
          const partEndCpIdx = partEndCpIdxRaw === -1 ? cps.length : partEndCpIdxRaw;
          if (partStartCpIdx >= 0 && partStartCpIdx < partEndCpIdx) {
            boundaries.push({ start: partStartCpIdx, end: partEndCpIdx });
          }
          currentOffset += part.length;
        }
        continue;
      }
      if (!isWordLike && /^[.,;!?，。；！？、]+$/.test(trimmedSegment)) {
        const startCpIdx2 = binarySearchCpIndex(cpToStrIdx, index);
        const endStrPos2 = index + segment.length;
        const endCpIdxRaw2 = binarySearchCpIndex(cpToStrIdx, endStrPos2);
        const endCpIdx2 = endCpIdxRaw2 === -1 ? cps.length : endCpIdxRaw2;
        if (startCpIdx2 >= 0 && startCpIdx2 < endCpIdx2) {
          boundaries.push({ start: startCpIdx2, end: endCpIdx2 });
        }
        continue;
      }
      const startCpIdx = binarySearchCpIndex(cpToStrIdx, index);
      const endStrPos = index + segment.length;
      const endCpIdxRaw = binarySearchCpIndex(cpToStrIdx, endStrPos);
      const endCpIdx = endCpIdxRaw === -1 ? cps.length : endCpIdxRaw;
      if (startCpIdx >= 0 && startCpIdx < endCpIdx) {
        boundaries.push({ start: startCpIdx, end: endCpIdx });
      }
    }
    evictCacheIfNeeded();
    wordBoundariesCache.set(line, boundaries);
    return boundaries;
  } catch (err2) {
    debugLogger138.warn("getWordBoundaries: error, using char fallback", err2);
    const fallback = charByCharFallback(line);
    evictCacheIfNeeded();
    wordBoundariesCache.set(line, fallback);
    return fallback;
  }
}
__name(getWordBoundaries, "getWordBoundaries");
function binarySearchCpIndex(cpToStrIdx, target) {
  let lo = 0;
  let hi = cpToStrIdx.length - 1;
  while (lo <= hi) {
    const mid = lo + hi >>> 1;
    if (cpToStrIdx[mid] >= target) hi = mid - 1;
    else lo = mid + 1;
  }
  return lo < cpToStrIdx.length ? lo : -1;
}
__name(binarySearchCpIndex, "binarySearchCpIndex");
function findPrevWordStart(boundaries, col) {
  for (let i4 = boundaries.length - 1; i4 >= 0; i4--) {
    const b2 = boundaries[i4];
    if (col > b2.start && col <= b2.end) {
      return b2.start;
    }
    if (col === b2.start && i4 > 0) {
      return boundaries[i4 - 1].start;
    }
  }
  return null;
}
__name(findPrevWordStart, "findPrevWordStart");
function findNextWordEnd(boundaries, col) {
  for (const b2 of boundaries) {
    if (col >= b2.start && col < b2.end) {
      return b2.end;
    }
    if (col < b2.start) {
      return null;
    }
  }
  return null;
}
__name(findNextWordEnd, "findNextWordEnd");
function findWordEndFallback(arr, startPos) {
  let end = startPos;
  while (end < arr.length) {
    const currChar = arr[end];
    const nextChar = end + 1 < arr.length ? arr[end + 1] : void 0;
    if (!isWordCharStrict(currChar ?? "") || nextChar !== void 0 && isWordCharStrict(currChar ?? "") && isWordCharStrict(nextChar) && isDifferentScript(currChar ?? "", nextChar)) {
      break;
    }
    if (nextChar !== void 0 && isCjkChar(currChar ?? "") && isCjkChar(nextChar)) {
      end++;
      break;
    }
    end++;
  }
  return end;
}
__name(findWordEndFallback, "findWordEndFallback");
var findNextWordStartInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i4 = col;
  if (i4 >= chars.length) return null;
  const currentChar = chars[i4];
  if (isWordCharStrict(currentChar)) {
    while (i4 < chars.length && isWordCharWithCombining(chars[i4])) {
      if (i4 + 1 < chars.length && isWordCharStrict(chars[i4 + 1]) && isDifferentScript(chars[i4], chars[i4 + 1])) {
        i4++;
        break;
      }
      i4++;
    }
  } else if (!isWhitespace4(currentChar)) {
    while (i4 < chars.length && !isWordCharStrict(chars[i4]) && !isWhitespace4(chars[i4])) {
      i4++;
    }
  }
  while (i4 < chars.length && isWhitespace4(chars[i4])) {
    i4++;
  }
  return i4 < chars.length ? i4 : null;
}, "findNextWordStartInLine");
var findPrevWordStartInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i4 = col;
  if (i4 <= 0) return null;
  i4--;
  while (i4 >= 0 && isWhitespace4(chars[i4])) {
    i4--;
  }
  if (i4 < 0) return null;
  if (isWordCharStrict(chars[i4])) {
    while (i4 >= 0 && isWordCharStrict(chars[i4])) {
      if (i4 - 1 >= 0 && isWordCharStrict(chars[i4 - 1]) && isDifferentScript(chars[i4], chars[i4 - 1])) {
        return i4;
      }
      i4--;
    }
    return i4 + 1;
  } else {
    while (i4 >= 0 && !isWordCharStrict(chars[i4]) && !isWhitespace4(chars[i4])) {
      i4--;
    }
    return i4 + 1;
  }
}, "findPrevWordStartInLine");
var findWordEndInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i4 = col;
  const atEndOfWordChar = i4 < chars.length && isWordCharWithCombining(chars[i4]) && (i4 + 1 >= chars.length || !isWordCharWithCombining(chars[i4 + 1]) || isWordCharStrict(chars[i4]) && i4 + 1 < chars.length && isWordCharStrict(chars[i4 + 1]) && isDifferentScript(chars[i4], chars[i4 + 1]));
  const atEndOfPunctuation = i4 < chars.length && !isWordCharWithCombining(chars[i4]) && !isWhitespace4(chars[i4]) && (i4 + 1 >= chars.length || isWhitespace4(chars[i4 + 1]) || isWordCharWithCombining(chars[i4 + 1]));
  if (atEndOfWordChar || atEndOfPunctuation) {
    i4++;
    while (i4 < chars.length && isWhitespace4(chars[i4])) {
      i4++;
    }
  }
  if (i4 < chars.length && !isWordCharWithCombining(chars[i4])) {
    while (i4 < chars.length && isWhitespace4(chars[i4])) {
      i4++;
    }
  }
  let foundWord = false;
  let lastBaseCharPos = -1;
  if (i4 < chars.length && isWordCharWithCombining(chars[i4])) {
    while (i4 < chars.length && isWordCharWithCombining(chars[i4])) {
      foundWord = true;
      if (isWordCharStrict(chars[i4])) {
        lastBaseCharPos = i4;
      }
      if (i4 + 1 < chars.length && isWordCharStrict(chars[i4 + 1]) && isDifferentScript(chars[i4], chars[i4 + 1])) {
        i4++;
        if (isWordCharStrict(chars[i4 - 1])) {
          lastBaseCharPos = i4 - 1;
        }
        break;
      }
      i4++;
    }
  } else if (i4 < chars.length && !isWhitespace4(chars[i4])) {
    while (i4 < chars.length && !isWordCharStrict(chars[i4]) && !isWhitespace4(chars[i4])) {
      foundWord = true;
      lastBaseCharPos = i4;
      i4++;
    }
  }
  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 offsetToRowCol = /* @__PURE__ */ __name((offset, lines) => {
  let running = 0;
  for (let i4 = 0; i4 < lines.length; i4++) {
    const lineLength = lines[i4].length + 1;
    if (running + lineLength > offset) {
      return { row: i4, col: offset - running };
    }
    running += lineLength;
  }
  const last2 = Math.max(0, lines.length - 1);
  return { row: last2, col: lines[last2]?.length ?? 0 };
}, "offsetToRowCol");
var getPositionFromOffsets = /* @__PURE__ */ __name((startOffset, endOffset, lines) => {
  const { row: startRow, col: startCol } = offsetToRowCol(startOffset, lines);
  const { row: endRow, col: endCol } = offsetToRowCol(endOffset, lines);
  return { startRow, startCol, endRow, endCol };
}, "getPositionFromOffsets");
var getLineRangeOffsets = /* @__PURE__ */ __name((startRow, lineCount, lines) => {
  let startOffset = 0;
  for (let i4 = 0; i4 < startRow; i4++) {
    startOffset += lines[i4].length + 1;
  }
  let endOffset = startOffset;
  for (let i4 = 0; i4 < lineCount; i4++) {
    const lineIndex = startRow + i4;
    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 i4 = 0; i4 < lines.length; i4++) {
    const line = lines[i4];
    const lineLength = cpLen(line);
    const lineLengthWithNewline = lineLength + (i4 < lines.length - 1 ? 1 : 0);
    if (offset <= currentOffset + lineLength) {
      row = i4;
      col = offset - currentOffset;
      return [row, col];
    } else if (offset <= currentOffset + lineLengthWithNewline) {
      row = i4;
      col = lineLength;
      if (offset === currentOffset + lineLengthWithNewline && i4 < lines.length - 1) {
        return [i4 + 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 i4 = 0; i4 < actualRow; i4++) {
    offset += cpLen(lines[i4]) + 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 i4 = currentPosInLogLine; i4 < codePointsInLogLine.length; i4++) {
          const char = codePointsInLogLine[i4];
          const charVisualWidth = getCachedStringWidth(char);
          if (currentChunkVisualWidth + charVisualWidth > viewportWidth) {
            if (lastWordBreakPoint !== -1 && numCodePointsAtLastWordBreak > 0 && currentPosInLogLine + numCodePointsAtLastWordBreak < i4) {
              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 = i4;
            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 parts2 = str2.split("\n");
      const lineContent = currentLine2(newCursorRow);
      const before = cpSlice(lineContent, 0, newCursorCol);
      const after = cpSlice(lineContent, newCursorCol);
      if (parts2.length > 1) {
        newLines[newCursorRow] = before + parts2[0];
        const remainingParts = parts2.slice(1);
        const lastPartOriginal = remainingParts.pop() ?? "";
        newLines.splice(newCursorRow + 1, 0, ...remainingParts);
        newLines.splice(
          newCursorRow + parts2.length - 1,
          0,
          lastPartOriginal + after
        );
        newCursorRow = newCursorRow + parts2.length - 1;
        newCursorCol = cpLen(lastPartOriginal);
      } else {
        newLines[newCursorRow] = before + parts2[0] + after;
        newCursorCol = cpLen(before) + cpLen(parts2[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;
            debugLogger138.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 start2 = cursorCol;
            const boundaries = getWordBoundaries(lineContent, arr);
            const startBoundary = findPrevWordStart(boundaries, start2);
            if (startBoundary !== null) {
              start2 = startBoundary;
            } else {
              let onlySpaces = true;
              for (let i4 = 0; i4 < start2; i4++) {
                if (isWordCharStrict(arr[i4] ?? "")) {
                  onlySpaces = false;
                  break;
                }
              }
              if (onlySpaces) {
                start2 = 0;
              } else {
                while (start2 > 0 && !isWordCharStrict(arr[start2 - 1] ?? ""))
                  start2--;
                while (start2 > 0) {
                  const prevChar = arr[start2 - 1];
                  const currChar = arr[start2];
                  if (!isWordCharStrict(prevChar ?? "") || isWordCharStrict(currChar ?? "") && isDifferentScript(currChar ?? "", prevChar ?? "")) {
                    break;
                  }
                  if (isCjkChar(currChar ?? "") && isCjkChar(prevChar ?? "")) {
                    break;
                  }
                  start2--;
                }
              }
            }
            newCursorCol = start2;
          }
          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 {
            const boundaries = getWordBoundaries(lineContent, arr);
            const endBoundary = findNextWordEnd(boundaries, cursorCol);
            let end;
            if (endBoundary !== null) {
              end = endBoundary;
              while (end < arr.length && isWhitespace4(arr[end] ?? "")) {
                end++;
              }
            } else if (cursorCol < arr.length && !isWordCharStrict(arr[cursorCol] ?? "")) {
              end = cursorCol;
              while (end < arr.length && !isWordCharStrict(arr[end] ?? ""))
                end++;
              if (end < arr.length) {
                const nextEnd = findNextWordEnd(boundaries, end);
                if (nextEnd !== null) {
                  end = nextEnd;
                } else {
                  end = findWordEndFallback(arr, end);
                }
              }
            } else {
              end = cursorCol;
              while (end < arr.length && !isWordCharStrict(arr[end] ?? ""))
                end++;
              end = findWordEndFallback(arr, 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 arr = toCodePoints(lineContent);
        const boundaries = getWordBoundaries(lineContent, arr);
        const startBoundary = findPrevWordStart(boundaries, newCursorCol);
        let start2;
        if (startBoundary !== null) {
          start2 = startBoundary;
        } else {
          const prevWordStart = findPrevWordStartInLine(
            lineContent,
            newCursorCol
          );
          start2 = prevWordStart === null ? 0 : prevWordStart;
        }
        newLines[newCursorRow] = cpSlice(lineContent, 0, start2) + cpSlice(lineContent, newCursorCol);
        newCursorCol = start2;
      } 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 arr = toCodePoints(lineContent);
        const boundaries = getWordBoundaries(lineContent, arr);
        const endBoundary = findNextWordEnd(boundaries, cursorCol);
        let end;
        if (endBoundary !== null) {
          end = endBoundary;
          while (end < arr.length && isWhitespace4(arr[end] ?? "")) {
            end++;
          }
        } else {
          const nextWordStart = findNextWordStartInLine(lineContent, cursorCol);
          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;
      debugLogger138.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: stdin2,
  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 = fs123.mkdtempSync(pathMod.join(os45.tmpdir(), "qwen-edit-"));
      const filePath = pathMod.join(tmpDir, "buffer.txt");
      fs123.writeFileSync(filePath, text, "utf8");
      dispatch({ type: "create_undo_snapshot" });
      const wasRaw = stdin2?.isRaw ?? false;
      try {
        setRawMode?.(false);
        const { status, error: error40 } = spawnSync4(editor, [filePath], {
          stdio: "inherit"
        });
        if (error40) throw error40;
        if (typeof status === "number" && status !== 0)
          throw new Error(`External editor exited with status ${status}`);
        let newText = fs123.readFileSync(filePath, "utf8");
        newText = newText.replace(/\r\n?/g, "\n");
        dispatch({ type: "set_text", payload: newText, pushToUndo: false });
      } catch (err2) {
        debugLogger138.error("[useTextBuffer] external editor error", err2);
      } finally {
        if (wasRaw) setRawMode?.(true);
        try {
          fs123.unlinkSync(filePath);
        } catch {
        }
        try {
          fs123.rmdirSync(tmpDir);
        } catch {
        }
      }
    },
    [text, stdin2, 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" && !key.shift) move("up");
      else if (key.name === "down" && !key.shift) 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 === "d") deleteWordRight();
      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 && key.name !== "tab" && input !== "	") {
        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_runtime16 = __toESM(require_jsx_runtime(), 1);
function TextInput({
  value,
  onChange,
  onSubmit,
  onTab,
  onUp,
  onDown,
  placeholder,
  height = 1,
  isActive = true,
  validationErrors = [],
  inputWidth = 80,
  initialCursorOffset
}) {
  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 || "",
    initialCursorOffset,
    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 (key.name === "tab" && !key.paste) {
        onTab?.(key);
        return;
      }
      if (key.name === "up" && onUp) {
        onUp();
        return;
      }
      if (key.name === "down" && onDown) {
        onDown();
        return;
      }
      if (allowMultiline && keyMatchers["newline" /* NEWLINE */](key)) {
        buffer.newline();
        return;
      }
      if (keyMatchers["submit" /* SUBMIT */](key) || !allowMultiline && key.name === "return") {
        handleSubmit();
        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_runtime16.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text3, { color: theme.text.accent, children: "> " }),
      /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: buffer.text.length === 0 && placeholder ? /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text3, { children: [
        import_chalk6.default.inverse(placeholder.slice(0, 1)),
        /* @__PURE__ */ (0, import_jsx_runtime16.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_runtime16.jsx)(Text3, { children: display }, `line-${visualIdxInRenderedSet}`);
      }) })
    ] }),
    validationErrors.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { flexDirection: "column", children: validationErrors.map((error40, index) => /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text3, { color: theme.status.error, children: [
      "\u26A0 ",
      error40
    ] }, index)) })
  ] });
}
__name(TextInput, "TextInput");

// packages/cli/src/ui/components/subagents/create/DescriptionInput.tsx
init_i18n();
var import_jsx_runtime17 = __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 (error40) {
      dispatch({ type: "SET_GENERATING", isGenerating: false });
      if (error40 instanceof Error && error40.name === "AbortError") {
        return;
      }
      dispatch({
        type: "SET_VALIDATION_ERRORS",
        errors: [
          t4("Failed to generate subagent: {{error}}", {
            error: error40 instanceof Error ? error40.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_runtime17.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime17.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_runtime17.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Box_default, { marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(build_default, {}) }),
      /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text3, { color: theme.text.accent, children: t4("Generating subagent configuration...") })
    ] }) : /* @__PURE__ */ (0, import_jsx_runtime17.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);
init_dist4();
init_i18n();
var import_jsx_runtime18 = __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_runtime18.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime18.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_runtime18.jsx)(Box_default, { flexDirection: "column", children: currentCategory.id === "all" ? /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text3, { color: theme.text.secondary, children: t4("All tools selected, including MCP tools") }) : currentCategory.tools.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(import_jsx_runtime18.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text3, { color: theme.text.secondary, children: t4("Selected tools:") }),
      /* @__PURE__ */ (0, import_jsx_runtime18.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_runtime18.jsxs)(import_jsx_runtime18.Fragment, { children: [
          categoryReadTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(Text3, { color: theme.text.secondary, children: [
            "\u2022 ",
            t4("Read-only tools:"),
            " ",
            categoryReadTools.join(", ")
          ] }),
          categoryEditTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(Text3, { color: theme.text.secondary, children: [
            "\u2022 ",
            t4("Edit tools:"),
            " ",
            categoryEditTools.join(", ")
          ] }),
          categoryExecuteTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime18.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_runtime19 = __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_runtime19.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime19.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_runtime19.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Text3, { color: theme.text.secondary, children: "Preview:" }),
      /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime19.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);
init_dist4();

// packages/cli/src/ui/hooks/useLaunchEditor.ts
init_esbuild_shims();
var import_react51 = __toESM(require_react(), 1);
init_dist4();
import { spawnSync as spawnSync5 } from "child_process";
function getEditorCommand(preferredEditor) {
  if (preferredEditor) {
    const execCmd = getEditorExecutable(preferredEditor);
    if (!execCmd) {
      throw new Error(
        `No available editor found for ${preferredEditor}. Please install a supported editor or set a different preferredEditor in settings.`
      );
    }
    return execCmd;
  }
  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: stdin2, 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 = stdin2?.isRaw ?? false;
      try {
        setRawMode?.(false);
        const needsShell = process.platform === "win32" && (editorCommand2.endsWith(".cmd") || editorCommand2.endsWith(".bat"));
        const { status, error: error40 } = spawnSync5(editorCommand2, editorArgs, {
          stdio: "inherit",
          shell: needsShell
        });
        if (error40) throw error40;
        if (typeof status === "number" && status !== 0) {
          throw new Error(`Editor exited with status ${status}`);
        }
      } finally {
        if (wasRaw) setRawMode?.(true);
      }
    },
    [settings.merged.general?.preferredEditor, setRawMode, stdin2]
  );
  return launchEditor;
}
__name(useLaunchEditor, "useLaunchEditor");

// packages/cli/src/ui/components/subagents/create/CreationSummary.tsx
init_i18n();
var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
var debugLogger139 = 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 (error40) {
        debugLogger139.warn("Error checking subagent name availability:", error40);
      }
      if (state.generatedDescription.length > 1e3) {
        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 (error40) {
      setSaveError(
        error40 instanceof Error ? error40.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 (error40) {
      setSaveError(
        t4("Failed to save and edit subagent: {{error}}", {
          error: error40 instanceof Error ? error40.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_runtime20.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { bold: true, color: theme.status.success, children: t4("\u2705 Subagent Created Successfully!") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { children: t4('Subagent "{{name}}" has been saved to {{level}} level.', {
        name: state.generatedName,
        level: state.location
      }) }) })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { color: theme.text.primary, children: t4("Name: ") }),
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { color: getColorForDisplay(state.color), children: state.generatedName })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { color: theme.text.primary, children: t4("Location: ") }),
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { children: state.location === "project" ? t4("Project Level (.qwen/agents/)") : t4("User Level (~/.qwen/agents/)") })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { color: theme.text.primary, children: t4("Tools: ") }),
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { children: toolsDisplay })
      ] }),
      shouldShowColor(state.color) && /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { color: theme.text.primary, children: t4("Color: ") }),
        /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { color: getColorForDisplay(state.color), children: state.color })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { color: theme.text.primary, children: t4("Description:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { wrap: "wrap", children: truncateText2(state.generatedDescription, 250) }) }),
      /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { color: theme.text.primary, children: t4("System Prompt:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { wrap: "wrap", children: truncateText2(state.generatedSystemPrompt, 250) }) })
    ] }),
    saveError && /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { bold: true, color: theme.status.error, children: t4("\u274C Error saving subagent:") }),
      /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { flexDirection: "column", padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { color: theme.status.error, wrap: "wrap", children: saveError }) })
    ] }),
    warnings.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text3, { bold: true, color: theme.status.warning, children: t4("Warnings:") }),
      /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { flexDirection: "column", padding: 1, paddingBottom: 0, children: warnings.map((warning, index) => /* @__PURE__ */ (0, import_jsx_runtime20.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_runtime21 = __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 error40 = validate3 ? validate3(value) : value.length === 0 ? "Please enter a value." : null;
    if (error40) {
      dispatch({ type: "SET_VALIDATION_ERRORS", errors: [error40] });
      return;
    }
    dispatch({ type: "SET_VALIDATION_ERRORS", errors: [] });
    onNext();
  }, [dispatch, onNext, validate3, initialText]);
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    description && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text3, { color: theme.text.secondary, children: description }) }),
    /* @__PURE__ */ (0, import_jsx_runtime21.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
init_i18n();
var import_jsx_runtime22 = __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_runtime22.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text3, { bold: true, children: getStepHeaderText() }) });
  }, [state.currentStep, state.generationMethod]);
  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_runtime22.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime22.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_runtime22.jsx)(LocationSelector, { ...stepProps });
      case "GEN_METHOD":
        return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(GenerationMethodSelector, { ...stepProps });
      case "LLM_DESC":
        return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(DescriptionInput, { ...stepProps });
      case "MANUAL_NAME":
        return /* @__PURE__ */ (0, import_jsx_runtime22.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_runtime22.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_runtime22.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_runtime22.jsx)(
          ToolSelector,
          {
            tools: state.selectedTools,
            onSelect: (tools) => {
              dispatch({ type: "SET_TOOLS", tools });
              handleNext();
            },
            config: config2
          }
        );
      case "COLOR":
        return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
          ColorSelector,
          {
            color: state.color,
            agentName: state.generatedName,
            onSelect: (color) => {
              dispatch({ type: "SET_BACKGROUND_COLOR", color });
              handleNext();
            }
          }
        );
      case "FINAL":
        return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(CreationSummary, { ...stepProps });
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime22.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_runtime22.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(
    Box_default,
    {
      borderStyle: "single",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      gap: 1,
      children: [
        renderStepHeader(),
        renderStepContent(),
        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);
init_dist4();
init_i18n();
var import_jsx_runtime23 = __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: name4 } = key;
      if (name4 === "up" || name4 === "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 (name4 === "down" || name4 === "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 (name4 === "return" || name4 === "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_runtime23.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text3, { color: theme.text.secondary, children: t4("No subagents found.") }),
      /* @__PURE__ */ (0, import_jsx_runtime23.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_runtime23.jsxs)(Box_default, { alignItems: "center", children: [
      /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text3, { color: isSelected ? theme.text.accent : theme.text.primary, children: isSelected ? "\u25CF" : " " }) }),
      /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Text3, { color: textColor, wrap: "truncate", children: [
        agent.name,
        agent.isBuiltin && /* @__PURE__ */ (0, import_jsx_runtime23.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_runtime23.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_runtime23.jsxs)(Box_default, { flexDirection: "column", children: [
    projectAgents.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text3, { color: theme.text.primary, bold: true, children: t4("Project Level ({{path}})", {
        path: projectAgents[0].filePath?.replace(/\/[^/]+$/, "") || ""
      }) }),
      /* @__PURE__ */ (0, import_jsx_runtime23.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_runtime23.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        marginBottom: builtinAgents.length > 0 ? 1 : 0,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text3, { color: theme.text.primary, bold: true, children: t4("User Level ({{path}})", {
            path: userAgents[0].filePath?.replace(/\/[^/]+$/, "") || ""
          }) }),
          /* @__PURE__ */ (0, import_jsx_runtime23.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_runtime23.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        marginBottom: extensionAgents.length > 0 ? 1 : 0,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text3, { color: theme.text.primary, bold: true, children: t4("Built-in Agents") }),
          /* @__PURE__ */ (0, import_jsx_runtime23.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_runtime23.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text3, { color: theme.text.primary, bold: true, children: t4("Extension Agents") }),
      /* @__PURE__ */ (0, import_jsx_runtime23.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_runtime23.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime23.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);
init_dist4();
init_i18n();
var import_jsx_runtime24 = __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_runtime24.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
    RadioButtonSelect,
    {
      items: actions,
      initialIndex: selectedIndex,
      onSelect: handleActionSelect,
      showNumbers: false
    }
  ) });
}, "ActionSelectionStep");

// packages/cli/src/ui/components/subagents/manage/AgentViewerStep.tsx
init_esbuild_shims();
init_dist4();
init_i18n();
var import_jsx_runtime25 = __toESM(require_jsx_runtime(), 1);
var AgentViewerStep = /* @__PURE__ */ __name(({ selectedAgent }) => {
  if (!selectedAgent) {
    return /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime25.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_runtime25.jsx)(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("File Path: ") }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { children: agent.filePath })
    ] }),
    /* @__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 })
    ] }),
    agent.model && /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { color: theme.text.primary, children: t4("Model: ") }),
      /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text3, { children: agent.model })
    ] }),
    shouldShowColor(agent.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(agent.color), children: agent.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: agent.description }) }),
    /* @__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: agent.systemPrompt }) })
  ] }) });
}, "AgentViewerStep");

// packages/cli/src/ui/components/subagents/manage/AgentEditStep.tsx
init_esbuild_shims();
var import_react57 = __toESM(require_react(), 1);
init_dist4();
init_i18n();
var import_jsx_runtime26 = __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 [error40, 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 (err2) {
          setError(
            t4("Failed to launch editor: {{error}}", {
              error: err2 instanceof Error ? err2.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_runtime26.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime26.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
      }
    ) }),
    error40 && /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Text3, { bold: true, color: theme.status.error, children: t4("\u274C Error:") }),
      /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Box_default, { flexDirection: "column", padding: 1, paddingBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Text3, { color: theme.status.error, wrap: "wrap", children: error40 }) })
    ] })
  ] });
}
__name(EditOptionsStep, "EditOptionsStep");

// packages/cli/src/ui/components/subagents/manage/AgentDeleteStep.tsx
init_esbuild_shims();
init_dist4();
init_dist4();
init_i18n();
var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1);
var debugLogger140 = 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 (error40) {
          debugLogger140.error("Failed to delete agent:", error40);
        }
      } else if (key.name === "n") {
        onNavigateBack();
      }
    },
    { isActive: true }
  );
  if (!selectedAgent) {
    return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Text3, { color: theme.status.error, children: t4("No agent selected") }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime27.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
init_dist4();
init_i18n();
var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
var debugLogger141 = 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 (error40) {
        debugLogger141.error("Failed to delete agent:", error40);
        throw error40;
      }
    },
    [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_runtime28.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime28.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_runtime28.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime28.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_runtime28.jsx)(
          AgentSelectionStep,
          {
            availableAgents,
            onAgentSelect: handleSelectAgent,
            ...commonProps
          }
        );
      case MANAGEMENT_STEPS.ACTION_SELECTION:
        return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(ActionSelectionStep, { selectedAgent, ...commonProps });
      case MANAGEMENT_STEPS.AGENT_VIEWER:
        return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(AgentViewerStep, { selectedAgent, ...commonProps });
      case MANAGEMENT_STEPS.EDIT_OPTIONS:
        return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(EditOptionsStep, { selectedAgent, ...commonProps });
      case MANAGEMENT_STEPS.EDIT_TOOLS:
        return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime28.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 (error40) {
                  debugLogger141.error("Failed to save agent changes:", error40);
                }
              }
            },
            config: config2
          }
        ) });
      case MANAGEMENT_STEPS.EDIT_COLOR:
        return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime28.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 (error40) {
                  debugLogger141.error("Failed to save color changes:", error40);
                }
              }
            }
          }
        ) });
      case MANAGEMENT_STEPS.DELETE_CONFIRMATION:
        return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
          AgentDeleteStep,
          {
            selectedAgent,
            onDelete: handleDeleteAgent,
            ...commonProps
          }
        );
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime28.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_runtime28.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime28.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_react61 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx
init_esbuild_shims();
var import_react60 = __toESM(require_react(), 1);
init_dist4();
init_i18n();

// packages/cli/src/ui/components/messages/AskUserQuestionDialog.tsx
init_esbuild_shims();
var import_react59 = __toESM(require_react(), 1);
init_dist4();
init_i18n();
var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1);
var AskUserQuestionDialog = /* @__PURE__ */ __name(({
  confirmationDetails,
  isFocused = true,
  onConfirm
}) => {
  const [currentQuestionIndex, setCurrentQuestionIndex] = (0, import_react59.useState)(0);
  const [selectedOptions, setSelectedOptions] = (0, import_react59.useState)({});
  const [customInputValues, setCustomInputValues] = (0, import_react59.useState)({});
  const [selectedIndex, setSelectedIndex] = (0, import_react59.useState)(0);
  const [multiSelectedOptions, setMultiSelectedOptions] = (0, import_react59.useState)({});
  const [customInputChecked, setCustomInputChecked] = (0, import_react59.useState)({});
  const hasMultipleQuestions = confirmationDetails.questions.length > 1;
  const totalTabs = hasMultipleQuestions ? confirmationDetails.questions.length + 1 : confirmationDetails.questions.length;
  const isSubmitTab = hasMultipleQuestions && currentQuestionIndex === totalTabs - 1;
  const currentQuestion = isSubmitTab ? null : confirmationDetails.questions[currentQuestionIndex];
  const isMultiSelect = currentQuestion?.multiSelect ?? false;
  const totalOptions = currentQuestion ? currentQuestion.options.length + 1 : 2;
  const isCustomInputSelected = !isSubmitTab && currentQuestion && selectedIndex === currentQuestion.options.length;
  const currentCustomInputValue = customInputValues[currentQuestionIndex] ?? "";
  const isCustomInputAnswer = !isSubmitTab && currentQuestion && !isMultiSelect && selectedOptions[currentQuestionIndex] !== void 0 && !currentQuestion.options.some(
    (opt) => opt.label === selectedOptions[currentQuestionIndex]
  );
  const getAnswerForQuestion = /* @__PURE__ */ __name((idx) => {
    const q2 = confirmationDetails.questions[idx];
    if (q2?.multiSelect) {
      const selections = [...multiSelectedOptions[idx] ?? []];
      const customValue = (customInputValues[idx] ?? "").trim();
      if (customInputChecked[idx] && customValue) {
        selections.push(customValue);
      }
      return selections.length > 0 ? selections.join(", ") : void 0;
    }
    return selectedOptions[idx];
  }, "getAnswerForQuestion");
  const handleSubmit = /* @__PURE__ */ __name(async () => {
    const answers = {};
    confirmationDetails.questions.forEach((_2, idx) => {
      const answer = getAnswerForQuestion(idx);
      if (answer !== void 0) {
        answers[idx] = answer;
      }
    });
    await onConfirm(ToolConfirmationOutcome.ProceedOnce, { answers });
  }, "handleSubmit");
  const selectAndAdvance = /* @__PURE__ */ __name((value) => {
    setSelectedOptions((prev) => ({ ...prev, [currentQuestionIndex]: value }));
    if (!hasMultipleQuestions) {
      void onConfirm(ToolConfirmationOutcome.ProceedOnce, {
        answers: { [currentQuestionIndex]: value }
      });
    } else if (currentQuestionIndex < totalTabs - 1) {
      setTimeout(() => {
        setCurrentQuestionIndex((prev) => Math.min(prev + 1, totalTabs - 1));
        setSelectedIndex(0);
      }, 150);
    }
  }, "selectAndAdvance");
  const handleMultiSelectSubmit = /* @__PURE__ */ __name(() => {
    if (!currentQuestion) return;
    const selections = [...multiSelectedOptions[currentQuestionIndex] ?? []];
    const customValue = currentCustomInputValue.trim();
    if (customInputChecked[currentQuestionIndex] && customValue) {
      selections.push(customValue);
    }
    if (selections.length === 0) return;
    selectAndAdvance(selections.join(", "));
  }, "handleMultiSelectSubmit");
  const handleCustomInputSubmit = /* @__PURE__ */ __name(() => {
    const trimmedValue = currentCustomInputValue.trim();
    if (isMultiSelect) {
      if (!trimmedValue) return;
      setCustomInputChecked((prev) => ({
        ...prev,
        [currentQuestionIndex]: !prev[currentQuestionIndex]
      }));
      return;
    }
    if (!trimmedValue) return;
    selectAndAdvance(trimmedValue);
  }, "handleCustomInputSubmit");
  useKeypress(
    (key) => {
      if (isCustomInputSelected) {
        if (key.name === "up") {
          setSelectedIndex(Math.max(0, selectedIndex - 1));
          return;
        }
        if (key.name === "down") {
          setSelectedIndex(Math.min(totalOptions - 1, selectedIndex + 1));
          return;
        }
        if (key.name === "escape" || key.ctrl && key.name === "c") {
          void onConfirm(ToolConfirmationOutcome.Cancel);
          return;
        }
        return;
      }
      const input = key.sequence;
      if (key.name === "left" && hasMultipleQuestions) {
        if (currentQuestionIndex > 0) {
          setCurrentQuestionIndex(currentQuestionIndex - 1);
          setSelectedIndex(0);
        }
        return;
      }
      if (key.name === "right" && hasMultipleQuestions) {
        if (currentQuestionIndex < totalTabs - 1) {
          setCurrentQuestionIndex(currentQuestionIndex + 1);
          setSelectedIndex(0);
        }
        return;
      }
      if (key.name === "up") {
        setSelectedIndex(Math.max(0, selectedIndex - 1));
        return;
      }
      if (key.name === "down") {
        setSelectedIndex(Math.min(totalOptions - 1, selectedIndex + 1));
        return;
      }
      const numKey = parseInt(input || "", 10);
      if (!isNaN(numKey) && numKey >= 1 && numKey <= totalOptions) {
        const targetIndex = numKey - 1;
        setSelectedIndex(targetIndex);
        if (!isMultiSelect && !isSubmitTab && currentQuestion && targetIndex < currentQuestion.options.length) {
          const option2 = currentQuestion.options[targetIndex];
          if (option2) {
            selectAndAdvance(option2.label);
          }
        }
        return;
      }
      if (key.name === "space" && isMultiSelect && currentQuestion) {
        if (selectedIndex < currentQuestion.options.length) {
          const option2 = currentQuestion.options[selectedIndex];
          if (option2) {
            const current = multiSelectedOptions[currentQuestionIndex] ?? [];
            const isChecked = current.includes(option2.label);
            const updated = isChecked ? current.filter((l3) => l3 !== option2.label) : [...current, option2.label];
            setMultiSelectedOptions((prev) => ({
              ...prev,
              [currentQuestionIndex]: updated
            }));
          }
        }
        return;
      }
      if (key.name === "return") {
        if (isSubmitTab) {
          if (selectedIndex === 0) {
            void handleSubmit();
          } else {
            void onConfirm(ToolConfirmationOutcome.Cancel);
          }
          return;
        }
        if (isMultiSelect && currentQuestion) {
          if (selectedIndex === currentQuestion.options.length) {
            return;
          }
          handleMultiSelectSubmit();
          return;
        }
        if (currentQuestion && selectedIndex < currentQuestion.options.length) {
          const option2 = currentQuestion.options[selectedIndex];
          if (option2) {
            selectAndAdvance(option2.label);
          }
        }
        return;
      }
      if (key.name === "escape" || key.ctrl && key.name === "c") {
        void onConfirm(ToolConfirmationOutcome.Cancel);
        return;
      }
    },
    { isActive: isFocused }
  );
  if (isSubmitTab) {
    return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { flexDirection: "column", padding: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { marginBottom: 1, flexDirection: "row", gap: 1, children: [
        confirmationDetails.questions.map((q2, idx) => {
          const isAnswered = getAnswerForQuestion(idx) !== void 0;
          return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Text3, { dimColor: true, children: [
            isAnswered ? "  " : "  ",
            q2.header,
            isAnswered ? " \u2713" : ""
          ] }) }, idx);
        }),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Text3, { color: theme.text.accent, bold: true, children: [
          "\u25B8 ",
          t4("Submit")
        ] }) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text3, { bold: true, children: t4("Your answers:") }),
        confirmationDetails.questions.map((q2, idx) => {
          const answer = getAnswerForQuestion(idx);
          return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Text3, { children: [
            q2.header,
            ":",
            " ",
            answer ? /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text3, { color: theme.text.accent, children: answer }) : /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text3, { dimColor: true, children: t4("(not answered)") })
          ] }) }, idx);
        })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { marginTop: 1, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text3, { children: t4("Ready to submit your answers?") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
          Text3,
          {
            color: selectedIndex === 0 ? theme.text.accent : theme.text.primary,
            bold: selectedIndex === 0,
            children: [
              selectedIndex === 0 ? "\u276F " : "  ",
              "1. ",
              t4("Submit answers")
            ]
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
          Text3,
          {
            color: selectedIndex === 1 ? theme.text.accent : theme.text.primary,
            bold: selectedIndex === 1,
            children: [
              selectedIndex === 1 ? "\u276F " : "  ",
              "2. ",
              t4("Cancel")
            ]
          }
        ) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text3, { dimColor: true, children: t4("\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select") }) })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { flexDirection: "column", padding: 1, children: [
    hasMultipleQuestions && /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { marginBottom: 1, flexDirection: "row", gap: 1, children: [
      confirmationDetails.questions.map((q2, idx) => {
        const isAnswered = getAnswerForQuestion(idx) !== void 0;
        return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
          Text3,
          {
            color: idx === currentQuestionIndex ? theme.text.accent : theme.text.primary,
            bold: idx === currentQuestionIndex,
            dimColor: idx !== currentQuestionIndex,
            children: [
              idx === currentQuestionIndex ? "\u25B8 " : "  ",
              q2.header,
              isAnswered ? " \u2713" : ""
            ]
          }
        ) }, idx);
      }),
      /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Text3, { dimColor: true, children: [
        " ",
        t4("Submit")
      ] }) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      !hasMultipleQuestions && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text3, { color: theme.text.accent, bold: true, children: currentQuestion.header }) }),
      /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text3, { children: currentQuestion.question })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      currentQuestion.options.map((opt, index) => {
        const isSelected = selectedIndex === index;
        const isMultiChecked = isMultiSelect && (multiSelectedOptions[currentQuestionIndex] ?? []).includes(
          opt.label
        );
        const isAnswered = !isMultiSelect && selectedOptions[currentQuestionIndex] === opt.label;
        const isHighlighted = isSelected || isAnswered || isMultiChecked;
        const prefixWidth = 2 + (isMultiSelect ? 4 : 0) + String(index + 1).length + 2;
        return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
            Text3,
            {
              color: isHighlighted ? theme.text.accent : theme.text.primary,
              bold: isHighlighted,
              children: [
                isSelected ? "\u276F " : "  ",
                isMultiSelect ? isMultiChecked ? "[\u2713] " : "[ ] " : "",
                index + 1,
                ". ",
                opt.label,
                isAnswered ? " \u2713" : ""
              ]
            }
          ) }),
          opt.description && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { marginLeft: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text3, { dimColor: true, children: opt.description }) })
        ] }, index);
      }),
      /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { flexDirection: "column", children: isCustomInputSelected ? (
        // Inline TextInput replaces the option text
        /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Text3, { color: theme.text.accent, bold: true, children: [
            "\u276F",
            " ",
            isMultiSelect ? customInputChecked[currentQuestionIndex] ? "[\u2713] " : "[ ] " : "",
            currentQuestion.options.length + 1,
            ".",
            " "
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
            TextInput,
            {
              value: currentCustomInputValue,
              initialCursorOffset: currentCustomInputValue.length,
              onChange: (value) => {
                const oldValue = customInputValues[currentQuestionIndex] ?? "";
                if (isMultiSelect && value !== oldValue) {
                  setCustomInputChecked((prevChecked) => ({
                    ...prevChecked,
                    [currentQuestionIndex]: value.trim().length > 0
                  }));
                }
                setCustomInputValues((prev) => ({
                  ...prev,
                  [currentQuestionIndex]: value
                }));
              },
              onSubmit: handleCustomInputSubmit,
              placeholder: t4("Type something..."),
              isActive: true,
              inputWidth: 50
            }
          )
        ] })
      ) : (
        // Show typed value or placeholder when not selected
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
          Text3,
          {
            color: isCustomInputAnswer || customInputChecked[currentQuestionIndex] ? theme.text.accent : theme.text.primary,
            bold: !!(isCustomInputAnswer || customInputChecked[currentQuestionIndex]),
            dimColor: !currentCustomInputValue && !isCustomInputAnswer && !customInputChecked[currentQuestionIndex],
            children: [
              "  ",
              isMultiSelect ? customInputChecked[currentQuestionIndex] ? "[\u2713] " : "[ ] " : "",
              currentQuestion.options.length + 1,
              ".",
              " ",
              currentCustomInputValue || t4("Type something..."),
              isCustomInputAnswer ? " \u2713" : ""
            ]
          }
        ) })
      ) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { flexDirection: "column", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text3, { dimColor: true, children: hasMultipleQuestions ? isMultiSelect ? t4(
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space: Toggle | Enter: Confirm | Esc: Cancel"
    ) : t4(
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select | Esc: Cancel"
    ) : isMultiSelect ? t4(
      "\u2191/\u2193: Navigate | Space: Toggle | Enter: Confirm | Esc: Cancel"
    ) : t4("\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel") }) }) })
  ] });
}, "AskUserQuestionDialog");

// packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx
var import_jsx_runtime30 = __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_react60.useState)(null);
  const [isDiffingEnabled, setIsDiffingEnabled] = (0, import_react60.useState)(false);
  (0, import_react60.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) => {
    onConfirm(outcome);
    if (confirmationDetails.type === "edit") {
      if (config2.getIdeMode() && isDiffingEnabled) {
        const cliOutcome = outcome === ToolConfirmationOutcome.Cancel ? "rejected" : "accepted";
        await ideClient?.resolveDiffFromCli(
          confirmationDetails.filePath,
          cliOutcome
        );
      }
    }
  }, "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_runtime30.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { wrap: "truncate", children: t4("Do you want to proceed?") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime30.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_runtime30.jsxs)(
        Box_default,
        {
          minWidth: "90%",
          borderStyle: "round",
          borderColor: theme.border.default,
          justifyContent: "space-around",
          padding: 1,
          overflow: "hidden",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Text3, { color: theme.text.primary, children: [
              t4("Modify in progress:"),
              " "
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime30.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_runtime30.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 && !confirmationDetails.hideAlwaysAllow) {
      const friendlyLabel = executionProps.permissionRules?.length ? ` ${buildHumanReadableRuleLabel(executionProps.permissionRules)}` : "";
      options2.push({
        label: friendlyLabel ? t4("Always allow {{action}} in this project", {
          action: friendlyLabel.trim()
        }) : t4("Always allow in this project"),
        value: ToolConfirmationOutcome.ProceedAlwaysProject,
        key: "Always allow in this project"
      });
      options2.push({
        label: friendlyLabel ? t4("Always allow {{action}} for this user", {
          action: friendlyLabel.trim()
        }) : t4("Always allow for this user"),
        value: ToolConfirmationOutcome.ProceedAlwaysUser,
        key: "Always allow for this user"
      });
    }
    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_runtime30.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { paddingX: 1, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
      MaxSizedBox,
      {
        maxHeight: bodyContentHeight,
        maxWidth: Math.max(contentWidth, 1),
        children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { color: theme.text.link, children: executionProps.command }) })
      }
    ) }) });
  } else if (confirmationDetails.type === "plan") {
    const planProps = confirmationDetails;
    question = planProps.title;
    options2.push({
      key: "restore-previous",
      label: t4("Yes, restore previous mode ({{mode}})", {
        mode: planProps.prePlanMode ?? "default"
      }),
      value: ToolConfirmationOutcome.RestorePrevious
    });
    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_runtime30.jsx)(Box_default, { flexDirection: "column", paddingX: 1, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime30.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 && !confirmationDetails.hideAlwaysAllow) {
      const friendlyLabel = "permissionRules" in infoProps && infoProps.permissionRules?.length ? ` ${buildHumanReadableRuleLabel(infoProps.permissionRules)}` : "";
      options2.push({
        label: friendlyLabel ? t4("Always allow {{action}} in this project", {
          action: friendlyLabel.trim()
        }) : t4("Always allow in this project"),
        value: ToolConfirmationOutcome.ProceedAlwaysProject,
        key: "Always allow in this project"
      });
      options2.push({
        label: friendlyLabel ? t4("Always allow {{action}} for this user", {
          action: friendlyLabel.trim()
        }) : t4("Always allow for this user"),
        value: ToolConfirmationOutcome.ProceedAlwaysUser,
        key: "Always allow for this user"
      });
    }
    options2.push({
      label: t4("No, suggest changes (esc)"),
      value: ToolConfirmationOutcome.Cancel,
      key: "No, suggest changes (esc)"
    });
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, marginLeft: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(RenderInline, { text: infoProps.prompt, textColor: theme.text.link }) }),
      displayUrls && infoProps.urls && infoProps.urls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { color: theme.text.primary, children: t4("URLs to fetch:") }),
        infoProps.urls.map((url3) => /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Text3, { children: [
          " ",
          "- ",
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(RenderInline, { text: url3 })
        ] }, url3))
      ] })
    ] });
  } else if (confirmationDetails.type === "ask_user_question") {
    return /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
      AskUserQuestionDialog,
      {
        confirmationDetails,
        isFocused,
        onConfirm
      }
    );
  } else {
    const mcpProps = confirmationDetails;
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, marginLeft: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { color: theme.text.link, children: t4("MCP Server: {{server}}", { server: mcpProps.serverName }) }),
      /* @__PURE__ */ (0, import_jsx_runtime30.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 && !confirmationDetails.hideAlwaysAllow) {
      const friendlyLabel = mcpProps.permissionRules?.length ? ` ${buildHumanReadableRuleLabel(mcpProps.permissionRules)}` : "";
      options2.push({
        label: friendlyLabel ? t4("Always allow {{action}} in this project", {
          action: friendlyLabel.trim()
        }) : t4("Always allow in this project"),
        value: ToolConfirmationOutcome.ProceedAlwaysProject,
        key: "Always allow in this project"
      });
      options2.push({
        label: friendlyLabel ? t4("Always allow {{action}} for this user", {
          action: friendlyLabel.trim()
        }) : t4("Always allow for this user"),
        value: ToolConfirmationOutcome.ProceedAlwaysUser,
        key: "Always allow for this user"
      });
    }
    options2.push({
      label: t4("No, suggest changes (esc)"),
      value: ToolConfirmationOutcome.Cancel,
      key: "No, suggest changes (esc)"
    });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { flexDirection: "column", padding: 1, width: contentWidth, children: [
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { flexGrow: 1, flexShrink: 1, overflow: "hidden", marginBottom: 1, children: bodyContent }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { marginBottom: 1, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text3, { color: theme.text.primary, wrap: "truncate", children: question }) }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
      RadioButtonSelect,
      {
        items: options2,
        onSelect: handleSelect,
        isFocused
      }
    ) })
  ] });
}, "ToolConfirmationMessage");

// packages/cli/src/ui/components/subagents/runtime/AgentExecutionDisplay.tsx
var import_jsx_runtime31 = __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 "background":
      return theme.text.secondary;
    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 "background":
      return "Running in background";
    case "cancelled":
      return "User Cancelled";
    case "failed":
      return "Failed";
    default:
      return "Unknown";
  }
}, "getStatusText");
var BackgroundManageHint = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.secondary, children: " (\u2193 to manage)" }), "BackgroundManageHint");
var MAX_TOOL_CALLS = 5;
var MAX_VERBOSE_TOOL_CALLS = 12;
var MAX_TASK_PROMPT_LINES = 5;
var DEFAULT_DETAIL_HEIGHT = 18;
var RUNNING_FIXED_OVERHEAD = 10;
var COMPLETED_FIXED_OVERHEAD = 22;
var ROWS_PER_TOOL_CALL = 2;
function truncateToVisualWidth(text, maxWidth) {
  const visualWidth = Math.max(1, Math.floor(maxWidth));
  const ellipsis = "...";
  const ellipsisWidth = getCachedStringWidth(ellipsis);
  let currentWidth = 0;
  let result = "";
  for (const char of toCodePoints(text)) {
    const charWidth = Math.max(getCachedStringWidth(char), 1);
    if (currentWidth + charWidth > visualWidth) {
      const availableWidth = Math.max(0, visualWidth - ellipsisWidth);
      let trimmed2 = "";
      let trimmedWidth = 0;
      for (const trimmedChar of toCodePoints(result)) {
        const trimmedCharWidth = Math.max(getCachedStringWidth(trimmedChar), 1);
        if (trimmedWidth + trimmedCharWidth > availableWidth) {
          break;
        }
        trimmed2 += trimmedChar;
        trimmedWidth += trimmedCharWidth;
      }
      return trimmed2 + ellipsis;
    }
    result += char;
    currentWidth += charWidth;
  }
  return result;
}
__name(truncateToVisualWidth, "truncateToVisualWidth");
var AgentExecutionDisplay = /* @__PURE__ */ __name(({
  data,
  availableHeight,
  childWidth,
  config: config2,
  isFocused = true,
  isWaitingForOtherApproval = false
}) => {
  const [displayMode, setDisplayMode] = import_react61.default.useState("compact");
  const detailHeight = Math.max(
    4,
    Math.floor(availableHeight ?? DEFAULT_DETAIL_HEIGHT)
  );
  const fixedOverhead = data.status === "running" ? RUNNING_FIXED_OVERHEAD : COMPLETED_FIXED_OVERHEAD;
  const renderableBudget = Math.max(2, detailHeight - fixedOverhead);
  const promptBudget = Math.max(1, Math.floor(renderableBudget / 3));
  const toolBudget = Math.max(
    1,
    Math.floor((renderableBudget - promptBudget) / ROWS_PER_TOOL_CALL)
  );
  const maxTaskPromptLines = displayMode === "verbose" ? Math.min(8, promptBudget) : Math.min(MAX_TASK_PROMPT_LINES, promptBudget);
  const maxToolCalls = displayMode === "verbose" ? Math.min(MAX_VERBOSE_TOOL_CALLS, toolBudget) : Math.min(MAX_TOOL_CALLS, toolBudget);
  const agentColor = (0, import_react61.useMemo)(() => {
    const colorOption = COLOR_OPTIONS.find(
      (option2) => option2.name === data.subagentColor
    );
    return colorOption?.value || theme.text.accent;
  }, [data.subagentColor]);
  const promptChildWidth = Math.max(1, childWidth - 2);
  const slicedPrompt = (0, import_react61.useMemo)(
    () => sliceTextByVisualHeight(
      data.taskPrompt,
      maxTaskPromptLines,
      promptChildWidth,
      { minHeight: 1, overflowDirection: "bottom" }
    ),
    [data.taskPrompt, maxTaskPromptLines, promptChildWidth]
  );
  const footerText = import_react61.default.useMemo(() => {
    if (data.status !== "running") return "";
    if (displayMode === "default") {
      const hasMoreLines = slicedPrompt.hiddenLinesCount > 0;
      const hasMoreToolCalls = data.toolCalls && data.toolCalls.length > maxToolCalls;
      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.status,
    data.toolCalls,
    slicedPrompt.hiddenLinesCount,
    maxToolCalls
  ]);
  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: data.status === "running" && isFocused }
  );
  if (displayMode === "compact") {
    return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", children: [
      !data.pendingConfirmation && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { bold: true, color: agentColor, children: data.subagentName }),
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(StatusDot, { status: data.status }),
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(StatusIndicator, { status: data.status }),
        data.status === "background" && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(BackgroundManageHint, {})
      ] }),
      data.status === "running" && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(import_jsx_runtime31.Fragment, { children: [
        data.toolCalls && data.toolCalls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
            ToolCallItem,
            {
              toolCall: data.toolCalls[data.toolCalls.length - 1],
              compact: true
            }
          ),
          data.toolCalls.length > 1 && !data.pendingConfirmation && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "row", paddingLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { color: theme.text.secondary, children: [
            "+",
            data.toolCalls.length - 1,
            " more tool calls (ctrl+e to expand)"
          ] }) })
        ] }),
        data.pendingConfirmation && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, paddingLeft: 1, children: [
          isWaitingForOtherApproval && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { marginBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.secondary, dimColor: true, children: "\u23F3 Waiting for other approval..." }) }),
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
            ToolConfirmationMessage,
            {
              confirmationDetails: data.pendingConfirmation,
              isFocused,
              availableTerminalHeight: availableHeight,
              contentWidth: childWidth - 4,
              compactMode: true,
              config: config2
            }
          )
        ] })
      ] }),
      data.status === "completed" && data.executionSummary && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "row", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime31.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_runtime31.jsx)(Box_default, { flexDirection: "row", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { color: theme.status.error, children: [
        "Failed: ",
        data.terminateReason
      ] }) })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { bold: true, color: agentColor, children: data.subagentName }),
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(StatusDot, { status: data.status }),
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(StatusIndicator, { status: data.status }),
      data.status === "background" && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(BackgroundManageHint, {})
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
      TaskPromptSection,
      {
        slicedPrompt,
        displayMode,
        maxVisualLines: maxTaskPromptLines
      }
    ),
    data.status === "running" && data.toolCalls && data.toolCalls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
      ToolCallsList,
      {
        toolCalls: data.toolCalls,
        displayMode,
        maxToolCalls,
        childWidth: childWidth - 2
      }
    ) }),
    data.pendingConfirmation && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", children: [
      isWaitingForOtherApproval && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { marginBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.secondary, dimColor: true, children: "\u23F3 Waiting for other approval..." }) }),
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
        ToolConfirmationMessage,
        {
          confirmationDetails: data.pendingConfirmation,
          config: config2,
          isFocused,
          availableTerminalHeight: availableHeight,
          contentWidth: childWidth - 4,
          compactMode: true
        }
      )
    ] }),
    (data.status === "completed" || data.status === "failed" || data.status === "cancelled") && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
      ResultsSection,
      {
        data,
        displayMode,
        maxToolCalls,
        childWidth: childWidth - 2
      }
    ),
    footerText && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.secondary, children: footerText }) })
  ] });
}, "AgentExecutionDisplay");
var TaskPromptSection = /* @__PURE__ */ __name(({ slicedPrompt, displayMode, maxVisualLines }) => {
  const shouldTruncate = slicedPrompt.hiddenLinesCount > 0;
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.primary, children: "Task Detail: " }),
      shouldTruncate && displayMode !== "compact" && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { color: theme.text.secondary, children: [
        " ",
        "Showing the first ",
        maxVisualLines,
        " visual lines."
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { wrap: "wrap", children: slicedPrompt.text }) }),
    slicedPrompt.hiddenLinesCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { color: theme.text.secondary, wrap: "truncate", children: [
      "... last ",
      slicedPrompt.hiddenLinesCount,
      " task line",
      slicedPrompt.hiddenLinesCount === 1 ? "" : "s",
      " hidden ..."
    ] }) })
  ] });
}, "TaskPromptSection");
var StatusDot = /* @__PURE__ */ __name(({ status }) => /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { marginLeft: 1, marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime31.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_runtime31.jsx)(Text3, { color, children: text });
}, "StatusIndicator");
var ToolCallsList = /* @__PURE__ */ __name(({ toolCalls, displayMode, maxToolCalls, childWidth }) => {
  const calls = toolCalls || [];
  const displayLimit = Math.max(1, Math.floor(maxToolCalls));
  const shouldTruncate = calls.length > displayLimit;
  const displayCalls = calls.slice(-displayLimit);
  const reversedDisplayCalls = [...displayCalls].reverse();
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "row", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.primary, children: "Tools:" }),
      shouldTruncate && displayMode !== "compact" && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { color: theme.text.secondary, children: [
        " ",
        "Showing the last ",
        displayCalls.length,
        " of ",
        calls.length,
        " tools."
      ] })
    ] }),
    reversedDisplayCalls.map((toolCall, index) => /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
      ToolCallItem,
      {
        toolCall,
        childWidth
      },
      `${toolCall.name}-${index}`
    ))
  ] });
}, "ToolCallsList");
var ToolCallItem = /* @__PURE__ */ __name(({ toolCall, compact = false, childWidth = 80 }) => {
  const STATUS_INDICATOR_WIDTH2 = 3;
  const textWidth = Math.max(8, childWidth - STATUS_INDICATOR_WIDTH2 - 1);
  const statusIcon = import_react61.default.useMemo(() => {
    const color = getStatusColor(toolCall.status);
    switch (toolCall.status) {
      case "executing":
        return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color, children: "\u22B7" });
      // Using same as ToolMessage
      case "awaiting_approval":
        return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.status.warning, children: "?" });
      case "success":
        return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color, children: "\u2713" });
      case "failed":
        return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color, bold: true, children: "x" });
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color, children: "o" });
    }
  }, [toolCall.status]);
  const description = import_react61.default.useMemo(() => {
    if (!toolCall.description) return "";
    const firstLine = toolCall.description.split("\n")[0];
    return truncateToVisualWidth(firstLine, textWidth);
  }, [toolCall.description, textWidth]);
  const truncatedOutput = import_react61.default.useMemo(() => {
    if (!toolCall.resultDisplay) return "";
    const firstLine = toolCall.resultDisplay.split("\n")[0];
    return truncateToVisualWidth(firstLine, textWidth);
  }, [toolCall.resultDisplay, textWidth]);
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 1, marginBottom: 0, children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { minWidth: STATUS_INDICATOR_WIDTH2, children: statusIcon }),
      /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { wrap: "truncate-end", children: [
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { children: toolCall.name }),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.secondary, children: description }),
        toolCall.error && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { color: theme.status.error, children: [
          " - ",
          toolCall.error
        ] })
      ] })
    ] }),
    !compact && truncatedOutput && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "row", paddingLeft: STATUS_INDICATOR_WIDTH2, children: /* @__PURE__ */ (0, import_jsx_runtime31.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_runtime31.jsx)(Box_default, { flexDirection: "column", paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.secondary, children: "\u2022 No summary available" }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { children: [
        "Duration: ",
        fmtDuration(stats.totalDurationMs)
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { children: [
        "Rounds: ",
        stats.rounds
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { children: [
        "Tokens: ",
        stats.totalTokens.toLocaleString()
      ] })
    ] })
  ] });
}, "ExecutionSummaryDetails");
var ToolUsageStats = /* @__PURE__ */ __name(({ executionSummary }) => {
  if (!executionSummary) {
    return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "column", paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.secondary, children: "\u2022 No tool usage data available" }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { children: "Total Calls:" }),
      " ",
      executionSummary.totalToolCalls
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { children: [
      "\u2022 ",
      /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { children: "Success Rate:" }),
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { color: theme.status.success, children: [
        executionSummary.successRate.toFixed(1),
        "%"
      ] }),
      " ",
      "(",
      /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { color: theme.status.success, children: [
        executionSummary.successfulToolCalls,
        " success"
      ] }),
      ",",
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text3, { color: theme.status.error, children: [
        executionSummary.failedToolCalls,
        " failed"
      ] }),
      ")"
    ] })
  ] });
}, "ToolUsageStats");
var ResultsSection = /* @__PURE__ */ __name(({ data, displayMode, maxToolCalls, childWidth }) => /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
  data.toolCalls && data.toolCalls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
    ToolCallsList,
    {
      toolCalls: data.toolCalls,
      displayMode,
      maxToolCalls,
      childWidth
    }
  ),
  data.status === "completed" && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "row", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.primary, children: "Execution Summary:" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(ExecutionSummaryDetails, { data, displayMode })
  ] }),
  data.status === "completed" && data.executionSummary && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "row", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.text.primary, children: "Tool Usage:" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(ToolUsageStats, { executionSummary: data.executionSummary })
  ] }),
  data.status === "cancelled" && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.status.warning, children: "\u23F9 User Cancelled" }) }),
  data.status === "failed" && /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.status.error, children: "Task Failed: " }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text3, { color: theme.status.error, children: data.terminateReason })
  ] })
] }), "ResultsSection");

// packages/cli/src/ui/components/PlanSummaryDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
var PlanSummaryDisplay = /* @__PURE__ */ __name(({
  data,
  availableHeight,
  childWidth
}) => {
  const { message, plan, rejected } = data;
  const messageColor = rejected ? Colors.AccentYellow : Colors.AccentGreen;
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(Text3, { color: messageColor, wrap: "wrap", children: message }) }),
    /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
      MarkdownDisplay,
      {
        text: plan,
        isPending: false,
        availableTerminalHeight: availableHeight,
        contentWidth: childWidth
      }
    )
  ] });
}, "PlanSummaryDisplay");

// packages/cli/src/ui/components/ShellInputPrompt.tsx
init_esbuild_shims();
var import_react62 = __toESM(require_react(), 1);
init_dist4();

// 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_react62.useCallback)(
    (input) => {
      if (activeShellPtyId) {
        ShellExecutionService.writeToPty(activeShellPtyId, input);
      }
    },
    [activeShellPtyId]
  );
  const handleInput = (0, import_react62.useCallback)(
    (key) => {
      if (!focus || !activeShellPtyId) {
        return;
      }
      if (keyMatchers["toggleShellInputFocus" /* TOGGLE_SHELL_INPUT_FOCUS */](key)) {
        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/contexts/CompactModeContext.tsx
init_esbuild_shims();
var import_react63 = __toESM(require_react(), 1);
var CompactModeContext = (0, import_react63.createContext)({
  compactMode: false
});
var useCompactMode = /* @__PURE__ */ __name(() => (0, import_react63.useContext)(CompactModeContext), "useCompactMode");
var CompactModeProvider = CompactModeContext.Provider;

// packages/cli/src/ui/components/shared/ToolStatusIndicator.tsx
init_esbuild_shims();
init_types22();

// packages/cli/src/ui/components/GeminiRespondingSpinner.tsx
init_esbuild_shims();
init_types22();
var import_jsx_runtime33 = __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_runtime33.jsx)(
      GeminiSpinner,
      {
        spinnerType,
        altText: SCREEN_READER_RESPONDING
      }
    );
  } else if (nonRespondingDisplay) {
    return isScreenReaderEnabled ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text3, { children: SCREEN_READER_LOADING }) : /* @__PURE__ */ (0, import_jsx_runtime33.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_runtime33.jsx)(Text3, { children: altText }) : /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text3, { color: theme.text.primary, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(build_default, { type: spinnerType }) });
}, "GeminiSpinner");

// packages/cli/src/ui/components/shared/ToolStatusIndicator.tsx
var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
var STATUS_INDICATOR_WIDTH = 3;
var ToolStatusIndicator = /* @__PURE__ */ __name(({
  status,
  name: name4
}) => {
  const isShell = name4 === SHELL_COMMAND_NAME || name4 === SHELL_NAME;
  const statusColor = isShell ? theme.ui.symbol : theme.status.warning;
  return /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Box_default, { minWidth: STATUS_INDICATOR_WIDTH, children: [
    status === "Pending" /* Pending */ && /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text3, { color: theme.status.success, children: TOOL_STATUS.PENDING }),
    status === "Executing" /* Executing */ && /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
      GeminiRespondingSpinner,
      {
        spinnerType: "toggle",
        nonRespondingDisplay: TOOL_STATUS.EXECUTING
      }
    ),
    status === "Success" /* Success */ && /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text3, { color: theme.status.success, "aria-label": "Success:", children: TOOL_STATUS.SUCCESS }),
    status === "Confirming" /* Confirming */ && /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text3, { color: statusColor, "aria-label": "Confirming:", children: TOOL_STATUS.CONFIRMING }),
    status === "Canceled" /* Canceled */ && /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text3, { color: statusColor, "aria-label": "Canceled:", bold: true, children: TOOL_STATUS.CANCELED }),
    status === "Error" /* Error */ && /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text3, { color: theme.status.error, "aria-label": "Error:", bold: true, children: TOOL_STATUS.ERROR })
  ] });
}, "ToolStatusIndicator");

// packages/cli/src/ui/components/shared/ToolElapsedTime.tsx
init_esbuild_shims();
var import_react64 = __toESM(require_react(), 1);
init_types22();
var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1);
var ToolElapsedTime = /* @__PURE__ */ __name(({
  status,
  executionStartTime,
  timeoutMs
}) => {
  const [elapsedSeconds, setElapsedSeconds] = (0, import_react64.useState)(0);
  (0, import_react64.useEffect)(() => {
    if (status !== "Executing" /* Executing */ || !executionStartTime) {
      setElapsedSeconds(0);
      return;
    }
    setElapsedSeconds(Math.floor((Date.now() - executionStartTime) / 1e3));
    const interval = setInterval(() => {
      setElapsedSeconds(Math.floor((Date.now() - executionStartTime) / 1e3));
    }, 1e3);
    return () => clearInterval(interval);
  }, [status, executionStartTime]);
  if (status !== "Executing" /* Executing */) return null;
  const hasTimeout = timeoutMs != null && timeoutMs > 0;
  if (!hasTimeout && elapsedSeconds < 3) return null;
  const elapsedStr = formatDuration(elapsedSeconds * 1e3, {
    hideTrailingZeros: true
  });
  const label = hasTimeout ? `(${elapsedStr} \xB7 timeout ${formatDuration(timeoutMs, { hideTrailingZeros: true })})` : elapsedStr;
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexShrink: 0, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text3, { color: theme.text.secondary, children: label }) });
}, "ToolElapsedTime");

// packages/cli/src/ui/components/messages/ToolMessage.tsx
var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1);
var STATIC_HEIGHT = 1;
var RESERVED_LINE_COUNT = 5;
var MIN_LINES_SHOWN = 2;
var DEFAULT_SHELL_OUTPUT_MAX_LINES = 5;
var MAXIMUM_RESULT_DISPLAY_CHARACTERS = 1e6;
function sliceTextForMaxHeight(text, maxHeight, maxWidth) {
  if (maxHeight === void 0) {
    return { text, hiddenLinesCount: 0 };
  }
  const targetMaxHeight = Math.max(Math.round(maxHeight), MINIMUM_MAX_HEIGHT);
  const visibleContentHeight = targetMaxHeight - 1;
  const visualWidth = Math.max(1, Math.floor(maxWidth));
  const visibleLines = [];
  let visualLineCount = 0;
  let currentLine = "";
  let currentLineWidth = 0;
  const appendVisibleLine = /* @__PURE__ */ __name((line) => {
    visualLineCount += 1;
    visibleLines.push(line);
    if (visibleLines.length > visibleContentHeight) {
      visibleLines.shift();
    }
  }, "appendVisibleLine");
  const flushCurrentLine = /* @__PURE__ */ __name(() => {
    appendVisibleLine(currentLine);
    currentLine = "";
    currentLineWidth = 0;
  }, "flushCurrentLine");
  for (const char of toCodePoints(text)) {
    if (char === "\n") {
      flushCurrentLine();
      continue;
    }
    const charWidth = Math.max(getCachedStringWidth(char), 1);
    if (currentLineWidth > 0 && currentLineWidth + charWidth > visualWidth) {
      flushCurrentLine();
    }
    currentLine += char;
    currentLineWidth += charWidth;
  }
  flushCurrentLine();
  if (visualLineCount <= targetMaxHeight) {
    return { text, hiddenLinesCount: 0 };
  }
  const hiddenLinesCount = visualLineCount - visibleContentHeight;
  return {
    text: visibleLines.join("\n"),
    hiddenLinesCount
  };
}
__name(sliceTextForMaxHeight, "sliceTextForMaxHeight");
var useResultDisplayRenderer = /* @__PURE__ */ __name((resultDisplay) => import_react65.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) {
    const display = resultDisplay;
    return {
      type: "ansi",
      data: display.ansiOutput,
      stats: {
        totalLines: display.totalLines,
        totalBytes: display.totalBytes
      }
    };
  }
  return {
    type: "string",
    data: resultDisplay
  };
}, [resultDisplay]), "useResultDisplayRenderer");
var TodoResultRenderer = /* @__PURE__ */ __name(({
  data
}) => /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(TodoDisplay, { todos: data.todos }), "TodoResultRenderer");
var PlanResultRenderer = /* @__PURE__ */ __name(({ data, availableHeight, childWidth }) => /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
  PlanSummaryDisplay,
  {
    data,
    availableHeight,
    childWidth
  }
), "PlanResultRenderer");
var SubagentExecutionRenderer = /* @__PURE__ */ __name(({
  data,
  availableHeight,
  childWidth,
  config: config2,
  isFocused,
  isWaitingForOtherApproval
}) => /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
  AgentExecutionDisplay,
  {
    data,
    availableHeight,
    childWidth,
    config: config2,
    isFocused,
    isWaitingForOtherApproval
  }
), "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_runtime36.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
      MarkdownDisplay,
      {
        text: displayData,
        isPending: false,
        availableTerminalHeight: availableHeight,
        contentWidth: childWidth
      }
    ) });
  }
  const sliced = sliceTextForMaxHeight(
    displayData,
    availableHeight,
    childWidth
  );
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
    MaxSizedBox,
    {
      maxHeight: availableHeight,
      maxWidth: childWidth,
      additionalHiddenLinesCount: sliced.hiddenLinesCount,
      children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Text3, { wrap: "wrap", color: theme.text.primary, children: sliced.text }) })
    }
  );
}, "StringResultRenderer");
var DiffResultRenderer = /* @__PURE__ */ __name(({ data, availableHeight, childWidth, settings }) => /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
  DiffRenderer,
  {
    diffContent: data.fileDiff,
    filename: data.fileName,
    availableTerminalHeight: availableHeight,
    contentWidth: childWidth,
    settings
  }
), "DiffResultRenderer");
var ToolMessage = /* @__PURE__ */ __name(({
  name: name4,
  description,
  resultDisplay,
  status,
  availableTerminalHeight,
  contentWidth,
  emphasis = "medium",
  renderOutputAsMarkdown = true,
  activeShellPtyId,
  embeddedShellFocused,
  ptyId,
  config: config2,
  forceShowResult,
  isFocused,
  isWaitingForOtherApproval,
  executionStartTime
}) => {
  const settings = useSettings();
  const isThisShellFocused = (name4 === SHELL_COMMAND_NAME || name4 === SHELL_NAME) && status === "Executing" /* Executing */ && ptyId === activeShellPtyId && embeddedShellFocused;
  const [lastUpdateTime, setLastUpdateTime] = import_react65.default.useState(null);
  const [userHasFocused, setUserHasFocused] = import_react65.default.useState(false);
  const [showFocusHint, setShowFocusHint] = import_react65.default.useState(false);
  import_react65.default.useEffect(() => {
    if (resultDisplay) {
      setLastUpdateTime(/* @__PURE__ */ new Date());
    }
  }, [resultDisplay]);
  const shellTimeoutMs = import_react65.default.useMemo(() => {
    if (typeof resultDisplay === "object" && resultDisplay !== null && "ansiOutput" in resultDisplay) {
      return resultDisplay.timeoutMs;
    }
    return void 0;
  }, [resultDisplay]);
  import_react65.default.useEffect(() => {
    if (!lastUpdateTime) {
      return;
    }
    const timer = setTimeout(() => {
      setShowFocusHint(true);
    }, 5e3);
    return () => clearTimeout(timer);
  }, [lastUpdateTime]);
  import_react65.default.useEffect(() => {
    if (isThisShellFocused) {
      setUserHasFocused(true);
    }
  }, [isThisShellFocused]);
  const isThisShellFocusable = (name4 === SHELL_COMMAND_NAME || name4 === SHELL_NAME) && 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 isShellTool = name4 === SHELL_COMMAND_NAME || name4 === SHELL_NAME;
  const rawShellCap = settings.merged.ui?.shellOutputMaxLines ?? DEFAULT_SHELL_OUTPUT_MAX_LINES;
  const shellOutputMaxLines = Math.max(0, Math.floor(rawShellCap || 0));
  const isCappingShell = isShellTool && shellOutputMaxLines > 0 && !forceShowResult && !isThisShellFocused;
  const shellCapHeight = isCappingShell ? Math.min(availableHeight ?? shellOutputMaxLines, shellOutputMaxLines) : availableHeight;
  const shellStringCapHeight = isCappingShell && shellCapHeight !== void 0 ? shellCapHeight + 1 : availableHeight;
  const innerWidth = contentWidth - STATUS_INDICATOR_WIDTH;
  if (availableHeight) {
    renderOutputAsMarkdown = false;
  }
  const displayRenderer = useResultDisplayRenderer(resultDisplay);
  const { compactMode } = useCompactMode();
  const effectiveDisplayRenderer = !compactMode || forceShowResult ? displayRenderer : { type: "none" };
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(Box_default, { paddingX: 1, paddingY: 0, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(Box_default, { minHeight: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(ToolStatusIndicator, { status, name: name4 }),
      /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
        ToolInfo,
        {
          name: name4,
          status,
          description,
          emphasis
        }
      ),
      shouldShowFocusHint && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Box_default, { marginLeft: 1, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Text3, { color: theme.text.accent, children: isThisShellFocused ? "(Focused)" : "(ctrl+f to focus)" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
        ToolElapsedTime,
        {
          status,
          executionStartTime,
          timeoutMs: shellTimeoutMs
        }
      ),
      emphasis === "high" && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(TrailingIndicator, {})
    ] }),
    effectiveDisplayRenderer.type !== "none" && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Box_default, { paddingLeft: STATUS_INDICATOR_WIDTH, width: "100%", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(Box_default, { flexDirection: "column", children: [
      effectiveDisplayRenderer.type === "todo" && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(TodoResultRenderer, { data: effectiveDisplayRenderer.data }),
      effectiveDisplayRenderer.type === "plan" && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
        PlanResultRenderer,
        {
          data: effectiveDisplayRenderer.data,
          availableHeight,
          childWidth: innerWidth
        }
      ),
      effectiveDisplayRenderer.type === "task" && config2 && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
        SubagentExecutionRenderer,
        {
          data: effectiveDisplayRenderer.data,
          availableHeight,
          childWidth: innerWidth,
          config: config2,
          isFocused,
          isWaitingForOtherApproval
        }
      ),
      effectiveDisplayRenderer.type === "diff" && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
        DiffResultRenderer,
        {
          data: effectiveDisplayRenderer.data,
          availableHeight,
          childWidth: innerWidth,
          settings
        }
      ),
      effectiveDisplayRenderer.type === "ansi" && /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(import_jsx_runtime36.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
          AnsiOutputText,
          {
            data: effectiveDisplayRenderer.data,
            availableTerminalHeight: shellCapHeight,
            maxWidth: innerWidth
          }
        ),
        effectiveDisplayRenderer.stats && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
          ShellStatsBar,
          {
            ...effectiveDisplayRenderer.stats,
            displayHeight: shellCapHeight
          }
        )
      ] }),
      effectiveDisplayRenderer.type === "string" && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
        StringResultRenderer,
        {
          data: effectiveDisplayRenderer.data,
          renderAsMarkdown: renderOutputAsMarkdown,
          availableHeight: shellStringCapHeight,
          childWidth: innerWidth
        }
      )
    ] }) }),
    isThisShellFocused && config2 && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Box_default, { paddingLeft: STATUS_INDICATOR_WIDTH, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
      ShellInputPrompt,
      {
        activeShellPtyId: activeShellPtyId ?? null,
        focus: embeddedShellFocused
      }
    ) })
  ] });
}, "ToolMessage");
var ToolInfo = /* @__PURE__ */ __name(({
  name: name4,
  description,
  status,
  emphasis
}) => {
  const nameColor = import_react65.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_runtime36.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(
    Text3,
    {
      wrap: "truncate-end",
      strikethrough: status === "Canceled" /* Canceled */,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Text3, { color: nameColor, bold: true, children: name4 }),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Text3, { color: theme.text.secondary, children: description })
      ]
    }
  ) });
}, "ToolInfo");
var TrailingIndicator = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(Text3, { color: theme.text.primary, wrap: "truncate", children: [
  " ",
  "\u2190"
] }), "TrailingIndicator");

// packages/cli/src/ui/components/messages/CompactToolGroupDisplay.tsx
init_esbuild_shims();
init_types22();
init_i18n();
var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1);
function getOverallStatus(toolCalls) {
  if (toolCalls.some((t5) => t5.status === "Confirming" /* Confirming */))
    return "Confirming" /* Confirming */;
  if (toolCalls.some((t5) => t5.status === "Executing" /* Executing */))
    return "Executing" /* Executing */;
  if (toolCalls.some((t5) => t5.status === "Error" /* Error */))
    return "Error" /* Error */;
  if (toolCalls.some((t5) => t5.status === "Canceled" /* Canceled */))
    return "Canceled" /* Canceled */;
  if (toolCalls.some((t5) => t5.status === "Pending" /* Pending */))
    return "Pending" /* Pending */;
  return "Success" /* Success */;
}
__name(getOverallStatus, "getOverallStatus");
function getActiveTool(toolCalls) {
  return toolCalls.find((t5) => t5.status === "Confirming" /* Confirming */) ?? toolCalls.find((t5) => t5.status === "Executing" /* Executing */) ?? toolCalls[toolCalls.length - 1];
}
__name(getActiveTool, "getActiveTool");
function getShellTimeoutMs(tool) {
  const display = tool.resultDisplay;
  if (typeof display === "object" && display !== null && "ansiOutput" in display) {
    return display.timeoutMs;
  }
  return void 0;
}
__name(getShellTimeoutMs, "getShellTimeoutMs");
function renderSummaryHeader(label, count) {
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(import_jsx_runtime37.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text3, { bold: true, children: label }),
    count > 1 ? /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Text3, { color: theme.text.secondary, children: [
      "  \xB7 ",
      count,
      " tools"
    ] }) : null
  ] });
}
__name(renderSummaryHeader, "renderSummaryHeader");
function renderDefaultHeader(activeToolName, activeToolDescription, count) {
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(import_jsx_runtime37.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text3, { bold: true, children: activeToolName }),
    count > 1 ? /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Text3, { color: theme.text.secondary, children: [
      " \xD7 ",
      count
    ] }) : null,
    activeToolDescription ? /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Text3, { color: theme.text.secondary, children: [
      "  ",
      activeToolDescription
    ] }) : null
  ] });
}
__name(renderDefaultHeader, "renderDefaultHeader");
var CompactToolGroupDisplay = /* @__PURE__ */ __name(({ toolCalls, contentWidth, compactLabel }) => {
  if (toolCalls.length === 0) return null;
  const overallStatus = getOverallStatus(toolCalls);
  const activeTool = getActiveTool(toolCalls);
  const isShellCommand = toolCalls.some(
    (t5) => t5.name === SHELL_COMMAND_NAME || t5.name === SHELL_NAME
  );
  const hasPending = !toolCalls.every(
    (t5) => t5.status === "Success" /* Success */
  );
  const borderColor = isShellCommand ? theme.ui.symbol : hasPending ? theme.status.warning : theme.border.default;
  const activeToolDescription = activeTool.description ? activeTool.description.split("\n")[0] : "";
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      width: contentWidth,
      borderDimColor: hasPending,
      borderColor,
      gap: 0,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(ToolStatusIndicator, { status: overallStatus, name: activeTool.name }),
          /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text3, { wrap: "truncate-end", children: compactLabel ? renderSummaryHeader(compactLabel, toolCalls.length) : renderDefaultHeader(
            activeTool.name,
            activeToolDescription,
            toolCalls.length
          ) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
            ToolElapsedTime,
            {
              status: overallStatus,
              executionStartTime: activeTool.executionStartTime,
              timeoutMs: getShellTimeoutMs(activeTool)
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text3, { color: theme.text.secondary, children: t4("Press Ctrl+O to show full tool output") })
      ]
    }
  );
}, "CompactToolGroupDisplay");

// packages/cli/src/ui/contexts/ConfigContext.tsx
init_esbuild_shims();
var import_react66 = __toESM(require_react(), 1);
init_dist4();
var ConfigContext = import_react66.default.createContext(void 0);
var useConfig = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react66.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);
function isAgentWithPendingConfirmation(rd) {
  return typeof rd === "object" && rd !== null && "type" in rd && rd.type === "task_execution" && rd.pendingConfirmation !== void 0;
}
__name(isAgentWithPendingConfirmation, "isAgentWithPendingConfirmation");
var ToolGroupMessage = /* @__PURE__ */ __name(({
  toolCalls,
  availableTerminalHeight,
  contentWidth,
  isFocused = true,
  activeShellPtyId,
  embeddedShellFocused,
  memoryWriteCount,
  memoryReadCount,
  isUserInitiated,
  compactLabel
}) => {
  const config2 = useConfig();
  const { compactMode } = useCompactMode();
  const hasConfirmingTool = toolCalls.some(
    (t5) => t5.status === "Confirming" /* Confirming */
  );
  const hasErrorTool = toolCalls.some((t5) => t5.status === "Error" /* Error */);
  const isEmbeddedShellFocused = embeddedShellFocused && toolCalls.some(
    (t5) => t5.ptyId === activeShellPtyId && t5.status === "Executing" /* Executing */
  );
  const toolAwaitingApproval = (0, import_react67.useMemo)(
    () => toolCalls.find((tc) => tc.status === "Confirming" /* Confirming */),
    [toolCalls]
  );
  const isMemoryOnlyGroup = (0, import_react67.useMemo)(
    () => toolCalls.length > 0 && toolCalls.every((t5) => t5.isMemoryOp != null),
    [toolCalls]
  );
  const allComplete = (0, import_react67.useMemo)(
    () => toolCalls.every(
      (t5) => t5.status === "Success" /* Success */ || t5.status === "Error" /* Error */
    ),
    [toolCalls]
  );
  const subagentsAwaitingApproval = (0, import_react67.useMemo)(
    () => toolCalls.filter(
      (tc) => isAgentWithPendingConfirmation(tc.resultDisplay)
    ),
    [toolCalls]
  );
  const focusedSubagentRef = (0, import_react67.useRef)(null);
  const stillPending = subagentsAwaitingApproval.some(
    (tc) => tc.callId === focusedSubagentRef.current
  );
  if (!stillPending) {
    focusedSubagentRef.current = subagentsAwaitingApproval[0]?.callId ?? null;
  }
  const focusedSubagentCallId = focusedSubagentRef.current;
  const hasSubagentPendingConfirmation = subagentsAwaitingApproval.length > 0;
  const showCompact = compactMode && !hasConfirmingTool && !hasSubagentPendingConfirmation && !hasErrorTool && !isEmbeddedShellFocused && !isUserInitiated;
  if (showCompact) {
    return /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
      CompactToolGroupDisplay,
      {
        toolCalls,
        contentWidth,
        compactLabel
      }
    );
  }
  const hasPending = !toolCalls.every(
    (t5) => t5.status === "Success" /* Success */
  );
  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;
  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;
  if (isMemoryOnlyGroup && allComplete) {
    const readCount = memoryReadCount ?? 0;
    const writeCount = memoryWriteCount ?? 0;
    return /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        borderStyle: "round",
        width: contentWidth,
        borderColor: theme.border.default,
        children: [
          readCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Text3, { dimColor: true, children: [
            "\u25CF ",
            "Recalled ",
            readCount,
            " ",
            readCount === 1 ? "memory" : "memories"
          ] }) }),
          writeCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Text3, { dimColor: true, children: [
            "\u25CF ",
            "Wrote ",
            writeCount,
            " ",
            writeCount === 1 ? "memory" : "memories"
          ] }) })
        ]
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      width: contentWidth,
      borderDimColor: hasPending && (!isShellCommand || !isEmbeddedShellFocused),
      borderColor,
      gap: 1,
      children: [
        !isMemoryOnlyGroup && ((memoryWriteCount ?? 0) > 0 || (memoryReadCount ?? 0) > 0) && (() => {
          const parts2 = [];
          if ((memoryReadCount ?? 0) > 0) {
            const n3 = memoryReadCount;
            parts2.push(`Recalled ${n3} ${n3 === 1 ? "memory" : "memories"}`);
          }
          if ((memoryWriteCount ?? 0) > 0) {
            const n3 = memoryWriteCount;
            parts2.push(`Wrote ${n3} ${n3 === 1 ? "memory" : "memories"}`);
          }
          return /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Text3, { dimColor: true, children: [
            "\u25CF ",
            parts2.join(", ")
          ] }) });
        })(),
        toolCalls.map((tool) => {
          const isConfirming = toolAwaitingApproval?.callId === tool.callId;
          const isSubagentFocused = isFocused && !toolAwaitingApproval && focusedSubagentCallId === tool.callId;
          const isWaitingForOtherApproval = isAgentWithPendingConfirmation(tool.resultDisplay) && focusedSubagentCallId !== null && focusedSubagentCallId !== 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,
                forceShowResult: isUserInitiated || tool.status === "Confirming" /* Confirming */ || tool.status === "Error" /* Error */ || isAgentWithPendingConfirmation(tool.resultDisplay),
                isFocused: isSubagentFocused,
                isWaitingForOtherApproval
              }
            ) }),
            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.callId);
        })
      ]
    }
  );
}, "ToolGroupMessage");

// packages/cli/src/ui/components/messages/CompressionMessage.tsx
init_esbuild_shims();
init_dist4();
init_i18n();
var import_jsx_runtime39 = __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_runtime39.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Box_default, { marginRight: 1, children: isPending ? /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(build_default, { type: "dots" }) : /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Text3, { color: theme.text.accent, children: "\u2726" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime39.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_runtime40 = __toESM(require_jsx_runtime(), 1);
var SummaryMessage = /* @__PURE__ */ __name(({ summary }) => {
  const getText4 = /* @__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_runtime40.jsx)(build_default, { type: "dots" });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Text3, { color: Colors.AccentGreen, children: "\u2705" });
  }, "getIcon");
  return /* @__PURE__ */ (0, import_jsx_runtime40.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Box_default, { marginRight: 1, children: getIcon() }),
    /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(
      Text3,
      {
        color: summary.isPending ? Colors.AccentPurple : Colors.AccentGreen,
        children: getText4()
      }
    ) })
  ] });
}, "SummaryMessage");

// packages/cli/src/ui/components/messages/StatusMessages.tsx
init_esbuild_shims();

// node_modules/ink-link/dist/index.js
init_esbuild_shims();
var import_react68 = __toESM(require_react(), 1);
var import_prop_types = __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 i4 = 0; i4 < count; i4++) {
    clear += ansiEscapes.eraseLine + (i4 < 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, url3) => {
  return [
    OSC2,
    "8",
    SEP2,
    SEP2,
    url3,
    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((cwd6 = process.cwd()) => `${OSC2}50;CurrentDir=${cwd6}${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, url3, { target = "stdout", ...options2 } = {}) {
  if (!import_supports_hyperlinks.default[target]) {
    if (options2.fallback === false) {
      return text;
    }
    return typeof options2.fallback === "function" ? options2.fallback(text, url3) : `${text} (\u200B${url3}\u200B)`;
  }
  return ansi_escapes_default.link(text, url3);
}
__name(terminalLink, "terminalLink");
terminalLink.isSupported = import_supports_hyperlinks.default.stdout;
terminalLink.stderr = (text, url3, options2 = {}) => terminalLink(text, url3, { target: "stderr", ...options2 });
terminalLink.stderr.isSupported = import_supports_hyperlinks.default.stderr;

// node_modules/ink-link/dist/index.js
var Link = /* @__PURE__ */ __name(({ children, url: url3, fallback = true }) => (
  // eslint-disable-line react/function-component-definition
  import_react68.default.createElement(
    Transform,
    { transform: /* @__PURE__ */ __name((children2) => terminalLink(children2, url3, { fallback }), "transform") },
    import_react68.default.createElement(Text3, null, children)
  )
), "Link");
Link.propTypes = {
  children: import_prop_types.default.oneOfType([
    import_prop_types.default.arrayOf(import_prop_types.default.node),
    import_prop_types.default.node
  ]).isRequired,
  url: import_prop_types.default.string.isRequired,
  fallback: import_prop_types.default.bool
  // eslint-disable-line react/boolean-prop-naming
};
var dist_default5 = Link;

// packages/cli/src/ui/components/messages/StatusMessages.tsx
var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1);
var StatusMessage = /* @__PURE__ */ __name(({
  text,
  prefix,
  prefixColor,
  textColor,
  children,
  footer
}) => {
  if ((!text || text.trim() === "") && !footer) {
    return null;
  }
  const prefixWidth = stringWidth4(prefix) + 1;
  return /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: prefixWidth, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text3, { color: prefixColor, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexGrow: 1, flexDirection: "column", children: [
      text && text.trim() !== "" && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text3, { wrap: "wrap", color: textColor, children: [
        /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(RenderInline, { text }),
        children
      ] }),
      footer
    ] })
  ] });
}, "StatusMessage");
var InfoMessage = /* @__PURE__ */ __name(({
  text,
  linkUrl,
  linkText
}) => /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u25CF",
    prefixColor: theme.text.primary,
    textColor: theme.text.primary,
    footer: linkUrl && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(dist_default5, { url: linkUrl, children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text3, { color: theme.text.link, underline: true, children: linkText ?? linkUrl }) })
  }
), "InfoMessage");
var SuccessMessage = /* @__PURE__ */ __name(({ text }) => /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u2713",
    prefixColor: theme.status.success,
    textColor: theme.status.success
  }
), "SuccessMessage");
var WarningMessage = /* @__PURE__ */ __name(({ text }) => /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u25B3",
    prefixColor: theme.status.warning,
    textColor: theme.status.warning
  }
), "WarningMessage");
var ErrorMessage = /* @__PURE__ */ __name(({
  text,
  hint
}) => /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u2715",
    prefixColor: theme.status.error,
    textColor: theme.status.error,
    children: hint && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text3, { color: theme.text.secondary, children: [
      " (",
      hint,
      ")"
    ] })
  }
), "ErrorMessage");
var RetryCountdownMessage = /* @__PURE__ */ __name(({ text }) => /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u21BB",
    prefixColor: theme.text.secondary,
    textColor: theme.text.secondary
  }
), "RetryCountdownMessage");
var AwayRecapMessage = /* @__PURE__ */ __name(({ text }) => /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
  /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text3, { color: theme.text.secondary, children: "\u203B" }) }),
  /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text3, { wrap: "wrap", children: [
    /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text3, { color: theme.text.secondary, bold: true, children: [
      "recap:",
      " "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text3, { color: theme.text.secondary, italic: true, children: text })
  ] })
] }), "AwayRecapMessage");

// packages/cli/src/ui/components/AboutBox.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime42 = __toESM(require_jsx_runtime(), 1);
var AboutBox = /* @__PURE__ */ __name(({ width, ...props }) => {
  const fields = getSystemInfoFields(props);
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Status") }) }),
        fields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(
          Box_default,
          {
            flexDirection: "row",
            marginTop: field.label === t4("Auth") ? 1 : 0,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text3, { bold: true, color: theme.text.link, children: field.label }) }),
              /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime42.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_react69 = __toESM(require_react(), 1);
var import_prop_types2 = __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(stripAnsi2(text)), "applyGradient");
  return import_react69.default.createElement(Transform, { transform: applyGradient }, props.children);
}, "Gradient");
Gradient.propTypes = {
  children: import_prop_types2.default.oneOfType([
    import_prop_types2.default.arrayOf(import_prop_types2.default.node),
    import_prop_types2.default.node
  ]).isRequired,
  name: import_prop_types2.default.oneOf([
    "cristal",
    "teen",
    "mind",
    "morning",
    "vice",
    "passion",
    "fruit",
    "instagram",
    "atlas",
    "retro",
    "summer",
    "pastel",
    "rainbow"
  ]),
  colors: import_prop_types2.default.arrayOf(import_prop_types2.default.oneOfType([
    import_prop_types2.default.string,
    import_prop_types2.default.object
  ]))
};
var dist_default6 = Gradient;

// packages/cli/src/ui/contexts/SessionContext.tsx
init_esbuild_shims();
var import_react70 = __toESM(require_react(), 1);
init_dist4();
var import_jsx_runtime43 = __toESM(require_jsx_runtime(), 1);
function areModelMetricsCoreEqual(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) {
    return false;
  }
  return true;
}
__name(areModelMetricsCoreEqual, "areModelMetricsCoreEqual");
function areModelMetricsEqual(a2, b2) {
  if (!areModelMetricsCoreEqual(a2, b2)) return false;
  const aKeys = Object.keys(a2.bySource);
  const bKeys = Object.keys(b2.bySource);
  if (aKeys.length !== bKeys.length) return false;
  for (const key of aKeys) {
    const aSource = a2.bySource[key];
    const bSource = b2.bySource[key];
    if (!bSource || !areModelMetricsCoreEqual(aSource, bSource)) {
      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_react70.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_react70.useState)(
    () => createDefaultStats(sessionId ?? "")
  );
  (0, import_react70.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_react70.useCallback)((sessionId2) => {
    setStats(() => ({
      ...createDefaultStats(sessionId2),
      lastPromptTokenCount: uiTelemetryService.getLastPromptTokenCount()
    }));
  }, []);
  const startNewPrompt = (0, import_react70.useCallback)(() => {
    setStats((prevState) => ({
      ...prevState,
      promptCount: prevState.promptCount + 1
    }));
  }, []);
  const getPromptCount = (0, import_react70.useCallback)(
    () => stats.promptCount,
    [stats.promptCount]
  );
  const value = (0, import_react70.useMemo)(
    () => ({
      stats,
      startNewSession,
      startNewPrompt,
      getPromptCount
    }),
    [stats, startNewSession, startNewPrompt, getPromptCount]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(SessionStatsContext.Provider, { value, children });
}, "SessionStatsProvider");
var useSessionStats = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react70.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();
init_dist4();
function getArenaStatusLabel(status) {
  switch (status) {
    case AgentStatus.IDLE:
      return { icon: "\u2713", text: "Idle", color: theme.status.success };
    case AgentStatus.COMPLETED:
      return { icon: "\u2713", text: "Done", color: theme.status.success };
    case AgentStatus.CANCELLED:
      return { icon: "\u2298", text: "Cancelled", color: theme.status.warning };
    case AgentStatus.FAILED:
      return { icon: "\u2717", text: "Failed", color: theme.status.error };
    case AgentStatus.RUNNING:
      return { icon: "\u25CB", text: "Running", color: theme.text.secondary };
    case AgentStatus.INITIALIZING:
      return { icon: "\u25CB", text: "Initializing", color: theme.text.secondary };
    default:
      return { icon: "\u25CB", text: status, color: theme.text.secondary };
  }
}
__name(getArenaStatusLabel, "getArenaStatusLabel");
var TOOL_SUCCESS_RATE_HIGH = 95;
var TOOL_SUCCESS_RATE_MEDIUM = 85;
var USER_AGREEMENT_RATE_HIGH = 75;
var USER_AGREEMENT_RATE_MEDIUM = 45;
var getStatusColor2 = /* @__PURE__ */ __name((value, thresholds, options2 = {}) => {
  if (value >= thresholds.green) {
    return theme.status.success;
  }
  if (value >= thresholds.yellow) {
    return theme.status.warning;
  }
  if (thresholds.red != null && value >= thresholds.red) {
    return theme.status.error;
  }
  return options2.defaultColor ?? theme.status.error;
}, "getStatusColor");

// packages/cli/src/ui/utils/gradientUtils.ts
init_esbuild_shims();
function getRenderableGradientColors(...candidates) {
  return candidates.find(
    (colors) => Array.isArray(colors) && colors.length >= 2 && colors.every(
      (color) => typeof color === "string" && color.trim().length > 0
    )
  );
}
__name(getRenderableGradientColors, "getRenderableGradientColors");

// packages/cli/src/ui/utils/modelsBySource.ts
init_esbuild_shims();
init_dist4();
function flattenModelsBySource(models) {
  const sessionHasNonMainSource = Object.values(models).some(
    (modelMetrics) => Object.keys(modelMetrics.bySource).some((source2) => source2 !== MAIN_SOURCE)
  );
  const result = [];
  for (const [modelName, modelMetrics] of Object.entries(models)) {
    if (modelMetrics.api.totalRequests <= 0) continue;
    const displayName = normalizeModelName(modelName);
    const sourceNames = Object.keys(modelMetrics.bySource);
    if (sourceNames.length === 0) {
      result.push({
        key: modelName,
        label: displayName,
        metrics: modelMetrics
      });
      continue;
    }
    if (!sessionHasNonMainSource) {
      result.push({
        key: modelName,
        label: displayName,
        metrics: modelMetrics.bySource[MAIN_SOURCE] ?? modelMetrics
      });
      continue;
    }
    const sortedSources = sortSources(sourceNames);
    for (const source2 of sortedSources) {
      result.push({
        key: `${modelName}::${source2}`,
        label: `${displayName} (${source2})`,
        metrics: modelMetrics.bySource[source2]
      });
    }
  }
  return result;
}
__name(flattenModelsBySource, "flattenModelsBySource");
function normalizeModelName(modelName) {
  return modelName.replace("-001", "");
}
__name(normalizeModelName, "normalizeModelName");
function sortSources(sources) {
  const main2 = [];
  const rest = [];
  for (const source2 of sources) {
    if (source2 === MAIN_SOURCE) {
      main2.push(source2);
    } else {
      rest.push(source2);
    }
  }
  rest.sort((a2, b2) => a2.localeCompare(b2));
  return [...main2, ...rest];
}
__name(sortSources, "sortSources");

// packages/cli/src/ui/components/StatsDisplay.tsx
init_i18n();
var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1);
var StatRow = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { children: [
  /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: 28, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { color: theme.text.link, children: title }) }),
  /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { flexGrow: 1, children })
] }), "StatRow");
var SubStatRow = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { paddingLeft: 2, children: [
  /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: 26, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.text.secondary, children: [
    "\xBB ",
    title
  ] }) }),
  /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { flexGrow: 1, children })
] }), "SubStatRow");
var Section = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "column", width: "100%", marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { bold: true, color: theme.text.primary, children: title }),
  children
] }), "Section");
var ModelUsageTable = /* @__PURE__ */ __name(({ models, totalCachedTokens, cacheEfficiency }) => {
  const nameWidth = 35;
  const requestsWidth = 8;
  const inputTokensWidth = 15;
  const outputTokensWidth = 15;
  const entries = flattenModelsBySource(models);
  return /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: nameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Model Usage") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: requestsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Reqs") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: inputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Input Tokens") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: outputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Output Tokens") }) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderBottom: true,
        borderTop: false,
        borderLeft: false,
        borderRight: false,
        borderColor: theme.border.default,
        width: nameWidth + requestsWidth + inputTokensWidth + outputTokensWidth
      }
    ),
    entries.map(({ key, label, metrics: metrics2 }) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: nameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { color: theme.text.primary, children: label }) }),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: requestsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { color: theme.text.primary, children: metrics2.api.totalRequests }) }),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: inputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { color: theme.status.warning, children: metrics2.tokens.prompt.toLocaleString() }) }),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: outputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { color: theme.status.warning, children: metrics2.tokens.candidates.toLocaleString() }) })
    ] }, key)),
    cacheEfficiency > 0 && /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime44.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_runtime44.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime44.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) {
      const gradientColors = getRenderableGradientColors(theme.ui.gradient);
      return gradientColors ? /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(dist_default6, { colors: gradientColors, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { bold: true, color: theme.text.primary, children: title }) }) : /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { bold: true, color: theme.text.accent, children: title });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Session Stats") });
  }, "renderTitle");
  return /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        renderTitle(),
        /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Section, { title: t4("Interaction Summary"), children: [
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: t4("Session ID:"), children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { color: theme.text.primary, children: stats.sessionId }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: t4("Tool Calls:"), children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.text.primary, children: [
            tools.totalCalls,
            " (",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.status.success, children: [
              "\u2713 ",
              tools.totalSuccess
            ] }),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.status.error, children: [
              "x ",
              tools.totalFail
            ] }),
            " )"
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: t4("Success Rate:"), children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: successColor, children: [
            computed.successRate.toFixed(1),
            "%"
          ] }) }),
          computed.totalDecisions > 0 && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: t4("User Agreement:"), children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: agreementColor, children: [
            computed.agreementRate.toFixed(1),
            "%",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.text.secondary, children: [
              "(",
              computed.totalDecisions,
              " ",
              t4("reviewed"),
              ")"
            ] })
          ] }) }),
          files && (files.totalLinesAdded > 0 || files.totalLinesRemoved > 0) && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: t4("Code Changes:"), children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.text.primary, children: [
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.status.success, children: [
              "+",
              files.totalLinesAdded
            ] }),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.status.error, children: [
              "-",
              files.totalLinesRemoved
            ] })
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Section, { title: t4("Performance"), children: [
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: t4("Wall Time:"), children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { color: theme.text.primary, children: duration3 }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: t4("Agent Active:"), children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text3, { color: theme.text.primary, children: formatDuration(computed.agentActiveTime) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(SubStatRow, { title: t4("API Time:"), children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.text.primary, children: [
            formatDuration(computed.totalApiTime),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.text.secondary, children: [
              "(",
              computed.apiTimePercent.toFixed(1),
              "%)"
            ] })
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(SubStatRow, { title: t4("Tool Time:"), children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.text.primary, children: [
            formatDuration(computed.totalToolTime),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text3, { color: theme.text.secondary, children: [
              "(",
              computed.toolTimePercent.toFixed(1),
              "%)"
            ] })
          ] }) })
        ] }),
        Object.keys(models).length > 0 && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
          ModelUsageTable,
          {
            models,
            totalCachedTokens: computed.totalCachedTokens,
            cacheEfficiency: computed.cacheEfficiency
          }
        )
      ]
    }
  );
}, "StatsDisplay");

// packages/cli/src/ui/components/ModelStatsDisplay.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1);
var METRIC_COL_WIDTH = 28;
var MODEL_COL_WIDTH = 24;
var StatRow2 = /* @__PURE__ */ __name(({
  title,
  values,
  isSubtle = false,
  isSection = false
}) => /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { children: [
  /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: METRIC_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime45.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_runtime45.jsx)(Box_default, { width: MODEL_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text3, { color: theme.text.primary, children: value }) }, index))
] }), "StatRow");
var ModelStatsDisplay = /* @__PURE__ */ __name(({
  width
}) => {
  const { stats } = useSessionStats();
  const { models } = stats.metrics;
  const entries = flattenModelsBySource(models);
  if (entries.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingY: 1,
        paddingX: 2,
        width,
        children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text3, { color: theme.text.primary, children: t4("No API calls have been made in this session.") })
      }
    );
  }
  const getModelValues = /* @__PURE__ */ __name((getter) => entries.map(({ metrics: metrics2 }) => getter(metrics2)), "getModelValues");
  const hasThoughts = entries.some(
    ({ metrics: metrics2 }) => metrics2.tokens.thoughts > 0
  );
  const hasCached = entries.some(({ metrics: metrics2 }) => metrics2.tokens.cached > 0);
  return /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Model Stats For Nerds") }),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: METRIC_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Metric") }) }),
          entries.map(({ key, label }) => /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { width: MODEL_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text3, { bold: true, color: theme.text.primary, children: label }) }, key))
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(StatRow2, { title: t4("API"), values: [], isSection: true }),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
          StatRow2,
          {
            title: t4("Requests"),
            values: getModelValues((m3) => m3.api.totalRequests.toLocaleString())
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
          StatRow2,
          {
            title: t4("Errors"),
            values: getModelValues((m3) => {
              const errorRate = calculateErrorRate(m3);
              return /* @__PURE__ */ (0, import_jsx_runtime45.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_runtime45.jsx)(
          StatRow2,
          {
            title: t4("Avg Latency"),
            values: getModelValues((m3) => {
              const avgLatency = calculateAverageLatency(m3);
              return formatDuration(avgLatency);
            })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(StatRow2, { title: t4("Tokens"), values: [], isSection: true }),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
          StatRow2,
          {
            title: t4("Total"),
            values: getModelValues((m3) => /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text3, { color: theme.status.warning, children: m3.tokens.total.toLocaleString() }))
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
          StatRow2,
          {
            title: t4("Prompt"),
            isSubtle: true,
            values: getModelValues((m3) => m3.tokens.prompt.toLocaleString())
          }
        ),
        hasCached && /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
          StatRow2,
          {
            title: t4("Cached"),
            isSubtle: true,
            values: getModelValues((m3) => {
              const cacheHitRate = calculateCacheHitRate(m3);
              return /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text3, { color: theme.status.success, children: [
                m3.tokens.cached.toLocaleString(),
                " (",
                cacheHitRate.toFixed(1),
                "%)"
              ] });
            })
          }
        ),
        hasThoughts && /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
          StatRow2,
          {
            title: t4("Thoughts"),
            isSubtle: true,
            values: getModelValues((m3) => m3.tokens.thoughts.toLocaleString())
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime45.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();
init_i18n();
var import_jsx_runtime46 = __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: name4, 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_runtime46.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: TOOL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.text.link, children: name4 }) }),
    /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: CALLS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.text.primary, children: stats.count }) }),
    /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Text3, { color: successColor, children: [
      successRate.toFixed(1),
      "%"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.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_runtime46.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingY: 1,
        paddingX: 2,
        width,
        children: /* @__PURE__ */ (0, import_jsx_runtime46.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_runtime46.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Tool Stats For Nerds") }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: TOOL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Tool Name") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: CALLS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Calls") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Success Rate") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Avg Duration") }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default,
            width: "100%"
          }
        ),
        activeTools.map(([name4, stats2]) => /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(StatRow3, { name: name4, stats: stats2 }, name4)),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("User Decision Summary") }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.text.link, children: t4("Total Reviewed Suggestions:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.text.primary, children: totalReviewed }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.text.primary, children: t4(" \xBB Accepted:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.status.success, children: totalDecisions.accept }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.text.primary, children: t4(" \xBB Rejected:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.status.error, children: totalDecisions.reject }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.text.primary, children: t4(" \xBB Modified:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.status.warning, children: totalDecisions.modify }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default,
            width: "100%"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text3, { color: theme.text.primary, children: t4(" Overall Agreement Rate:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime46.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();
init_i18n();
var import_jsx_runtime47 = __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_runtime47.jsxs)(import_jsx_runtime47.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
      StatsDisplay,
      {
        title: t4("Agent powering down. Goodbye!"),
        duration: duration3,
        width
      }
    ),
    hasMessages && canResume && /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Text3, { color: theme.text.secondary, children: [
      t4("To continue this session, run"),
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Text3, { color: theme.text.accent, children: [
        "qwen --resume ",
        stats.sessionId
      ] })
    ] }) })
  ] });
}, "SessionSummaryDisplay");

// packages/cli/src/ui/components/Help.tsx
init_esbuild_shims();
init_types21();
init_i18n();
var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1);
var Help = /* @__PURE__ */ __name(({ commands, width }) => /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(
  Box_default,
  {
    flexDirection: "column",
    borderColor: theme.border.default,
    borderStyle: "round",
    padding: 1,
    width,
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Basics:") }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.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_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.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_runtime48.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Commands:") }),
      commands.filter((command2) => command2.description && !command2.hidden).map((command2) => /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
          /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { bold: true, color: theme.text.accent, children: [
            " ",
            formatCommandLabel(command2, "/")
          ] }),
          command2.kind === "mcp-prompt" /* MCP_PROMPT */ && /* @__PURE__ */ (0, import_jsx_runtime48.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_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
          /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { bold: true, color: theme.text.accent, children: [
            "   ",
            formatCommandLabel(subCommand)
          ] }),
          subCommand.description && " - " + subCommand.description
        ] }, subCommand.name))
      ] }, command2.name)),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { bold: true, color: theme.text.accent, children: [
          " ",
          "!",
          " "
        ] }),
        "- ",
        t4("shell command")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { color: theme.text.secondary, children: "[MCP]" }),
        " -",
        " ",
        t4("Model Context Protocol command (from external servers)")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Keyboard Shortcuts:") }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Alt+Left/Right" }),
        " ",
        "- ",
        t4("Jump through words in the input")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Ctrl+C" }),
        " ",
        "- ",
        t4("Close dialogs, cancel requests, or quit application")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.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_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Ctrl+L" }),
        " ",
        "- ",
        t4("Clear the screen")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Ctrl+O" }),
        " ",
        "- ",
        t4("to toggle compact mode")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.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_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Enter" }),
        " ",
        "- ",
        t4("Send message")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Esc" }),
        " ",
        "- ",
        t4("Cancel operation / Clear input (double press)")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.accent, children: process.platform === "win32" ? "Tab" : "Shift+Tab" }),
        " ",
        "- ",
        t4("Cycle approval modes")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text3, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Up/Down" }),
        " ",
        "- ",
        t4("Cycle through your prompt history")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime48.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();
init_dist4();
var import_jsx_runtime49 = __toESM(require_jsx_runtime(), 1);
var debugLogger142 = 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_runtime49.jsx)(Text3, { children: "No extensions installed." });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, marginBottom: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { children: "Installed extensions:" }),
    /* @__PURE__ */ (0, import_jsx_runtime49.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:
          debugLogger142.error(`Unhandled ExtensionUpdateState ${state}`);
          break;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text3, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { color: "cyan", children: `${ext2.name} (v${ext2.version})` }),
          /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { color: activeColor, children: ` - ${activeString}` }),
          /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { color: stateColor, children: ` (${stateText})` })
        ] }),
        ext2.resolvedSettings && ext2.resolvedSettings.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text3, { children: "settings:" }),
          ext2.resolvedSettings.map((setting) => /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text3, { children: [
            "- ",
            setting.name,
            ": ",
            setting.value
          ] }, setting.name))
        ] })
      ] }, ext2.name);
    }) })
  ] });
}, "ExtensionsList");

// packages/cli/src/ui/components/HistoryItemDisplay.tsx
init_dist4();

// packages/cli/src/ui/components/views/SkillsList.tsx
init_esbuild_shims();
init_types22();
init_i18n();
var import_jsx_runtime50 = __toESM(require_jsx_runtime(), 1);
var SkillsList = /* @__PURE__ */ __name(({ skills }) => /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Available skills:") }),
  /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { height: 1 }),
  skills.length > 0 ? skills.map((skill) => /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text3, { color: theme.text.primary, children: [
      "  ",
      "- "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text3, { bold: true, color: theme.text.accent, children: skill.name })
  ] }, skill.name)) : /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text3, { color: theme.text.primary, children: [
    " ",
    t4("No skills available")
  ] })
] }), "SkillsList");

// packages/cli/src/ui/components/views/ToolsList.tsx
init_esbuild_shims();
init_types22();
init_i18n();
var import_jsx_runtime51 = __toESM(require_jsx_runtime(), 1);
var ToolsList = /* @__PURE__ */ __name(({
  tools,
  showDescriptions,
  contentWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Box_default, { flexDirection: "column", children: [
  /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Available Qwen Code CLI tools:") }),
  /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { height: 1 }),
  tools.length > 0 ? tools.map((tool) => /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Text3, { color: theme.text.primary, children: [
      "  ",
      "- "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Text3, { bold: true, color: theme.text.accent, children: [
        tool.displayName,
        showDescriptions ? ` (${tool.name})` : ""
      ] }),
      showDescriptions && tool.description && /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(
        MarkdownDisplay,
        {
          contentWidth,
          text: tool.description,
          isPending: false
        }
      )
    ] })
  ] }, tool.name)) : /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Text3, { color: theme.text.primary, children: [
    " ",
    t4("No tools available")
  ] })
] }), "ToolsList");

// packages/cli/src/ui/components/views/McpStatus.tsx
init_esbuild_shims();
init_dist4();
init_i18n();
var import_jsx_runtime52 = __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_runtime52.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { children: t4("No MCP servers configured.") }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", children: [
    discoveryInProgress && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.status.warning, children: t4("\u23F3 MCP servers are starting up ({{count}} initializing)...", {
        count: String(connectingServers.length)
      }) }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.primary, children: t4(
        "Note: First startup may take longer. Tool availability will update automatically."
      ) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, children: t4("Configured MCP servers:") }),
    /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { height: 1 }),
    serverNames.map((serverName) => {
      const server = servers[serverName];
      const serverTools = tools.filter(
        (tool) => tool.serverName === serverName
      );
      const serverPrompts = 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 statusIndicator2 = "";
      let statusText = "";
      let statusColor = theme.text.primary;
      switch (status) {
        case MCPServerStatus.CONNECTED:
          statusIndicator2 = "\u{1F7E2}";
          statusText = t4("Ready");
          statusColor = theme.status.success;
          break;
        case MCPServerStatus.CONNECTING:
          statusIndicator2 = "\u{1F504}";
          statusText = t4("Starting... (first startup may take longer)");
          statusColor = theme.status.warning;
          break;
        case MCPServerStatus.DISCONNECTED:
        default:
          statusIndicator2 = "\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 parts2 = [];
      if (toolCount > 0) {
        parts2.push(
          toolCount === 1 ? t4("{{count}} tool", { count: String(toolCount) }) : t4("{{count}} tools", { count: String(toolCount) })
        );
      }
      if (promptCount > 0) {
        parts2.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_runtime52.jsxs)(Text3, { children: [
          " (",
          t4("OAuth"),
          ")"
        ] });
      } else if (serverAuthStatus === "expired") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.status.error, children: [
          " (",
          t4("OAuth expired"),
          ")"
        ] });
      } else if (serverAuthStatus === "unauthenticated") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: theme.status.warning, children: [
          " ",
          "(",
          t4("OAuth not authenticated"),
          ")"
        ] });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { color: statusColor, children: [
            statusIndicator2,
            " "
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { bold: true, children: serverDisplayName }),
          /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
            " - ",
            statusText,
            status === MCPServerStatus.CONNECTED && parts2.length > 0 && ` (${parts2.join(", ")})`
          ] }),
          authStatusNode
        ] }),
        status === MCPServerStatus.CONNECTING && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
          " (",
          t4("tools and prompts will appear when ready"),
          ")"
        ] }),
        status === MCPServerStatus.DISCONNECTED && toolCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
          "(",
          t4("{{count}} tools cached", { count: String(toolCount) }),
          ")"
        ] }),
        showDescriptions && server?.description && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.secondary, children: server.description.trim() }),
        serverTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(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_runtime52.jsxs)(Box_default, { flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
                "- ",
                /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.primary, children: tool.name })
              ] }),
              showDescriptions && tool.description && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.secondary, children: tool.description.trim() }) }),
              schemaContent && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginLeft: 4, children: [
                /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.secondary, children: t4("Parameters:") }),
                /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.secondary, children: schemaContent })
              ] })
            ] }, tool.name);
          })
        ] }),
        serverPrompts.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.primary, children: t4("Prompts:") }),
          serverPrompts.map((prompt) => /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
              "- ",
              /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.primary, children: prompt.name })
            ] }),
            showDescriptions && prompt.description && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.primary, children: prompt.description.trim() }) })
          ] }, prompt.name))
        ] })
      ] }, serverName);
    }),
    blockedServers.map((server) => /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.status.error, children: "\u{1F534} " }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { bold: true, children: [
        server.name,
        server.extensionName ? ` ${t4("(from {{extensionName}})", {
          extensionName: server.extensionName
        })}` : ""
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
        " - ",
        t4("Blocked")
      ] })
    ] }, server.name)),
    showTips && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.accent, children: t4("\u{1F4A1} Tips:") }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
        "  ",
        "- ",
        t4("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.accent, children: "/mcp desc" }),
        " ",
        t4("to show server and tool descriptions")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
        "  ",
        "- ",
        t4("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.accent, children: "/mcp schema" }),
        " ",
        t4("to show tool parameter schemas")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
        "  ",
        "- ",
        t4("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.accent, children: "/mcp nodesc" }),
        " ",
        t4("to hide descriptions")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
        "  ",
        "- ",
        t4("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.accent, children: "/mcp auth <server-name>" }),
        " ",
        t4("to authenticate with OAuth-enabled servers")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text3, { children: [
        "  ",
        "- ",
        t4("Press"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text3, { color: theme.text.accent, children: "Ctrl+T" }),
        " ",
        t4("to toggle tool descriptions on/off")
      ] })
    ] })
  ] });
}, "McpStatus");

// packages/cli/src/ui/components/views/ContextUsage.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime53 = __toESM(require_jsx_runtime(), 1);
var FILLED = "\u2588";
var BUFFER3 = "\u2592";
var EMPTY2 = "\u2591";
var CONTENT_WIDTH = 56;
function truncateName(name4, maxLen) {
  if (name4.length <= maxLen) return name4;
  return name4.slice(0, maxLen - 1) + "\u2026";
}
__name(truncateName, "truncateName");
function formatTokens(tokens) {
  if (tokens >= 1e3) {
    return `${(tokens / 1e3).toFixed(1)}k`;
  }
  return `${tokens}`;
}
__name(formatTokens, "formatTokens");
var ProgressBar = /* @__PURE__ */ __name(({ usedPercentage, bufferPercentage, width }) => {
  const usedCount = Math.round(Math.min(usedPercentage, 100) / 100 * width);
  const bufferCount = Math.round(
    Math.min(bufferPercentage, 100 - usedPercentage) / 100 * width
  );
  const freeCount = Math.max(0, width - usedCount - bufferCount);
  const usedStr = FILLED.repeat(Math.max(0, usedCount));
  const freeStr = EMPTY2.repeat(Math.max(0, freeCount));
  const bufferStr = BUFFER3.repeat(Math.max(0, bufferCount));
  let usedColor = theme.text.accent;
  if (usedPercentage > 80) {
    usedColor = theme.status.error;
  } else if (usedPercentage > 60) {
    usedColor = theme.status.warning;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: usedColor, children: usedStr }),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: theme.text.secondary, children: freeStr }),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: theme.status.warning, children: bufferStr })
  ] });
}, "ProgressBar");
function formatPercentage(tokens, contextWindowSize) {
  if (contextWindowSize <= 0) return "0.0";
  const percentage = tokens / contextWindowSize * 100;
  if (percentage > 100) {
    return ">100";
  }
  return percentage.toFixed(1);
}
__name(formatPercentage, "formatPercentage");
var CategoryRow = /* @__PURE__ */ __name(({
  symbol: symbol2,
  label,
  tokens,
  contextWindowSize,
  symbolColor,
  isOverLimit
}) => {
  const percentageStr = formatPercentage(tokens, contextWindowSize);
  const tokenStr = `${formatTokens(tokens)} ${t4("tokens")} (${percentageStr}%)`;
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { width: CONTENT_WIDTH, children: [
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { width: 2, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: symbolColor || theme.text.secondary, children: symbol2 }) }),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { width: 24, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: theme.text.primary, children: label }) }),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: isOverLimit ? theme.status.error : theme.text.secondary, children: tokenStr }) })
  ] });
}, "CategoryRow");
var DETAIL_NAME_MAX_LEN = 30;
var DetailRow = /* @__PURE__ */ __name(({ name: name4, tokens }) => {
  const tokenStr = tokens > 0 ? `${formatTokens(tokens)} ${t4("tokens")}` : `0 ${t4("tokens")}`;
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { width: CONTENT_WIDTH, paddingLeft: 2, children: [
    /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { color: theme.text.secondary, children: [
      "\u2514",
      " "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { width: 32, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: theme.text.link, children: truncateName(name4, DETAIL_NAME_MAX_LEN) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: theme.text.secondary, children: tokenStr }) })
  ] });
}, "DetailRow");
var ContextUsage = /* @__PURE__ */ __name(({
  modelName,
  totalTokens,
  contextWindowSize,
  breakdown,
  builtinTools,
  mcpTools,
  memoryFiles,
  skills,
  isEstimated,
  showDetails = false
}) => {
  const percentage = contextWindowSize > 0 ? totalTokens / contextWindowSize * 100 : 0;
  const isOverLimit = percentage > 100;
  const sortedBuiltinTools = [...builtinTools].sort(
    (a2, b2) => b2.tokens - a2.tokens
  );
  const sortedMcpTools = [...mcpTools].sort((a2, b2) => b2.tokens - a2.tokens);
  const sortedMemoryFiles = [...memoryFiles].sort(
    (a2, b2) => b2.tokens - a2.tokens
  );
  const sortedSkills = [...skills].sort((a2, b2) => {
    if (a2.loaded !== b2.loaded) return a2.loaded ? -1 : 1;
    const aTotal = a2.tokens + (a2.bodyTokens ?? 0);
    const bTotal = b2.tokens + (b2.bodyTokens ?? 0);
    return bTotal - aTotal;
  });
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Context Usage") }),
        /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { height: 1 }),
        isEstimated ? /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(import_jsx_runtime53.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: theme.status.warning, italic: true, children: t4("No API response yet. Send a message to see actual usage.") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Estimated pre-conversation overhead") }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { color: theme.text.secondary, children: [
            t4("Model"),
            ": ",
            modelName,
            "  ",
            t4("Context window"),
            ": ",
            formatTokens(contextWindowSize),
            " ",
            t4("tokens")
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { height: 1 })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(import_jsx_runtime53.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { width: CONTENT_WIDTH, marginBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { color: theme.text.secondary, children: [
              t4("Model"),
              ": ",
              modelName
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { color: theme.text.secondary, children: [
              t4("Context window"),
              ": ",
              formatTokens(contextWindowSize),
              " ",
              t4("tokens")
            ] }) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { width: CONTENT_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
            ProgressBar,
            {
              usedPercentage: Math.min(percentage, 100),
              bufferPercentage: contextWindowSize > 0 ? breakdown.autocompactBuffer / contextWindowSize * 100 : 0,
              width: CONTENT_WIDTH
            }
          ) }),
          isOverLimit && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: theme.status.error, children: t4("Context exceeds limit! Use /compress or /clear to reduce.") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { height: 1 }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
            CategoryRow,
            {
              symbol: FILLED,
              label: t4("Used"),
              tokens: totalTokens,
              contextWindowSize,
              symbolColor: isOverLimit ? theme.status.error : theme.text.accent,
              isOverLimit
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
            CategoryRow,
            {
              symbol: EMPTY2,
              label: t4("Free"),
              tokens: breakdown.freeSpace,
              contextWindowSize,
              symbolColor: theme.text.secondary
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
            CategoryRow,
            {
              symbol: BUFFER3,
              label: t4("Autocompact buffer"),
              tokens: breakdown.autocompactBuffer,
              contextWindowSize,
              symbolColor: theme.status.warning
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { height: 1 }),
          /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Usage by category") })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t4("System prompt"),
            tokens: breakdown.systemPrompt,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t4("Built-in tools"),
            tokens: breakdown.builtinTools,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        breakdown.mcpTools > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t4("MCP tools"),
            tokens: breakdown.mcpTools,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t4("Memory files"),
            tokens: breakdown.memoryFiles,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t4("Skills"),
            tokens: breakdown.skills,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        !isEstimated && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t4("Messages"),
            tokens: breakdown.messages,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        showDetails ? /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(import_jsx_runtime53.Fragment, { children: [
          sortedBuiltinTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Built-in tools") }),
            sortedBuiltinTools.map((tool) => /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
              DetailRow,
              {
                name: tool.name,
                tokens: tool.tokens
              },
              tool.name
            ))
          ] }),
          sortedMcpTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("MCP tools") }),
            sortedMcpTools.map((tool) => /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
              DetailRow,
              {
                name: tool.name,
                tokens: tool.tokens
              },
              tool.name
            ))
          ] }),
          sortedMemoryFiles.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Memory files") }),
            sortedMemoryFiles.map((file2) => /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
              DetailRow,
              {
                name: file2.path,
                tokens: file2.tokens
              },
              file2.path
            ))
          ] }),
          sortedSkills.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Skills") }),
            sortedSkills.map((skill) => /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { width: CONTENT_WIDTH, paddingLeft: 2, children: [
                /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { color: theme.text.secondary, children: [
                  "\u2514",
                  " "
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { width: 32, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: theme.text.link, children: truncateName(skill.name, DETAIL_NAME_MAX_LEN) }),
                  skill.loaded && /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { color: theme.status.success, children: [
                    " ",
                    t4("active")
                  ] })
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { color: theme.text.secondary, children: [
                  formatTokens(skill.tokens),
                  " ",
                  t4("tokens")
                ] }) })
              ] }),
              skill.loaded && skill.bodyTokens != null && skill.bodyTokens > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { width: CONTENT_WIDTH, paddingLeft: 4, children: [
                /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { color: theme.text.secondary, children: [
                  "  \u2514",
                  " "
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { width: 30, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: theme.text.secondary, italic: true, children: t4("body loaded") }) }),
                /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text3, { color: theme.status.success, children: [
                  "+",
                  formatTokens(skill.bodyTokens),
                  " ",
                  t4("tokens")
                ] }) })
              ] })
            ] }, skill.name))
          ] })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text3, { color: theme.text.secondary, italic: true, children: t4("Run /context detail for per-item breakdown.") }) })
      ]
    }
  );
}, "ContextUsage");

// packages/cli/src/ui/components/views/DoctorReport.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime54 = __toESM(require_jsx_runtime(), 1);
var STATUS_ICONS2 = {
  pass: "\u2713",
  // checkmark
  warn: "\u26A0",
  // warning triangle
  fail: "\u2717"
  // X mark
};
function getStatusColor3(status) {
  switch (status) {
    case "pass":
      return theme.status.success;
    case "warn":
      return theme.status.warning;
    case "fail":
      return theme.status.error;
    default:
      return theme.text.primary;
  }
}
__name(getStatusColor3, "getStatusColor");
function groupByCategory(checks) {
  const groups = /* @__PURE__ */ new Map();
  for (const check2 of checks) {
    const group = groups.get(check2.category);
    if (group) {
      group.push(check2);
    } else {
      groups.set(check2.category, [check2]);
    }
  }
  return groups;
}
__name(groupByCategory, "groupByCategory");
var DoctorReport = /* @__PURE__ */ __name(({
  checks,
  summary,
  width
}) => {
  const groups = groupByCategory(checks);
  const categoryEntries = Array.from(groups.entries());
  const nameColWidth = Math.max(20, ...checks.map((c4) => c4.name.length + 2));
  return /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Doctor Report") }),
        /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Box_default, { height: 1 }),
        categoryEntries.map(([category, items], groupIdx) => /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(
          Box_default,
          {
            flexDirection: "column",
            marginTop: groupIdx > 0 ? 1 : 0,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text3, { bold: true, color: theme.text.link, children: category }),
              items.map((check2) => /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Box_default, { flexDirection: "column", children: [
                /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Box_default, { flexDirection: "row", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Text3, { color: getStatusColor3(check2.status), children: [
                    "  ",
                    STATUS_ICONS2[check2.status],
                    " "
                  ] }),
                  /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Box_default, { width: nameColWidth, children: /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text3, { color: theme.text.primary, children: check2.name }) }),
                  /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text3, { dimColor: true, children: check2.message })
                ] }),
                check2.detail && /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Box_default, { marginLeft: 6, children: /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Text3, { dimColor: true, children: [
                  "-> ",
                  check2.detail
                ] }) })
              ] }, `${category}-${check2.name}`))
            ]
          },
          category
        )),
        /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Box_default, { marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text3, { dimColor: true, children: "-- " }),
          /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Text3, { color: theme.status.success, children: [
            summary.pass,
            " ",
            t4("passed")
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text3, { dimColor: true, children: ", " }),
          /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Text3, { color: theme.status.warning, children: [
            summary.warn,
            " ",
            t4("warnings")
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text3, { dimColor: true, children: ", " }),
          /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Text3, { color: theme.status.error, children: [
            summary.fail,
            " ",
            t4("failures")
          ] })
        ] })
      ]
    }
  );
}, "DoctorReport");

// packages/cli/src/ui/components/arena/ArenaCards.tsx
init_esbuild_shims();
var import_jsx_runtime55 = __toESM(require_jsx_runtime(), 1);
var ArenaAgentCard = /* @__PURE__ */ __name(({
  agent,
  width
}) => {
  const { icon, text, color } = getArenaStatusLabel(agent.status);
  const duration3 = formatDuration(agent.durationMs);
  const tokens = agent.totalTokens.toLocaleString();
  const inTokens = agent.inputTokens.toLocaleString();
  const outTokens = agent.outputTokens.toLocaleString();
  return /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", width, children: [
    /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color, children: [
      icon,
      " ",
      agent.label,
      " \xB7 ",
      text,
      " \xB7 ",
      duration3
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.secondary, children: [
      "Tokens: ",
      tokens,
      " (in ",
      inTokens,
      ", out ",
      outTokens,
      ")"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.secondary, children: [
      "Tool Calls: ",
      agent.toolCalls,
      agent.failedToolCalls > 0 && /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(import_jsx_runtime55.Fragment, { children: [
        " ",
        "(",
        /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.status.success, children: [
          "\u2713 ",
          agent.successfulToolCalls
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.secondary, children: " " }),
        /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.status.error, children: [
          "\u2715 ",
          agent.failedToolCalls
        ] }),
        ")"
      ] })
    ] }) }),
    agent.error && /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.status.error, children: agent.error }) })
  ] });
}, "ArenaAgentCard");
function getDiffStats(diff4, diffSummary) {
  if (diffSummary) {
    return {
      text: `+${diffSummary.additions}/-${diffSummary.deletions}`,
      additions: diffSummary.additions,
      deletions: diffSummary.deletions
    };
  }
  if (!diff4) return { text: "", additions: 0, deletions: 0 };
  const lines = diff4.split("\n");
  let additions = 0;
  let deletions = 0;
  for (const line of lines) {
    if (line.startsWith("+") && !line.startsWith("+++")) {
      additions++;
    } else if (line.startsWith("-") && !line.startsWith("---")) {
      deletions++;
    }
  }
  return { text: `+${additions}/-${deletions}`, additions, deletions };
}
__name(getDiffStats, "getDiffStats");
var MAX_FILE_LIST_ITEMS = 4;
function formatFileList2(files) {
  if (!files || files.length === 0) {
    return "none";
  }
  const visible = files.slice(0, MAX_FILE_LIST_ITEMS);
  const suffix = files.length > MAX_FILE_LIST_ITEMS ? `, +${files.length - MAX_FILE_LIST_ITEMS} more` : "";
  return `${visible.join(", ")}${suffix}`;
}
__name(formatFileList2, "formatFileList");
function getAgentFiles(agent) {
  return agent.modifiedFiles ?? agent.diffSummary?.files.map((file2) => file2.path) ?? [];
}
__name(getAgentFiles, "getAgentFiles");
function getComparisonFileGroups(agents) {
  const counts = /* @__PURE__ */ new Map();
  for (const agent of agents) {
    for (const file2 of new Set(getAgentFiles(agent))) {
      counts.set(file2, (counts.get(file2) ?? 0) + 1);
    }
  }
  const common = [...counts.entries()].filter(([, count]) => count > 1).map(([file2]) => file2).sort();
  const groups = [{ label: "common", files: common }];
  for (const agent of agents) {
    const unique = getAgentFiles(agent).filter((file2) => counts.get(file2) === 1).sort();
    if (unique.length > 0) {
      groups.push({ label: `${agent.label}-only`, files: unique });
    }
  }
  return groups;
}
__name(getComparisonFileGroups, "getComparisonFileGroups");
function getTreeBranch(index, total) {
  return index === total - 1 ? "\u2514\u2500" : "\u251C\u2500";
}
__name(getTreeBranch, "getTreeBranch");
var ArenaSessionCard = /* @__PURE__ */ __name(({
  sessionStatus,
  agents,
  width
}) => {
  const titleLabel = sessionStatus === "idle" || sessionStatus === "completed" ? "Arena Comparison Summary" : sessionStatus === "cancelled" ? "Arena Cancelled" : "Arena Failed";
  return /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingX: 2,
      paddingY: 1,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { bold: true, color: theme.text.primary, children: titleLabel }) }),
        /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { height: 1 }),
        (sessionStatus === "idle" || sessionStatus === "completed") && /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(import_jsx_runtime55.Fragment, { children: [
          /* @__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: "Status Summary:" }),
            agents.map((agent, index) => {
              const { text: statusText, color } = getArenaStatusLabel(
                agent.status
              );
              return /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { marginLeft: 2, children: [
                /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.secondary, children: [
                  index === agents.length - 1 ? "\u2514\u2500" : "\u251C\u2500",
                  " ",
                  agent.label,
                  ":",
                  " "
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color, children: statusText })
              ] }, agent.label);
            })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { height: 1 }),
          /* @__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: "Files Modified:" }),
            getComparisonFileGroups(agents).map((group, index, groups) => /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { marginLeft: 2, children: [
              /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.secondary, children: [
                getTreeBranch(index, groups.length),
                " ",
                group.label,
                ":",
                " "
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.primary, children: formatFileList2(group.files) })
            ] }, group.label))
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { height: 1 }),
          /* @__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: "Approach Summary:" }),
            agents.map((agent, index) => {
              const diffStats = getDiffStats(agent.diff, agent.diffSummary);
              const files = getAgentFiles(agent).length;
              const branch = index === agents.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
              const summary = agent.approachSummary ?? "No approach summary available.";
              return /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { children: [
                /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.secondary, children: [
                  branch,
                  " ",
                  agent.label,
                  ":",
                  " "
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.primary, children: [
                  summary,
                  " "
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.secondary, children: "(" }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.accent, children: files }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.secondary, children: files === 1 ? " file, " : " files, " }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.status.success, children: [
                  "+",
                  diffStats.additions
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.secondary, children: " " }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.status.error, children: [
                  "-",
                  diffStats.deletions
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.secondary, children: " lines, " }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.accent, children: agent.toolCalls }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.secondary, children: agent.toolCalls === 1 ? " tool call)" : " tool calls)" })
              ] }) }, agent.label);
            })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { height: 1 }),
          /* @__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: "Token Efficiency:" }),
            agents.map((agent, index) => /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { marginLeft: 2, children: [
              /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.secondary, children: [
                index === agents.length - 1 ? "\u2514\u2500" : "\u251C\u2500",
                " ",
                agent.label,
                ":",
                " "
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.primary, children: [
                agent.totalTokens.toLocaleString(),
                " tokens \xB7 runtime",
                " ",
                formatDuration(agent.durationMs)
              ] })
            ] }, agent.label))
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { height: 1 }),
        sessionStatus === "idle" && /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.secondary, children: [
          "Run ",
          /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.accent, children: "/arena select" }),
          " to view detailed diff or pick a winner."
        ] }) }),
        sessionStatus === "completed" && /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text3, { color: theme.text.secondary, children: [
          "Run ",
          /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text3, { color: theme.text.accent, children: "/arena select" }),
          " to pick a winner."
        ] }) })
      ]
    }
  );
}, "ArenaSessionCard");

// packages/cli/src/ui/components/messages/InsightProgressMessage.tsx
init_esbuild_shims();
var import_jsx_runtime56 = __toESM(require_jsx_runtime(), 1);
var InsightProgressMessage = /* @__PURE__ */ __name(({
  progress
}) => {
  const { stage, progress: percent, isComplete, error: error40 } = 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 (error40) {
    return /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { color: theme.status.error, children: [
        "\u2715 ",
        stage
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.secondary, children: error40 })
    ] });
  }
  if (isComplete) {
    return /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Box_default, { flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { color: theme.status.success, children: [
      "\u2713 ",
      stage
    ] }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { color: theme.text.accent, children: /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(build_default, { type: "dots" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text3, { children: " " }),
    /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { color: theme.text.secondary, children: [
      bar,
      " "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text3, { color: theme.text.accent, children: [
      stage,
      progress.detail ? ` (${progress.detail})` : ""
    ] })
  ] });
}, "InsightProgressMessage");

// packages/cli/src/ui/components/messages/BtwMessage.tsx
init_esbuild_shims();
var import_react72 = __toESM(require_react(), 1);
init_i18n();

// packages/cli/src/ui/hooks/useTerminalSize.ts
init_esbuild_shims();
var import_react71 = __toESM(require_react(), 1);
function useTerminalSize() {
  const [size, setSize] = (0, import_react71.useState)({
    columns: process.stdout.columns || 80,
    rows: process.stdout.rows || 24
  });
  (0, import_react71.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/messages/BtwMessage.tsx
var import_jsx_runtime57 = __toESM(require_jsx_runtime(), 1);
var BTW_SELF_CHROME = 4;
function normalizeCodeFences(text) {
  return text.replace(/([^\n])(```|~~~)/g, "$1\n$2");
}
__name(normalizeCodeFences, "normalizeCodeFences");
var BtwMessageInternal = /* @__PURE__ */ __name(({
  btw,
  containerWidth
}) => {
  const { columns: terminalWidth } = useTerminalSize();
  const baseWidth = containerWidth ?? terminalWidth;
  const contentWidth = Math.max(2, baseWidth - BTW_SELF_CHROME);
  return /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: Colors.AccentYellow,
      paddingX: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Text3, { color: Colors.AccentYellow, bold: true, children: "/btw " }),
          /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Text3, { wrap: "wrap", color: Colors.AccentYellow, children: btw.question })
        ] }),
        btw.isPending ? /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Box_default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Text3, { color: Colors.AccentYellow, children: "+ " }),
            /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Text3, { color: Colors.AccentYellow, children: t4("Answering...") })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Text3, { dimColor: true, children: t4("Press Escape, Ctrl+C, or Ctrl+D to cancel") }) })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(
            MarkdownDisplay,
            {
              text: normalizeCodeFences(btw.answer),
              isPending: false,
              contentWidth
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Text3, { dimColor: true, children: t4("Press Space, Enter, or Escape to dismiss") }) })
        ] })
      ]
    }
  );
}, "BtwMessageInternal");
var BtwMessage = import_react72.default.memo(BtwMessageInternal);

// packages/cli/src/ui/components/messages/MemorySavedMessage.tsx
init_esbuild_shims();
var import_jsx_runtime58 = __toESM(require_jsx_runtime(), 1);
var MemorySavedMessage = /* @__PURE__ */ __name(({
  item
}) => {
  const verb = item.verb ?? "Saved";
  const n3 = item.writtenCount;
  const label = n3 === 1 ? "memory" : "memories";
  return /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Box_default, { minWidth: 2, children: /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Text3, { dimColor: true, children: "\u25CF" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(Text3, { dimColor: true, children: [
      verb,
      " ",
      n3,
      " ",
      label
    ] })
  ] });
}, "MemorySavedMessage");

// packages/cli/src/ui/components/HistoryItemDisplay.tsx
var import_jsx_runtime59 = __toESM(require_jsx_runtime(), 1);
var HistoryItemDisplayComponent = /* @__PURE__ */ __name(({
  item,
  availableTerminalHeight,
  terminalWidth,
  mainAreaWidth,
  isPending,
  commands,
  isFocused = true,
  activeShellPtyId,
  embeddedShellFocused,
  availableTerminalHeightGemini,
  compactLabel,
  summaryAbsorbed = false
}) => {
  const marginTop = item.type === "gemini_content" || item.type === "gemini_thought_content" ? 0 : 1;
  const { compactMode } = useCompactMode();
  const itemForDisplay = (0, import_react73.useMemo)(() => escapeAnsiCtrlCodes(item), [item]);
  const contentWidth = terminalWidth - 4;
  const boxWidth = mainAreaWidth || contentWidth;
  return /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      marginTop,
      marginLeft: 2,
      marginRight: 2,
      children: [
        itemForDisplay.type === "user" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(UserMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "notification" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(InfoMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "user_shell" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(UserShellMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "gemini" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          AssistantMessage,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth
          }
        ),
        itemForDisplay.type === "gemini_content" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          AssistantMessageContent,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth
          }
        ),
        !compactMode && itemForDisplay.type === "gemini_thought" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          ThinkMessage,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth
          }
        ),
        !compactMode && itemForDisplay.type === "gemini_thought_content" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          ThinkMessageContent,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth
          }
        ),
        itemForDisplay.type === "info" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          InfoMessage,
          {
            text: itemForDisplay.text,
            linkUrl: itemForDisplay.linkUrl,
            linkText: itemForDisplay.linkText
          }
        ),
        itemForDisplay.type === "success" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SuccessMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "warning" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(WarningMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "error" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(ErrorMessage, { text: itemForDisplay.text, hint: itemForDisplay.hint }),
        itemForDisplay.type === "retry_countdown" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(RetryCountdownMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "about" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(AboutBox, { ...itemForDisplay.systemInfo, width: boxWidth }),
        itemForDisplay.type === "help" && commands && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Help, { commands, width: boxWidth }),
        itemForDisplay.type === "stats" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(StatsDisplay, { duration: itemForDisplay.duration, width: boxWidth }),
        itemForDisplay.type === "model_stats" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(ModelStatsDisplay, { width: boxWidth }),
        itemForDisplay.type === "tool_stats" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(ToolStatsDisplay, { width: boxWidth }),
        itemForDisplay.type === "quit" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          SessionSummaryDisplay,
          {
            duration: itemForDisplay.duration,
            width: boxWidth
          }
        ),
        itemForDisplay.type === "tool_group" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          ToolGroupMessage,
          {
            toolCalls: itemForDisplay.tools,
            groupId: itemForDisplay.id,
            availableTerminalHeight,
            contentWidth,
            isFocused,
            activeShellPtyId,
            embeddedShellFocused,
            memoryWriteCount: itemForDisplay.memoryWriteCount,
            memoryReadCount: itemForDisplay.memoryReadCount,
            isUserInitiated: itemForDisplay.isUserInitiated,
            compactLabel
          }
        ),
        itemForDisplay.type === "tool_use_summary" && (!compactMode || !summaryAbsorbed) && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(Text3, { dimColor: true, children: [
          "\u25CF ",
          itemForDisplay.summary
        ] }) }),
        itemForDisplay.type === "compression" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(CompressionMessage, { compression: itemForDisplay.compression }),
        itemForDisplay.type === "summary" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SummaryMessage, { summary: itemForDisplay.summary }),
        itemForDisplay.type === "extensions_list" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(ExtensionsList, {}),
        itemForDisplay.type === "tools_list" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          ToolsList,
          {
            contentWidth,
            tools: itemForDisplay.tools,
            showDescriptions: itemForDisplay.showDescriptions
          }
        ),
        itemForDisplay.type === "skills_list" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(SkillsList, { skills: itemForDisplay.skills }),
        itemForDisplay.type === "mcp_status" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(McpStatus, { ...itemForDisplay, serverStatus: getMCPServerStatus }),
        itemForDisplay.type === "context_usage" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          ContextUsage,
          {
            modelName: itemForDisplay.modelName,
            totalTokens: itemForDisplay.totalTokens,
            contextWindowSize: itemForDisplay.contextWindowSize,
            breakdown: itemForDisplay.breakdown,
            builtinTools: itemForDisplay.builtinTools,
            mcpTools: itemForDisplay.mcpTools,
            memoryFiles: itemForDisplay.memoryFiles,
            skills: itemForDisplay.skills,
            isEstimated: itemForDisplay.isEstimated,
            showDetails: itemForDisplay.showDetails
          }
        ),
        itemForDisplay.type === "doctor" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          DoctorReport,
          {
            checks: itemForDisplay.checks,
            summary: itemForDisplay.summary,
            width: boxWidth
          }
        ),
        itemForDisplay.type === "arena_agent_complete" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(ArenaAgentCard, { agent: itemForDisplay.agent, width: boxWidth }),
        itemForDisplay.type === "arena_session_complete" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          ArenaSessionCard,
          {
            sessionStatus: itemForDisplay.sessionStatus,
            task: itemForDisplay.task,
            totalDurationMs: itemForDisplay.totalDurationMs,
            agents: itemForDisplay.agents,
            width: boxWidth
          }
        ),
        itemForDisplay.type === "insight_progress" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(InsightProgressMessage, { progress: itemForDisplay.progress }),
        itemForDisplay.type === "btw" && itemForDisplay.btw && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(BtwMessage, { btw: itemForDisplay.btw, containerWidth: contentWidth }),
        itemForDisplay.type === "user_prompt_submit_blocked" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Text3, { color: theme.status.warning, children: `\u2715 UserPromptSubmit operation blocked by hook:
${itemForDisplay.reason}

Original prompt: ${sanitizeSensitiveText(itemForDisplay.originalPrompt)}` }) }),
        itemForDisplay.type === "stop_hook_loop" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
          InfoMessage,
          {
            text: `Ran ${itemForDisplay.stopHookCount} stop hooks
  \u23BF  Stop hook error: ${itemForDisplay.reasons[itemForDisplay.reasons.length - 1]}`
          }
        ),
        itemForDisplay.type === "stop_hook_system_message" && /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Text3, { color: theme.text.primary, children: " \u23BF Stop says:" }),
          /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Box_default, { marginLeft: 4, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
            MarkdownDisplay,
            {
              text: itemForDisplay.message,
              isPending: false,
              contentWidth: contentWidth - 4
            }
          ) })
        ] }),
        itemForDisplay.type === "memory_saved" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(MemorySavedMessage, { item: itemForDisplay }),
        itemForDisplay.type === "away_recap" && /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(AwayRecapMessage, { text: itemForDisplay.text })
      ]
    },
    itemForDisplay.id
  );
}, "HistoryItemDisplayComponent");

// packages/cli/src/ui/components/QuittingDisplay.tsx
var import_jsx_runtime60 = __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_runtime60.jsx)(Box_default, { flexDirection: "column", marginBottom: 1, children: uiState.quittingMessages.map((item) => /* @__PURE__ */ (0, import_jsx_runtime60.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_react74 = __toESM(require_react(), 1);
var AppContext2 = (0, import_react74.createContext)(null);
var useAppContext = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react74.useContext)(AppContext2);
  if (!context2) {
    throw new Error("useAppContext must be used within an AppProvider");
  }
  return context2;
}, "useAppContext");

// packages/cli/src/ui/components/Notifications.tsx
init_types22();

// packages/cli/src/ui/components/UpdateNotification.tsx
init_esbuild_shims();
var import_jsx_runtime61 = __toESM(require_jsx_runtime(), 1);
var UpdateNotification = /* @__PURE__ */ __name(({ message }) => /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
  Box_default,
  {
    borderStyle: "round",
    borderColor: theme.status.warning,
    paddingX: 1,
    marginY: 1,
    children: /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(Text3, { color: theme.status.warning, children: message })
  }
), "UpdateNotification");

// packages/cli/src/ui/components/Notifications.tsx
var import_jsx_runtime62 = __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_runtime62.jsxs)(import_jsx_runtime62.Fragment, { children: [
    updateInfo && /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(UpdateNotification, { message: updateInfo.message }),
    showStartupWarnings && /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.status.warning,
        paddingX: 1,
        marginY: 1,
        flexDirection: "column",
        children: startupWarnings.map((warning, index) => /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(Text3, { color: theme.status.warning, children: warning }, index))
      }
    ),
    showInitError && /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.status.error,
        paddingX: 1,
        marginBottom: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(Text3, { color: theme.status.error, children: [
            "Initialization Error: ",
            initError
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime62.jsxs)(Text3, { color: theme.status.error, children: [
            " ",
            "Please check API key and configuration."
          ] })
        ]
      }
    )
  ] });
}, "Notifications");

// packages/cli/src/ui/components/MainContent.tsx
init_esbuild_shims();
var import_react78 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/ShowMoreLines.tsx
init_esbuild_shims();
init_types22();
var import_jsx_runtime63 = __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_runtime63.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text3, { color: theme.text.secondary, wrap: "truncate", children: "Press ctrl-s to show more lines" }) });
}, "ShowMoreLines");

// packages/cli/src/ui/contexts/UIActionsContext.tsx
init_esbuild_shims();
var import_react76 = __toESM(require_react(), 1);

// packages/cli/src/ui/IdeIntegrationNudge.tsx
init_esbuild_shims();
var import_jsx_runtime64 = __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_runtime64.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Text3, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Text3, { color: theme.status.warning, children: "> " }),
            `Do you want to connect ${ideName ?? "your editor"} to Qwen Code?`
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Text3, { color: theme.text.secondary, children: installText })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete })
      ]
    }
  );
}
__name(IdeIntegrationNudge, "IdeIntegrationNudge");

// packages/cli/src/ui/CommandFormatMigrationNudge.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime65 = __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_runtime65.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(Text3, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Text3, { color: theme.status.warning, children: "\u26A0\uFE0F  " }),
            /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Text3, { bold: true, children: t4("Command Format Migration") })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime65.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_runtime65.jsx)(Text3, { color: theme.text.secondary, children: fileList }),
          /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Text3, { children: "" }),
          /* @__PURE__ */ (0, import_jsx_runtime65.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_runtime65.jsx)(Text3, { color: theme.text.secondary, children: t4("(Backups will be created and original files will be preserved)") })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete })
      ]
    }
  );
}
__name(CommandFormatMigrationNudge, "CommandFormatMigrationNudge");

// packages/cli/src/ui/components/FolderTrustDialog.tsx
init_esbuild_shims();
var import_react75 = __toESM(require_react(), 1);
import * as process34 from "node:process";
import * as path128 from "node:path";

// packages/cli/src/utils/processUtils.ts
init_esbuild_shims();
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_runtime66 = __toESM(require_jsx_runtime(), 1);
var FolderTrustDialog = /* @__PURE__ */ __name(({
  onSelect,
  isRestarting
}) => {
  (0, import_react75.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 = path128.basename(process34.cwd());
  const parentFolder = path128.basename(path128.dirname(process34.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_runtime66.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: theme.status.warning,
        padding: 1,
        width: "100%",
        marginLeft: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime66.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(Text3, { bold: true, color: theme.text.primary, children: "Do you trust this folder?" }),
            /* @__PURE__ */ (0, import_jsx_runtime66.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_runtime66.jsx)(
            RadioButtonSelect,
            {
              items: options2,
              onSelect,
              isFocused: !isRestarting
            }
          )
        ]
      }
    ),
    isRestarting && /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(Box_default, { marginLeft: 1, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(Text3, { color: theme.status.warning, children: "Qwen Code is restarting to apply the trust changes..." }) })
  ] });
}, "FolderTrustDialog");

// packages/cli/src/ui/contexts/UIActionsContext.tsx
init_dist4();
var UIActionsContext = (0, import_react76.createContext)(null);
var useUIActions = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react76.useContext)(UIActionsContext);
  if (!context2) {
    throw new Error("useUIActions must be used within a UIActionsProvider");
  }
  return context2;
}, "useUIActions");

// packages/cli/src/ui/components/AppHeader.tsx
init_esbuild_shims();
init_dist4();

// packages/cli/src/ui/components/Header.tsx
init_esbuild_shims();
init_dist4();

// 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_runtime67 = __toESM(require_jsx_runtime(), 1);
var Header2 = /* @__PURE__ */ __name(({
  customAsciiArt,
  version: version2,
  authDisplayType,
  model,
  workingDirectory
}) => {
  const { columns: terminalWidth } = useTerminalSize();
  const displayLogo = customAsciiArt ?? shortAsciiLogo;
  const logoWidth = getAsciiArtWidth(displayLogo);
  const formattedAuthType = authDisplayType ?? "Unknown" /* UNKNOWN */;
  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 = getRenderableGradientColors(theme.ui.gradient, [
    theme.text.secondary,
    theme.text.link,
    theme.text.accent
  ]);
  return /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(
    Box_default,
    {
      flexDirection: "row",
      alignItems: "center",
      marginX: containerMarginX,
      width: availableTerminalWidth,
      children: [
        showLogo && /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(import_jsx_runtime67.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Box_default, { flexShrink: 0, children: gradientColors ? /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(dist_default6, { colors: gradientColors, children: /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Text3, { children: displayLogo }) }) : /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Text3, { children: displayLogo }) }),
          /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Box_default, { width: logoGap })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(
          Box_default,
          {
            flexDirection: "column",
            borderStyle: "single",
            borderColor: theme.border.default,
            paddingX: infoPanelPaddingX,
            flexGrow: showLogo ? 0 : 1,
            width: showLogo ? availableInfoPanelWidth : void 0,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Text3, { children: [
                /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Text3, { bold: true, color: theme.text.accent, children: ">_ Qwen Code" }),
                /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Text3, { color: theme.text.secondary, children: [
                  " (v",
                  version2,
                  ")"
                ] })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Text3, { children: " " }),
              /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Text3, { children: [
                /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Text3, { color: theme.text.secondary, children: authModelText }),
                showModelHint && /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Text3, { color: theme.text.secondary, children: modelHintText })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Text3, { color: theme.text.secondary, children: displayPath })
            ]
          }
        )
      ]
    }
  );
}, "Header");

// packages/cli/src/ui/components/Tips.tsx
init_esbuild_shims();
var import_react77 = __toESM(require_react(), 1);
init_i18n();

// packages/cli/src/services/tips/index.ts
init_esbuild_shims();

// packages/cli/src/services/tips/tipHistory.ts
init_esbuild_shims();
init_dist4();
import * as fs124 from "node:fs";
import * as path129 from "node:path";
var TipHistory = class _TipHistory {
  static {
    __name(this, "TipHistory");
  }
  /** In-session tracking: tipId → prompt count when last shown */
  sessionShown = /* @__PURE__ */ new Map();
  data;
  filePath;
  constructor(data, filePath) {
    this.data = data;
    this.filePath = filePath;
  }
  get sessionCount() {
    return this.data.sessionCount;
  }
  /**
   * Check if a tip has cooled down enough to be shown again.
   */
  isCooledDown(tipId, cooldownPrompts, currentPromptCount) {
    const lastShown = this.sessionShown.get(tipId);
    if (lastShown === void 0) return true;
    return currentPromptCount - lastShown >= cooldownPrompts;
  }
  /**
   * Get a recency score for LRU sorting. Lower = shown longer ago (or never).
   * Tips shown in this session get a high score (shown recently).
   * Tips never shown in this session fall back to cross-session
   * lastSessionTimestamp for true recency-based rotation.
   */
  getLastShown(tipId) {
    if (this.sessionShown.has(tipId)) {
      return Number.MAX_SAFE_INTEGER - 1e6 + (this.sessionShown.get(tipId) ?? 0);
    }
    return this.normalizeEntry(this.data.tips[tipId]).lastSessionTimestamp;
  }
  /**
   * Normalize a persisted tip entry so corrupted values cannot crash mutations.
   */
  normalizeEntry(raw2) {
    if (typeof raw2 !== "object" || raw2 === null || Array.isArray(raw2)) {
      return { totalShown: 0, lastSessionTimestamp: 0 };
    }
    const candidate = raw2;
    return {
      totalShown: typeof candidate.totalShown === "number" && Number.isFinite(candidate.totalShown) ? candidate.totalShown : 0,
      lastSessionTimestamp: typeof candidate.lastSessionTimestamp === "number" && Number.isFinite(candidate.lastSessionTimestamp) ? candidate.lastSessionTimestamp : 0
    };
  }
  /**
   * Record that a tip was shown at the given prompt count.
   */
  recordShown(tipId, currentPromptCount) {
    this.sessionShown.set(tipId, currentPromptCount);
    const entry = this.normalizeEntry(this.data.tips[tipId]);
    entry.totalShown++;
    entry.lastSessionTimestamp = Date.now();
    this.data.tips[tipId] = entry;
    this.persist();
  }
  /**
   * Persist history to disk.
   */
  persist() {
    try {
      const dir = path129.dirname(this.filePath);
      if (!fs124.existsSync(dir)) {
        fs124.mkdirSync(dir, { recursive: true });
      }
      fs124.writeFileSync(this.filePath, JSON.stringify(this.data, null, 2), {
        mode: 384
      });
    } catch {
    }
  }
  /**
   * Load history from disk, incrementing session count.
   */
  static load() {
    const filePath = path129.join(Storage.getGlobalQwenDir(), "tip_history.json");
    let data = { sessionCount: 0, tips: {} };
    try {
      if (fs124.existsSync(filePath)) {
        const raw2 = fs124.readFileSync(filePath, "utf-8");
        const parsed = JSON.parse(raw2);
        if (typeof parsed === "object" && parsed !== null && typeof parsed.sessionCount === "number") {
          data = {
            sessionCount: Number.isFinite(parsed.sessionCount) && parsed.sessionCount >= 0 ? Math.floor(parsed.sessionCount) : 0,
            tips: parsed.tips ?? {}
          };
        }
      }
    } catch {
    }
    data.sessionCount++;
    data.tips = typeof data.tips === "object" && data.tips !== null && !Array.isArray(data.tips) ? data.tips : {};
    const history = new _TipHistory(data, filePath);
    history.persist();
    return history;
  }
};

// packages/cli/src/services/tips/tipScheduler.ts
init_esbuild_shims();
function selectTip(trigger, context2, tips, history) {
  const candidates = tips.filter((tip) => tip.trigger === trigger).filter((tip) => {
    try {
      return tip.isRelevant(context2);
    } catch {
      return false;
    }
  }).filter(
    (tip) => history.isCooledDown(
      tip.id,
      tip.cooldownPrompts,
      context2.sessionPromptCount
    )
  );
  if (candidates.length === 0) return null;
  candidates.sort((a2, b2) => {
    if (b2.priority !== a2.priority) return b2.priority - a2.priority;
    return history.getLastShown(a2.id) - history.getLastShown(b2.id);
  });
  return candidates[0] ?? null;
}
__name(selectTip, "selectTip");

// packages/cli/src/services/tips/tipRegistry.ts
init_esbuild_shims();
init_dist4();
function getContextUsagePercent(ctx) {
  const windowSize = ctx.contextWindowSize || DEFAULT_TOKEN_LIMIT;
  return ctx.lastPromptTokenCount / windowSize * 100;
}
__name(getContextUsagePercent, "getContextUsagePercent");
var tipRegistry = [
  // --- Post-response contextual tips (priority: higher = more urgent) ---
  {
    id: "context-critical",
    content: "Context is almost full! Run /compress now or start /new to continue.",
    trigger: "post-response",
    isRelevant: /* @__PURE__ */ __name((ctx) => getContextUsagePercent(ctx) >= 95, "isRelevant"),
    cooldownPrompts: 3,
    priority: 100
  },
  {
    id: "context-high",
    content: "Context is getting full. Use /compress to free up space.",
    trigger: "post-response",
    isRelevant: /* @__PURE__ */ __name((ctx) => {
      const pct = getContextUsagePercent(ctx);
      return pct >= 80 && pct < 95;
    }, "isRelevant"),
    cooldownPrompts: 5,
    priority: 90
  },
  {
    id: "compress-intro",
    content: "Long conversation? /compress summarizes history to free context.",
    trigger: "post-response",
    isRelevant: /* @__PURE__ */ __name((ctx) => {
      const pct = getContextUsagePercent(ctx);
      return pct >= 50 && pct < 80 && ctx.sessionPromptCount > 5;
    }, "isRelevant"),
    cooldownPrompts: 10,
    priority: 50
  },
  // --- Startup tips ---
  {
    id: "new-user-slash",
    content: "Type / to open the command popup; Tab autocompletes slash commands and saved prompts.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name((ctx) => ctx.sessionCount < 5, "isRelevant"),
    cooldownPrompts: 0,
    priority: 70
  },
  {
    id: "new-user-qwenmd",
    content: "Add a QWEN.md file to give Qwen Code persistent project context.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name((ctx) => ctx.sessionCount < 10, "isRelevant"),
    cooldownPrompts: 0,
    priority: 70
  },
  {
    id: "new-user-resume",
    content: "You can resume a previous conversation by running qwen --continue or qwen --resume.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name((ctx) => ctx.sessionCount < 10, "isRelevant"),
    cooldownPrompts: 0,
    priority: 70
  },
  {
    id: "shell-commands",
    content: "You can run any shell commands from Qwen Code using ! (e.g. !ls).",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name((ctx) => ctx.sessionCount < 15, "isRelevant"),
    cooldownPrompts: 0,
    priority: 70
  },
  {
    id: "compress-startup",
    content: "Use /compress when the conversation gets long to summarize history and free up context.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name(() => true, "isRelevant"),
    cooldownPrompts: 0,
    priority: 50
  },
  {
    id: "approval-mode-win32",
    content: "You can switch permission mode quickly with Tab or /approval-mode.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name((ctx) => ctx.platform === "win32", "isRelevant"),
    cooldownPrompts: 0,
    priority: 50
  },
  {
    id: "approval-mode",
    content: "You can switch permission mode quickly with Shift+Tab or /approval-mode.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name((ctx) => ctx.platform !== "win32", "isRelevant"),
    cooldownPrompts: 0,
    priority: 50
  },
  {
    id: "insight-command",
    content: "Try /insight to generate personalized insights from your chat history.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name((ctx) => ctx.sessionCount > 20, "isRelevant"),
    cooldownPrompts: 0,
    priority: 70
  },
  {
    id: "btw-command",
    content: "Use /btw to ask a quick side question without disrupting the conversation.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name(() => true, "isRelevant"),
    cooldownPrompts: 0,
    priority: 50
  },
  {
    id: "clear-new",
    content: "Start a fresh idea with /clear or /new; the previous session stays available in history.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name(() => true, "isRelevant"),
    cooldownPrompts: 0,
    priority: 50
  },
  {
    id: "bug-report",
    content: "Use /bug to submit issues to the maintainers when something goes off.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name(() => true, "isRelevant"),
    cooldownPrompts: 0,
    priority: 50
  },
  {
    id: "auth-switch",
    content: "Switch auth type quickly with /auth.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name(() => true, "isRelevant"),
    cooldownPrompts: 0,
    priority: 50
  },
  {
    id: "compact-mode",
    content: "Press Ctrl+O to toggle compact mode \u2014 hide tool output and thinking for a cleaner view.",
    trigger: "startup",
    isRelevant: /* @__PURE__ */ __name(() => true, "isRelevant"),
    cooldownPrompts: 0,
    priority: 50
  }
];

// packages/cli/src/services/tips/index.ts
var _tipHistory = null;
function getTipHistory() {
  if (!_tipHistory) {
    _tipHistory = TipHistory.load();
  }
  return _tipHistory;
}
__name(getTipHistory, "getTipHistory");

// packages/cli/src/ui/components/Tips.tsx
var import_jsx_runtime68 = __toESM(require_jsx_runtime(), 1);
function pickStartupTip() {
  const history = getTipHistory();
  const context2 = {
    lastPromptTokenCount: 0,
    contextWindowSize: 0,
    sessionPromptCount: 0,
    sessionCount: history.sessionCount,
    platform: process.platform
  };
  const tip = selectTip("startup", context2, tipRegistry, history);
  if (tip) {
    history.recordShown(tip.id, 0);
    return tip.content;
  }
  return "Type / to see all available commands.";
}
__name(pickStartupTip, "pickStartupTip");
var Tips = /* @__PURE__ */ __name(() => {
  const selectedTip = (0, import_react77.useMemo)(() => pickStartupTip(), []);
  return /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Box_default, { marginLeft: 2, marginRight: 2, children: /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(Text3, { color: theme.text.secondary, children: [
    t4("Tips: "),
    t4(selectedTip)
  ] }) });
}, "Tips");

// packages/cli/src/ui/components/AppHeader.tsx
var import_jsx_runtime69 = __toESM(require_jsx_runtime(), 1);
function getAuthDisplayType(authType, baseUrl, apiKeyEnvKey) {
  if (!authType) {
    return "Unknown" /* UNKNOWN */;
  }
  if (isCodingPlanConfig(baseUrl, apiKeyEnvKey)) {
    return "Coding Plan" /* CODING_PLAN */;
  }
  switch (authType) {
    case AuthType2.QWEN_OAUTH:
      return "Qwen OAuth" /* QWEN_OAUTH */;
    default:
      return "API Key" /* API_KEY */;
  }
}
__name(getAuthDisplayType, "getAuthDisplayType");
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());
  const authDisplayType = getAuthDisplayType(
    authType,
    contentGeneratorConfig?.baseUrl,
    contentGeneratorConfig?.apiKeyEnvKey
  );
  return /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { flexDirection: "column", children: [
    showBanner && /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
      Header2,
      {
        version: version2,
        authDisplayType,
        model,
        workingDirectory: targetDir
      }
    ),
    showTips && /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Tips, {})
  ] });
}, "AppHeader");

// packages/cli/src/ui/components/DebugModeNotification.tsx
init_esbuild_shims();
init_dist4();
var import_jsx_runtime70 = __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_runtime70.jsxs)(Box_default, { paddingX: 1, marginTop: 1, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text3, { color: theme.status.warning, children: "Debug mode enabled" }),
    /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Text3, { dimColor: true, children: [
      "Logging to: ",
      logPath
    ] }),
    isDegraded && /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text3, { dimColor: true, children: "Warning: Debug logging is degraded (write failures occurred)" })
  ] });
}, "DebugModeNotification");

// packages/cli/src/ui/utils/mergeCompactToolGroups.ts
init_esbuild_shims();
init_types22();
function isAgentWithPendingConfirmation2(rd) {
  return typeof rd === "object" && rd !== null && rd.type === "task_execution" && rd.pendingConfirmation !== void 0;
}
__name(isAgentWithPendingConfirmation2, "isAgentWithPendingConfirmation");
function isForceExpandGroup(item, embeddedShellFocused, activeShellPtyId) {
  if (item.type !== "tool_group") {
    return false;
  }
  if (item.isUserInitiated) {
    return true;
  }
  const tools = item.tools;
  if (tools.some((t5) => t5.status === "Confirming" /* Confirming */)) {
    return true;
  }
  if (tools.some((t5) => t5.status === "Error" /* Error */)) {
    return true;
  }
  if (tools.some((t5) => isAgentWithPendingConfirmation2(t5.resultDisplay))) {
    return true;
  }
  if (embeddedShellFocused && activeShellPtyId !== void 0 && tools.some(
    (t5) => t5.ptyId === activeShellPtyId && t5.status === "Executing" /* Executing */
  )) {
    return true;
  }
  return false;
}
__name(isForceExpandGroup, "isForceExpandGroup");
function isHiddenInCompactMode(item) {
  return item.type === "gemini_thought" || item.type === "gemini_thought_content" || item.type === "tool_use_summary";
}
__name(isHiddenInCompactMode, "isHiddenInCompactMode");
function mergeCompactToolGroups(items, embeddedShellFocused = false, activeShellPtyId = void 0, absorbedCallIds = /* @__PURE__ */ new Set()) {
  const result = [];
  let i4 = 0;
  while (i4 < items.length) {
    const item = items[i4];
    if (item.type === "tool_use_summary") {
      const allAbsorbed = item.precedingToolUseIds.length > 0 && item.precedingToolUseIds.every((id) => absorbedCallIds.has(id));
      if (allAbsorbed) {
        i4++;
        continue;
      }
      result.push(item);
      i4++;
      continue;
    }
    if (item.type !== "tool_group" || isForceExpandGroup(item, embeddedShellFocused, activeShellPtyId)) {
      result.push(item);
      i4++;
      continue;
    }
    const mergeableGroups = [item];
    let lastMergedIdx = i4;
    let j2 = i4 + 1;
    while (j2 < items.length) {
      const next = items[j2];
      if (isHiddenInCompactMode(next)) {
        j2++;
        continue;
      }
      if (next.type === "tool_group" && !isForceExpandGroup(next, embeddedShellFocused, activeShellPtyId)) {
        mergeableGroups.push(next);
        lastMergedIdx = j2;
        j2++;
        continue;
      }
      break;
    }
    if (mergeableGroups.length === 1) {
      result.push(item);
      i4++;
      continue;
    }
    const mergedTools = mergeableGroups.flatMap(
      (g2) => g2.type === "tool_group" ? g2.tools : []
    );
    const mergedGroup = {
      type: "tool_group",
      tools: mergedTools,
      id: mergeableGroups[0].id
    };
    result.push(mergedGroup);
    i4 = lastMergedIdx + 1;
  }
  return result;
}
__name(mergeCompactToolGroups, "mergeCompactToolGroups");

// packages/cli/src/ui/components/MainContent.tsx
var import_jsx_runtime71 = __toESM(require_jsx_runtime(), 1);
var MAX_GEMINI_MESSAGE_LINES = 65536;
var MainContent = /* @__PURE__ */ __name(() => {
  const { version: version2 } = useAppContext();
  const uiState = useUIState();
  const uiActions = useUIActions();
  const { compactMode } = useCompactMode();
  const {
    pendingHistoryItems,
    terminalWidth,
    mainAreaWidth,
    staticAreaMaxItemHeight,
    availableTerminalHeight,
    historyRemountKey
  } = uiState;
  const absorbedCallIds = (0, import_react78.useMemo)(() => {
    const absorbed = /* @__PURE__ */ new Set();
    if (!compactMode) return absorbed;
    for (const item of uiState.history) {
      if (item.type !== "tool_group") continue;
      if (isForceExpandGroup(
        item,
        uiState.embeddedShellFocused ?? false,
        uiState.activePtyId
      )) {
        continue;
      }
      for (const tool of item.tools) absorbed.add(tool.callId);
    }
    return absorbed;
  }, [
    compactMode,
    uiState.history,
    uiState.embeddedShellFocused,
    uiState.activePtyId
  ]);
  const mergedHistory = (0, import_react78.useMemo)(
    () => compactMode ? mergeCompactToolGroups(
      uiState.history,
      uiState.embeddedShellFocused,
      uiState.activePtyId,
      absorbedCallIds
    ) : uiState.history,
    [
      compactMode,
      uiState.history,
      uiState.embeddedShellFocused,
      uiState.activePtyId,
      absorbedCallIds
    ]
  );
  const summaryByCallId = (0, import_react78.useMemo)(() => {
    const map3 = /* @__PURE__ */ new Map();
    for (const item of uiState.history) {
      if (item.type === "tool_use_summary") {
        for (const callId of item.precedingToolUseIds) {
          if (!map3.has(callId)) {
            map3.set(callId, item.summary);
          }
        }
      }
    }
    return map3;
  }, [uiState.history]);
  const isSummaryAbsorbed = (0, import_react78.useCallback)(
    (item) => {
      if (item.type !== "tool_use_summary") return false;
      return item.precedingToolUseIds.some((id) => absorbedCallIds.has(id));
    },
    [absorbedCallIds]
  );
  const getCompactLabel = (0, import_react78.useCallback)(
    (item) => {
      if (item.type !== "tool_group" || item.tools.length === 0)
        return void 0;
      return summaryByCallId.get(item.tools[0].callId);
    },
    [summaryByCallId]
  );
  const prevHistoryLengthRef = (0, import_react78.useRef)(uiState.history.length);
  const prevMergedLengthRef = (0, import_react78.useRef)(mergedHistory.length);
  (0, import_react78.useEffect)(() => {
    if (!compactMode) {
      prevHistoryLengthRef.current = uiState.history.length;
      prevMergedLengthRef.current = mergedHistory.length;
      return;
    }
    const prevHLen = prevHistoryLengthRef.current;
    const currHLen = uiState.history.length;
    const prevMLen = prevMergedLengthRef.current;
    const currMLen = mergedHistory.length;
    if (currHLen > prevHLen && currMLen <= prevMLen) {
      uiActions.refreshStatic();
    }
    prevHistoryLengthRef.current = currHLen;
    prevMergedLengthRef.current = currMLen;
  }, [compactMode, uiState.history, mergedHistory, uiActions]);
  return /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(import_jsx_runtime71.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
      Static,
      {
        items: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(AppHeader, { version: version2 }, "app-header"),
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(DebugModeNotification, {}, "debug-notification"),
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Notifications, {}, "notifications"),
          ...mergedHistory.map((h3) => /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
            HistoryItemDisplayComponent,
            {
              terminalWidth,
              mainAreaWidth,
              availableTerminalHeight: staticAreaMaxItemHeight,
              availableTerminalHeightGemini: MAX_GEMINI_MESSAGE_LINES,
              item: h3,
              isPending: false,
              commands: uiState.slashCommands,
              compactLabel: getCompactLabel(h3),
              summaryAbsorbed: isSummaryAbsorbed(h3)
            },
            h3.id
          ))
        ],
        children: (item) => item
      },
      historyRemountKey
    ),
    /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(OverflowProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { flexDirection: "column", children: [
      pendingHistoryItems.map((item, i4) => /* @__PURE__ */ (0, import_jsx_runtime71.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,
          compactLabel: getCompactLabel(item),
          summaryAbsorbed: isSummaryAbsorbed(item)
        },
        i4
      )),
      /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(ShowMoreLines, { constrainHeight: uiState.constrainHeight })
    ] }) })
  ] });
}, "MainContent");

// packages/cli/src/ui/components/DialogManager.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/LoopDetectionConfirmation.tsx
init_esbuild_shims();
var import_jsx_runtime72 = __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_runtime72.jsx)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      width: "100%",
      marginLeft: 1,
      children: /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Box_default, { paddingX: 1, paddingY: 0, flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Box_default, { minHeight: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Box_default, { minWidth: 3, children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text3, { color: theme.status.warning, "aria-label": "Loop detected:", children: "?" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Text3, { wrap: "truncate-end", children: [
            /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text3, { color: theme.text.primary, bold: true, children: "A potential loop was detected" }),
            " "
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Box_default, { width: "100%", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime72.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_runtime72.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete }) }),
          /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime72.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/ShellConfirmationDialog.tsx
init_esbuild_shims();
init_dist4();
init_i18n();
var import_jsx_runtime73 = __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("Always allow in this project"),
      value: ToolConfirmationOutcome.ProceedAlwaysProject,
      key: "Always allow in this project"
    },
    {
      label: t4("Always allow for this user"),
      value: ToolConfirmationOutcome.ProceedAlwaysUser,
      key: "Always allow for this user"
    },
    {
      label: t4("No (esc)"),
      value: ToolConfirmationOutcome.Cancel,
      key: "No (esc)"
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Shell Command Execution") }),
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Text3, { color: theme.text.primary, children: t4("A custom command wants to run the following shell commands:") }),
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
            Box_default,
            {
              flexDirection: "column",
              borderStyle: "round",
              borderColor: theme.border.default,
              paddingX: 1,
              marginTop: 1,
              children: commands.map((cmd) => /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Text3, { color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(RenderInline, { text: cmd }) }, cmd))
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(Text3, { color: theme.text.primary, children: t4("Do you want to proceed?") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(RadioButtonSelect, { items: options2, onSelect: handleSelect, isFocused: true })
      ]
    }
  );
}, "ShellConfirmationDialog");

// packages/cli/src/ui/components/ConsentPrompt.tsx
init_esbuild_shims();
var import_react79 = __toESM(require_react(), 1);
var import_jsx_runtime74 = __toESM(require_jsx_runtime(), 1);
var ConsentPrompt = /* @__PURE__ */ __name((props) => {
  const { prompt, onConfirm, terminalWidth } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      children: [
        typeof prompt === "string" ? /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
          MarkdownDisplay,
          {
            isPending: true,
            text: prompt,
            contentWidth: terminalWidth
          }
        ) : prompt,
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.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_react80 = __toESM(require_react(), 1);
init_i18n();
var import_chalk7 = __toESM(require_source(), 1);
var import_jsx_runtime75 = __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_runtime75.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text3, { color: theme.text.accent, children: "> " }),
    value.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Text3, { children: [
      cursorChar,
      /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text3, { dimColor: true, children: placeholder.slice(1) })
    ] }) : /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Text3, { children: [
      displayValue,
      cursorChar
    ] })
  ] });
}, "PasswordInput");
var SettingInputPrompt = /* @__PURE__ */ __name((props) => {
  const {
    settingName,
    settingDescription,
    sensitive,
    onSubmit,
    onCancel,
    terminalWidth
  } = props;
  const [value, setValue2] = (0, import_react80.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_runtime75.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text3, { bold: true, color: theme.text.accent, children: settingName }),
        /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Text3, { children: settingDescription }) }),
        /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: sensitive ? /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
          PasswordInput,
          {
            value,
            onChange: setValue2,
            onSubmit: handleSubmit,
            placeholder: t4("Enter sensitive value...")
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
          TextInput,
          {
            value,
            onChange: setValue2,
            onSubmit: handleSubmit,
            placeholder: t4("Enter value..."),
            inputWidth: Math.min(terminalWidth - 10, 60),
            isActive: true
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime75.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_react81 = __toESM(require_react(), 1);
init_i18n();
var import_jsx_runtime76 = __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_react81.useState)(0);
  const prefixWidth = 2;
  const handleKeypress = (0, import_react81.useCallback)(
    (key) => {
      const { name: name4, sequence } = key;
      if (name4 === "escape") {
        onCancel();
        return;
      }
      if (name4 === "return") {
        const plugin4 = plugins[selectedIndex];
        if (plugin4) {
          onSelect(plugin4.name);
        }
        return;
      }
      if (name4 === "up" || sequence === "k") {
        setSelectedIndex((prev) => prev > 0 ? prev - 1 : plugins.length - 1);
        return;
      }
      if (name4 === "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 plugin4 = plugins[num - 1];
        if (plugin4) {
          onSelect(plugin4.name);
        }
      }
    },
    [plugins, selectedIndex, onSelect, onCancel]
  );
  useKeypress(handleKeypress, { isActive: true });
  const { visiblePlugins, startIndex, hasMore, hasLess } = (0, import_react81.useMemo)(() => {
    const total = plugins.length;
    if (total <= MAX_VISIBLE_ITEMS) {
      return {
        visiblePlugins: plugins,
        startIndex: 0,
        hasMore: false,
        hasLess: false
      };
    }
    let start2 = 0;
    const halfWindow = Math.floor(MAX_VISIBLE_ITEMS / 2);
    if (selectedIndex <= halfWindow) {
      start2 = 0;
    } else if (selectedIndex >= total - halfWindow) {
      start2 = total - MAX_VISIBLE_ITEMS;
    } else {
      start2 = selectedIndex - halfWindow;
    }
    const end = Math.min(start2 + MAX_VISIBLE_ITEMS, total);
    return {
      visiblePlugins: plugins.slice(start2, end),
      startIndex: start2,
      hasLess: start2 > 0,
      hasMore: end < total
    };
  }, [plugins, selectedIndex]);
  return /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4('Select a plugin from "{{name}}"', { name: marketplaceName }) }),
        /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          hasLess && /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Text3, { dimColor: true, children: [
            " ",
            "\u2191 ",
            t4("{{count}} more above", { count: String(startIndex) })
          ] }) }),
          visiblePlugins.map((plugin4, visibleIndex) => {
            const actualIndex = startIndex + visibleIndex;
            const isSelected = actualIndex === selectedIndex;
            const prefix = isSelected ? "\u276F " : "  ";
            return /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Box_default, { flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Box_default, { flexDirection: "row", children: [
                /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Text3, { color: isSelected ? theme.text.accent : void 0, children: prefix }),
                /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
                  Text3,
                  {
                    bold: isSelected,
                    color: isSelected ? theme.text.accent : void 0,
                    children: plugin4.name
                  }
                )
              ] }),
              isSelected && plugin4.description && /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Box_default, { marginLeft: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Text3, { color: theme.text.accent, children: plugin4.description }) })
            ] }, plugin4.name);
          }),
          hasMore && /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Text3, { dimColor: true, children: [
            " ",
            "\u2193",
            " ",
            t4("{{count}} more below", {
              count: String(plugins.length - startIndex - MAX_VISIBLE_ITEMS)
            })
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Box_default, { marginTop: 1, flexDirection: "row", gap: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime76.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_runtime76.jsxs)(Text3, { dimColor: true, children: [
            "(",
            selectedIndex + 1,
            "/",
            plugins.length,
            ")"
          ] })
        ] })
      ]
    }
  );
}, "PluginChoicePrompt");

// packages/cli/src/ui/components/ThemeDialog.tsx
init_esbuild_shims();
var import_react82 = __toESM(require_react(), 1);

// packages/cli/src/utils/dialogScopeUtils.ts
init_esbuild_shims();
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();
init_i18n();
var import_jsx_runtime77 = __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_runtime77.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Text3, { bold: isFocused, wrap: "truncate", children: [
      isFocused ? "> " : "  ",
      t4("Apply To")
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { height: 1 }),
    /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(
      RadioButtonSelect,
      {
        items: scopeItems,
        initialIndex: safeInitialIndex,
        onSelect,
        onHighlight,
        isFocused,
        showNumbers: isFocused
      }
    )
  ] });
}
__name(ScopeSelector, "ScopeSelector");

// packages/cli/src/ui/components/ThemeDialog.tsx
init_i18n();
var import_jsx_runtime78 = __toESM(require_jsx_runtime(), 1);
function ThemeDialog({
  onSelect,
  onHighlight,
  settings,
  availableTerminalHeight,
  terminalWidth
}) {
  const [selectedScope, setSelectedScope] = (0, import_react82.useState)(
    "User" /* User */
  );
  const [highlightedThemeName, setHighlightedThemeName] = (0, import_react82.useState)(settings.merged.ui?.theme || AUTO_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 = [
    {
      label: t4("Auto (detect terminal theme)"),
      value: AUTO_THEME_NAME,
      themeNameDisplay: t4("Auto"),
      themeTypeDisplay: t4("Auto"),
      key: AUTO_THEME_NAME
    },
    ...builtInThemes.map((theme2) => ({
      label: theme2.name,
      value: theme2.name,
      themeNameDisplay: theme2.name,
      themeTypeDisplay: capitalize(theme2.type),
      key: theme2.name
    })),
    ...customThemeNames.map((name4) => ({
      label: name4,
      value: name4,
      themeNameDisplay: name4,
      themeTypeDisplay: "Custom",
      key: name4
    }))
  ];
  const initialThemeIndex = themeItems.findIndex(
    (item) => item.value === highlightedThemeName
  );
  const safeInitialThemeIndex = initialThemeIndex >= 0 ? initialThemeIndex : 0;
  const handleThemeSelect = (0, import_react82.useCallback)(
    (themeName) => {
      onSelect(themeName, selectedScope);
    },
    [onSelect, selectedScope]
  );
  const handleThemeHighlight = /* @__PURE__ */ __name((themeName) => {
    setHighlightedThemeName(themeName);
    onHighlight(themeName);
  }, "handleThemeHighlight");
  const handleScopeHighlight = (0, import_react82.useCallback)((scope) => {
    setSelectedScope(scope);
  }, []);
  const handleScopeSelect = (0, import_react82.useCallback)(
    (scope) => {
      onSelect(highlightedThemeName, scope);
    },
    [onSelect, highlightedThemeName]
  );
  const [mode, setMode] = (0, import_react82.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_runtime78.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_runtime78.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Box_default, { flexDirection: "column", width: "45%", paddingRight: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Text3, { bold: mode === "theme", wrap: "truncate", children: [
              mode === "theme" ? "> " : "  ",
              t4("Select Theme"),
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text3, { color: theme.text.secondary, children: otherScopeModifiedMessage })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(
              RadioButtonSelect,
              {
                items: themeItems,
                initialIndex: safeInitialThemeIndex,
                onSelect: handleThemeSelect,
                onHighlight: handleThemeHighlight,
                isFocused: mode === "theme",
                maxItemsToShow: 12,
                showScrollArrows: true,
                showNumbers: mode === "theme"
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Box_default, { flexDirection: "column", width: "55%", paddingLeft: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Preview") }),
            (() => {
              const previewTheme = highlightedThemeName === AUTO_THEME_NAME ? themeManager.getActiveTheme() : themeManager.getTheme(
                highlightedThemeName || DEFAULT_THEME.name
              ) || DEFAULT_THEME;
              return /* @__PURE__ */ (0, import_jsx_runtime78.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_runtime78.jsx)(Box_default, { marginTop: 1 }),
                    /* @__PURE__ */ (0, import_jsx_runtime78.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_runtime78.jsx)(
          ScopeSelector,
          {
            onSelect: handleScopeSelect,
            onHighlight: handleScopeHighlight,
            isFocused: mode === "scope",
            initialScope: selectedScope
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime78.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_react84 = __toESM(require_react(), 1);
init_i18n();

// packages/cli/src/ui/contexts/VimModeContext.tsx
init_esbuild_shims();
var import_react83 = __toESM(require_react(), 1);
var import_jsx_runtime79 = __toESM(require_jsx_runtime(), 1);
var VimModeContext = (0, import_react83.createContext)(void 0);
var VimModeProvider = /* @__PURE__ */ __name(({
  children,
  settings
}) => {
  const initialVimEnabled = settings.merged.general?.vimMode ?? false;
  const [vimEnabled, setVimEnabled] = (0, import_react83.useState)(initialVimEnabled);
  const [vimMode, setVimMode] = (0, import_react83.useState)(
    initialVimEnabled ? "NORMAL" : "INSERT"
  );
  (0, import_react83.useEffect)(() => {
    const enabled2 = settings.merged.general?.vimMode ?? false;
    setVimEnabled(enabled2);
    if (enabled2) {
      setVimMode("NORMAL");
    }
  }, [settings.merged.general?.vimMode]);
  const toggleVimEnabled = (0, import_react83.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_runtime79.jsx)(VimModeContext.Provider, { value, children });
}, "VimModeProvider");
var useVimMode = /* @__PURE__ */ __name(() => {
  const context2 = (0, import_react83.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
init_dist4();
var import_chalk8 = __toESM(require_source(), 1);
var import_jsx_runtime80 = __toESM(require_jsx_runtime(), 1);
var debugLogger143 = createDebugLogger("SETTINGS_DIALOG");
var maxItemsToShow = 8;
function SettingsDialog({
  settings,
  onSelect,
  onRestartRequest,
  availableTerminalHeight,
  config: config2
}) {
  const { vimEnabled, toggleVimEnabled } = useVimMode();
  const { compactMode, setCompactMode } = useCompactMode();
  const uiActions = useUIActions();
  const [mode, setMode] = (0, import_react84.useState)("settings");
  const [selectedScope, setSelectedScope] = (0, import_react84.useState)(
    "User" /* User */
  );
  const [activeSettingIndex, setActiveSettingIndex] = (0, import_react84.useState)(0);
  const [scrollOffset, setScrollOffset] = (0, import_react84.useState)(0);
  const [pendingSettings, setPendingSettings] = (0, import_react84.useState)(
    () => (
      // Deep clone to avoid mutation
      structuredClone(settings.forScope(selectedScope).settings)
    )
  );
  const [modifiedSettings, setModifiedSettings] = (0, import_react84.useState)(
    /* @__PURE__ */ new Set()
  );
  const [globalPendingChanges, setGlobalPendingChanges] = (0, import_react84.useState)(/* @__PURE__ */ new Map());
  const [restartRequiredSettings, setRestartRequiredSettings] = (0, import_react84.useState)(/* @__PURE__ */ new Set());
  const showRestartPrompt = restartRequiredSettings.size > 0;
  (0, import_react84.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,
        description: definition?.description ? t4(definition.description) || definition.description : void 0,
        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,
              {}
            );
            debugLogger143.debug(
              `[DEBUG SettingsDialog] Saving ${key} immediately with value:`,
              newValue
            );
            saveModifiedSettings(
              immediateSettings,
              immediateSettingsObject,
              settings,
              selectedScope
            );
            if (key === "general.vimMode" && newValue !== vimEnabled) {
              toggleVimEnabled().catch((error40) => {
                debugLogger143.error("Failed to toggle vim mode:", error40);
              });
            }
            if (key === "ui.compactMode" && newValue !== compactMode) {
              setCompactMode?.(newValue);
              uiActions.refreshStatic();
            }
            if (key === "tools.approvalMode" && settings.merged.tools?.approvalMode) {
              try {
                config2?.setApprovalMode(settings.merged.tools.approvalMode);
              } catch (error40) {
                debugLogger143.error(
                  "Failed to apply approval mode to current session:",
                  error40
                );
              }
            }
            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_react84.useState)(null);
  const [editBuffer, setEditBuffer] = (0, import_react84.useState)("");
  const [editCursorPos, setEditCursorPos] = (0, import_react84.useState)(0);
  const [cursorVisible, setCursorVisible] = (0, import_react84.useState)(true);
  (0, import_react84.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 activeDescription = mode === "settings" && items[activeSettingIndex]?.description ? items[activeSettingIndex].description : void 0;
  const DIALOG_PADDING = 2;
  const SETTINGS_TITLE_HEIGHT = 2;
  const SCROLL_ARROWS_HEIGHT = 2;
  const DESCRIPTION_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 + DESCRIPTION_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: name4, ctrl } = key;
      if (name4 === "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 (name4 === "backspace" || name4 === "delete") {
            if (name4 === "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 (name4 === "delete" && editCursorPos < cpLen(editBuffer)) {
              setEditBuffer((b2) => {
                const before = cpSlice(b2, 0, editCursorPos);
                const after = cpSlice(b2, editCursorPos + 1);
                return before + after;
              });
            }
            return;
          }
          if (name4 === "escape") {
            commitEdit(editingKey);
            return;
          }
          if (name4 === "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 (name4 === "left") {
            setEditCursorPos((pos2) => Math.max(0, pos2 - 1));
            return;
          }
          if (name4 === "right") {
            setEditCursorPos((pos2) => Math.min(cpLen(editBuffer), pos2 + 1));
            return;
          }
          if (name4 === "home") {
            setEditCursorPos(0);
            return;
          }
          if (name4 === "end") {
            setEditCursorPos(cpLen(editBuffer));
            return;
          }
          return;
        }
        if (name4 === "up" || name4 === "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 (name4 === "down" || name4 === "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 (name4 === "return" || name4 === "space") {
          const currentItem = items[activeSettingIndex];
          if (currentItem?.value === "ui.theme") {
            if (name4 === "return") {
              onSelect("ui.theme", selectedScope);
            }
            return;
          }
          if (currentItem?.value === "general.preferredEditor") {
            if (name4 === "return") {
              onSelect("general.preferredEditor", selectedScope);
            }
            return;
          }
          if (currentItem?.value === "fastModel") {
            if (name4 === "return") {
              onSelect("fastModel", selectedScope);
            }
            return;
          }
          if (currentItem?.type === "number" || currentItem?.type === "string") {
            startEditing(currentItem.value);
          } else {
            currentItem?.toggle();
          }
        } else if (name4 === "right") {
          const currentItem = items[activeSettingIndex];
          if (currentItem?.value === "ui.theme" || currentItem?.value === "general.preferredEditor" || currentItem?.value === "fastModel") {
            onSelect(currentItem.value, selectedScope);
          }
        } else if (/^[0-9]$/.test(key.sequence || "") && !editingKey) {
          const currentItem = items[activeSettingIndex];
          if (currentItem?.type === "number") {
            startEditing(currentItem.value, key.sequence);
          }
        } else if (ctrl && (name4 === "c" || name4 === "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 (error40) {
                  debugLogger143.error(
                    "Failed to apply approval mode to current session:",
                    error40
                  );
                }
              }
              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 && name4 === "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 (name4 === "escape") {
        if (editingKey) {
          commitEdit(editingKey);
        } else {
          onSelect(void 0, selectedScope);
        }
      }
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        mode === "settings" ? /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(Box_default, { flexDirection: "column", flexGrow: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(Text3, { bold: mode === "settings", wrap: "truncate", children: [
            mode === "settings" ? "> " : "  ",
            t4("Settings")
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { height: 1 }),
          showScrollUp && /* @__PURE__ */ (0, import_jsx_runtime80.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 isSubDialogSetting = item.value === "ui.theme" || item.value === "general.preferredEditor" || item.value === "fastModel";
              const path150 = item.value.split(".");
              const currentValue = getNestedValue(pendingSettings, path150);
              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 += "*";
              }
              if (isSubDialogSetting) {
                displayValue = displayValue ? displayValue + " \u25B8" : "\u25B8";
              }
            } 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_runtime80.jsxs)(Box_default, { flexDirection: "row", alignItems: "center", children: [
              /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
                Text3,
                {
                  color: isActive ? theme.status.success : theme.text.secondary,
                  children: isActive ? "\u25CF" : ""
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { flexGrow: 1, flexShrink: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(
                Text3,
                {
                  color: isActive ? theme.status.success : theme.text.primary,
                  wrap: "truncate",
                  children: [
                    item.label,
                    scopeMessage && /* @__PURE__ */ (0, import_jsx_runtime80.jsxs)(Text3, { color: theme.text.secondary, children: [
                      " ",
                      scopeMessage
                    ] })
                  ]
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginLeft: 1, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime80.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_runtime80.jsx)(Text3, { color: theme.text.secondary, children: "\u25BC" })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
          ScopeSelector,
          {
            onSelect: handleScopeSelect,
            onHighlight: handleScopeHighlight,
            isFocused: mode === "scope",
            initialScope: selectedScope
          }
        ),
        activeDescription && mode === "settings" && /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text3, { color: theme.text.secondary, wrap: "truncate-end", italic: true, children: activeDescription }) }),
        /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Box_default, { marginTop: activeDescription && mode === "settings" ? 0 : 1, children: /* @__PURE__ */ (0, import_jsx_runtime80.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_runtime80.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_react85 = __toESM(require_react(), 1);
init_i18n();
var import_jsx_runtime81 = __toESM(require_jsx_runtime(), 1);
function formatTime(seconds) {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
}
__name(formatTime, "formatTime");
function QwenOAuthProgress({
  onTimeout,
  onCancel,
  deviceAuth,
  authStatus,
  authMessage
}) {
  const defaultTimeout = deviceAuth?.expires_in || 300;
  const [timeRemaining, setTimeRemaining] = (0, import_react85.useState)(defaultTimeout);
  const [dots, setDots] = (0, import_react85.useState)("...");
  useKeypress(
    (key) => {
      if (authStatus === "timeout" || authStatus === "error") {
        onCancel();
      } else if (key.name === "escape" || key.ctrl && key.name === "c") {
        onCancel();
      }
    },
    { isActive: true }
  );
  (0, import_react85.useEffect)(() => {
    const timer = setInterval(() => {
      setTimeRemaining((prev) => {
        if (prev <= 1) {
          onTimeout();
          return 0;
        }
        return prev - 1;
      });
    }, 1e3);
    return () => clearInterval(timer);
  }, [onTimeout]);
  (0, import_react85.useEffect)(() => {
    const dotFrames = [".  ", ".. ", "..."];
    let frameIndex = 0;
    const dotsTimer = setInterval(() => {
      frameIndex = (frameIndex + 1) % dotFrames.length;
      setDots(dotFrames[frameIndex]);
    }, 500);
    return () => clearInterval(dotsTimer);
  }, []);
  if (authStatus === "timeout") {
    return /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(
      Box_default,
      {
        borderStyle: "single",
        borderColor: theme.border.default,
        flexDirection: "column",
        padding: 1,
        width: "100%",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { bold: true, color: theme.status.error, children: t4("Qwen OAuth Authentication Timeout") }),
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { children: authMessage || t4(
            "OAuth token expired (over {{seconds}} seconds). Please select authentication method again.",
            {
              seconds: defaultTimeout.toString()
            }
          ) }) }),
          /* @__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 any key to return to authentication type selection.") }) })
        ]
      }
    );
  }
  if (authStatus === "error") {
    return /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(
      Box_default,
      {
        borderStyle: "single",
        borderColor: theme.border.default,
        flexDirection: "column",
        padding: 1,
        width: "100%",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { bold: true, color: theme.status.error, children: t4("Qwen OAuth Authentication Error") }),
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { children: authMessage || t4("An error occurred during authentication. Please try again.") }) }),
          /* @__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 any key to return to authentication type selection.") }) })
        ]
      }
    );
  }
  if (!deviceAuth) {
    return /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(
      Box_default,
      {
        borderStyle: "single",
        borderColor: theme.border.default,
        flexDirection: "column",
        padding: 1,
        width: "100%",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { bold: true, children: t4("Qwen OAuth Authentication") }),
          /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { children: t4("Waiting for Qwen OAuth authentication...") }),
            /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(Text3, { children: [
              t4("Time remaining:"),
              " ",
              formatTime(timeRemaining)
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { color: theme.text.secondary, children: t4("Esc to cancel") }) })
        ]
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(
    Box_default,
    {
      borderStyle: "single",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { bold: true, children: t4("Qwen OAuth Authentication") }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { children: t4("Please visit this URL to authorize:") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(dist_default5, { url: deviceAuth.verification_uri_complete || "", fallback: false, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { color: theme.text.link, bold: true, children: deviceAuth.verification_uri_complete }) }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(Text3, { children: [
            t4("Waiting for authorization"),
            dots
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(Text3, { children: [
            t4("Time remaining:"),
            " ",
            formatTime(timeRemaining)
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text3, { color: theme.text.secondary, children: t4("Esc to cancel") }) })
      ]
    }
  );
}
__name(QwenOAuthProgress, "QwenOAuthProgress");

// packages/cli/src/ui/components/ExternalAuthProgress.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime82 = __toESM(require_jsx_runtime(), 1);
function ExternalAuthProgress({
  title,
  message,
  detail,
  onCancel
}) {
  useKeypress(
    (key) => {
      if (key.name === "escape" || key.ctrl && key.name === "c") {
        onCancel?.();
      }
    },
    { isActive: Boolean(onCancel) }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(
    Box_default,
    {
      borderStyle: "single",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { bold: true, children: title }),
        /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { children: message }),
          detail ? /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme.text.secondary, children: detail }) : null
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme.text.secondary, children: t4("Please wait while authentication completes...") }),
          onCancel ? /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text3, { color: theme.text.secondary, children: t4("Esc to cancel") }) : null
        ] })
      ]
    }
  );
}
__name(ExternalAuthProgress, "ExternalAuthProgress");

// packages/cli/src/ui/auth/AuthDialog.tsx
init_esbuild_shims();
var import_react89 = __toESM(require_react(), 1);
init_dist4();

// packages/cli/src/ui/components/shared/DescriptiveRadioButtonSelect.tsx
init_esbuild_shims();
var import_jsx_runtime83 = __toESM(require_jsx_runtime(), 1);
function DescriptiveRadioButtonSelect({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showNumbers = false,
  showScrollArrows = false,
  maxItemsToShow: maxItemsToShow2 = 10,
  itemGap = 0
}) {
  return /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(
    BaseSelectionList,
    {
      items,
      initialIndex,
      onSelect,
      onHighlight,
      isFocused,
      showNumbers,
      showScrollArrows,
      maxItemsToShow: maxItemsToShow2,
      itemGap,
      renderItem: (item, { titleColor }) => /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text3, { color: titleColor, children: item.title }),
        typeof item.description === "string" ? /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text3, { color: theme.text.secondary, children: item.description }) : item.description
      ] }, item.key)
    }
  );
}
__name(DescriptiveRadioButtonSelect, "DescriptiveRadioButtonSelect");

// packages/cli/src/ui/components/ApiKeyInput.tsx
init_esbuild_shims();
var import_react86 = __toESM(require_react(), 1);
init_i18n();
init_dist4();
var import_jsx_runtime84 = __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 = CodingPlanRegion.CHINA
}) {
  const [apiKey, setApiKey] = (0, import_react86.useState)("");
  const [error40, setError] = (0, import_react86.useState)(null);
  const apiKeyUrl = region === CodingPlanRegion.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;
        }
        if (region === CodingPlanRegion.CHINA && !trimmedKey.startsWith("sk-sp-")) {
          setError(
            t4(
              'Invalid API key. Coding Plan API keys start with "sk-sp-". Please check.'
            )
          );
          return;
        }
        onSubmit(trimmedKey);
      }
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(TextInput, { value: apiKey, onChange: setApiKey, placeholder: "sk-sp-..." }),
    error40 && /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text3, { color: theme.status.error, children: error40 }) }),
    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text3, { children: t4("You can get your Coding Plan API key here") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { marginTop: 0, children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(dist_default5, { url: apiKeyUrl, fallback: false, children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text3, { color: theme.text.link, underline: true, children: apiKeyUrl }) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to submit, Esc to go back") }) })
  ] });
}
__name(ApiKeyInput, "ApiKeyInput");

// packages/cli/src/ui/auth/AuthDialog.tsx
init_i18n();

// packages/cli/src/ui/auth/useAuth.ts
init_esbuild_shims();
init_dist4();
var import_react88 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useQwenAuth.ts
init_esbuild_shims();
var import_react87 = __toESM(require_react(), 1);
init_dist4();
var useQwenAuth = /* @__PURE__ */ __name((pendingAuthType, isAuthenticating) => {
  const [qwenAuthState, setQwenAuthState] = (0, import_react87.useState)({
    deviceAuth: null,
    authStatus: "idle",
    authMessage: null
  });
  const isQwenAuth = pendingAuthType === AuthType2.QWEN_OAUTH;
  (0, import_react87.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_react87.useCallback)(() => {
    qwenOAuth2Events.emit(QwenOAuth2Event.AuthCancel);
    setQwenAuthState({
      deviceAuth: null,
      authStatus: "idle",
      authMessage: null
    });
  }, []);
  return {
    qwenAuthState,
    cancelQwenAuth
  };
}, "useQwenAuth");

// packages/cli/src/ui/auth/useAuth.ts
init_types22();
init_i18n();
function generateCustomApiKeyEnvKey(protocol, baseUrl) {
  const normalize13 = /* @__PURE__ */ __name((value) => value.trim().toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, ""), "normalize");
  return `QWEN_CUSTOM_API_KEY_${normalize13(protocol)}_${normalize13(baseUrl)}`;
}
__name(generateCustomApiKeyEnvKey, "generateCustomApiKeyEnvKey");
function normalizeCustomModelIds(modelIdsInput) {
  return modelIdsInput.split(",").map((id) => id.trim()).filter((id, index, array2) => id.length > 0 && array2.indexOf(id) === index);
}
__name(normalizeCustomModelIds, "normalizeCustomModelIds");
function maskApiKey(apiKey) {
  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}...${tail}`;
}
__name(maskApiKey, "maskApiKey");
var useAuthCommand = /* @__PURE__ */ __name((settings, config2, addItem, onAuthChange) => {
  const unAuthenticated = config2.getAuthType() === void 0;
  const [authState, setAuthState] = (0, import_react88.useState)(
    unAuthenticated ? "updating" /* Updating */ : "unauthenticated" /* Unauthenticated */
  );
  const [authError, setAuthError] = (0, import_react88.useState)(null);
  const [isAuthenticating, setIsAuthenticating] = (0, import_react88.useState)(false);
  const [isAuthDialogOpen, setIsAuthDialogOpen] = (0, import_react88.useState)(unAuthenticated);
  const [pendingAuthType, setPendingAuthType] = (0, import_react88.useState)(
    void 0
  );
  const [externalAuthState, setExternalAuthState] = (0, import_react88.useState)(null);
  const [openRouterAuthAbortController, setOpenRouterAuthAbortController] = (0, import_react88.useState)(null);
  const { qwenAuthState, cancelQwenAuth } = useQwenAuth(
    pendingAuthType,
    isAuthenticating
  );
  const onAuthError = (0, import_react88.useCallback)(
    (error40) => {
      setAuthError(error40);
      if (error40) {
        setAuthState("updating" /* Updating */);
        setIsAuthDialogOpen(true);
      }
    },
    [setAuthError, setAuthState]
  );
  const handleAuthFailure = (0, import_react88.useCallback)(
    (error40) => {
      setIsAuthenticating(false);
      setExternalAuthState(null);
      const errorMessage = t4("Failed to authenticate. Message: {{message}}", {
        message: getErrorMessage(error40)
      });
      onAuthError(errorMessage);
      if (pendingAuthType) {
        const authEvent = new AuthEvent(
          pendingAuthType,
          "manual",
          "error",
          errorMessage
        );
        logAuth(config2, authEvent);
      }
    },
    [onAuthError, pendingAuthType, config2]
  );
  const handleAuthSuccess = (0, import_react88.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 (error40) {
        handleAuthFailure(error40);
        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_react88.useCallback)(
    async (authType, credentials) => {
      try {
        await config2.refreshAuth(authType);
        handleAuthSuccess(authType, credentials);
      } catch (e4) {
        handleAuthFailure(e4);
      }
    },
    [config2, handleAuthSuccess, handleAuthFailure]
  );
  const isProviderManagedModel = (0, import_react88.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_react88.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_react88.useCallback)(() => {
    setIsAuthDialogOpen(true);
  }, []);
  const cancelAuthentication = (0, import_react88.useCallback)(() => {
    if (isAuthenticating && pendingAuthType === AuthType2.QWEN_OAUTH) {
      cancelQwenAuth();
    }
    if (isAuthenticating && pendingAuthType === AuthType2.USE_OPENAI) {
      openRouterAuthAbortController?.abort();
      setOpenRouterAuthAbortController(null);
    }
    if (isAuthenticating && pendingAuthType) {
      const authEvent = new AuthEvent(pendingAuthType, "manual", "cancelled");
      logAuth(config2, authEvent);
    }
    setIsAuthenticating(false);
    setExternalAuthState(null);
    setIsAuthDialogOpen(true);
    setAuthError(null);
  }, [
    isAuthenticating,
    pendingAuthType,
    cancelQwenAuth,
    config2,
    openRouterAuthAbortController
  ]);
  const handleCodingPlanSubmit = (0, import_react88.useCallback)(
    async (apiKey, region = CodingPlanRegion.CHINA) => {
      try {
        setIsAuthenticating(true);
        setAuthError(null);
        const { template, version: version2 } = 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.",
              { region: t4("Alibaba Cloud Coding Plan") }
            )
          },
          Date.now()
        );
        addItem(
          {
            type: "info" /* INFO */,
            text: t4(
              "Tip: Use /model to switch between available Coding Plan models."
            )
          },
          Date.now()
        );
        const authEvent = new AuthEvent(
          AuthType2.USE_OPENAI,
          "coding-plan",
          "success"
        );
        logAuth(config2, authEvent);
      } catch (error40) {
        handleAuthFailure(error40);
      }
    },
    [settings, config2, handleAuthFailure, addItem, onAuthChange]
  );
  const handleAlibabaStandardSubmit = (0, import_react88.useCallback)(
    async (apiKey, region, modelIdsInput) => {
      try {
        setIsAuthenticating(true);
        setAuthError(null);
        const trimmedApiKey = apiKey.trim();
        const modelIds = modelIdsInput.split(",").map((id) => id.trim()).filter(
          (id, index, array2) => id.length > 0 && array2.indexOf(id) === index
        );
        if (!trimmedApiKey) {
          throw new Error(t4("API key cannot be empty."));
        }
        if (modelIds.length === 0) {
          throw new Error(t4("Model IDs cannot be empty."));
        }
        const baseUrl = ALIBABA_STANDARD_API_KEY_ENDPOINTS[region];
        const persistScope = getPersistScopeForModelSelection(settings);
        const settingsFile = settings.forScope(persistScope);
        backupSettingsFile(settingsFile.path);
        settings.setValue(
          persistScope,
          `env.${DASHSCOPE_STANDARD_API_KEY_ENV_KEY}`,
          trimmedApiKey
        );
        process.env[DASHSCOPE_STANDARD_API_KEY_ENV_KEY] = trimmedApiKey;
        const newConfigs = modelIds.map((modelId) => ({
          id: modelId,
          name: `[ModelStudio Standard] ${modelId}`,
          baseUrl,
          envKey: DASHSCOPE_STANDARD_API_KEY_ENV_KEY
        }));
        const existingConfigs = settings.merged.modelProviders?.[AuthType2.USE_OPENAI] || [];
        const nonAlibabaStandardConfigs = existingConfigs.filter(
          (existing) => !(existing.envKey === DASHSCOPE_STANDARD_API_KEY_ENV_KEY && typeof existing.baseUrl === "string" && Object.values(ALIBABA_STANDARD_API_KEY_ENDPOINTS).includes(
            existing.baseUrl
          ))
        );
        const updatedConfigs = [...newConfigs, ...nonAlibabaStandardConfigs];
        settings.setValue(
          persistScope,
          `modelProviders.${AuthType2.USE_OPENAI}`,
          updatedConfigs
        );
        settings.setValue(
          persistScope,
          "security.auth.selectedType",
          AuthType2.USE_OPENAI
        );
        settings.setValue(persistScope, "model.name", modelIds[0]);
        const updatedModelProviders = {
          ...settings.merged.modelProviders,
          [AuthType2.USE_OPENAI]: updatedConfigs
        };
        config2.reloadModelProvidersConfig(updatedModelProviders);
        await config2.refreshAuth(AuthType2.USE_OPENAI);
        setAuthError(null);
        setAuthState("authenticated" /* Authenticated */);
        setPendingAuthType(void 0);
        setIsAuthDialogOpen(false);
        setIsAuthenticating(false);
        onAuthChange?.();
        addItem(
          {
            type: "info" /* INFO */,
            text: t4(
              "Alibaba Cloud ModelStudio Standard API Key successfully entered. Settings updated with env.DASHSCOPE_API_KEY and {{modelCount}} model(s).",
              { modelCount: String(modelIds.length) }
            )
          },
          Date.now()
        );
        addItem(
          {
            type: "info" /* INFO */,
            text: t4(
              "You can use /model to see new ModelStudio Standard models and switch between them."
            )
          },
          Date.now()
        );
        const authEvent = new AuthEvent(
          AuthType2.USE_OPENAI,
          "manual",
          "success"
        );
        logAuth(config2, authEvent);
      } catch (error40) {
        handleAuthFailure(error40);
      }
    },
    [settings, config2, handleAuthFailure, addItem, onAuthChange]
  );
  const handleOpenRouterSubmit = (0, import_react88.useCallback)(async () => {
    try {
      setPendingAuthType(AuthType2.USE_OPENAI);
      setIsAuthenticating(true);
      setAuthError(null);
      setIsAuthDialogOpen(false);
      const oauthSession = createOpenRouterOAuthSession(
        OPENROUTER_OAUTH_CALLBACK_URL
      );
      setExternalAuthState({
        title: t4("OpenRouter Authentication"),
        message: t4(
          "Open the authorization page if your browser does not launch automatically."
        ),
        detail: oauthSession.authorizationUrl
      });
      const abortController = new AbortController();
      setOpenRouterAuthAbortController(abortController);
      const oauthResult = await runOpenRouterOAuthLogin(
        OPENROUTER_OAUTH_CALLBACK_URL,
        {
          abortSignal: abortController.signal,
          session: oauthSession
        }
      );
      setOpenRouterAuthAbortController(null);
      setExternalAuthState({
        title: t4("OpenRouter Authentication"),
        message: t4("Finalizing OpenRouter setup..."),
        detail: t4(
          "Syncing OpenRouter models and updating your local configuration."
        )
      });
      const selectedKey = oauthResult.apiKey;
      if (!selectedKey) {
        throw new Error(
          t4("OpenRouter authentication completed without an API key.")
        );
      }
      const persistScope = getPersistScopeForModelSelection(settings);
      const settingsFile = settings.forScope(persistScope);
      backupSettingsFile(settingsFile.path);
      await applyOpenRouterModelsConfiguration({
        settings,
        config: config2,
        apiKey: selectedKey,
        reloadConfig: true
      });
      await config2.refreshAuth(AuthType2.USE_OPENAI);
      setAuthError(null);
      setExternalAuthState(null);
      setAuthState("authenticated" /* Authenticated */);
      setPendingAuthType(void 0);
      setIsAuthDialogOpen(false);
      setIsAuthenticating(false);
      onAuthChange?.();
      addItem(
        {
          type: "info" /* INFO */,
          text: t4("Successfully configured OpenRouter.")
        },
        Date.now()
      );
      addItem(
        {
          type: "info" /* INFO */,
          text: t4("Use /model to switch models.")
        },
        Date.now()
      );
      addItem(
        {
          type: "info" /* INFO */,
          text: t4(
            "Want more OpenRouter models? Use /manage-models to browse and enable them."
          )
        },
        Date.now()
      );
      const authEvent = new AuthEvent(AuthType2.USE_OPENAI, "manual", "success");
      logAuth(config2, authEvent);
    } catch (error40) {
      setOpenRouterAuthAbortController(null);
      if (error40 instanceof DOMException && error40.name === "AbortError") {
        setExternalAuthState(null);
        setPendingAuthType(void 0);
        setIsAuthenticating(false);
        setIsAuthDialogOpen(true);
        return;
      }
      handleAuthFailure(error40);
    }
  }, [
    settings,
    config2,
    handleAuthFailure,
    addItem,
    onAuthChange,
    setOpenRouterAuthAbortController
  ]);
  const handleCustomApiKeySubmit = (0, import_react88.useCallback)(
    async (protocol, baseUrl, apiKey, modelIdsInput, generationConfig) => {
      try {
        setIsAuthenticating(true);
        setAuthError(null);
        const trimmedApiKey = apiKey.trim();
        const trimmedBaseUrl = baseUrl.trim();
        const modelIds = normalizeCustomModelIds(modelIdsInput);
        if (!trimmedApiKey) {
          throw new Error(t4("API key cannot be empty."));
        }
        if (!trimmedBaseUrl) {
          throw new Error(t4("Base URL cannot be empty."));
        }
        if (!/^https?:\/\//i.test(trimmedBaseUrl)) {
          throw new Error(t4("Base URL must start with http:// or https://."));
        }
        if (modelIds.length === 0) {
          throw new Error(t4("Model IDs cannot be empty."));
        }
        const generatedEnvKey = generateCustomApiKeyEnvKey(
          protocol,
          trimmedBaseUrl
        );
        const persistScope = getPersistScopeForModelSelection(settings);
        const settingsFile = settings.forScope(persistScope);
        backupSettingsFile(settingsFile.path);
        settings.setValue(
          persistScope,
          `env.${generatedEnvKey}`,
          trimmedApiKey
        );
        process.env[generatedEnvKey] = trimmedApiKey;
        let genConfig;
        if (generationConfig) {
          const hasThinking = generationConfig.enableThinking === true;
          const hasMultimodal = generationConfig.multimodal && (generationConfig.multimodal.image === true || generationConfig.multimodal.video === true || generationConfig.multimodal.audio === true);
          const hasMaxTokens = generationConfig.maxTokens !== void 0 && generationConfig.maxTokens > 0;
          if (hasThinking || hasMultimodal || hasMaxTokens) {
            genConfig = {};
            if (hasMultimodal) {
              genConfig.modalities = {
                image: generationConfig.multimodal.image ?? false,
                video: generationConfig.multimodal.video ?? false,
                audio: generationConfig.multimodal.audio ?? false
              };
            }
            if (hasThinking) {
              genConfig.extra_body = { enable_thinking: true };
            }
            if (hasMaxTokens) {
              genConfig.samplingParams = {
                max_tokens: generationConfig.maxTokens
              };
            }
          }
        }
        const newConfigs = modelIds.map((modelId) => ({
          id: modelId,
          name: modelId,
          baseUrl: trimmedBaseUrl,
          envKey: generatedEnvKey,
          ...genConfig ? { generationConfig: genConfig } : {}
        }));
        const existingConfigs = settings.merged.modelProviders?.[protocol] || [];
        const preservedConfigs = existingConfigs.filter(
          (existing) => existing.envKey !== generatedEnvKey
        );
        const updatedConfigs = [...newConfigs, ...preservedConfigs];
        settings.setValue(
          persistScope,
          `modelProviders.${protocol}`,
          updatedConfigs
        );
        settings.setValue(persistScope, "security.auth.selectedType", protocol);
        settings.setValue(persistScope, "model.name", modelIds[0]);
        const updatedModelProviders = {
          ...settings.merged.modelProviders,
          [protocol]: updatedConfigs
        };
        config2.reloadModelProvidersConfig(updatedModelProviders);
        await config2.refreshAuth(protocol);
        setAuthError(null);
        setAuthState("authenticated" /* Authenticated */);
        setPendingAuthType(void 0);
        setIsAuthDialogOpen(false);
        setIsAuthenticating(false);
        onAuthChange?.();
        addItem(
          {
            type: "info" /* INFO */,
            text: t4(
              "Custom API Key authenticated successfully. Settings updated with generated env key and model provider config."
            )
          },
          Date.now()
        );
        addItem(
          {
            type: "info" /* INFO */,
            text: t4("Tip: Use /model to switch between configured models.")
          },
          Date.now()
        );
        const authEvent = new AuthEvent(protocol, "manual", "success");
        logAuth(config2, authEvent);
      } catch (error40) {
        handleAuthFailure(error40);
      }
    },
    [settings, config2, handleAuthFailure, addItem, onAuthChange]
  );
  (0, import_react88.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,
    externalAuthState,
    qwenAuthState,
    handleAuthSelect,
    handleCodingPlanSubmit,
    handleAlibabaStandardSubmit,
    handleOpenRouterSubmit,
    handleCustomApiKeySubmit,
    openAuthDialog,
    cancelAuthentication
  };
}, "useAuthCommand");

// packages/cli/src/ui/auth/AuthDialog.tsx
var import_jsx_runtime85 = __toESM(require_jsx_runtime(), 1);
var MODEL_PROVIDERS_DOCUMENTATION_URL = "https://qwenlm.github.io/qwen-code-docs/en/users/configuration/model-providers/";
function parseDefaultAuthType(defaultAuthType) {
  if (defaultAuthType && Object.values(AuthType2).includes(defaultAuthType)) {
    return defaultAuthType;
  }
  return null;
}
__name(parseDefaultAuthType, "parseDefaultAuthType");
var ALIBABA_STANDARD_MODEL_IDS_PLACEHOLDER = "qwen3.5-plus,glm-5,kimi-k2.5";
var ALIBABA_STANDARD_API_DOCUMENTATION_URLS = {
  "cn-beijing": "https://bailian.console.aliyun.com/cn-beijing?tab=api#/api",
  "sg-singapore": "https://modelstudio.console.alibabacloud.com/ap-southeast-1?tab=api#/api/?type=model&url=2712195",
  "us-virginia": "https://modelstudio.console.alibabacloud.com/us-east-1?tab=api#/api/?type=model&url=2712195",
  "cn-hongkong": "https://modelstudio.console.alibabacloud.com/cn-hongkong?tab=api#/api/?type=model&url=2712195"
};
function AuthDialog() {
  const { pendingAuthType, authError } = useUIState();
  const {
    handleAuthSelect: onAuthSelect,
    handleCodingPlanSubmit,
    handleAlibabaStandardSubmit,
    handleOpenRouterSubmit,
    handleCustomApiKeySubmit,
    onAuthError
  } = useUIActions();
  const config2 = useConfig();
  const [errorMessage, setErrorMessage] = (0, import_react89.useState)(null);
  const [viewLevel, setViewLevel] = (0, import_react89.useState)("main");
  const [regionIndex, setRegionIndex] = (0, import_react89.useState)(0);
  const [region, setRegion] = (0, import_react89.useState)(
    CodingPlanRegion.CHINA
  );
  const [alibabaStandardRegionIndex, setAlibabaStandardRegionIndex] = (0, import_react89.useState)(0);
  const [apiKeyTypeIndex, setApiKeyTypeIndex] = (0, import_react89.useState)(0);
  const [oauthProviderIndex, setOAuthProviderIndex] = (0, import_react89.useState)(0);
  const [alibabaStandardRegion, setAlibabaStandardRegion] = (0, import_react89.useState)("cn-beijing");
  const [alibabaStandardApiKey, setAlibabaStandardApiKey] = (0, import_react89.useState)("");
  const [alibabaStandardApiKeyError, setAlibabaStandardApiKeyError] = (0, import_react89.useState)(null);
  const [alibabaStandardModelId, setAlibabaStandardModelId] = (0, import_react89.useState)("");
  const [alibabaStandardModelIdError, setAlibabaStandardModelIdError] = (0, import_react89.useState)(null);
  const [customProtocolIndex, setCustomProtocolIndex] = (0, import_react89.useState)(0);
  const [customProtocol, setCustomProtocol] = (0, import_react89.useState)(
    AuthType2.USE_OPENAI
  );
  const [customBaseUrl, setCustomBaseUrl] = (0, import_react89.useState)("");
  const [customBaseUrlError, setCustomBaseUrlError] = (0, import_react89.useState)(
    null
  );
  const [customApiKey, setCustomApiKey] = (0, import_react89.useState)("");
  const [customApiKeyError, setCustomApiKeyError] = (0, import_react89.useState)(
    null
  );
  const [customModelIds, setCustomModelIds] = (0, import_react89.useState)("");
  const [customModelIdsError, setCustomModelIdsError] = (0, import_react89.useState)(
    null
  );
  const [advancedThinkingEnabled, setAdvancedThinkingEnabled] = (0, import_react89.useState)(false);
  const [advancedModalityEnabled, setAdvancedModalityEnabled] = (0, import_react89.useState)(false);
  const [focusedConfigIndex, setFocusedConfigIndex] = (0, import_react89.useState)(0);
  const mainItems = [
    {
      key: "CODING_PLAN",
      title: t4("Alibaba Cloud Coding Plan"),
      label: t4("Alibaba Cloud Coding Plan"),
      description: t4(
        "Paid \xB7 Up to 6,000 requests/5 hrs \xB7 All Alibaba Cloud Coding Plan Models"
      ),
      value: "CODING_PLAN"
    },
    {
      key: "API_KEY",
      title: t4("API Key"),
      label: t4("API Key"),
      description: t4("Bring your own API key"),
      value: "API_KEY"
    },
    {
      key: "OAUTH",
      title: t4("OAuth"),
      label: t4("OAuth"),
      description: t4(
        "Browser-based authentication with third-party providers (e.g. OpenRouter, ModelScope)"
      ),
      value: "OAUTH"
    }
  ];
  const regionItems = [
    {
      key: "china",
      title: "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)",
      label: "\u963F\u91CC\u4E91\u767E\u70BC (aliyun.com)",
      description: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
        dist_default5,
        {
          url: "https://help.aliyun.com/zh/model-studio/coding-plan",
          fallback: false,
          children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: "https://help.aliyun.com/zh/model-studio/coding-plan" })
        }
      ),
      value: CodingPlanRegion.CHINA
    },
    {
      key: "global",
      title: "Alibaba Cloud (alibabacloud.com)",
      label: "Alibaba Cloud (alibabacloud.com)",
      description: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
        dist_default5,
        {
          url: "https://www.alibabacloud.com/help/en/model-studio/coding-plan",
          fallback: false,
          children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: "https://www.alibabacloud.com/help/en/model-studio/coding-plan" })
        }
      ),
      value: CodingPlanRegion.GLOBAL
    }
  ];
  const alibabaStandardRegionItems = [
    {
      key: "cn-beijing",
      title: t4("China (Beijing)"),
      label: t4("China (Beijing)"),
      description: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text3, { color: theme.text.secondary, children: [
        "Endpoint: ",
        ALIBABA_STANDARD_API_KEY_ENDPOINTS["cn-beijing"]
      ] }),
      value: "cn-beijing"
    },
    {
      key: "sg-singapore",
      title: t4("Singapore"),
      label: t4("Singapore"),
      description: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text3, { color: theme.text.secondary, children: [
        "Endpoint: ",
        ALIBABA_STANDARD_API_KEY_ENDPOINTS["sg-singapore"]
      ] }),
      value: "sg-singapore"
    },
    {
      key: "us-virginia",
      title: t4("US (Virginia)"),
      label: t4("US (Virginia)"),
      description: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text3, { color: theme.text.secondary, children: [
        "Endpoint: ",
        ALIBABA_STANDARD_API_KEY_ENDPOINTS["us-virginia"]
      ] }),
      value: "us-virginia"
    },
    {
      key: "cn-hongkong",
      title: t4("China (Hong Kong)"),
      label: t4("China (Hong Kong)"),
      description: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text3, { color: theme.text.secondary, children: [
        "Endpoint: ",
        ALIBABA_STANDARD_API_KEY_ENDPOINTS["cn-hongkong"]
      ] }),
      value: "cn-hongkong"
    }
  ];
  const protocolItems = [
    {
      key: AuthType2.USE_OPENAI,
      title: t4("OpenAI-compatible"),
      label: t4("OpenAI-compatible"),
      description: t4(
        "OpenAI Chat Completions API (OpenRouter, vLLM, Ollama, LM Studio, Fireworks, etc.)"
      ),
      value: AuthType2.USE_OPENAI
    },
    {
      key: AuthType2.USE_ANTHROPIC,
      title: t4("Anthropic-compatible"),
      label: t4("Anthropic-compatible"),
      description: t4("Anthropic Messages API"),
      value: AuthType2.USE_ANTHROPIC
    },
    {
      key: AuthType2.USE_GEMINI,
      title: t4("Gemini-compatible"),
      label: t4("Gemini-compatible"),
      description: t4("Google Gemini API"),
      value: AuthType2.USE_GEMINI
    }
  ];
  const DEFAULT_CUSTOM_BASE_URLS = {
    [AuthType2.USE_OPENAI]: "https://api.openai.com/v1",
    [AuthType2.USE_ANTHROPIC]: "https://api.anthropic.com/v1",
    [AuthType2.USE_GEMINI]: "https://generativelanguage.googleapis.com"
  };
  const apiKeyTypeItems = [
    {
      key: "ALIBABA_STANDARD_API_KEY",
      title: t4("Alibaba Cloud ModelStudio Standard API Key"),
      label: t4("Alibaba Cloud ModelStudio Standard API Key"),
      description: t4("Quick setup for Model Studio (China/International)"),
      value: "ALIBABA_STANDARD_API_KEY"
    },
    {
      key: "CUSTOM_API_KEY",
      title: t4("Custom API Key"),
      label: t4("Custom API Key"),
      description: t4(
        "For other OpenAI / Anthropic / Gemini-compatible providers"
      ),
      value: "CUSTOM_API_KEY"
    }
  ];
  const oauthProviderItems = [
    {
      key: "OPENROUTER_OAUTH",
      title: t4("OpenRouter"),
      label: t4("OpenRouter"),
      description: t4(
        "Browser OAuth \xB7 Auto-configure API key and OpenRouter models"
      ),
      value: "OPENROUTER_OAUTH"
    },
    {
      key: "MODELSCOPE_OAUTH",
      title: t4("ModelScope"),
      label: t4("ModelScope"),
      description: t4(
        "Browser OAuth \xB7 Auto-configure API key and ModelScope models"
      ),
      value: "MODELSCOPE_OAUTH"
    },
    {
      key: "QWEN_OAUTH_DISCONTINUED",
      title: t4("Qwen"),
      label: t4("Qwen"),
      description: t4("Discontinued \u2014 switch to Coding Plan or API Key"),
      value: "QWEN_OAUTH_DISCONTINUED"
    }
  ];
  const contentGenConfig = config2.getContentGeneratorConfig();
  const isCurrentlyCodingPlan = isCodingPlanConfig(
    contentGenConfig?.baseUrl,
    contentGenConfig?.apiKeyEnvKey
  ) !== false;
  const authTypeToMainOption = /* @__PURE__ */ __name((authType) => {
    if (authType === AuthType2.QWEN_OAUTH) return "OAUTH";
    if (authType === AuthType2.USE_OPENAI && isCurrentlyCodingPlan) {
      return "CODING_PLAN";
    }
    return "API_KEY";
  }, "authTypeToMainOption");
  const initialAuthIndex = Math.max(
    0,
    mainItems.findIndex((item) => {
      if (pendingAuthType) {
        return item.value === authTypeToMainOption(pendingAuthType);
      }
      const currentAuthType = config2.getAuthType();
      if (currentAuthType) {
        return item.value === authTypeToMainOption(currentAuthType);
      }
      const defaultAuthType = parseDefaultAuthType(
        process.env["QWEN_DEFAULT_AUTH_TYPE"]
      );
      if (defaultAuthType) {
        return item.value === authTypeToMainOption(defaultAuthType);
      }
      return item.value === "OAUTH";
    })
  );
  const handleMainSelect = /* @__PURE__ */ __name(async (value) => {
    setErrorMessage(null);
    onAuthError(null);
    if (value === "CODING_PLAN") {
      setViewLevel("region-select");
      return;
    }
    if (value === "API_KEY") {
      setViewLevel("api-key-type-select");
      return;
    }
    if (value === "OAUTH") {
      setViewLevel("oauth-provider-select");
      return;
    }
    await onAuthSelect(value);
  }, "handleMainSelect");
  const handleApiKeyTypeSelect = /* @__PURE__ */ __name(async (value) => {
    setErrorMessage(null);
    onAuthError(null);
    if (value === "ALIBABA_STANDARD_API_KEY") {
      setAlibabaStandardModelIdError(null);
      setAlibabaStandardApiKeyError(null);
      setViewLevel("alibaba-standard-region-select");
      return;
    }
    setCustomProtocolIndex(0);
    setCustomProtocol(AuthType2.USE_OPENAI);
    setCustomBaseUrl("");
    setCustomBaseUrlError(null);
    setCustomApiKey("");
    setCustomApiKeyError(null);
    setCustomModelIds("");
    setCustomModelIdsError(null);
    setAdvancedThinkingEnabled(false);
    setAdvancedModalityEnabled(false);
    setFocusedConfigIndex(0);
    setViewLevel("custom-protocol-select");
  }, "handleApiKeyTypeSelect");
  const handleOAuthProviderSelect = /* @__PURE__ */ __name(async (value) => {
    setErrorMessage(null);
    onAuthError(null);
    if (value === "OPENROUTER_OAUTH") {
      await handleOpenRouterSubmit();
      return;
    }
    if (value === "QWEN_OAUTH_DISCONTINUED") {
      setErrorMessage(
        t4(
          "Qwen OAuth free tier was discontinued on 2026-04-15. Please select Coding Plan or API Key instead."
        )
      );
      return;
    }
    if (value === "MODELSCOPE_OAUTH") {
      setErrorMessage(
        t4(
          "ModelScope OAuth is not yet implemented. Please select another option."
        )
      );
      return;
    }
    await onAuthSelect(AuthType2.USE_OPENAI);
  }, "handleOAuthProviderSelect");
  const handleRegionSelect = /* @__PURE__ */ __name(async (selectedRegion) => {
    setErrorMessage(null);
    onAuthError(null);
    setRegion(selectedRegion);
    setViewLevel("api-key-input");
  }, "handleRegionSelect");
  const handleAlibabaStandardRegionSelect = /* @__PURE__ */ __name(async (selectedRegion) => {
    setErrorMessage(null);
    onAuthError(null);
    setAlibabaStandardApiKeyError(null);
    setAlibabaStandardModelIdError(null);
    setAlibabaStandardRegion(selectedRegion);
    setViewLevel("alibaba-standard-api-key-input");
  }, "handleAlibabaStandardRegionSelect");
  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 handleAlibabaStandardApiKeySubmit = /* @__PURE__ */ __name(() => {
    const trimmedKey = alibabaStandardApiKey.trim();
    if (!trimmedKey) {
      setAlibabaStandardApiKeyError(t4("API key cannot be empty."));
      return;
    }
    setAlibabaStandardApiKeyError(null);
    if (!alibabaStandardModelId.trim()) {
      setAlibabaStandardModelId(ALIBABA_STANDARD_MODEL_IDS_PLACEHOLDER);
    }
    setViewLevel("alibaba-standard-model-id-input");
  }, "handleAlibabaStandardApiKeySubmit");
  const handleAlibabaStandardModelSubmit = /* @__PURE__ */ __name(() => {
    const trimmedApiKey = alibabaStandardApiKey.trim();
    const trimmedModelIds = alibabaStandardModelId.trim();
    if (!trimmedApiKey) {
      setAlibabaStandardApiKeyError(t4("API key cannot be empty."));
      setViewLevel("alibaba-standard-api-key-input");
      return;
    }
    if (!trimmedModelIds) {
      setAlibabaStandardModelIdError(t4("Model IDs cannot be empty."));
      return;
    }
    setAlibabaStandardModelIdError(null);
    void handleAlibabaStandardSubmit(
      trimmedApiKey,
      alibabaStandardRegion,
      trimmedModelIds
    );
  }, "handleAlibabaStandardModelSubmit");
  const handleCustomProtocolSelect = /* @__PURE__ */ __name((protocol) => {
    setErrorMessage(null);
    onAuthError(null);
    setCustomProtocol(protocol);
    const defaultUrl = DEFAULT_CUSTOM_BASE_URLS[protocol] ?? "";
    setCustomBaseUrl(defaultUrl);
    setCustomBaseUrlError(null);
    setViewLevel("custom-base-url-input");
  }, "handleCustomProtocolSelect");
  const handleCustomBaseUrlSubmit = /* @__PURE__ */ __name(() => {
    const trimmedUrl = customBaseUrl.trim();
    if (!trimmedUrl) {
      setCustomBaseUrlError(t4("Base URL cannot be empty."));
      return;
    }
    if (!/^https?:\/\//i.test(trimmedUrl)) {
      setCustomBaseUrlError(t4("Base URL must start with http:// or https://."));
      return;
    }
    setCustomBaseUrlError(null);
    setCustomApiKey("");
    setCustomApiKeyError(null);
    setViewLevel("custom-api-key-input");
  }, "handleCustomBaseUrlSubmit");
  const handleCustomApiKeySubmitLocal = /* @__PURE__ */ __name(() => {
    const trimmedKey = customApiKey.trim();
    if (!trimmedKey) {
      setCustomApiKeyError(t4("API key cannot be empty."));
      return;
    }
    setCustomApiKeyError(null);
    setCustomModelIds("");
    setCustomModelIdsError(null);
    setViewLevel("custom-model-id-input");
  }, "handleCustomApiKeySubmitLocal");
  const handleCustomModelIdSubmit = /* @__PURE__ */ __name(() => {
    const normalized2 = normalizeCustomModelIds(customModelIds);
    if (normalized2.length === 0) {
      setCustomModelIdsError(t4("Model IDs cannot be empty."));
      return;
    }
    setCustomModelIdsError(null);
    setViewLevel("custom-advanced-config");
  }, "handleCustomModelIdSubmit");
  const handleAdvancedConfigSubmit = /* @__PURE__ */ __name(() => {
    setViewLevel("custom-review-json");
  }, "handleAdvancedConfigSubmit");
  const handleCustomReviewSubmit = /* @__PURE__ */ __name(() => {
    const trimmedBaseUrl = customBaseUrl.trim();
    const trimmedApiKey = customApiKey.trim();
    const trimmedModelIds = customModelIds;
    const hasThinking = advancedThinkingEnabled;
    const hasModality = advancedModalityEnabled;
    const generationConfig = hasThinking || hasModality ? {
      enableThinking: hasThinking ? true : void 0,
      multimodal: hasModality ? { image: true, video: true, audio: true } : void 0
    } : void 0;
    void handleCustomApiKeySubmit(
      customProtocol,
      trimmedBaseUrl,
      trimmedApiKey,
      trimmedModelIds,
      generationConfig
    );
  }, "handleCustomReviewSubmit");
  const handleGoBack = /* @__PURE__ */ __name(() => {
    setErrorMessage(null);
    onAuthError(null);
    if (viewLevel === "region-select") {
      setViewLevel("main");
    } else if (viewLevel === "api-key-input") {
      setViewLevel("region-select");
    } else if (viewLevel === "api-key-type-select") {
      setViewLevel("main");
    } else if (viewLevel === "custom-protocol-select") {
      setViewLevel("api-key-type-select");
    } else if (viewLevel === "custom-base-url-input") {
      setViewLevel("custom-protocol-select");
    } else if (viewLevel === "custom-api-key-input") {
      setViewLevel("custom-base-url-input");
    } else if (viewLevel === "custom-model-id-input") {
      setViewLevel("custom-api-key-input");
    } else if (viewLevel === "custom-advanced-config") {
      setViewLevel("custom-model-id-input");
    } else if (viewLevel === "custom-review-json") {
      setViewLevel("custom-advanced-config");
    } else if (viewLevel === "alibaba-standard-region-select") {
      setViewLevel("api-key-type-select");
    } else if (viewLevel === "alibaba-standard-api-key-input") {
      setViewLevel("alibaba-standard-region-select");
    } else if (viewLevel === "alibaba-standard-model-id-input") {
      setViewLevel("alibaba-standard-api-key-input");
    } else if (viewLevel === "oauth-provider-select") {
      setViewLevel("main");
    }
  }, "handleGoBack");
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        if (viewLevel === "region-select") {
          handleGoBack();
          return;
        }
        if (viewLevel === "api-key-input") {
          handleGoBack();
          return;
        }
        if (viewLevel === "custom-protocol-select" || viewLevel === "custom-base-url-input" || viewLevel === "custom-api-key-input" || viewLevel === "custom-model-id-input" || viewLevel === "custom-advanced-config" || viewLevel === "custom-review-json") {
          handleGoBack();
          return;
        }
        if (viewLevel === "api-key-type-select" || viewLevel === "alibaba-standard-region-select" || viewLevel === "alibaba-standard-api-key-input" || viewLevel === "alibaba-standard-model-id-input" || viewLevel === "oauth-provider-select") {
          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 }
  );
  useKeypress(
    (key) => {
      if (key.name === "return" && viewLevel === "custom-review-json") {
        handleCustomReviewSubmit();
      }
    },
    { isActive: true }
  );
  useKeypress(
    (key) => {
      if (viewLevel !== "custom-advanced-config") return;
      const { name: name4 } = key;
      if (name4 === "up") {
        setFocusedConfigIndex((v2) => v2 <= 0 ? 1 : v2 - 1);
        return;
      }
      if (name4 === "down") {
        setFocusedConfigIndex((v2) => v2 >= 1 ? 0 : v2 + 1);
        return;
      }
      if (name4 === "space") {
        if (focusedConfigIndex === 0) {
          setAdvancedThinkingEnabled((v2) => !v2);
        } else {
          setAdvancedModalityEnabled((v2) => !v2);
        }
        return;
      }
      if (name4 === "return") {
        handleAdvancedConfigSubmit();
        return;
      }
    },
    { isActive: true }
  );
  const renderMainView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(import_jsx_runtime85.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
    DescriptiveRadioButtonSelect,
    {
      items: mainItems,
      initialIndex: initialAuthIndex,
      onSelect: handleMainSelect,
      itemGap: 1
    }
  ) }) }), "renderMainView");
  const renderRegionSelectView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(import_jsx_runtime85.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.primary, children: t4("Choose based on where your account is registered") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      DescriptiveRadioButtonSelect,
      {
        items: regionItems,
        initialIndex: regionIndex,
        onSelect: handleRegionSelect,
        onHighlight: (value) => {
          const index = regionItems.findIndex((item) => item.value === value);
          setRegionIndex(index);
        },
        itemGap: 1
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme?.text?.secondary, children: t4("Enter to select, \u2191\u2193 to navigate, Esc to go back") }) })
  ] }), "renderRegionSelectView");
  const renderApiKeyInputView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
    ApiKeyInput,
    {
      onSubmit: handleApiKeyInputSubmit,
      onCancel: handleGoBack,
      region
    }
  ) }), "renderApiKeyInputView");
  const renderApiKeyTypeSelectView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(import_jsx_runtime85.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      DescriptiveRadioButtonSelect,
      {
        items: apiKeyTypeItems,
        initialIndex: apiKeyTypeIndex,
        onSelect: handleApiKeyTypeSelect,
        onHighlight: (value) => {
          const index = apiKeyTypeItems.findIndex(
            (item) => item.value === value
          );
          setApiKeyTypeIndex(index);
        },
        itemGap: 1
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme?.text?.secondary, children: t4("Enter to select, \u2191\u2193 to navigate, Esc to go back") }) })
  ] }), "renderApiKeyTypeSelectView");
  const renderAlibabaStandardRegionSelectView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(import_jsx_runtime85.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      DescriptiveRadioButtonSelect,
      {
        items: alibabaStandardRegionItems,
        initialIndex: alibabaStandardRegionIndex,
        onSelect: handleAlibabaStandardRegionSelect,
        onHighlight: (value) => {
          const index = alibabaStandardRegionItems.findIndex(
            (item) => item.value === value
          );
          setAlibabaStandardRegionIndex(index);
        },
        itemGap: 1
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme?.text?.secondary, children: t4("Enter to select, \u2191\u2193 to navigate, Esc to go back") }) })
  ] }), "renderAlibabaStandardRegionSelectView");
  const renderAlibabaStandardApiKeyInputView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text3, { color: theme.text.secondary, children: [
      "Endpoint: ",
      ALIBABA_STANDARD_API_KEY_ENDPOINTS[alibabaStandardRegion]
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text3, { color: theme.text.secondary, children: [
      t4("Documentation"),
      ":"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 0, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      dist_default5,
      {
        url: ALIBABA_STANDARD_API_DOCUMENTATION_URLS[alibabaStandardRegion],
        fallback: false,
        children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.link, children: ALIBABA_STANDARD_API_DOCUMENTATION_URLS[alibabaStandardRegion] })
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      TextInput,
      {
        value: alibabaStandardApiKey,
        onChange: (value) => {
          setAlibabaStandardApiKey(value);
          if (alibabaStandardApiKeyError) {
            setAlibabaStandardApiKeyError(null);
          }
        },
        onSubmit: handleAlibabaStandardApiKeySubmit,
        placeholder: "sk-..."
      }
    ) }),
    alibabaStandardApiKeyError && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.status.error, children: alibabaStandardApiKeyError }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to submit, Esc to go back") }) })
  ] }), "renderAlibabaStandardApiKeyInputView");
  const renderAlibabaStandardModelIdInputView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4(
      "You can enter multiple model IDs, separated by commas. Examples: qwen3.5-plus,glm-5,kimi-k2.5"
    ) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      TextInput,
      {
        value: alibabaStandardModelId,
        onChange: (value) => {
          setAlibabaStandardModelId(value);
          if (alibabaStandardModelIdError) {
            setAlibabaStandardModelIdError(null);
          }
        },
        onSubmit: handleAlibabaStandardModelSubmit,
        placeholder: ALIBABA_STANDARD_MODEL_IDS_PLACEHOLDER
      }
    ) }),
    alibabaStandardModelIdError && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.status.error, children: alibabaStandardModelIdError }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to submit, Esc to go back") }) })
  ] }), "renderAlibabaStandardModelIdInputView");
  const renderCustomProtocolSelectView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(import_jsx_runtime85.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      DescriptiveRadioButtonSelect,
      {
        items: protocolItems,
        initialIndex: customProtocolIndex,
        onSelect: handleCustomProtocolSelect,
        onHighlight: (value) => {
          const index = protocolItems.findIndex(
            (item) => item.value === value
          );
          setCustomProtocolIndex(index);
        },
        itemGap: 1
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to select, \u2191\u2193 to navigate, Esc to go back") }) })
  ] }), "renderCustomProtocolSelectView");
  const renderCustomBaseUrlInputView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.primary, children: t4("Enter the API endpoint for this protocol.") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      TextInput,
      {
        value: customBaseUrl,
        onChange: (value) => {
          setCustomBaseUrl(value);
          if (customBaseUrlError) {
            setCustomBaseUrlError(null);
          }
        },
        onSubmit: handleCustomBaseUrlSubmit,
        placeholder: "https://api.openai.com/v1"
      }
    ) }),
    customBaseUrlError && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.status.error, children: customBaseUrlError }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(dist_default5, { url: MODEL_PROVIDERS_DOCUMENTATION_URL, fallback: false, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.link, children: t4(
      "Need advanced generationConfig or capabilities? See documentation"
    ) }) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to submit, Esc to go back") }) })
  ] }), "renderCustomBaseUrlInputView");
  const renderCustomApiKeyInputView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.primary, children: t4("Enter the API key for this endpoint.") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      TextInput,
      {
        value: customApiKey,
        onChange: (value) => {
          setCustomApiKey(value);
          if (customApiKeyError) {
            setCustomApiKeyError(null);
          }
        },
        onSubmit: handleCustomApiKeySubmitLocal,
        placeholder: "sk-..."
      }
    ) }),
    customApiKeyError && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.status.error, children: customApiKeyError }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to submit, Esc to go back") }) })
  ] }), "renderCustomApiKeyInputView");
  const renderCustomModelIdInputView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.primary, children: t4("Enter one or more model IDs, separated by commas.") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      TextInput,
      {
        value: customModelIds,
        onChange: (value) => {
          setCustomModelIds(value);
          if (customModelIdsError) {
            setCustomModelIdsError(null);
          }
        },
        onSubmit: handleCustomModelIdSubmit,
        placeholder: "qwen/qwen3-coder,openai/gpt-4.1"
      }
    ) }),
    customModelIdsError && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.status.error, children: customModelIdsError }) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to submit, Esc to go back") }) })
  ] }), "renderCustomModelIdInputView");
  const renderCustomAdvancedConfigView = /* @__PURE__ */ __name(() => {
    const checkmark = /* @__PURE__ */ __name((v2) => v2 ? "\u25C9" : "\u25CB", "checkmark");
    const cursor = /* @__PURE__ */ __name((index) => focusedConfigIndex === index ? "\u203A" : " ", "cursor");
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.primary, children: t4("Optional: configure advanced generation settings.") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(
        Text3,
        {
          color: focusedConfigIndex === 0 ? theme.status.success : void 0,
          children: [
            cursor(0),
            " ",
            checkmark(advancedThinkingEnabled),
            " ",
            t4("Enable thinking")
          ]
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 0, marginLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4(
        "Allows the model to perform extended reasoning before responding."
      ) }) }),
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(
        Text3,
        {
          color: focusedConfigIndex === 1 ? theme.status.success : void 0,
          children: [
            cursor(1),
            " ",
            checkmark(advancedModalityEnabled),
            " ",
            t4("Enable modality")
          ]
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 0, marginLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4("Enables image, video, and audio input/output capabilities.") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4(
        "\u2191\u2193 to navigate, Space to toggle, Enter to continue, Esc to go back"
      ) }) })
    ] });
  }, "renderCustomAdvancedConfigView");
  const renderCustomReviewJsonView = /* @__PURE__ */ __name(() => {
    const generatedEnvKey = generateCustomApiKeyEnvKey(
      customProtocol,
      customBaseUrl.trim()
    );
    const normalizedIds = normalizeCustomModelIds(customModelIds);
    const maskedKey = maskApiKey(customApiKey);
    const hasThinking = advancedThinkingEnabled;
    const hasModality = advancedModalityEnabled;
    const hasGenConfig = hasThinking || hasModality;
    let genConfig;
    if (hasGenConfig) {
      genConfig = {};
      if (hasModality) {
        genConfig["modalities"] = {
          image: true,
          video: true,
          audio: true
        };
      }
      if (hasThinking) {
        genConfig["extra_body"] = {
          enable_thinking: true
        };
      }
    }
    const modelEntries = normalizedIds.map((id) => {
      const entry = {
        id,
        name: id,
        baseUrl: customBaseUrl.trim(),
        envKey: generatedEnvKey
      };
      if (genConfig) {
        entry["generationConfig"] = genConfig;
      }
      return entry;
    });
    const preview = {
      env: { [generatedEnvKey]: maskedKey },
      modelProviders: {
        [customProtocol]: modelEntries
      },
      security: {
        auth: {
          selectedType: customProtocol
        }
      },
      model: {
        name: normalizedIds[0]
      }
    };
    const jsonPreview = JSON.stringify(preview, null, 2);
    return /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.primary, children: t4("The following JSON will be saved to settings.json:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { children: jsonPreview }) }),
      /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to save, Esc to go back") }) })
    ] });
  }, "renderCustomReviewJsonView");
  const renderOAuthProviderSelectView = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(import_jsx_runtime85.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
      DescriptiveRadioButtonSelect,
      {
        items: oauthProviderItems,
        initialIndex: oauthProviderIndex,
        onSelect: handleOAuthProviderSelect,
        onHighlight: (value) => {
          const index = oauthProviderItems.findIndex(
            (item) => item.value === value
          );
          setOAuthProviderIndex(index);
        },
        itemGap: 1
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme?.text?.secondary, children: t4("Enter to select, \u2191\u2193 to navigate, Esc to go back") }) })
  ] }), "renderOAuthProviderSelectView");
  const getViewTitle = /* @__PURE__ */ __name(() => {
    switch (viewLevel) {
      case "main":
        return t4("Select Authentication Method");
      case "region-select":
        return t4("Select Region for Coding Plan");
      case "api-key-input":
        return t4("Enter Coding Plan API Key");
      case "api-key-type-select":
        return t4("Select API Key Type");
      case "custom-protocol-select":
        return t4("Step 1/6 \xB7 Protocol");
      case "custom-base-url-input":
        return t4("Step 2/6 \xB7 Base URL");
      case "custom-api-key-input":
        return t4("Step 3/6 \xB7 API Key");
      case "custom-model-id-input":
        return t4("Step 4/6 \xB7 Model IDs");
      case "custom-advanced-config":
        return t4("Step 5/6 \xB7 Advanced Config");
      case "custom-review-json":
        return t4("Step 6/6 \xB7 Review");
      case "alibaba-standard-region-select":
        return t4(
          "Select Region for Alibaba Cloud ModelStudio Standard API Key"
        );
      case "alibaba-standard-api-key-input":
        return t4("Enter Alibaba Cloud ModelStudio Standard API Key");
      case "alibaba-standard-model-id-input":
        return t4("Enter Model IDs");
      case "oauth-provider-select":
        return t4("Select OAuth Provider");
      default:
        return t4("Select Authentication Method");
    }
  }, "getViewTitle");
  return /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(
    Box_default,
    {
      borderStyle: "single",
      borderColor: theme?.border?.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { bold: true, children: getViewTitle() }),
        viewLevel === "main" && renderMainView(),
        viewLevel === "region-select" && renderRegionSelectView(),
        viewLevel === "api-key-input" && renderApiKeyInputView(),
        viewLevel === "api-key-type-select" && renderApiKeyTypeSelectView(),
        viewLevel === "alibaba-standard-region-select" && renderAlibabaStandardRegionSelectView(),
        viewLevel === "alibaba-standard-api-key-input" && renderAlibabaStandardApiKeyInputView(),
        viewLevel === "alibaba-standard-model-id-input" && renderAlibabaStandardModelIdInputView(),
        viewLevel === "custom-protocol-select" && renderCustomProtocolSelectView(),
        viewLevel === "custom-base-url-input" && renderCustomBaseUrlInputView(),
        viewLevel === "custom-api-key-input" && renderCustomApiKeyInputView(),
        viewLevel === "custom-model-id-input" && renderCustomModelIdInputView(),
        viewLevel === "custom-advanced-config" && renderCustomAdvancedConfigView(),
        viewLevel === "custom-review-json" && renderCustomReviewJsonView(),
        viewLevel === "oauth-provider-select" && renderOAuthProviderSelectView(),
        (authError || errorMessage) && /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.status.error, children: authError || errorMessage }) }),
        viewLevel === "main" && /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(import_jsx_runtime85.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginY: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(80) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text3, { color: theme.text.primary, children: [
            t4("Terms of Services and Privacy Notice"),
            ":"
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
            dist_default5,
            {
              url: "https://qwenlm.github.io/qwen-code-docs/en/users/support/tos-privacy/",
              fallback: false,
              children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text3, { color: theme.text.secondary, underline: true, 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_react90 = __toESM(require_react(), 1);

// packages/cli/src/ui/editors/editorSettingsManager.ts
init_esbuild_shims();
init_dist4();
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
init_dist4();
init_i18n();
var import_jsx_runtime86 = __toESM(require_jsx_runtime(), 1);
var debugLogger144 = createDebugLogger("EDITOR_SETTINGS_DIALOG");
function EditorSettingsDialog({
  onSelect,
  settings,
  onExit
}) {
  const [selectedScope, setSelectedScope] = (0, import_react90.useState)(
    "User" /* User */
  );
  const [mode, setMode] = (0, import_react90.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) {
    debugLogger144.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_runtime86.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "row",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { flexDirection: "column", width: "45%", paddingRight: 2, children: [
          mode === "editor" ? /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Text3, { bold: mode === "editor", wrap: "truncate", children: [
              mode === "editor" ? "> " : "  ",
              t4("Select Editor"),
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { color: theme.text.secondary, children: otherScopeModifiedMessage })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { height: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime86.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_runtime86.jsx)(
            ScopeSelector,
            {
              onSelect: handleScopeSelect,
              onHighlight: handleScopeHighlight,
              isFocused: mode === "scope",
              initialScope: selectedScope
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime86.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_runtime86.jsxs)(Box_default, { flexDirection: "column", width: "55%", paddingLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Editor Preference") }),
          /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { flexDirection: "column", gap: 1, marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime86.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_runtime86.jsxs)(Text3, { color: theme.text.secondary, children: [
              t4("Your preferred editor is:"),
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(
                Text3,
                {
                  color: mergedEditorName === "None" ? theme.status.error : theme.text.link,
                  bold: true,
                  children: mergedEditorName
                }
              ),
              "."
            ] })
          ] })
        ] })
      ]
    }
  );
}
__name(EditorSettingsDialog, "EditorSettingsDialog");

// packages/cli/src/ui/components/TrustDialog.tsx
init_esbuild_shims();

// packages/cli/src/ui/hooks/useTrustModify.ts
init_esbuild_shims();
var import_react91 = __toESM(require_react(), 1);
import * as process35 from "node:process";
init_types22();
function getInitialTrustState(settings, cwd6) {
  const folders = loadTrustedFolders();
  const explicitTrustLevel = folders.user.config[cwd6];
  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 useTrustModify = /* @__PURE__ */ __name((onExit, addItem) => {
  const settings = useSettings();
  const cwd6 = process35.cwd();
  const [initialState2] = (0, import_react91.useState)(() => getInitialTrustState(settings, cwd6));
  const [currentTrustLevel] = (0, import_react91.useState)(
    initialState2.currentTrustLevel
  );
  const [pendingTrustLevel, setPendingTrustLevel] = (0, import_react91.useState)();
  const [isInheritedTrustFromParent] = (0, import_react91.useState)(
    initialState2.isInheritedTrustFromParent
  );
  const [isInheritedTrustFromIde] = (0, import_react91.useState)(
    initialState2.isInheritedTrustFromIde
  );
  const [needsRestart, setNeedsRestart] = (0, import_react91.useState)(false);
  const isFolderTrustEnabled2 = !!settings.merged.security?.folderTrust?.enabled;
  const updateTrustLevel = (0, import_react91.useCallback)(
    (trustLevel) => {
      const wasTrusted = isWorkspaceTrusted(settings.merged).isTrusted;
      const currentConfig = loadTrustedFolders().user.config;
      const newConfig = { ...currentConfig, [cwd6]: 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(cwd6, trustLevel);
        onExit();
      }
    },
    [cwd6, settings.merged, onExit, addItem]
  );
  const commitTrustLevelChange = (0, import_react91.useCallback)(() => {
    if (pendingTrustLevel) {
      const folders = loadTrustedFolders();
      folders.setValue(cwd6, pendingTrustLevel);
    }
  }, [cwd6, pendingTrustLevel]);
  return {
    cwd: cwd6,
    currentTrustLevel,
    isInheritedTrustFromParent,
    isInheritedTrustFromIde,
    needsRestart,
    updateTrustLevel,
    commitTrustLevelChange,
    isFolderTrustEnabled: isFolderTrustEnabled2
  };
}, "useTrustModify");

// packages/cli/src/ui/components/TrustDialog.tsx
var import_jsx_runtime87 = __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 TrustDialog({
  onExit,
  addItem
}) {
  const {
    cwd: cwd6,
    currentTrustLevel,
    isInheritedTrustFromParent,
    isInheritedTrustFromIde,
    needsRestart,
    updateTrustLevel,
    commitTrustLevelChange
  } = useTrustModify(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_runtime87.jsxs)(import_jsx_runtime87.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        flexDirection: "column",
        padding: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Box_default, { flexDirection: "column", paddingBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Text3, { bold: true, children: [
              "> ",
              "Modify Trust Level"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Box_default, { marginTop: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Text3, { children: [
              "Folder: ",
              cwd6
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Text3, { children: [
              "Current Level: ",
              /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text3, { bold: true, children: currentTrustLevel || "Not Set" })
            ] }),
            isInheritedTrustFromParent && /* @__PURE__ */ (0, import_jsx_runtime87.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_runtime87.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_runtime87.jsx)(
            RadioButtonSelect,
            {
              items: TRUST_LEVEL_ITEMS,
              onSelect: updateTrustLevel,
              isFocused: true,
              initialIndex
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text3, { color: theme.text.secondary, children: "(Use Enter to select)" }) })
        ]
      }
    ),
    needsRestart && /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Box_default, { marginLeft: 1, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text3, { color: theme.status.warning, children: "To apply the trust changes, Qwen Code must be restarted. Press 'r' to restart CLI now." }) })
  ] });
}
__name(TrustDialog, "TrustDialog");

// packages/cli/src/ui/components/PermissionsDialog.tsx
init_esbuild_shims();
var import_react92 = __toESM(require_react(), 1);
import * as fs125 from "node:fs";
import * as os46 from "node:os";
import * as nodePath3 from "node:path";
init_i18n();
init_dist4();
var import_jsx_runtime88 = __toESM(require_jsx_runtime(), 1);
function getPermScopeItems() {
  return [
    {
      label: t4("Project settings"),
      description: t4("Checked in at .qwen/settings.json"),
      value: "Workspace" /* Workspace */,
      key: "project"
    },
    {
      label: t4("User settings"),
      description: t4("Saved in at ~/.qwen/settings.json"),
      value: "User" /* User */,
      key: "user"
    }
  ];
}
__name(getPermScopeItems, "getPermScopeItems");
function getTabs() {
  return [
    {
      id: "allow",
      label: t4("Allow"),
      description: t4("Qwen Code won't ask before using allowed tools.")
    },
    {
      id: "ask",
      label: t4("Ask"),
      description: t4("Qwen Code will ask before using these tools.")
    },
    {
      id: "deny",
      label: t4("Deny"),
      description: t4("Qwen Code is not allowed to use denied tools.")
    },
    {
      id: "workspace",
      label: t4("Workspace"),
      description: t4("Manage trusted directories for this workspace.")
    }
  ];
}
__name(getTabs, "getTabs");
function describeRule(raw2) {
  const match2 = raw2.match(/^([^(]+?)(?:\((.+)\))?$/);
  if (!match2) return raw2;
  const toolName = match2[1].trim();
  const specifier = match2[2]?.trim();
  if (!specifier) {
    return t4("Any use of the {{tool}} tool", { tool: toolName });
  }
  return t4("{{tool}} commands matching '{{pattern}}'", {
    tool: toolName,
    pattern: specifier
  });
}
__name(describeRule, "describeRule");
function scopeLabel(scope) {
  switch (scope) {
    case "user":
      return t4("From user settings");
    case "workspace":
      return t4("From project settings");
    case "session":
      return t4("From session");
    default:
      return scope;
  }
}
__name(scopeLabel, "scopeLabel");
function PermissionsDialog({
  onExit
}) {
  const config2 = useConfig();
  const settings = useSettings();
  const pm = config2.getPermissionManager?.();
  const tabs = (0, import_react92.useMemo)(() => getTabs(), []);
  const [activeTabIndex, setActiveTabIndex] = (0, import_react92.useState)(0);
  const activeTab = tabs[activeTabIndex];
  const [allRules, setAllRules] = (0, import_react92.useState)([]);
  const [searchQuery, setSearchQuery] = (0, import_react92.useState)("");
  const [isSearchActive, setIsSearchActive] = (0, import_react92.useState)(false);
  const [view, setView] = (0, import_react92.useState)("rule-list");
  const [newRuleInput, setNewRuleInput] = (0, import_react92.useState)("");
  const [ruleInputError, setRuleInputError] = (0, import_react92.useState)("");
  const [pendingRuleText, setPendingRuleText] = (0, import_react92.useState)("");
  const [deleteTarget, setDeleteTarget] = (0, import_react92.useState)(null);
  const workspaceContext = config2.getWorkspaceContext();
  const [newDirInput, setNewDirInput] = (0, import_react92.useState)("");
  const [dirInputError, setDirInputError] = (0, import_react92.useState)("");
  const [dirInputRemountKey, setDirInputRemountKey] = (0, import_react92.useState)(0);
  const [completionIndex, setCompletionIndex] = (0, import_react92.useState)(0);
  const [removeDirTarget, setRemoveDirTarget] = (0, import_react92.useState)(null);
  const [dirRefreshKey, setDirRefreshKey] = (0, import_react92.useState)(0);
  const refreshRules = (0, import_react92.useCallback)(() => {
    if (pm) {
      setAllRules(pm.listRules());
    }
  }, [pm]);
  (0, import_react92.useEffect)(() => {
    refreshRules();
  }, [refreshRules]);
  const directories = (0, import_react92.useMemo)(() => {
    dirRefreshKey;
    return workspaceContext.getDirectories();
  }, [workspaceContext, dirRefreshKey]);
  const initialDirs = (0, import_react92.useMemo)(
    () => new Set(workspaceContext.getInitialDirectories()),
    [workspaceContext]
  );
  const dirCompletions = (0, import_react92.useMemo)(() => {
    const trimmed2 = newDirInput.trim();
    if (!trimmed2) return [];
    const expanded = trimmed2.startsWith("~") ? trimmed2.replace(/^~/, os46.homedir()) : trimmed2;
    const endsWithSep = expanded.endsWith("/") || expanded.endsWith(nodePath3.sep);
    const searchDir = endsWithSep ? expanded : nodePath3.dirname(expanded);
    const prefix = endsWithSep ? "" : nodePath3.basename(expanded);
    try {
      return fs125.readdirSync(searchDir, { withFileTypes: true }).filter(
        (e4) => e4.isDirectory() && e4.name.startsWith(prefix) && !e4.name.startsWith(".")
      ).map((e4) => nodePath3.join(searchDir, e4.name)).slice(0, 6);
    } catch {
      return [];
    }
  }, [newDirInput]);
  const handleDirInputChange = (0, import_react92.useCallback)(
    (text) => {
      setNewDirInput(text);
      if (dirInputError) setDirInputError("");
    },
    [dirInputError]
  );
  (0, import_react92.useEffect)(() => {
    setCompletionIndex(0);
  }, [dirCompletions]);
  const handleDirTabComplete = (0, import_react92.useCallback)(() => {
    const selected = dirCompletions[completionIndex] ?? dirCompletions[0];
    if (selected) {
      setNewDirInput(selected + "/");
      setDirInputRemountKey((k2) => k2 + 1);
    }
  }, [dirCompletions, completionIndex]);
  const handleDirCompletionUp = (0, import_react92.useCallback)(() => {
    if (dirCompletions.length === 0) return;
    setCompletionIndex(
      (prev) => (prev - 1 + dirCompletions.length) % dirCompletions.length
    );
  }, [dirCompletions.length]);
  const handleDirCompletionDown = (0, import_react92.useCallback)(() => {
    if (dirCompletions.length === 0) return;
    setCompletionIndex((prev) => (prev + 1) % dirCompletions.length);
  }, [dirCompletions.length]);
  const dirListItems = (0, import_react92.useMemo)(() => {
    const items = [];
    items.push({
      label: t4("Add directory\u2026"),
      value: "__add_dir__",
      key: "__add_dir__"
    });
    for (const dir of directories) {
      if (!initialDirs.has(dir)) {
        items.push({
          label: dir,
          value: dir,
          key: `dir-${dir}`
        });
      }
    }
    return items;
  }, [directories, initialDirs]);
  const handleDirListSelect = (0, import_react92.useCallback)(
    (value) => {
      if (value === "__add_dir__") {
        setNewDirInput("");
        setView("ws-add-dir-input");
        return;
      }
      if (!initialDirs.has(value)) {
        setRemoveDirTarget(value);
        setView("ws-remove-confirm");
      }
    },
    [initialDirs]
  );
  const handleAddDirSubmit = (0, import_react92.useCallback)(() => {
    const trimmed2 = newDirInput.trim();
    if (!trimmed2) return;
    const expanded = trimmed2.startsWith("~") ? trimmed2.replace(/^~/, os46.homedir()) : trimmed2;
    const absoluteExpanded = nodePath3.isAbsolute(expanded) ? expanded : nodePath3.resolve(expanded);
    if (!fs125.existsSync(absoluteExpanded)) {
      setDirInputError(t4("Directory does not exist."));
      return;
    }
    if (!fs125.statSync(absoluteExpanded).isDirectory()) {
      setDirInputError(t4("Path is not a directory."));
      return;
    }
    let resolved;
    try {
      resolved = fs125.realpathSync(absoluteExpanded);
    } catch {
      resolved = absoluteExpanded;
    }
    if (directories.includes(resolved)) {
      setDirInputError(t4("This directory is already in the workspace."));
      return;
    }
    for (const existingDir of directories) {
      if (isPathWithinRoot(resolved, existingDir)) {
        setDirInputError(
          t4("Already covered by existing directory: {{dir}}", {
            dir: existingDir
          })
        );
        return;
      }
    }
    setDirInputError("");
    workspaceContext.addDirectory(resolved);
    const key = "context.includeDirectories";
    const currentDirs = settings.merged["context"];
    const existingDirs = currentDirs?.["includeDirectories"] ?? [];
    if (!existingDirs.includes(resolved)) {
      settings.setValue("Workspace" /* Workspace */, key, [
        ...existingDirs,
        resolved
      ]);
    }
    setDirRefreshKey((k2) => k2 + 1);
    setView("ws-dir-list");
    setNewDirInput("");
  }, [newDirInput, directories, workspaceContext, settings]);
  const handleRemoveDirConfirm = (0, import_react92.useCallback)(() => {
    if (!removeDirTarget) return;
    workspaceContext.removeDirectory(removeDirTarget);
    for (const scope of ["User" /* User */, "Workspace" /* Workspace */]) {
      const scopeSettings = settings.forScope(scope).settings;
      const contextSection = scopeSettings["context"];
      const scopeDirs = contextSection?.["includeDirectories"];
      if (scopeDirs?.includes(removeDirTarget)) {
        const updated = scopeDirs.filter((d2) => d2 !== removeDirTarget);
        settings.setValue(scope, "context.includeDirectories", updated);
        break;
      }
    }
    setDirRefreshKey((k2) => k2 + 1);
    setRemoveDirTarget(null);
    setView("ws-dir-list");
  }, [removeDirTarget, workspaceContext, settings]);
  const currentTabRules = (0, import_react92.useMemo)(() => {
    if (activeTab.id === "workspace") return [];
    return allRules.filter((r5) => r5.type === activeTab.id);
  }, [allRules, activeTab.id]);
  const filteredRules = (0, import_react92.useMemo)(() => {
    if (!searchQuery.trim()) return currentTabRules;
    const q2 = searchQuery.toLowerCase();
    return currentTabRules.filter(
      (r5) => r5.rule.raw.toLowerCase().includes(q2) || r5.rule.toolName.toLowerCase().includes(q2)
    );
  }, [currentTabRules, searchQuery]);
  const listItems = (0, import_react92.useMemo)(() => {
    const items = [
      {
        label: t4("Add a new rule\u2026"),
        value: "__add__",
        key: "__add__"
      }
    ];
    for (const r5 of filteredRules) {
      items.push({
        label: `${r5.rule.raw}`,
        value: r5.rule.raw,
        key: `${r5.type}-${r5.scope}-${r5.rule.raw}`
      });
    }
    return items;
  }, [filteredRules]);
  const handleTabCycle = (0, import_react92.useCallback)(
    (direction) => {
      const newIndex = (activeTabIndex + direction + tabs.length) % tabs.length;
      setActiveTabIndex(newIndex);
      setSearchQuery("");
      setIsSearchActive(false);
      setDirInputError("");
      const newTab = tabs[newIndex];
      setView(newTab.id === "workspace" ? "ws-dir-list" : "rule-list");
    },
    [activeTabIndex, tabs]
  );
  const handleListSelect = (0, import_react92.useCallback)(
    (value) => {
      if (value === "__add__") {
        setNewRuleInput("");
        setRuleInputError("");
        setView("add-rule-input");
        return;
      }
      const found = filteredRules.find((r5) => r5.rule.raw === value);
      if (found) {
        setDeleteTarget(found);
        setView("delete-confirm");
      }
    },
    [filteredRules]
  );
  const handleAddRuleSubmit = (0, import_react92.useCallback)(() => {
    const trimmed2 = newRuleInput.trim();
    if (!trimmed2) return;
    const rule = parseRule(trimmed2);
    if (rule.invalid) {
      setRuleInputError(
        t4(
          "Malformed rule: unbalanced parentheses. Use the format ToolName(specifier)."
        )
      );
      return;
    }
    setRuleInputError("");
    setPendingRuleText(trimmed2);
    setView("add-rule-scope");
  }, [newRuleInput]);
  const handleScopeSelect = (0, import_react92.useCallback)(
    (scope) => {
      if (!pm || activeTab.id === "workspace") return;
      const ruleType = activeTab.id;
      pm.addPersistentRule(pendingRuleText, ruleType);
      const key = `permissions.${ruleType}`;
      const perms = settings.merged["permissions"];
      const currentRules = perms?.[ruleType] ?? [];
      if (!currentRules.includes(pendingRuleText)) {
        settings.setValue(scope, key, [...currentRules, pendingRuleText]);
      }
      refreshRules();
      setView("rule-list");
      setPendingRuleText("");
    },
    [pm, activeTab.id, pendingRuleText, settings, refreshRules]
  );
  const handleDeleteConfirm = (0, import_react92.useCallback)(() => {
    if (!pm || !deleteTarget) return;
    const ruleType = deleteTarget.type;
    pm.removePersistentRule(deleteTarget.rule.raw, ruleType);
    for (const scope of ["User" /* User */, "Workspace" /* Workspace */]) {
      const scopeSettings = settings.forScope(scope).settings;
      const perms = scopeSettings["permissions"];
      const scopeRules = perms?.[ruleType];
      if (scopeRules?.includes(deleteTarget.rule.raw)) {
        const updated = scopeRules.filter(
          (r5) => r5 !== deleteTarget.rule.raw
        );
        settings.setValue(scope, `permissions.${ruleType}`, updated);
        break;
      }
    }
    refreshRules();
    setDeleteTarget(null);
    setView("rule-list");
  }, [pm, deleteTarget, settings, refreshRules]);
  useKeypress(
    (key) => {
      if (view === "rule-list") {
        if (key.name === "escape") {
          if (isSearchActive && searchQuery) {
            setSearchQuery("");
            setIsSearchActive(false);
          } else {
            onExit();
          }
          return;
        }
        if (key.name === "tab") {
          handleTabCycle(1);
          return;
        }
        if (key.name === "right" || key.name === "left") {
          handleTabCycle(key.name === "right" ? 1 : -1);
          return;
        }
        if (key.name === "backspace" || key.name === "delete") {
          if (searchQuery.length > 0) {
            setSearchQuery((prev) => prev.slice(0, -1));
          }
          return;
        }
        if (key.sequence && !key.ctrl && !key.meta && key.sequence.length === 1 && key.sequence >= " ") {
          setSearchQuery((prev) => prev + key.sequence);
          setIsSearchActive(true);
          return;
        }
      }
      if (view === "add-rule-input") {
        if (key.name === "escape") {
          setView("rule-list");
          return;
        }
      }
      if (view === "add-rule-scope") {
        if (key.name === "escape") {
          setView("add-rule-input");
          return;
        }
      }
      if (view === "delete-confirm") {
        if (key.name === "escape") {
          setDeleteTarget(null);
          setView("rule-list");
          return;
        }
        if (key.name === "return") {
          handleDeleteConfirm();
          return;
        }
      }
      if (view === "ws-dir-list") {
        if (key.name === "escape") {
          onExit();
          return;
        }
        if (key.name === "tab") {
          handleTabCycle(1);
          return;
        }
        if (key.name === "right" || key.name === "left") {
          handleTabCycle(key.name === "right" ? 1 : -1);
          return;
        }
      }
      if (view === "ws-add-dir-input") {
        if (key.name === "escape") {
          setDirInputError("");
          setView("ws-dir-list");
          return;
        }
      }
      if (view === "ws-remove-confirm") {
        if (key.name === "escape") {
          setRemoveDirTarget(null);
          setView("ws-dir-list");
          return;
        }
        if (key.name === "return") {
          handleRemoveDirConfirm();
          return;
        }
      }
    },
    { isActive: true }
  );
  if (activeTab.id === "workspace" && view === "ws-add-dir-input") {
    return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { bold: true, color: theme.text.accent, children: t4("Add directory to workspace") }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, wrap: "wrap", children: t4(
        "Qwen Code will be able to read files in this directory and make edits when auto-accept edits is on."
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { children: t4("Enter the path to the directory:") }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
        Box_default,
        {
          borderStyle: "round",
          borderColor: theme.border.default,
          paddingLeft: 1,
          paddingRight: 1,
          marginTop: 1,
          children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
            TextInput,
            {
              value: newDirInput,
              onChange: handleDirInputChange,
              onSubmit: handleAddDirSubmit,
              onTab: dirCompletions.length > 0 ? handleDirTabComplete : void 0,
              onUp: dirCompletions.length > 0 ? handleDirCompletionUp : void 0,
              onDown: dirCompletions.length > 0 ? handleDirCompletionDown : void 0,
              placeholder: t4("Enter directory path\u2026"),
              isActive: true,
              validationErrors: dirInputError ? [dirInputError] : []
            },
            dirInputRemountKey
          )
        }
      ),
      dirCompletions.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { flexDirection: "column", marginTop: 1, paddingLeft: 2, children: dirCompletions.map((completion3, idx) => {
        const name4 = nodePath3.basename(completion3);
        const isSelected = idx === completionIndex;
        return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
            Text3,
            {
              bold: isSelected,
              color: isSelected ? theme.text.primary : theme.text.secondary,
              children: `${name4}/`
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: `    directory` })
        ] }, completion3);
      }) }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: t4("Tab to complete \xB7 Enter to add \xB7 Esc to cancel") }) })
    ] });
  }
  if (activeTab.id === "workspace" && view === "ws-remove-confirm" && removeDirTarget) {
    return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(
        Box_default,
        {
          borderStyle: "round",
          borderColor: theme.border.default,
          flexDirection: "column",
          padding: 1,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { bold: true, children: t4("Remove directory?") }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { marginLeft: 2, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { bold: true, children: removeDirTarget }) }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { children: t4(
              "Are you sure you want to remove this directory from the workspace?"
            ) })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { marginTop: 1, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to confirm \xB7 Esc to cancel") }) })
    ] });
  }
  if (activeTab.id === "workspace") {
    const initialDirArray = Array.from(initialDirs);
    return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(TabBar, { tabs, activeIndex: activeTabIndex }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, wrap: "wrap", children: t4(
        "Qwen Code can read files in the workspace, and make edits when auto-accept edits is on."
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
      initialDirArray.map((dir, idx) => /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { marginLeft: 2, children: [
        /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: "- " }),
        /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { children: dir }),
        /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: idx === 0 ? t4("  (Original working directory)") : t4("  (from settings)") })
      ] }, dir)),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
        RadioButtonSelect,
        {
          items: dirListItems,
          onSelect: handleDirListSelect,
          isFocused: view === "ws-dir-list",
          showNumbers: true,
          showScrollArrows: false,
          maxItemsToShow: 15
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(FooterHint, { view })
    ] });
  }
  if (view === "add-rule-input") {
    return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(
        Box_default,
        {
          borderStyle: "round",
          borderColor: theme.border.default,
          flexDirection: "column",
          padding: 1,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { bold: true, children: t4("Add {{type}} permission rule", { type: activeTab.id }) }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { wrap: "wrap", children: t4(
              "Permission rules are a tool name, optionally followed by a specifier in parentheses."
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Text3, { children: [
              t4("e.g.,"),
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { bold: true, children: "WebFetch" }),
              " ",
              t4("or"),
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { bold: true, children: "Bash(ls:*)" })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
              Box_default,
              {
                borderStyle: "round",
                borderColor: theme.border.default,
                paddingLeft: 1,
                paddingRight: 1,
                children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
                  TextInput,
                  {
                    value: newRuleInput,
                    onChange: setNewRuleInput,
                    onSubmit: handleAddRuleSubmit,
                    placeholder: t4("Enter permission rule\u2026"),
                    isActive: true
                  }
                )
              }
            ),
            ruleInputError && /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(import_jsx_runtime88.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
              /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.status.error, children: ruleInputError })
            ] })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { marginTop: 1, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to submit \xB7 Esc to cancel") }) })
    ] });
  }
  if (view === "add-rule-scope") {
    const scopeItems = getPermScopeItems();
    return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(
        Box_default,
        {
          borderStyle: "round",
          borderColor: theme.border.default,
          flexDirection: "column",
          padding: 1,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { bold: true, children: t4("Add {{type}} permission rule", { type: activeTab.id }) }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { marginLeft: 2, flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { bold: true, children: pendingRuleText }),
              /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: describeRule(pendingRuleText) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { children: t4("Where should this rule be saved?") }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
              RadioButtonSelect,
              {
                items: scopeItems.map((s5) => ({
                  label: `${s5.label}    ${s5.description}`,
                  value: s5.value,
                  key: s5.key
                })),
                onSelect: handleScopeSelect,
                isFocused: true,
                showNumbers: true
              }
            )
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { marginTop: 1, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to confirm \xB7 Esc to cancel") }) })
    ] });
  }
  if (view === "delete-confirm" && deleteTarget) {
    return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(
        Box_default,
        {
          borderStyle: "round",
          borderColor: theme.border.default,
          flexDirection: "column",
          padding: 1,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { bold: true, children: t4("Delete {{type}} rule?", { type: deleteTarget.type }) }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { marginLeft: 2, flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { bold: true, children: deleteTarget.rule.raw }),
              /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: describeRule(deleteTarget.rule.raw) }),
              /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: scopeLabel(deleteTarget.scope) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { children: t4("Are you sure you want to delete this permission rule?") })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { marginTop: 1, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to confirm \xB7 Esc to cancel") }) })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(TabBar, { tabs, activeIndex: activeTabIndex }),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { children: activeTab.description }),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingLeft: 1,
        paddingRight: 1,
        width: 60,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.accent, children: "> " }),
          searchQuery ? /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { children: searchQuery }) : /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: Colors.Gray, children: t4("Search\u2026") })
        ]
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { height: 1 }),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
      RadioButtonSelect,
      {
        items: listItems,
        onSelect: handleListSelect,
        isFocused: view === "rule-list",
        showNumbers: true,
        showScrollArrows: false,
        maxItemsToShow: 15
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(FooterHint, { view })
  ] });
}
__name(PermissionsDialog, "PermissionsDialog");
function TabBar({
  tabs,
  activeIndex
}) {
  return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { marginBottom: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Text3, { color: theme.text.accent, bold: true, children: [
      t4("Permissions:"),
      " "
    ] }),
    tabs.map((tab2, i4) => /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { marginRight: 2, children: i4 === activeIndex ? /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
      Text3,
      {
        bold: true,
        backgroundColor: theme.text.accent,
        color: theme.background.primary,
        children: ` ${tab2.label} `
      }
    ) : /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: ` ${tab2.label} ` }) }, tab2.id)),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: t4("(\u2190/\u2192 or tab to cycle)") })
  ] });
}
__name(TabBar, "TabBar");
function FooterHint({ view }) {
  if (view !== "rule-list" && view !== "ws-dir-list") return /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(import_jsx_runtime88.Fragment, {});
  return /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text3, { color: theme.text.secondary, children: t4(
    "Press \u2191\u2193 to navigate \xB7 Enter to select \xB7 Type to search \xB7 Esc to cancel"
  ) }) });
}
__name(FooterHint, "FooterHint");

// packages/cli/src/ui/components/ModelDialog.tsx
init_esbuild_shims();
var import_react93 = __toESM(require_react(), 1);
init_dist4();
init_i18n();
var import_jsx_runtime89 = __toESM(require_jsx_runtime(), 1);
function formatModalities(modalities) {
  if (!modalities) return t4("text-only");
  const parts2 = [];
  if (modalities.image) parts2.push(t4("image"));
  if (modalities.pdf) parts2.push(t4("pdf"));
  if (modalities.audio) parts2.push(t4("audio"));
  if (modalities.video) parts2.push(t4("video"));
  if (parts2.length === 0) return t4("text-only");
  return `${t4("text")} \xB7 ${parts2.join(" \xB7 ")}`;
}
__name(formatModalities, "formatModalities");
function maskApiKey2(apiKey) {
  if (!apiKey) return `(${t4("not set")})`;
  const trimmed2 = apiKey.trim();
  if (trimmed2.length === 0) return `(${t4("not set")})`;
  if (trimmed2.length <= 6) return "***";
  const head = trimmed2.slice(0, 3);
  const tail = trimmed2.slice(-4);
  return `${head}\u2026${tail}`;
}
__name(maskApiKey2, "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 = maskApiKey2(after?.apiKey);
  uiState?.historyManager.addItem(
    {
      type: "info",
      text: `authType: ${effectiveAuthType ?? `(${t4("none")})`}
Using ${isRuntime ? "runtime " : ""}model: ${effectiveModelId}
Base URL: ${baseUrl}
API key: ${maskedKey}`
    },
    Date.now()
  );
}
__name(handleModelSwitchSuccess, "handleModelSwitchSuccess");
function formatContextWindow(size) {
  if (!size) return `(${t4("unknown")})`;
  return `${size.toLocaleString("en-US")} tokens`;
}
__name(formatContextWindow, "formatContextWindow");
function DetailRow2({
  label,
  value
}) {
  return /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { minWidth: 16, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text3, { color: theme.text.secondary, children: [
      label,
      ":"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { flexGrow: 1, flexDirection: "row", flexWrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { children: value }) })
  ] });
}
__name(DetailRow2, "DetailRow");
function ModelDialog({
  onClose,
  isFastModelMode
}) {
  const config2 = (0, import_react93.useContext)(ConfigContext);
  const uiState = (0, import_react93.useContext)(UIStateContext);
  const settings = useSettings();
  const [errorMessage, setErrorMessage] = (0, import_react93.useState)(null);
  const [highlightedValue, setHighlightedValue] = (0, import_react93.useState)(null);
  const authType = config2?.getAuthType();
  const availableModelEntries = (0, import_react93.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_react93.useMemo)(
    () => availableModelEntries.map(
      ({ authType: t22, model, isRuntime, snapshotId }) => {
        const value = isRuntime && snapshotId ? snapshotId : `${t22}::${model.id}`;
        const isQwenOAuth = t22 === AuthType2.QWEN_OAUTH;
        const title = /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text3, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(
            Text3,
            {
              bold: true,
              color: isQwenOAuth ? theme.status.warning : isRuntime ? theme.status.warning : theme.text.accent,
              children: [
                "[",
                t22,
                "]"
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { children: ` ${model.label}` }),
          isRuntime && /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { color: theme.status.warning, children: " (Runtime)" }),
          isQwenOAuth && !isRuntime && /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text3, { color: theme.status.warning, children: [
            " (",
            t4("Discontinued"),
            ")"
          ] })
        ] });
        let description = model.description || "";
        if (isRuntime) {
          description = description ? `${description} (Runtime)` : "Runtime model";
        }
        if (isQwenOAuth && !isRuntime) {
          description = t4("Discontinued \u2014 switch to Coding Plan or API Key");
        }
        return {
          value,
          title,
          description,
          key: value
        };
      }
    ),
    [availableModelEntries]
  );
  const fastModelSetting = settings?.merged?.fastModel;
  const preferredModelId = isFastModelMode && fastModelSetting ? fastModelSetting : config2?.getModel() || MAINLINE_CODER_MODEL;
  const activeRuntimeSnapshot = isFastModelMode ? void 0 : config2?.getActiveRuntimeModelSnapshot?.();
  const preferredKey = activeRuntimeSnapshot ? activeRuntimeSnapshot.id : authType ? `${authType}::${preferredModelId}` : "";
  useKeypress(
    (key) => {
      if (key.name === "escape" || key.name === "left" && isFastModelMode) {
        onClose();
      }
    },
    { isActive: true }
  );
  const initialIndex = (0, import_react93.useMemo)(() => {
    const index = MODEL_OPTIONS.findIndex(
      (option2) => option2.value === preferredKey
    );
    return index === -1 ? 0 : index;
  }, [MODEL_OPTIONS, preferredKey]);
  const handleHighlight = (0, import_react93.useCallback)((value) => {
    setHighlightedValue(value);
  }, []);
  const highlightedEntry = (0, import_react93.useMemo)(() => {
    const key = highlightedValue ?? preferredKey;
    return availableModelEntries.find(
      ({ authType: t22, model, isRuntime, snapshotId }) => {
        const v2 = isRuntime && snapshotId ? snapshotId : `${t22}::${model.id}`;
        return v2 === key;
      }
    );
  }, [highlightedValue, preferredKey, availableModelEntries]);
  const handleSelect = (0, import_react93.useCallback)(
    async (selected) => {
      setErrorMessage(null);
      if (isFastModelMode) {
        let modelId;
        if (selected.includes("::")) {
          modelId = selected.split("::").slice(1).join("::");
        } else if (selected.startsWith("$runtime|")) {
          const parts2 = selected.split("|");
          modelId = parts2[2] ?? selected;
        } else {
          modelId = selected;
        }
        const scope = getPersistScopeForModelSelection(settings);
        settings.setValue(scope, "fastModel", modelId);
        config2?.setFastModel(modelId);
        uiState?.historyManager.addItem(
          {
            type: "success",
            text: `${t4("Fast Model")}: ${modelId}`
          },
          Date.now()
        );
        onClose();
        return;
      }
      const isQwenOAuthSelection = selected.startsWith(`${AuthType2.QWEN_OAUTH}::`) || selected.startsWith("$runtime|") && selected.split("|")[1] === AuthType2.QWEN_OAUTH;
      const isRuntimeOAuthSelection = selected.startsWith(
        `$runtime|${AuthType2.QWEN_OAUTH}|`
      );
      if (isQwenOAuthSelection && !isRuntimeOAuthSelection) {
        setErrorMessage(
          t4(
            "Qwen OAuth free tier was discontinued on 2026-04-15. Please select a model from another provider or run /auth to switch."
          )
        );
        return;
      }
      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 parts2 = selected.split("|");
          if (parts2.length >= 2 && parts2[0] === "$runtime") {
            selectedAuthType = parts2[1];
          } else {
            selectedAuthType = authType;
          }
          modelId = selected;
        } else {
          const sep13 = "::";
          const idx = selected.indexOf(sep13);
          selectedAuthType = idx >= 0 ? selected.slice(0, idx) : authType;
          modelId = idx >= 0 ? selected.slice(idx + sep13.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,
      isFastModelMode
    ]
  );
  const hasModels = MODEL_OPTIONS.length > 0;
  return /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { bold: true, children: t4("Select Model") }),
        !hasModels ? /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime89.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_runtime89.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { color: theme.text.secondary, children: t4(
            "Please configure models in settings.modelProviders or use environment variables."
          ) }) })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(
          DescriptiveRadioButtonSelect,
          {
            items: MODEL_OPTIONS,
            onSelect: handleSelect,
            onHighlight: handleHighlight,
            initialIndex,
            showNumbers: true
          }
        ) }),
        highlightedEntry && /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(
            Box_default,
            {
              borderStyle: "single",
              borderTop: true,
              borderBottom: false,
              borderLeft: false,
              borderRight: false,
              borderColor: theme.border.default
            }
          ),
          highlightedEntry.authType === AuthType2.QWEN_OAUTH && !highlightedEntry.isRuntime && /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text3, { color: theme.status.warning, children: [
            "\u26A0 ",
            t4("Discontinued \u2014 switch to Coding Plan or API Key")
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(
            DetailRow2,
            {
              label: t4("Modality"),
              value: formatModalities(highlightedEntry.model.modalities)
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(
            DetailRow2,
            {
              label: t4("Context Window"),
              value: formatContextWindow(
                highlightedEntry.model.contextWindowSize
              )
            }
          ),
          highlightedEntry.authType !== AuthType2.QWEN_OAUTH && /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(import_jsx_runtime89.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(
              DetailRow2,
              {
                label: "Base URL",
                value: highlightedEntry.model.baseUrl ?? t4("(default)")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(
              DetailRow2,
              {
                label: "API Key",
                value: highlightedEntry.model.envKey ?? t4("(not set)")
              }
            )
          ] })
        ] }),
        errorMessage && /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { marginTop: 1, flexDirection: "column", paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime89.jsxs)(Text3, { color: theme.status.error, wrap: "wrap", children: [
          "\u2715 ",
          errorMessage
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to select, \u2191\u2193 to navigate, Esc to close") }) })
      ]
    }
  );
}
__name(ModelDialog, "ModelDialog");

// packages/cli/src/ui/components/ManageModelsDialog.tsx
init_esbuild_shims();
var import_react94 = __toESM(require_react(), 1);
init_dist4();
import process36 from "node:process";

// packages/cli/src/ui/manageModels/manageModels.ts
init_esbuild_shims();
init_dist4();
function isFreeOpenRouterModel(modelId) {
  const normalizedId = modelId.toLowerCase();
  return normalizedId.includes(":free") || normalizedId === "openrouter/free";
}
__name(isFreeOpenRouterModel, "isFreeOpenRouterModel");
function getManageModelsDisplayLabel(source2, model) {
  const rawLabel = model.name || model.id;
  switch (source2) {
    case "openrouter":
      return rawLabel.replace(/^OpenRouter\s*·\s*/i, "").trim() || model.id;
    default:
      return rawLabel;
  }
}
__name(getManageModelsDisplayLabel, "getManageModelsDisplayLabel");
function createEntry(source2, model) {
  const contextWindowSize = model.generationConfig?.contextWindowSize;
  const supportsVision = model.capabilities?.vision === true;
  const badges = [];
  if (isFreeOpenRouterModel(model.id)) {
    badges.push("free");
  }
  if (supportsVision) {
    badges.push("vision");
  }
  if (typeof contextWindowSize === "number" && contextWindowSize >= 1e6) {
    badges.push("long-context");
  }
  const displayLabel = getManageModelsDisplayLabel(source2, model);
  return {
    id: model.id,
    label: displayLabel,
    searchText: [model.id, model.name, displayLabel, ...badges].filter(Boolean).join(" "),
    supportsVision,
    contextWindowSize,
    badges,
    model
  };
}
__name(createEntry, "createEntry");
async function fetchManageModelsCatalog(source2) {
  switch (source2) {
    case "openrouter": {
      const models = await fetchOpenRouterModels();
      return {
        source: source2,
        title: "OpenRouter",
        description: "Browse the latest OpenRouter model catalog and choose which models are enabled locally.",
        authType: AuthType2.USE_OPENAI,
        entries: models.map((model) => createEntry(source2, model))
      };
    }
    default:
      throw new Error(`Unsupported manage models source: ${source2}`);
  }
}
__name(fetchManageModelsCatalog, "fetchManageModelsCatalog");
function getEnabledModelIdsForSource(source2, settings) {
  const modelProviders = settings.merged.modelProviders;
  const openaiConfigs = modelProviders?.[AuthType2.USE_OPENAI] || [];
  switch (source2) {
    case "openrouter":
      return openaiConfigs.filter((config2) => isOpenRouterConfig(config2)).map((config2) => config2.id);
    default:
      return [];
  }
}
__name(getEnabledModelIdsForSource, "getEnabledModelIdsForSource");
async function saveManageModelsSelection(params) {
  const { source: source2, selectedModels, settings, config: config2 } = params;
  const persistScope = getPersistScopeForModelSelection(settings);
  const mergedModelProviders = settings.merged.modelProviders;
  const existingOpenAIConfigs = mergedModelProviders?.[AuthType2.USE_OPENAI] || [];
  switch (source2) {
    case "openrouter": {
      const updatedConfigs = mergeOpenRouterConfigs(
        existingOpenAIConfigs,
        selectedModels
      );
      if (updatedConfigs.length === 0) {
        throw new Error(
          "At least one OpenAI-compatible model must remain enabled."
        );
      }
      settings.setValue(
        persistScope,
        `modelProviders.${AuthType2.USE_OPENAI}`,
        updatedConfigs
      );
      const selectedIds = selectedModels.map((model) => model.id);
      const currentAuthType = config2.getContentGeneratorConfig()?.authType;
      const currentModelId = config2.getModel();
      const currentModelStillAvailable = currentModelId ? updatedConfigs.some((model) => model.id === currentModelId) : false;
      let activeModelId = currentModelId;
      if (!currentModelStillAvailable) {
        const preferredDefault = updatedConfigs.find(
          (model) => model.id === OPENROUTER_DEFAULT_MODEL
        );
        activeModelId = preferredDefault?.id || updatedConfigs[0]?.id;
        if (activeModelId) {
          settings.setValue(persistScope, "model.name", activeModelId);
        }
      }
      const updatedModelProviders = {
        ...mergedModelProviders || {},
        [AuthType2.USE_OPENAI]: updatedConfigs
      };
      config2.reloadModelProvidersConfig(updatedModelProviders);
      if (currentAuthType === AuthType2.USE_OPENAI) {
        await config2.refreshAuth(AuthType2.USE_OPENAI);
      }
      return {
        updatedConfigs,
        selectedIds,
        activeModelId
      };
    }
    default:
      throw new Error(`Unsupported manage models source: ${source2}`);
  }
}
__name(saveManageModelsSelection, "saveManageModelsSelection");

// packages/cli/src/ui/components/ManageModelsDialog.tsx
var import_jsx_runtime90 = __toESM(require_jsx_runtime(), 1);
var MAX_VISIBLE_MODELS = 12;
var MANAGE_MODELS_TABS = [
  { source: "openrouter", label: "OpenRouter", enabled: true },
  { source: "modelstudio", label: "ModelStudio", enabled: false }
];
function buildModelLabel(entry) {
  return entry.label;
}
__name(buildModelLabel, "buildModelLabel");
function applyCatalogFilters(params) {
  const { entries, query, selectedIds, filterMode } = params;
  const normalized2 = query.trim().toLowerCase();
  const rawTokens = normalized2 ? normalized2.split(/\s+/).filter(Boolean) : [];
  const quickFilterEnabled = rawTokens.some(
    (token2) => token2 === "enabled" || token2 === "is:enabled"
  );
  const tokens = rawTokens.filter(
    (token2) => token2 !== "enabled" && token2 !== "is:enabled"
  );
  const selectedSet = new Set(selectedIds);
  return entries.filter((entry) => {
    if ((filterMode === "enabled" || quickFilterEnabled) && !selectedSet.has(entry.id)) {
      return false;
    }
    if (filterMode === "free" && !entry.badges.includes("free")) {
      return false;
    }
    if (filterMode === "vision" && !entry.supportsVision) {
      return false;
    }
    if (tokens.length === 0) {
      return true;
    }
    const haystack = `${entry.searchText} ${entry.id}`.toLowerCase();
    return tokens.every((token2) => haystack.includes(token2));
  });
}
__name(applyCatalogFilters, "applyCatalogFilters");
function getFilterLabel(filterMode) {
  switch (filterMode) {
    case "enabled":
      return "Enabled";
    case "free":
      return "Free";
    case "vision":
      return "Vision";
    case "all":
    default:
      return "All";
  }
}
__name(getFilterLabel, "getFilterLabel");
function cycleFilter(current, direction) {
  const modes = ["all", "enabled", "free", "vision"];
  const currentIndex = modes.indexOf(current);
  const nextIndex = direction === "right" ? (currentIndex + 1) % modes.length : (currentIndex - 1 + modes.length) % modes.length;
  return modes[nextIndex] || "all";
}
__name(cycleFilter, "cycleFilter");
function formatContextWindowSize(value) {
  return typeof value === "number" ? value.toLocaleString("en-US") : "unknown";
}
__name(formatContextWindowSize, "formatContextWindowSize");
function getNextFocusMode(current, direction, hasList) {
  const order = hasList ? ["tabs", "search", "list"] : ["tabs", "search"];
  const currentIndex = order.indexOf(current);
  const safeIndex = currentIndex >= 0 ? currentIndex : 0;
  const nextIndex = direction === "forward" ? (safeIndex + 1) % order.length : (safeIndex - 1 + order.length) % order.length;
  return order[nextIndex] || "tabs";
}
__name(getNextFocusMode, "getNextFocusMode");
function getNextEnabledTabSource(current, direction) {
  const currentIndex = MANAGE_MODELS_TABS.findIndex(
    (tab2) => tab2.source === current
  );
  const safeIndex = currentIndex >= 0 ? currentIndex : 0;
  for (let offset = 1; offset <= MANAGE_MODELS_TABS.length; offset += 1) {
    const candidateIndex = direction === "right" ? (safeIndex + offset) % MANAGE_MODELS_TABS.length : (safeIndex - offset + MANAGE_MODELS_TABS.length) % MANAGE_MODELS_TABS.length;
    const candidate = MANAGE_MODELS_TABS[candidateIndex];
    if (candidate?.enabled) {
      return candidate.source;
    }
  }
  return current;
}
__name(getNextEnabledTabSource, "getNextEnabledTabSource");
function ManageModelsDialog({
  config: config2,
  onClose
}) {
  const settings = useSettings();
  const [activeTabSource, setActiveTabSource] = (0, import_react94.useState)("openrouter");
  const source2 = "openrouter";
  const [status, setStatus] = (0, import_react94.useState)("loading");
  const [error40, setError] = (0, import_react94.useState)(null);
  const [catalog, setCatalog] = (0, import_react94.useState)(null);
  const [query, setQuery] = (0, import_react94.useState)("");
  const [focusMode, setFocusMode] = (0, import_react94.useState)("tabs");
  const [filterMode, setFilterMode] = (0, import_react94.useState)("all");
  const [selectedIds, setSelectedIds] = (0, import_react94.useState)([]);
  const [highlightedId, setHighlightedId] = (0, import_react94.useState)(null);
  const [statusMessage, setStatusMessage] = (0, import_react94.useState)(null);
  const loadCatalog = (0, import_react94.useCallback)(async () => {
    setStatus("loading");
    setError(null);
    setStatusMessage(null);
    try {
      const nextCatalog = await fetchManageModelsCatalog(source2);
      const enabledIds = getEnabledModelIdsForSource(source2, settings);
      setCatalog(nextCatalog);
      setSelectedIds(enabledIds);
      setHighlightedId(nextCatalog.entries[0]?.id || null);
      setStatus("ready");
    } catch (loadError) {
      setError(
        loadError instanceof Error ? loadError.message : String(loadError)
      );
      setStatus("error");
    }
  }, [settings, source2]);
  (0, import_react94.useEffect)(() => {
    void loadCatalog();
  }, [loadCatalog]);
  const filteredEntries = (0, import_react94.useMemo)(
    () => applyCatalogFilters({
      entries: catalog?.entries || [],
      query,
      selectedIds,
      filterMode
    }),
    [catalog?.entries, query, selectedIds, filterMode]
  );
  (0, import_react94.useEffect)(() => {
    if (filteredEntries.length === 0) {
      setHighlightedId(null);
      if (focusMode === "list") {
        setFocusMode("search");
      }
      return;
    }
    if (highlightedId && filteredEntries.some((entry) => entry.id === highlightedId)) {
      return;
    }
    setHighlightedId(filteredEntries[0]?.id || null);
  }, [filteredEntries, focusMode, highlightedId]);
  const highlightedIndex = (0, import_react94.useMemo)(() => {
    if (!highlightedId) {
      return 0;
    }
    const index = filteredEntries.findIndex(
      (entry) => entry.id === highlightedId
    );
    return index >= 0 ? index : 0;
  }, [filteredEntries, highlightedId]);
  const highlightedEntry = (0, import_react94.useMemo)(() => {
    if (!highlightedId) {
      return null;
    }
    return catalog?.entries.find((entry) => entry.id === highlightedId) || null;
  }, [catalog?.entries, highlightedId]);
  const visibleWindow = (0, import_react94.useMemo)(() => {
    if (filteredEntries.length <= MAX_VISIBLE_MODELS) {
      return {
        start: 0,
        entries: filteredEntries
      };
    }
    const centeredStart = Math.max(
      0,
      Math.min(
        highlightedIndex - Math.floor(MAX_VISIBLE_MODELS / 2),
        filteredEntries.length - MAX_VISIBLE_MODELS
      )
    );
    return {
      start: centeredStart,
      entries: filteredEntries.slice(
        centeredStart,
        centeredStart + MAX_VISIBLE_MODELS
      )
    };
  }, [filteredEntries, highlightedIndex]);
  const moveHighlight = (0, import_react94.useCallback)(
    (direction) => {
      if (filteredEntries.length === 0) {
        return;
      }
      if (direction === "up") {
        if (highlightedIndex <= 0) {
          setFocusMode("search");
          return;
        }
        setHighlightedId(filteredEntries[highlightedIndex - 1]?.id || null);
        return;
      }
      const nextIndex = Math.min(
        highlightedIndex + 1,
        filteredEntries.length - 1
      );
      setHighlightedId(filteredEntries[nextIndex]?.id || null);
    },
    [filteredEntries, highlightedIndex]
  );
  const toggleHighlightedSelection = (0, import_react94.useCallback)(() => {
    const currentEntry = filteredEntries[highlightedIndex];
    if (!currentEntry) {
      return;
    }
    setSelectedIds((current) => {
      const next = new Set(current);
      if (next.has(currentEntry.id)) {
        next.delete(currentEntry.id);
      } else {
        next.add(currentEntry.id);
      }
      return Array.from(next);
    });
  }, [filteredEntries, highlightedIndex]);
  const handleSave = (0, import_react94.useCallback)(async () => {
    if (!catalog) {
      return;
    }
    const selectedEntries = catalog.entries.filter(
      (entry) => selectedIds.includes(entry.id)
    );
    if (selectedEntries.length === 0) {
      setError("Select at least one model to keep enabled.");
      return;
    }
    setStatus("saving");
    setError(null);
    setStatusMessage(null);
    try {
      const selectedModels = selectedEntries.map(
        (entry) => entry.model
      );
      const result = await saveManageModelsSelection({
        source: source2,
        selectedModels,
        settings,
        config: config2
      });
      setSelectedIds(result.selectedIds);
      setStatus("ready");
      setStatusMessage(
        result.activeModelId ? `Saved ${result.selectedIds.length} enabled models \xB7 active model: ${result.activeModelId} \xB7 use /model to switch models` : `Saved ${result.selectedIds.length} enabled models \xB7 use /model to switch models`
      );
    } catch (saveError) {
      setError(
        saveError instanceof Error ? saveError.message : String(saveError)
      );
      setStatus("error");
    }
  }, [catalog, config2, selectedIds, settings, source2]);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onClose();
        return;
      }
      if (key.ctrl && key.name === "r" && status !== "saving") {
        void loadCatalog();
        return;
      }
      if (status === "saving") {
        return;
      }
      if (key.name === "tab") {
        setFocusMode(
          (current) => getNextFocusMode(
            current,
            key.shift ? "backward" : "forward",
            filteredEntries.length > 0
          )
        );
        return;
      }
      if (focusMode === "tabs") {
        if (key.name === "left") {
          setActiveTabSource(
            (current) => getNextEnabledTabSource(current, "left")
          );
          return;
        }
        if (key.name === "right") {
          setActiveTabSource(
            (current) => getNextEnabledTabSource(current, "right")
          );
          return;
        }
        if (key.name === "down") {
          setFocusMode("search");
        }
        return;
      }
      if (focusMode === "search") {
        if (key.name === "left") {
          setFilterMode((current) => cycleFilter(current, "left"));
          return;
        }
        if (key.name === "right") {
          setFilterMode((current) => cycleFilter(current, "right"));
          return;
        }
        if (key.name === "up") {
          setFocusMode("tabs");
          return;
        }
        if (key.name === "down" && filteredEntries.length > 0) {
          setFocusMode("list");
        }
        return;
      }
      if (focusMode === "list") {
        if (key.name === "up") {
          moveHighlight("up");
          return;
        }
        if (key.name === "down") {
          moveHighlight("down");
          return;
        }
        if (key.name === "space" || key.sequence === " ") {
          toggleHighlightedSelection();
          return;
        }
        if (key.name === "return") {
          void handleSave();
        }
      }
    },
    { isActive: true }
  );
  const terminalWidth = process36.stdout.columns || 120;
  const searchInputWidth = Math.max(40, Math.min(100, terminalWidth - 16));
  const enabledSet = (0, import_react94.useMemo)(() => new Set(selectedIds), [selectedIds]);
  const hiddenAboveCount = visibleWindow.start;
  const hiddenBelowCount = Math.max(
    0,
    filteredEntries.length - (visibleWindow.start + visibleWindow.entries.length)
  );
  return /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { flexDirection: "column", width: "100%", children: [
    /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.border.default, wrap: "truncate", children: "\u2500".repeat(200) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.accent, bold: true, children: [
        "Manage Models:",
        " "
      ] }),
      MANAGE_MODELS_TABS.map((tab2) => {
        const isActive = activeTabSource === tab2.source;
        const isFocused = focusMode === "tabs" && isActive;
        return /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { marginRight: 2, children: isActive ? /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(
          Text3,
          {
            bold: true,
            backgroundColor: isFocused ? theme.text.accent : theme.border.default,
            color: theme.background.primary,
            children: ` ${tab2.label} `
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.text.secondary, children: ` ${tab2.label}${tab2.enabled ? "" : " (soon)"} ` }) }, tab2.source);
      })
    ] }) }),
    (status === "loading" || status === "saving") && /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.text.secondary, children: status === "loading" ? "Loading OpenRouter catalog\u2026" : "Saving enabled models\u2026" }) }),
    error40 && /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.status.error, children: error40 }) }),
    statusMessage && /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.status.success, children: statusMessage }) }),
    /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: focusMode === "search" ? theme.text.accent : theme.border.default,
        paddingLeft: 1,
        paddingRight: 1,
        children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(
          TextInput,
          {
            value: query,
            onChange: setQuery,
            onTab: () => {
              if (filteredEntries.length > 0) {
                setFocusMode("list");
              }
            },
            onDown: () => {
              if (filteredEntries.length > 0) {
                setFocusMode("list");
              }
            },
            placeholder: "Search models\u2026 (type enabled to filter)",
            height: 1,
            isActive: status !== "saving" && focusMode === "search",
            inputWidth: searchInputWidth
          }
        )
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { flexDirection: "row", gap: 2, children: [
      /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(
        Box_default,
        {
          borderStyle: "round",
          borderColor: theme.border.default,
          flexDirection: "column",
          paddingX: 1,
          paddingY: 0,
          width: "56%",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
              getFilterLabel(filterMode),
              " \xB7 ",
              catalog?.entries.length || 0,
              " total \xB7 ",
              filteredEntries.length,
              " shown \xB7 ",
              selectedIds.length,
              " enabled"
            ] }),
            filteredEntries.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.text.secondary, children: "No models match the current search and filter." }) : /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { flexDirection: "column", children: [
              hiddenAboveCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
                "\u2191 ",
                hiddenAboveCount,
                " more above"
              ] }),
              visibleWindow.entries.map((entry, index) => {
                const absoluteIndex = visibleWindow.start + index;
                const isActive = focusMode === "list" && absoluteIndex === highlightedIndex;
                const isEnabled2 = enabledSet.has(entry.id);
                const prefix = isActive ? "\u203A" : " ";
                const checkbox = isEnabled2 ? "[\u2713]" : "[ ]";
                const rowColor = isActive ? theme.status.success : isEnabled2 ? theme.text.accent : theme.text.primary;
                return /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: rowColor, wrap: "truncate-end", children: [
                  prefix,
                  " ",
                  checkbox,
                  " ",
                  buildModelLabel(entry)
                ] }, entry.id);
              }),
              hiddenBelowCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
                "\u2193 ",
                hiddenBelowCount,
                " more below"
              ] })
            ] })
          ]
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(
        Box_default,
        {
          borderStyle: "round",
          borderColor: theme.border.default,
          flexDirection: "column",
          paddingX: 1,
          paddingY: 0,
          width: "44%",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { bold: true, children: "Details" }),
            highlightedEntry ? /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { children: highlightedEntry.label }),
              /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
                "Model ID: ",
                highlightedEntry.id
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
                "Enabled: ",
                enabledSet.has(highlightedEntry.id) ? "yes" : "no"
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
                "Vision: ",
                highlightedEntry.supportsVision ? "yes" : "no"
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
                "Context:",
                " ",
                formatContextWindowSize(highlightedEntry.contextWindowSize)
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Text3, { color: theme.text.secondary, children: [
                "Tags:",
                " ",
                highlightedEntry.badges.length > 0 ? highlightedEntry.badges.join(", ") : "none"
              ] })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.text.secondary, children: "Move to the model list to inspect a model." })
          ]
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text3, { color: theme.text.secondary, children: "\u2190/\u2192 tab switch \xB7 \u2193 enter list \xB7 Space toggle \xB7 Enter save \xB7 Esc cancel" }) })
  ] });
}
__name(ManageModelsDialog, "ManageModelsDialog");

// packages/cli/src/ui/components/arena/ArenaStartDialog.tsx
init_esbuild_shims();
var import_react96 = __toESM(require_react(), 1);
init_dist4();

// packages/cli/src/ui/components/shared/MultiSelect.tsx
init_esbuild_shims();
var import_react95 = __toESM(require_react(), 1);
var import_jsx_runtime91 = __toESM(require_jsx_runtime(), 1);
var EMPTY_SELECTED_KEYS = [];
function getSelectedValues(items, selectedKeys) {
  return items.filter((item) => selectedKeys.has(item.key)).map((item) => item.value);
}
__name(getSelectedValues, "getSelectedValues");
function MultiSelect({
  items,
  initialIndex = 0,
  selectedKeys = EMPTY_SELECTED_KEYS,
  onConfirm,
  onChange,
  onSelectedKeysChange,
  onHighlight,
  isFocused = true,
  showNumbers = true,
  showScrollArrows = false,
  maxItemsToShow: maxItemsToShow2 = 10
}) {
  const [scrollOffset, setScrollOffset] = (0, import_react95.useState)(0);
  const selectedKeySet = (0, import_react95.useMemo)(() => new Set(selectedKeys), [selectedKeys]);
  const { activeIndex } = useSelectionList({
    items,
    initialIndex,
    isFocused,
    // Disable numeric quick-select in useSelectionList — in a multi-select
    // context, onSelect triggers onConfirm (submit), so numeric keys would
    // accidentally submit the dialog instead of toggling checkboxes.
    // Numbers are still rendered visually via the showNumbers prop below.
    showNumbers: false,
    onHighlight,
    onSelect: /* @__PURE__ */ __name(() => {
      onConfirm(getSelectedValues(items, selectedKeySet));
    }, "onSelect")
  });
  const toggleSelectionAtIndex = (0, import_react95.useCallback)(
    (index) => {
      const item = items[index];
      if (!item || item.disabled) {
        return;
      }
      const next = new Set(selectedKeySet);
      if (next.has(item.key)) {
        next.delete(item.key);
      } else {
        next.add(item.key);
      }
      const nextKeys = Array.from(next);
      onSelectedKeysChange?.(nextKeys);
      onChange?.(getSelectedValues(items, next));
    },
    [items, onChange, onSelectedKeysChange, selectedKeySet]
  );
  useKeypress(
    (key) => {
      if (key.name === "space" || key.sequence === " ") {
        toggleSelectionAtIndex(activeIndex);
      }
    },
    { isActive: isFocused }
  );
  (0, import_react95.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 = (0, import_react95.useMemo)(
    () => items.slice(scrollOffset, scrollOffset + maxItemsToShow2),
    [items, scrollOffset, maxItemsToShow2]
  );
  const numberColumnWidth = String(items.length).length;
  const hasMoreAbove = scrollOffset > 0;
  const hasMoreBelow = scrollOffset + maxItemsToShow2 < items.length;
  const moreAboveCount = scrollOffset;
  const moreBelowCount = Math.max(
    0,
    items.length - (scrollOffset + maxItemsToShow2)
  );
  return /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Box_default, { flexDirection: "column", children: [
    showScrollArrows && hasMoreAbove && /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Text3, { color: theme.text.secondary, children: [
      "\u2191 ",
      moreAboveCount,
      " more above"
    ] }),
    visibleItems.map((item, index) => {
      const itemIndex = scrollOffset + index;
      const isActive = activeIndex === itemIndex;
      const isChecked = selectedKeySet.has(item.key);
      const itemNumberText = `${String(itemIndex + 1).padStart(
        numberColumnWidth
      )}.`;
      const checkboxText = item.disabled ? "[x]" : isChecked ? "[\u2713]" : "[ ]";
      let textColor = theme.text.primary;
      if (item.disabled) {
        textColor = theme.text.secondary;
      } else if (isActive) {
        textColor = theme.status.success;
      } else if (isChecked) {
        textColor = theme.text.accent;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Box_default, { alignItems: "flex-start", children: [
        /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { minWidth: 4, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text3, { color: textColor, children: checkboxText }) }),
        showNumbers && /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { marginRight: 1, minWidth: itemNumberText.length, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text3, { color: textColor, children: itemNumberText }) }),
        /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text3, { color: textColor, children: item.label }) })
      ] }, item.key);
    }),
    showScrollArrows && hasMoreBelow && /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Text3, { color: theme.text.secondary, children: [
      "\u2193 ",
      moreBelowCount,
      " more below"
    ] })
  ] });
}
__name(MultiSelect, "MultiSelect");

// packages/cli/src/ui/components/arena/ArenaStartDialog.tsx
init_i18n();
var import_jsx_runtime92 = __toESM(require_jsx_runtime(), 1);
var MODEL_PROVIDERS_DOCUMENTATION_URL2 = "https://qwenlm.github.io/qwen-code-docs/en/users/configuration/settings/#modelproviders";
function ArenaStartDialog({
  onClose,
  onConfirm
}) {
  const config2 = useConfig();
  const [errorMessage, setErrorMessage] = (0, import_react96.useState)(null);
  const modelItems = (0, import_react96.useMemo)(() => {
    const allModels = config2.getAllConfiguredModels();
    const selectableModels = allModels.filter((model) => !model.isRuntimeModel);
    return selectableModels.map((model) => {
      const token2 = `${model.authType}:${model.id}`;
      const isQwenOauth = model.authType === AuthType2.QWEN_OAUTH;
      return {
        key: token2,
        value: token2,
        label: `[${model.authType}] ${model.label}`,
        disabled: isQwenOauth
      };
    });
  }, [config2]);
  const hasDisabledQwenOauth = modelItems.some((item) => item.disabled);
  const selectableModelCount = modelItems.filter(
    (item) => !item.disabled
  ).length;
  const needsMoreModels = selectableModelCount < 2;
  const shouldShowMoreModelsHint = selectableModelCount >= 2 && selectableModelCount < 3;
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onClose();
      }
    },
    { isActive: true }
  );
  const handleConfirm = /* @__PURE__ */ __name((values) => {
    if (values.length < 2) {
      setErrorMessage(
        t4("Please select at least 2 models to start an Arena session.")
      );
      return;
    }
    setErrorMessage(null);
    onConfirm(values);
  }, "handleConfirm");
  return /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { bold: true, children: t4("Select Models") }),
        modelItems.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.status.warning, children: t4("No models available. Please configure models first.") }) }) : /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(
          MultiSelect,
          {
            items: modelItems,
            initialIndex: 0,
            onConfirm: handleConfirm,
            showNumbers: true,
            showScrollArrows: true,
            maxItemsToShow: 10
          }
        ) }),
        errorMessage && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.status.error, children: errorMessage }) }),
        (hasDisabledQwenOauth || needsMoreModels) && /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          hasDisabledQwenOauth && /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.status.warning, children: t4("Note: qwen-oauth models are not supported in Arena.") }),
          needsMoreModels && /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(import_jsx_runtime92.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.status.warning, children: t4("Arena requires at least 2 models. To add more:") }),
            /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.status.warning, children: t4(
              "  - Run /auth to set up a Coding Plan (includes multiple models)"
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.status.warning, children: t4("  - Or configure modelProviders in settings.json") })
          ] })
        ] }),
        shouldShowMoreModelsHint && /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(import_jsx_runtime92.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.text.secondary, children: t4("Configure more models with the modelProviders guide:") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { marginTop: 0, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(dist_default5, { url: MODEL_PROVIDERS_DOCUMENTATION_URL2, fallback: false, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.text.secondary, underline: true, children: MODEL_PROVIDERS_DOCUMENTATION_URL2 }) }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text3, { color: theme.text.secondary, children: t4("Space to toggle, Enter to confirm, Esc to cancel") }) })
      ]
    }
  );
}
__name(ArenaStartDialog, "ArenaStartDialog");

// packages/cli/src/ui/components/arena/ArenaSelectDialog.tsx
init_esbuild_shims();
var import_react97 = __toESM(require_react(), 1);
init_dist4();
init_types22();
var import_jsx_runtime93 = __toESM(require_jsx_runtime(), 1);
function ArenaSelectDialog({
  manager,
  config: config2,
  addItem,
  closeArenaDialog
}) {
  const pushMessage = (0, import_react97.useCallback)(
    (result2) => {
      const item = {
        type: result2.messageType === "info" ? "info" /* INFO */ : "error" /* ERROR */,
        text: result2.content
      };
      addItem(item, Date.now());
      try {
        const chatRecorder = config2.getChatRecordingService();
        chatRecorder?.recordSlashCommand({
          phase: "result",
          rawCommand: "/arena select",
          outputHistoryItems: [{ ...item }]
        });
      } catch {
      }
    },
    [addItem, config2]
  );
  const onSelect = (0, import_react97.useCallback)(
    async (agentId) => {
      closeArenaDialog();
      const mgr = config2.getArenaManager();
      if (!mgr) {
        pushMessage({
          messageType: "error",
          content: "No arena session found. Start one with /arena start."
        });
        return;
      }
      const agent = mgr.getAgentState(agentId) ?? mgr.getAgentStates().find((item) => item.agentId === agentId);
      const label = agent?.model.modelId || agentId;
      pushMessage({
        messageType: "info",
        content: `Applying changes from ${label}\u2026`
      });
      const result2 = await mgr.applyAgentResult(agentId);
      if (!result2.success) {
        pushMessage({
          messageType: "error",
          content: `Failed to apply changes from ${label}: ${result2.error}`
        });
        return;
      }
      try {
        await config2.cleanupArenaRuntime(true);
      } catch (err2) {
        pushMessage({
          messageType: "error",
          content: `Warning: failed to clean up arena resources: ${err2 instanceof Error ? err2.message : String(err2)}`
        });
      }
      pushMessage({
        messageType: "info",
        content: `Applied changes from ${label} to workspace. Arena session complete.`
      });
    },
    [closeArenaDialog, config2, pushMessage]
  );
  const onDiscard = (0, import_react97.useCallback)(async () => {
    closeArenaDialog();
    const mgr = config2.getArenaManager();
    if (!mgr) {
      pushMessage({
        messageType: "error",
        content: "No arena session found. Start one with /arena start."
      });
      return;
    }
    try {
      pushMessage({
        messageType: "info",
        content: "Discarding Arena results and cleaning up\u2026"
      });
      await config2.cleanupArenaRuntime(true);
      pushMessage({
        messageType: "info",
        content: "Arena results discarded. All worktrees cleaned up."
      });
    } catch (err2) {
      pushMessage({
        messageType: "error",
        content: `Failed to clean up arena worktrees: ${err2 instanceof Error ? err2.message : String(err2)}`
      });
    }
  }, [closeArenaDialog, config2, pushMessage]);
  const result = manager.getResult();
  const agents = manager.getAgentStates();
  const firstSelectableAgentId = agents.find(
    (agent) => isSuccessStatus(agent.status)
  )?.agentId;
  const [selectedAgentId, setSelectedAgentId] = (0, import_react97.useState)(
    firstSelectableAgentId
  );
  const [showPreview, setShowPreview] = (0, import_react97.useState)(false);
  const [showDetailedDiff, setShowDetailedDiff] = (0, import_react97.useState)(false);
  const selectedResult = result?.agents.find(
    (agent) => agent.agentId === selectedAgentId
  );
  const items = (0, import_react97.useMemo)(
    () => agents.map((agent) => {
      const label = agent.model.modelId;
      const statusInfo = getArenaStatusLabel(agent.status);
      const duration3 = formatDuration(agent.stats.durationMs);
      const tokens = agent.stats.totalTokens.toLocaleString();
      let diffAdditions = 0;
      let diffDeletions = 0;
      let fileCount = 0;
      if (isSuccessStatus(agent.status) && result) {
        const agentResult = result.agents.find(
          (a2) => a2.agentId === agent.agentId
        );
        if (agentResult?.diffSummary) {
          diffAdditions = agentResult.diffSummary.additions;
          diffDeletions = agentResult.diffSummary.deletions;
          fileCount = agentResult.diffSummary.files.length;
        } else if (agentResult?.diff) {
          const lines = agentResult.diff.split("\n");
          for (const line of lines) {
            if (line.startsWith("+") && !line.startsWith("+++")) {
              diffAdditions++;
            } else if (line.startsWith("-") && !line.startsWith("---")) {
              diffDeletions++;
            }
          }
        }
        fileCount = agentResult?.modifiedFiles?.length ?? fileCount;
      }
      const title = /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { children: label });
      const description = /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text3, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: statusInfo.color, children: statusInfo.text }),
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: " \xB7 " }),
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: duration3 }),
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: " \xB7 " }),
        /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text3, { color: theme.text.secondary, children: [
          tokens,
          " tokens"
        ] }),
        fileCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(import_jsx_runtime93.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: " \xB7 " }),
          /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text3, { color: theme.text.secondary, children: [
            fileCount,
            " files"
          ] })
        ] }),
        (diffAdditions > 0 || diffDeletions > 0) && /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(import_jsx_runtime93.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: " \xB7 " }),
          /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text3, { color: theme.status.success, children: [
            "+",
            diffAdditions
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: "/" }),
          /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text3, { color: theme.status.error, children: [
            "-",
            diffDeletions
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: " lines" })
        ] })
      ] });
      return {
        key: agent.agentId,
        value: agent.agentId,
        title,
        description,
        disabled: !isSuccessStatus(agent.status)
      };
    }),
    [agents, result]
  );
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        closeArenaDialog();
      }
      if (key.name === "p" && !key.ctrl && !key.meta) {
        setShowPreview((current) => !current);
      }
      if (key.name === "d" && !key.ctrl && !key.meta) {
        setShowDetailedDiff((current) => !current);
      }
      if (key.name === "x" && !key.ctrl && !key.meta) {
        onDiscard();
      }
    },
    { isActive: true }
  );
  const task = result?.task || "";
  return /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { bold: true, color: theme.text.primary, children: "Arena Results" }),
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text3, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: "Task: " }),
          /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
            Text3,
            {
              color: theme.text.primary,
              children: `"${task.length > 60 ? task.slice(0, 59) + "\u2026" : task}"`
            }
          )
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: "Select a winner to apply changes:" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(
          DescriptiveRadioButtonSelect,
          {
            items,
            initialIndex: items.findIndex((item) => !item.disabled),
            onSelect: (agentId) => {
              onSelect(agentId);
            },
            onHighlight: (agentId) => {
              setSelectedAgentId(agentId);
            },
            isFocused: true,
            showNumbers: false
          }
        ) }),
        showPreview && selectedResult && /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(ArenaAgentPreview, { result: selectedResult }),
        showDetailedDiff && selectedResult && /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(ArenaAgentDetailedDiff, { result: selectedResult }),
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: "p preview, d detailed diff, Enter select winner, x discard all, Esc cancel" }) })
      ]
    }
  );
}
__name(ArenaSelectDialog, "ArenaSelectDialog");
function ArenaAgentPreview({
  result
}) {
  const fileSummary = result.diffSummary?.files ?? [];
  return /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text3, { bold: true, color: theme.text.primary, children: [
      "Quick Preview \xB7 ",
      result.model.modelId
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Box_default, { marginLeft: 2, children: [
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: "Approach: " }),
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.primary, children: result.approachSummary ?? "No approach summary available." })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Box_default, { marginLeft: 2, children: [
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: "Major files: " }),
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.primary, children: formatFileList3(fileSummary.map((file2) => file2.path)) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Box_default, { marginLeft: 2, children: [
      /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: "Metrics: " }),
      /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text3, { color: theme.text.primary, children: [
        result.stats.totalTokens.toLocaleString(),
        " tokens \xB7",
        " ",
        formatDuration(result.stats.durationMs),
        " \xB7 ",
        result.stats.toolCalls,
        " ",
        "tools"
      ] })
    ] })
  ] });
}
__name(ArenaAgentPreview, "ArenaAgentPreview");
function ArenaAgentDetailedDiff({
  result
}) {
  const diffLines2 = getVisibleDiffLines(result.diff);
  return /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text3, { bold: true, color: theme.text.primary, children: [
      "Detailed Diff \xB7 ",
      result.model.modelId
    ] }),
    diffLines2.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: theme.text.secondary, children: "No diff available." }) }) : /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { marginLeft: 2, flexDirection: "column", children: diffLines2.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text3, { color: getDiffLineColor(line), children: line }, `${index}-${line}`)) })
  ] });
}
__name(ArenaAgentDetailedDiff, "ArenaAgentDetailedDiff");
function formatFileList3(files) {
  if (files.length === 0) {
    return "none";
  }
  const visible = files.slice(0, 6);
  const suffix = files.length > visible.length ? `, +${files.length - visible.length} more` : "";
  return `${visible.join(", ")}${suffix}`;
}
__name(formatFileList3, "formatFileList");
function getVisibleDiffLines(diff4) {
  if (!diff4) {
    return [];
  }
  const lines = diff4.split("\n");
  const maxLines = 180;
  if (lines.length <= maxLines) {
    return lines;
  }
  return [
    ...lines.slice(0, maxLines),
    `... truncated ${lines.length - maxLines} diff lines`
  ];
}
__name(getVisibleDiffLines, "getVisibleDiffLines");
function getDiffLineColor(line) {
  if (line.startsWith("+") && !line.startsWith("+++")) {
    return theme.status.success;
  }
  if (line.startsWith("-") && !line.startsWith("---")) {
    return theme.status.error;
  }
  if (line.startsWith("diff --git") || line.startsWith("@@") || line.startsWith("---") || line.startsWith("+++")) {
    return theme.text.accent;
  }
  return theme.text.secondary;
}
__name(getDiffLineColor, "getDiffLineColor");

// packages/cli/src/ui/components/arena/ArenaStopDialog.tsx
init_esbuild_shims();
var import_react98 = __toESM(require_react(), 1);
init_dist4();
init_types22();
var import_jsx_runtime94 = __toESM(require_jsx_runtime(), 1);
var debugLogger145 = createDebugLogger("ARENA_STOP_DIALOG");
function ArenaStopDialog({
  config: config2,
  addItem,
  closeArenaDialog
}) {
  const [isProcessing, setIsProcessing] = (0, import_react98.useState)(false);
  const pushMessage = (0, import_react98.useCallback)(
    (result) => {
      const item = {
        type: result.messageType === "info" ? "info" /* INFO */ : "error" /* ERROR */,
        text: result.content
      };
      addItem(item, Date.now());
      try {
        const chatRecorder = config2.getChatRecordingService();
        chatRecorder?.recordSlashCommand({
          phase: "result",
          rawCommand: "/arena stop",
          outputHistoryItems: [{ ...item }]
        });
      } catch {
      }
    },
    [addItem, config2]
  );
  const onStop = (0, import_react98.useCallback)(
    async (action) => {
      if (isProcessing) return;
      setIsProcessing(true);
      closeArenaDialog();
      const mgr = config2.getArenaManager();
      if (!mgr) {
        pushMessage({
          messageType: "error",
          content: "No running Arena session found."
        });
        return;
      }
      try {
        const sessionStatus = mgr.getSessionStatus();
        if (sessionStatus === ArenaSessionStatus.RUNNING || sessionStatus === ArenaSessionStatus.INITIALIZING) {
          pushMessage({
            messageType: "info",
            content: "Stopping Arena agents\u2026"
          });
          await mgr.cancel();
        }
        await mgr.waitForSettled();
        pushMessage({
          messageType: "info",
          content: "Cleaning up Arena resources\u2026"
        });
        if (action === "preserve") {
          await mgr.cleanupRuntime();
        } else {
          await mgr.cleanup();
        }
        config2.setArenaManager(null);
        if (action === "preserve") {
          pushMessage({
            messageType: "info",
            content: "Arena session stopped. Worktrees and session files were preserved. Use /arena select --discard to manually clean up later."
          });
        } else {
          pushMessage({
            messageType: "info",
            content: "Arena session stopped. All Arena resources (including Git worktrees) were cleaned up."
          });
        }
      } catch (error40) {
        const message = error40 instanceof Error ? error40.message : String(error40);
        debugLogger145.error("Failed to stop Arena session:", error40);
        pushMessage({
          messageType: "error",
          content: `Failed to stop Arena session: ${message}`
        });
      }
    },
    [isProcessing, closeArenaDialog, config2, pushMessage]
  );
  const configPreserve = config2.getAgentsSettings().arena?.preserveArtifacts ?? false;
  const items = (0, import_react98.useMemo)(
    () => [
      {
        key: "cleanup",
        value: "cleanup",
        title: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { children: "Stop and clean up" }),
        description: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { color: theme.text.secondary, children: "Remove all worktrees and session files" })
      },
      {
        key: "preserve",
        value: "preserve",
        title: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { children: "Stop and preserve artifacts" }),
        description: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { color: theme.text.secondary, children: "Keep worktrees and session files for later inspection" })
      }
    ],
    []
  );
  const defaultIndex = configPreserve ? 1 : 0;
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        closeArenaDialog();
      }
    },
    { isActive: !isProcessing }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { bold: true, color: theme.text.primary, children: "Stop Arena Session" }),
        /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { color: theme.text.secondary, children: "Choose what to do with Arena artifacts:" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(
          DescriptiveRadioButtonSelect,
          {
            items,
            initialIndex: defaultIndex,
            onSelect: (action) => {
              onStop(action);
            },
            isFocused: !isProcessing,
            showNumbers: false
          }
        ) }),
        configPreserve && /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { color: theme.text.secondary, dimColor: true, children: "Default: preserve (agents.arena.preserveArtifacts is enabled)" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text3, { color: theme.text.secondary, children: "Enter to confirm, Esc to cancel" }) })
      ]
    }
  );
}
__name(ArenaStopDialog, "ArenaStopDialog");

// packages/cli/src/ui/components/arena/ArenaStatusDialog.tsx
init_esbuild_shims();
var import_react99 = __toESM(require_react(), 1);
init_dist4();
var import_jsx_runtime95 = __toESM(require_jsx_runtime(), 1);
var STATUS_REFRESH_INTERVAL_MS = 2e3;
var IN_PROCESS_REFRESH_INTERVAL_MS = 1e3;
function truncate2(str2, maxLen) {
  if (str2.length <= maxLen) return str2;
  return str2.slice(0, maxLen - 1) + "\u2026";
}
__name(truncate2, "truncate");
function pad(str2, len, align2 = "left") {
  if (str2.length >= len) return str2.slice(0, len);
  const padding = " ".repeat(len - str2.length);
  return align2 === "right" ? padding + str2 : str2 + padding;
}
__name(pad, "pad");
function getElapsedMs(agent) {
  if (isSettledStatus(agent.status)) {
    return agent.stats.durationMs;
  }
  return Date.now() - agent.startedAt;
}
__name(getElapsedMs, "getElapsedMs");
function getSessionStatusLabel(status) {
  switch (status) {
    case ArenaSessionStatus.RUNNING:
      return { text: "Running", color: theme.status.success };
    case ArenaSessionStatus.INITIALIZING:
      return { text: "Initializing", color: theme.status.warning };
    case ArenaSessionStatus.IDLE:
      return { text: "Idle", color: theme.status.success };
    case ArenaSessionStatus.COMPLETED:
      return { text: "Completed", color: theme.status.success };
    case ArenaSessionStatus.CANCELLED:
      return { text: "Cancelled", color: theme.status.warning };
    case ArenaSessionStatus.FAILED:
      return { text: "Failed", color: theme.status.error };
    default:
      return { text: String(status), color: theme.text.secondary };
  }
}
__name(getSessionStatusLabel, "getSessionStatusLabel");
var MAX_MODEL_NAME_LENGTH = 35;
function ArenaStatusDialog({
  manager,
  closeArenaDialog,
  width
}) {
  const [tick, setTick] = (0, import_react99.useState)(0);
  const backend = manager.getBackend();
  const isInProcess = backend?.type === DISPLAY_MODE.IN_PROCESS;
  const inProcessBackend = isInProcess ? backend : null;
  (0, import_react99.useEffect)(() => {
    const interval = isInProcess ? IN_PROCESS_REFRESH_INTERVAL_MS : STATUS_REFRESH_INTERVAL_MS;
    const timer = setInterval(() => {
      setTick((prev) => prev + 1);
    }, interval);
    return () => clearInterval(timer);
  }, [isInProcess]);
  void tick;
  const sessionStatus = manager.getSessionStatus();
  const sessionLabel = getSessionStatusLabel(sessionStatus);
  const agents = manager.getAgentStates();
  const task = manager.getTask() ?? "";
  const liveStats = (0, import_react99.useMemo)(() => {
    if (!inProcessBackend) return null;
    const statsMap = /* @__PURE__ */ new Map();
    for (const agent of agents) {
      const interactive = inProcessBackend.getAgent(agent.agentId);
      if (interactive) {
        statsMap.set(agent.agentId, interactive.getStats());
      }
    }
    return statsMap;
  }, [inProcessBackend, agents, tick]);
  const maxTaskLen = 60;
  const displayTask = task.length > maxTaskLen ? task.slice(0, maxTaskLen - 1) + "\u2026" : task;
  const colStatus = 14;
  const colTime = 8;
  const colTokens = 10;
  const colRounds = 8;
  const colTools = 8;
  useKeypress(
    (key) => {
      if (key.name === "escape" || key.name === "q" || key.name === "return") {
        closeArenaDialog();
      }
    },
    { isActive: true }
  );
  const innerWidth = (width ?? 80) - 6;
  return /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingX: 2,
      paddingY: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { bold: true, color: theme.text.primary, children: "Arena Status" }),
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.text.secondary, children: " \xB7 " }),
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: sessionLabel.color, children: sessionLabel.text })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Text3, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.text.secondary, children: "Task: " }),
          /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Text3, { color: theme.text.primary, children: [
            '"',
            displayTask,
            '"'
          ] })
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { bold: true, color: theme.text.secondary, children: "Agent" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { width: colStatus, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { bold: true, color: theme.text.secondary, children: "Status" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { width: colTime, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { bold: true, color: theme.text.secondary, children: "Time" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { width: colTokens, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { bold: true, color: theme.text.secondary, children: "Tokens" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { width: colRounds, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { bold: true, color: theme.text.secondary, children: "Rounds" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { width: colTools, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { bold: true, color: theme.text.secondary, children: "Tools" }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(innerWidth) }) }),
        agents.map((agent) => {
          const label = agent.model.modelId;
          const { text: statusText, color } = getArenaStatusLabel(agent.status);
          const elapsed = getElapsedMs(agent);
          const live = liveStats?.get(agent.agentId);
          const totalTokens = live?.totalTokens ?? agent.stats.totalTokens;
          const rounds = live?.rounds ?? agent.stats.rounds;
          const toolCalls = live?.totalToolCalls ?? agent.stats.toolCalls;
          const successfulToolCalls = live?.successfulToolCalls ?? agent.stats.successfulToolCalls;
          const failedToolCalls = live?.failedToolCalls ?? agent.stats.failedToolCalls;
          return /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Box_default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.text.primary, children: truncate2(label, MAX_MODEL_NAME_LENGTH) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { width: colStatus, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color, children: statusText }) }),
            /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { width: colTime, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.text.primary, children: pad(formatDuration(elapsed), colTime - 1, "right") }) }),
            /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { width: colTokens, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.text.primary, children: pad(totalTokens.toLocaleString(), colTokens - 1, "right") }) }),
            /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { width: colRounds, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.text.primary, children: pad(String(rounds), colRounds - 1, "right") }) }),
            /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { width: colTools, justifyContent: "flex-end", children: failedToolCalls > 0 ? /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Text3, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.status.success, children: successfulToolCalls }),
              /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.text.secondary, children: "/" }),
              /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.status.error, children: failedToolCalls })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(
              Text3,
              {
                color: toolCalls > 0 ? theme.status.success : theme.text.primary,
                children: pad(String(toolCalls), colTools - 1, "right")
              }
            ) })
          ] }) }, agent.agentId);
        }),
        agents.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime95.jsx)(Text3, { color: theme.text.secondary, children: "No agents registered yet." }) })
      ]
    }
  );
}
__name(ArenaStatusDialog, "ArenaStatusDialog");

// packages/cli/src/ui/components/ApprovalModeDialog.tsx
init_esbuild_shims();
var import_react100 = __toESM(require_react(), 1);
init_dist4();
init_i18n();
var import_jsx_runtime96 = __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_react100.useState)(
    "User" /* User */
  );
  const [highlightedMode, setHighlightedMode] = (0, import_react100.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_react100.useCallback)(
    (mode2) => {
      onSelect(mode2, selectedScope);
    },
    [onSelect, selectedScope]
  );
  const handleModeHighlight = /* @__PURE__ */ __name((mode2) => {
    setHighlightedMode(mode2);
  }, "handleModeHighlight");
  const handleScopeHighlight = (0, import_react100.useCallback)((scope) => {
    setSelectedScope(scope);
  }, []);
  const handleScopeSelect = (0, import_react100.useCallback)((scope) => {
    setSelectedScope(scope);
    setMode("mode");
  }, []);
  const [mode, setMode] = (0, import_react100.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_runtime96.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        mode === "mode" ? /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(Box_default, { flexDirection: "column", flexGrow: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime96.jsxs)(Text3, { bold: mode === "mode", wrap: "truncate", children: [
            mode === "mode" ? "> " : "  ",
            t4("Approval Mode"),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text3, { color: theme.text.secondary, children: otherScopeModifiedMessage })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Box_default, { height: 1 }),
          /* @__PURE__ */ (0, import_jsx_runtime96.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_runtime96.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime96.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_runtime96.jsx)(
          ScopeSelector,
          {
            onSelect: handleScopeSelect,
            onHighlight: handleScopeHighlight,
            isFocused: mode === "scope",
            initialScope: selectedScope
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime96.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
init_types22();
init_dist4();
import process37 from "node:process";

// packages/cli/src/ui/components/IdeTrustChangeDialog.tsx
init_esbuild_shims();
init_dist4();
var import_jsx_runtime97 = __toESM(require_jsx_runtime(), 1);
var debugLogger146 = 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") {
    debugLogger146.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_runtime97.jsx)(Box_default, { borderStyle: "round", borderColor: theme.status.warning, paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime97.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();
init_dist4();
init_i18n();
var import_jsx_runtime98 = __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_runtime98.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: Colors.AccentBlue,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Box_default, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text3, { color: Colors.AccentBlue, bold: true, children: t4("\u{1F44B} Welcome back! (Last updated: {{timeAgo}})", {
          timeAgo: timeAgo || ""
        }) }) }),
        goalContent && /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text3, { color: Colors.Foreground, bold: true, children: t4("\u{1F3AF} Overall Goal:") }),
          /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Box_default, { marginTop: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text3, { color: Colors.Gray, children: goalContent }) })
        ] }),
        totalTasks > 0 && /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text3, { color: Colors.Foreground, bold: true, children: [
            "\u{1F4CB} ",
            t4("Current Plan:")
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Box_default, { marginTop: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime98.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_runtime98.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, paddingLeft: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text3, { color: Colors.Foreground, bold: true, children: t4("Pending Tasks:") }),
            pendingTasks.map((task, index) => /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Text3, { color: Colors.Gray, children: [
              "\u2022 ",
              task
            ] }, index))
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text3, { bold: true, children: t4("What would you like to do?") }),
          /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text3, { children: t4("Choose how to proceed with your session:") })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(RadioButtonSelect, { items: options2, onSelect, isFocused: true }) })
      ]
    }
  );
}
__name(WelcomeBackDialog, "WelcomeBackDialog");

// packages/cli/src/ui/components/extensions/ExtensionsManagerDialog.tsx
init_esbuild_shims();
var import_react103 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/extensions/steps/index.ts
init_esbuild_shims();

// packages/cli/src/ui/components/extensions/steps/ExtensionListStep.tsx
init_esbuild_shims();
var import_react101 = __toESM(require_react(), 1);
init_dist4();
init_i18n();
var import_jsx_runtime99 = __toESM(require_jsx_runtime(), 1);
var ExtensionListStep = /* @__PURE__ */ __name(({
  extensions,
  extensionsUpdateState,
  onExtensionSelect
}) => {
  const [selectedIndex, setSelectedIndex] = (0, import_react101.useState)(0);
  const { maxNameWidth, maxVersionWidth, maxStatusWidth } = (0, import_react101.useMemo)(() => {
    let maxName = 0;
    let maxVersion = 0;
    let maxStatus = 0;
    for (const ext2 of extensions) {
      maxName = Math.max(maxName, ext2.name.length);
      maxVersion = Math.max(maxVersion, ext2.version.length);
      const statusLength = ext2.isActive ? t4("active").length : t4("disabled").length;
      maxStatus = Math.max(maxStatus, statusLength);
    }
    return {
      maxNameWidth: maxName,
      maxVersionWidth: maxVersion,
      maxStatusWidth: maxStatus
    };
  }, [extensions]);
  (0, import_react101.useEffect)(() => {
    if (extensions.length > 0 && selectedIndex >= extensions.length) {
      setSelectedIndex(0);
    }
  }, [extensions, selectedIndex]);
  useKeypress(
    (key) => {
      if (key.name === "up" || key.name === "k") {
        setSelectedIndex(
          (prev) => prev > 0 ? prev - 1 : extensions.length - 1
        );
      } else if (key.name === "down" || key.name === "j") {
        setSelectedIndex(
          (prev) => prev < extensions.length - 1 ? prev + 1 : 0
        );
      } else if (key.name === "return" || key.name === "space") {
        if (extensions.length > 0) {
          onExtensionSelect(selectedIndex);
        }
      }
    },
    { isActive: true }
  );
  if (extensions.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text3, { color: theme.text.secondary, children: t4("No extensions installed.") }),
      /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text3, { color: theme.text.secondary, children: t4("Use '/extensions install' to install your first extension.") })
    ] });
  }
  const getUpdateStateColor = /* @__PURE__ */ __name((state) => {
    if (!state) return theme.text.secondary;
    switch (state) {
      case "checking for updates" /* CHECKING_FOR_UPDATES */:
      case "updating" /* UPDATING */:
        return theme.text.secondary;
      case "update available" /* UPDATE_AVAILABLE */:
      case "updated, needs restart" /* UPDATED_NEEDS_RESTART */:
        return theme.status.warning;
      case "error" /* ERROR */:
        return theme.status.error;
      case "up to date" /* UP_TO_DATE */:
      case "not updatable" /* NOT_UPDATABLE */:
      case "updated" /* UPDATED */:
        return theme.status.success;
      default:
        return theme.text.secondary;
    }
  }, "getUpdateStateColor");
  const getLocalizedUpdateState = /* @__PURE__ */ __name((state) => {
    if (!state) return "";
    const stateMap = {
      "up to date": t4("up to date"),
      "update available": t4("update available"),
      "checking...": t4("checking..."),
      "not updatable": t4("not updatable"),
      error: t4("error")
    };
    return stateMap[state] || state;
  }, "getLocalizedUpdateState");
  const renderExtensionItem = /* @__PURE__ */ __name((extension, index, isSelected) => {
    const isActive = extension.isActive;
    const activeColor = isActive ? theme.status.success : theme.text.secondary;
    const activeString = isActive ? t4("active") : t4("disabled");
    const updateState = extensionsUpdateState.get(extension.name);
    const stateColor = getUpdateStateColor(updateState);
    const stateText = getLocalizedUpdateState(updateState);
    return /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Box_default, { alignItems: "center", children: [
      /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text3, { color: isSelected ? theme.text.accent : theme.text.primary, children: isSelected ? "\u25CF" : " " }) }),
      /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { width: maxNameWidth, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(
        Text3,
        {
          color: isSelected ? theme.text.accent : theme.text.primary,
          wrap: "truncate",
          children: extension.name
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { width: maxVersionWidth + 8, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text3, { color: theme.text.secondary, children: [
        " v",
        extension.version
      ] }) }),
      /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { width: maxStatusWidth + 8, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text3, { color: activeColor, children: [
        "(",
        activeString,
        ")"
      ] }) }),
      stateText && /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text3, { color: stateColor, children: [
        "[",
        stateText,
        "]"
      ] })
    ] }, extension.name);
  }, "renderExtensionItem");
  return /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text3, { color: theme.text.secondary, children: t4("{{count}} extensions installed", {
      count: extensions.length.toString()
    }) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { flexDirection: "column", children: extensions.map(
      (extension, index) => renderExtensionItem(extension, index, index === selectedIndex)
    ) })
  ] });
}, "ExtensionListStep");

// packages/cli/src/ui/components/extensions/steps/ExtensionDetailStep.tsx
init_esbuild_shims();
init_dist4();
init_i18n();
var import_jsx_runtime100 = __toESM(require_jsx_runtime(), 1);
var ExtensionDetailStep = /* @__PURE__ */ __name(({
  selectedExtension
}) => {
  if (!selectedExtension) {
    return /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.status.error, children: t4("No extension selected") }) });
  }
  const ext2 = selectedExtension;
  const isActive = ext2.isActive;
  const activeColor = isActive ? theme.status.success : theme.text.secondary;
  const activeString = isActive ? t4("active") : t4("disabled");
  const LABEL_WIDTH2 = 12;
  return /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { width: LABEL_WIDTH2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.primary, children: t4("Name:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { children: ext2.name })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { width: LABEL_WIDTH2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.primary, children: t4("Version:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { children: ext2.version })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { width: LABEL_WIDTH2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.primary, children: t4("Status:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: activeColor, children: activeString })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { width: LABEL_WIDTH2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.primary, children: t4("Path:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { children: ext2.path })
    ] }),
    ext2.installMetadata && /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { width: LABEL_WIDTH2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.primary, children: t4("Source:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { children: ext2.installMetadata.source })
    ] }),
    ext2.mcpServers && Object.keys(ext2.mcpServers).length > 0 && /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { width: LABEL_WIDTH2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.primary, children: t4("MCP Servers:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { children: Object.keys(ext2.mcpServers).join(", ") })
    ] }),
    ext2.commands && ext2.commands.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { width: LABEL_WIDTH2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.primary, children: t4("Commands:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { children: ext2.commands.join(", ") })
    ] }),
    ext2.skills && ext2.skills.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { width: LABEL_WIDTH2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.primary, children: t4("Skills:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { children: ext2.skills.map((s5) => s5.name).join(", ") })
    ] }),
    ext2.agents && ext2.agents.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { width: LABEL_WIDTH2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.primary, children: t4("Agents:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { children: ext2.agents.map((a2) => a2.name).join(", ") })
    ] }),
    ext2.resolvedSettings && ext2.resolvedSettings.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { width: LABEL_WIDTH2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text3, { color: theme.text.primary, children: t4("Settings:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Box_default, { flexDirection: "column", paddingLeft: 2, children: ext2.resolvedSettings.map((setting) => /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Text3, { children: [
        "- ",
        setting.name,
        ": ",
        setting.value
      ] }, setting.name)) })
    ] })
  ] }) });
}, "ExtensionDetailStep");

// packages/cli/src/ui/components/extensions/steps/ActionSelectionStep.tsx
init_esbuild_shims();
var import_react102 = __toESM(require_react(), 1);
init_dist4();
init_i18n();

// packages/cli/src/ui/components/extensions/types.ts
init_esbuild_shims();
var MANAGEMENT_STEPS2 = {
  EXTENSION_LIST: "extension-list",
  ACTION_SELECTION: "action-selection",
  EXTENSION_DETAIL: "extension-detail",
  UNINSTALL_CONFIRMATION: "uninstall-confirmation",
  DISABLE_SCOPE_SELECT: "disable-scope-select",
  ENABLE_SCOPE_SELECT: "enable-scope-select",
  UPDATE_PROGRESS: "update-progress"
};

// packages/cli/src/ui/components/extensions/steps/ActionSelectionStep.tsx
var import_jsx_runtime101 = __toESM(require_jsx_runtime(), 1);
var ActionSelectionStep2 = /* @__PURE__ */ __name(({
  selectedExtension,
  hasUpdateAvailable,
  onActionSelect
}) => {
  const [selectedAction, setSelectedAction] = (0, import_react102.useState)(
    null
  );
  const isActive = selectedExtension?.isActive ?? false;
  const actions = (0, import_react102.useMemo)(() => {
    const allActions = [
      {
        key: "view",
        get label() {
          return t4("View Details");
        },
        value: "view"
      },
      ...hasUpdateAvailable ? [
        {
          key: "update",
          get label() {
            return t4("Update Extension");
          },
          value: "update"
        }
      ] : [],
      ...isActive ? [
        {
          key: "disable",
          get label() {
            return t4("Disable Extension");
          },
          value: "disable"
        }
      ] : [
        {
          key: "enable",
          get label() {
            return t4("Enable Extension");
          },
          value: "enable"
        }
      ],
      {
        key: "uninstall",
        get label() {
          return t4("Uninstall Extension");
        },
        value: "uninstall"
      }
    ];
    return allActions;
  }, [hasUpdateAvailable, isActive]);
  const handleActionSelect = /* @__PURE__ */ __name((value) => {
    setSelectedAction(value);
    onActionSelect(value);
  }, "handleActionSelect");
  const selectedIndex = selectedAction ? actions.findIndex((action) => action.value === selectedAction) : 0;
  return /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
    RadioButtonSelect,
    {
      items: actions,
      initialIndex: selectedIndex,
      onSelect: handleActionSelect,
      showNumbers: false
    }
  ) });
}, "ActionSelectionStep");

// packages/cli/src/ui/components/extensions/steps/UninstallConfirmStep.tsx
init_esbuild_shims();
init_dist4();
init_dist4();
init_i18n();
var import_jsx_runtime102 = __toESM(require_jsx_runtime(), 1);
var debugLogger147 = createDebugLogger("EXTENSION_UNINSTALL_STEP");
function UninstallConfirmStep({
  selectedExtension,
  onConfirm,
  onNavigateBack
}) {
  useKeypress(
    async (key) => {
      if (!selectedExtension) return;
      if (key.name === "y" || key.name === "return") {
        try {
          await onConfirm(selectedExtension);
        } catch (error40) {
          debugLogger147.error("Failed to uninstall extension:", error40);
        }
      } else if (key.name === "n" || key.name === "escape") {
        onNavigateBack();
      }
    },
    { isActive: true }
  );
  if (!selectedExtension) {
    return /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Text3, { color: theme.status.error, children: t4("No extension selected") }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime102.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Text3, { color: theme.status.error, children: t4('Are you sure you want to uninstall extension "{{name}}"?', {
      name: selectedExtension.name
    }) }),
    /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Text3, { color: theme.text.secondary, children: t4("This action cannot be undone.") })
  ] });
}
__name(UninstallConfirmStep, "UninstallConfirmStep");

// packages/cli/src/ui/components/extensions/steps/ScopeSelectStep.tsx
init_esbuild_shims();
init_dist4();
init_i18n();
var import_jsx_runtime103 = __toESM(require_jsx_runtime(), 1);
function ScopeSelectStep({
  selectedExtension,
  mode,
  onScopeSelect
}) {
  const scopeItems = [
    {
      key: "user",
      get label() {
        return t4("User (global)");
      },
      value: "user"
    },
    {
      key: "workspace",
      get label() {
        return t4("Workspace (project-specific)");
      },
      value: "workspace"
    }
  ];
  const handleSelect = /* @__PURE__ */ __name((value) => {
    onScopeSelect(value);
  }, "handleSelect");
  if (!selectedExtension) {
    return /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Text3, { color: theme.status.error, children: t4("No extension selected") }) });
  }
  const title = mode === "disable" ? t4('Disable "{{name}}" - Select Scope', { name: selectedExtension.name }) : t4('Enable "{{name}}" - Select Scope', { name: selectedExtension.name });
  return /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Text3, { color: theme.text.primary, children: title }),
    /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
      RadioButtonSelect,
      {
        items: scopeItems,
        onSelect: handleSelect,
        showNumbers: false
      }
    ) })
  ] });
}
__name(ScopeSelectStep, "ScopeSelectStep");

// packages/cli/src/ui/components/extensions/ExtensionsManagerDialog.tsx
init_i18n();
init_dist4();
var import_jsx_runtime104 = __toESM(require_jsx_runtime(), 1);
var debugLogger148 = createDebugLogger("EXTENSIONS_MANAGER_DIALOG");
function ExtensionsManagerDialog({
  onClose,
  config: config2
}) {
  const { extensionsUpdateState } = useUIState();
  const [extensions, setExtensions] = (0, import_react103.useState)([]);
  const [selectedExtensionIndex, setSelectedExtensionIndex] = (0, import_react103.useState)(-1);
  const [navigationStack, setNavigationStack] = (0, import_react103.useState)([
    MANAGEMENT_STEPS2.EXTENSION_LIST
  ]);
  const [updateInProgress, setUpdateInProgress] = (0, import_react103.useState)(false);
  const [updateError, setUpdateError] = (0, import_react103.useState)(null);
  const [successMessage, setSuccessMessage] = (0, import_react103.useState)(null);
  const [errorMessage, setErrorMessage] = (0, import_react103.useState)(null);
  const { columns } = useTerminalSize();
  const boxWidth = columns - 4;
  const loadExtensions = (0, import_react103.useCallback)(async () => {
    if (!config2) return;
    const extensionManager = config2.getExtensionManager();
    if (!extensionManager) {
      debugLogger148.error("ExtensionManager not available");
      return;
    }
    try {
      await extensionManager.refreshCache();
      const loadedExtensions = extensionManager.getLoadedExtensions();
      setExtensions(loadedExtensions);
    } catch (error40) {
      debugLogger148.error("Failed to load extensions:", error40);
    }
  }, [config2]);
  (0, import_react103.useEffect)(() => {
    loadExtensions();
  }, [loadExtensions]);
  const selectedExtension = (0, import_react103.useMemo)(
    () => selectedExtensionIndex >= 0 ? extensions[selectedExtensionIndex] : null,
    [extensions, selectedExtensionIndex]
  );
  const hasUpdateAvailable = (0, import_react103.useMemo)(() => {
    if (!selectedExtension) return false;
    const state = extensionsUpdateState.get(selectedExtension.name);
    return state === "update available" /* UPDATE_AVAILABLE */;
  }, [selectedExtension, extensionsUpdateState]);
  const getCurrentStep = (0, import_react103.useCallback)(
    () => navigationStack[navigationStack.length - 1] || MANAGEMENT_STEPS2.EXTENSION_LIST,
    [navigationStack]
  );
  const handleSelectExtension = (0, import_react103.useCallback)((extensionIndex) => {
    setSelectedExtensionIndex(extensionIndex);
    setSuccessMessage(null);
    setErrorMessage(null);
    setNavigationStack((prev) => [...prev, MANAGEMENT_STEPS2.ACTION_SELECTION]);
  }, []);
  const handleNavigateToStep = (0, import_react103.useCallback)((step) => {
    setNavigationStack((prev) => [...prev, step]);
  }, []);
  const handleNavigateBack = (0, import_react103.useCallback)(() => {
    setNavigationStack((prev) => {
      if (prev.length <= 1) {
        return prev;
      }
      return prev.slice(0, -1);
    });
    setErrorMessage(null);
  }, []);
  const handleUpdateExtension = (0, import_react103.useCallback)(async () => {
    if (!config2 || !selectedExtension) return;
    setUpdateInProgress(true);
    setUpdateError(null);
    try {
      const extensionManager = config2.getExtensionManager();
      if (!extensionManager) {
        throw new Error("ExtensionManager not available");
      }
      const state = extensionsUpdateState.get(selectedExtension.name);
      if (state !== "update available" /* UPDATE_AVAILABLE */) {
        throw new Error("No update available");
      }
      await extensionManager.updateExtension(
        selectedExtension,
        "update available" /* UPDATE_AVAILABLE */,
        (name4, newState) => {
          debugLogger148.debug(`Update state for ${name4}:`, newState);
        }
      );
      await loadExtensions();
      await extensionManager.checkForAllExtensionUpdates((name4, newState) => {
        debugLogger148.debug(`Recheck update state for ${name4}:`, newState);
      });
      setSuccessMessage(
        t4('Extension "{{name}}" updated successfully.', {
          name: selectedExtension.name
        })
      );
      handleNavigateBack();
    } catch (error40) {
      debugLogger148.error("Failed to update extension:", error40);
      setUpdateError(
        error40 instanceof Error ? error40.message : "Unknown error occurred"
      );
    } finally {
      setUpdateInProgress(false);
    }
  }, [
    config2,
    selectedExtension,
    extensionsUpdateState,
    loadExtensions,
    handleNavigateBack
  ]);
  const handleActionSelect = (0, import_react103.useCallback)(
    (action) => {
      switch (action) {
        case "view":
          handleNavigateToStep(MANAGEMENT_STEPS2.EXTENSION_DETAIL);
          break;
        case "update":
          handleNavigateToStep(MANAGEMENT_STEPS2.UPDATE_PROGRESS);
          handleUpdateExtension();
          break;
        case "disable":
          handleNavigateToStep(MANAGEMENT_STEPS2.DISABLE_SCOPE_SELECT);
          break;
        case "enable":
          handleNavigateToStep(MANAGEMENT_STEPS2.ENABLE_SCOPE_SELECT);
          break;
        case "uninstall":
          handleNavigateToStep(MANAGEMENT_STEPS2.UNINSTALL_CONFIRMATION);
          break;
        default:
          break;
      }
    },
    [handleNavigateToStep, handleUpdateExtension]
  );
  const handleToggleExtensionState = (0, import_react103.useCallback)(
    async (scope, newState) => {
      if (!config2 || !selectedExtension) return;
      try {
        const extensionManager = config2.getExtensionManager();
        if (!extensionManager) {
          throw new Error("ExtensionManager not available");
        }
        const settingScope = scope === "user" ? SettingScope.User : SettingScope.Workspace;
        if (newState) {
          await extensionManager.enableExtension(
            selectedExtension.name,
            settingScope
          );
        } else {
          await extensionManager.disableExtension(
            selectedExtension.name,
            settingScope
          );
        }
        setExtensions(
          (prev) => prev.map(
            (ext2) => ext2.name === selectedExtension.name ? { ...ext2, isActive: newState } : ext2
          )
        );
        const actionKey = newState ? "enabled" : "disabled";
        setSuccessMessage(
          t4(`Extension "{{name}}" ${actionKey} successfully.`, {
            name: selectedExtension.name
          })
        );
        setErrorMessage(null);
        setNavigationStack([MANAGEMENT_STEPS2.EXTENSION_LIST]);
      } catch (error40) {
        debugLogger148.error(
          `Failed to ${newState ? "enable" : "disable"} extension:`,
          error40
        );
        setErrorMessage(
          t4('Failed to {{action}} extension "{{name}}": {{error}}', {
            action: newState ? "enable" : "disable",
            name: selectedExtension.name,
            error: getErrorMessage4(error40)
          })
        );
        setSuccessMessage(null);
      }
    },
    [config2, selectedExtension]
  );
  const handleDisableExtension = (0, import_react103.useCallback)(
    async (scope) => {
      await handleToggleExtensionState(scope, false);
    },
    [handleToggleExtensionState]
  );
  const handleEnableExtension = (0, import_react103.useCallback)(
    async (scope) => {
      await handleToggleExtensionState(scope, true);
    },
    [handleToggleExtensionState]
  );
  const handleUninstallExtension = (0, import_react103.useCallback)(
    async (extension) => {
      if (!config2) return;
      try {
        const extensionManager = config2.getExtensionManager();
        if (!extensionManager) {
          throw new Error("ExtensionManager not available");
        }
        await extensionManager.uninstallExtension(extension.name, false);
        await loadExtensions();
        setNavigationStack([MANAGEMENT_STEPS2.EXTENSION_LIST]);
        setSelectedExtensionIndex(-1);
      } catch (error40) {
        debugLogger148.error("Failed to uninstall extension:", error40);
        throw error40;
      }
    },
    [config2, loadExtensions]
  );
  useKeypress(
    (key) => {
      if (key.name !== "escape") {
        return;
      }
      const currentStep = getCurrentStep();
      if (successMessage && currentStep === MANAGEMENT_STEPS2.EXTENSION_LIST) {
        setSuccessMessage(null);
        return;
      }
      if (currentStep === MANAGEMENT_STEPS2.EXTENSION_LIST) {
        onClose();
      } else {
        handleNavigateBack();
      }
    },
    { isActive: true }
  );
  const renderStepHeader = (0, import_react103.useCallback)(() => {
    const currentStep = getCurrentStep();
    const getStepHeaderText = /* @__PURE__ */ __name(() => {
      switch (currentStep) {
        case MANAGEMENT_STEPS2.EXTENSION_LIST:
          return t4("Manage Extensions");
        case MANAGEMENT_STEPS2.ACTION_SELECTION:
          return selectedExtension?.name || t4("Choose Action");
        case MANAGEMENT_STEPS2.EXTENSION_DETAIL:
          return t4("Extension Details");
        case MANAGEMENT_STEPS2.DISABLE_SCOPE_SELECT:
          return t4("Disable Extension");
        case MANAGEMENT_STEPS2.ENABLE_SCOPE_SELECT:
          return t4("Enable Extension");
        case MANAGEMENT_STEPS2.UNINSTALL_CONFIRMATION:
          return t4("Uninstall Extension");
        case MANAGEMENT_STEPS2.UPDATE_PROGRESS:
          return t4("Update Extension");
        default:
          return t4("Unknown Step");
      }
    }, "getStepHeaderText");
    return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text3, { color: theme.text.accent, bold: true, children: getStepHeaderText() }) });
  }, [getCurrentStep, selectedExtension]);
  const renderStepFooter = (0, import_react103.useCallback)(() => {
    const currentStep = getCurrentStep();
    const getNavigationInstructions = /* @__PURE__ */ __name(() => {
      if (currentStep === MANAGEMENT_STEPS2.EXTENSION_LIST) {
        if (extensions.length === 0 || successMessage) {
          return t4("Esc to close");
        }
        return t4("\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close");
      }
      if (currentStep === MANAGEMENT_STEPS2.EXTENSION_DETAIL) {
        return t4("Esc to go back");
      }
      if (currentStep === MANAGEMENT_STEPS2.UNINSTALL_CONFIRMATION) {
        return t4("Y/Enter to confirm \xB7 N/Esc to cancel");
      }
      if (currentStep === MANAGEMENT_STEPS2.UPDATE_PROGRESS) {
        return updateInProgress ? t4("Updating...") : "";
      }
      return t4("\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to go back");
    }, "getNavigationInstructions");
    return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text3, { color: theme.text.secondary, children: getNavigationInstructions() }) });
  }, [getCurrentStep, extensions.length, updateInProgress, successMessage]);
  const renderStepContent = (0, import_react103.useCallback)(() => {
    const currentStep = getCurrentStep();
    if (errorMessage && currentStep === MANAGEMENT_STEPS2.EXTENSION_LIST) {
      return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text3, { color: theme.status.error, children: errorMessage }) });
    }
    if (successMessage && currentStep === MANAGEMENT_STEPS2.EXTENSION_LIST) {
      return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text3, { color: theme.status.success, children: successMessage }) });
    }
    if (updateError && currentStep === MANAGEMENT_STEPS2.UPDATE_PROGRESS) {
      return /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text3, { color: theme.status.error, children: t4("Update failed:") }),
        /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text3, { children: updateError })
      ] });
    }
    switch (currentStep) {
      case MANAGEMENT_STEPS2.EXTENSION_LIST:
        return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
          ExtensionListStep,
          {
            extensions,
            extensionsUpdateState,
            onExtensionSelect: handleSelectExtension
          }
        );
      case MANAGEMENT_STEPS2.ACTION_SELECTION:
        return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
          ActionSelectionStep2,
          {
            selectedExtension,
            hasUpdateAvailable,
            onNavigateToStep: handleNavigateToStep,
            onActionSelect: handleActionSelect
          }
        );
      case MANAGEMENT_STEPS2.EXTENSION_DETAIL:
        return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(ExtensionDetailStep, { selectedExtension });
      case MANAGEMENT_STEPS2.DISABLE_SCOPE_SELECT:
        return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
          ScopeSelectStep,
          {
            selectedExtension,
            mode: "disable",
            onScopeSelect: handleDisableExtension
          }
        );
      case MANAGEMENT_STEPS2.ENABLE_SCOPE_SELECT:
        return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
          ScopeSelectStep,
          {
            selectedExtension,
            mode: "enable",
            onScopeSelect: handleEnableExtension
          }
        );
      case MANAGEMENT_STEPS2.UNINSTALL_CONFIRMATION:
        return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(
          UninstallConfirmStep,
          {
            selectedExtension,
            onConfirm: handleUninstallExtension,
            onNavigateBack: handleNavigateBack
          }
        );
      case MANAGEMENT_STEPS2.UPDATE_PROGRESS:
        return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Box_default, { flexDirection: "column", gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text3, { children: updateInProgress ? t4("Updating {{name}}...", {
          name: selectedExtension?.name || ""
        }) : t4("Update complete!") }) });
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Text3, { color: theme.status.error, children: t4("Invalid step: {{step}}", { step: currentStep }) }) });
    }
  }, [
    getCurrentStep,
    extensions,
    extensionsUpdateState,
    selectedExtension,
    hasUpdateAvailable,
    updateInProgress,
    updateError,
    successMessage,
    errorMessage,
    handleSelectExtension,
    handleNavigateToStep,
    handleNavigateBack,
    handleActionSelect,
    handleDisableExtension,
    handleEnableExtension,
    handleUninstallExtension
  ]);
  return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Box_default, { flexDirection: "column", width: boxWidth, children: /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(
    Box_default,
    {
      borderStyle: "single",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingLeft: 1,
      paddingRight: 1,
      width: boxWidth,
      gap: 1,
      children: [
        renderStepHeader(),
        renderStepContent(),
        renderStepFooter()
      ]
    }
  ) });
}
__name(ExtensionsManagerDialog, "ExtensionsManagerDialog");

// packages/cli/src/ui/components/mcp/MCPManagementDialog.tsx
init_esbuild_shims();
var import_react109 = __toESM(require_react(), 1);
init_i18n();

// packages/cli/src/ui/components/mcp/types.ts
init_esbuild_shims();
var MCP_MANAGEMENT_STEPS = {
  SERVER_LIST: "server-list",
  SERVER_DETAIL: "server-detail",
  DISABLE_SCOPE_SELECT: "disable-scope-select",
  TOOL_LIST: "tool-list",
  TOOL_DETAIL: "tool-detail",
  AUTHENTICATE: "authenticate"
  // OAuth 认证步骤
};

// packages/cli/src/ui/components/mcp/steps/ServerListStep.tsx
init_esbuild_shims();
var import_react104 = __toESM(require_react(), 1);
init_i18n();

// packages/cli/src/ui/components/mcp/utils.ts
init_esbuild_shims();

// packages/cli/src/ui/components/mcp/constants.ts
init_esbuild_shims();
var VISIBLE_TOOLS_COUNT = 10;
var SOURCE_DISPLAY_NAMES = {
  user: "User MCPs",
  project: "Project MCPs",
  extension: "Extension MCPs"
};

// packages/cli/src/ui/components/mcp/utils.ts
function groupServersBySource(servers) {
  const groups = /* @__PURE__ */ new Map();
  for (const server of servers) {
    const existing = groups.get(server.source);
    if (existing) {
      existing.push(server);
    } else {
      groups.set(server.source, [server]);
    }
  }
  const sourceOrder = ["user", "project", "extension"];
  const result = [];
  for (const source2 of sourceOrder) {
    const servers2 = groups.get(source2);
    if (servers2 && servers2.length > 0) {
      result.push({
        source: source2,
        displayName: SOURCE_DISPLAY_NAMES[source2] || source2,
        servers: servers2
      });
    }
  }
  return result;
}
__name(groupServersBySource, "groupServersBySource");
function getStatusColor4(status) {
  switch (status) {
    case "connected":
      return "green";
    case "connecting":
      return "yellow";
    case "disconnected":
      return "red";
    default:
      return "gray";
  }
}
__name(getStatusColor4, "getStatusColor");
function getStatusIcon(status) {
  switch (status) {
    case "connected":
      return "\u2713";
    case "connecting":
      return "\u2026";
    case "disconnected":
      return "\u2717";
    default:
      return "?";
  }
}
__name(getStatusIcon, "getStatusIcon");
function formatServerCommand(server) {
  const config2 = server.config;
  if (config2.httpUrl) {
    return `${config2.httpUrl} (http)`;
  }
  if (config2.url) {
    return `${config2.url} (sse)`;
  }
  if (config2.command) {
    const args2 = config2.args?.join(" ") || "";
    return `${config2.command} ${args2} (stdio)`.trim();
  }
  return "Unknown";
}
__name(formatServerCommand, "formatServerCommand");
function isToolValid(name4, description) {
  return !!name4 && !!description;
}
__name(isToolValid, "isToolValid");
function getToolInvalidReasons(name4, description) {
  const reasons = [];
  if (!name4) reasons.push("missing name");
  if (!description) reasons.push("missing description");
  return reasons;
}
__name(getToolInvalidReasons, "getToolInvalidReasons");

// packages/cli/src/ui/components/mcp/steps/ServerListStep.tsx
var import_jsx_runtime105 = __toESM(require_jsx_runtime(), 1);
var ServerListStep = /* @__PURE__ */ __name(({
  servers,
  onSelect
}) => {
  const [selectedIndex, setSelectedIndex] = (0, import_react104.useState)(0);
  const groupedServers = (0, import_react104.useMemo)(
    () => groupServersBySource(servers),
    [servers]
  );
  const serverNameWidth = (0, import_react104.useMemo)(() => {
    if (servers.length === 0) return 20;
    const maxLength = Math.max(...servers.map((s5) => s5.name.length));
    return Math.min(Math.max(maxLength + 2, 20), 35);
  }, [servers]);
  const flatServers = (0, import_react104.useMemo)(() => {
    const result = [];
    for (const group of groupedServers) {
      result.push(...group.servers);
    }
    return result;
  }, [groupedServers]);
  useKeypress(
    (key) => {
      if (key.name === "up") {
        setSelectedIndex((prev) => Math.max(0, prev - 1));
      } else if (key.name === "down") {
        setSelectedIndex((prev) => Math.min(flatServers.length - 1, prev + 1));
      } else if (key.name === "return") {
        onSelect(selectedIndex);
      }
    },
    { isActive: true }
  );
  if (servers.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Text3, { color: theme.text.secondary, children: t4("No MCP servers configured.") }),
      /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Text3, { color: theme.text.secondary, children: t4("Add MCP servers to your settings to get started.") })
    ] });
  }
  const getSelectionPosition = /* @__PURE__ */ __name((globalIndex) => {
    let currentIndex = 0;
    for (const group of groupedServers) {
      if (globalIndex < currentIndex + group.servers.length) {
        return {
          groupIndex: groupedServers.indexOf(group),
          itemIndex: globalIndex - currentIndex
        };
      }
      currentIndex += group.servers.length;
    }
    return { groupIndex: 0, itemIndex: 0 };
  }, "getSelectionPosition");
  const currentPosition = getSelectionPosition(selectedIndex);
  return /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(Box_default, { flexDirection: "column", children: [
    groupedServers.map((group, groupIndex) => /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        marginBottom: groupIndex === groupedServers.length - 1 ? 0 : 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(Text3, { bold: true, color: theme.text.primary, children: [
            `  ${group.displayName}`,
            group.servers[0]?.configPath && /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(Text3, { color: theme.text.secondary, children: [
              " ",
              "(",
              group.servers[0].configPath,
              ")"
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Box_default, { flexDirection: "column", children: group.servers.map((server, itemIndex) => {
            const isSelected = groupIndex === currentPosition.groupIndex && itemIndex === currentPosition.itemIndex;
            const statusColor = server.isDisabled ? "yellow" : getStatusColor4(server.status);
            return /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(Box_default, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Box_default, { minWidth: 2, children: /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(
                Text3,
                {
                  color: isSelected ? theme.text.accent : theme.text.primary,
                  children: isSelected ? "\u276F" : " "
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Box_default, { width: serverNameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(
                Text3,
                {
                  color: isSelected ? theme.text.accent : theme.text.primary,
                  wrap: "truncate",
                  children: server.name
                }
              ) }),
              /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Text3, { color: theme.text.secondary, children: " \xB7 " }),
              /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(
                Text3,
                {
                  color: statusColor === "green" ? theme.status.success : statusColor === "yellow" ? theme.status.warning : theme.status.error,
                  children: [
                    getStatusIcon(server.status),
                    " ",
                    server.isDisabled ? t4("disabled") : t4(server.status)
                  ]
                }
              ),
              !!server.invalidToolCount && server.invalidToolCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(Text3, { color: theme.status.warning, children: [
                " ",
                t4("{{count}} invalid tools", {
                  count: String(server.invalidToolCount)
                })
              ] })
            ] }, server.name);
          }) })
        ]
      },
      group.source
    )),
    servers.some((s5) => s5.status === "disconnected" && !s5.isDisabled) && /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(Text3, { color: theme.status.warning, children: [
      "\u203B ",
      t4("Run qwen --debug to see error logs")
    ] }) })
  ] });
}, "ServerListStep");

// packages/cli/src/ui/components/mcp/steps/ServerDetailStep.tsx
init_esbuild_shims();
var import_react105 = __toESM(require_react(), 1);
init_i18n();
var import_jsx_runtime106 = __toESM(require_jsx_runtime(), 1);
var LABEL_WIDTH = 15;
var ServerDetailStep = /* @__PURE__ */ __name(({
  server,
  onViewTools,
  onReconnect,
  onDisable,
  onAuthenticate,
  onClearAuth,
  onBack
}) => {
  const statusColor = server ? server.isDisabled ? "yellow" : getStatusColor4(server.status) : "gray";
  const actions = (0, import_react105.useMemo)(() => {
    const result = [];
    if (!server) {
      return result;
    }
    if (!server.isDisabled && (server.toolCount ?? 0) > 0) {
      result.push({
        key: "view-tools",
        label: t4("View tools"),
        value: "view-tools"
      });
    }
    if (!server.isDisabled && server.status === "disconnected") {
      result.push({
        key: "reconnect",
        label: t4("Reconnect"),
        value: "reconnect"
      });
    }
    result.push({
      key: "toggle-disable",
      label: server?.isDisabled ? t4("Enable") : t4("Disable"),
      value: "toggle-disable"
    });
    if (!server.isDisabled) {
      result.push({
        key: "authenticate",
        label: server.hasOAuthTokens ? t4("Re-authenticate") : t4("Authenticate"),
        value: "authenticate"
      });
    }
    if (!server.isDisabled && server.hasOAuthTokens) {
      result.push({
        key: "clear-auth",
        label: t4("Clear Authentication"),
        value: "clear-auth"
      });
    }
    return result;
  }, [server]);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onBack();
      }
    },
    { isActive: true }
  );
  if (!server) {
    return /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { color: theme.status.error, children: t4("No server selected") }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { width: LABEL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { color: theme.text.primary, children: t4("Status:") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(
          Text3,
          {
            color: statusColor === "green" ? theme.status.success : statusColor === "yellow" ? theme.status.warning : theme.status.error,
            children: [
              getStatusIcon(server.status),
              " ",
              server.isDisabled ? t4("disabled") : t4(server.status)
            ]
          }
        ) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { width: LABEL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { color: theme.text.primary, children: t4("Source:") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { color: theme.text.primary, children: server.source === "user" ? t4("User Settings") : server.source === "project" ? t4("Workspace Settings") : t4("Extension") }) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { width: LABEL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { color: theme.text.primary, children: t4("Command:") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { wrap: "truncate", children: formatServerCommand(server) }) })
      ] }),
      server.config.cwd && /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { width: LABEL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { color: theme.text.primary, children: t4("Working Directory:") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { wrap: "truncate", children: server.config.cwd }) })
      ] }),
      !server.isDisabled && /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { width: LABEL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { color: theme.text.primary, children: t4("Tools:") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Text3, { children: [
          server.toolCount,
          " ",
          server.toolCount === 1 ? t4("tool") : t4("tools"),
          !!server.invalidToolCount && server.invalidToolCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Text3, { color: theme.status.warning, children: [
            " ",
            "(",
            server.invalidToolCount,
            " ",
            server.invalidToolCount === 1 ? t4("invalid") : t4("invalid"),
            ")"
          ] })
        ] }) })
      ] }),
      server.errorMessage && /* @__PURE__ */ (0, import_jsx_runtime106.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { width: LABEL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { color: theme.status.error, children: t4("Error:") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text3, { color: theme.status.error, wrap: "wrap", children: server.errorMessage }) })
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(
      RadioButtonSelect,
      {
        items: actions,
        showNumbers: false,
        onSelect: (value) => {
          switch (value) {
            case "view-tools":
              onViewTools();
              break;
            case "reconnect":
              onReconnect?.();
              break;
            case "toggle-disable":
              onDisable?.();
              break;
            case "authenticate":
              onAuthenticate?.();
              break;
            case "clear-auth":
              onClearAuth?.();
              break;
            default:
              break;
          }
        }
      }
    ) })
  ] });
}, "ServerDetailStep");

// packages/cli/src/ui/components/mcp/steps/ToolListStep.tsx
init_esbuild_shims();
var import_react106 = __toESM(require_react(), 1);
init_i18n();
var import_jsx_runtime107 = __toESM(require_jsx_runtime(), 1);
var ToolListStep = /* @__PURE__ */ __name(({
  tools,
  onSelect,
  onBack
}) => {
  const [selectedIndex, setSelectedIndex] = (0, import_react106.useState)(0);
  const toolNameWidth = (0, import_react106.useMemo)(() => {
    if (tools.length === 0) return 30;
    const maxLength = Math.max(...tools.map((t5) => t5.name.length));
    return Math.min(Math.max(maxLength + 2, 30), 50);
  }, [tools]);
  const scrollOffset = (0, import_react106.useMemo)(() => {
    if (tools.length <= VISIBLE_TOOLS_COUNT) {
      return 0;
    }
    if (selectedIndex < VISIBLE_TOOLS_COUNT - 1) {
      return 0;
    }
    return Math.min(
      selectedIndex - VISIBLE_TOOLS_COUNT + 1,
      tools.length - VISIBLE_TOOLS_COUNT
    );
  }, [selectedIndex, tools.length]);
  const displayTools = (0, import_react106.useMemo)(
    () => tools.slice(scrollOffset, scrollOffset + VISIBLE_TOOLS_COUNT),
    [tools, scrollOffset]
  );
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onBack();
      } else if (key.name === "up") {
        setSelectedIndex((prev) => Math.max(0, prev - 1));
      } else if (key.name === "down") {
        setSelectedIndex((prev) => Math.min(tools.length - 1, prev + 1));
      } else if (key.name === "return") {
        if (tools[selectedIndex]) {
          onSelect(tools[selectedIndex]);
        }
      }
    },
    { isActive: true }
  );
  if (tools.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Text3, { color: theme.text.secondary, children: t4("No tools available for this server.") }) });
  }
  const getToolAnnotations = /* @__PURE__ */ __name((tool) => {
    const hints = [];
    if (tool.annotations?.destructiveHint) hints.push("destructive");
    if (tool.annotations?.readOnlyHint) hints.push("read-only");
    if (tool.annotations?.openWorldHint) hints.push("open-world");
    if (tool.annotations?.idempotentHint) hints.push("idempotent");
    return hints.join(", ");
  }, "getToolAnnotations");
  return /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Box_default, { flexDirection: "column", children: displayTools.map((tool, index) => {
      const actualIndex = scrollOffset + index;
      const isSelected = actualIndex === selectedIndex;
      const annotations = getToolAnnotations(tool);
      return /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Box_default, { minWidth: 2, children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(
          Text3,
          {
            color: isSelected ? theme.text.accent : theme.text.primary,
            children: isSelected ? "\u276F" : " "
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Box_default, { width: toolNameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(
          Text3,
          {
            color: isSelected ? theme.text.accent : theme.text.primary,
            wrap: "truncate",
            children: tool.name
          }
        ) }),
        !tool.isValid && /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Text3, { color: theme.status.warning, children: t4("invalid: {{reason}}", {
          reason: tool.invalidReason || t4("unknown")
        }) }),
        annotations && tool.isValid && /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Text3, { color: theme.text.secondary, children: annotations })
      ] }, tool.name);
    }) }),
    tools.length > VISIBLE_TOOLS_COUNT && /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(Text3, { color: theme.text.secondary, children: [
      scrollOffset > 0 ? "\u2191 " : "  ",
      t4("{{current}}/{{total}}", {
        current: (selectedIndex + 1).toString(),
        total: tools.length.toString()
      }),
      scrollOffset + VISIBLE_TOOLS_COUNT < tools.length ? " \u2193" : ""
    ] }) })
  ] });
}, "ToolListStep");

// packages/cli/src/ui/components/mcp/steps/ToolDetailStep.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime108 = __toESM(require_jsx_runtime(), 1);
var renderParameter = /* @__PURE__ */ __name((name4, param, isRequired) => {
  const type = param["type"] || "any";
  const description = param["description"] || "";
  const text = `\u2022 ${name4}${isRequired ? t4("required") : ""}: ${type} ${description ? `- ${description}` : ""}`;
  return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Text3, { color: theme.text.secondary, wrap: "wrap", children: text }) }, name4);
}, "renderParameter");
var ParametersList = /* @__PURE__ */ __name(({ properties, required: required2 }) => {
  const requiredSet = new Set(required2);
  return /* @__PURE__ */ (0, import_jsx_runtime108.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime108.jsxs)(Text3, { color: theme.text.primary, bold: true, children: [
      t4("Parameters"),
      ":"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { flexDirection: "column", marginLeft: 1, children: Object.entries(properties).map(
      ([name4, param]) => renderParameter(
        name4,
        param,
        requiredSet.has(name4)
      )
    ) })
  ] });
}, "ParametersList");
var SchemaSummary = /* @__PURE__ */ __name(({ schema }) => {
  const obj = schema;
  const properties = obj["properties"];
  const required2 = obj["required"] || [];
  return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { flexDirection: "column", children: properties && Object.keys(properties).length > 0 && /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(ParametersList, { properties, required: required2 }) });
}, "SchemaSummary");
var ToolDetailStep = /* @__PURE__ */ __name(({
  tool,
  onBack
}) => {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onBack();
      }
    },
    { isActive: true }
  );
  if (!tool) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Text3, { color: theme.status.error, children: t4("No tool selected") }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime108.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    !tool.isValid && /* @__PURE__ */ (0, import_jsx_runtime108.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Text3, { color: theme.status.error, bold: true, children: t4("Warning: This tool cannot be called by the LLM") }),
      /* @__PURE__ */ (0, import_jsx_runtime108.jsxs)(Text3, { color: theme.status.error, children: [
        t4("Reason"),
        ": ",
        tool.invalidReason || t4("unknown")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Text3, { color: theme.text.secondary, children: t4(
        "Tools must have both name and description to be used by the LLM."
      ) })
    ] }),
    tool.description && /* @__PURE__ */ (0, import_jsx_runtime108.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime108.jsxs)(Text3, { color: theme.text.primary, bold: true, children: [
        t4("Description"),
        ":"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Text3, { wrap: "wrap", children: tool.description })
    ] }),
    tool.schema && /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(SchemaSummary, { schema: tool.schema }) })
  ] });
}, "ToolDetailStep");

// packages/cli/src/ui/components/mcp/steps/DisableScopeSelectStep.tsx
init_esbuild_shims();
var import_react107 = __toESM(require_react(), 1);
init_i18n();
var import_jsx_runtime109 = __toESM(require_jsx_runtime(), 1);
var DisableScopeSelectStep = /* @__PURE__ */ __name(({
  server,
  onSelectScope,
  onBack
}) => {
  const [selectedScope, setSelectedScope] = (0, import_react107.useState)(
    "user"
  );
  const scopes = [
    {
      key: "user",
      get label() {
        return t4("User Settings (global)");
      },
      value: "user"
    },
    {
      key: "workspace",
      get label() {
        return t4("Workspace Settings (project-specific)");
      },
      value: "workspace"
    }
  ];
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onBack();
      } else if (key.name === "return") {
        onSelectScope(selectedScope);
      }
    },
    { isActive: true }
  );
  if (!server) {
    return /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Text3, { color: theme.status.error, children: t4("No server selected") }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime109.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime109.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime109.jsxs)(Text3, { color: theme.text.primary, children: [
        t4("Disable server:"),
        " ",
        server.name
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Text3, { color: theme.text.secondary, children: t4("Select where to add the server to the exclude list:") }) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(
      RadioButtonSelect,
      {
        items: scopes,
        onHighlight: (value) => setSelectedScope(value),
        onSelect: (value) => onSelectScope(value)
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Text3, { color: theme.text.secondary, children: t4("Press Enter to confirm, Esc to cancel") }) })
  ] });
}, "DisableScopeSelectStep");

// packages/cli/src/ui/components/mcp/steps/AuthenticateStep.tsx
init_esbuild_shims();
var import_react108 = __toESM(require_react(), 1);
init_i18n();
init_dist4();
var import_jsx_runtime110 = __toESM(require_jsx_runtime(), 1);
var AUTO_BACK_DELAY_MS = 2e3;
var COPY_FEEDBACK_MS = 2e3;
function wrapForMultiplexer(osc2) {
  if (process.env["TMUX"]) {
    return `\x1BPtmux;${osc2.split("\x1B").join("\x1B\x1B")}\x1B\\`;
  }
  if (process.env["STY"]) {
    return `\x1BP${osc2}\x1B\\`;
  }
  return osc2;
}
__name(wrapForMultiplexer, "wrapForMultiplexer");
function sanitizeForOsc(s5) {
  return s5.replace(/[\x00-\x1f\x7f]/g, "");
}
__name(sanitizeForOsc, "sanitizeForOsc");
function osc8Hyperlink(url3, label = url3) {
  const safeUrl = sanitizeForOsc(url3);
  const safeLabel = sanitizeForOsc(label);
  return wrapForMultiplexer(`\x1B]8;;${safeUrl}\x07${safeLabel}\x1B]8;;\x07`);
}
__name(osc8Hyperlink, "osc8Hyperlink");
function copyToClipboardViaOsc52(text) {
  const base643 = Buffer.from(text, "utf8").toString("base64");
  const seq = wrapForMultiplexer(`\x1B]52;c;${base643}\x07`);
  const stream5 = process.stderr.isTTY ? process.stderr : process.stdout.isTTY ? process.stdout : null;
  if (!stream5) return false;
  try {
    stream5.write(seq);
    return true;
  } catch {
    return false;
  }
}
__name(copyToClipboardViaOsc52, "copyToClipboardViaOsc52");
var AuthenticateStep = /* @__PURE__ */ __name(({
  server,
  onBack
}) => {
  const config2 = useConfig();
  const [authState, setAuthState] = (0, import_react108.useState)("idle");
  const [messages, setMessages] = (0, import_react108.useState)([]);
  const [errorMessage, setErrorMessage] = (0, import_react108.useState)(null);
  const [authUrl, setAuthUrl] = (0, import_react108.useState)(null);
  const [copyState, setCopyState] = (0, import_react108.useState)({ status: "idle" });
  const isRunning = (0, import_react108.useRef)(false);
  const runAuthentication = (0, import_react108.useCallback)(async () => {
    if (!server || !config2 || isRunning.current) return;
    isRunning.current = true;
    setAuthState("authenticating");
    setMessages([]);
    setErrorMessage(null);
    try {
      setMessages([
        t4("Starting OAuth authentication for MCP server '{{name}}'...", {
          name: server.name
        })
      ]);
      let oauthConfig = server.config.oauth;
      if (!oauthConfig) {
        oauthConfig = { enabled: false };
      }
      const mcpServerUrl = server.config.httpUrl || server.config.url;
      const authProvider = new MCPOAuthProvider(new MCPOAuthTokenStorage());
      await authProvider.authenticate(
        server.name,
        oauthConfig,
        mcpServerUrl,
        appEvents
      );
      setMessages((prev) => [
        ...prev,
        t4("Successfully authenticated and refreshed tools for '{{name}}'.", {
          name: server.name
        })
      ]);
      const toolRegistry = config2.getToolRegistry();
      if (toolRegistry) {
        setMessages((prev) => [
          ...prev,
          t4("Re-discovering tools from '{{name}}'...", {
            name: server.name
          })
        ]);
        await toolRegistry.discoverToolsForServer(server.name);
        const discoveredTools = toolRegistry.getToolsByServer(server.name);
        setMessages((prev) => [
          ...prev,
          t4("Discovered {{count}} tool(s) from '{{name}}'.", {
            count: String(discoveredTools.length),
            name: server.name
          })
        ]);
      }
      const geminiClient = config2.getGeminiClient();
      if (geminiClient) {
        await geminiClient.setTools();
      }
      setMessages((prev) => [
        ...prev,
        t4("Authentication complete. Returning to server details...")
      ]);
      setAuthState("success");
    } catch (error40) {
      setErrorMessage(getErrorMessage(error40));
      setAuthState("error");
    } finally {
      isRunning.current = false;
    }
  }, [server, config2]);
  (0, import_react108.useEffect)(() => {
    const displayListener = /* @__PURE__ */ __name((message) => {
      const text = typeof message === "string" ? message : t4(message.key, message.params);
      setMessages((prev) => [...prev, text]);
    }, "displayListener");
    const authUrlListener = /* @__PURE__ */ __name((url3) => {
      setAuthUrl(url3);
    }, "authUrlListener");
    appEvents.on("oauth-display-message" /* OauthDisplayMessage */, displayListener);
    appEvents.on("oauth-auth-url" /* OauthAuthUrl */, authUrlListener);
    return () => {
      appEvents.removeListener("oauth-display-message" /* OauthDisplayMessage */, displayListener);
      appEvents.removeListener("oauth-auth-url" /* OauthAuthUrl */, authUrlListener);
    };
  }, []);
  (0, import_react108.useEffect)(() => {
    runAuthentication();
  }, []);
  (0, import_react108.useEffect)(() => {
    if (authState !== "success") return;
    const timer = setTimeout(() => {
      onBack();
    }, AUTO_BACK_DELAY_MS);
    return () => clearTimeout(timer);
  }, [authState, onBack]);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onBack();
        return;
      }
      if (key.name === "c" && !key.ctrl && !key.meta && !key.paste && authUrl && authState === "authenticating") {
        const ok2 = copyToClipboardViaOsc52(authUrl);
        setCopyState({
          status: ok2 ? "copied" : "unsupported",
          nonce: Date.now()
        });
      }
    },
    { isActive: true }
  );
  (0, import_react108.useEffect)(() => {
    if (copyState.status === "idle") return;
    const timer = setTimeout(
      () => setCopyState({ status: "idle" }),
      COPY_FEEDBACK_MS
    );
    return () => clearTimeout(timer);
  }, [copyState]);
  if (!server) {
    return /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Text3, { color: theme.status.error, children: t4("No server selected") }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime110.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime110.jsxs)(Text3, { color: theme.text.secondary, children: [
      t4("Server:"),
      " ",
      server.name
    ] }) }),
    messages.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Box_default, { flexDirection: "column", children: messages.map((msg, i4) => /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Text3, { color: theme.text.secondary, children: msg }, i4)) }),
    authState === "error" && errorMessage && /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Text3, { color: theme.status.error, children: errorMessage }) }),
    authUrl && /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Text3, { color: theme.text.accent, children: osc8Hyperlink(authUrl) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime110.jsxs)(Box_default, { flexDirection: "column", children: [
      authState === "authenticating" && /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Text3, { color: theme.text.secondary, children: t4("Authenticating... Please complete the login in your browser.") }),
      authState === "authenticating" && authUrl && /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(
        Text3,
        {
          bold: copyState.status === "idle",
          color: copyState.status === "copied" ? theme.status.success : copyState.status === "unsupported" ? theme.status.warning : theme.text.accent,
          children: copyState.status === "copied" ? t4(
            "Copy request sent to your terminal. If paste is empty, copy the URL above manually."
          ) : copyState.status === "unsupported" ? t4("Cannot write to terminal \u2014 copy the URL above manually.") : t4("Press c to copy the authorization URL to your clipboard.")
        }
      ),
      authState === "success" && /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Text3, { color: theme.status.success, children: t4("Authentication successful.") })
    ] })
  ] });
}, "AuthenticateStep");

// packages/cli/src/ui/components/mcp/MCPManagementDialog.tsx
init_dist4();
var import_jsx_runtime111 = __toESM(require_jsx_runtime(), 1);
var debugLogger149 = createDebugLogger("MCP_DIALOG");
var MCPManagementDialog = /* @__PURE__ */ __name(({
  onClose
}) => {
  const config2 = useConfig();
  const { columns: width } = useTerminalSize();
  const boxWidth = width - 4;
  const [servers, setServers] = (0, import_react109.useState)([]);
  const [selectedServerIndex, setSelectedServerIndex] = (0, import_react109.useState)(-1);
  const [selectedTool, setSelectedTool] = (0, import_react109.useState)(
    null
  );
  const [navigationStack, setNavigationStack] = (0, import_react109.useState)([
    MCP_MANAGEMENT_STEPS.SERVER_LIST
  ]);
  const [isLoading, setIsLoading] = (0, import_react109.useState)(true);
  const fetchServerData = (0, import_react109.useCallback)(async () => {
    if (!config2) return [];
    const mcpServers = config2.getMcpServers() || {};
    const toolRegistry = config2.getToolRegistry();
    const promptRegistry = config2.getPromptRegistry();
    const settings = loadSettings();
    const userSettings = settings.forScope("User" /* User */).settings;
    const workspaceSettings = settings.forScope(
      "Workspace" /* Workspace */
    ).settings;
    const serverInfos = [];
    for (const [name4, serverConfig] of Object.entries(mcpServers)) {
      const status = getMCPServerStatus(name4);
      const allTools = toolRegistry?.getAllTools() || [];
      const serverTools = allTools.filter(
        (t5) => t5 instanceof DiscoveredMCPTool && t5.serverName === name4
      );
      const allPrompts = promptRegistry?.getAllPrompts() || [];
      const serverPrompts = allPrompts.filter(
        (p2) => "serverName" in p2 && p2.serverName === name4
      );
      let source2 = "user";
      if (serverConfig.extensionName) {
        source2 = "extension";
      } else if (workspaceSettings.mcpServers?.[name4]) {
        source2 = "project";
      } else if (userSettings.mcpServers?.[name4]) {
        source2 = "user";
      }
      const isDisabled = config2.isMcpServerDisabled(name4);
      const invalidToolCount = serverTools.filter(
        (t5) => !t5.name || !t5.description
      ).length;
      let hasOAuthTokens = false;
      try {
        const tokenStorage = new MCPOAuthTokenStorage();
        const credentials = await tokenStorage.getCredentials(name4);
        hasOAuthTokens = credentials !== null;
      } catch {
      }
      serverInfos.push({
        name: name4,
        status,
        source: source2,
        config: serverConfig,
        toolCount: serverTools.length,
        invalidToolCount,
        promptCount: serverPrompts.length,
        isDisabled,
        hasOAuthTokens
      });
    }
    return serverInfos;
  }, [config2]);
  (0, import_react109.useEffect)(() => {
    const loadServers = /* @__PURE__ */ __name(async () => {
      setIsLoading(true);
      try {
        const serverInfos = await fetchServerData();
        setServers(serverInfos);
      } catch (error40) {
        debugLogger149.error("Error loading MCP servers:", error40);
      } finally {
        setIsLoading(false);
      }
    }, "loadServers");
    loadServers();
  }, [fetchServerData]);
  const selectedServer = (0, import_react109.useMemo)(() => {
    if (selectedServerIndex >= 0 && selectedServerIndex < servers.length) {
      return servers[selectedServerIndex];
    }
    return null;
  }, [servers, selectedServerIndex]);
  const getCurrentStep = (0, import_react109.useCallback)(
    () => navigationStack[navigationStack.length - 1] || MCP_MANAGEMENT_STEPS.SERVER_LIST,
    [navigationStack]
  );
  const handleNavigateToStep = (0, import_react109.useCallback)((step) => {
    setNavigationStack((prev) => [...prev, step]);
  }, []);
  const handleNavigateBack = (0, import_react109.useCallback)(() => {
    setNavigationStack((prev) => {
      if (prev.length <= 1) return prev;
      return prev.slice(0, -1);
    });
  }, []);
  const handleSelectServer = (0, import_react109.useCallback)(
    (index) => {
      setSelectedServerIndex(index);
      handleNavigateToStep(MCP_MANAGEMENT_STEPS.SERVER_DETAIL);
    },
    [handleNavigateToStep]
  );
  const getServerTools = (0, import_react109.useCallback)(() => {
    if (!config2 || !selectedServer) return [];
    const toolRegistry = config2.getToolRegistry();
    if (!toolRegistry) return [];
    const allTools = toolRegistry.getAllTools();
    const mcpTools = [];
    for (const tool of allTools) {
      if (tool instanceof DiscoveredMCPTool && tool.serverName === selectedServer.name) {
        mcpTools.push(tool);
      }
    }
    return mcpTools.map((tool) => {
      const isValid2 = isToolValid(tool.name, tool.description);
      let invalidReason;
      if (!isValid2) {
        const reasons = getToolInvalidReasons(tool.name, tool.description);
        invalidReason = reasons.map((r5) => t4(r5)).join(", ");
      }
      return {
        name: tool.name || t4("(unnamed)"),
        description: tool.description,
        serverName: tool.serverName,
        schema: tool.parameterSchema,
        annotations: tool.annotations,
        isValid: isValid2,
        invalidReason
      };
    });
  }, [config2, selectedServer]);
  const handleViewTools = (0, import_react109.useCallback)(() => {
    handleNavigateToStep(MCP_MANAGEMENT_STEPS.TOOL_LIST);
  }, [handleNavigateToStep]);
  const handleAuthenticate = (0, import_react109.useCallback)(() => {
    handleNavigateToStep(MCP_MANAGEMENT_STEPS.AUTHENTICATE);
  }, [handleNavigateToStep]);
  const handleSelectTool = (0, import_react109.useCallback)(
    (tool) => {
      setSelectedTool(tool);
      handleNavigateToStep(MCP_MANAGEMENT_STEPS.TOOL_DETAIL);
    },
    [handleNavigateToStep]
  );
  const reloadServers = (0, import_react109.useCallback)(async () => {
    setIsLoading(true);
    try {
      const serverInfos = await fetchServerData();
      setServers(serverInfos);
    } catch (error40) {
      debugLogger149.error("Error reloading MCP servers:", error40);
    } finally {
      setIsLoading(false);
    }
  }, [fetchServerData]);
  const handleClearAuth = (0, import_react109.useCallback)(async () => {
    if (!config2 || !selectedServer) return;
    try {
      setIsLoading(true);
      const tokenStorage = new MCPOAuthTokenStorage();
      await tokenStorage.deleteCredentials(selectedServer.name);
      debugLogger149.info(
        `Cleared OAuth tokens for server '${selectedServer.name}'`
      );
      const toolRegistry = config2.getToolRegistry();
      if (toolRegistry) {
        await toolRegistry.disconnectServer(selectedServer.name);
      }
      await reloadServers();
    } catch (error40) {
      debugLogger149.error(
        `Error clearing OAuth tokens for server '${selectedServer.name}':`,
        error40
      );
    } finally {
      setIsLoading(false);
    }
  }, [config2, selectedServer, reloadServers]);
  const handleReconnect = (0, import_react109.useCallback)(async () => {
    if (!config2 || !selectedServer) return;
    try {
      setIsLoading(true);
      const toolRegistry = config2.getToolRegistry();
      if (toolRegistry) {
        await toolRegistry.discoverToolsForServer(selectedServer.name);
      }
      await reloadServers();
    } catch (error40) {
      debugLogger149.error(
        `Error reconnecting to server '${selectedServer.name}':`,
        error40
      );
    } finally {
      setIsLoading(false);
    }
  }, [config2, selectedServer, reloadServers]);
  const handleEnableServer = (0, import_react109.useCallback)(async () => {
    if (!config2 || !selectedServer) return;
    try {
      setIsLoading(true);
      const server = selectedServer;
      const settings = loadSettings();
      for (const scope of ["User" /* User */, "Workspace" /* Workspace */]) {
        const scopeSettings = settings.forScope(scope).settings;
        const currentExcluded2 = scopeSettings.mcp?.excluded || [];
        if (currentExcluded2.includes(server.name)) {
          const newExcluded2 = currentExcluded2.filter(
            (name4) => name4 !== server.name
          );
          settings.setValue(scope, "mcp.excluded", newExcluded2);
        }
      }
      const currentExcluded = config2.getExcludedMcpServers() || [];
      const newExcluded = currentExcluded.filter(
        (name4) => name4 !== server.name
      );
      config2.setExcludedMcpServers(newExcluded);
      const toolRegistry = config2.getToolRegistry();
      if (toolRegistry) {
        await toolRegistry.discoverToolsForServer(server.name);
      }
      await reloadServers();
    } catch (error40) {
      debugLogger149.error(
        `Error enabling server '${selectedServer.name}':`,
        error40
      );
    } finally {
      setIsLoading(false);
    }
  }, [config2, selectedServer, reloadServers]);
  const handleDisable2 = (0, import_react109.useCallback)(async () => {
    if (!selectedServer) return;
    if (selectedServer.isDisabled) {
      void handleEnableServer();
    } else {
      try {
        setIsLoading(true);
        const server = selectedServer;
        const settings = loadSettings();
        let targetScope = "user";
        if (server.source === "extension") {
          debugLogger149.warn(
            `Cannot disable extension MCP server '${server.name}'`
          );
          setIsLoading(false);
          return;
        } else if (server.source === "project") {
          targetScope = "workspace";
        }
        const scopeSettings = settings.forScope(
          targetScope === "user" ? "User" /* User */ : "Workspace" /* Workspace */
        ).settings;
        const currentExcluded = scopeSettings.mcp?.excluded || [];
        if (!currentExcluded.includes(server.name)) {
          const newExcluded = [...currentExcluded, server.name];
          settings.setValue(
            targetScope === "user" ? "User" /* User */ : "Workspace" /* Workspace */,
            "mcp.excluded",
            newExcluded
          );
        }
        const toolRegistry = config2.getToolRegistry();
        if (toolRegistry) {
          await toolRegistry.disableMcpServer(server.name);
        }
        await reloadServers();
      } catch (error40) {
        debugLogger149.error(
          `Error disabling server '${selectedServer.name}':`,
          error40
        );
      } finally {
        setIsLoading(false);
      }
    }
  }, [selectedServer, handleEnableServer, config2, reloadServers]);
  const handleSelectDisableScope = (0, import_react109.useCallback)(
    async (scope) => {
      if (!config2 || !selectedServer) return;
      try {
        setIsLoading(true);
        const server = selectedServer;
        const settings = loadSettings();
        const scopeSettings = settings.forScope(
          scope === "user" ? "User" /* User */ : "Workspace" /* Workspace */
        ).settings;
        const currentExcluded = scopeSettings.mcp?.excluded || [];
        if (!currentExcluded.includes(server.name)) {
          const newExcluded = [...currentExcluded, server.name];
          settings.setValue(
            scope === "user" ? "User" /* User */ : "Workspace" /* Workspace */,
            "mcp.excluded",
            newExcluded
          );
        }
        const toolRegistry = config2.getToolRegistry();
        if (toolRegistry) {
          await toolRegistry.disableMcpServer(server.name);
        }
        await reloadServers();
        handleNavigateBack();
      } catch (error40) {
        debugLogger149.error(
          `Error disabling server '${selectedServer.name}':`,
          error40
        );
      } finally {
        setIsLoading(false);
      }
    },
    [config2, selectedServer, handleNavigateBack, reloadServers]
  );
  const renderStepHeader = (0, import_react109.useCallback)(() => {
    const currentStep = getCurrentStep();
    let headerText = /* @__PURE__ */ (0, import_jsx_runtime111.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.text.accent, bold: true, children: t4("Manage MCP servers") }),
      /* @__PURE__ */ (0, import_jsx_runtime111.jsxs)(Text3, { color: theme.text.secondary, children: [
        servers.length,
        " ",
        servers.length === 1 ? t4("server") : t4("servers")
      ] })
    ] });
    switch (currentStep) {
      case MCP_MANAGEMENT_STEPS.SERVER_DETAIL:
        headerText = /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.text.accent, bold: true, children: selectedServer?.name || t4("Server Detail") }) });
        break;
      case MCP_MANAGEMENT_STEPS.TOOL_LIST:
        headerText = /* @__PURE__ */ (0, import_jsx_runtime111.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.text.accent, bold: true, children: t4("Tools for {{serverName}}", {
            serverName: selectedServer?.name || "Server"
          }) }),
          /* @__PURE__ */ (0, import_jsx_runtime111.jsxs)(Text3, { color: theme.text.secondary, children: [
            "(",
            getServerTools().length,
            " ",
            getServerTools().length === 1 ? t4("tool") : t4("tools"),
            ")"
          ] })
        ] });
        break;
      case MCP_MANAGEMENT_STEPS.TOOL_DETAIL:
        headerText = /* @__PURE__ */ (0, import_jsx_runtime111.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime111.jsxs)(Box_default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.text.accent, bold: true, children: selectedTool?.name || t4("Tool Detail") }),
            selectedTool?.annotations?.destructiveHint && /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.status.error, children: "[destructive]" }),
            selectedTool?.annotations?.idempotentHint && /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.status.warning, children: "[idempotent]" }),
            selectedTool?.annotations?.readOnlyHint && /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.status.success, children: "[read-only]" }),
            selectedTool?.annotations?.openWorldHint && /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.text.primary, children: "[open-world]" })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.text.secondary, children: selectedTool?.serverName || t4("Server") })
        ] });
        break;
      case MCP_MANAGEMENT_STEPS.AUTHENTICATE:
        headerText = /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.text.accent, bold: true, children: t4("OAuth Authentication") }) });
        break;
      case MCP_MANAGEMENT_STEPS.SERVER_LIST:
      default:
        break;
    }
    return headerText;
  }, [getCurrentStep, selectedServer, selectedTool, getServerTools, servers]);
  const renderStepContent = (0, import_react109.useCallback)(() => {
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.text.secondary, children: t4("Loading...") });
    }
    const currentStep = getCurrentStep();
    switch (currentStep) {
      case MCP_MANAGEMENT_STEPS.SERVER_LIST:
        return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(ServerListStep, { servers, onSelect: handleSelectServer });
      case MCP_MANAGEMENT_STEPS.SERVER_DETAIL:
        return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
          ServerDetailStep,
          {
            server: selectedServer,
            onViewTools: handleViewTools,
            onReconnect: handleReconnect,
            onDisable: handleDisable2,
            onAuthenticate: handleAuthenticate,
            onClearAuth: handleClearAuth,
            onBack: handleNavigateBack
          }
        );
      case MCP_MANAGEMENT_STEPS.DISABLE_SCOPE_SELECT:
        return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
          DisableScopeSelectStep,
          {
            server: selectedServer,
            onSelectScope: handleSelectDisableScope,
            onBack: handleNavigateBack
          }
        );
      case MCP_MANAGEMENT_STEPS.TOOL_LIST:
        return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
          ToolListStep,
          {
            tools: getServerTools(),
            serverName: selectedServer?.name || "",
            onSelect: handleSelectTool,
            onBack: handleNavigateBack
          }
        );
      case MCP_MANAGEMENT_STEPS.TOOL_DETAIL:
        return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(ToolDetailStep, { tool: selectedTool, onBack: handleNavigateBack });
      case MCP_MANAGEMENT_STEPS.AUTHENTICATE:
        return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
          AuthenticateStep,
          {
            server: selectedServer,
            onBack: () => {
              handleNavigateBack();
              void reloadServers();
            }
          }
        );
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.status.error, children: t4("Unknown step") }) });
    }
  }, [
    isLoading,
    getCurrentStep,
    servers,
    selectedServer,
    selectedTool,
    handleSelectServer,
    handleViewTools,
    handleReconnect,
    handleDisable2,
    handleAuthenticate,
    handleClearAuth,
    handleNavigateBack,
    handleSelectTool,
    handleSelectDisableScope,
    getServerTools,
    reloadServers
  ]);
  const renderStepFooter = (0, import_react109.useCallback)(() => {
    const currentStep = getCurrentStep();
    let footerText = "";
    switch (currentStep) {
      case MCP_MANAGEMENT_STEPS.SERVER_LIST:
        if (servers.length === 0) {
          footerText = t4("Esc to close");
        } else {
          footerText = t4("\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to close");
        }
        break;
      case MCP_MANAGEMENT_STEPS.SERVER_DETAIL:
        footerText = t4("\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back");
        break;
      case MCP_MANAGEMENT_STEPS.DISABLE_SCOPE_SELECT:
        footerText = t4("\u2191\u2193 to navigate \xB7 Enter to confirm \xB7 Esc to back");
        break;
      case MCP_MANAGEMENT_STEPS.TOOL_LIST:
        footerText = t4("\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to back");
        break;
      case MCP_MANAGEMENT_STEPS.TOOL_DETAIL:
        footerText = t4("Esc to back");
        break;
      case MCP_MANAGEMENT_STEPS.AUTHENTICATE:
        footerText = t4("Esc to go back");
        break;
      default:
        footerText = t4("Esc to close");
    }
    return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text3, { color: theme.text.secondary, children: footerText }) });
  }, [getCurrentStep, servers.length]);
  useKeypress(
    (key) => {
      if (key.name === "escape" && getCurrentStep() === MCP_MANAGEMENT_STEPS.SERVER_LIST) {
        onClose();
      }
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Box_default, { flexDirection: "column", width: boxWidth, children: /* @__PURE__ */ (0, import_jsx_runtime111.jsxs)(
    Box_default,
    {
      borderStyle: "single",
      borderColor: theme.border.default,
      flexDirection: "column",
      width: boxWidth,
      gap: 1,
      paddingLeft: 1,
      paddingRight: 1,
      children: [
        renderStepHeader(),
        renderStepContent(),
        renderStepFooter()
      ]
    }
  ) });
}, "MCPManagementDialog");

// packages/cli/src/ui/components/hooks/HooksManagementDialog.tsx
init_esbuild_shims();
var import_react110 = __toESM(require_react(), 1);
init_dist4();

// packages/cli/src/ui/components/hooks/types.ts
init_esbuild_shims();
var HOOKS_MANAGEMENT_STEPS = {
  HOOKS_DISABLED: "hooks_disabled",
  HOOKS_LIST: "hooks_list",
  HOOK_DETAIL: "hook_detail",
  HOOK_CONFIG_DETAIL: "hook_config_detail"
};

// packages/cli/src/ui/components/hooks/HooksListStep.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime112 = __toESM(require_jsx_runtime(), 1);
function HooksListStep({
  hooks,
  selectedIndex
}) {
  const { columns: terminalWidth } = useTerminalSize();
  const hookNameWidth = Math.min(
    35,
    Math.max(20, Math.floor(terminalWidth * 0.25))
  );
  if (hooks.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Box_default, { flexDirection: "column", paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Text3, { color: theme.text.secondary, children: t4("No hook events found.") }) });
  }
  const totalConfigured = hooks.reduce(
    (sum, hook) => sum + hook.configs.length,
    0
  );
  const hooksConfiguredText = totalConfigured === 1 ? t4("{{count}} hook configured", { count: String(totalConfigured) }) : t4("{{count}} hooks configured", { count: String(totalConfigured) });
  return /* @__PURE__ */ (0, import_jsx_runtime112.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime112.jsxs)(Box_default, { marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Hooks") }),
      /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Text3, { color: theme.text.secondary, children: ` \xB7 ${hooksConfiguredText}` })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Text3, { color: theme.text.secondary, children: t4(
      "This menu is read-only. To add or modify hooks, edit settings.json directly or ask Qwen Code."
    ) }) }),
    hooks.map((hook, index) => {
      const isSelected = index === selectedIndex;
      const configCount = hook.configs.length;
      const maxDigits = String(hooks.length).length;
      const paddedIndex = String(index + 1).padStart(maxDigits);
      return /* @__PURE__ */ (0, import_jsx_runtime112.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Box_default, { minWidth: 2, children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Text3, { color: isSelected ? theme.text.accent : theme.text.primary, children: isSelected ? "\u276F" : " " }) }),
        /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Box_default, { width: hookNameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime112.jsxs)(
          Text3,
          {
            color: isSelected ? theme.text.accent : theme.text.primary,
            bold: isSelected,
            children: [
              paddedIndex,
              ". ",
              hook.event,
              configCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime112.jsxs)(Text3, { color: theme.status.success, children: [
                " (",
                configCount,
                ")"
              ] })
            ]
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Text3, { color: theme.text.secondary, children: hook.shortDescription })
      ] }, hook.event);
    }),
    /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to select \xB7 Esc to cancel") }) })
  ] });
}
__name(HooksListStep, "HooksListStep");

// packages/cli/src/ui/components/hooks/HookDetailStep.tsx
init_esbuild_shims();
init_dist4();

// packages/cli/src/ui/components/hooks/constants.ts
init_esbuild_shims();
init_dist4();
init_i18n();
function getHookExitCodes(eventName) {
  const exitCodesMap = {
    [HookEventName.Stop]: [
      { code: 0, description: t4("stdout/stderr not shown") },
      {
        code: 2,
        description: t4("show stderr to model and continue conversation")
      },
      { code: "Other", description: t4("show stderr to user only") }
    ],
    [HookEventName.PreToolUse]: [
      { code: 0, description: t4("stdout/stderr not shown") },
      { code: 2, description: t4("show stderr to model and block tool call") },
      {
        code: "Other",
        description: t4("show stderr to user only but continue with tool call")
      }
    ],
    [HookEventName.PostToolUse]: [
      { code: 0, description: t4("stdout shown in transcript mode (ctrl+o)") },
      { code: 2, description: t4("show stderr to model immediately") },
      { code: "Other", description: t4("show stderr to user only") }
    ],
    [HookEventName.PostToolUseFailure]: [
      { code: 0, description: t4("stdout shown in transcript mode (ctrl+o)") },
      { code: 2, description: t4("show stderr to model immediately") },
      { code: "Other", description: t4("show stderr to user only") }
    ],
    [HookEventName.Notification]: [
      { code: 0, description: t4("stdout/stderr not shown") },
      { code: "Other", description: t4("show stderr to user only") }
    ],
    [HookEventName.UserPromptSubmit]: [
      { code: 0, description: t4("stdout shown to Qwen") },
      {
        code: 2,
        description: t4(
          "block processing, erase original prompt, and show stderr to user only"
        )
      },
      { code: "Other", description: t4("show stderr to user only") }
    ],
    [HookEventName.SessionStart]: [
      { code: 0, description: t4("stdout shown to Qwen") },
      {
        code: "Other",
        description: t4("show stderr to user only (blocking errors ignored)")
      }
    ],
    [HookEventName.SessionEnd]: [
      { code: 0, description: t4("command completes successfully") },
      { code: "Other", description: t4("show stderr to user only") }
    ],
    [HookEventName.SubagentStart]: [
      { code: 0, description: t4("stdout shown to subagent") },
      {
        code: "Other",
        description: t4("show stderr to user only (blocking errors ignored)")
      }
    ],
    [HookEventName.SubagentStop]: [
      { code: 0, description: t4("stdout/stderr not shown") },
      {
        code: 2,
        description: t4("show stderr to subagent and continue having it run")
      },
      { code: "Other", description: t4("show stderr to user only") }
    ],
    [HookEventName.PreCompact]: [
      {
        code: 0,
        description: t4("stdout appended as custom compact instructions")
      },
      { code: 2, description: t4("block compaction") },
      {
        code: "Other",
        description: t4("show stderr to user only but continue with compaction")
      }
    ],
    [HookEventName.PermissionRequest]: [
      { code: 0, description: t4("use hook decision if provided") },
      { code: "Other", description: t4("show stderr to user only") }
    ]
  };
  return exitCodesMap[eventName] || [];
}
__name(getHookExitCodes, "getHookExitCodes");
function getHookShortDescription(eventName) {
  const descriptions = {
    [HookEventName.PreToolUse]: t4("Before tool execution"),
    [HookEventName.PostToolUse]: t4("After tool execution"),
    [HookEventName.PostToolUseFailure]: t4("After tool execution fails"),
    [HookEventName.Notification]: t4("When notifications are sent"),
    [HookEventName.UserPromptSubmit]: t4("When the user submits a prompt"),
    [HookEventName.SessionStart]: t4("When a new session is started"),
    [HookEventName.Stop]: t4("Right before Qwen Code concludes its response"),
    [HookEventName.SubagentStart]: t4(
      "When a subagent (Agent tool call) is started"
    ),
    [HookEventName.SubagentStop]: t4(
      "Right before a subagent concludes its response"
    ),
    [HookEventName.PreCompact]: t4("Before conversation compaction"),
    [HookEventName.SessionEnd]: t4("When a session is ending"),
    [HookEventName.PermissionRequest]: t4(
      "When a permission dialog is displayed"
    )
  };
  return descriptions[eventName] || "";
}
__name(getHookShortDescription, "getHookShortDescription");
function getHookDescription(eventName) {
  const descriptions = {
    [HookEventName.Stop]: "",
    [HookEventName.PreToolUse]: t4(
      "Input to command is JSON of tool call arguments."
    ),
    [HookEventName.PostToolUse]: t4(
      'Input to command is JSON with fields "inputs" (tool call arguments) and "response" (tool call response).'
    ),
    [HookEventName.PostToolUseFailure]: t4(
      "Input to command is JSON with tool_name, tool_input, tool_use_id, error, error_type, is_interrupt, and is_timeout."
    ),
    [HookEventName.Notification]: t4(
      "Input to command is JSON with notification message and type."
    ),
    [HookEventName.UserPromptSubmit]: t4(
      "Input to command is JSON with original user prompt text."
    ),
    [HookEventName.SessionStart]: t4(
      "Input to command is JSON with session start source."
    ),
    [HookEventName.SessionEnd]: t4(
      "Input to command is JSON with session end reason."
    ),
    [HookEventName.SubagentStart]: t4(
      "Input to command is JSON with agent_id and agent_type."
    ),
    [HookEventName.SubagentStop]: t4(
      "Input to command is JSON with agent_id, agent_type, and agent_transcript_path."
    ),
    [HookEventName.PreCompact]: t4(
      "Input to command is JSON with compaction details."
    ),
    [HookEventName.PermissionRequest]: t4(
      "Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny."
    )
  };
  return descriptions[eventName] || "";
}
__name(getHookDescription, "getHookDescription");
function getTranslatedSourceDisplayMap() {
  return {
    [HooksConfigSource.Project]: t4("Local Settings"),
    [HooksConfigSource.User]: t4("User Settings"),
    [HooksConfigSource.System]: t4("System Settings"),
    [HooksConfigSource.Extensions]: t4("Extensions"),
    [HooksConfigSource.Session]: t4("Session (temporary)")
  };
}
__name(getTranslatedSourceDisplayMap, "getTranslatedSourceDisplayMap");
var DISPLAY_HOOK_EVENTS = Object.values(HookEventName);
function createEmptyHookEventInfo(eventName) {
  return {
    event: eventName,
    shortDescription: getHookShortDescription(eventName),
    description: getHookDescription(eventName),
    exitCodes: getHookExitCodes(eventName),
    configs: []
  };
}
__name(createEmptyHookEventInfo, "createEmptyHookEventInfo");

// packages/cli/src/ui/components/hooks/HookDetailStep.tsx
init_i18n();
var import_jsx_runtime113 = __toESM(require_jsx_runtime(), 1);
function HookDetailStep({
  hook,
  selectedIndex
}) {
  const hasConfigs = hook.configs.length > 0;
  const { columns: terminalWidth } = useTerminalSize();
  const sourceDisplayMap = getTranslatedSourceDisplayMap();
  const commandWidth = Math.floor(terminalWidth * 0.65);
  const sourceWidth = Math.floor(terminalWidth * 0.3);
  const getConfigSourceDisplay = /* @__PURE__ */ __name((config2) => {
    if (config2.source === HooksConfigSource.Extensions) {
      return `${sourceDisplayMap[HooksConfigSource.Extensions]} (${config2.sourceDisplay})`;
    }
    return sourceDisplayMap[config2.source] || config2.source;
  }, "getConfigSourceDisplay");
  return /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text3, { bold: true, color: theme.text.primary, children: hook.event }) }),
    hook.description && /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text3, { color: theme.text.secondary, children: hook.description }) }),
    hook.exitCodes.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Exit codes:") }),
      hook.exitCodes.map((ec, index) => /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text3, { color: theme.text.secondary, children: `  ${ec.code}: ${ec.description}` }) }, index))
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { marginTop: 1 }),
    hasConfigs ? /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(import_jsx_runtime113.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Configured hooks:") }),
      hook.configs.map((config2, index) => {
        const isSelected = index === selectedIndex;
        const sourceDisplay = getConfigSourceDisplay(config2);
        let hookDisplay = "";
        const hookType = config2.config.type;
        if (hookType === HookType.Command) {
          hookDisplay = config2.config.command || "";
        } else if (hookType === HookType.Http) {
          hookDisplay = config2.config.name || config2.config.url || "";
        } else if (hookType === HookType.Function) {
          hookDisplay = config2.config.name || config2.config.id || "function-hook";
        }
        const isAsync2 = hookType === HookType.Command && config2.config.async === true;
        const typeDisplay = isAsync2 ? `${hookType} async` : String(hookType);
        return /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(Box_default, { width: commandWidth, children: [
            /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { minWidth: 2, children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(
              Text3,
              {
                color: isSelected ? theme.text.accent : theme.text.primary,
                children: isSelected ? "\u276F" : " "
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(
              Text3,
              {
                color: isSelected ? theme.text.accent : theme.text.primary,
                bold: isSelected,
                wrap: "wrap",
                children: `${index + 1}. [${typeDisplay}] ${hookDisplay}`
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { width: 2 }),
          /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { width: sourceWidth, children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text3, { color: theme.text.secondary, wrap: "wrap", children: sourceDisplay }) })
        ] }, index);
      }),
      /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to select \xB7 Esc to go back") }) })
    ] }) : /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(import_jsx_runtime113.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text3, { color: theme.text.secondary, children: t4("No hooks configured for this event.") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text3, { color: theme.text.secondary, children: t4("To add hooks, edit settings.json directly or ask Qwen.") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text3, { color: theme.text.secondary, children: t4("Esc to go back") }) })
    ] })
  ] });
}
__name(HookDetailStep, "HookDetailStep");

// packages/cli/src/ui/components/hooks/HookConfigDetailStep.tsx
init_esbuild_shims();
init_dist4();
init_i18n();
var import_jsx_runtime114 = __toESM(require_jsx_runtime(), 1);
function HookConfigDetailStep({
  hookEvent,
  hookConfig
}) {
  const { columns: terminalWidth } = useTerminalSize();
  const getSourceDisplay = /* @__PURE__ */ __name(() => {
    switch (hookConfig.source) {
      case HooksConfigSource.Project:
        return t4("Local Settings");
      case HooksConfigSource.User:
        return t4("User Settings");
      case HooksConfigSource.System:
        return t4("System Settings");
      case HooksConfigSource.Extensions:
        return t4("Extensions");
      default:
        return hookConfig.source;
    }
  }, "getSourceDisplay");
  const isFromExtension = hookConfig.source === HooksConfigSource.Extensions;
  const getHookTypeDisplay = /* @__PURE__ */ __name(() => {
    switch (hookConfig.config.type) {
      case "command":
        return "command";
      default:
        return hookConfig.config.type;
    }
  }, "getHookTypeDisplay");
  const getCommand = /* @__PURE__ */ __name(() => {
    if (hookConfig.config.type === "command") {
      return hookConfig.config.command;
    }
    return "";
  }, "getCommand");
  const commandBoxWidth = Math.min(terminalWidth - 6, 80);
  const labelWidth = 12;
  return /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Hook details") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { width: labelWidth, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.secondary, children: t4("Event:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.primary, children: hookEvent.event })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { width: labelWidth, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.secondary, children: t4("Type:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.primary, children: getHookTypeDisplay() })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { width: labelWidth, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.secondary, children: t4("Source:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.primary, children: getSourceDisplay() }),
      hookConfig.sourcePath && /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(Text3, { color: theme.text.secondary, children: [
        " (",
        hookConfig.sourcePath,
        ")"
      ] })
    ] }),
    isFromExtension && hookConfig.sourceDisplay && /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { width: labelWidth, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.secondary, children: t4("Extension:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.primary, children: hookConfig.sourceDisplay })
    ] }),
    hookConfig.config.name && /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { width: labelWidth, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.secondary, children: t4("Name:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.primary, children: hookConfig.config.name })
    ] }),
    hookConfig.config.description && /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { width: labelWidth, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.secondary, children: t4("Desc:") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.primary, children: hookConfig.config.description })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.secondary, children: t4("Command:") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(
      Box_default,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingX: 1,
        width: commandBoxWidth,
        children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.primary, children: getCommand() })
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.secondary, children: t4(
      "To modify or remove this hook, edit settings.json directly or ask Qwen to help."
    ) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text3, { color: theme.text.secondary, children: t4("Esc to go back") }) })
  ] });
}
__name(HookConfigDetailStep, "HookConfigDetailStep");

// packages/cli/src/ui/components/hooks/HooksDisabledStep.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime115 = __toESM(require_jsx_runtime(), 1);
function HooksDisabledStep({
  configuredHooksCount
}) {
  const hooksText = configuredHooksCount === 1 ? t4("{{count}} configured hook", { count: String(configuredHooksCount) }) : t4("{{count}} configured hooks", {
    count: String(configuredHooksCount)
  });
  return /* @__PURE__ */ (0, import_jsx_runtime115.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Text3, { bold: true, color: theme.status.warning, children: t4("Hook Configuration - Disabled") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Text3, { color: theme.text.primary, children: t4(
      "All hooks are currently disabled. You have {{count}} that are not running.",
      {
        count: hooksText
      }
    ) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime115.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("When hooks are disabled:") }),
      /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Text3, { color: theme.text.secondary, children: `  \xB7 ${t4("No hook commands will execute")}` }) }),
      /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Text3, { color: theme.text.secondary, children: `  \xB7 ${t4("StatusLine will not be displayed")}` }) }),
      /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Text3, { color: theme.text.secondary, children: `  \xB7 ${t4("Tool operations will proceed without hook validation")}` }) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Text3, { color: theme.text.secondary, children: t4(
      'To re-enable hooks, remove "disableAllHooks" from settings.json or ask Qwen Code.'
    ) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Text3, { color: theme.text.secondary, children: t4("Esc to close") }) })
  ] });
}
__name(HooksDisabledStep, "HooksDisabledStep");

// packages/cli/src/ui/components/hooks/HooksManagementDialog.tsx
init_i18n();
var import_jsx_runtime116 = __toESM(require_jsx_runtime(), 1);
var debugLogger150 = createDebugLogger("HOOKS_DIALOG");
function isValidHookConfig(config2) {
  if (typeof config2 !== "object" || config2 === null || !("type" in config2)) {
    return false;
  }
  const obj = config2;
  if (obj["type"] === "command") {
    return "command" in obj && typeof obj["command"] === "string";
  }
  if (obj["type"] === "http") {
    return "url" in obj && typeof obj["url"] === "string";
  }
  if (obj["type"] === "function") {
    return "callback" in obj && typeof obj["callback"] === "function";
  }
  return false;
}
__name(isValidHookConfig, "isValidHookConfig");
function isValidHookDefinition(def2) {
  if (typeof def2 !== "object" || def2 === null) {
    return false;
  }
  const obj = def2;
  if (!("hooks" in obj) || !Array.isArray(obj["hooks"])) {
    return false;
  }
  for (const hook of obj["hooks"]) {
    if (!isValidHookConfig(hook)) {
      return false;
    }
  }
  if ("matcher" in obj && typeof obj["matcher"] !== "string") {
    return false;
  }
  if ("sequential" in obj && typeof obj["sequential"] !== "boolean") {
    return false;
  }
  return true;
}
__name(isValidHookDefinition, "isValidHookDefinition");
function isValidHooksRecord(hooks) {
  if (typeof hooks !== "object" || hooks === null) {
    return false;
  }
  const record2 = hooks;
  for (const [key, value] of Object.entries(record2)) {
    if (HOOKS_CONFIG_FIELDS.includes(key)) {
      continue;
    }
    if (!Array.isArray(value)) {
      return false;
    }
    for (const def2 of value) {
      if (!isValidHookDefinition(def2)) {
        return false;
      }
    }
  }
  return true;
}
__name(isValidHooksRecord, "isValidHooksRecord");
function HooksManagementDialog({
  onClose
}) {
  const config2 = useConfig();
  const { columns: width } = useTerminalSize();
  const boxWidth = width - 4;
  const disableAllHooks = config2?.getDisableAllHooks() ?? false;
  const [navigationStack, setNavigationStack] = (0, import_react110.useState)([
    disableAllHooks ? HOOKS_MANAGEMENT_STEPS.HOOKS_DISABLED : HOOKS_MANAGEMENT_STEPS.HOOKS_LIST
  ]);
  const [selectedHookIndex, setSelectedHookIndex] = (0, import_react110.useState)(-1);
  const [selectedConfigIndex, setSelectedConfigIndex] = (0, import_react110.useState)(-1);
  const [listSelectedIndex, setListSelectedIndex] = (0, import_react110.useState)(0);
  const [detailSelectedIndex, setDetailSelectedIndex] = (0, import_react110.useState)(0);
  const [hooks, setHooks] = (0, import_react110.useState)([]);
  const [isLoading, setIsLoading] = (0, import_react110.useState)(true);
  const [loadError, setLoadError] = (0, import_react110.useState)(null);
  const currentStep = navigationStack[navigationStack.length - 1] || HOOKS_MANAGEMENT_STEPS.HOOKS_LIST;
  const selectedHook = (0, import_react110.useMemo)(() => {
    if (selectedHookIndex >= 0 && selectedHookIndex < hooks.length) {
      return hooks[selectedHookIndex];
    }
    return null;
  }, [hooks, selectedHookIndex]);
  useKeypress(
    (key) => {
      if (isLoading || loadError) {
        if (key.name === "escape") {
          onClose();
        }
        return;
      }
      switch (currentStep) {
        case HOOKS_MANAGEMENT_STEPS.HOOKS_DISABLED:
          if (key.name === "escape") {
            onClose();
          }
          break;
        case HOOKS_MANAGEMENT_STEPS.HOOKS_LIST:
          if (key.name === "up") {
            setListSelectedIndex((prev) => Math.max(0, prev - 1));
          } else if (key.name === "down") {
            setListSelectedIndex(
              (prev) => Math.min(hooks.length - 1, prev + 1)
            );
          } else if (key.name === "return") {
            if (hooks.length > 0 && listSelectedIndex >= 0) {
              setSelectedHookIndex(listSelectedIndex);
              setSelectedConfigIndex(-1);
              setDetailSelectedIndex(0);
              setNavigationStack((prev) => [
                ...prev,
                HOOKS_MANAGEMENT_STEPS.HOOK_DETAIL
              ]);
            }
          } else if (key.name === "escape") {
            onClose();
          }
          break;
        case HOOKS_MANAGEMENT_STEPS.HOOK_DETAIL:
          if (key.name === "escape") {
            handleNavigateBack();
          } else if (selectedHook && selectedHook.configs.length > 0) {
            if (key.name === "up") {
              setDetailSelectedIndex((prev) => Math.max(0, prev - 1));
            } else if (key.name === "down") {
              setDetailSelectedIndex(
                (prev) => Math.min(selectedHook.configs.length - 1, prev + 1)
              );
            } else if (key.name === "return") {
              setSelectedConfigIndex(detailSelectedIndex);
              setNavigationStack((prev) => [
                ...prev,
                HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL
              ]);
            }
          }
          break;
        case HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL:
          if (key.name === "escape") {
            handleNavigateBack();
          }
          break;
        default:
          break;
      }
    },
    { isActive: true }
  );
  const fetchHooksData = (0, import_react110.useCallback)(() => {
    if (!config2) return [];
    const settings = loadSettings();
    const userSettings = settings.forScope("User" /* User */).settings;
    const workspaceSettings = settings.forScope(
      "Workspace" /* Workspace */
    ).settings;
    const sourceDisplayMap = getTranslatedSourceDisplayMap();
    const result = [];
    for (const eventName of DISPLAY_HOOK_EVENTS) {
      const hookInfo = createEmptyHookEventInfo(eventName);
      const userSettingsRecord = userSettings;
      const userHooksRaw = userSettingsRecord?.["hooks"];
      if (isValidHooksRecord(userHooksRaw) && userHooksRaw[eventName]) {
        for (const def2 of userHooksRaw[eventName]) {
          for (const hookConfig of def2.hooks) {
            hookInfo.configs.push({
              config: hookConfig,
              source: HooksConfigSource.User,
              sourceDisplay: sourceDisplayMap[HooksConfigSource.User],
              enabled: true
            });
          }
        }
      }
      const workspaceSettingsRecord = workspaceSettings;
      const workspaceHooksRaw = workspaceSettingsRecord?.["hooks"];
      if (isValidHooksRecord(workspaceHooksRaw) && workspaceHooksRaw[eventName]) {
        for (const def2 of workspaceHooksRaw[eventName]) {
          for (const hookConfig of def2.hooks) {
            hookInfo.configs.push({
              config: hookConfig,
              source: HooksConfigSource.Project,
              sourceDisplay: sourceDisplayMap[HooksConfigSource.Project],
              enabled: true
            });
          }
        }
      }
      const extensions = config2.getExtensions() || [];
      for (const extension of extensions) {
        if (extension.isActive && extension.hooks?.[eventName]) {
          const extensionHooks = extension.hooks[eventName];
          if (Array.isArray(extensionHooks)) {
            for (const def2 of extensionHooks) {
              if (isValidHookDefinition(def2)) {
                for (const hookConfig of def2.hooks) {
                  hookInfo.configs.push({
                    config: hookConfig,
                    source: HooksConfigSource.Extensions,
                    sourceDisplay: extension.name,
                    sourcePath: extension.path,
                    enabled: true
                  });
                }
              }
            }
          }
        }
      }
      const hookSystem = config2.getHookSystem();
      if (hookSystem) {
        const sessionId = config2.getSessionId();
        if (sessionId) {
          const sessionHooksManager = hookSystem.getSessionHooksManager();
          const allSessionHooks = sessionHooksManager.getAllSessionHooks(sessionId);
          const eventSessionHooks = allSessionHooks.filter(
            (hook) => hook.eventName === eventName
          );
          for (const sessionHook of eventSessionHooks) {
            hookInfo.configs.push({
              config: sessionHook.config,
              source: HooksConfigSource.Session,
              sourceDisplay: t4("Session (temporary)"),
              matcher: sessionHook.matcher,
              enabled: true
            });
          }
        }
      }
      result.push(hookInfo);
    }
    return result;
  }, [config2]);
  (0, import_react110.useEffect)(() => {
    let cancelled = false;
    setIsLoading(true);
    setLoadError(null);
    try {
      debugLogger150.debug("Fetching hooks data for dialog");
      const hooksData = fetchHooksData();
      debugLogger150.debug("Hooks data fetched:", hooksData.length, "events");
      if (!cancelled) {
        setHooks(hooksData);
      }
    } catch (error40) {
      if (!cancelled) {
        debugLogger150.error("Error loading hooks:", error40);
        setLoadError(
          error40 instanceof Error ? error40.message : "Failed to load hooks"
        );
      }
    } finally {
      if (!cancelled) {
        setIsLoading(false);
      }
    }
    return () => {
      cancelled = true;
    };
  }, [fetchHooksData]);
  const handleNavigateBack = (0, import_react110.useCallback)(() => {
    setNavigationStack((prev) => {
      if (prev.length <= 1) {
        onClose();
        return prev;
      }
      return prev.slice(0, -1);
    });
  }, [onClose]);
  const selectedConfig = (0, import_react110.useMemo)(() => {
    if (selectedHook && selectedConfigIndex >= 0 && selectedConfigIndex < selectedHook.configs.length) {
      return selectedHook.configs[selectedConfigIndex];
    }
    return null;
  }, [selectedHook, selectedConfigIndex]);
  const configuredHooksCount = (0, import_react110.useMemo)(
    () => hooks.reduce((sum, hook) => sum + hook.configs.length, 0),
    [hooks]
  );
  const renderContent = /* @__PURE__ */ __name(() => {
    if (currentStep === HOOKS_MANAGEMENT_STEPS.HOOKS_DISABLED) {
      return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(HooksDisabledStep, { configuredHooksCount });
    }
    if (isLoading) {
      return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Box_default, { flexDirection: "column", paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Text3, { color: theme.text.secondary, children: t4("Loading hooks...") }) });
    }
    if (loadError) {
      return /* @__PURE__ */ (0, import_jsx_runtime116.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Text3, { color: theme.status.error, children: t4("Error loading hooks:") }),
        /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Text3, { color: theme.text.secondary, children: loadError }),
        /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Text3, { color: theme.text.secondary, children: t4("Press Escape to close") }) })
      ] });
    }
    switch (currentStep) {
      case HOOKS_MANAGEMENT_STEPS.HOOKS_LIST:
        return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(HooksListStep, { hooks, selectedIndex: listSelectedIndex });
      case HOOKS_MANAGEMENT_STEPS.HOOK_DETAIL:
        if (selectedHook) {
          return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(
            HookDetailStep,
            {
              hook: selectedHook,
              selectedIndex: detailSelectedIndex
            }
          );
        }
        return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Box_default, { flexDirection: "column", paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Text3, { color: theme.text.secondary, children: t4("No hook selected") }) });
      case HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL:
        if (selectedHook && selectedConfig) {
          return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(
            HookConfigDetailStep,
            {
              hookEvent: selectedHook,
              hookConfig: selectedConfig
            }
          );
        }
        return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Box_default, { flexDirection: "column", paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Text3, { color: theme.text.secondary, children: t4("No hook config selected") }) });
      default:
        return null;
    }
  }, "renderContent");
  return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.border.default,
      width: boxWidth,
      paddingX: 1,
      paddingY: 1,
      children: renderContent()
    }
  );
}
__name(HooksManagementDialog, "HooksManagementDialog");

// packages/cli/src/ui/components/SessionPicker.tsx
init_esbuild_shims();

// packages/cli/src/ui/hooks/useSessionPicker.ts
init_esbuild_shims();
var import_react111 = __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,
  initialSessions,
  isActive = true,
  enablePreview = false
}) {
  const hasInitialSessions = initialSessions !== void 0;
  const [selectedIndex, setSelectedIndex] = (0, import_react111.useState)(0);
  const [sessionState, setSessionState] = (0, import_react111.useState)(
    hasInitialSessions ? { sessions: initialSessions, hasMore: false, nextCursor: void 0 } : { sessions: [], hasMore: true, nextCursor: void 0 }
  );
  const [filterByBranch, setFilterByBranch] = (0, import_react111.useState)(false);
  const [isLoading, setIsLoading] = (0, import_react111.useState)(!hasInitialSessions);
  const [followScrollOffset, setFollowScrollOffset] = (0, import_react111.useState)(0);
  const [viewMode, setViewMode] = (0, import_react111.useState)("list");
  const [previewSessionId, setPreviewSessionId] = (0, import_react111.useState)(null);
  const exitPreview = (0, import_react111.useCallback)(() => {
    setViewMode("list");
    setPreviewSessionId(null);
  }, []);
  const isLoadingMoreRef = (0, import_react111.useRef)(false);
  const filteredSessions = (0, import_react111.useMemo)(
    () => filterSessions(sessionState.sessions, filterByBranch, currentBranch),
    [sessionState.sessions, filterByBranch, currentBranch]
  );
  const scrollOffset = (0, import_react111.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_react111.useMemo)(
    () => filteredSessions.slice(scrollOffset, scrollOffset + maxVisibleItems),
    [filteredSessions, maxVisibleItems, scrollOffset]
  );
  const showScrollUp = scrollOffset > 0;
  const showScrollDown = scrollOffset + maxVisibleItems < filteredSessions.length;
  (0, import_react111.useEffect)(() => {
    if (!sessionService || hasInitialSessions) {
      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, hasInitialSessions]);
  const loadMoreSessions = (0, import_react111.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_react111.useEffect)(() => {
    setSelectedIndex(0);
    setFollowScrollOffset(0);
  }, [filterByBranch]);
  (0, import_react111.useEffect)(() => {
    if (selectedIndex >= filteredSessions.length && filteredSessions.length > 0) {
      setSelectedIndex(filteredSessions.length - 1);
    }
  }, [filteredSessions.length, selectedIndex]);
  (0, import_react111.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) => {
      if (viewMode !== "list") {
        return;
      }
      const { name: name4, sequence, ctrl } = key;
      if (name4 === "escape" || ctrl && name4 === "c") {
        onCancel();
        return;
      }
      if (name4 === "return") {
        const session = filteredSessions[selectedIndex];
        if (session) {
          onSelect(session.sessionId);
        }
        return;
      }
      if (name4 === "up" || name4 === "k") {
        setSelectedIndex((prev) => {
          const newIndex = Math.max(0, prev - 1);
          if (!centerSelection && newIndex < followScrollOffset) {
            setFollowScrollOffset(newIndex);
          }
          return newIndex;
        });
        return;
      }
      if (name4 === "down" || name4 === "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 (name4 === "space" && enablePreview) {
        const session = filteredSessions[selectedIndex];
        if (session) {
          setPreviewSessionId(session.sessionId);
          setViewMode("preview");
        }
        return;
      }
      if (sequence === "b" || sequence === "B") {
        if (currentBranch) {
          setFilterByBranch((prev) => !prev);
        }
      }
    },
    { isActive: isActive && viewMode === "list" }
  );
  return {
    selectedIndex,
    sessionState,
    filteredSessions,
    filterByBranch,
    isLoading,
    scrollOffset,
    visibleSessions,
    showScrollUp,
    showScrollDown,
    loadMoreSessions,
    viewMode,
    previewSessionId,
    exitPreview
  };
}
__name(useSessionPicker, "useSessionPicker");

// packages/cli/src/ui/components/SessionPicker.tsx
init_i18n();

// packages/cli/src/ui/components/SessionPreview.tsx
init_esbuild_shims();
var import_react112 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/resumeHistoryUtils.ts
init_esbuild_shims();
init_types22();
import * as path130 from "node:path";
function extractTextFromParts(parts2) {
  if (!parts2) return "";
  const textParts = [];
  for (const part of parts2) {
    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(parts2) {
  if (!parts2) return "";
  const thoughtParts = [];
  for (const part of parts2) {
    if ("text" in part && part.text && "thought" in part && part.thought) {
      thoughtParts.push(part.text);
    }
  }
  return thoughtParts.join("\n");
}
__name(extractThoughtTextFromParts, "extractThoughtTextFromParts");
function extractFunctionCalls(parts2) {
  if (!parts2) return [];
  const calls = [];
  for (const part of parts2) {
    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, name4) {
  if (!config2) return void 0;
  const toolRegistry = config2.getToolRegistry();
  return toolRegistry.getTool(name4);
}
__name(getTool, "getTool");
function formatToolDescription(tool, args2) {
  try {
    const invocation = tool.build(args2);
    return invocation.getDescription();
  } catch {
    if (typeof args2["description"] === "string") {
      return args2["description"];
    }
    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 ${path130.basename(filePath)}` : `Read file ${path130.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);
      }
      if (record2.subtype === "rewind") {
        items.push({ type: "info", text: "Conversation rewound." });
      }
      continue;
    }
    switch (record2.type) {
      case "user": {
        if (record2.subtype === "notification" || record2.subtype === "cron") {
          const payload = record2.systemPayload;
          const fallback = record2.subtype === "cron" ? "Cron job fired" : "Background agent completed";
          const text2 = payload?.displayText || extractTextFromParts(record2.message?.parts) || fallback;
          items.push({ type: "notification", text: text2 });
          break;
        }
        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 parts2 = record2.message?.parts;
        const thoughtText = !config2 || !config2.getContentGenerator().useSummarizedThinking() ? extractThoughtTextFromParts(parts2) : "";
        const text = extractTextFromParts(parts2);
        const functionCalls = extractFunctionCalls(parts2);
        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/components/SessionPreview.tsx
init_i18n();
var import_jsx_runtime117 = __toESM(require_jsx_runtime(), 1);
function SessionPreview(props) {
  const {
    sessionService,
    sessionId,
    sessionTitle,
    messageCount,
    mtime,
    gitBranch,
    onExit,
    onResume
  } = props;
  const { columns } = useTerminalSize();
  const [data, setData] = (0, import_react112.useState)(null);
  const [error40, setError] = (0, import_react112.useState)(null);
  (0, import_react112.useEffect)(() => {
    let cancelled = false;
    setData(null);
    setError(null);
    sessionService.loadSession(sessionId).then((d2) => {
      if (cancelled) return;
      if (!d2) {
        setError("Session not found");
        return;
      }
      setData(d2);
    }).catch((e4) => {
      if (cancelled) return;
      setError(e4 instanceof Error ? e4.message : String(e4));
    });
    return () => {
      cancelled = true;
    };
  }, [sessionService, sessionId]);
  const items = (0, import_react112.useMemo)(() => {
    if (!data) return [];
    return buildResumedHistoryItems(data, null);
  }, [data]);
  useKeypress(
    (key) => {
      const { name: name4, ctrl } = key;
      if (name4 === "escape" || ctrl && name4 === "c") {
        onExit();
        return;
      }
      if (name4 === "return") {
        onResume(sessionId);
      }
    },
    { isActive: true }
  );
  const boxWidth = Math.max(10, columns - 4);
  const separatorWidth = Math.max(0, boxWidth - 2);
  const metaParts = [];
  if (typeof messageCount === "number") {
    metaParts.push(formatMessageCount(messageCount));
  }
  if (typeof mtime === "number") {
    metaParts.push(formatRelativeTime(mtime));
  }
  if (gitBranch) {
    metaParts.push(gitBranch);
  }
  const metaLine = metaParts.join(" \xB7 ");
  return /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(Box_default, { flexDirection: "column", width: boxWidth, children: [
    /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text3, { bold: true, color: theme.text.primary, children: sessionTitle ?? t4("Session Preview") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(separatorWidth) }) }),
    error40 ? /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { paddingY: 1, justifyContent: "center", children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text3, { color: theme.status.error, children: error40 }) }) : !data ? /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { paddingY: 1, justifyContent: "center", children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text3, { color: theme.text.secondary, children: t4("Loading session preview...") }) }) : /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { flexDirection: "column", children: items.map((item) => /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(
      HistoryItemDisplayComponent,
      {
        item,
        terminalWidth: boxWidth,
        isPending: false
      },
      item.id
    )) }),
    /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(separatorWidth) }) }),
    metaLine && /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text3, { color: theme.text.secondary, children: metaLine }) }),
    /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to resume \xB7 Esc to back") }) })
  ] });
}
__name(SessionPreview, "SessionPreview");

// packages/cli/src/ui/components/SessionPicker.tsx
var import_jsx_runtime118 = __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.customTitle || session.prompt || "(empty prompt)";
  const truncatedPrompt = truncateText(promptText, maxPromptWidth);
  const isAutoTitle = session.titleSource === "auto" && Boolean(session.customTitle);
  return /* @__PURE__ */ (0, import_jsx_runtime118.jsxs)(Box_default, { flexDirection: "column", marginBottom: isLast ? 0 : 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime118.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(
        Text3,
        {
          color: isSelected ? theme.text.accent : showUpIndicator || showDownIndicator ? theme.text.secondary : void 0,
          bold: isSelected && boldSelectedPrefix,
          children: prefix
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(
        Text3,
        {
          color: isSelected ? theme.text.accent : isAutoTitle ? theme.text.secondary : theme.text.primary,
          bold: isSelected,
          children: truncatedPrompt
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Box_default, { paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime118.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,
    title,
    centerSelection = true,
    initialSessions,
    enablePreview = false
  } = 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,
    initialSessions,
    isActive: true,
    enablePreview
  });
  if (enablePreview && picker.viewMode === "preview" && picker.previewSessionId && sessionService) {
    const previewed = picker.filteredSessions.find(
      (s5) => s5.sessionId === picker.previewSessionId
    );
    return /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(
      SessionPreview,
      {
        sessionService,
        sessionId: picker.previewSessionId,
        sessionTitle: previewed?.customTitle ?? previewed?.prompt ?? void 0,
        messageCount: previewed?.messageCount,
        mtime: previewed?.mtime,
        gitBranch: previewed?.gitBranch,
        onExit: picker.exitPreview,
        onResume: onSelect
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(
    Box_default,
    {
      flexDirection: "column",
      width: boxWidth,
      height: height - 1,
      overflow: "hidden",
      children: /* @__PURE__ */ (0, import_jsx_runtime118.jsxs)(
        Box_default,
        {
          flexDirection: "column",
          borderStyle: "round",
          borderColor: theme.border.default,
          width: boxWidth,
          height: height - 1,
          overflow: "hidden",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime118.jsxs)(Box_default, { paddingX: 1, children: [
              /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Text3, { bold: true, color: theme.text.primary, children: title ?? t4("Resume Session") }),
              picker.filterByBranch && currentBranch && /* @__PURE__ */ (0, import_jsx_runtime118.jsxs)(Text3, { color: theme.text.secondary, children: [
                " ",
                t4("(branch: {{branch}})", { branch: currentBranch })
              ] })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(boxWidth - 2) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Box_default, { flexDirection: "column", flexGrow: 1, paddingX: 1, overflow: "hidden", children: !sessionService || picker.isLoading ? /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Box_default, { paddingY: 1, justifyContent: "center", children: /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Text3, { color: theme.text.secondary, children: t4("Loading sessions...") }) }) : picker.filteredSessions.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Box_default, { paddingY: 1, justifyContent: "center", children: /* @__PURE__ */ (0, import_jsx_runtime118.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_runtime118.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_runtime118.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(boxWidth - 2) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime118.jsxs)(Box_default, { flexDirection: "row", children: [
              currentBranch && /* @__PURE__ */ (0, import_jsx_runtime118.jsxs)(Text3, { color: theme.text.secondary, children: [
                /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(
                  Text3,
                  {
                    bold: picker.filterByBranch,
                    color: picker.filterByBranch ? theme.text.accent : void 0,
                    children: "B"
                  }
                ),
                t4(" to toggle branch \xB7 ")
              ] }),
              enablePreview && /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Text3, { color: theme.text.secondary, children: t4("Space to preview \xB7 ") }),
              /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Text3, { color: theme.text.secondary, children: t4("\u2191\u2193 to navigate \xB7 Esc to cancel") })
            ] }) })
          ]
        }
      )
    }
  );
}
__name(SessionPicker, "SessionPicker");

// packages/cli/src/ui/components/RewindSelector.tsx
init_esbuild_shims();
var import_react113 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/historyMapping.ts
init_esbuild_shims();
function isRealUserTurn(item) {
  if (item.type !== "user" || !item.text) return false;
  return !item.text.startsWith("/") && !item.text.startsWith("?");
}
__name(isRealUserTurn, "isRealUserTurn");
var STARTUP_CONTEXT_MODEL_ACK2 = "Got it. Thanks for the context!";
function isUserTextContent(content) {
  if (content.role !== "user") return false;
  if (!content.parts || content.parts.length === 0) return false;
  const hasFunctionResponse = content.parts.some(
    (part) => "functionResponse" in part
  );
  if (hasFunctionResponse) return false;
  return content.parts.some((part) => "text" in part && part.text);
}
__name(isUserTextContent, "isUserTextContent");
function hasStartupContext(apiHistory) {
  if (apiHistory.length < 2) return false;
  const first2 = apiHistory[0];
  const second = apiHistory[1];
  if (first2?.role !== "user" || second?.role !== "model") return false;
  return second.parts?.some(
    (part) => "text" in part && part.text === STARTUP_CONTEXT_MODEL_ACK2
  ) ?? false;
}
__name(hasStartupContext, "hasStartupContext");
function computeApiTruncationIndex(uiHistory, targetUserItemId, apiHistory) {
  let uiUserTurnCount = 0;
  for (const item of uiHistory) {
    if (item.id === targetUserItemId) {
      break;
    }
    if (isRealUserTurn(item)) {
      uiUserTurnCount++;
    }
  }
  const startIndex = hasStartupContext(apiHistory) ? 2 : 0;
  if (uiUserTurnCount === 0) {
    return startIndex;
  }
  let realUserPromptCount = 0;
  for (let i4 = startIndex; i4 < apiHistory.length; i4++) {
    if (isUserTextContent(apiHistory[i4])) {
      realUserPromptCount++;
      if (realUserPromptCount > uiUserTurnCount) {
        return i4;
      }
    }
  }
  return -1;
}
__name(computeApiTruncationIndex, "computeApiTruncationIndex");

// packages/cli/src/ui/components/RewindSelector.tsx
init_i18n();
var import_jsx_runtime119 = __toESM(require_jsx_runtime(), 1);
var MAX_VISIBLE_ITEMS2 = 7;
function getUserTurns(history) {
  return history.filter(isRealUserTurn);
}
__name(getUserTurns, "getUserTurns");
function TurnItemView({
  item,
  isSelected,
  isFirst,
  isLast,
  showScrollUp,
  showScrollDown,
  maxPromptWidth,
  turnNumber
}) {
  const showUpIndicator = isFirst && showScrollUp;
  const showDownIndicator = isLast && showScrollDown;
  const prefix = isSelected ? "\u203A " : showUpIndicator ? "\u2191 " : showDownIndicator ? "\u2193 " : "  ";
  const promptText = item.text || "(empty prompt)";
  const truncatedPrompt = truncateText(promptText, maxPromptWidth);
  return /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { flexDirection: "column", marginBottom: isLast ? 0 : 1, children: /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
      Text3,
      {
        color: isSelected ? theme.text.accent : showUpIndicator || showDownIndicator ? theme.text.secondary : void 0,
        bold: isSelected,
        children: prefix
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.text.secondary, children: `#${turnNumber} ` }),
    /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
      Text3,
      {
        color: isSelected ? theme.text.accent : theme.text.primary,
        bold: isSelected,
        children: truncatedPrompt
      }
    )
  ] }) });
}
__name(TurnItemView, "TurnItemView");
function RewindSelector({
  history,
  onRewind,
  onCancel
}) {
  const { columns: width, rows: height } = useTerminalSize();
  const userTurns = (0, import_react113.useMemo)(() => getUserTurns(history), [history]);
  const [selectedIndex, setSelectedIndex] = (0, import_react113.useState)(userTurns.length - 1);
  const [confirmItem, setConfirmItem] = (0, import_react113.useState)(null);
  const boxWidth = width - 4;
  const maxVisibleItems = Math.min(MAX_VISIBLE_ITEMS2, userTurns.length);
  const scrollOffset = (0, import_react113.useMemo)(() => {
    if (userTurns.length <= maxVisibleItems) return 0;
    const halfVisible = Math.floor(maxVisibleItems / 2);
    let offset = selectedIndex - halfVisible;
    offset = Math.max(0, offset);
    offset = Math.min(userTurns.length - maxVisibleItems, offset);
    return offset;
  }, [userTurns.length, maxVisibleItems, selectedIndex]);
  const visibleTurns = (0, import_react113.useMemo)(
    () => userTurns.slice(scrollOffset, scrollOffset + maxVisibleItems),
    [userTurns, scrollOffset, maxVisibleItems]
  );
  const showScrollUp = scrollOffset > 0;
  const showScrollDown = scrollOffset + maxVisibleItems < userTurns.length;
  const handleConfirmSelect = (0, import_react113.useCallback)(
    (confirmed) => {
      if (confirmed && confirmItem) {
        onRewind(confirmItem);
      } else {
        setConfirmItem(null);
      }
    },
    [confirmItem, onRewind]
  );
  useKeypress(
    (key) => {
      const { name: name4, ctrl } = key;
      if (name4 === "escape" || ctrl && name4 === "c") {
        onCancel();
        return;
      }
      if (name4 === "return") {
        const selected = userTurns[selectedIndex];
        if (selected) {
          setConfirmItem(selected);
        }
        return;
      }
      if (name4 === "up" || name4 === "k") {
        setSelectedIndex((prev) => Math.max(0, prev - 1));
        return;
      }
      if (name4 === "down" || name4 === "j") {
        setSelectedIndex((prev) => Math.min(userTurns.length - 1, prev + 1));
        return;
      }
    },
    { isActive: confirmItem === null }
  );
  useKeypress(
    (key) => {
      const { name: name4, ctrl, sequence } = key;
      if (name4 === "escape" || ctrl && name4 === "c") {
        setConfirmItem(null);
        return;
      }
      if (name4 === "return" || sequence === "y" || sequence === "Y") {
        handleConfirmSelect(true);
        return;
      }
      if (sequence === "n" || sequence === "N") {
        handleConfirmSelect(false);
        return;
      }
    },
    { isActive: confirmItem !== null }
  );
  if (userTurns.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { flexDirection: "column", width: boxWidth, children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
      Box_default,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: theme.border.default,
        width: boxWidth,
        children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.text.secondary, children: t4("No user turns to rewind to.") }) })
      }
    ) });
  }
  if (confirmItem) {
    const promptPreview = truncateText(
      confirmItem.text || "(empty)",
      boxWidth - 10
    );
    return /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { flexDirection: "column", width: boxWidth, children: /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: theme.border.default,
        width: boxWidth,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Rewind Conversation") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(boxWidth - 2) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)(Box_default, { paddingX: 1, flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)(Box_default, { marginBottom: 1, children: [
              /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.text.primary, children: t4("Rewind to: ") }),
              /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.text.accent, bold: true, children: promptPreview })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.status.warning, children: t4(
              "This will remove all conversation after this turn. The prompt will be pre-populated in the input for editing."
            ) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(boxWidth - 2) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter/Y to confirm \xB7 Esc/N to go back") }) })
        ]
      }
    ) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
    Box_default,
    {
      flexDirection: "column",
      width: boxWidth,
      height: height - 1,
      overflow: "hidden",
      children: /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)(
        Box_default,
        {
          flexDirection: "column",
          borderStyle: "round",
          borderColor: theme.border.default,
          width: boxWidth,
          height: height - 1,
          overflow: "hidden",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)(Box_default, { paddingX: 1, children: [
              /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { bold: true, color: theme.text.primary, children: t4("Rewind Conversation") }),
              /* @__PURE__ */ (0, import_jsx_runtime119.jsxs)(Text3, { color: theme.text.secondary, children: [
                " ",
                t4("({{count}} turns)", { count: String(userTurns.length) })
              ] })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(boxWidth - 2) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { flexDirection: "column", flexGrow: 1, paddingX: 1, overflow: "hidden", children: visibleTurns.map((item, visibleIndex) => {
              const actualIndex = scrollOffset + visibleIndex;
              return /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
                TurnItemView,
                {
                  item,
                  isSelected: actualIndex === selectedIndex,
                  isFirst: visibleIndex === 0,
                  isLast: visibleIndex === visibleTurns.length - 1,
                  showScrollUp,
                  showScrollDown,
                  maxPromptWidth: boxWidth - 10,
                  turnNumber: actualIndex + 1
                },
                item.id
              );
            }) }),
            /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.border.default, children: "\u2500".repeat(boxWidth - 2) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text3, { color: theme.text.secondary, children: t4("\u2191\u2193 to navigate \xB7 Enter to select \xB7 Esc to cancel") }) })
          ]
        }
      )
    }
  );
}
__name(RewindSelector, "RewindSelector");

// packages/cli/src/ui/components/MemoryDialog.tsx
init_esbuild_shims();
var import_react114 = __toESM(require_react(), 1);
init_dist4();
import fs126 from "node:fs/promises";
import os47 from "node:os";
import path131 from "node:path";
import { spawnSync as spawnSync6 } from "node:child_process";
init_i18n();
var import_jsx_runtime120 = __toESM(require_jsx_runtime(), 1);
async function resolvePreferredMemoryFile(dir, fallbackFilename) {
  for (const filename of getAllGeminiMdFilenames()) {
    const filePath = path131.join(dir, filename);
    try {
      await fs126.access(filePath);
      return filePath;
    } catch {
    }
  }
  return path131.join(dir, fallbackFilename);
}
__name(resolvePreferredMemoryFile, "resolvePreferredMemoryFile");
function openFolderPath(folderPath) {
  let command2 = "xdg-open";
  switch (process.platform) {
    case "darwin":
      command2 = "open";
      break;
    case "win32":
      command2 = "explorer";
      break;
    default:
      command2 = "xdg-open";
      break;
  }
  const needsShell = process.platform === "win32" && (command2.endsWith(".cmd") || command2.endsWith(".bat"));
  const result = spawnSync6(command2, [folderPath], {
    stdio: "inherit",
    shell: needsShell
  });
  if (result.error) {
    throw result.error;
  }
  if (typeof result.status === "number" && result.status !== 0) {
    throw new Error(`Folder opener exited with status ${result.status}`);
  }
}
__name(openFolderPath, "openFolderPath");
async function ensureFileExists(filePath) {
  await fs126.mkdir(path131.dirname(filePath), { recursive: true });
  try {
    await fs126.access(filePath);
  } catch {
    await fs126.writeFile(filePath, "", "utf-8");
  }
}
__name(ensureFileExists, "ensureFileExists");
function formatDisplayPath(filePath) {
  const home = os47.homedir();
  if (filePath.startsWith(home)) {
    return `~${filePath.slice(home.length)}`;
  }
  return filePath;
}
__name(formatDisplayPath, "formatDisplayPath");
function MemoryDialog({ onClose }) {
  const config2 = useConfig();
  const loadedSettings = useSettings();
  const launchEditor = useLaunchEditor();
  const [error40, setError] = (0, import_react114.useState)(null);
  const [highlightedIndex, setHighlightedIndex] = (0, import_react114.useState)(0);
  const [focusedSection, setFocusedSection] = (0, import_react114.useState)("list");
  const [autoMemoryOn, setAutoMemoryOn] = (0, import_react114.useState)(
    () => config2.getManagedAutoMemoryEnabled()
  );
  const [autoDreamOn, setAutoDreamOn] = (0, import_react114.useState)(
    () => config2.getManagedAutoDreamEnabled()
  );
  const [lastDreamAt, setLastDreamAt] = (0, import_react114.useState)(null);
  const globalMemoryPath = (0, import_react114.useMemo)(
    () => path131.join(
      os47.homedir(),
      QWEN_DIR,
      getAllGeminiMdFilenames()[0] ?? "QWEN.md"
    ),
    []
  );
  const projectMemoryPath = (0, import_react114.useMemo)(
    () => path131.join(
      config2.getWorkingDir(),
      getAllGeminiMdFilenames()[0] ?? "QWEN.md"
    ),
    [config2]
  );
  const managedMemoryPath = (0, import_react114.useMemo)(
    () => getAutoMemoryRoot(config2.getProjectRoot()),
    [config2]
  );
  const memoryStatePath = (0, import_react114.useMemo)(
    () => getAutoMemoryProjectStateDir(config2.getProjectRoot()),
    [config2]
  );
  const items = (0, import_react114.useMemo)(
    () => [
      {
        label: t4("User memory"),
        value: "global",
        description: t4("Saved in {{path}}", {
          path: formatDisplayPath(globalMemoryPath)
        })
      },
      {
        label: t4("Project memory"),
        value: "project",
        description: t4("Saved in {{path}}", {
          path: path131.relative(config2.getWorkingDir(), projectMemoryPath) || path131.basename(projectMemoryPath)
        })
      },
      {
        label: t4("Open auto-memory folder"),
        value: "managed"
      }
    ],
    [config2, globalMemoryPath, projectMemoryPath]
  );
  (0, import_react114.useEffect)(() => {
    let cancelled = false;
    async function loadMeta() {
      try {
        const metadataPath = path131.join(memoryStatePath, "meta.json");
        const content = await fs126.readFile(metadataPath, "utf-8");
        const parsed = JSON.parse(content);
        if (!cancelled && parsed.lastDreamAt) {
          const ts = new Date(parsed.lastDreamAt).getTime();
          if (!Number.isNaN(ts)) {
            setLastDreamAt(ts);
          }
        }
      } catch {
      }
    }
    __name(loadMeta, "loadMeta");
    void loadMeta();
    return () => {
      cancelled = true;
    };
  }, [memoryStatePath]);
  const dreamStatusText = (0, import_react114.useMemo)(() => {
    if (lastDreamAt !== null) return formatRelativeTime(lastDreamAt);
    return t4("never");
  }, [lastDreamAt]);
  const resolveTargetPath = (0, import_react114.useCallback)(
    async (target) => {
      switch (target) {
        case "project":
          return resolvePreferredMemoryFile(
            config2.getWorkingDir(),
            getAllGeminiMdFilenames()[0] ?? "QWEN.md"
          );
        case "global":
          return resolvePreferredMemoryFile(
            path131.join(os47.homedir(), QWEN_DIR),
            getAllGeminiMdFilenames()[0] ?? "QWEN.md"
          );
        case "managed":
          return managedMemoryPath;
        default:
          return managedMemoryPath;
      }
    },
    [config2, managedMemoryPath]
  );
  const handleSelect = (0, import_react114.useCallback)(
    async (target) => {
      try {
        setError(null);
        const targetPath = await resolveTargetPath(target);
        if (target === "managed") {
          await fs126.mkdir(targetPath, { recursive: true });
          openFolderPath(targetPath);
        } else {
          await ensureFileExists(targetPath);
          await launchEditor(targetPath);
        }
        onClose();
      } catch (selectionError) {
        setError(
          selectionError instanceof Error ? selectionError.message : String(selectionError)
        );
      }
    },
    [launchEditor, onClose, resolveTargetPath]
  );
  const handleToggleAutoMemory = (0, import_react114.useCallback)(() => {
    const newValue = !autoMemoryOn;
    loadedSettings.setValue(
      "Workspace" /* Workspace */,
      "memory.enableManagedAutoMemory",
      newValue
    );
    setAutoMemoryOn(newValue);
  }, [autoMemoryOn, loadedSettings]);
  const handleToggleAutoDream = (0, import_react114.useCallback)(() => {
    const newValue = !autoDreamOn;
    loadedSettings.setValue(
      "Workspace" /* Workspace */,
      "memory.enableManagedAutoDream",
      newValue
    );
    setAutoDreamOn(newValue);
  }, [autoDreamOn, loadedSettings]);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onClose();
        return;
      }
      if (focusedSection === "autoMemory") {
        if (key.name === "down") {
          setFocusedSection("autoDream");
          return;
        }
        if (key.name === "return") {
          handleToggleAutoMemory();
          return;
        }
        return;
      }
      if (focusedSection === "autoDream") {
        if (key.name === "up") {
          setFocusedSection("autoMemory");
          return;
        }
        if (key.name === "down") {
          setFocusedSection("list");
          setHighlightedIndex(0);
          return;
        }
        if (key.name === "return") {
          handleToggleAutoDream();
          return;
        }
        return;
      }
      if (key.name === "up") {
        if (highlightedIndex === 0) {
          setFocusedSection("autoDream");
        } else {
          setHighlightedIndex((current) => current - 1);
        }
        return;
      }
      if (key.name === "down") {
        setHighlightedIndex((current) => (current + 1) % items.length);
        return;
      }
      if (key.name === "return") {
        void handleSelect(items[highlightedIndex]?.value ?? "project");
        return;
      }
      if (key.sequence && /^[1-3]$/.test(key.sequence)) {
        const nextIndex = Number(key.sequence) - 1;
        if (items[nextIndex]) {
          setHighlightedIndex(nextIndex);
          void handleSelect(items[nextIndex].value);
        }
      }
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime120.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime120.jsx)(Text3, { bold: true, children: t4("Memory") }),
        /* @__PURE__ */ (0, import_jsx_runtime120.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime120.jsxs)(
            Text3,
            {
              color: focusedSection === "autoMemory" ? theme.status.success : theme.text.secondary,
              children: [
                focusedSection === "autoMemory" ? "\u203A " : "  ",
                t4("Auto-memory: {{status}}", {
                  status: autoMemoryOn ? t4("on") : t4("off")
                })
              ]
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime120.jsxs)(
            Text3,
            {
              color: focusedSection === "autoDream" ? theme.status.success : theme.text.secondary,
              children: [
                focusedSection === "autoDream" ? "\u203A " : "  ",
                t4("Auto-dream: {{status}} \xB7 {{lastDream}} \xB7 /dream to run", {
                  status: autoDreamOn ? t4("on") : t4("off"),
                  lastDream: dreamStatusText
                })
              ]
            }
          )
        ] }),
        error40 && /* @__PURE__ */ (0, import_jsx_runtime120.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime120.jsx)(Text3, { color: theme.status.error, children: error40 }) }),
        /* @__PURE__ */ (0, import_jsx_runtime120.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: items.map((item, index) => {
          const isSelected = focusedSection === "list" && index === highlightedIndex;
          return /* @__PURE__ */ (0, import_jsx_runtime120.jsxs)(Box_default, { flexDirection: "row", children: [
            /* @__PURE__ */ (0, import_jsx_runtime120.jsxs)(Text3, { color: isSelected ? theme.status.success : void 0, children: [
              isSelected ? "\u203A " : "  ",
              index + 1,
              ". ",
              item.label
            ] }),
            item.description ? /* @__PURE__ */ (0, import_jsx_runtime120.jsx)(
              Text3,
              {
                color: theme.text.secondary,
                children: `  ${item.description}`
              }
            ) : null
          ] }, item.value);
        }) }),
        /* @__PURE__ */ (0, import_jsx_runtime120.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime120.jsx)(Text3, { color: theme.text.secondary, children: t4("Enter to confirm \xB7 Esc to cancel") }) })
      ]
    }
  );
}
__name(MemoryDialog, "MemoryDialog");

// packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx
init_esbuild_shims();
var import_react117 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/BackgroundTaskViewContext.tsx
init_esbuild_shims();
var import_react116 = __toESM(require_react(), 1);
init_dist4();

// packages/cli/src/ui/hooks/useBackgroundTaskView.ts
init_esbuild_shims();
var import_react115 = __toESM(require_react(), 1);
init_dist4();
function entryId(entry) {
  return entry.kind === "agent" ? entry.agentId : entry.shellId;
}
__name(entryId, "entryId");
function useBackgroundTaskView(config2) {
  const [entries, setEntries] = (0, import_react115.useState)([]);
  (0, import_react115.useEffect)(() => {
    if (!config2) return;
    const agentRegistry = config2.getBackgroundTaskRegistry();
    const shellRegistry = config2.getBackgroundShellRegistry();
    const refresh = /* @__PURE__ */ __name(() => {
      const agentEntries = agentRegistry.getAll().map((e4) => ({ ...e4, kind: "agent" }));
      const shellEntries = shellRegistry.getAll().map((e4) => ({ ...e4, kind: "shell" }));
      const merged = [...agentEntries, ...shellEntries].sort(
        (a2, b2) => a2.startTime - b2.startTime
      );
      setEntries(merged);
    }, "refresh");
    refresh();
    agentRegistry.setStatusChangeCallback(refresh);
    shellRegistry.setStatusChangeCallback(refresh);
    return () => {
      agentRegistry.setStatusChangeCallback(void 0);
      shellRegistry.setStatusChangeCallback(void 0);
    };
  }, [config2]);
  return { entries };
}
__name(useBackgroundTaskView, "useBackgroundTaskView");

// packages/cli/src/ui/contexts/BackgroundTaskViewContext.tsx
var import_jsx_runtime121 = __toESM(require_jsx_runtime(), 1);
var BackgroundTaskViewStateContext = (0, import_react116.createContext)(null);
var BackgroundTaskViewActionsContext = (0, import_react116.createContext)(null);
var DEFAULT_STATE = {
  entries: [],
  selectedIndex: 0,
  dialogMode: "closed",
  dialogOpen: false,
  pillFocused: false
};
var noop8 = /* @__PURE__ */ __name(() => {
}, "noop");
var noopBool = /* @__PURE__ */ __name(() => false, "noopBool");
var DEFAULT_ACTIONS = {
  moveSelectionUp: noopBool,
  moveSelectionDown: noopBool,
  openDialog: noop8,
  closeDialog: noop8,
  enterDetail: noop8,
  exitDetail: noop8,
  cancelSelected: noop8,
  setPillFocused: noop8
};
function useBackgroundTaskViewState() {
  return (0, import_react116.useContext)(BackgroundTaskViewStateContext) ?? DEFAULT_STATE;
}
__name(useBackgroundTaskViewState, "useBackgroundTaskViewState");
function useBackgroundTaskViewActions() {
  return (0, import_react116.useContext)(BackgroundTaskViewActionsContext) ?? DEFAULT_ACTIONS;
}
__name(useBackgroundTaskViewActions, "useBackgroundTaskViewActions");
function BackgroundTaskViewProvider({
  config: config2,
  children
}) {
  const { entries } = useBackgroundTaskView(config2 ?? null);
  const [rawSelectedIndex, setRawSelectedIndex] = (0, import_react116.useState)(0);
  const [dialogMode, setDialogMode] = (0, import_react116.useState)("closed");
  const [pillFocused, setPillFocused] = (0, import_react116.useState)(false);
  const dialogOpen = dialogMode !== "closed";
  const hasEntries = entries.length > 0;
  (0, import_react116.useEffect)(() => {
    if (pillFocused && !hasEntries) setPillFocused(false);
  }, [pillFocused, hasEntries]);
  const selectedIndex = entries.length === 0 ? 0 : Math.min(Math.max(0, rawSelectedIndex), entries.length - 1);
  const moveSelectionUp = (0, import_react116.useCallback)(() => {
    if (selectedIndex <= 0) return false;
    setRawSelectedIndex(selectedIndex - 1);
    return true;
  }, [selectedIndex]);
  const moveSelectionDown = (0, import_react116.useCallback)(() => {
    if (entries.length === 0) return false;
    if (selectedIndex >= entries.length - 1) return false;
    setRawSelectedIndex(selectedIndex + 1);
    return true;
  }, [entries.length, selectedIndex]);
  const openDialog = (0, import_react116.useCallback)(() => {
    setDialogMode("list");
    setPillFocused(false);
  }, []);
  const closeDialog = (0, import_react116.useCallback)(() => {
    setDialogMode("closed");
  }, []);
  const enterDetail = (0, import_react116.useCallback)(() => {
    if (entries.length === 0) return;
    setDialogMode("detail");
  }, [entries.length]);
  const exitDetail = (0, import_react116.useCallback)(() => {
    setDialogMode("list");
  }, []);
  const cancelSelected = (0, import_react116.useCallback)(() => {
    if (!config2) return;
    const target = entries[selectedIndex];
    if (!target) return;
    if (target.kind === "agent") {
      config2.getBackgroundTaskRegistry().cancel(target.agentId);
    } else {
      config2.getBackgroundShellRegistry().requestCancel(target.shellId);
    }
  }, [config2, entries, selectedIndex]);
  const state = (0, import_react116.useMemo)(
    () => ({
      entries,
      selectedIndex,
      dialogMode,
      dialogOpen,
      pillFocused
    }),
    [entries, selectedIndex, dialogMode, dialogOpen, pillFocused]
  );
  const actions = (0, import_react116.useMemo)(
    () => ({
      moveSelectionUp,
      moveSelectionDown,
      openDialog,
      closeDialog,
      enterDetail,
      exitDetail,
      cancelSelected,
      setPillFocused
    }),
    [
      moveSelectionUp,
      moveSelectionDown,
      openDialog,
      closeDialog,
      enterDetail,
      exitDetail,
      cancelSelected,
      setPillFocused
    ]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(BackgroundTaskViewStateContext.Provider, { value: state, children: /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(BackgroundTaskViewActionsContext.Provider, { value: actions, children }) });
}
__name(BackgroundTaskViewProvider, "BackgroundTaskViewProvider");

// packages/cli/src/ui/components/background-view/BackgroundTasksDialog.tsx
init_dist4();
var import_jsx_runtime122 = __toESM(require_jsx_runtime(), 1);
var TOOL_DISPLAY_BY_NAME = Object.fromEntries(
  Object.keys(ToolNames).map((key) => [
    ToolNames[key],
    ToolDisplayNames[key]
  ])
);
function formatActivityLabel(name4, description) {
  const display = TOOL_DISPLAY_BY_NAME[name4] ?? name4;
  const singleLineDesc = description ? description.replace(/\s*\n\s*/g, " ").trim() : "";
  return singleLineDesc ? `${display}(${singleLineDesc})` : display;
}
__name(formatActivityLabel, "formatActivityLabel");
var STATUS_VERBS = {
  running: "Running",
  completed: "Completed",
  failed: "Failed",
  cancelled: "Stopped"
};
function terminalStatusPresentation(status) {
  switch (status) {
    case "completed":
      return {
        icon: "\u2714",
        color: theme.status.success,
        labelColor: theme.text.secondary
      };
    case "failed":
      return {
        icon: "\u2716",
        color: theme.status.error,
        labelColor: theme.status.errorDim
      };
    case "cancelled":
      return {
        icon: "\u2716",
        color: theme.status.warning,
        labelColor: theme.status.warningDim
      };
    default:
      return null;
  }
}
__name(terminalStatusPresentation, "terminalStatusPresentation");
function rowLabel(entry) {
  if (entry.kind === "agent") {
    return buildBackgroundEntryLabel(entry, { includePrefix: false });
  }
  return `[shell] ${entry.command}`;
}
__name(rowLabel, "rowLabel");
function elapsedFor(entry) {
  const elapsedMs = Math.max(
    0,
    (entry.endTime ?? Date.now()) - entry.startTime
  );
  const wholeSeconds = Math.floor(elapsedMs / 1e3);
  return formatDuration(wholeSeconds * 1e3, { hideTrailingZeros: true });
}
__name(elapsedFor, "elapsedFor");
function truncateToWidth(text, maxWidth) {
  if (maxWidth <= 0) return "";
  if (stringWidth4(text) <= maxWidth) return text;
  const ellipsis = "\u2026";
  const ellipsisWidth = stringWidth4(ellipsis);
  const target = Math.max(0, maxWidth - ellipsisWidth);
  let width = 0;
  let result = "";
  for (const char of text) {
    const charWidth = stringWidth4(char);
    if (width + charWidth > target) break;
    width += charWidth;
    result += char;
  }
  return result + ellipsis;
}
__name(truncateToWidth, "truncateToWidth");
var ListBody = /* @__PURE__ */ __name(({ entries, selectedIndex, maxRows }) => {
  if (entries.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(Box_default, { paddingX: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, children: "Background tasks" }),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: theme.text.secondary, children: " (0)" })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: theme.text.secondary, children: "No tasks currently running" }) })
    ] });
  }
  const fits = entries.length <= maxRows;
  const effectiveRows = Math.max(1, fits ? maxRows : maxRows - 2);
  const windowStart = fits ? 0 : Math.max(
    0,
    Math.min(
      selectedIndex - Math.floor(effectiveRows / 2),
      entries.length - effectiveRows
    )
  );
  const windowEnd = fits ? entries.length : Math.min(entries.length, windowStart + effectiveRows);
  const hiddenAbove = windowStart;
  const hiddenBelow = entries.length - windowEnd;
  const visible = entries.slice(windowStart, windowEnd);
  return /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(Box_default, { paddingX: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, children: "Background tasks" }),
      /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(Text3, { color: theme.text.secondary, children: [
        " (",
        entries.length,
        ")"
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(Box_default, { flexDirection: "column", children: [
      hiddenAbove > 0 && /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: theme.text.secondary, children: `  ^ ${hiddenAbove} more above` }) }),
      visible.map((entry, visibleIdx) => {
        const idx = windowStart + visibleIdx;
        const isSelected = idx === selectedIndex;
        const terminal = terminalStatusPresentation(entry.status);
        const labelColor = isSelected ? theme.text.accent : terminal ? terminal.labelColor : theme.text.primary;
        return /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(Box_default, { flexDirection: "row", paddingX: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: isSelected ? theme.text.accent : void 0, children: isSelected ? "> " : "  " }),
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: labelColor, children: rowLabel(entry) })
        ] }, entryId(entry));
      }),
      hiddenBelow > 0 && /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: theme.text.secondary, children: `  v ${hiddenBelow} more below` }) })
    ] })
  ] });
}, "ListBody");
var DetailBody = /* @__PURE__ */ __name(({ entry, maxHeight, maxWidth }) => entry.kind === "agent" ? /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(AgentDetailBody, { entry, maxHeight, maxWidth }) : /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(ShellDetailBody, { entry, maxHeight, maxWidth }), "DetailBody");
var AgentDetailBody = /* @__PURE__ */ __name(({ entry, maxHeight, maxWidth }) => {
  const title = `${entry.subagentType ?? "Agent"} \u203A ${buildBackgroundEntryLabel(entry, { includePrefix: false })}`;
  const terminal = terminalStatusPresentation(entry.status);
  const dimSubtitleParts = [elapsedFor(entry)];
  if (entry.stats?.totalTokens) {
    dimSubtitleParts.push(
      `${formatTokenCount(entry.stats.totalTokens)} tokens`
    );
  }
  if (entry.stats?.toolUses !== void 0) {
    dimSubtitleParts.push(
      `${entry.stats.toolUses} tool${entry.stats.toolUses === 1 ? "" : "s"}`
    );
  }
  const activities = (entry.recentActivities ?? []).slice(-5);
  const hasError = entry.status === "failed" && Boolean(entry.error);
  const promptLines = entry.prompt ? entry.prompt.split("\n") : [];
  const visiblePromptLines = promptLines.slice(0, 5);
  const promptTruncated = promptLines.length > visiblePromptLines.length;
  if (promptTruncated && visiblePromptLines.length > 0) {
    const lastIdx = visiblePromptLines.length - 1;
    visiblePromptLines[lastIdx] = `${visiblePromptLines[lastIdx].trimEnd()}\u2026`;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(
    MaxSizedBox,
    {
      maxHeight,
      maxWidth,
      overflowDirection: "bottom",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, color: theme.text.accent, children: title }) }),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(Box_default, { children: [
          terminal && /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: terminal.color, children: `${terminal.icon} ${STATUS_VERBS[entry.status]} \xB7 ` }),
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: theme.text.secondary, children: dimSubtitleParts.join(" \xB7 ") })
        ] }),
        activities.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(import_react117.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, {}),
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, dimColor: true, children: "Progress" }) }),
          activities.map((a2, i4) => {
            const isLast = i4 === activities.length - 1;
            const prefix = isLast ? "> " : "  ";
            const label = truncateToWidth(
              formatActivityLabel(a2.name, a2.description),
              Math.max(0, maxWidth - stringWidth4(prefix))
            );
            return /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(
              Text3,
              {
                color: isLast ? theme.text.primary : theme.text.secondary,
                children: [
                  prefix,
                  label
                ]
              }
            ) }, `${a2.at}-${i4}`);
          })
        ] }),
        visiblePromptLines.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(import_react117.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, {}),
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, dimColor: true, children: "Prompt" }) }),
          visiblePromptLines.map((line, i4) => /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { wrap: "truncate-end", children: line || " " }) }, `prompt-${i4}`))
        ] }),
        hasError && /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(import_react117.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, {}),
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, color: theme.status.error, children: "Error" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: theme.status.error, wrap: "wrap", children: entry.error }) })
        ] })
      ]
    }
  );
}, "AgentDetailBody");
var ShellDetailBody = /* @__PURE__ */ __name(({ entry, maxHeight, maxWidth }) => {
  const title = `Shell \u203A ${entry.command}`;
  const terminal = terminalStatusPresentation(entry.status);
  const dimSubtitleParts = [elapsedFor(entry)];
  if (entry.pid !== void 0) {
    dimSubtitleParts.push(`pid ${entry.pid}`);
  }
  if (entry.status === "completed" && entry.exitCode !== void 0) {
    dimSubtitleParts.push(`exit ${entry.exitCode}`);
  }
  const hasError = entry.status === "failed" && Boolean(entry.error);
  return /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(
    MaxSizedBox,
    {
      maxHeight,
      maxWidth,
      overflowDirection: "bottom",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, color: theme.text.accent, children: title }) }),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(Box_default, { children: [
          terminal && /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: terminal.color, children: `${terminal.icon} ${STATUS_VERBS[entry.status]} \xB7 ` }),
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: theme.text.secondary, children: dimSubtitleParts.join(" \xB7 ") })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, {}),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, dimColor: true, children: "Working dir" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { wrap: "truncate-end", children: entry.cwd }) }),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, {}),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, dimColor: true, children: "Output file" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { wrap: "truncate-end", children: entry.outputPath }) }),
        hasError && /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(import_react117.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, {}),
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, color: theme.status.error, children: "Error" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: theme.status.error, wrap: "wrap", children: entry.error }) })
        ] })
      ]
    }
  );
}, "ShellDetailBody");
var BackgroundTasksDialog = /* @__PURE__ */ __name(({
  availableTerminalHeight,
  terminalWidth
}) => {
  const { entries, selectedIndex, dialogOpen, dialogMode } = useBackgroundTaskViewState();
  const {
    moveSelectionUp,
    moveSelectionDown,
    closeDialog,
    enterDetail,
    exitDetail,
    cancelSelected
  } = useBackgroundTaskViewActions();
  const config2 = useConfig();
  const detailContentHeight = Math.max(10, availableTerminalHeight - 6);
  const detailContentWidth = Math.max(10, terminalWidth - 4);
  const listMaxRows = Math.max(3, availableTerminalHeight - 10);
  const [activityTick, setActivityTick] = (0, import_react117.useState)(0);
  const selectedEntry = (0, import_react117.useMemo)(() => {
    const fromSnapshot = entries[selectedIndex] ?? null;
    if (!fromSnapshot || fromSnapshot.kind !== "agent") return fromSnapshot;
    const live = config2.getBackgroundTaskRegistry().get(fromSnapshot.agentId);
    return live ? { ...live, kind: "agent" } : fromSnapshot;
  }, [entries, selectedIndex, config2, activityTick]);
  const selectedEntryId = selectedEntry ? entryId(selectedEntry) : void 0;
  const selectedAgentIdForActivity = selectedEntry?.kind === "agent" ? selectedEntry.agentId : void 0;
  (0, import_react117.useEffect)(() => {
    if (!dialogOpen || dialogMode !== "detail" || !selectedAgentIdForActivity)
      return;
    const registry3 = config2.getBackgroundTaskRegistry();
    const onActivity = /* @__PURE__ */ __name((entry) => {
      if (entry.agentId !== selectedAgentIdForActivity) return;
      setActivityTick((n3) => n3 + 1);
    }, "onActivity");
    registry3.setActivityChangeCallback(onActivity);
    return () => registry3.setActivityChangeCallback(void 0);
  }, [dialogOpen, dialogMode, config2, selectedAgentIdForActivity]);
  const selectedStatus = selectedEntry?.status;
  (0, import_react117.useEffect)(() => {
    if (!dialogOpen || dialogMode !== "detail" || !selectedEntryId || selectedStatus !== "running")
      return;
    const id = setInterval(() => setActivityTick((n3) => n3 + 1), 1e3);
    return () => clearInterval(id);
  }, [dialogOpen, dialogMode, selectedEntryId, selectedStatus]);
  const initialDetailStatusRef = (0, import_react117.useRef)(null);
  (0, import_react117.useEffect)(() => {
    if (!dialogOpen || dialogMode !== "detail") {
      initialDetailStatusRef.current = null;
      return;
    }
    if (!selectedEntryId) {
      initialDetailStatusRef.current = null;
      exitDetail();
      return;
    }
    const seen = initialDetailStatusRef.current;
    if (!seen || seen.entryId !== selectedEntryId) {
      if (selectedStatus) {
        initialDetailStatusRef.current = {
          entryId: selectedEntryId,
          status: selectedStatus
        };
      }
      return;
    }
    if (seen.status === "running" && selectedStatus && selectedStatus !== "running") {
      exitDetail();
    }
  }, [dialogOpen, dialogMode, selectedEntryId, selectedStatus, exitDetail]);
  useKeypress(
    (key) => {
      if (!dialogOpen) return;
      if (dialogMode === "list") {
        if (key.name === "up") {
          moveSelectionUp();
          return;
        }
        if (key.name === "down") {
          moveSelectionDown();
          return;
        }
        if (key.name === "return") {
          if (selectedEntry) enterDetail();
          return;
        }
        if (key.name === "escape" || key.name === "left") {
          closeDialog();
          return;
        }
        if (key.sequence === "x" && !key.ctrl && !key.meta) {
          cancelSelected();
          return;
        }
        return;
      }
      if (key.name === "left") {
        exitDetail();
        return;
      }
      if (key.name === "escape" || key.name === "return" || key.name === "space") {
        closeDialog();
        return;
      }
      if (key.sequence === "x" && !key.ctrl && !key.meta) {
        cancelSelected();
        return;
      }
    },
    { isActive: dialogOpen }
  );
  if (!dialogOpen) return null;
  const hints = [];
  if (dialogMode === "list") {
    hints.push("\u2191/\u2193 select", "Enter view");
    if (selectedEntry?.status === "running") hints.push("x stop");
    hints.push("\u2190/Esc close");
  } else {
    hints.push("\u2190 go back", "Esc/Enter/Space close");
    if (selectedEntry?.status === "running") hints.push("x stop");
  }
  return /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.border.default,
      marginTop: 1,
      paddingX: 1,
      children: [
        dialogMode === "list" && /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { bold: true, color: theme.text.accent, children: "Background tasks" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { marginTop: dialogMode === "list" ? 1 : 0, children: dialogMode === "list" ? /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(
          ListBody,
          {
            entries,
            selectedIndex,
            maxRows: listMaxRows
          }
        ) : selectedEntry ? /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(
          DetailBody,
          {
            entry: selectedEntry,
            maxHeight: detailContentHeight,
            maxWidth: detailContentWidth
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: theme.text.secondary, children: "No entry to show." }) }) }),
        /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { marginTop: 1, paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text3, { color: theme.text.secondary, children: hints.join(" \xB7 ") }) })
      ]
    }
  );
}, "BackgroundTasksDialog");

// packages/cli/src/ui/components/DialogManager.tsx
init_i18n();
var import_jsx_runtime123 = __toESM(require_jsx_runtime(), 1);
var DialogManager = /* @__PURE__ */ __name(({
  addItem,
  terminalWidth
}) => {
  const config2 = useConfig();
  const settings = useSettings();
  const uiState = useUIState();
  const uiActions = useUIActions();
  const { dialogOpen: bgTasksDialogOpen } = useBackgroundTaskViewState();
  const { constrainHeight, terminalHeight, staticExtraHeight, mainAreaWidth } = uiState;
  if (uiState.showWelcomeBackDialog && uiState.welcomeBackInfo?.hasHistory) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      WelcomeBackDialog,
      {
        welcomeBackInfo: uiState.welcomeBackInfo,
        onSelect: uiActions.handleWelcomeBackSelection,
        onClose: uiActions.handleWelcomeBackClose
      }
    );
  }
  if (uiState.showIdeRestartPrompt) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(IdeTrustChangeDialog, { reason: uiState.ideTrustRestartReason });
  }
  if (uiState.shouldShowIdePrompt) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      IdeIntegrationNudge,
      {
        ide: uiState.currentIDE,
        onComplete: uiActions.handleIdePromptComplete
      }
    );
  }
  if (uiState.shouldShowCommandMigrationNudge) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      CommandFormatMigrationNudge,
      {
        tomlFiles: uiState.commandMigrationTomlFiles,
        onComplete: uiActions.handleCommandMigrationComplete
      }
    );
  }
  if (uiState.isFolderTrustDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      FolderTrustDialog,
      {
        onSelect: uiActions.handleFolderTrustSelect,
        isRestarting: uiState.isRestarting
      }
    );
  }
  if (uiState.shellConfirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(ShellConfirmationDialog, { request: uiState.shellConfirmationRequest });
  }
  if (uiState.loopDetectionConfirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      LoopDetectionConfirmation,
      {
        onComplete: uiState.loopDetectionConfirmationRequest.onComplete
      }
    );
  }
  if (uiState.confirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.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_runtime123.jsx)(
      ConsentPrompt,
      {
        prompt: request4.prompt,
        onConfirm: request4.onConfirm,
        terminalWidth
      }
    );
  }
  if (uiState.codingPlanUpdateRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.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_runtime123.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_runtime123.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_runtime123.jsxs)(Box_default, { flexDirection: "column", children: [
      uiState.themeError && /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(Text3, { color: theme.status.error, children: uiState.themeError }) }),
      /* @__PURE__ */ (0, import_jsx_runtime123.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_runtime123.jsxs)(Box_default, { flexDirection: "column", children: [
      uiState.editorError && /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(Text3, { color: theme.status.error, children: uiState.editorError }) }),
      /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
        EditorSettingsDialog,
        {
          onSelect: uiActions.handleEditorSelect,
          settings,
          onExit: uiActions.exitEditorDialog
        }
      )
    ] });
  }
  if (uiState.isModelDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      ModelDialog,
      {
        onClose: uiActions.closeModelDialog,
        isFastModelMode: uiState.isFastModelMode
      }
    );
  }
  if (uiState.isManageModelsDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      ManageModelsDialog,
      {
        config: config2,
        onClose: uiActions.closeManageModelsDialog
      }
    );
  }
  if (uiState.isSettingsDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      SettingsDialog,
      {
        settings,
        onSelect: (settingName) => {
          if (settingName === "ui.theme") {
            uiActions.openThemeDialog();
            return;
          }
          if (settingName === "general.preferredEditor") {
            uiActions.openEditorDialog();
            return;
          }
          if (settingName === "fastModel") {
            uiActions.openModelDialog({ fastModelMode: true });
            return;
          }
          uiActions.closeSettingsDialog();
        },
        onRestartRequest: () => process37.exit(0),
        availableTerminalHeight: terminalHeight - staticExtraHeight,
        config: config2
      }
    ) });
  }
  if (uiState.isMemoryDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(MemoryDialog, { onClose: uiActions.closeMemoryDialog });
  }
  if (uiState.isApprovalModeDialogOpen) {
    const currentMode = config2.getApprovalMode();
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      ApprovalModeDialog,
      {
        settings,
        currentMode,
        onSelect: uiActions.handleApprovalModeSelect,
        availableTerminalHeight: constrainHeight ? terminalHeight - staticExtraHeight : void 0
      }
    ) });
  }
  if (uiState.activeArenaDialog === "start") {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      ArenaStartDialog,
      {
        onClose: () => uiActions.closeArenaDialog(),
        onConfirm: (models) => uiActions.handleArenaModelsSelected?.(models)
      }
    );
  }
  if (uiState.activeArenaDialog === "status") {
    const arenaManager = config2.getArenaManager();
    if (arenaManager) {
      return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
        ArenaStatusDialog,
        {
          manager: arenaManager,
          closeArenaDialog: uiActions.closeArenaDialog,
          width: mainAreaWidth
        }
      );
    }
  }
  if (uiState.activeArenaDialog === "stop") {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      ArenaStopDialog,
      {
        config: config2,
        addItem,
        closeArenaDialog: uiActions.closeArenaDialog
      }
    );
  }
  if (uiState.activeArenaDialog === "select") {
    const arenaManager = config2.getArenaManager();
    if (arenaManager) {
      return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
        ArenaSelectDialog,
        {
          manager: arenaManager,
          config: config2,
          addItem,
          closeArenaDialog: uiActions.closeArenaDialog
        }
      );
    }
  }
  if (uiState.isAuthDialogOpen || uiState.authError) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(AuthDialog, {}) });
  }
  if (uiState.isAuthenticating) {
    if (uiState.pendingAuthType === AuthType2.USE_OPENAI && uiState.externalAuthState) {
      return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
        ExternalAuthProgress,
        {
          title: uiState.externalAuthState.title,
          message: uiState.externalAuthState.message,
          detail: uiState.externalAuthState.detail,
          onCancel: () => {
            uiActions.cancelAuthentication();
            uiActions.setAuthState("updating" /* Updating */);
          }
        }
      );
    }
    if (uiState.pendingAuthType === AuthType2.QWEN_OAUTH) {
      return /* @__PURE__ */ (0, import_jsx_runtime123.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.isTrustDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(TrustDialog, { onExit: uiActions.closeTrustDialog, addItem });
  }
  if (uiState.isPermissionsDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(PermissionsDialog, { onExit: uiActions.closePermissionsDialog });
  }
  if (uiState.isSubagentCreateDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      AgentCreationWizard,
      {
        onClose: uiActions.closeSubagentCreateDialog,
        config: config2
      }
    );
  }
  if (uiState.isAgentsManagerDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      AgentsManagerDialog,
      {
        onClose: uiActions.closeAgentsManagerDialog,
        config: config2
      }
    );
  }
  if (uiState.isExtensionsManagerDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      ExtensionsManagerDialog,
      {
        onClose: uiActions.closeExtensionsManagerDialog,
        config: config2
      }
    );
  }
  if (uiState.isHooksDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(HooksManagementDialog, { onClose: uiActions.closeHooksDialog });
  }
  if (uiState.isMcpDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(MCPManagementDialog, { onClose: uiActions.closeMcpDialog });
  }
  if (uiState.isResumeDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      SessionPicker,
      {
        sessionService: config2.getSessionService(),
        currentBranch: uiState.branchName,
        onSelect: uiActions.handleResume,
        onCancel: uiActions.closeResumeDialog,
        initialSessions: uiState.resumeMatchedSessions,
        enablePreview: true
      }
    );
  }
  if (uiState.isDeleteDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      SessionPicker,
      {
        sessionService: config2.getSessionService(),
        currentBranch: uiState.branchName,
        onSelect: uiActions.handleDelete,
        onCancel: uiActions.closeDeleteDialog,
        title: t4("Delete Session")
      }
    );
  }
  if (uiState.isRewindSelectorOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      RewindSelector,
      {
        history: uiState.history,
        onRewind: uiActions.handleRewindConfirm,
        onCancel: uiActions.closeRewindSelector
      }
    );
  }
  if (bgTasksDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(
      BackgroundTasksDialog,
      {
        availableTerminalHeight: terminalHeight - staticExtraHeight,
        terminalWidth: mainAreaWidth
      }
    );
  }
  return null;
}, "DialogManager");

// packages/cli/src/ui/components/Composer.tsx
init_esbuild_shims();
var import_react139 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/LoadingIndicator.tsx
init_esbuild_shims();
var import_react119 = __toESM(require_react(), 1);
init_types22();

// packages/cli/src/ui/hooks/useAnimationFrame.ts
init_esbuild_shims();
var import_react118 = __toESM(require_react(), 1);
function useAnimationFrame(watchRef, intervalMs = 50) {
  const [displayValue, setDisplayValue] = (0, import_react118.useState)(() => watchRef.current);
  const displayRef = (0, import_react118.useRef)(watchRef.current);
  const targetRef = (0, import_react118.useRef)(watchRef.current);
  const currentTarget = watchRef.current;
  if (currentTarget < displayRef.current) {
    displayRef.current = currentTarget;
    targetRef.current = currentTarget;
  }
  (0, import_react118.useEffect)(() => {
    if (intervalMs === null) return;
    const current = watchRef.current;
    if (current !== targetRef.current) {
      targetRef.current = current;
      if (current < displayRef.current) {
        displayRef.current = current;
        setDisplayValue(current);
      }
    }
    const id = setInterval(() => {
      const realValue = watchRef.current;
      targetRef.current = realValue;
      if (realValue < displayRef.current) {
        displayRef.current = realValue;
        setDisplayValue(realValue);
        return;
      }
      const gap = realValue - displayRef.current;
      if (gap <= 0) return;
      let increment2;
      if (gap < 70) {
        increment2 = 3;
      } else if (gap <= 200) {
        increment2 = Math.max(3, Math.round(gap * 0.2));
      } else {
        increment2 = 50;
      }
      const next = Math.min(displayRef.current + increment2, realValue);
      displayRef.current = next;
      setDisplayValue(next);
    }, intervalMs);
    return () => clearInterval(id);
  }, [watchRef, intervalMs]);
  return Math.min(displayValue, currentTarget);
}
__name(useAnimationFrame, "useAnimationFrame");

// 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
init_i18n();
var import_jsx_runtime124 = __toESM(require_jsx_runtime(), 1);
var LoadingIndicator = /* @__PURE__ */ __name(({
  currentLoadingPhrase,
  elapsedTime,
  rightContent,
  thought,
  candidatesTokens,
  streamingCharsRef,
  isStreaming,
  isReceivingContent = true
}) => {
  const streamingState = useStreamingContext();
  const { columns: terminalWidth } = useTerminalSize();
  const isNarrow = isNarrowWidth(terminalWidth);
  const fallbackRef = (0, import_react119.useRef)(0);
  const animatedChars = useAnimationFrame(
    streamingCharsRef ?? fallbackRef,
    streamingCharsRef && isStreaming ? 100 : null
  );
  if (streamingState === "idle" /* Idle */) {
    return null;
  }
  const primaryText = thought?.subject || currentLoadingPhrase;
  const streamingTokens = streamingCharsRef ? Math.round(animatedChars / 4) : 0;
  const outputTokens = (candidatesTokens ?? 0) + streamingTokens;
  const showTokens = !isNarrow && outputTokens > 0;
  const tokenArrow = isReceivingContent ? "\u2193" : "\u2191";
  const timeStr = elapsedTime < 60 ? `${elapsedTime}s` : formatDuration(elapsedTime * 1e3);
  const tokenStr = showTokens ? ` \xB7 ${tokenArrow} ${formatTokenCount(outputTokens)} tokens` : "";
  const cancelAndTimerContent = streamingState !== "waiting_for_confirmation" /* WaitingForConfirmation */ ? t4("({{time}}{{tokens}} \xB7 esc to cancel)", {
    time: timeStr,
    tokens: tokenStr
  }) : null;
  return /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(Box_default, { paddingLeft: 2, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(
      Box_default,
      {
        width: "100%",
        flexDirection: isNarrow ? "column" : "row",
        alignItems: isNarrow ? "flex-start" : "center",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(Box_default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
              GeminiRespondingSpinner,
              {
                nonRespondingDisplay: streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ ? "\u280F" : ""
              }
            ) }),
            primaryText && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Text3, { color: theme.text.accent, wrap: "truncate-end", children: primaryText }),
            !isNarrow && cancelAndTimerContent && /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(Text3, { color: theme.text.secondary, children: [
              " ",
              cancelAndTimerContent
            ] })
          ] }),
          !isNarrow && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { flexGrow: 1 }),
          !isNarrow && rightContent && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { children: rightContent })
        ]
      }
    ),
    isNarrow && cancelAndTimerContent && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Text3, { color: theme.text.secondary, children: cancelAndTimerContent }) }),
    isNarrow && rightContent && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { children: rightContent })
  ] });
}, "LoadingIndicator");

// packages/cli/src/ui/components/InputPrompt.tsx
init_esbuild_shims();
var import_react133 = __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_react120 = __toESM(require_react(), 1);
var import_jsx_runtime125 = __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_runtime125.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 start2 = matchedIndex - beforeSpace;
    let end = matchedIndex + matchLength + afterSpace;
    if (start2 < 0) {
      end += -start2;
      start2 = 0;
    }
    if (end > label.length) {
      start2 -= end - label.length;
      end = label.length;
    }
    start2 = Math.max(0, start2);
    const finalMatchIndex = matchedIndex - start2;
    const slicedLabel = label.slice(start2, end);
    before = slicedLabel.slice(0, finalMatchIndex);
    match2 = slicedLabel.slice(finalMatchIndex, finalMatchIndex + matchLength);
    after = slicedLabel.slice(finalMatchIndex + matchLength);
    if (start2 > 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_runtime125.jsxs)(Text3, { color: textColor, wrap: "wrap", children: [
    before,
    match2 ? match2.split(/(\s+)/).map((part, index) => /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(
      Text3,
      {
        color: theme.background.primary,
        backgroundColor: theme.text.primary,
        children: part
      },
      `match-${index}`
    )) : null,
    after
  ] });
}, "_PrepareLabel");
var PrepareLabel = import_react120.default.memo(_PrepareLabel);

// packages/cli/src/ui/components/SuggestionsDisplay.tsx
init_types21();
var import_jsx_runtime126 = __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_runtime126.jsx)(Box_default, { width, children: /* @__PURE__ */ (0, import_jsx_runtime126.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_runtime126.jsxs)(Box_default, { flexDirection: "column", width, children: [
    scrollOffset > 0 && /* @__PURE__ */ (0, import_jsx_runtime126.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_runtime126.jsx)(
        PrepareLabel,
        {
          label: displayLabel,
          matchedIndex: suggestion.matchedIndex,
          userInput,
          textColor,
          isExpanded
        }
      );
      return /* @__PURE__ */ (0, import_jsx_runtime126.jsxs)(Box_default, { flexDirection: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(
          Box_default,
          {
            ...mode === "slash" ? { width: commandColumnWidth, flexShrink: 0 } : { flexShrink: 1 },
            children: /* @__PURE__ */ (0, import_jsx_runtime126.jsxs)(Box_default, { children: [
              labelElement,
              suggestion.commandKind === "mcp-prompt" /* MCP_PROMPT */ && /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(Text3, { color: textColor, children: " [MCP]" })
            ] })
          }
        ),
        suggestion.description && /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(Box_default, { flexGrow: 1, paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(Text3, { color: textColor, wrap: "truncate", children: suggestion.description }) }),
        isActive && isLong && /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(Text3, { color: Colors.Gray, children: isExpanded ? " \u2190 " : " \u2192 " }) })
      ] }, `${suggestion.value}-${originalIndex}`);
    }),
    endIndex < suggestions.length && /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(Text3, { color: "gray", children: "\u25BC" }),
    suggestions.length > MAX_SUGGESTIONS_TO_SHOW && /* @__PURE__ */ (0, import_jsx_runtime126.jsxs)(Text3, { color: "gray", children: [
      "(",
      activeIndex + 1,
      "/",
      suggestions.length,
      ")"
    ] })
  ] });
}
__name(SuggestionsDisplay, "SuggestionsDisplay");

// packages/cli/src/ui/hooks/useInputHistory.ts
init_esbuild_shims();
var import_react121 = __toESM(require_react(), 1);
function useInputHistory({
  userMessages,
  onSubmit,
  isActive,
  currentQuery,
  onChange
}) {
  const [historyIndex, setHistoryIndex] = (0, import_react121.useState)(-1);
  const [originalQueryBeforeNav, setOriginalQueryBeforeNav] = (0, import_react121.useState)("");
  const resetHistoryNav = (0, import_react121.useCallback)(() => {
    setHistoryIndex(-1);
    setOriginalQueryBeforeNav("");
  }, []);
  const handleSubmit = (0, import_react121.useCallback)(
    (value) => {
      const trimmedValue = value.trim();
      if (trimmedValue) {
        onSubmit(trimmedValue);
      }
      resetHistoryNav();
    },
    [onSubmit, resetHistoryNav]
  );
  const navigateUp = (0, import_react121.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_react121.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,
    resetHistoryNav
  };
}
__name(useInputHistory, "useInputHistory");

// packages/cli/src/ui/components/InputPrompt.tsx
var import_chalk10 = __toESM(require_source(), 1);

// packages/cli/src/ui/hooks/useShellHistory.ts
init_esbuild_shims();
var import_react122 = __toESM(require_react(), 1);
init_dist4();
import * as fs127 from "node:fs/promises";
import * as path132 from "node:path";
var MAX_HISTORY_LENGTH2 = 100;
var debugLogger151 = 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 fs127.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 (err2) {
    if (isNodeError(err2) && err2.code === "ENOENT") return [];
    debugLogger151.error("Error reading history:", err2);
    return [];
  }
}
__name(readHistoryFile, "readHistoryFile");
async function writeHistoryFile(filePath, history) {
  try {
    await fs127.mkdir(path132.dirname(filePath), { recursive: true });
    await fs127.writeFile(filePath, history.join("\n"));
  } catch (error40) {
    debugLogger151.error("Error writing shell history:", error40);
  }
}
__name(writeHistoryFile, "writeHistoryFile");
function useShellHistory(projectRoot, storage) {
  const [history, setHistory] = (0, import_react122.useState)([]);
  const [historyIndex, setHistoryIndex] = (0, import_react122.useState)(-1);
  const [historyFilePath, setHistoryFilePath] = (0, import_react122.useState)(null);
  (0, import_react122.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_react122.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_react122.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_react122.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_react122.useCallback)(() => {
    setHistoryIndex(-1);
  }, []);
  return {
    history,
    addCommandToHistory,
    getPreviousCommand,
    getNextCommand,
    resetHistoryPosition
  };
}
__name(useShellHistory, "useShellHistory");

// packages/cli/src/ui/hooks/useReverseSearchCompletion.tsx
init_esbuild_shims();
var import_react124 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useCompletion.ts
init_esbuild_shims();
var import_react123 = __toESM(require_react(), 1);
function useCompletion() {
  const [suggestions, setSuggestions] = (0, import_react123.useState)([]);
  const [activeSuggestionIndex, setActiveSuggestionIndex] = (0, import_react123.useState)(-1);
  const [visibleStartIndex, setVisibleStartIndex] = (0, import_react123.useState)(0);
  const [showSuggestions, setShowSuggestions] = (0, import_react123.useState)(false);
  const [isLoadingSuggestions, setIsLoadingSuggestions] = (0, import_react123.useState)(false);
  const [isPerfectMatch, setIsPerfectMatch] = (0, import_react123.useState)(false);
  const resetCompletionState = (0, import_react123.useCallback)(() => {
    setSuggestions([]);
    setActiveSuggestionIndex(-1);
    setVisibleStartIndex(0);
    setShowSuggestions(false);
    setIsLoadingSuggestions(false);
    setIsPerfectMatch(false);
  }, []);
  const navigateUp = (0, import_react123.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_react123.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, delay5 = 200) {
  const [debounced, setDebounced] = (0, import_react124.useState)(value);
  (0, import_react124.useEffect)(() => {
    const handle2 = setTimeout(() => setDebounced(value), delay5);
    return () => clearTimeout(handle2);
  }, [value, delay5]);
  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_react124.useRef)("");
  const prevMatchesRef = (0, import_react124.useRef)([]);
  (0, import_react124.useEffect)(() => {
    if (reverseSearchActive) {
      prevQueryRef.current = "";
      prevMatchesRef.current = [];
    }
  }, [reverseSearchActive]);
  (0, import_react124.useEffect)(() => {
    prevQueryRef.current = "";
    prevMatchesRef.current = [];
  }, [history]);
  const searchHistory = (0, import_react124.useCallback)(
    (query, items) => {
      const out2 = [];
      for (let i4 = 0; i4 < items.length; i4++) {
        const cmd = items[i4];
        const idx = cmd.toLowerCase().indexOf(query);
        if (idx !== -1) {
          out2.push({ label: cmd, value: cmd, matchedIndex: idx });
        }
      }
      return out2;
    },
    []
  );
  const matches2 = (0, import_react124.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_react124.useEffect)(() => {
    if (!reverseSearchActive) {
      resetCompletionState();
      return;
    }
    setSuggestions(matches2);
    const hasAny = matches2.length > 0;
    setShowSuggestions(hasAny);
    setActiveSuggestionIndex(hasAny ? 0 : -1);
    setVisibleStartIndex(0);
    prevQueryRef.current = debouncedQuery.toLowerCase();
    prevMatchesRef.current = matches2;
  }, [
    debouncedQuery,
    matches2,
    reverseSearchActive,
    setSuggestions,
    setShowSuggestions,
    setActiveSuggestionIndex,
    setVisibleStartIndex,
    resetCompletionState
  ]);
  const handleAutocomplete = (0, import_react124.useCallback)(
    (i4) => {
      if (i4 < 0 || i4 >= suggestions.length) return;
      buffer.setText(suggestions[i4].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_react127 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useAtCompletion.ts
init_esbuild_shims();
var import_react125 = __toESM(require_react(), 1);
init_dist4();
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: enabled2,
    pattern,
    config: config2,
    cwd: cwd6,
    setSuggestions,
    setIsLoadingSuggestions
  } = props;
  const [state, dispatch] = (0, import_react125.useReducer)(atCompletionReducer, initialState);
  const fileSearch = (0, import_react125.useRef)(null);
  const searchAbortController = (0, import_react125.useRef)(null);
  const slowSearchTimer = (0, import_react125.useRef)(null);
  (0, import_react125.useEffect)(() => {
    setSuggestions(state.suggestions);
  }, [state.suggestions, setSuggestions]);
  (0, import_react125.useEffect)(() => {
    setIsLoadingSuggestions(state.isLoading);
  }, [state.isLoading, setIsLoadingSuggestions]);
  (0, import_react125.useEffect)(() => {
    dispatch({ type: "RESET" });
  }, [cwd6, config2]);
  (0, import_react125.useEffect)(() => {
    if (!enabled2) {
      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 });
    }
  }, [enabled2, pattern, state.status, state.pattern]);
  (0, import_react125.useEffect)(() => {
    const initialize = /* @__PURE__ */ __name(async () => {
      try {
        const searcher = FileSearchFactory.create({
          projectRoot: cwd6,
          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 (error40) {
        if (!(error40 instanceof Error && error40.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, cwd6]);
}
__name(useAtCompletion, "useAtCompletion");

// packages/cli/src/ui/hooks/useSlashCompletion.ts
init_esbuild_shims();
var import_react126 = __toESM(require_react(), 1);
init_fzf_es();
init_dist4();
init_types21();
var debugLogger152 = createDebugLogger("SLASH_COMPLETION");
function logErrorSafely(error40, context2) {
  if (error40 instanceof Error) {
    debugLogger152.error(`[${context2}]`, error40);
  } else {
    debugLogger152.error(`[${context2}] Non-error thrown:`, error40);
  }
}
__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_react126.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 getCompletionPriority(command2) {
  return command2.completionPriority ?? 0;
}
__name(getCompletionPriority, "getCompletionPriority");
function isSegmentBoundary(value, start2) {
  if (start2 <= 0) {
    return false;
  }
  return ["-", "_", "/", " "].includes(value[start2 - 1] ?? "");
}
__name(isSegmentBoundary, "isSegmentBoundary");
function getCommandMatchStrength(matchedValue, query, start2) {
  const normalizedValue = matchedValue.toLowerCase();
  const normalizedQuery = query.toLowerCase();
  if (normalizedValue === normalizedQuery) {
    return 3 /* EXACT */;
  }
  if (normalizedValue.startsWith(normalizedQuery)) {
    return 2 /* PREFIX */;
  }
  if (start2 > 0 && normalizedValue.slice(start2).startsWith(normalizedQuery) && isSegmentBoundary(normalizedValue, start2)) {
    return 1 /* SEGMENT_PREFIX */;
  }
  return 0 /* FUZZY */;
}
__name(getCommandMatchStrength, "getCommandMatchStrength");
function compareRankedCommandMatches(left3, right3) {
  return right3.matchStrength - left3.matchStrength || right3.completionPriority - left3.completionPriority || right3.score - left3.score || left3.start - right3.start || left3.itemLength - right3.itemLength || left3.originalIndex - right3.originalIndex;
}
__name(compareRankedCommandMatches, "compareRankedCommandMatches");
function createRankedCommandMatch(command2, matchedValue, query, result, originalIndex) {
  return {
    command: command2,
    matchStrength: getCommandMatchStrength(matchedValue, query, result.start),
    completionPriority: getCompletionPriority(command2),
    score: result.score,
    start: result.start,
    itemLength: matchedValue.length,
    originalIndex
  };
}
__name(createRankedCommandMatch, "createRankedCommandMatch");
function useCommandSuggestions(parserResult, commandContext, getFzfForCommands, getPrefixSuggestions) {
  const [suggestions, setSuggestions] = (0, import_react126.useState)([]);
  const [isLoading, setIsLoading] = (0, import_react126.useState)(false);
  (0, import_react126.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) {
          debugLogger152.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 (error40) {
          if (!signal.aborted) {
            logErrorSafely(error40, "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 commandOrder = /* @__PURE__ */ new Map();
              commandsToSearch.forEach((cmd, index) => {
                commandOrder.set(cmd, index);
              });
              const rankedMatches = /* @__PURE__ */ new Map();
              fzfResults.forEach((result) => {
                const cmd = fzfInstance.commandMap.get(result.item);
                const originalIndex = cmd ? commandOrder.get(cmd) : void 0;
                if (cmd && cmd.description && originalIndex !== void 0) {
                  const rankedMatch = createRankedCommandMatch(
                    cmd,
                    result.item,
                    partial2,
                    result,
                    originalIndex
                  );
                  const existingRank = rankedMatches.get(cmd);
                  if (!existingRank || compareRankedCommandMatches(rankedMatch, existingRank) < 0) {
                    rankedMatches.set(cmd, rankedMatch);
                  }
                }
              });
              potentialSuggestions = Array.from(rankedMatches.values()).sort(compareRankedCommandMatches).map((match2) => match2.command);
            } catch (error40) {
              logErrorSafely(
                error40,
                "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((error40) => {
        logErrorSafely(error40, "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_react126.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_react126.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: enabled2,
    query,
    slashCommands,
    commandContext,
    setSuggestions,
    setIsLoadingSuggestions,
    setIsPerfectMatch
  } = props;
  const [completionStart, setCompletionStart] = (0, import_react126.useState)(-1);
  const [completionEnd, setCompletionEnd] = (0, import_react126.useState)(-1);
  const fzfInstanceCache = (0, import_react126.useMemo)(
    () => /* @__PURE__ */ new WeakMap(),
    []
  );
  const getFzfForCommands = (0, import_react126.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 instance2 = {
          fzf: new AsyncFzf(commandItems, {
            fuzzy: "v2",
            casing: "case-insensitive"
            // Explicitly enforce case-insensitivity
          }),
          commandMap
        };
        fzfInstanceCache.set(commands, instance2);
        return instance2;
      } catch (error40) {
        logErrorSafely(error40, "FZF instance creation");
        return null;
      }
    },
    [fzfInstanceCache]
  );
  const getPrefixSuggestions = (0, import_react126.useMemo)(
    () => (commands, partial2) => {
      const rankedMatches = commands.flatMap((cmd, index) => {
        if (!cmd.description || cmd.hidden) {
          return [];
        }
        const matchedValues = [cmd.name, ...cmd.altNames ?? []].filter(
          (value) => value.toLowerCase().startsWith(partial2.toLowerCase())
        );
        if (matchedValues.length === 0) {
          return [];
        }
        const bestMatch = matchedValues.map(
          (matchedValue) => createRankedCommandMatch(
            cmd,
            matchedValue,
            partial2,
            {
              score: matchedValue.toLowerCase() === partial2.toLowerCase() ? 100 : 80,
              start: 0
            },
            index
          )
        ).sort(compareRankedCommandMatches)[0];
        return bestMatch ? [bestMatch] : [];
      });
      return rankedMatches.sort(compareRankedCommandMatches).map((match2) => match2.command);
    },
    []
  );
  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_react126.useEffect)(() => {
    if (!enabled2) {
      setSuggestions([]);
      setIsLoadingSuggestions(false);
      setIsPerfectMatch(false);
      setCompletionStart(-1);
      setCompletionEnd(-1);
    }
  }, [enabled2, setSuggestions, setIsLoadingSuggestions, setIsPerfectMatch]);
  (0, import_react126.useEffect)(() => {
    if (!enabled2 || query === null) {
      return;
    }
    setSuggestions(hookSuggestions);
    setIsLoadingSuggestions(isLoading);
    setIsPerfectMatch(isPerfectMatch);
    setCompletionStart(calculatedStart);
    setCompletionEnd(calculatedEnd);
  }, [
    enabled2,
    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, cwd6, 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_react127.useMemo)(() => {
    const currentLine = buffer.lines[cursorRow] || "";
    const codePoints = toCodePoints(currentLine);
    for (let i4 = cursorCol - 1; i4 >= 0; i4--) {
      const char = codePoints[i4];
      if (char === " ") {
        let backslashCount = 0;
        for (let j2 = i4 - 1; j2 >= 0 && codePoints[j2] === "\\"; j2--) {
          backslashCount++;
        }
        if (backslashCount % 2 === 0) {
          break;
        }
      } else if (char === "@") {
        let end = codePoints.length;
        for (let i5 = cursorCol; i5 < codePoints.length; i5++) {
          if (codePoints[i5] === " ") {
            let backslashCount = 0;
            for (let j2 = i5 - 1; j2 >= 0 && codePoints[j2] === "\\"; j2--) {
              backslashCount++;
            }
            if (backslashCount % 2 === 0) {
              end = i5;
              break;
            }
          }
        }
        const pathStart = i4 + 1;
        const partialPath = currentLine.substring(pathStart, end);
        return {
          completionMode: "AT" /* AT */,
          query: partialPath,
          completionStart: pathStart,
          completionEnd: end
        };
      }
    }
    if (cursorRow === 0 && isSlashCommand(currentLine.trim())) {
      return {
        completionMode: "SLASH" /* SLASH */,
        query: currentLine,
        completionStart: 0,
        completionEnd: currentLine.length
      };
    }
    return {
      completionMode: "IDLE" /* IDLE */,
      query: null,
      completionStart: -1,
      completionEnd: -1
    };
  }, [cursorRow, cursorCol, buffer.lines]);
  useAtCompletion({
    enabled: completionMode === "AT" /* AT */,
    pattern: query || "",
    config: config2,
    cwd: cwd6,
    setSuggestions,
    setIsLoadingSuggestions
  });
  const slashCompletionRange = useSlashCompletion({
    enabled: completionMode === "SLASH" /* SLASH */,
    query,
    slashCommands,
    commandContext,
    setSuggestions,
    setIsLoadingSuggestions,
    setIsPerfectMatch
  });
  (0, import_react127.useEffect)(() => {
    setActiveSuggestionIndex(suggestions.length > 0 ? 0 : -1);
    setVisibleStartIndex(0);
  }, [suggestions, setActiveSuggestionIndex, setVisibleStartIndex]);
  (0, import_react127.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_react127.useCallback)(
    (indexToUse) => {
      if (indexToUse < 0 || indexToUse >= suggestions.length) {
        return;
      }
      const suggestion = suggestions[indexToUse].value;
      let start2 = completionStart;
      let end = completionEnd;
      if (completionMode === "SLASH" /* SLASH */) {
        const lineOffset = completionStart;
        start2 = lineOffset + slashCompletionRange.completionStart;
        end = lineOffset + slashCompletionRange.completionEnd;
      }
      if (start2 === -1 || end === -1) {
        return;
      }
      let suggestionText = suggestion;
      if (completionMode === "SLASH" /* SLASH */) {
        if (start2 === end && start2 > 1 && (buffer.lines[cursorRow] || "")[start2 - 1] !== " ") {
          suggestionText = " " + suggestionText;
        }
      }
      const lineCodePoints = toCodePoints(buffer.lines[cursorRow] || "");
      const charAfterCompletion = lineCodePoints[end];
      if (charAfterCompletion !== " ") {
        suggestionText += " ";
      }
      buffer.replaceRangeByOffset(
        logicalPosToOffset(buffer.lines, cursorRow, start2),
        logicalPosToOffset(buffer.lines, cursorRow, end),
        suggestionText
      );
    },
    [
      cursorRow,
      buffer,
      suggestions,
      completionMode,
      completionStart,
      completionEnd,
      slashCompletionRange
    ]
  );
  const midInputGhostText = (0, import_react127.useMemo)(() => {
    if (!active || reverseSearchActive) return null;
    const cursorOffset = logicalPosToOffset(buffer.lines, cursorRow, cursorCol);
    const midCmd = findMidInputSlashCommand(buffer.text, cursorOffset);
    if (midCmd) {
      const match2 = getBestSlashCommandMatch(
        midCmd.partialCommand,
        slashCommands
      );
      if (!match2) return null;
      return {
        text: match2.suffix,
        insertPosition: cursorOffset,
        acceptText: match2.suffix
      };
    }
    if (cursorRow !== 0) return null;
    const currentLine = buffer.lines[cursorRow] || "";
    const lineCodePoints = toCodePoints(currentLine);
    if (cursorCol !== lineCodePoints.length) return null;
    const lineToCursor = lineCodePoints.slice(0, cursorCol).join("");
    if (!isSlashCommand(lineToCursor.trim())) return null;
    const { commandToExecute, args: args2 } = parseSlashCommand(
      lineToCursor,
      slashCommands
    );
    if (!commandToExecute?.argumentHint || args2.trim().length > 0) {
      return null;
    }
    return {
      text: commandToExecute.argumentHint,
      insertPosition: cursorOffset,
      showCursorBeforeText: true
    };
  }, [
    buffer.text,
    buffer.lines,
    cursorRow,
    cursorCol,
    slashCommands,
    active,
    reverseSearchActive
  ]);
  return {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    showSuggestions,
    isLoadingSuggestions,
    isPerfectMatch,
    setActiveSuggestionIndex,
    setShowSuggestions,
    resetCompletionState,
    navigateUp,
    navigateDown,
    handleAutocomplete,
    midInputGhostText
  };
}
__name(useCommandCompletion, "useCommandCompletion");

// packages/cli/src/ui/hooks/useFollowupSuggestions.tsx
init_esbuild_shims();
var import_react128 = __toESM(require_react(), 1);
init_dist4();
function useFollowupSuggestionsCLI(options2 = {}) {
  const { enabled: enabled2 = true, onAccept, config: config2, isFocused = true } = options2;
  const [state, setState] = (0, import_react128.useState)(INITIAL_FOLLOWUP_STATE);
  const onAcceptRef = (0, import_react128.useRef)(onAccept);
  onAcceptRef.current = onAccept;
  const configRef = (0, import_react128.useRef)(config2);
  configRef.current = config2;
  const firstKeystrokeAtRef = (0, import_react128.useRef)(0);
  const prevShownAtRef = (0, import_react128.useRef)(0);
  const wasFocusedWhenShownRef = (0, import_react128.useRef)(true);
  (0, import_react128.useEffect)(() => {
    if (state.shownAt > 0 && state.shownAt !== prevShownAtRef.current) {
      prevShownAtRef.current = state.shownAt;
      wasFocusedWhenShownRef.current = isFocused;
      firstKeystrokeAtRef.current = 0;
    } else if (state.shownAt === 0) {
      prevShownAtRef.current = 0;
    }
  }, [state.shownAt, isFocused]);
  const recordKeystroke = (0, import_react128.useCallback)(() => {
    if (firstKeystrokeAtRef.current === 0 && state.isVisible) {
      firstKeystrokeAtRef.current = Date.now();
    }
  }, [state.isVisible]);
  const onOutcome = (0, import_react128.useCallback)(
    (params) => {
      const cfg = configRef.current;
      if (!cfg) return;
      logPromptSuggestion(
        cfg,
        new PromptSuggestionEvent({
          outcome: params.outcome,
          accept_method: params.accept_method,
          ...params.outcome === "accepted" ? { time_to_accept_ms: params.time_ms } : { time_to_ignore_ms: params.time_ms },
          ...firstKeystrokeAtRef.current > 0 && prevShownAtRef.current > 0 && {
            time_to_first_keystroke_ms: firstKeystrokeAtRef.current - prevShownAtRef.current
          },
          suggestion_length: params.suggestion_length,
          similarity: params.outcome === "accepted" ? 1 : 0,
          was_focused_when_shown: wasFocusedWhenShownRef.current
        })
      );
    },
    []
  );
  const controller = (0, import_react128.useMemo)(
    () => createFollowupController({
      enabled: enabled2,
      onStateChange: setState,
      getOnAccept: /* @__PURE__ */ __name(() => onAcceptRef.current, "getOnAccept"),
      onOutcome
    }),
    [enabled2, onOutcome]
  );
  (0, import_react128.useEffect)(() => {
    if (!enabled2) {
      controller.clear();
    }
    return () => controller.cleanup();
  }, [controller, enabled2]);
  return (0, import_react128.useMemo)(
    () => ({
      state,
      setSuggestion: controller.setSuggestion,
      accept: controller.accept,
      dismiss: controller.dismiss,
      clear: controller.clear,
      recordKeystroke
    }),
    [state, controller, recordKeystroke]
  );
}
__name(useFollowupSuggestionsCLI, "useFollowupSuggestionsCLI");

// packages/cli/src/ui/components/InputPrompt.tsx
init_dist4();

// 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
init_i18n();
import * as path133 from "node:path";

// packages/cli/src/ui/contexts/ShellFocusContext.tsx
init_esbuild_shims();
var import_react129 = __toESM(require_react(), 1);
var ShellFocusContext = (0, import_react129.createContext)(true);
var useShellFocusState = /* @__PURE__ */ __name(() => (0, import_react129.useContext)(ShellFocusContext), "useShellFocusState");

// packages/cli/src/ui/contexts/AgentViewContext.tsx
init_esbuild_shims();
var import_react131 = __toESM(require_react(), 1);
init_dist4();

// packages/cli/src/ui/hooks/useArenaInProcess.ts
init_esbuild_shims();
var import_react130 = __toESM(require_react(), 1);
init_dist4();
var AGENT_COLORS = [
  theme.text.accent,
  theme.text.link,
  theme.status.success,
  theme.status.warning,
  theme.text.code,
  theme.status.error
];
function useArenaInProcess(config2, actions) {
  const actionsRef = (0, import_react130.useRef)(actions);
  actionsRef.current = actions;
  (0, import_react130.useEffect)(() => {
    if (!config2) return;
    let detachArenaListeners = null;
    const retryTimeouts = /* @__PURE__ */ new Set();
    const detachSession = /* @__PURE__ */ __name(() => {
      actionsRef.current.unregisterAll();
      for (const t5 of retryTimeouts) clearTimeout(t5);
      retryTimeouts.clear();
      detachArenaListeners?.();
      detachArenaListeners = null;
    }, "detachSession");
    const attachSession = /* @__PURE__ */ __name((manager) => {
      const emitter = manager.getEventEmitter();
      let colorIndex = 0;
      const nextColor = /* @__PURE__ */ __name(() => AGENT_COLORS[colorIndex++ % AGENT_COLORS.length], "nextColor");
      const getInProcessBackend = /* @__PURE__ */ __name(() => {
        const backend = manager.getBackend();
        if (!backend || backend.type !== DISPLAY_MODE.IN_PROCESS) return null;
        return backend;
      }, "getInProcessBackend");
      const inProcessBackend = getInProcessBackend();
      if (inProcessBackend) {
        for (const agentState of manager.getAgentStates()) {
          const interactive = inProcessBackend.getAgent(agentState.agentId);
          if (interactive) {
            actionsRef.current.registerAgent(
              agentState.agentId,
              interactive,
              agentState.model.modelId,
              nextColor(),
              agentState.model.displayName
            );
          }
        }
      }
      const MAX_RETRIES = 20;
      const RETRY_MS = 50;
      const onAgentStart = /* @__PURE__ */ __name((event) => {
        const tryRegister = /* @__PURE__ */ __name((retriesLeft) => {
          const backend = getInProcessBackend();
          if (!backend) return;
          const interactive = backend.getAgent(event.agentId);
          if (interactive) {
            actionsRef.current.registerAgent(
              event.agentId,
              interactive,
              event.model.modelId,
              nextColor(),
              event.model.displayName
            );
            return;
          }
          if (retriesLeft > 0) {
            const timeout2 = setTimeout(() => {
              retryTimeouts.delete(timeout2);
              tryRegister(retriesLeft - 1);
            }, RETRY_MS);
            retryTimeouts.add(timeout2);
          }
        }, "tryRegister");
        tryRegister(MAX_RETRIES);
      }, "onAgentStart");
      const onSessionComplete = /* @__PURE__ */ __name((event) => {
        if (event.result.status === ArenaSessionStatus.IDLE) return;
        detachSession();
      }, "onSessionComplete");
      const onSessionError = /* @__PURE__ */ __name(() => detachSession(), "onSessionError");
      emitter.on(ArenaEventType.AGENT_START, onAgentStart);
      emitter.on(ArenaEventType.SESSION_COMPLETE, onSessionComplete);
      emitter.on(ArenaEventType.SESSION_ERROR, onSessionError);
      detachArenaListeners = /* @__PURE__ */ __name(() => {
        emitter.off(ArenaEventType.AGENT_START, onAgentStart);
        emitter.off(ArenaEventType.SESSION_COMPLETE, onSessionComplete);
        emitter.off(ArenaEventType.SESSION_ERROR, onSessionError);
      }, "detachArenaListeners");
    }, "attachSession");
    const handleManagerChange = /* @__PURE__ */ __name((manager) => {
      detachSession();
      if (manager) {
        attachSession(manager);
      }
    }, "handleManagerChange");
    config2.onArenaManagerChange(handleManagerChange);
    const current = config2.getArenaManager();
    if (current) {
      attachSession(current);
    }
    return () => {
      config2.onArenaManagerChange(null);
      detachSession();
    };
  }, [config2]);
}
__name(useArenaInProcess, "useArenaInProcess");

// packages/cli/src/ui/contexts/AgentViewContext.tsx
var import_jsx_runtime127 = __toESM(require_jsx_runtime(), 1);
var AgentViewStateContext = (0, import_react131.createContext)(null);
var AgentViewActionsContext = (0, import_react131.createContext)(null);
var DEFAULT_STATE2 = {
  activeView: "main",
  agents: /* @__PURE__ */ new Map(),
  agentShellFocused: false,
  agentInputBufferText: "",
  agentTabBarFocused: false,
  agentApprovalModes: /* @__PURE__ */ new Map()
};
var noop9 = /* @__PURE__ */ __name(() => {
}, "noop");
var DEFAULT_ACTIONS2 = {
  switchToMain: noop9,
  switchToAgent: noop9,
  switchToNext: noop9,
  switchToPrevious: noop9,
  registerAgent: noop9,
  unregisterAgent: noop9,
  unregisterAll: noop9,
  setAgentShellFocused: noop9,
  setAgentInputBufferText: noop9,
  setAgentTabBarFocused: noop9,
  setAgentApprovalMode: noop9
};
function useAgentViewState() {
  return (0, import_react131.useContext)(AgentViewStateContext) ?? DEFAULT_STATE2;
}
__name(useAgentViewState, "useAgentViewState");
function useAgentViewActions() {
  return (0, import_react131.useContext)(AgentViewActionsContext) ?? DEFAULT_ACTIONS2;
}
__name(useAgentViewActions, "useAgentViewActions");
function AgentViewProvider({
  config: config2,
  children
}) {
  const [activeView, setActiveView] = (0, import_react131.useState)("main");
  const [agents, setAgents] = (0, import_react131.useState)(
    () => /* @__PURE__ */ new Map()
  );
  const [agentShellFocused, setAgentShellFocused] = (0, import_react131.useState)(false);
  const [agentInputBufferText, setAgentInputBufferText] = (0, import_react131.useState)("");
  const [agentTabBarFocused, setAgentTabBarFocused] = (0, import_react131.useState)(false);
  const [agentApprovalModes, setAgentApprovalModes] = (0, import_react131.useState)(() => /* @__PURE__ */ new Map());
  const switchToMain = (0, import_react131.useCallback)(() => {
    setActiveView("main");
    setAgentTabBarFocused(false);
  }, []);
  const switchToAgent = (0, import_react131.useCallback)(
    (agentId) => {
      if (agents.has(agentId)) {
        setActiveView(agentId);
      }
    },
    [agents]
  );
  const switchToNext = (0, import_react131.useCallback)(() => {
    const ids = ["main", ...agents.keys()];
    const currentIndex = ids.indexOf(activeView);
    const nextIndex = (currentIndex + 1) % ids.length;
    setActiveView(ids[nextIndex]);
  }, [agents, activeView]);
  const switchToPrevious = (0, import_react131.useCallback)(() => {
    const ids = ["main", ...agents.keys()];
    const currentIndex = ids.indexOf(activeView);
    const prevIndex = (currentIndex - 1 + ids.length) % ids.length;
    setActiveView(ids[prevIndex]);
  }, [agents, activeView]);
  const registerAgent = (0, import_react131.useCallback)(
    (agentId, interactiveAgent, modelId, color, modelName) => {
      setAgents((prev) => {
        const next = new Map(prev);
        next.set(agentId, {
          interactiveAgent,
          modelId,
          color,
          modelName
        });
        return next;
      });
      const mode = interactiveAgent.getCore().runtimeContext.getApprovalMode();
      setAgentApprovalModes((prev) => {
        const next = new Map(prev);
        next.set(agentId, mode);
        return next;
      });
    },
    []
  );
  const unregisterAgent = (0, import_react131.useCallback)((agentId) => {
    setAgents((prev) => {
      if (!prev.has(agentId)) return prev;
      const next = new Map(prev);
      next.delete(agentId);
      return next;
    });
    setAgentApprovalModes((prev) => {
      if (!prev.has(agentId)) return prev;
      const next = new Map(prev);
      next.delete(agentId);
      return next;
    });
    setActiveView((current) => current === agentId ? "main" : current);
  }, []);
  const unregisterAll = (0, import_react131.useCallback)(() => {
    setAgents(/* @__PURE__ */ new Map());
    setAgentApprovalModes(/* @__PURE__ */ new Map());
    setActiveView("main");
    setAgentTabBarFocused(false);
  }, []);
  const setAgentApprovalMode = (0, import_react131.useCallback)(
    (agentId, mode) => {
      const agent = agents.get(agentId);
      if (agent) {
        agent.interactiveAgent.getCore().runtimeContext.setApprovalMode(mode);
      }
      setAgentApprovalModes((prev) => {
        const next = new Map(prev);
        next.set(agentId, mode);
        return next;
      });
    },
    [agents]
  );
  const state = (0, import_react131.useMemo)(
    () => ({
      activeView,
      agents,
      agentShellFocused,
      agentInputBufferText,
      agentTabBarFocused,
      agentApprovalModes
    }),
    [
      activeView,
      agents,
      agentShellFocused,
      agentInputBufferText,
      agentTabBarFocused,
      agentApprovalModes
    ]
  );
  const actions = (0, import_react131.useMemo)(
    () => ({
      switchToMain,
      switchToAgent,
      switchToNext,
      switchToPrevious,
      registerAgent,
      unregisterAgent,
      unregisterAll,
      setAgentShellFocused,
      setAgentInputBufferText,
      setAgentTabBarFocused,
      setAgentApprovalMode
    }),
    [
      switchToMain,
      switchToAgent,
      switchToNext,
      switchToPrevious,
      registerAgent,
      unregisterAgent,
      unregisterAll,
      setAgentShellFocused,
      setAgentInputBufferText,
      setAgentTabBarFocused,
      setAgentApprovalMode
    ]
  );
  useArenaInProcess(config2 ?? null, actions);
  return /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(AgentViewStateContext.Provider, { value: state, children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(AgentViewActionsContext.Provider, { value: actions, children }) });
}
__name(AgentViewProvider, "AgentViewProvider");

// packages/cli/src/ui/FeedbackDialog.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime128 = __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_runtime128.jsxs)(Box_default, { flexDirection: "column", marginY: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text3, { color: "cyan", children: "\u25CF " }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text3, { bold: true, children: t4("How is Qwen doing this session? (optional)") })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(Box_default, { marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(Text3, { color: "cyan", children: [
        FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.GOOD],
        ":",
        " "
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text3, { children: t4("Good") }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text3, { children: " " }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(Text3, { color: "cyan", children: [
        FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.BAD],
        ": "
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text3, { children: t4("Bad") }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text3, { children: " " }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(Text3, { color: "cyan", children: [
        FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.FINE],
        ":",
        " "
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text3, { children: t4("Fine") }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text3, { children: " " }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(Text3, { color: "cyan", children: [
        FEEDBACK_OPTION_KEYS[FEEDBACK_OPTIONS.DISMISS],
        ":",
        " "
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text3, { children: t4("Dismiss") }),
      /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text3, { children: " " })
    ] })
  ] });
}, "FeedbackDialog");

// packages/cli/src/ui/components/BaseTextInput.tsx
init_esbuild_shims();
var import_react132 = __toESM(require_react(), 1);
var import_chalk9 = __toESM(require_source(), 1);
var import_jsx_runtime129 = __toESM(require_jsx_runtime(), 1);
function defaultRenderLine({
  lineText,
  isOnCursorLine,
  cursorCol,
  showCursor
}) {
  if (!isOnCursorLine || !showCursor) {
    return /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(Text3, { children: lineText || " " });
  }
  const len = cpLen(lineText);
  if (cursorCol >= len) {
    return /* @__PURE__ */ (0, import_jsx_runtime129.jsxs)(Text3, { children: [
      lineText,
      import_chalk9.default.inverse(" ") + "\u200B"
    ] });
  }
  const before = cpSlice(lineText, 0, cursorCol);
  const cursorChar = cpSlice(lineText, cursorCol, cursorCol + 1);
  const after = cpSlice(lineText, cursorCol + 1);
  return /* @__PURE__ */ (0, import_jsx_runtime129.jsxs)(Text3, { children: [
    before,
    import_chalk9.default.inverse(cursorChar),
    after
  ] });
}
__name(defaultRenderLine, "defaultRenderLine");
var BaseTextInput = /* @__PURE__ */ __name(({
  buffer,
  onSubmit,
  onKeypress,
  showCursor = true,
  placeholder,
  prefix,
  borderColor,
  topRightLabel,
  isActive = true,
  renderLine = defaultRenderLine
}) => {
  const handleKey = (0, import_react132.useCallback)(
    (key) => {
      if (onKeypress?.(key)) {
        return;
      }
      if (keyMatchers["submit" /* SUBMIT */](key)) {
        if (buffer.text.trim()) {
          const text = buffer.text;
          buffer.setText("");
          onSubmit(text);
        }
        return;
      }
      if (keyMatchers["newline" /* NEWLINE */](key)) {
        buffer.newline();
        return;
      }
      if (keyMatchers["escape" /* ESCAPE */](key)) {
        if (buffer.text.length > 0) {
          buffer.setText("");
        }
        return;
      }
      if (keyMatchers["clearInput" /* CLEAR_INPUT */](key)) {
        if (buffer.text.length > 0) {
          buffer.setText("");
        }
        return;
      }
      if (keyMatchers["home" /* HOME */](key)) {
        buffer.move("home");
        return;
      }
      if (keyMatchers["end" /* END */](key)) {
        buffer.move("end");
        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 ((key.name === "tab" || key.sequence === "	") && !key.paste) {
        return;
      }
      if (key.name === "backspace" || key.sequence === "\x7F" || key.ctrl && key.name === "h") {
        buffer.backspace();
        return;
      }
      buffer.handleInput(key);
    },
    [buffer, onSubmit, onKeypress]
  );
  useKeypress(handleKey, { isActive });
  const linesToRender = buffer.viewportVisualLines;
  const [cursorVisualRow, cursorVisualCol] = buffer.visualCursor;
  const scrollVisualRow = buffer.visualScrollRow;
  const resolvedBorderColor = borderColor ?? theme.border.focused;
  const resolvedPrefix = prefix ?? /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(Text3, { color: theme.text.accent, children: "> " });
  const columns = process.stdout.columns || 80;
  const labelWidth = topRightLabel ? stringWidth4(topRightLabel) + 4 : 0;
  const dashCount = Math.max(1, columns - labelWidth);
  const topBorderLine = topRightLabel ? `${"\u2500".repeat(dashCount)} ${topRightLabel} ${"\u2500".repeat(2)}` : "\u2500".repeat(columns);
  return /* @__PURE__ */ (0, import_jsx_runtime129.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(Text3, { color: resolvedBorderColor, wrap: "truncate-end", children: topBorderLine }),
    /* @__PURE__ */ (0, import_jsx_runtime129.jsxs)(
      Box_default,
      {
        borderStyle: "single",
        borderTop: false,
        borderBottom: true,
        borderLeft: false,
        borderRight: false,
        borderColor: resolvedBorderColor,
        children: [
          resolvedPrefix,
          /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: buffer.text.length === 0 && placeholder ? showCursor ? /* @__PURE__ */ (0, import_jsx_runtime129.jsxs)(Text3, { children: [
            import_chalk9.default.inverse(placeholder.slice(0, 1)),
            /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(Text3, { color: theme.text.secondary, children: placeholder.slice(1) })
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(Text3, { color: theme.text.secondary, children: placeholder }) : linesToRender.map((lineText, idx) => {
            const absoluteVisualIndex = scrollVisualRow + idx;
            const isOnCursorLine = absoluteVisualIndex === cursorVisualRow;
            return /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(Box_default, { height: 1, children: renderLine({
              lineText,
              isOnCursorLine,
              cursorCol: cursorVisualCol,
              showCursor,
              visualLineIndex: idx,
              absoluteVisualIndex,
              buffer,
              scrollVisualRow
            }) }, idx);
          }) })
        ]
      }
    )
  ] });
}, "BaseTextInput");

// packages/cli/src/ui/utils/layoutUtils.ts
init_esbuild_shims();
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");

// packages/cli/src/ui/components/InputPrompt.tsx
var import_jsx_runtime130 = __toESM(require_jsx_runtime(), 1);
var debugLogger153 = createDebugLogger("INPUT_PROMPT");
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,
  promptSuggestion,
  onPromptSuggestionDismiss
}) => {
  const isShellFocused = useShellFocusState();
  const uiState = useUIState();
  const uiActions = useUIActions();
  const { pasteWorkaround } = useKeypressContext();
  const { agents, agentTabBarFocused } = useAgentViewState();
  const { setAgentTabBarFocused } = useAgentViewActions();
  const {
    entries: bgEntries,
    dialogOpen: bgDialogOpen,
    pillFocused: bgPillFocused
  } = useBackgroundTaskViewState();
  const { setPillFocused: setBgPillFocused } = useBackgroundTaskViewActions();
  const hasAgents = agents.size > 0;
  const hasBgAgents = bgEntries.length > 0;
  const [justNavigatedHistory, setJustNavigatedHistory] = (0, import_react133.useState)(false);
  const [escPressCount, setEscPressCount] = (0, import_react133.useState)(0);
  const [showEscapePrompt, setShowEscapePrompt] = (0, import_react133.useState)(false);
  const escapeTimerRef = (0, import_react133.useRef)(null);
  const [recentPasteTime, setRecentPasteTime] = (0, import_react133.useState)(null);
  const pasteTimeoutRef = (0, import_react133.useRef)(null);
  const [attachments, setAttachments] = (0, import_react133.useState)([]);
  const [isAttachmentMode, setIsAttachmentMode] = (0, import_react133.useState)(false);
  const [selectedAttachmentIndex, setSelectedAttachmentIndex] = (0, import_react133.useState)(-1);
  const [pendingPastes, setPendingPastes] = (0, import_react133.useState)(
    /* @__PURE__ */ new Map()
  );
  const activePlaceholderIds = (0, import_react133.useRef)(/* @__PURE__ */ new Map());
  const parsePlaceholder = (0, import_react133.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_react133.useCallback)((charCount, id) => {
    const activeIds = activePlaceholderIds.current.get(charCount);
    if (activeIds) {
      activeIds.delete(id);
      if (activeIds.size === 0) {
        activePlaceholderIds.current.delete(charCount);
      }
    }
  }, []);
  const [reverseSearchActive, setReverseSearchActive] = (0, import_react133.useState)(false);
  const [commandSearchActive, setCommandSearchActive] = (0, import_react133.useState)(false);
  const [textBeforeReverseSearch, setTextBeforeReverseSearch] = (0, import_react133.useState)("");
  const [cursorPosition, setCursorPosition] = (0, import_react133.useState)([
    0,
    0
  ]);
  const [expandedSuggestionIndex, setExpandedSuggestionIndex] = (0, import_react133.useState)(-1);
  const shellHistory = useShellHistory(config2.getProjectRoot());
  const shellHistoryData = shellHistory.history;
  const completion3 = useCommandCompletion(
    buffer,
    config2.getTargetDir(),
    slashCommands,
    commandContext,
    reverseSearchActive,
    config2,
    // Suppress completion when history navigation just occurred
    !justNavigatedHistory
  );
  const midInputGhostTextRef = (0, import_react133.useRef)(null);
  midInputGhostTextRef.current = completion3.midInputGhostText;
  const reverseSearchCompletion = useReverseSearchCompletion(
    buffer,
    shellHistoryData,
    reverseSearchActive
  );
  const commandSearchHistory = (0, import_react133.useMemo)(
    () => [...userMessages].reverse(),
    [userMessages]
  );
  const commandSearchCompletion = useReverseSearchCompletion(
    buffer,
    commandSearchHistory,
    commandSearchActive
  );
  const followup = useFollowupSuggestionsCLI({
    onAccept: /* @__PURE__ */ __name((suggestion) => {
      buffer.insert(suggestion);
    }, "onAccept"),
    config: config2,
    isFocused: isShellFocused
  });
  const resetCompletionState = completion3.resetCompletionState;
  const resetReverseSearchCompletionState = reverseSearchCompletion.resetCompletionState;
  const resetCommandSearchCompletionState = commandSearchCompletion.resetCompletionState;
  const showCursor = focus && isShellFocused && !isEmbeddedShellFocused && !agentTabBarFocused;
  const resetEscapeState = (0, import_react133.useCallback)(() => {
    if (escapeTimerRef.current) {
      clearTimeout(escapeTimerRef.current);
      escapeTimerRef.current = null;
    }
    setEscPressCount(0);
    setShowEscapePrompt(false);
  }, []);
  (0, import_react133.useEffect)(() => {
    if (onEscapePromptChange) {
      onEscapePromptChange(showEscapePrompt);
    }
  }, [showEscapePrompt, onEscapePromptChange]);
  const nextLargePastePlaceholder = (0, import_react133.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_react133.useEffect)(
    () => () => {
      if (escapeTimerRef.current) {
        clearTimeout(escapeTimerRef.current);
      }
      if (pasteTimeoutRef.current) {
        clearTimeout(pasteTimeoutRef.current);
      }
    },
    []
  );
  const resetHistoryNavRef = (0, import_react133.useRef)(() => {
  });
  const handleSubmitAndClear = (0, import_react133.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) => `@${path133.relative(config2.getTargetDir(), att.path)}`).join(" ");
        finalValue = `${attachmentRefs}

${finalValue.trim()}`;
      }
      buffer.setText("");
      onSubmit(finalValue);
      resetHistoryNavRef.current();
      followup.dismiss();
      setAttachments([]);
      setIsAttachmentMode(false);
      setSelectedAttachmentIndex(-1);
      resetCompletionState();
      resetReverseSearchCompletionState();
    },
    [
      onSubmit,
      buffer,
      resetCompletionState,
      shellModeActive,
      shellHistory,
      resetReverseSearchCompletionState,
      attachments,
      config2,
      pendingPastes,
      followup
    ]
  );
  const customSetTextAndResetCompletionSignal = (0, import_react133.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
  });
  resetHistoryNavRef.current = inputHistory.resetHistoryNav;
  const prevHasAgentsRef = (0, import_react133.useRef)(hasAgents);
  (0, import_react133.useEffect)(() => {
    if (hasAgents && !prevHasAgentsRef.current) {
      inputHistory.resetHistoryNav();
    }
    prevHasAgentsRef.current = hasAgents;
  }, [hasAgents, inputHistory]);
  (0, import_react133.useEffect)(() => {
    if (justNavigatedHistory) {
      resetCompletionState();
      resetReverseSearchCompletionState();
      resetCommandSearchCompletionState();
      setExpandedSuggestionIndex(-1);
      setJustNavigatedHistory(false);
    }
  }, [
    justNavigatedHistory,
    buffer.text,
    resetCompletionState,
    setJustNavigatedHistory,
    resetReverseSearchCompletionState,
    resetCommandSearchCompletionState
  ]);
  const handleClipboardImage = (0, import_react133.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 = path133.basename(imagePath);
          const newAttachment = {
            id: String(Date.now()),
            path: imagePath,
            filename
          };
          setAttachments((prev) => [...prev, newAttachment]);
        }
      }
    } catch (error40) {
      debugLogger153.error("Error handling clipboard image:", error40);
    }
  }, []);
  const handleAttachmentDelete = (0, import_react133.useCallback)((index) => {
    setAttachments((prev) => {
      const newList = prev.filter((_2, i4) => i4 !== index);
      if (newList.length === 0) {
        setIsAttachmentMode(false);
        setSelectedAttachmentIndex(-1);
      } else {
        setSelectedAttachmentIndex(Math.min(index, newList.length - 1));
      }
      return newList;
    });
  }, []);
  const handleInput = (0, import_react133.useCallback)(
    (key) => {
      if (agentTabBarFocused || bgPillFocused) {
        if (key.sequence && key.sequence.length === 1 && !key.ctrl && !key.meta) {
          return false;
        }
        return true;
      }
      if (bgDialogOpen) {
        return true;
      }
      if (!focus && !key.paste) {
        return true;
      }
      if (key.paste) {
        if (buffer.text.length === 0 && followup.state.isVisible) {
          followup.dismiss();
          onPromptSuggestionDismiss?.();
        }
        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 true;
      }
      if (vimHandleInput && vimHandleInput(key)) {
        return true;
      }
      if (uiState.isFeedbackDialogOpen) {
        if (FEEDBACK_DIALOG_KEYS.includes(key.name)) {
          return true;
        } else {
          uiActions.temporaryCloseFeedbackDialog();
        }
      }
      const popQueueIntoInput = /* @__PURE__ */ __name(() => {
        const popped = uiActions.popAllQueuedMessages();
        if (!popped) return false;
        const currentText = buffer.text;
        if (currentText) {
          const currentCursorOffset = logicalPosToOffset(
            buffer.lines,
            buffer.cursor[0],
            buffer.cursor[1]
          );
          buffer.setText(`${popped}
${currentText}`);
          buffer.moveToOffset(popped.length + 1 + currentCursorOffset);
        } else {
          buffer.setText(popped);
        }
        return true;
      }, "popQueueIntoInput");
      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 true;
      }
      if (key.sequence === "?" && buffer.text === "" && !completion3.showSuggestions && onToggleShortcuts) {
        onToggleShortcuts();
        return true;
      }
      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 true;
        }
        if (commandSearchActive) {
          cancelSearch(
            setCommandSearchActive,
            commandSearchCompletion.resetCompletionState
          );
          return true;
        }
        if (shellModeActive) {
          setShellModeActive(false);
          resetEscapeState();
          return true;
        }
        if (completion3.showSuggestions) {
          completion3.resetCompletionState();
          setExpandedSuggestionIndex(-1);
          resetEscapeState();
          return true;
        }
        if (!isAttachmentMode && uiState.messageQueue.length > 0) {
          if (popQueueIntoInput()) {
            resetEscapeState();
            return true;
          }
        }
        if (escPressCount === 0) {
          if (buffer.text === "") {
            return true;
          }
          setEscPressCount(1);
          setShowEscapePrompt(true);
          if (escapeTimerRef.current) {
            clearTimeout(escapeTimerRef.current);
          }
          escapeTimerRef.current = setTimeout(() => {
            resetEscapeState();
          }, 500);
        } else {
          buffer.setText("");
          resetCompletionState();
          resetEscapeState();
        }
        return true;
      }
      if (keyMatchers["retryLast" /* RETRY_LAST */](key)) {
        uiActions.handleRetryLastPrompt();
        return true;
      }
      if (shellModeActive && keyMatchers["reverseSearch" /* REVERSE_SEARCH */](key)) {
        setReverseSearchActive(true);
        setTextBeforeReverseSearch(buffer.text);
        setCursorPosition(buffer.cursor);
        return true;
      }
      if (keyMatchers["clearScreen" /* CLEAR_SCREEN */](key)) {
        onClearScreen();
        return true;
      }
      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 true;
          }
          if (keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key)) {
            navigateDown();
            return true;
          }
          if (keyMatchers["collapseSuggestion" /* COLLAPSE_SUGGESTION */](key)) {
            if (suggestions[activeSuggestionIndex].value.length >= MAX_WIDTH) {
              setExpandedSuggestionIndex(-1);
              return true;
            }
          }
          if (keyMatchers["expandSuggestion" /* EXPAND_SUGGESTION */](key)) {
            if (suggestions[activeSuggestionIndex].value.length >= MAX_WIDTH) {
              setExpandedSuggestionIndex(activeSuggestionIndex);
              return true;
            }
          }
          if (keyMatchers["acceptSuggestionReverseSearch" /* ACCEPT_SUGGESTION_REVERSE_SEARCH */](key)) {
            sc.handleAutocomplete(activeSuggestionIndex);
            resetState();
            setActive(false);
            return true;
          }
        }
        if (keyMatchers["submitReverseSearch" /* SUBMIT_REVERSE_SEARCH */](key)) {
          const textToSubmit = showSuggestions && activeSuggestionIndex > -1 ? suggestions[activeSuggestionIndex].value : buffer.text;
          handleSubmitAndClear(textToSubmit);
          resetState();
          setActive(false);
          return true;
        }
        if (keyMatchers["navigationUp" /* NAVIGATION_UP */](key) || keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key)) {
          return true;
        }
      }
      if (completion3.isPerfectMatch && keyMatchers["return" /* RETURN */](key)) {
        handleSubmitAndClear(buffer.text);
        return true;
      }
      if (key.name === "tab" && !key.paste && !key.shift && buffer.text.length === 0 && !completion3.showSuggestions && !reverseSearchActive && !commandSearchActive && followup.state.isVisible && followup.state.suggestion) {
        followup.accept("tab");
        return true;
      }
      if (key.name === "right" && !key.ctrl && !key.meta && buffer.text.length === 0 && followup.state.isVisible && followup.state.suggestion) {
        followup.accept("right");
        return true;
      }
      if (completion3.showSuggestions) {
        if (completion3.suggestions.length > 1) {
          if (keyMatchers["completionUp" /* COMPLETION_UP */](key)) {
            completion3.navigateUp();
            setExpandedSuggestionIndex(-1);
            return true;
          }
          if (keyMatchers["completionDown" /* COMPLETION_DOWN */](key)) {
            completion3.navigateDown();
            setExpandedSuggestionIndex(-1);
            return true;
          }
        }
        if (keyMatchers["acceptSuggestion" /* ACCEPT_SUGGESTION */](key) && !key.paste) {
          if (completion3.suggestions.length > 0) {
            const targetIndex = completion3.activeSuggestionIndex === -1 ? 0 : completion3.activeSuggestionIndex;
            if (targetIndex < completion3.suggestions.length) {
              completion3.handleAutocomplete(targetIndex);
              setExpandedSuggestionIndex(-1);
            }
          }
          return true;
        }
      }
      if (key.name === "tab" && !key.paste && !key.shift && !completion3.showSuggestions && midInputGhostTextRef.current?.acceptText) {
        buffer.insert(midInputGhostTextRef.current.acceptText);
        return true;
      }
      if (isAttachmentMode && attachments.length > 0) {
        if (key.name === "left") {
          setSelectedAttachmentIndex((i4) => Math.max(0, i4 - 1));
          return true;
        }
        if (key.name === "right") {
          setSelectedAttachmentIndex(
            (i4) => Math.min(attachments.length - 1, i4 + 1)
          );
          return true;
        }
        if (keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key)) {
          setIsAttachmentMode(false);
          setSelectedAttachmentIndex(-1);
          return true;
        }
        if (key.name === "backspace" || key.name === "delete") {
          handleAttachmentDelete(selectedAttachmentIndex);
          return true;
        }
        if (key.name === "return" || key.name === "escape") {
          setIsAttachmentMode(false);
          setSelectedAttachmentIndex(-1);
          return true;
        }
        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 true;
      }
      if (!shellModeActive) {
        if (keyMatchers["reverseSearch" /* REVERSE_SEARCH */](key)) {
          setCommandSearchActive(true);
          setTextBeforeReverseSearch(buffer.text);
          setCursorPosition(buffer.cursor);
          return true;
        }
        if (!isAttachmentMode && uiState.messageQueue.length > 0 && keyMatchers["navigationUp" /* NAVIGATION_UP */](key) && (buffer.allVisualLines.length === 1 || buffer.visualCursor[0] === 0 && buffer.visualScrollRow === 0)) {
          if (popQueueIntoInput()) return true;
        }
        if (keyMatchers["historyUp" /* HISTORY_UP */](key)) {
          inputHistory.navigateUp();
          return true;
        }
        if (keyMatchers["historyDown" /* HISTORY_DOWN */](key)) {
          inputHistory.navigateDown();
          return true;
        }
        if (keyMatchers["navigationUp" /* NAVIGATION_UP */](key) && (buffer.allVisualLines.length === 1 || buffer.visualCursor[0] === 0 && buffer.visualScrollRow === 0)) {
          inputHistory.navigateUp();
          return true;
        }
        if (keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key) && (buffer.allVisualLines.length === 1 || buffer.visualCursor[0] === buffer.allVisualLines.length - 1)) {
          if (inputHistory.navigateDown()) {
            return true;
          }
          if (hasAgents) {
            setAgentTabBarFocused(true);
            return true;
          }
          if (hasBgAgents) {
            setBgPillFocused(true);
            return true;
          }
          return true;
        }
      } else {
        if (keyMatchers["navigationUp" /* NAVIGATION_UP */](key)) {
          const prevCommand = shellHistory.getPreviousCommand();
          if (prevCommand !== null) buffer.setText(prevCommand);
          return true;
        }
        if (keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key)) {
          const nextCommand = shellHistory.getNextCommand();
          if (nextCommand !== null) buffer.setText(nextCommand);
          return true;
        }
      }
      if (keyMatchers["submit" /* SUBMIT */](key)) {
        if (buffer.text.length === 0 && followup.state.isVisible && followup.state.suggestion) {
          const text = followup.state.suggestion;
          followup.accept("enter", { skipOnAccept: true });
          handleSubmitAndClear(text);
          return true;
        }
        if (buffer.text.trim()) {
          if (pasteWorkaround && recentPasteTime !== null) {
            return true;
          }
          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 true;
      }
      if (keyMatchers["pasteClipboardImage" /* PASTE_CLIPBOARD_IMAGE */](key)) {
        handleClipboardImage();
        return true;
      }
      if (pendingPastes.size > 0 && (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 i4 = 0; i4 < row; i4++) {
          offset += buffer.lines[i4].length + 1;
        }
        offset += col;
        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);
            }
            return true;
          }
        }
      }
      if (keyMatchers["clearInput" /* CLEAR_INPUT */](key)) {
        if (buffer.text.length > 0) {
          resetCompletionState();
        }
      }
      if (buffer.text.length === 0 && followup.state.isVisible && key.sequence && key.sequence.length === 1 && !key.ctrl && !key.meta) {
        followup.recordKeystroke();
        followup.dismiss();
        onPromptSuggestionDismiss?.();
      }
      return false;
    },
    [
      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,
      agentTabBarFocused,
      bgDialogOpen,
      bgPillFocused,
      hasAgents,
      hasBgAgents,
      setAgentTabBarFocused,
      setBgPillFocused,
      followup,
      onPromptSuggestionDismiss
    ]
  );
  const renderLineWithHighlighting = (0, import_react133.useCallback)(
    (opts) => {
      const {
        lineText,
        isOnCursorLine,
        cursorCol: cursorVisualColAbsolute,
        showCursor: showCursorOpt,
        absoluteVisualIndex,
        buffer: buf
      } = opts;
      const mapEntry = buf.visualToLogicalMap[absoluteVisualIndex];
      const [logicalLineIdx, logicalStartCol] = mapEntry;
      const logicalLine = buf.lines[logicalLineIdx] || "";
      const tokens = parseInputForHighlighting(logicalLine, logicalLineIdx);
      const visualStart = logicalStartCol;
      const visualEnd = logicalStartCol + cpLen(lineText);
      const segments = buildSegmentsForVisualSlice(
        tokens,
        visualStart,
        visualEnd
      );
      const renderedLine = [];
      let charCount = 0;
      segments.forEach((seg, segIdx) => {
        const segLen = cpLen(seg.text);
        let display = seg.text;
        if (isOnCursorLine) {
          const segStart = charCount;
          const segEnd = segStart + segLen;
          if (cursorVisualColAbsolute >= segStart && cursorVisualColAbsolute < segEnd) {
            const charToHighlight = cpSlice(
              seg.text,
              cursorVisualColAbsolute - segStart,
              cursorVisualColAbsolute - segStart + 1
            );
            const highlighted = showCursorOpt ? import_chalk10.default.inverse(charToHighlight) : charToHighlight;
            display = cpSlice(seg.text, 0, cursorVisualColAbsolute - segStart) + highlighted + cpSlice(seg.text, cursorVisualColAbsolute - segStart + 1);
          }
          charCount = segEnd;
        }
        const color = seg.type === "command" || seg.type === "file" ? theme.text.accent : theme.text.primary;
        renderedLine.push(
          /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Text3, { color, children: display }, `token-${segIdx}`)
        );
      });
      if (isOnCursorLine && cursorVisualColAbsolute === cpLen(lineText)) {
        const ghostText = midInputGhostTextRef.current;
        if (ghostText && showCursorOpt && ghostText.text.length > 0) {
          if (ghostText.showCursorBeforeText) {
            renderedLine.push(
              /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Text3, { children: import_chalk10.default.inverse(" ") }, "ghost-cursor")
            );
            renderedLine.push(
              /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Text3, { color: theme.text.secondary, children: ghostText.text }, "ghost-rest")
            );
          } else {
            const firstChar = ghostText.text[0];
            const rest = ghostText.text.slice(firstChar.length);
            renderedLine.push(
              /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Text3, { children: import_chalk10.default.inverse(firstChar) }, "ghost-cursor")
            );
            if (rest.length > 0) {
              renderedLine.push(
                /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Text3, { color: theme.text.secondary, children: rest }, "ghost-rest")
              );
            }
          }
          renderedLine.push(/* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Text3, { children: `\u200B` }, "ghost-zwsp"));
        } else {
          renderedLine.push(
            /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Text3, { children: showCursorOpt ? import_chalk10.default.inverse(" ") + "\u200B" : " \u200B" }, `cursor-end-${cursorVisualColAbsolute}`)
          );
        }
      }
      return /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Text3, { children: renderedLine });
    },
    []
  );
  const getActiveCompletion = /* @__PURE__ */ __name(() => {
    if (commandSearchActive) return commandSearchCompletion;
    if (reverseSearchActive) return reverseSearchCompletion;
    return completion3;
  }, "getActiveCompletion");
  const activeCompletion = getActiveCompletion();
  const shouldShowSuggestions = activeCompletion.showSuggestions;
  (0, import_react133.useEffect)(() => {
    if (onSuggestionsVisibilityChange) {
      onSuggestionsVisibilityChange(shouldShowSuggestions);
    }
  }, [shouldShowSuggestions, onSuggestionsVisibilityChange]);
  (0, import_react133.useEffect)(() => {
    followup.setSuggestion(promptSuggestion ?? null);
  }, [promptSuggestion]);
  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 && !agentTabBarFocused ? statusColor ?? theme.border.focused : theme.border.default;
  const prefixNode = /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(
    Text3,
    {
      color: statusColor ?? theme.text.accent,
      "aria-label": statusText || void 0,
      children: [
        shellModeActive ? reverseSearchActive ? /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(Text3, { color: theme.text.link, "aria-label": SCREEN_READER_USER_PREFIX, children: [
          "(r:)",
          " "
        ] }) : "!" : commandSearchActive ? /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Text3, { color: theme.text.accent, children: "(r:) " }) : showYoloStyling ? "*" : ">",
        " "
      ]
    }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(import_jsx_runtime130.Fragment, { children: [
    attachments.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(Box_default, { marginLeft: 2, marginBottom: 0, children: [
      /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Text3, { color: theme.text.secondary, children: t4("Attachments: ") }),
      attachments.map((att, idx) => /* @__PURE__ */ (0, import_jsx_runtime130.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_runtime130.jsx)(
      BaseTextInput,
      {
        buffer,
        onSubmit: handleSubmitAndClear,
        onKeypress: handleInput,
        showCursor,
        placeholder: followup.state.isVisible && followup.state.suggestion ? followup.state.suggestion : placeholder,
        prefix: prefixNode,
        borderColor,
        topRightLabel: uiState.sessionName || void 0,
        isActive: !isEmbeddedShellFocused,
        renderLine: renderLineWithHighlighting
      }
    ),
    shouldShowSuggestions && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Box_default, { marginLeft: 2, marginRight: 2, children: /* @__PURE__ */ (0, import_jsx_runtime130.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_runtime130.jsx)(Box_default, { marginLeft: 2, marginRight: 2, children: /* @__PURE__ */ (0, import_jsx_runtime130.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();
var import_react137 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/ContextUsageDisplay.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime131 = __toESM(require_jsx_runtime(), 1);
function formatPercentageUsed(percentage) {
  if (percentage > 1) {
    return ">100";
  }
  return (percentage * 100).toFixed(1);
}
__name(formatPercentageUsed, "formatPercentageUsed");
var ContextUsageDisplay = /* @__PURE__ */ __name(({
  promptTokenCount,
  terminalWidth,
  contextWindowSize
}) => {
  if (promptTokenCount === 0) {
    return null;
  }
  const percentage = promptTokenCount / contextWindowSize;
  const percentageUsed = formatPercentageUsed(percentage);
  const isOverLimit = percentage > 1;
  const label = terminalWidth < 100 ? t4("% used") : t4("% context used");
  if (isOverLimit) {
    return /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(import_jsx_runtime131.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(Text3, { color: theme.status.error, children: [
      percentageUsed,
      label
    ] }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(Text3, { color: theme.text.secondary, children: [
    percentageUsed,
    label
  ] });
}, "ContextUsageDisplay");

// packages/cli/src/ui/components/AutoAcceptIndicator.tsx
init_esbuild_shims();
init_dist4();
init_i18n();
var import_jsx_runtime132 = __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_runtime132.jsxs)(Text3, { color: textColor, children: [
    textContent2,
    subText && /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(Text3, { color: theme.text.secondary, children: subText })
  ] });
}, "AutoAcceptIndicator");

// packages/cli/src/ui/components/ShellModeIndicator.tsx
init_esbuild_shims();
var import_jsx_runtime133 = __toESM(require_jsx_runtime(), 1);
var ShellModeIndicator = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime133.jsxs)(Text3, { color: theme.ui.symbol, children: [
  "shell mode enabled",
  /* @__PURE__ */ (0, import_jsx_runtime133.jsx)(Text3, { color: theme.text.secondary, children: " (esc to disable)" })
] }), "ShellModeIndicator");

// packages/cli/src/ui/components/background-view/BackgroundTasksPill.tsx
init_esbuild_shims();
var import_react134 = __toESM(require_react(), 1);
var import_jsx_runtime134 = __toESM(require_jsx_runtime(), 1);
var KIND_NAMES = {
  agent: { singular: "local agent", plural: "local agents" },
  shell: { singular: "shell", plural: "shells" }
};
function getPillLabel(entries) {
  if (entries.length === 0) return "";
  const running = entries.filter((e4) => e4.status === "running");
  if (running.length > 0) {
    return groupAndFormat(running);
  }
  return entries.length === 1 ? "1 task done" : `${entries.length} tasks done`;
}
__name(getPillLabel, "getPillLabel");
function groupAndFormat(entries) {
  const counts = { agent: 0, shell: 0 };
  for (const e4 of entries) counts[e4.kind]++;
  const parts2 = [];
  if (counts.shell > 0) parts2.push(formatCount("shell", counts.shell));
  if (counts.agent > 0) parts2.push(formatCount("agent", counts.agent));
  return parts2.join(", ");
}
__name(groupAndFormat, "groupAndFormat");
function formatCount(kind2, n3) {
  const names = KIND_NAMES[kind2];
  return `${n3} ${n3 === 1 ? names.singular : names.plural}`;
}
__name(formatCount, "formatCount");
var BackgroundTasksPill = /* @__PURE__ */ __name(() => {
  const { entries, pillFocused } = useBackgroundTaskViewState();
  const { openDialog, setPillFocused } = useBackgroundTaskViewActions();
  const onKeypress = (0, import_react134.useCallback)(
    (key) => {
      if (key.name === "return") {
        openDialog();
      } else if (key.name === "up" || key.name === "escape") {
        setPillFocused(false);
      } else if (key.sequence && key.sequence.length === 1 && !key.ctrl && !key.meta) {
        setPillFocused(false);
      }
    },
    [openDialog, setPillFocused]
  );
  useKeypress(onKeypress, { isActive: pillFocused });
  if (entries.length === 0) return null;
  const label = getPillLabel(entries);
  return /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(import_jsx_runtime134.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Text3, { color: theme.text.secondary, children: " \xB7 " }),
    /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Text3, { inverse: pillFocused, children: label })
  ] });
}, "BackgroundTasksPill");

// packages/cli/src/ui/hooks/useStatusLine.ts
init_esbuild_shims();
var import_react135 = __toESM(require_react(), 1);
init_dist4();
import { exec as exec4 } from "child_process";
var debugLog = createDebugLogger("STATUS_LINE");
var MAX_STATUS_LINES = 2;
function getStatusLineConfig(settings) {
  const raw2 = settings.merged.ui?.statusLine;
  if (raw2 && typeof raw2 === "object" && "type" in raw2 && raw2.type === "command" && "command" in raw2 && typeof raw2.command === "string" && raw2.command.trim().length > 0) {
    const config2 = {
      type: "command",
      command: raw2.command
    };
    if (typeof raw2.refreshInterval === "number" && Number.isFinite(raw2.refreshInterval) && raw2.refreshInterval >= 1) {
      config2.refreshInterval = raw2.refreshInterval;
    }
    return config2;
  }
  return void 0;
}
__name(getStatusLineConfig, "getStatusLineConfig");
function buildMetricsPayload(m3) {
  const models = {};
  for (const [id, mm] of Object.entries(m3.models)) {
    models[id] = {
      api: {
        total_requests: mm.api.totalRequests,
        total_errors: mm.api.totalErrors,
        total_latency_ms: mm.api.totalLatencyMs
      },
      tokens: {
        prompt: mm.tokens.prompt,
        completion: mm.tokens.candidates,
        total: mm.tokens.total,
        cached: mm.tokens.cached,
        thoughts: mm.tokens.thoughts
      }
    };
  }
  return {
    models,
    files: {
      total_lines_added: m3.files.totalLinesAdded,
      total_lines_removed: m3.files.totalLinesRemoved
    }
  };
}
__name(buildMetricsPayload, "buildMetricsPayload");
function useStatusLine() {
  const settings = useSettings();
  const uiState = useUIState();
  const config2 = useConfig();
  const { vimEnabled, vimMode } = useVimMode();
  const statusLineConfig = getStatusLineConfig(settings);
  const statusLineCommand = statusLineConfig?.command;
  const refreshInterval = statusLineConfig?.refreshInterval;
  const [output, setOutput] = (0, import_react135.useState)([]);
  const uiStateRef = (0, import_react135.useRef)(uiState);
  uiStateRef.current = uiState;
  const configRef = (0, import_react135.useRef)(config2);
  configRef.current = config2;
  const vimEnabledRef = (0, import_react135.useRef)(vimEnabled);
  vimEnabledRef.current = vimEnabled;
  const vimModeRef = (0, import_react135.useRef)(vimMode);
  vimModeRef.current = vimMode;
  const statusLineCommandRef = (0, import_react135.useRef)(statusLineCommand);
  statusLineCommandRef.current = statusLineCommand;
  const debounceTimerRef = (0, import_react135.useRef)(
    void 0
  );
  const { lastPromptTokenCount } = uiState.sessionStats;
  const { currentModel, branchName } = uiState;
  const totalToolCalls = uiState.sessionStats.metrics.tools.totalCalls;
  const totalLinesAdded = uiState.sessionStats.metrics.files.totalLinesAdded;
  const totalLinesRemoved = uiState.sessionStats.metrics.files.totalLinesRemoved;
  const effectiveVim = vimEnabled ? vimMode : void 0;
  const prevStateRef = (0, import_react135.useRef)({
    promptTokenCount: lastPromptTokenCount,
    currentModel,
    effectiveVim,
    branchName,
    totalToolCalls,
    totalLinesAdded,
    totalLinesRemoved
  });
  const hasMountedRef = (0, import_react135.useRef)(false);
  const activeChildRef = (0, import_react135.useRef)(void 0);
  const generationRef = (0, import_react135.useRef)(0);
  const doUpdate = (0, import_react135.useCallback)(() => {
    const cmd = statusLineCommandRef.current;
    if (!cmd) {
      setOutput([]);
      return;
    }
    const ui2 = uiStateRef.current;
    const cfg = configRef.current;
    const stats = ui2.sessionStats;
    const m3 = stats.metrics;
    const contextWindowSize = cfg.getContentGeneratorConfig()?.contextWindowSize || 0;
    const usedPercentage = contextWindowSize > 0 ? Math.min(
      100,
      Math.max(
        0,
        Math.round(
          stats.lastPromptTokenCount / contextWindowSize * 1e3
        ) / 10
      )
    ) : 0;
    let totalInputTokens = 0;
    let totalOutputTokens = 0;
    for (const mm of Object.values(m3.models)) {
      totalInputTokens += mm.tokens.prompt;
      totalOutputTokens += mm.tokens.candidates;
    }
    const input = {
      session_id: stats.sessionId,
      version: cfg.getCliVersion() || "unknown",
      model: {
        display_name: ui2.currentModel || cfg.getModel() || "unknown"
      },
      context_window: {
        context_window_size: contextWindowSize,
        used_percentage: usedPercentage,
        remaining_percentage: Math.round((100 - usedPercentage) * 10) / 10,
        current_usage: stats.lastPromptTokenCount,
        total_input_tokens: totalInputTokens,
        total_output_tokens: totalOutputTokens
      },
      workspace: {
        current_dir: cfg.getTargetDir()
      },
      ...ui2.branchName && {
        git: {
          branch: ui2.branchName
        }
      },
      metrics: buildMetricsPayload(m3),
      ...vimEnabledRef.current && {
        vim: { mode: vimModeRef.current }
      }
    };
    if (activeChildRef.current) {
      activeChildRef.current.kill();
      activeChildRef.current = void 0;
    }
    const gen = ++generationRef.current;
    let child;
    try {
      child = exec4(
        cmd,
        { cwd: cfg.getTargetDir(), timeout: 5e3, maxBuffer: 1024 * 10 },
        (error40, stdout2) => {
          if (gen !== generationRef.current) return;
          activeChildRef.current = void 0;
          const nextLines = !error40 && stdout2 ? stdout2.replace(/\r?\n$/, "").split(/\r?\n/).filter(Boolean).slice(0, MAX_STATUS_LINES) : [];
          setOutput((prev) => {
            if (prev.length === nextLines.length && prev.every((v2, i4) => v2 === nextLines[i4])) {
              return prev;
            }
            return nextLines;
          });
        }
      );
    } catch (err2) {
      debugLog.error("statusline exec error:", err2.message);
      setOutput([]);
      return;
    }
    activeChildRef.current = child;
    if (child.stdin) {
      child.stdin.on("error", (err2) => {
        if (err2.code !== "EPIPE") {
          debugLog.error("statusline stdin error:", err2.message);
        }
      });
      child.stdin.write(JSON.stringify(input));
      child.stdin.end();
    }
  }, []);
  const scheduleUpdate = (0, import_react135.useCallback)(() => {
    if (debounceTimerRef.current !== void 0) {
      clearTimeout(debounceTimerRef.current);
    }
    debounceTimerRef.current = setTimeout(() => {
      debounceTimerRef.current = void 0;
      doUpdate();
    }, 300);
  }, [doUpdate]);
  (0, import_react135.useEffect)(() => {
    if (!statusLineCommand) {
      activeChildRef.current?.kill();
      activeChildRef.current = void 0;
      generationRef.current++;
      if (debounceTimerRef.current !== void 0) {
        clearTimeout(debounceTimerRef.current);
        debounceTimerRef.current = void 0;
      }
      setOutput([]);
      return;
    }
    const prev = prevStateRef.current;
    if (lastPromptTokenCount !== prev.promptTokenCount || currentModel !== prev.currentModel || effectiveVim !== prev.effectiveVim || branchName !== prev.branchName || totalToolCalls !== prev.totalToolCalls || totalLinesAdded !== prev.totalLinesAdded || totalLinesRemoved !== prev.totalLinesRemoved) {
      prev.promptTokenCount = lastPromptTokenCount;
      prev.currentModel = currentModel;
      prev.effectiveVim = effectiveVim;
      prev.branchName = branchName;
      prev.totalToolCalls = totalToolCalls;
      prev.totalLinesAdded = totalLinesAdded;
      prev.totalLinesRemoved = totalLinesRemoved;
      scheduleUpdate();
    }
  }, [
    statusLineCommand,
    lastPromptTokenCount,
    currentModel,
    effectiveVim,
    branchName,
    totalToolCalls,
    totalLinesAdded,
    totalLinesRemoved,
    scheduleUpdate
  ]);
  (0, import_react135.useEffect)(() => {
    if (!hasMountedRef.current) return;
    if (statusLineCommand) {
      if (debounceTimerRef.current !== void 0) {
        clearTimeout(debounceTimerRef.current);
        debounceTimerRef.current = void 0;
      }
      doUpdate();
    }
  }, [statusLineCommand]);
  (0, import_react135.useEffect)(() => {
    if (!statusLineCommand || !refreshInterval) return;
    const timer = setInterval(() => {
      if (activeChildRef.current) return;
      doUpdate();
    }, refreshInterval * 1e3);
    return () => {
      clearInterval(timer);
    };
  }, [statusLineCommand, refreshInterval, doUpdate]);
  (0, import_react135.useEffect)(() => {
    hasMountedRef.current = true;
    const genRef = generationRef;
    const debounceRef = debounceTimerRef;
    const childRef = activeChildRef;
    doUpdate();
    return () => {
      childRef.current?.kill();
      childRef.current = void 0;
      genRef.current++;
      if (debounceRef.current !== void 0) {
        clearTimeout(debounceRef.current);
        debounceRef.current = void 0;
      }
    };
  }, []);
  return { lines: output };
}
__name(useStatusLine, "useStatusLine");

// packages/cli/src/ui/hooks/useConfigInitMessage.ts
init_esbuild_shims();
var import_react136 = __toESM(require_react(), 1);
init_dist4();
init_i18n();
function useConfigInitMessage(isConfigInitialized) {
  const [message, setMessage] = (0, import_react136.useState)(() => t4("Initializing..."));
  (0, import_react136.useEffect)(() => {
    if (isConfigInitialized) {
      return;
    }
    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);
    };
  }, [isConfigInitialized]);
  return isConfigInitialized ? null : message;
}
__name(useConfigInitMessage, "useConfigInitMessage");

// packages/cli/src/ui/components/Footer.tsx
init_dist4();
init_i18n();
var import_jsx_runtime135 = __toESM(require_jsx_runtime(), 1);
function useDreamRunning(projectRoot) {
  const config2 = useConfig();
  const subscribe = (0, import_react137.useCallback)(
    (onStoreChange) => config2.getMemoryManager().subscribe(onStoreChange),
    [config2]
  );
  const getSnapshot = (0, import_react137.useCallback)(
    () => config2.getMemoryManager().listTasksByType("dream", projectRoot).some((task) => task.status === "pending" || task.status === "running"),
    [config2, projectRoot]
  );
  return (0, import_react137.useSyncExternalStore)(subscribe, getSnapshot);
}
__name(useDreamRunning, "useDreamRunning");
var Footer = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const config2 = useConfig();
  const { vimEnabled, vimMode } = useVimMode();
  const { lines: statusLineLines } = useStatusLine();
  const configInitMessage = useConfigInitMessage(uiState.isConfigInitialized);
  const dreamRunning = useDreamRunning(config2.getProjectRoot());
  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 suppressHint = statusLineLines.length > 0;
  const leftBottomContent = uiState.ctrlCPressedOnce ? /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { color: theme.status.warning, children: t4("Press Ctrl+C again to exit.") }) : uiState.ctrlDPressedOnce ? /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { color: theme.status.warning, children: t4("Press Ctrl+D again to exit.") }) : uiState.showEscapePrompt ? /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { color: theme.text.secondary, children: t4("Press Esc again to clear.") }) : uiState.rewindEscPending ? /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { color: theme.text.secondary, children: t4("Press Esc again to rewind conversation.") }) : vimEnabled && vimMode === "INSERT" ? /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { color: theme.text.secondary, children: "-- INSERT --" }) : uiState.shellModeActive ? /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(ShellModeIndicator, {}) : configInitMessage ? /* @__PURE__ */ (0, import_jsx_runtime135.jsxs)(Text3, { color: theme.text.secondary, children: [
    /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(GeminiSpinner, {}),
    " ",
    configInitMessage
  ] }) : showAutoAcceptIndicator !== void 0 && showAutoAcceptIndicator !== ApprovalMode.DEFAULT ? /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(AutoAcceptIndicator, { approvalMode: showAutoAcceptIndicator }) : suppressHint ? null : /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { color: theme.text.secondary, children: t4("? for shortcuts") });
  const rightItems = [];
  if (sandboxInfo) {
    rightItems.push({
      key: "sandbox",
      node: /* @__PURE__ */ (0, import_jsx_runtime135.jsxs)(Text3, { color: theme.status.success, children: [
        "\u{1F512} ",
        sandboxInfo
      ] })
    });
  }
  if (debugMode) {
    rightItems.push({
      key: "debug",
      node: /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { color: theme.status.warning, children: "Debug Mode" })
    });
  }
  if (dreamRunning) {
    rightItems.push({
      key: "dream",
      node: /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { color: theme.text.secondary, children: t4("\u2726 dreaming") })
    });
  }
  if (promptTokenCount > 0 && contextWindowSize) {
    rightItems.push({
      key: "context",
      node: /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { color: theme.text.accent, children: /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(
        ContextUsageDisplay,
        {
          promptTokenCount,
          terminalWidth,
          contextWindowSize
        }
      ) })
    });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime135.jsxs)(
    Box_default,
    {
      flexDirection: isNarrow ? "column" : "row",
      justifyContent: isNarrow ? "flex-start" : "space-between",
      width: "100%",
      paddingX: 2,
      gap: isNarrow ? 0 : 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime135.jsxs)(Box_default, { flexDirection: "column", flexShrink: isNarrow ? 0 : 1, children: [
          statusLineLines.length > 0 && !uiState.ctrlCPressedOnce && !uiState.ctrlDPressedOnce && statusLineLines.map((line, i4) => /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { dimColor: true, wrap: "truncate", children: line }, `status-line-${i4}`)),
          /* @__PURE__ */ (0, import_jsx_runtime135.jsxs)(Box_default, { flexDirection: "row", flexShrink: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { wrap: "truncate", children: leftBottomContent }),
            /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(BackgroundTasksPill, {})
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Box_default, { flexShrink: 0, gap: 1, alignItems: "flex-start", children: rightItems.map(({ key, node }, index) => /* @__PURE__ */ (0, import_jsx_runtime135.jsxs)(Box_default, { alignItems: "center", children: [
          index > 0 && /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Text3, { color: theme.text.secondary, children: " | " }),
          node
        ] }, key)) })
      ]
    }
  );
}, "Footer");

// packages/cli/src/ui/components/QueuedMessageDisplay.tsx
init_esbuild_shims();
var import_react138 = __toESM(require_react(), 1);
init_i18n();
var import_jsx_runtime136 = __toESM(require_jsx_runtime(), 1);
var MAX_DISPLAYED_QUEUED_MESSAGES = 3;
var NUM_TIMES_QUEUE_HINT_SHOWN = 3;
var QueuedMessageDisplay = /* @__PURE__ */ __name(({
  messageQueue
}) => {
  const hintSeenCountRef = (0, import_react138.useRef)(0);
  const wasEmptyRef = (0, import_react138.useRef)(true);
  if (messageQueue.length === 0) {
    wasEmptyRef.current = true;
    return null;
  }
  if (wasEmptyRef.current) {
    hintSeenCountRef.current++;
    wasEmptyRef.current = false;
  }
  const showHint = hintSeenCountRef.current <= NUM_TIMES_QUEUE_HINT_SHOWN;
  return /* @__PURE__ */ (0, import_jsx_runtime136.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_runtime136.jsx)(Box_default, { paddingLeft: 2, width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Text3, { dimColor: true, wrap: "truncate", children: preview }) }, index);
    }),
    messageQueue.length > MAX_DISPLAYED_QUEUED_MESSAGES && /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Box_default, { paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(Text3, { dimColor: true, children: [
      "... (+",
      messageQueue.length - MAX_DISPLAYED_QUEUED_MESSAGES,
      " more)"
    ] }) }),
    showHint && /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Box_default, { paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Text3, { dimColor: true, italic: true, children: t4("Press \u2191 to edit queued messages") }) })
  ] });
}, "QueuedMessageDisplay");

// packages/cli/src/ui/components/KeyboardShortcuts.tsx
init_esbuild_shims();
init_i18n();
var import_jsx_runtime137 = __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: "ctrl+y", description: t4("to retry last request") },
  { key: getPasteKey(), description: t4("to paste images") },
  { key: getExternalEditorKey(), description: t4("for external editor") },
  { key: "ctrl+o", description: t4("to toggle compact mode") }
], "getShortcuts");
var ShortcutItem = /* @__PURE__ */ __name(({ shortcut }) => /* @__PURE__ */ (0, import_jsx_runtime137.jsxs)(Text3, { color: theme.text.secondary, children: [
  /* @__PURE__ */ (0, import_jsx_runtime137.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: [5, 4, 4],
  2: [7, 6],
  1: [13]
};
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_runtime137.jsx)(
    Box_default,
    {
      flexDirection: "row",
      marginLeft: MARGIN_LEFT,
      marginRight: MARGIN_RIGHT,
      children: columns.map((column, colIndex) => /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(
        Box_default,
        {
          flexDirection: "column",
          marginRight: colIndex < numColumns - 1 ? COLUMN_GAP : 0,
          children: column.map((shortcut) => /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(ShortcutItem, { shortcut }, shortcut.key))
        },
        colIndex
      ))
    }
  );
}, "KeyboardShortcuts");

// packages/cli/src/ui/components/Composer.tsx
init_types22();
init_i18n();
var import_jsx_runtime138 = __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,
    streamingResponseLengthRef,
    isReceivingContent
  } = uiState;
  const isStreaming = uiState.streamingState === "responding" /* Responding */ || uiState.streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */;
  let agentTokens = 0;
  for (const item of uiState.pendingGeminiHistoryItems ?? []) {
    if (item.type === "tool_group") {
      const toolGroup = item;
      for (const tool of toolGroup.tools) {
        const display = tool.resultDisplay;
        if (typeof display === "object" && display !== null && "type" in display && display.type === "task_execution" && "tokenCount" in display && typeof display.tokenCount === "number") {
          agentTokens += display.tokenCount;
        }
      }
    }
  }
  const [showShortcuts, setShowShortcuts] = (0, import_react139.useState)(false);
  const handleToggleShortcuts = (0, import_react139.useCallback)(() => {
    setShowShortcuts((prev) => !prev);
  }, []);
  const [showSuggestions, setShowSuggestions] = (0, import_react139.useState)(false);
  const handleSuggestionsVisibilityChange = (0, import_react139.useCallback)(
    (visible) => {
      setShowSuggestions(visible);
      uiActions.onSuggestionsVisibilityChange(visible);
    },
    [uiActions]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime138.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    !uiState.embeddedShellFocused && /* @__PURE__ */ (0, import_jsx_runtime138.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,
        candidatesTokens: agentTokens,
        streamingCharsRef: streamingResponseLengthRef,
        isStreaming,
        isReceivingContent
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(QueuedMessageDisplay, { messageQueue: uiState.messageQueue }),
    uiState.isFeedbackDialogOpen && /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(FeedbackDialog, {}),
    uiState.isInputActive && /* @__PURE__ */ (0, import_jsx_runtime138.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"),
        promptSuggestion: uiState.promptSuggestion,
        onPromptSuggestionDismiss: uiState.dismissPromptSuggestion
      }
    ),
    uiState.isInputActive && !showSuggestions && (showShortcuts ? /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(KeyboardShortcuts, {}) : !isScreenReaderEnabled && /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(Footer, {}))
  ] });
}, "Composer");

// packages/cli/src/ui/components/ExitWarning.tsx
init_esbuild_shims();
var import_jsx_runtime139 = __toESM(require_jsx_runtime(), 1);
var ExitWarning = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  return /* @__PURE__ */ (0, import_jsx_runtime139.jsxs)(import_jsx_runtime139.Fragment, { children: [
    uiState.dialogsVisible && uiState.ctrlCPressedOnce && /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(Text3, { color: theme.status.warning, children: "Press Ctrl+C again to exit." }) }),
    uiState.dialogsVisible && uiState.ctrlDPressedOnce && /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(Text3, { color: theme.status.warning, children: "Press Ctrl+D again to exit." }) })
  ] });
}, "ExitWarning");

// packages/cli/src/ui/components/StickyTodoList.tsx
init_esbuild_shims();
var import_react140 = __toESM(require_react(), 1);
init_i18n();

// packages/cli/src/ui/utils/todoSnapshot.ts
init_esbuild_shims();
var MIN_HISTORY_ITEMS_AFTER_TODO_BEFORE_STICKY = 2;
var STICKY_TODO_MAX_VISIBLE_ITEMS = 5;
var STICKY_TODO_ROWS_PER_VISIBLE_ITEM = 5;
var STICKY_TODO_STATUS_PRIORITY = {
  in_progress: 0,
  pending: 1,
  completed: 2
};
function clampStickyTodoVisibleItems(value) {
  if (!Number.isFinite(value)) {
    return STICKY_TODO_MAX_VISIBLE_ITEMS;
  }
  return Math.max(
    1,
    Math.min(STICKY_TODO_MAX_VISIBLE_ITEMS, Math.floor(value))
  );
}
__name(clampStickyTodoVisibleItems, "clampStickyTodoVisibleItems");
function extractTodosFromResultDisplay(resultDisplay) {
  if (!resultDisplay) {
    return null;
  }
  if (typeof resultDisplay === "object") {
    const candidate = resultDisplay;
    if (candidate["type"] === "todo_list" && Array.isArray(candidate["todos"])) {
      return candidate["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;
    }
  }
  return null;
}
__name(extractTodosFromResultDisplay, "extractTodosFromResultDisplay");
function findLatestTodoSnapshot(items) {
  for (let itemIndex = items.length - 1; itemIndex >= 0; itemIndex -= 1) {
    const item = items[itemIndex];
    if (item.type !== "tool_group") {
      continue;
    }
    for (let toolIndex = item.tools.length - 1; toolIndex >= 0; toolIndex -= 1) {
      const tool = item.tools[toolIndex];
      const todos = extractTodosFromResultDisplay(tool.resultDisplay);
      if (todos) {
        return {
          itemIndex,
          todos: todos.length > 0 ? todos : null
        };
      }
    }
  }
  return void 0;
}
__name(findLatestTodoSnapshot, "findLatestTodoSnapshot");
function areAllTodosCompleted(todos) {
  return todos.length > 0 && todos.every((todo) => todo.status === "completed");
}
__name(areAllTodosCompleted, "areAllTodosCompleted");
function isRecentHistoryTodoSnapshot(snapshotItemIndex, historyLength) {
  const historyItemsAfterSnapshot = historyLength - snapshotItemIndex - 1;
  return historyItemsAfterSnapshot < MIN_HISTORY_ITEMS_AFTER_TODO_BEFORE_STICKY;
}
__name(isRecentHistoryTodoSnapshot, "isRecentHistoryTodoSnapshot");
function getStickyTodos(history, pendingHistoryItems) {
  const pendingSnapshot = findLatestTodoSnapshot(pendingHistoryItems);
  if (pendingSnapshot !== void 0) {
    return null;
  }
  const historySnapshot = findLatestTodoSnapshot(history);
  if (historySnapshot === void 0 || historySnapshot.todos === null) {
    return null;
  }
  if (isRecentHistoryTodoSnapshot(historySnapshot.itemIndex, history.length)) {
    return null;
  }
  if (areAllTodosCompleted(historySnapshot.todos)) {
    return null;
  }
  return historySnapshot.todos;
}
__name(getStickyTodos, "getStickyTodos");
function getOrderedStickyTodos(todos) {
  return todos.map((todo, index) => ({ todo, index })).sort(
    (left3, right3) => STICKY_TODO_STATUS_PRIORITY[left3.todo.status] - STICKY_TODO_STATUS_PRIORITY[right3.todo.status] || left3.index - right3.index
  ).map(({ todo }) => todo);
}
__name(getOrderedStickyTodos, "getOrderedStickyTodos");
function getStickyTodosRenderKey(todos) {
  if (!todos) {
    return "null";
  }
  return JSON.stringify(
    todos.map((todo) => [todo.id, todo.content, todo.status])
  );
}
__name(getStickyTodosRenderKey, "getStickyTodosRenderKey");
function getStickyTodosLayoutKey(todos, width, maxVisibleItems) {
  if (!todos) {
    return "null";
  }
  const visibleTodoCount = clampStickyTodoVisibleItems(maxVisibleItems);
  const visibleTodos = todos.slice(0, visibleTodoCount);
  const hasHiddenTodos = todos.length > visibleTodos.length;
  return JSON.stringify({
    width,
    maxVisibleItems: visibleTodoCount,
    hasHiddenTodos,
    todos: visibleTodos.map((todo) => [todo.id, todo.content])
  });
}
__name(getStickyTodosLayoutKey, "getStickyTodosLayoutKey");
function getStickyTodoMaxVisibleItems(terminalHeight) {
  if (!Number.isFinite(terminalHeight) || terminalHeight <= 0) {
    return STICKY_TODO_MAX_VISIBLE_ITEMS;
  }
  return clampStickyTodoVisibleItems(
    terminalHeight / STICKY_TODO_ROWS_PER_VISIBLE_ITEM
  );
}
__name(getStickyTodoMaxVisibleItems, "getStickyTodoMaxVisibleItems");

// packages/cli/src/ui/components/StickyTodoList.tsx
var import_jsx_runtime140 = __toESM(require_jsx_runtime(), 1);
var STATUS_ICONS3 = {
  pending: "\u25CB",
  in_progress: "\u25D0",
  completed: "\u25CF"
};
function clampVisibleTodoCount(value) {
  if (!Number.isFinite(value)) {
    return STICKY_TODO_MAX_VISIBLE_ITEMS;
  }
  return Math.max(
    1,
    Math.min(STICKY_TODO_MAX_VISIBLE_ITEMS, Math.floor(value))
  );
}
__name(clampVisibleTodoCount, "clampVisibleTodoCount");
var StickyTodoListComponent = /* @__PURE__ */ __name(({
  todos,
  width,
  maxVisibleItems = STICKY_TODO_MAX_VISIBLE_ITEMS
}) => {
  const orderedTodos = (0, import_react140.useMemo)(() => getOrderedStickyTodos(todos), [todos]);
  const todoNumberById = (0, import_react140.useMemo)(
    () => new Map(todos.map((todo, index) => [todo.id, `${index + 1}.`])),
    [todos]
  );
  if (todos.length === 0) {
    return null;
  }
  const visibleTodoCount = clampVisibleTodoCount(maxVisibleItems);
  const visibleTodos = orderedTodos.slice(0, visibleTodoCount);
  const hiddenTodoCount = orderedTodos.length - visibleTodos.length;
  const numberColumnWidth = Math.max(
    ...visibleTodos.map(
      (todo, index) => (todoNumberById.get(todo.id) ?? `${index + 1}.`).length
    )
  ) + 1;
  const contentColumnWidth = Math.max(1, width - numberColumnWidth - 6);
  return /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(
    Box_default,
    {
      marginX: 2,
      width,
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.border.default,
      paddingX: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(Text3, { color: theme.text.secondary, bold: true, children: t4("Current tasks") }),
        visibleTodos.map((todo, index) => {
          const todoNumber = todoNumberById.get(todo.id) ?? `${index + 1}.`;
          const itemColor = todo.status === "in_progress" ? Colors.AccentGreen : Colors.Foreground;
          return /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(Box_default, { flexDirection: "row", height: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(Box_default, { width: numberColumnWidth, children: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(Text3, { color: theme.text.secondary, children: todoNumber }) }),
            /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(Box_default, { width: 2, children: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(Text3, { color: itemColor, children: STATUS_ICONS3[todo.status] }) }),
            /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(Box_default, { width: contentColumnWidth, children: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
              Text3,
              {
                color: itemColor,
                strikethrough: todo.status === "completed",
                wrap: "truncate-end",
                children: todo.content
              }
            ) })
          ] }, todo.id);
        }),
        hiddenTodoCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime140.jsxs)(Box_default, { flexDirection: "row", height: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(Box_default, { width: numberColumnWidth }),
          /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(Box_default, { width: 2 }),
          /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(Box_default, { width: contentColumnWidth, children: /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(Text3, { color: theme.text.secondary, wrap: "truncate-end", children: t4("... and {{count}} more", {
            count: String(hiddenTodoCount)
          }) }) })
        ] })
      ]
    }
  );
}, "StickyTodoListComponent");
var StickyTodoList = (0, import_react140.memo)(
  StickyTodoListComponent,
  (previousProps, nextProps) => previousProps.width === nextProps.width && previousProps.maxVisibleItems === nextProps.maxVisibleItems && getStickyTodosRenderKey(previousProps.todos) === getStickyTodosRenderKey(nextProps.todos)
);

// packages/cli/src/ui/layouts/ScreenReaderAppLayout.tsx
init_types22();
var import_jsx_runtime141 = __toESM(require_jsx_runtime(), 1);
var ScreenReaderAppLayout = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const stickyTodoWidth = Math.min(uiState.mainAreaWidth, 64);
  const stickyTodoMaxVisibleItems = getStickyTodoMaxVisibleItems(
    uiState.terminalHeight
  );
  const shouldShowStickyTodos = uiState.stickyTodos !== null && !uiState.dialogsVisible && !uiState.isFeedbackDialogOpen && uiState.streamingState !== "waiting_for_confirmation" /* WaitingForConfirmation */;
  return /* @__PURE__ */ (0, import_jsx_runtime141.jsxs)(Box_default, { flexDirection: "column", width: "90%", height: "100%", children: [
    /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(Notifications, {}),
    /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(Footer, {}),
    /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(Box_default, { flexGrow: 1, overflow: "hidden", children: /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(MainContent, {}) }),
    uiState.dialogsVisible ? /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(Box_default, { marginX: 2, flexDirection: "column", width: uiState.mainAreaWidth, children: /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
      DialogManager,
      {
        terminalWidth: uiState.terminalWidth,
        addItem: uiState.historyManager.addItem
      }
    ) }) : /* @__PURE__ */ (0, import_jsx_runtime141.jsxs)(import_jsx_runtime141.Fragment, { children: [
      shouldShowStickyTodos && /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
        StickyTodoList,
        {
          todos: uiState.stickyTodos,
          width: stickyTodoWidth,
          maxVisibleItems: stickyTodoMaxVisibleItems
        }
      ),
      uiState.btwItem && /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(Box_default, { marginX: 2, width: uiState.mainAreaWidth, children: /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(
        BtwMessage,
        {
          btw: uiState.btwItem.btw,
          containerWidth: uiState.mainAreaWidth
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(Composer, {})
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(ExitWarning, {})
  ] });
}, "ScreenReaderAppLayout");

// packages/cli/src/ui/layouts/DefaultAppLayout.tsx
init_esbuild_shims();
var import_react146 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/agent-view/AgentTabBar.tsx
init_esbuild_shims();
var import_react141 = __toESM(require_react(), 1);
init_dist4();
var import_jsx_runtime142 = __toESM(require_jsx_runtime(), 1);
function statusIndicator(agent) {
  const status = agent.interactiveAgent.getStatus();
  switch (status) {
    case AgentStatus.RUNNING:
    case AgentStatus.INITIALIZING:
      return { symbol: "\u25CF", color: theme.status.warning };
    // ● running
    case AgentStatus.IDLE:
      return { symbol: "\u25CF", color: theme.status.success };
    // ● idle (ready)
    case AgentStatus.COMPLETED:
      return { symbol: "\u2713", color: theme.status.success };
    // ✓ completed
    case AgentStatus.FAILED:
      return { symbol: "\u2717", color: theme.status.error };
    // ✗ failed
    case AgentStatus.CANCELLED:
      return { symbol: "\u25CB", color: theme.text.secondary };
    // ○ cancelled
    default:
      return { symbol: "\u25CB", color: theme.text.secondary };
  }
}
__name(statusIndicator, "statusIndicator");
var AgentTabBar = /* @__PURE__ */ __name(() => {
  const { activeView, agents, agentShellFocused, agentTabBarFocused } = useAgentViewState();
  const {
    switchToNext,
    switchToPrevious,
    switchToMain,
    setAgentTabBarFocused
  } = useAgentViewActions();
  const { entries: bgEntries } = useBackgroundTaskViewState();
  const { setPillFocused: setBgPillFocused } = useBackgroundTaskViewActions();
  const { embeddedShellFocused } = useUIState();
  const hasBgAgents = bgEntries.length > 0;
  useKeypress(
    (key) => {
      if (embeddedShellFocused || agentShellFocused) return;
      if (!agentTabBarFocused) return;
      if (key.name === "left") {
        switchToPrevious();
      } else if (key.name === "right") {
        switchToNext();
      } else if (key.name === "up") {
        setAgentTabBarFocused(false);
      } else if (key.name === "down") {
        if (hasBgAgents) {
          setAgentTabBarFocused(false);
          switchToMain();
          setBgPillFocused(true);
        }
      } else if (key.sequence && key.sequence.length === 1 && !key.ctrl && !key.meta) {
        setAgentTabBarFocused(false);
      }
    },
    { isActive: true }
  );
  const [, setTick] = (0, import_react141.useState)(0);
  const forceRender = (0, import_react141.useCallback)(() => setTick((t5) => t5 + 1), []);
  (0, import_react141.useEffect)(() => {
    const cleanups = [];
    for (const [, agent] of agents) {
      const emitter = agent.interactiveAgent.getEventEmitter();
      if (emitter) {
        emitter.on(AgentEventType.STATUS_CHANGE, forceRender);
        cleanups.push(
          () => emitter.off(AgentEventType.STATUS_CHANGE, forceRender)
        );
      }
    }
    return () => cleanups.forEach((fn) => fn());
  }, [agents, forceRender]);
  const isFocused = agentTabBarFocused;
  const hint = isFocused ? "\u2190/\u2192 switch  \u2191 input" : "\u2193 tabs";
  return /* @__PURE__ */ (0, import_jsx_runtime142.jsxs)(Box_default, { flexDirection: "row", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(Box_default, { marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
      Text3,
      {
        bold: activeView === "main",
        dimColor: !isFocused,
        backgroundColor: activeView === "main" ? theme.border.default : void 0,
        color: activeView === "main" ? theme.text.primary : theme.text.secondary,
        children: " Main "
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(Text3, { dimColor: !isFocused, color: theme.border.default, children: "\u2502" }),
    [...agents.entries()].map(([agentId, agent]) => {
      const isActive = activeView === agentId;
      const { symbol: symbol2, color: indicatorColor } = statusIndicator(agent);
      return /* @__PURE__ */ (0, import_jsx_runtime142.jsxs)(Box_default, { marginLeft: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
          Text3,
          {
            bold: isActive,
            dimColor: !isFocused,
            backgroundColor: isActive ? theme.border.default : void 0,
            color: isActive ? void 0 : agent.color || theme.text.secondary,
            children: ` ${agent.modelId} `
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(Text3, { dimColor: !isFocused, color: indicatorColor, children: ` ${symbol2}` })
      ] }, agentId);
    }),
    /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(Text3, { color: theme.text.secondary, children: hint }) })
  ] });
}, "AgentTabBar");

// packages/cli/src/ui/components/agent-view/AgentChatView.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/agent-view/AgentChatContent.tsx
init_esbuild_shims();
var import_react142 = __toESM(require_react(), 1);
init_dist4();
init_types22();

// packages/cli/src/ui/components/agent-view/agentHistoryAdapter.ts
init_esbuild_shims();
init_types22();
function agentMessagesToHistoryItems(messages, pendingApprovals, liveOutputs, shellPids, executionStartTimes) {
  const items = [];
  let nextId = 0;
  let i4 = 0;
  while (i4 < messages.length) {
    const msg = messages[i4];
    if (msg.role === "user") {
      items.push({ type: "user", text: msg.content, id: nextId++ });
      i4++;
    } else if (msg.role === "assistant") {
      if (msg.metadata?.["error"]) {
        items.push({ type: "error", text: msg.content, id: nextId++ });
      } else if (msg.thought) {
        items.push({ type: "gemini_thought", text: msg.content, id: nextId++ });
      } else {
        items.push({ type: "gemini", text: msg.content, id: nextId++ });
      }
      i4++;
    } else if (msg.role === "info") {
      const level = msg.metadata?.["level"];
      const type = level === "warning" || level === "success" || level === "error" ? level : "info";
      items.push({ type, text: msg.content, id: nextId++ });
      i4++;
    } else if (msg.role === "tool_call" || msg.role === "tool_result") {
      const groupId = nextId++;
      const callMap = /* @__PURE__ */ new Map();
      const callOrder = [];
      while (i4 < messages.length && (messages[i4].role === "tool_call" || messages[i4].role === "tool_result")) {
        const m3 = messages[i4];
        const callId = m3.metadata?.["callId"] ?? `unknown-${i4}`;
        if (m3.role === "tool_call") {
          if (!callMap.has(callId)) callOrder.push(callId);
          callMap.set(callId, {
            callId,
            name: m3.metadata?.["toolName"] ?? "unknown",
            description: m3.metadata?.["description"] ?? "",
            resultDisplay: void 0,
            outputFile: void 0,
            renderOutputAsMarkdown: m3.metadata?.["renderOutputAsMarkdown"],
            success: void 0
          });
        } else {
          const entry = callMap.get(callId);
          const resultDisplay = m3.metadata?.["resultDisplay"];
          const outputFile = m3.metadata?.["outputFile"];
          const success2 = m3.metadata?.["success"];
          if (entry) {
            entry.success = success2;
            entry.resultDisplay = resultDisplay;
            entry.outputFile = outputFile;
          } else {
            callOrder.push(callId);
            callMap.set(callId, {
              callId,
              name: m3.metadata?.["toolName"] ?? "unknown",
              description: "",
              resultDisplay,
              outputFile,
              renderOutputAsMarkdown: void 0,
              success: success2
            });
          }
        }
        i4++;
      }
      const tools = callOrder.map((callId) => {
        const entry = callMap.get(callId);
        const approval = pendingApprovals.get(callId);
        let status;
        if (approval) {
          status = "Confirming" /* Confirming */;
        } else if (entry.success === void 0) {
          status = "Executing" /* Executing */;
        } else if (entry.success) {
          status = "Success" /* Success */;
        } else {
          status = "Error" /* Error */;
        }
        const resultDisplay = status === "Executing" /* Executing */ && liveOutputs?.has(callId) ? liveOutputs.get(callId) : entry.resultDisplay;
        return {
          callId: entry.callId,
          name: entry.name,
          description: entry.description,
          resultDisplay,
          outputFile: entry.outputFile,
          renderOutputAsMarkdown: entry.renderOutputAsMarkdown,
          status,
          confirmationDetails: approval,
          ptyId: status === "Executing" /* Executing */ ? shellPids?.get(callId) : void 0,
          executionStartTime: status === "Executing" /* Executing */ ? executionStartTimes?.get(callId) : void 0
        };
      });
      items.push({ type: "tool_group", tools, id: groupId });
    } else {
      i4++;
    }
  }
  return items;
}
__name(agentMessagesToHistoryItems, "agentMessagesToHistoryItems");

// packages/cli/src/ui/components/agent-view/AgentHeader.tsx
init_esbuild_shims();
init_dist4();
var import_jsx_runtime143 = __toESM(require_jsx_runtime(), 1);
var AgentHeader = /* @__PURE__ */ __name(({
  modelId,
  modelName,
  workingDirectory,
  gitBranch
}) => {
  const { columns: terminalWidth } = useTerminalSize();
  const maxPathLen = Math.max(20, terminalWidth - 12);
  const displayPath = shortenPath(tildeifyPath(workingDirectory), maxPathLen);
  const modelText = modelName && modelName !== modelId ? `${modelId} (${modelName})` : modelId;
  return /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      marginX: 2,
      marginTop: 1,
      borderStyle: "round",
      borderColor: theme.border.default,
      paddingX: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)(Text3, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(Text3, { color: theme.text.secondary, children: "Model:  " }),
          /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(Text3, { color: theme.text.primary, children: modelText })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)(Text3, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(Text3, { color: theme.text.secondary, children: "Path:   " }),
          /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(Text3, { color: theme.text.primary, children: displayPath })
        ] }),
        gitBranch && /* @__PURE__ */ (0, import_jsx_runtime143.jsxs)(Text3, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(Text3, { color: theme.text.secondary, children: "Branch: " }),
          /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(Text3, { color: theme.text.primary, children: gitBranch })
        ] })
      ]
    }
  );
}, "AgentHeader");

// packages/cli/src/ui/components/agent-view/AgentChatContent.tsx
var import_jsx_runtime144 = __toESM(require_jsx_runtime(), 1);
var AgentChatContent = /* @__PURE__ */ __name(({
  core,
  interactiveAgent,
  instanceKey,
  modelName
}) => {
  const readonly2 = !interactiveAgent;
  const uiState = useUIState();
  const { historyRemountKey, availableTerminalHeight, constrainHeight } = uiState;
  const { columns: terminalWidth } = useTerminalSize();
  const contentWidth = terminalWidth - 4;
  const [, setRenderTick] = (0, import_react142.useState)(0);
  const tickRef = (0, import_react142.useRef)(0);
  const forceRender = (0, import_react142.useCallback)(() => {
    tickRef.current += 1;
    setRenderTick(tickRef.current);
  }, []);
  (0, import_react142.useEffect)(() => {
    const emitter = core.getEventEmitter();
    const onStatusChange = /* @__PURE__ */ __name((_event) => forceRender(), "onStatusChange");
    const onToolCall = /* @__PURE__ */ __name(() => forceRender(), "onToolCall");
    const onToolResult = /* @__PURE__ */ __name(() => forceRender(), "onToolResult");
    const onRoundEnd = /* @__PURE__ */ __name(() => forceRender(), "onRoundEnd");
    const onApproval = /* @__PURE__ */ __name(() => forceRender(), "onApproval");
    const onOutputUpdate = /* @__PURE__ */ __name(() => forceRender(), "onOutputUpdate");
    const onFinish = /* @__PURE__ */ __name(() => forceRender(), "onFinish");
    emitter.on(AgentEventType.STATUS_CHANGE, onStatusChange);
    emitter.on(AgentEventType.TOOL_CALL, onToolCall);
    emitter.on(AgentEventType.TOOL_RESULT, onToolResult);
    emitter.on(AgentEventType.ROUND_END, onRoundEnd);
    emitter.on(AgentEventType.TOOL_WAITING_APPROVAL, onApproval);
    emitter.on(AgentEventType.TOOL_OUTPUT_UPDATE, onOutputUpdate);
    emitter.on(AgentEventType.FINISH, onFinish);
    return () => {
      emitter.off(AgentEventType.STATUS_CHANGE, onStatusChange);
      emitter.off(AgentEventType.TOOL_CALL, onToolCall);
      emitter.off(AgentEventType.TOOL_RESULT, onToolResult);
      emitter.off(AgentEventType.ROUND_END, onRoundEnd);
      emitter.off(AgentEventType.TOOL_WAITING_APPROVAL, onApproval);
      emitter.off(AgentEventType.TOOL_OUTPUT_UPDATE, onOutputUpdate);
      emitter.off(AgentEventType.FINISH, onFinish);
    };
  }, [core, forceRender]);
  const messages = core.getMessages();
  const pendingApprovals = core.getPendingApprovals();
  const liveOutputs = core.getLiveOutputs();
  const shellPids = core.getShellPids();
  const status = interactiveAgent?.getStatus() ?? AgentStatus.COMPLETED;
  const executionStartTimes = interactiveAgent?.getExecutionStartTimes();
  const activePtyId = shellPids.size > 0 ? shellPids.values().next().value ?? null : null;
  const isRunning = status === AgentStatus.RUNNING || status === AgentStatus.INITIALIZING;
  const [embeddedShellFocused, setEmbeddedShellFocused] = (0, import_react142.useState)(false);
  const { setAgentShellFocused } = useAgentViewActions();
  (0, import_react142.useEffect)(() => {
    if (readonly2) return;
    setAgentShellFocused(embeddedShellFocused);
    return () => setAgentShellFocused(false);
  }, [embeddedShellFocused, readonly2, setAgentShellFocused]);
  (0, import_react142.useEffect)(() => {
    if (!activePtyId) setEmbeddedShellFocused(false);
  }, [activePtyId]);
  useKeypress(
    (key) => {
      if (readonly2) return;
      if (key.ctrl && key.name === "f") {
        if (activePtyId || embeddedShellFocused) {
          setEmbeddedShellFocused((prev) => !prev);
        }
      }
    },
    { isActive: !readonly2 }
  );
  const allItems = (0, import_react142.useMemo)(
    () => agentMessagesToHistoryItems(
      messages,
      pendingApprovals,
      liveOutputs,
      shellPids,
      executionStartTimes
    ),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [
      instanceKey,
      messages.length,
      pendingApprovals.size,
      liveOutputs.size,
      shellPids.size,
      executionStartTimes?.size,
      tickRef.current
    ]
  );
  const splitIndex = (0, import_react142.useMemo)(() => {
    for (let idx = allItems.length - 1; idx >= 0; idx--) {
      const item = allItems[idx];
      if (item.type === "tool_group" && item.tools.some(
        (t5) => t5.status === "Executing" /* Executing */ || t5.status === "Confirming" /* Confirming */
      )) {
        return idx;
      }
    }
    return allItems.length;
  }, [allItems]);
  const committedItems = allItems.slice(0, splitIndex);
  const pendingItems = allItems.slice(splitIndex);
  const agentWorkingDir = core.runtimeContext.getTargetDir() ?? "";
  const agentGitBranch = (0, import_react142.useMemo)(
    () => agentWorkingDir ? getGitBranch(agentWorkingDir) : "",
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [instanceKey]
  );
  const agentModelId = core.modelConfig.model ?? "";
  return /* @__PURE__ */ (0, import_jsx_runtime144.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
      Static,
      {
        items: [
          /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
            AgentHeader,
            {
              modelId: agentModelId,
              modelName,
              workingDirectory: agentWorkingDir,
              gitBranch: agentGitBranch
            },
            "agent-header"
          ),
          ...committedItems.map((item) => /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
            HistoryItemDisplayComponent,
            {
              item,
              isPending: false,
              terminalWidth,
              mainAreaWidth: contentWidth
            },
            item.id
          ))
        ],
        children: (item) => item
      },
      `agent-${instanceKey}-${historyRemountKey}`
    ),
    pendingItems.map((item) => /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(
      HistoryItemDisplayComponent,
      {
        item,
        isPending: true,
        terminalWidth,
        mainAreaWidth: contentWidth,
        availableTerminalHeight: constrainHeight ? availableTerminalHeight : void 0,
        isFocused: !readonly2,
        activeShellPtyId: activePtyId,
        embeddedShellFocused
      },
      item.id
    )),
    isRunning && /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(Box_default, { marginX: 2, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(GeminiRespondingSpinner, {}) })
  ] });
}, "AgentChatContent");
var AgentChatMissing = /* @__PURE__ */ __name(({ label }) => /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(Box_default, { marginX: 2, children: /* @__PURE__ */ (0, import_jsx_runtime144.jsx)(Text3, { color: theme.status.error, children: label }) }), "AgentChatMissing");

// packages/cli/src/ui/components/agent-view/AgentChatView.tsx
var import_jsx_runtime145 = __toESM(require_jsx_runtime(), 1);
var AgentChatView = /* @__PURE__ */ __name(({ agentId }) => {
  const { agents } = useAgentViewState();
  const agent = agents.get(agentId);
  const interactiveAgent = agent?.interactiveAgent;
  const core = interactiveAgent?.getCore();
  if (!agent || !interactiveAgent || !core) {
    return /* @__PURE__ */ (0, import_jsx_runtime145.jsx)(AgentChatMissing, { label: `Agent "${agentId}" not found.` });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime145.jsx)(
    AgentChatContent,
    {
      core,
      interactiveAgent,
      instanceKey: agentId,
      modelName: agent.modelName
    }
  );
}, "AgentChatView");

// packages/cli/src/ui/components/agent-view/AgentComposer.tsx
init_esbuild_shims();
var import_react145 = __toESM(require_react(), 1);
init_dist4();
init_types22();

// packages/cli/src/ui/hooks/useAgentStreamingState.ts
init_esbuild_shims();
var import_react144 = __toESM(require_react(), 1);
init_dist4();
init_types22();

// packages/cli/src/ui/hooks/useTimer.ts
init_esbuild_shims();
var import_react143 = __toESM(require_react(), 1);
var useTimer = /* @__PURE__ */ __name((isActive, resetKey) => {
  const [elapsedTime, setElapsedTime] = (0, import_react143.useState)(0);
  const timerRef = (0, import_react143.useRef)(null);
  const prevResetKeyRef = (0, import_react143.useRef)(resetKey);
  const prevIsActiveRef = (0, import_react143.useRef)(isActive);
  (0, import_react143.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/useAgentStreamingState.ts
function useAgentStreamingState(interactiveAgent, events) {
  const [, setTick] = (0, import_react144.useState)(0);
  const tickRef = (0, import_react144.useRef)(0);
  const forceRender = (0, import_react144.useCallback)(() => {
    tickRef.current += 1;
    setTick(tickRef.current);
  }, []);
  const [lastPromptTokenCount, setLastPromptTokenCount] = (0, import_react144.useState)(
    () => interactiveAgent?.getLastPromptTokenCount() ?? 0
  );
  const subscribedEvents = events ?? DEFAULT_EVENTS;
  (0, import_react144.useEffect)(() => {
    if (!interactiveAgent) return;
    const emitter = interactiveAgent.getEventEmitter();
    if (!emitter) return;
    const handler = /* @__PURE__ */ __name(() => forceRender(), "handler");
    for (const evt of subscribedEvents) {
      emitter.on(evt, handler);
    }
    const usageHandler = /* @__PURE__ */ __name((event) => {
      const count = event?.usage?.totalTokenCount ?? event?.usage?.promptTokenCount;
      if (typeof count === "number" && count > 0) {
        setLastPromptTokenCount(count);
      }
    }, "usageHandler");
    emitter.on(AgentEventType.USAGE_METADATA, usageHandler);
    return () => {
      for (const evt of subscribedEvents) {
        emitter.off(evt, handler);
      }
      emitter.off(AgentEventType.USAGE_METADATA, usageHandler);
    };
  }, [interactiveAgent, forceRender, subscribedEvents]);
  const status = interactiveAgent?.getStatus();
  const pendingApprovals = interactiveAgent?.getPendingApprovals();
  const hasPendingApprovals = pendingApprovals !== void 0 && pendingApprovals.size > 0;
  const streamingState = (0, import_react144.useMemo)(() => {
    if (hasPendingApprovals) {
      return "waiting_for_confirmation" /* WaitingForConfirmation */;
    }
    if (status === AgentStatus.RUNNING || status === AgentStatus.INITIALIZING) {
      return "responding" /* Responding */;
    }
    return "idle" /* Idle */;
  }, [status, hasPendingApprovals]);
  const isInputActive = (streamingState === "idle" /* Idle */ || streamingState === "responding" /* Responding */) && status !== void 0 && !isTerminalStatus(status);
  const [timerResetKey, setTimerResetKey] = (0, import_react144.useState)(0);
  const prevStreamingRef = (0, import_react144.useRef)(streamingState);
  (0, import_react144.useEffect)(() => {
    if (streamingState === "responding" /* Responding */ && prevStreamingRef.current !== "responding" /* Responding */) {
      setTimerResetKey((k2) => k2 + 1);
    }
    prevStreamingRef.current = streamingState;
  }, [streamingState]);
  const elapsedTime = useTimer(
    streamingState === "responding" /* Responding */,
    timerResetKey
  );
  return {
    status,
    streamingState,
    isInputActive,
    elapsedTime,
    lastPromptTokenCount
  };
}
__name(useAgentStreamingState, "useAgentStreamingState");
var DEFAULT_EVENTS = [
  AgentEventType.STATUS_CHANGE,
  AgentEventType.TOOL_WAITING_APPROVAL,
  AgentEventType.TOOL_RESULT
];

// packages/cli/src/ui/components/agent-view/AgentFooter.tsx
init_esbuild_shims();
init_dist4();
var import_jsx_runtime146 = __toESM(require_jsx_runtime(), 1);
var AgentFooter = /* @__PURE__ */ __name(({
  approvalMode,
  promptTokenCount,
  contextWindowSize,
  terminalWidth
}) => {
  const showApproval = approvalMode !== void 0 && approvalMode !== ApprovalMode.DEFAULT;
  const showContext = promptTokenCount > 0 && contextWindowSize !== void 0;
  if (!showApproval && !showContext) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime146.jsxs)(
    Box_default,
    {
      justifyContent: "space-between",
      width: "100%",
      flexDirection: "row",
      alignItems: "center",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime146.jsx)(Box_default, { marginLeft: 2, children: showApproval ? /* @__PURE__ */ (0, import_jsx_runtime146.jsx)(AutoAcceptIndicator, { approvalMode }) : null }),
        /* @__PURE__ */ (0, import_jsx_runtime146.jsx)(Box_default, { marginRight: 2, children: showContext && /* @__PURE__ */ (0, import_jsx_runtime146.jsx)(Text3, { color: theme.text.accent, children: /* @__PURE__ */ (0, import_jsx_runtime146.jsx)(
          ContextUsageDisplay,
          {
            promptTokenCount,
            terminalWidth,
            contextWindowSize
          }
        ) }) })
      ]
    }
  );
}, "AgentFooter");

// packages/cli/src/ui/components/agent-view/AgentComposer.tsx
init_i18n();
var import_jsx_runtime147 = __toESM(require_jsx_runtime(), 1);
var AgentComposer = /* @__PURE__ */ __name(({ agentId }) => {
  const { agents, agentTabBarFocused, agentShellFocused, agentApprovalModes } = useAgentViewState();
  const {
    setAgentInputBufferText,
    setAgentTabBarFocused,
    setAgentApprovalMode
  } = useAgentViewActions();
  const agent = agents.get(agentId);
  const interactiveAgent = agent?.interactiveAgent;
  const config2 = useConfig();
  const { columns: terminalWidth } = useTerminalSize();
  const { inputWidth } = calculatePromptWidths(terminalWidth);
  const { stdin: stdin2, setRawMode } = use_stdin_default();
  const {
    status,
    streamingState,
    isInputActive,
    elapsedTime,
    lastPromptTokenCount
  } = useAgentStreamingState(interactiveAgent);
  useKeypress(
    (key) => {
      if (key.name === "escape" && streamingState === "responding" /* Responding */) {
        interactiveAgent?.cancelCurrentRound();
      }
    },
    {
      isActive: streamingState === "responding" /* Responding */ && !agentShellFocused
    }
  );
  const agentApprovalMode = agentApprovalModes.get(agentId) ?? ApprovalMode.DEFAULT;
  useKeypress(
    (key) => {
      const isShiftTab = key.shift && key.name === "tab";
      const isWindowsTab = process.platform === "win32" && key.name === "tab" && !key.ctrl && !key.meta;
      if (isShiftTab || isWindowsTab) {
        const currentIndex = APPROVAL_MODES.indexOf(agentApprovalMode);
        const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % APPROVAL_MODES.length;
        setAgentApprovalMode(agentId, APPROVAL_MODES[nextIndex]);
      }
    },
    { isActive: !agentShellFocused }
  );
  const isValidPath = (0, import_react145.useCallback)(() => false, []);
  const buffer = useTextBuffer({
    initialText: "",
    viewport: { height: 3, width: inputWidth },
    stdin: stdin2,
    setRawMode,
    isValidPath
  });
  (0, import_react145.useEffect)(() => {
    setAgentInputBufferText(buffer.text);
    return () => setAgentInputBufferText("");
  }, [buffer.text, setAgentInputBufferText]);
  (0, import_react145.useEffect)(() => {
    if (!isInputActive) {
      setAgentTabBarFocused(true);
    }
  }, [isInputActive, streamingState, setAgentTabBarFocused]);
  const handleKeypress = (0, import_react145.useCallback)(
    (key) => {
      if (agentTabBarFocused) {
        if (key.sequence && key.sequence.length === 1 && !key.ctrl && !key.meta) {
          return false;
        }
        return true;
      }
      if (keyMatchers["navigationDown" /* NAVIGATION_DOWN */](key)) {
        if (buffer.text === "" || buffer.allVisualLines.length === 1 || buffer.visualCursor[0] === buffer.allVisualLines.length - 1) {
          setAgentTabBarFocused(true);
          return true;
        }
      }
      return false;
    },
    [buffer, agentTabBarFocused, setAgentTabBarFocused]
  );
  const [messageQueue, setMessageQueue] = (0, import_react145.useState)([]);
  (0, import_react145.useEffect)(() => {
    if (streamingState === "idle" /* Idle */ && messageQueue.length > 0 && status !== void 0 && !isTerminalStatus(status)) {
      const combined = messageQueue.join("\n");
      setMessageQueue([]);
      interactiveAgent?.enqueueMessage(combined);
    }
  }, [streamingState, messageQueue, interactiveAgent, status]);
  const handleSubmit = (0, import_react145.useCallback)(
    (text) => {
      const trimmed2 = text.trim();
      if (!trimmed2 || !interactiveAgent) return;
      if (streamingState === "idle" /* Idle */) {
        interactiveAgent.enqueueMessage(trimmed2);
      } else {
        setMessageQueue((prev) => [...prev, trimmed2]);
      }
    },
    [interactiveAgent, streamingState]
  );
  const statusLabel2 = (0, import_react145.useMemo)(() => {
    switch (status) {
      case AgentStatus.COMPLETED:
        return { text: t4("Completed"), color: theme.status.success };
      case AgentStatus.FAILED:
        return {
          text: t4("Failed: {{error}}", {
            error: interactiveAgent?.getError() ?? interactiveAgent?.getLastRoundError() ?? "unknown"
          }),
          color: theme.status.error
        };
      case AgentStatus.CANCELLED:
        return { text: t4("Cancelled"), color: theme.text.secondary };
      default:
        return null;
    }
  }, [status, interactiveAgent]);
  const isYolo = agentApprovalMode === ApprovalMode.YOLO;
  const isAutoAccept = agentApprovalMode !== ApprovalMode.DEFAULT;
  const statusColor = isYolo ? theme.status.errorDim : isAutoAccept ? theme.status.warningDim : void 0;
  const inputBorderColor = !isInputActive || agentTabBarFocused ? theme.border.default : statusColor ?? theme.border.focused;
  const prefixNode = /* @__PURE__ */ (0, import_jsx_runtime147.jsxs)(Text3, { color: statusColor ?? theme.text.accent, children: [
    isYolo ? "*" : ">",
    " "
  ] });
  return /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(StreamingContext.Provider, { value: streamingState, children: /* @__PURE__ */ (0, import_jsx_runtime147.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
      LoadingIndicator,
      {
        currentLoadingPhrase: streamingState === "responding" /* Responding */ ? t4("Thinking\u2026") : void 0,
        elapsedTime
      }
    ),
    statusLabel2 && /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(Text3, { color: statusLabel2.color, children: statusLabel2.text }) }),
    /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(QueuedMessageDisplay, { messageQueue }),
    /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
      BaseTextInput,
      {
        buffer,
        onSubmit: handleSubmit,
        onKeypress: handleKeypress,
        showCursor: isInputActive && !agentTabBarFocused,
        placeholder: "  " + t4("Send a message to this agent"),
        prefix: prefixNode,
        borderColor: inputBorderColor,
        isActive: isInputActive && !agentShellFocused
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime147.jsx)(
      AgentFooter,
      {
        approvalMode: agentApprovalMode,
        promptTokenCount: lastPromptTokenCount,
        contextWindowSize: config2.getContentGeneratorConfig()?.contextWindowSize,
        terminalWidth
      }
    )
  ] }) });
}, "AgentComposer");

// packages/cli/src/ui/layouts/DefaultAppLayout.tsx
init_types22();
var import_jsx_runtime148 = __toESM(require_jsx_runtime(), 1);
var DefaultAppLayout = /* @__PURE__ */ __name(() => {
  const uiState = useUIState();
  const { refreshStatic } = useUIActions();
  const { activeView, agents } = useAgentViewState();
  const { columns: terminalWidth } = useTerminalSize();
  const hasAgents = agents.size > 0;
  const isAgentTab = activeView !== "main" && agents.has(activeView);
  const stickyTodoWidth = Math.min(uiState.mainAreaWidth, 64);
  const stickyTodoMaxVisibleItems = getStickyTodoMaxVisibleItems(
    uiState.terminalHeight
  );
  const shouldShowStickyTodos = uiState.stickyTodos !== null && !uiState.dialogsVisible && !uiState.isFeedbackDialogOpen && uiState.streamingState !== "waiting_for_confirmation" /* WaitingForConfirmation */;
  const prevViewRef = (0, import_react146.useRef)(activeView);
  (0, import_react146.useEffect)(() => {
    if (prevViewRef.current !== activeView) {
      prevViewRef.current = activeView;
      refreshStatic();
    }
  }, [activeView, refreshStatic]);
  return /* @__PURE__ */ (0, import_jsx_runtime148.jsxs)(Box_default, { flexDirection: "column", width: terminalWidth, children: [
    isAgentTab ? /* @__PURE__ */ (0, import_jsx_runtime148.jsxs)(import_jsx_runtime148.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(AgentChatView, { agentId: activeView }),
      /* @__PURE__ */ (0, import_jsx_runtime148.jsxs)(Box_default, { flexDirection: "column", ref: uiState.mainControlsRef, children: [
        /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(AgentComposer, { agentId: activeView }, activeView),
        /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(ExitWarning, {})
      ] })
    ] }) : /* @__PURE__ */ (0, import_jsx_runtime148.jsxs)(import_jsx_runtime148.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(MainContent, {}),
      /* @__PURE__ */ (0, import_jsx_runtime148.jsxs)(Box_default, { flexDirection: "column", ref: uiState.mainControlsRef, children: [
        uiState.dialogsVisible ? /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(
          Box_default,
          {
            marginX: 2,
            flexDirection: "column",
            width: uiState.mainAreaWidth,
            children: /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(
              DialogManager,
              {
                terminalWidth: uiState.terminalWidth,
                addItem: uiState.historyManager.addItem
              }
            )
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime148.jsxs)(import_jsx_runtime148.Fragment, { children: [
          shouldShowStickyTodos && /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(
            StickyTodoList,
            {
              todos: uiState.stickyTodos,
              width: stickyTodoWidth,
              maxVisibleItems: stickyTodoMaxVisibleItems
            }
          ),
          uiState.btwItem && /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(Box_default, { marginX: 2, width: uiState.mainAreaWidth, children: /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(
            BtwMessage,
            {
              btw: uiState.btwItem.btw,
              containerWidth: uiState.mainAreaWidth
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(Composer, {})
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(ExitWarning, {})
      ] })
    ] }),
    hasAgents && !uiState.dialogsVisible && /* @__PURE__ */ (0, import_jsx_runtime148.jsx)(AgentTabBar, {})
  ] });
}, "DefaultAppLayout");

// packages/cli/src/ui/App.tsx
var import_jsx_runtime149 = __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_runtime149.jsx)(QuittingDisplay, {});
  }
  return /* @__PURE__ */ (0, import_jsx_runtime149.jsx)(StreamingContext.Provider, { value: uiState.streamingState, children: isScreenReaderEnabled ? /* @__PURE__ */ (0, import_jsx_runtime149.jsx)(ScreenReaderAppLayout, {}) : /* @__PURE__ */ (0, import_jsx_runtime149.jsx)(DefaultAppLayout, {}) });
}, "App");

// packages/cli/src/ui/AppContainer.tsx
init_types22();
init_types22();
init_dist4();
import process50 from "node:process";

// packages/cli/src/ui/hooks/useMemoryMonitor.ts
init_esbuild_shims();
var import_react147 = __toESM(require_react(), 1);
init_types22();
import process38 from "node:process";
var MEMORY_WARNING_THRESHOLD = 7 * 1024 * 1024 * 1024;
var MEMORY_CHECK_INTERVAL = 60 * 1e3;
var useMemoryMonitor = /* @__PURE__ */ __name(({ addItem }) => {
  (0, import_react147.useEffect)(() => {
    const intervalId = setInterval(() => {
      const usage2 = process38.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_react148 = __toESM(require_react(), 1);
init_types22();
init_i18n();
import process39 from "node:process";
var useThemeCommand = /* @__PURE__ */ __name((loadedSettings, setThemeError, addItem, initialThemeError) => {
  const [isThemeDialogOpen, setIsThemeDialogOpen] = (0, import_react148.useState)(!!initialThemeError);
  const [themeBeforeDialogOpen, setThemeBeforeDialogOpen] = (0, import_react148.useState)(themeManager.getActiveTheme().name);
  const openThemeDialog = (0, import_react148.useCallback)(() => {
    if (process39.env["NO_COLOR"]) {
      addItem(
        {
          type: "info" /* INFO */,
          text: t4(
            "Theme configuration unavailable due to NO_COLOR env variable."
          )
        },
        Date.now()
      );
      return;
    }
    setThemeBeforeDialogOpen(themeManager.getActiveTheme().name);
    setIsThemeDialogOpen(true);
  }, [addItem]);
  const applyTheme = (0, import_react148.useCallback)(
    (themeName) => {
      if (!themeManager.setActiveTheme(themeName)) {
        setIsThemeDialogOpen(true);
        setThemeError(
          t4('Theme "{{themeName}}" not found.', {
            themeName: themeName ?? ""
          })
        );
      } else {
        setThemeError(null);
      }
    },
    [setThemeError]
  );
  const handleThemeHighlight = (0, import_react148.useCallback)(
    (themeName) => {
      applyTheme(themeName);
    },
    [applyTheme]
  );
  const handleThemeSelect = (0, import_react148.useCallback)(
    (themeName, scope) => {
      if (themeName === void 0) {
        applyTheme(themeBeforeDialogOpen);
        setThemeError(null);
        setIsThemeDialogOpen(false);
        return;
      }
      try {
        const mergedCustomThemes = {
          ...loadedSettings.user.settings.ui?.customThemes || {},
          ...loadedSettings.workspace.settings.ui?.customThemes || {}
        };
        const isAuto = themeName === AUTO_THEME_NAME;
        const isBuiltIn = themeManager.findThemeByName(themeName);
        const isCustom = themeName && mergedCustomThemes[themeName];
        if (!isAuto && !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, themeBeforeDialogOpen]
  );
  return {
    isThemeDialogOpen,
    openThemeDialog,
    handleThemeSelect,
    handleThemeHighlight
  };
}, "useThemeCommand");

// packages/cli/src/ui/hooks/useFeedbackDialog.ts
init_esbuild_shims();
var import_react149 = __toESM(require_react(), 1);
init_dist4();
init_types22();
import * as fs128 from "node:fs";
var import_strip_json_comments4 = __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 debugLogger154 = 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 (fs128.existsSync(USER_SETTINGS_PATH)) {
      const content = fs128.readFileSync(USER_SETTINGS_PATH, "utf-8");
      const settings = JSON.parse((0, import_strip_json_comments4.default)(content));
      return settings?.ui?.feedbackLastShownTimestamp ?? 0;
    }
  } catch (error40) {
    if (isNodeError(error40) && error40.code !== "ENOENT") {
      debugLogger154.warn(
        "Failed to read feedbackLastShownTimestamp from settings file:",
        error40
      );
    }
  }
  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_react149.useState)(false);
  const [isFeedbackDismissedTemporarily, setIsFeedbackDismissedTemporarily] = (0, import_react149.useState)(false);
  const openFeedbackDialog = (0, import_react149.useCallback)(() => {
    setIsFeedbackDialogOpen(true);
  }, []);
  const closeFeedbackDialog = (0, import_react149.useCallback)(
    () => setIsFeedbackDialogOpen(false),
    []
  );
  const temporaryCloseFeedbackDialog = (0, import_react149.useCallback)(() => {
    setIsFeedbackDialogOpen(false);
    setIsFeedbackDismissedTemporarily(true);
  }, []);
  const submitFeedback = (0, import_react149.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_react149.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_react149.useEffect)(() => {
    if (streamingState === "responding" /* Responding */ && isFeedbackDismissedTemporarily) {
      setIsFeedbackDismissedTemporarily(false);
    }
  }, [streamingState, isFeedbackDismissedTemporarily]);
  return {
    isFeedbackDialogOpen,
    openFeedbackDialog,
    closeFeedbackDialog,
    temporaryCloseFeedbackDialog,
    submitFeedback
  };
}, "useFeedbackDialog");

// packages/cli/src/ui/hooks/useEditorSettings.ts
init_esbuild_shims();
var import_react150 = __toESM(require_react(), 1);
init_types22();
init_dist4();
var useEditorSettings = /* @__PURE__ */ __name((loadedSettings, setEditorError, addItem) => {
  const [isEditorDialogOpen, setIsEditorDialogOpen] = (0, import_react150.useState)(false);
  const openEditorDialog = (0, import_react150.useCallback)(() => {
    setIsEditorDialogOpen(true);
  }, []);
  const handleEditorSelect = (0, import_react150.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 (error40) {
        setEditorError(`Failed to set editor preference: ${error40}`);
      }
    },
    [loadedSettings, setEditorError, addItem]
  );
  const exitEditorDialog = (0, import_react150.useCallback)(() => {
    setIsEditorDialogOpen(false);
  }, []);
  return {
    isEditorDialogOpen,
    openEditorDialog,
    handleEditorSelect,
    exitEditorDialog
  };
}, "useEditorSettings");

// packages/cli/src/ui/hooks/useSettingsCommand.ts
init_esbuild_shims();
var import_react151 = __toESM(require_react(), 1);
function useSettingsCommand() {
  const [isSettingsDialogOpen, setIsSettingsDialogOpen] = (0, import_react151.useState)(false);
  const openSettingsDialog = (0, import_react151.useCallback)(() => {
    setIsSettingsDialogOpen(true);
  }, []);
  const closeSettingsDialog = (0, import_react151.useCallback)(() => {
    setIsSettingsDialogOpen(false);
  }, []);
  return {
    isSettingsDialogOpen,
    openSettingsDialog,
    closeSettingsDialog
  };
}
__name(useSettingsCommand, "useSettingsCommand");

// packages/cli/src/ui/hooks/useModelCommand.ts
init_esbuild_shims();
var import_react152 = __toESM(require_react(), 1);
var useModelCommand = /* @__PURE__ */ __name(() => {
  const [isModelDialogOpen, setIsModelDialogOpen] = (0, import_react152.useState)(false);
  const [isFastModelMode, setIsFastModelMode] = (0, import_react152.useState)(false);
  const openModelDialog = (0, import_react152.useCallback)(
    (options2) => {
      setIsFastModelMode(options2?.fastModelMode ?? false);
      setIsModelDialogOpen(true);
    },
    []
  );
  const closeModelDialog = (0, import_react152.useCallback)(() => {
    setIsModelDialogOpen(false);
    setIsFastModelMode(false);
  }, []);
  return {
    isModelDialogOpen,
    isFastModelMode,
    openModelDialog,
    closeModelDialog
  };
}, "useModelCommand");

// packages/cli/src/ui/hooks/useManageModelsCommand.ts
init_esbuild_shims();
var import_react153 = __toESM(require_react(), 1);
function useManageModelsCommand() {
  const [isManageModelsDialogOpen, setIsManageModelsDialogOpen] = (0, import_react153.useState)(false);
  const openManageModelsDialog = (0, import_react153.useCallback)(() => {
    setIsManageModelsDialogOpen(true);
  }, []);
  const closeManageModelsDialog = (0, import_react153.useCallback)(() => {
    setIsManageModelsDialogOpen(false);
  }, []);
  return {
    isManageModelsDialogOpen,
    openManageModelsDialog,
    closeManageModelsDialog
  };
}
__name(useManageModelsCommand, "useManageModelsCommand");

// packages/cli/src/ui/hooks/useApprovalModeCommand.ts
init_esbuild_shims();
var import_react154 = __toESM(require_react(), 1);
var useApprovalModeCommand = /* @__PURE__ */ __name((loadedSettings, config2) => {
  const [isApprovalModeDialogOpen, setIsApprovalModeDialogOpen] = (0, import_react154.useState)(false);
  const openApprovalModeDialog = (0, import_react154.useCallback)(() => {
    setIsApprovalModeDialogOpen(true);
  }, []);
  const handleApprovalModeSelect = (0, import_react154.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_react155 = __toESM(require_react(), 1);
init_dist4();
function useResumeCommand(options2) {
  const [isResumeDialogOpen, setIsResumeDialogOpen] = (0, import_react155.useState)(false);
  const [resumeMatchedSessions, setResumeMatchedSessions] = (0, import_react155.useState)();
  const openResumeDialog = (0, import_react155.useCallback)(
    (matchedSessions) => {
      setResumeMatchedSessions(matchedSessions);
      setIsResumeDialogOpen(true);
    },
    []
  );
  const closeResumeDialog = (0, import_react155.useCallback)(() => {
    setIsResumeDialogOpen(false);
    setResumeMatchedSessions(void 0);
  }, []);
  const { config: config2, historyManager, startNewSession, setSessionName, remount } = options2 ?? {};
  const hasHistoryManager = !!historyManager;
  const { clearItems, loadHistory } = historyManager || {};
  const handleResume = (0, import_react155.useCallback)(
    async (sessionId) => {
      if (!config2 || !hasHistoryManager || !startNewSession) {
        return;
      }
      closeResumeDialog();
      const cwd6 = config2.getTargetDir();
      const sessionService = new SessionService(cwd6);
      const sessionData = await sessionService.loadSession(sessionId);
      if (!sessionData) {
        return;
      }
      startNewSession(sessionId);
      const customTitle = sessionService.getSessionTitle(sessionId);
      setSessionName?.(customTitle ?? null);
      const uiHistoryItems = buildResumedHistoryItems(sessionData, config2);
      clearItems?.();
      loadHistory?.(uiHistoryItems);
      config2.startNewSession(sessionId, sessionData);
      config2.getChatRecordingService()?.rebuildTurnBoundaries(sessionData.conversation.messages);
      await config2.getGeminiClient()?.initialize?.();
      try {
        await config2.getHookSystem()?.fireSessionStartEvent(
          SessionStartSource.Resume,
          config2.getModel() ?? "",
          String(config2.getApprovalMode())
        );
      } catch (err2) {
        config2.getDebugLogger().warn(`SessionStart hook failed: ${err2}`);
      }
      remount?.();
    },
    [
      closeResumeDialog,
      config2,
      hasHistoryManager,
      clearItems,
      loadHistory,
      startNewSession,
      setSessionName,
      remount
    ]
  );
  return {
    isResumeDialogOpen,
    resumeMatchedSessions,
    openResumeDialog,
    closeResumeDialog,
    handleResume
  };
}
__name(useResumeCommand, "useResumeCommand");

// packages/cli/src/ui/hooks/useDeleteCommand.ts
init_esbuild_shims();
var import_react156 = __toESM(require_react(), 1);
init_i18n();
function useDeleteCommand(options2) {
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = (0, import_react156.useState)(false);
  const openDeleteDialog = (0, import_react156.useCallback)(() => {
    setIsDeleteDialogOpen(true);
  }, []);
  const closeDeleteDialog = (0, import_react156.useCallback)(() => {
    setIsDeleteDialogOpen(false);
  }, []);
  const { config: config2, addItem } = options2 ?? {};
  const handleDelete = (0, import_react156.useCallback)(
    async (sessionId) => {
      if (!config2) {
        return;
      }
      closeDeleteDialog();
      if (sessionId === config2.getSessionId()) {
        addItem?.(
          {
            type: "info",
            text: t4("Cannot delete the current active session.")
          },
          Date.now()
        );
        return;
      }
      try {
        const sessionService = config2.getSessionService();
        const success2 = await sessionService.removeSession(sessionId);
        if (success2) {
          addItem?.(
            {
              type: "info",
              text: t4("Session deleted successfully.")
            },
            Date.now()
          );
        } else {
          addItem?.(
            {
              type: "error",
              text: t4("Failed to delete session. Session not found.")
            },
            Date.now()
          );
        }
      } catch {
        addItem?.(
          {
            type: "error",
            text: t4("Failed to delete session.")
          },
          Date.now()
        );
      }
    },
    [closeDeleteDialog, config2, addItem]
  );
  return {
    isDeleteDialogOpen,
    openDeleteDialog,
    closeDeleteDialog,
    handleDelete
  };
}
__name(useDeleteCommand, "useDeleteCommand");

// packages/cli/src/ui/hooks/slashCommandProcessor.ts
init_esbuild_shims();
var import_react157 = __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 Language3;
(function(Language4) {
  Language4["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED";
  Language4["PYTHON"] = "PYTHON";
})(Language3 || (Language3 = {}));
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/ui/hooks/slashCommandProcessor.ts
init_dist4();
init_types22();
init_types21();

// packages/cli/src/services/McpPromptLoader.ts
init_esbuild_shims();
init_dist4();
init_types21();
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 */,
          source: "mcp-prompt",
          sourceLabel: `MCP: ${serverName}`,
          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, args2) => {
            if (!this.config) {
              return {
                type: "message",
                messageType: "error",
                content: "Config not loaded."
              };
            }
            const promptInputs = this.parseArgs(args2, 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 (error40) {
              return {
                type: "message",
                messageType: "error",
                content: `Error: ${getErrorMessage(error40)}`
              };
            }
          }, "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 i4 = 0; i4 < unfilledArgs.length; i4++) {
        if (positionalArgs.length > i4) {
          promptInputs[unfilledArgs[i4].name] = positionalArgs[i4];
        } else {
          missingArgs.push(unfilledArgs[i4].name);
        }
      }
      if (missingArgs.length > 0) {
        const missingArgNames = missingArgs.map((name4) => `--${name4}`).join(", ");
        return new Error(`Missing required argument(s): ${missingArgNames}`);
      }
    }
    return promptInputs;
  }
};

// packages/cli/src/ui/hooks/slashCommandProcessor.ts
init_stdioHelpers();
var debugLogger155 = 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",
  "delete",
  "btw"
]);
var useSlashCommandProcessor = /* @__PURE__ */ __name((config2, settings, addItem, clearItems, loadHistory, refreshStatic, toggleVimEnabled, isProcessing, setIsProcessing, isIdleRef, setGeminiMdFileCount, actions, extensionsUpdateState, isConfigInitialized, logger6, setSessionName) => {
  const { stats: sessionStats, startNewSession } = useSessionStats();
  const [commands, setCommands] = (0, import_react157.useState)([]);
  const [reloadTrigger, setReloadTrigger] = (0, import_react157.useState)(0);
  const reloadCommands = (0, import_react157.useCallback)(() => {
    setReloadTrigger((v2) => v2 + 1);
  }, []);
  const [shellConfirmationRequest, setShellConfirmationRequest] = (0, import_react157.useState)(null);
  const [confirmationRequest, setConfirmationRequest] = (0, import_react157.useState)(null);
  const [sessionShellAllowlist, setSessionShellAllowlist] = (0, import_react157.useState)(
    /* @__PURE__ */ new Set()
  );
  const gitService = (0, import_react157.useMemo)(() => {
    if (!config2?.getProjectRoot()) {
      return;
    }
    return new GitService(config2.getProjectRoot(), config2.storage);
  }, [config2]);
  const [pendingItem, setPendingItem] = (0, import_react157.useState)(
    null
  );
  const [btwItem, setBtwItem] = (0, import_react157.useState)(null);
  const btwAbortControllerRef = (0, import_react157.useRef)(null);
  const cancelBtw = (0, import_react157.useCallback)(() => {
    btwAbortControllerRef.current?.abort();
    btwAbortControllerRef.current = null;
    setBtwItem(null);
  }, []);
  const abortControllerRef = (0, import_react157.useRef)(null);
  const cancelSlashCommand = (0, import_react157.useCallback)(() => {
    cancelBtw();
    if (!abortControllerRef.current) {
      return;
    }
    abortControllerRef.current.abort();
    addItem(
      {
        type: "info" /* INFO */,
        text: "Command cancelled."
      },
      Date.now()
    );
    setPendingItem(null);
    setIsProcessing(false);
  }, [addItem, setIsProcessing, cancelBtw]);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        cancelSlashCommand();
      }
    },
    { isActive: isProcessing }
  );
  const pendingHistoryItems = (0, import_react157.useMemo)(() => {
    const items = [];
    if (pendingItem != null) {
      items.push(pendingItem);
    }
    return items;
  }, [pendingItem]);
  const addMessage = (0, import_react157.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_react157.useMemo)(
    () => ({
      services: {
        config: config2,
        settings,
        git: gitService,
        logger: logger6
      },
      ui: {
        addItem,
        clear: /* @__PURE__ */ __name(() => {
          cancelBtw();
          clearItems();
          clearScreen2();
          refreshStatic();
          setSessionName?.(null);
        }, "clear"),
        loadHistory,
        setDebugMessage: actions.setDebugMessage,
        pendingItem,
        setPendingItem,
        btwItem,
        setBtwItem,
        cancelBtw,
        btwAbortControllerRef,
        isIdleRef,
        toggleVimEnabled,
        setGeminiMdFileCount,
        reloadCommands,
        setSessionName: setSessionName ?? (() => {
        }),
        extensionsUpdateState,
        dispatchExtensionStateUpdate: actions.dispatchExtensionStateUpdate,
        addConfirmUpdateExtensionRequest: actions.addConfirmUpdateExtensionRequest
      },
      session: {
        stats: sessionStats,
        sessionShellAllowlist,
        startNewSession
      },
      executionMode: "interactive"
    }),
    [
      config2,
      settings,
      gitService,
      logger6,
      loadHistory,
      addItem,
      clearItems,
      refreshStatic,
      sessionStats,
      startNewSession,
      actions,
      pendingItem,
      setPendingItem,
      btwItem,
      setBtwItem,
      cancelBtw,
      toggleVimEnabled,
      sessionShellAllowlist,
      setGeminiMdFileCount,
      reloadCommands,
      setSessionName,
      extensionsUpdateState,
      isIdleRef
    ]
  );
  (0, import_react157.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_react157.useEffect)(() => {
    const controller = new AbortController();
    const load = /* @__PURE__ */ __name(async () => {
      try {
        const loaders = [
          new McpPromptLoader(config2),
          new BuiltinCommandLoader(config2),
          new BundledSkillLoader(config2),
          new SkillCommandLoader(config2),
          new FileCommandLoader(config2)
        ];
        const disabled = config2?.getDisabledSlashCommands() ?? [];
        const commandService = await CommandService.create(
          loaders,
          controller.signal,
          disabled.length > 0 ? new Set(disabled) : void 0
        );
        if (config2) {
          config2.setModelInvocableCommandsProvider(
            () => commandService.getModelInvocableCommands().map((cmd) => ({
              name: cmd.name,
              description: typeof cmd.description === "string" ? cmd.description : cmd.description
            }))
          );
          config2.setModelInvocableCommandsExecutor(
            async (name4, args2 = "") => {
              const commands2 = commandService.getModelInvocableCommands();
              const cmd = commands2.find((c4) => c4.name === name4);
              if (!cmd?.action) return null;
              const minimalContext = {
                executionMode: "non_interactive",
                invocation: {
                  raw: args2 ? `/${name4} ${args2}` : `/${name4}`,
                  name: name4,
                  args: args2
                },
                services: { config: config2, settings, git: gitService, logger: null }
              };
              const result = await cmd.action(minimalContext, args2);
              if (!result || result.type !== "submit_prompt") return null;
              const content = result.content;
              if (typeof content === "string") return content;
              if (Array.isArray(content)) {
                return content.map(
                  (p2) => typeof p2 === "string" ? p2 : p2.text ?? ""
                ).join("");
              }
              return null;
            }
          );
        }
        if (!controller.signal.aborted) {
          setCommands(commandService.getCommandsForMode("interactive"));
        }
      } catch (error40) {
        debugLogger155.error("Failed to load slash commands:", error40);
      }
    }, "load");
    load();
    return () => {
      controller.abort();
    };
  }, [config2, reloadTrigger, isConfigInitialized, settings, gitService]);
  const handleSlashCommand2 = (0, import_react157.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();
      if (!isBtwCommand(trimmed2)) {
        addItemWithRecording(
          { type: "user" /* USER */, text: trimmed2 },
          userMessageTimestamp
        );
      }
      let hasError = false;
      const {
        commandToExecute,
        args: args2,
        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: args2
              },
              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((resolve42) => {
              abortController.signal.addEventListener(
                "abort",
                () => resolve42(void 0),
                { once: true }
              );
            });
            const result = await Promise.race([
              commandToExecute.action(fullCommandContext, args2),
              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 "arena_start":
                      actions.openArenaDialog?.("start");
                      return { type: "handled" };
                    case "arena_select":
                      actions.openArenaDialog?.("select");
                      return { type: "handled" };
                    case "arena_stop":
                      actions.openArenaDialog?.("stop");
                      return { type: "handled" };
                    case "arena_status":
                      actions.openArenaDialog?.("status");
                      return { type: "handled" };
                    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 "memory":
                      actions.openMemoryDialog();
                      return { type: "handled" };
                    case "model":
                      actions.openModelDialog();
                      return { type: "handled" };
                    case "fast-model":
                      actions.openModelDialog({ fastModelMode: true });
                      return { type: "handled" };
                    case "manage-models":
                      actions.openManageModelsDialog();
                      return { type: "handled" };
                    case "trust":
                      actions.openTrustDialog();
                      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 "mcp":
                      actions.openMcpDialog();
                      return { type: "handled" };
                    case "hooks":
                      actions.openHooksDialog();
                      return { type: "handled" };
                    case "approval-mode":
                      actions.openApprovalModeDialog();
                      return { type: "handled" };
                    case "resume":
                      if (result.sessionId) {
                        actions.handleResume(result.sessionId);
                      } else {
                        actions.openResumeDialog(result.matchedSessions);
                      }
                      return { type: "handled" };
                    case "delete":
                      actions.openDeleteDialog();
                      return { type: "handled" };
                    case "extensions_manage":
                      actions.openExtensionsManagerDialog();
                      return { type: "handled" };
                    case "rewind":
                      actions.openRewindSelector();
                      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);
                  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,
                    onComplete: result.onComplete
                  };
                case "confirm_shell_commands": {
                  const { outcome, approvedCommands } = await new Promise((resolve42) => {
                    setShellConfirmationRequest({
                      commands: result.commandsToConfirm,
                      onConfirm: /* @__PURE__ */ __name((resolvedOutcome, resolvedApprovedCommands) => {
                        setShellConfirmationRequest(null);
                        resolve42({
                          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((resolve42) => {
                    setConfirmationRequest({
                      prompt: result.prompt,
                      onConfirm: /* @__PURE__ */ __name((resolvedConfirmed) => {
                        setConfirmationRequest(null);
                        resolve42({ 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) {
            debugLogger155.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,
    btwItem,
    setBtwItem,
    cancelBtw,
    commandContext,
    shellConfirmationRequest,
    confirmationRequest
  };
}, "useSlashCommandProcessor");

// packages/cli/src/ui/hooks/useDoublePress.ts
init_esbuild_shims();
var import_react158 = __toESM(require_react(), 1);
var DOUBLE_PRESS_TIMEOUT_MS = 800;
function useDoublePress(onDoublePress, onPending) {
  const timeoutRef = (0, import_react158.useRef)(null);
  (0, import_react158.useEffect)(
    () => () => {
      if (timeoutRef.current !== null) {
        clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }
    },
    []
  );
  return (0, import_react158.useCallback)(() => {
    if (timeoutRef.current !== null) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
      onPending?.(false);
      onDoublePress();
    } else {
      onPending?.(true);
      timeoutRef.current = setTimeout(() => {
        timeoutRef.current = null;
        onPending?.(false);
      }, DOUBLE_PRESS_TIMEOUT_MS);
    }
  }, [onDoublePress, onPending]);
}
__name(useDoublePress, "useDoublePress");

// packages/cli/src/ui/AppContainer.tsx
import * as fs138 from "node:fs";
import { basename as basename32 } 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/AppContainer.tsx
init_stdioHelpers();

// packages/cli/src/ui/hooks/useLogger.ts
init_esbuild_shims();
var import_react159 = __toESM(require_react(), 1);
init_dist4();
var useLogger = /* @__PURE__ */ __name((storage, sessionId) => {
  const [logger6, setLogger] = (0, import_react159.useState)(null);
  (0, import_react159.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_react164 = __toESM(require_react(), 1);
init_dist4();
init_types22();

// packages/cli/src/ui/hooks/shellCommandProcessor.ts
init_esbuild_shims();
init_types22();
var import_react160 = __toESM(require_react(), 1);
init_dist4();
import crypto17 from "node:crypto";
import path134 from "node:path";
import os48 from "node:os";
import fs129 from "node:fs";
var OUTPUT_UPDATE_INTERVAL_MS2 = 1e3;
var MAX_OUTPUT_LENGTH3 = 1e4;
var debugLogger156 = createDebugLogger("SHELL_COMMAND_PROCESSOR");
function addShellCommandToGeminiHistory(geminiClient, rawQuery, resultText) {
  const modelContent = resultText.length > MAX_OUTPUT_LENGTH3 ? resultText.substring(0, MAX_OUTPUT_LENGTH3) + "\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_react160.useState)(null);
  const handleShellCommand = (0, import_react160.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 = os48.platform() === "win32";
      const targetDir = config2.getTargetDir();
      let commandToExecute = rawQuery;
      let pwdFilePath;
      if (!isWindows9) {
        let command2 = rawQuery.trim();
        const pwdFileName = `shell_pwd_${crypto17.randomBytes(6).toString("hex")}.tmp`;
        pwdFilePath = path134.join(os48.tmpdir(), pwdFileName);
        if (!command2.endsWith(";") && !command2.endsWith("&")) {
          command2 += ";";
        }
        commandToExecute = `{ ${command2} }; __code=$?; pwd > "${pwdFilePath}"; exit $__code`;
      }
      const executeCommand = /* @__PURE__ */ __name(async (resolve42) => {
        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],
          isUserInitiated: true
        });
        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
          );
          debugLogger156.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 && fs129.existsSync(pwdFilePath)) {
              const finalPwd = fs129.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],
                isUserInitiated: true
              },
              userMessageTimestamp
            );
            addShellCommandToGeminiHistory(
              geminiClient,
              rawQuery,
              finalOutput
            );
          }).catch((err2) => {
            setPendingHistoryItem(null);
            const errorMessage = err2 instanceof Error ? err2.message : String(err2);
            addItemToHistory(
              {
                type: "error",
                text: `An unexpected error occurred: ${errorMessage}`
              },
              userMessageTimestamp
            );
          }).finally(() => {
            abortSignal.removeEventListener("abort", abortHandler);
            if (pwdFilePath && fs129.existsSync(pwdFilePath)) {
              fs129.unlinkSync(pwdFilePath);
            }
            setActiveShellPtyId(null);
            setShellInputFocused(false);
            resolve42();
          });
        } catch (err2) {
          setPendingHistoryItem(null);
          const errorMessage = err2 instanceof Error ? err2.message : String(err2);
          addItemToHistory(
            {
              type: "error",
              text: `An unexpected error occurred: ${errorMessage}`
            },
            userMessageTimestamp
          );
          if (pwdFilePath && fs129.existsSync(pwdFilePath)) {
            fs129.unlinkSync(pwdFilePath);
          }
          setActiveShellPtyId(null);
          setShellInputFocused(false);
          resolve42();
        }
      }, "executeCommand");
      const execPromise = new Promise((resolve42) => {
        executeCommand(resolve42);
      });
      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_react161 = __toESM(require_react(), 1);
var useStateAndRef = /* @__PURE__ */ __name((initialValue) => {
  const [state, setState] = import_react161.default.useState(initialValue);
  const ref = import_react161.default.useRef(initialValue);
  const setStateInternal = import_react161.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();
init_dist4();
var import_react162 = __toESM(require_react(), 1);
init_types22();
import * as path135 from "node:path";
var debugLogger157 = createDebugLogger("REACT_TOOL_SCHEDULER");
function useReactToolScheduler(onComplete, config2, getPreferredEditor, onEditorClose) {
  const [toolCallsForDisplay, setToolCallsForDisplay] = (0, import_react162.useState)([]);
  const outputUpdateHandler = (0, import_react162.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_react162.useCallback)(
    async (completedToolCalls) => {
      await onComplete(completedToolCalls);
    },
    [onComplete]
  );
  const toolCallsUpdateHandler = (0, import_react162.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_react162.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_react162.useCallback)(
    (request4, signal) => {
      void scheduler.schedule(request4, signal);
    },
    [scheduler]
  );
  const markToolsAsSubmitted = (0, import_react162.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;
      debugLogger157.warn(`Unknown core status encountered: ${exhaustiveCheck}`);
      return "Error" /* Error */;
    }
  }
}
__name(mapCoreStatusToDisplayStatus, "mapCoreStatusToDisplayStatus");
function detectMemoryOp(toolName, args2, projectRoot) {
  const WRITE_TOOLS2 = /* @__PURE__ */ new Set(["write_file", "edit"]);
  const READ_TOOLS2 = /* @__PURE__ */ new Set(["read_file"]);
  const filePath = args2?.["file_path"];
  if (!filePath) return void 0;
  const resolved = path135.resolve(filePath);
  if (!isAutoMemPath(resolved, projectRoot)) return void 0;
  if (WRITE_TOOLS2.has(toolName)) return "write";
  if (READ_TOOLS2.has(toolName)) return "read";
  return void 0;
}
__name(detectMemoryOp, "detectMemoryOp");
function mapToDisplay(toolOrTools, projectRoot) {
  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,
        isMemoryOp: projectRoot && trackedCall.status !== "error" ? detectMemoryOp(
          trackedCall.request.name,
          trackedCall.request.args,
          projectRoot
        ) : void 0
      };
      switch (trackedCall.status) {
        case "success":
          return {
            ...baseDisplayProperties,
            status: mapCoreStatusToDisplayStatus(trackedCall.status),
            resultDisplay: trackedCall.response.resultDisplay,
            confirmationDetails: void 0
          };
        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,
            executionStartTime: trackedCall.executionStartTime
          };
        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,
    memoryWriteCount: toolDisplays.filter((t5) => t5.isMemoryOp === "write").length || void 0,
    memoryReadCount: toolDisplays.filter((t5) => t5.isMemoryOp === "read").length || void 0
  };
}
__name(mapToDisplay, "mapToDisplay");

// packages/cli/src/ui/hooks/useGeminiStream.ts
import { promises as fs130 } from "node:fs";
import path136 from "node:path";
init_i18n();

// packages/cli/src/dualOutput/DualOutputContext.tsx
init_esbuild_shims();
var import_react163 = __toESM(require_react(), 1);
var DualOutputContext = (0, import_react163.createContext)(null);
function useDualOutput() {
  return (0, import_react163.useContext)(DualOutputContext);
}
__name(useDualOutput, "useDualOutput");

// packages/cli/src/ui/hooks/useGeminiStream.ts
var debugLogger158 = createDebugLogger("GEMINI_STREAM");
function extractLastAssistantText(history) {
  for (let i4 = history.length - 1; i4 >= 0; i4--) {
    const item = history[i4];
    if ((item.type === "gemini" || item.type === "gemini_content") && typeof item.text === "string" && item.text.trim().length > 0) {
      return item.text;
    }
  }
  return void 0;
}
__name(extractLastAssistantText, "extractLastAssistantText");
function extractToolResultText(parts2) {
  if (!parts2) return "";
  const list3 = Array.isArray(parts2) ? parts2 : [parts2];
  const chunks = [];
  for (const part of list3) {
    if ("functionResponse" in part && part.functionResponse) {
      const response = part.functionResponse.response;
      if (response !== void 0) chunks.push(response);
    } else if ("text" in part && typeof part.text === "string") {
      chunks.push(part.text);
    }
  }
  if (chunks.length === 0) return "";
  if (chunks.length === 1) return chunks[0];
  return chunks;
}
__name(extractToolResultText, "extractToolResultText");
function classifyApiError(error40) {
  const status = error40.status;
  const message = error40.message?.toLowerCase() ?? "";
  if (status === 429 || message.includes("rate limit")) {
    return "rate_limit";
  }
  if (status === 401 || message.includes("unauthorized")) {
    return "authentication_failed";
  }
  if (status === 402 || status === 403 || message.includes("billing") || message.includes("quota")) {
    return "billing_error";
  }
  if (status === 400 || message.includes("invalid")) {
    return "invalid_request";
  }
  if (status !== void 0 && status >= 500) {
    return "server_error";
  }
  if (message.includes("max_tokens") || message.includes("token limit")) {
    return "max_output_tokens";
  }
  return "unknown";
}
__name(classifyApiError, "classifyApiError");
function checkImageFormatsSupport(parts2) {
  const unsupportedMimeTypes = [];
  let hasImages = false;
  if (typeof parts2 === "string") {
    return {
      hasImages: false,
      hasUnsupportedFormats: false,
      unsupportedMimeTypes: []
    };
  }
  const partsArray = Array.isArray(parts2) ? parts2 : [parts2];
  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"]);
var STREAM_UPDATE_THROTTLE_MS = 60;
function showCitations(settings) {
  const enabled2 = settings?.merged?.ui?.showCitations;
  if (enabled2 !== void 0) {
    return enabled2;
  }
  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, midTurnDrainRef) => {
  const [initError, setInitError] = (0, import_react164.useState)(null);
  const abortControllerRef = (0, import_react164.useRef)(null);
  const flushBufferedStreamEventsRef = (0, import_react164.useRef)(/* @__PURE__ */ new Set());
  const turnCancelledRef = (0, import_react164.useRef)(false);
  const isSubmittingQueryRef = (0, import_react164.useRef)(false);
  const lastPromptRef = (0, import_react164.useRef)(null);
  const lastPromptErroredRef = (0, import_react164.useRef)(false);
  const dualOutput = useDualOutput();
  const [isResponding, setIsResponding] = (0, import_react164.useState)(false);
  const [thought, setThought] = (0, import_react164.useState)(null);
  const historyRef = (0, import_react164.useRef)(history);
  (0, import_react164.useLayoutEffect)(() => {
    historyRef.current = history;
  }, [history]);
  const summaryAbortRefsRef = (0, import_react164.useRef)(/* @__PURE__ */ new Set());
  const [pendingHistoryItem, pendingHistoryItemRef, setPendingHistoryItem] = useStateAndRef(null);
  const [
    pendingRetryErrorItem,
    pendingRetryErrorItemRef,
    setPendingRetryErrorItem
  ] = useStateAndRef(null);
  const [
    pendingRetryCountdownItem,
    pendingRetryCountdownItemRef,
    setPendingRetryCountdownItem
  ] = useStateAndRef(null);
  const retryCountdownTimerRef = (0, import_react164.useRef)(
    null
  );
  const processedMemoryToolsRef = (0, import_react164.useRef)(/* @__PURE__ */ new Set());
  const submitPromptOnCompleteRef = (0, import_react164.useRef)(null);
  const modelOverrideRef = (0, import_react164.useRef)(void 0);
  const streamingResponseLengthRef = (0, import_react164.useRef)(0);
  const [isReceivingContent, setIsReceivingContent] = (0, import_react164.useState)(false);
  const {
    startNewPrompt,
    getPromptCount,
    stats: sessionStates
  } = useSessionStats();
  const storage = config2.storage;
  const logger6 = useLogger(storage, sessionStates.sessionId);
  const gitService = (0, import_react164.useMemo)(() => {
    if (!config2.getProjectRoot()) {
      return;
    }
    return new GitService(config2.getProjectRoot(), storage);
  }, [config2, storage]);
  const [toolCalls, scheduleToolCalls, markToolsAsSubmitted] = useReactToolScheduler(
    async (completedToolCallsFromScheduler) => {
      if (completedToolCallsFromScheduler.length > 0) {
        const projectRoot = config2.getProjectRoot();
        const toolGroupDisplay = mapToDisplay(
          completedToolCallsFromScheduler,
          projectRoot
        );
        addItem(toolGroupDisplay, Date.now());
        await handleCompletedTools(
          completedToolCallsFromScheduler
        );
      }
    },
    config2,
    getPreferredEditor,
    onEditorClose
  );
  const pendingToolCallGroupDisplay = (0, import_react164.useMemo)(
    () => toolCalls.length ? mapToDisplay(toolCalls, config2.getProjectRoot()) : void 0,
    [toolCalls, config2]
  );
  const activeToolPtyId = (0, import_react164.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_react164.useRef)(false);
  const [
    loopDetectionConfirmationRequest,
    setLoopDetectionConfirmationRequest
  ] = (0, import_react164.useState)(null);
  const stopRetryCountdownTimer = (0, import_react164.useCallback)(() => {
    if (retryCountdownTimerRef.current) {
      clearInterval(retryCountdownTimerRef.current);
      retryCountdownTimerRef.current = null;
    }
  }, []);
  const clearRetryCountdown = (0, import_react164.useCallback)(() => {
    stopRetryCountdownTimer();
    skipRetryDelayRef.current = null;
    setPendingRetryErrorItem(null);
    setPendingRetryCountdownItem(null);
  }, [
    setPendingRetryErrorItem,
    setPendingRetryCountdownItem,
    stopRetryCountdownTimer
  ]);
  const skipRetryDelayRef = (0, import_react164.useRef)(null);
  const startRetryCountdown = (0, import_react164.useCallback)(
    (retryInfo) => {
      stopRetryCountdownTimer();
      skipRetryDelayRef.current = retryInfo.skipDelay;
      const startTime = Date.now();
      const { message, attempt, maxRetries, delayMs } = retryInfo;
      const retryReasonText = message ?? t4("Rate limit exceeded. Please wait and try again.");
      const updateCountdown = /* @__PURE__ */ __name(() => {
        const elapsedMs = Date.now() - startTime;
        const remainingMs = Math.max(0, delayMs - elapsedMs);
        const remainingSec = Math.ceil(remainingMs / 1e3);
        const hintText = `Retrying in ${remainingSec}s\u2026 (attempt ${attempt}/${maxRetries})`;
        setPendingRetryErrorItem({
          type: "error" /* ERROR */,
          text: retryReasonText,
          hint: hintText
        });
        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);
    },
    [
      setPendingRetryErrorItem,
      setPendingRetryCountdownItem,
      stopRetryCountdownTimer
    ]
  );
  (0, import_react164.useEffect)(() => () => stopRetryCountdownTimer(), [stopRetryCountdownTimer]);
  const onExec = (0, import_react164.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_react164.useEffect)(() => {
    if (!activePtyId) {
      setShellInputFocused(false);
    }
  }, [activePtyId, setShellInputFocused]);
  const streamingState = (0, import_react164.useMemo)(() => {
    if (toolCalls.some((tc) => tc.status === "awaiting_approval")) {
      return "waiting_for_confirmation" /* WaitingForConfirmation */;
    }
    if (toolCalls.some((tc) => {
      if (tc.status !== "executing") return false;
      const liveOutput = tc.liveOutput;
      return typeof liveOutput === "object" && liveOutput !== null && "type" in liveOutput && liveOutput.type === "task_execution" && "pendingConfirmation" in liveOutput && liveOutput.pendingConfirmation != null;
    })) {
      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_react164.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_react164.useCallback)(() => {
    if (streamingState !== "responding" /* Responding */) {
      return;
    }
    if (turnCancelledRef.current) {
      return;
    }
    for (const flushBufferedStreamEvents of flushBufferedStreamEventsRef.current) {
      flushBufferedStreamEvents();
    }
    turnCancelledRef.current = true;
    isSubmittingQueryRef.current = false;
    abortControllerRef.current?.abort();
    for (const ac of summaryAbortRefsRef.current) {
      ac.abort();
    }
    summaryAbortRefsRef.current.clear();
    config2.getArenaAgentClient()?.reportCancelled();
    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_react164.useCallback)(
    async (query, userMessageTimestamp, abortSignal, prompt_id, submitType) => {
      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();
        if (submitType === SendMessageType.Notification) {
          onDebugMessage(
            `Received notification (${trimmedQuery.length} chars)`
          );
          return { queryToSend: trimmedQuery, shouldProceed: true };
        }
        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;
              submitPromptOnCompleteRef.current = slashCommandResult.onComplete ?? null;
              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;
        if (submitType !== SendMessageType.Cron) {
          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_react164.useCallback)(
    (eventValue, currentGeminiMessageBuffer, userMessageTimestamp) => {
      if (turnCancelledRef.current) {
        return "";
      }
      streamingResponseLengthRef.current += eventValue.length;
      setIsReceivingContent(true);
      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_react164.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_react164.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_react164.useCallback)(
    (userMessageTimestamp) => {
      if (turnCancelledRef.current) {
        return;
      }
      lastPromptErroredRef.current = false;
      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_react164.useCallback)(
    (eventValue, userMessageTimestamp) => {
      lastPromptErroredRef.current = true;
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      const isShowingAutoRetry = retryCountdownTimerRef.current !== null;
      clearRetryCountdown();
      const formattedErrorText = parseAndFormatApiError(
        eventValue.error,
        config2.getContentGeneratorConfig()?.authType
      );
      if (!isShowingAutoRetry) {
        const retryHint = t4("Press Ctrl+Y to retry");
        setPendingRetryErrorItem({
          type: "error",
          text: formattedErrorText,
          hint: retryHint
        });
      }
      setThought(null);
      const errorType = classifyApiError(eventValue.error);
      config2.getHookSystem()?.fireStopFailureEvent(
        errorType,
        eventValue.error.message,
        formattedErrorText
      ).catch((err2) => {
        debugLogger158.warn(`StopFailure hook failed: ${err2}`);
      });
    },
    [
      addItem,
      pendingHistoryItemRef,
      setPendingHistoryItem,
      setPendingRetryErrorItem,
      config2,
      setThought,
      clearRetryCountdown
    ]
  );
  const handleCitationEvent = (0, import_react164.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_react164.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
        );
      }
      if (retryCountdownTimerRef.current) {
        clearRetryCountdown();
      }
    },
    [addItem, clearRetryCountdown]
  );
  const handleChatCompressionEvent = (0, import_react164.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_react164.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_react164.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_react164.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_react164.useCallback)(() => {
    setLoopDetectionConfirmationRequest({
      onComplete: handleLoopDetectionConfirmation
    });
  }, [handleLoopDetectionConfirmation]);
  const handleUserPromptSubmitBlockedEvent = (0, import_react164.useCallback)(
    (value, userMessageTimestamp) => {
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      addItem(
        {
          type: "user_prompt_submit_blocked",
          reason: value.reason,
          originalPrompt: value.originalPrompt
        },
        userMessageTimestamp
      );
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem]
  );
  const handleStopHookLoopEvent = (0, import_react164.useCallback)(
    (value, userMessageTimestamp) => {
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      addItem(
        {
          type: "stop_hook_loop",
          iterationCount: value.iterationCount,
          reasons: value.reasons,
          stopHookCount: value.stopHookCount
        },
        userMessageTimestamp
      );
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem]
  );
  const processGeminiStreamEvents = (0, import_react164.useCallback)(
    async (stream5, userMessageTimestamp, signal) => {
      let geminiMessageBuffer = "";
      let thoughtBuffer = "";
      const toolCallRequests = [];
      const bufferedEvents = [];
      let flushTimer = null;
      const discardBufferedStreamEvents = /* @__PURE__ */ __name(() => {
        if (flushTimer) {
          clearTimeout(flushTimer);
          flushTimer = null;
        }
        bufferedEvents.length = 0;
      }, "discardBufferedStreamEvents");
      const flushBufferedStreamEvents = /* @__PURE__ */ __name(() => {
        if (flushTimer) {
          clearTimeout(flushTimer);
          flushTimer = null;
        }
        if (bufferedEvents.length === 0) {
          return;
        }
        while (bufferedEvents.length > 0) {
          const nextEvent = bufferedEvents.shift();
          if (nextEvent.kind === "content") {
            let mergedContent = nextEvent.value;
            while (bufferedEvents[0]?.kind === "content") {
              const queuedContent = bufferedEvents.shift();
              if (queuedContent?.kind !== "content") {
                break;
              }
              mergedContent += queuedContent.value;
            }
            geminiMessageBuffer = handleContentEvent(
              mergedContent,
              geminiMessageBuffer,
              userMessageTimestamp
            );
            continue;
          }
          let mergedThought = nextEvent.value;
          while (bufferedEvents[0]?.kind === "thought") {
            const queuedThought = bufferedEvents.shift();
            if (queuedThought?.kind !== "thought") {
              break;
            }
            mergedThought = {
              subject: queuedThought.value.subject || mergedThought.subject,
              description: `${mergedThought.description ?? ""}${queuedThought.value.description ?? ""}`
            };
          }
          thoughtBuffer = handleThoughtEvent(
            mergedThought,
            thoughtBuffer,
            userMessageTimestamp
          );
        }
      }, "flushBufferedStreamEvents");
      const scheduleBufferedStreamFlush = /* @__PURE__ */ __name(() => {
        if (flushTimer) {
          return;
        }
        flushTimer = setTimeout(() => {
          flushBufferedStreamEvents();
        }, STREAM_UPDATE_THROTTLE_MS);
      }, "scheduleBufferedStreamFlush");
      flushBufferedStreamEventsRef.current.add(flushBufferedStreamEvents);
      dualOutput?.startAssistantMessage();
      try {
        for await (const event of stream5) {
          dualOutput?.processEvent(event);
          switch (event.type) {
            case GeminiEventType.Thought:
              if (event.value.subject && !event.value.description) {
                flushBufferedStreamEvents();
                setThought(event.value);
              } else {
                bufferedEvents.push({ kind: "thought", value: event.value });
                scheduleBufferedStreamFlush();
              }
              break;
            case GeminiEventType.Content:
              bufferedEvents.push({ kind: "content", value: event.value });
              scheduleBufferedStreamFlush();
              break;
            case GeminiEventType.ToolCallRequest:
              flushBufferedStreamEvents();
              toolCallRequests.push(event.value);
              try {
                const argsJson = JSON.stringify(event.value.args);
                streamingResponseLengthRef.current += argsJson.length;
              } catch {
              }
              break;
            case GeminiEventType.UserCancelled:
              flushBufferedStreamEvents();
              handleUserCancelledEvent(userMessageTimestamp);
              break;
            case GeminiEventType.Error:
              flushBufferedStreamEvents();
              handleErrorEvent(event.value, userMessageTimestamp);
              break;
            case GeminiEventType.ChatCompressed:
              flushBufferedStreamEvents();
              handleChatCompressionEvent(event.value, userMessageTimestamp);
              break;
            case GeminiEventType.ToolCallConfirmation:
            case GeminiEventType.ToolCallResponse:
              flushBufferedStreamEvents();
              break;
            case GeminiEventType.MaxSessionTurns:
              flushBufferedStreamEvents();
              handleMaxSessionTurnsEvent();
              break;
            case GeminiEventType.SessionTokenLimitExceeded:
              flushBufferedStreamEvents();
              handleSessionTokenLimitExceededEvent(event.value);
              break;
            case GeminiEventType.Finished:
              flushBufferedStreamEvents();
              handleFinishedEvent(
                event,
                userMessageTimestamp
              );
              break;
            case GeminiEventType.Citation:
              flushBufferedStreamEvents();
              handleCitationEvent(event.value, userMessageTimestamp);
              break;
            case GeminiEventType.LoopDetected:
              flushBufferedStreamEvents();
              loopDetectedRef.current = true;
              break;
            case GeminiEventType.Retry:
              if (!event.isContinuation) {
                discardBufferedStreamEvents();
                if (pendingHistoryItemRef.current) {
                  setPendingHistoryItem(null);
                }
                geminiMessageBuffer = "";
                thoughtBuffer = "";
              } else {
                flushBufferedStreamEvents();
              }
              toolCallRequests.length = 0;
              if (event.retryInfo) {
                startRetryCountdown(event.retryInfo);
              } else {
                clearRetryCountdown();
              }
              break;
            case GeminiEventType.HookSystemMessage:
              flushBufferedStreamEvents();
              if (pendingHistoryItemRef.current) {
                addItem(pendingHistoryItemRef.current, userMessageTimestamp);
                setPendingHistoryItem(null);
              }
              addItem(
                {
                  type: "stop_hook_system_message",
                  message: event.value
                },
                userMessageTimestamp
              );
              break;
            case GeminiEventType.UserPromptSubmitBlocked:
              flushBufferedStreamEvents();
              handleUserPromptSubmitBlockedEvent(
                event.value,
                userMessageTimestamp
              );
              break;
            case GeminiEventType.StopHookLoop:
              flushBufferedStreamEvents();
              handleStopHookLoopEvent(event.value, userMessageTimestamp);
              break;
            default: {
              const unreachable = event;
              return unreachable;
            }
          }
        }
      } finally {
        flushBufferedStreamEvents();
        discardBufferedStreamEvents();
        flushBufferedStreamEventsRef.current.delete(flushBufferedStreamEvents);
      }
      dualOutput?.finalizeAssistantMessage();
      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,
      handleUserPromptSubmitBlockedEvent,
      handleStopHookLoopEvent,
      addItem,
      dualOutput
    ]
  );
  const submitQuery = (0, import_react164.useCallback)(
    async (query, submitType = SendMessageType.UserQuery, prompt_id, metadata2) => {
      const allowConcurrentBtwDuringResponse = submitType === SendMessageType.UserQuery && streamingState === "responding" /* Responding */ && typeof query === "string" && isBtwCommand(query);
      if (isSubmittingQueryRef.current && submitType !== SendMessageType.ToolResult && !allowConcurrentBtwDuringResponse) {
        return;
      }
      if ((streamingState === "responding" /* Responding */ || streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */) && submitType !== SendMessageType.ToolResult && !allowConcurrentBtwDuringResponse)
        return;
      isSubmittingQueryRef.current = true;
      const userMessageTimestamp = Date.now();
      if (submitType !== SendMessageType.ToolResult && !allowConcurrentBtwDuringResponse) {
        setModelSwitchedFromQuotaError(false);
        if (submitType !== SendMessageType.Retry) {
          modelOverrideRef.current = void 0;
        }
        if (pendingRetryCountdownItemRef.current || pendingRetryErrorItemRef.current) {
          clearRetryCountdown();
        }
      }
      const abortController = new AbortController();
      const abortSignal = abortController.signal;
      if (!allowConcurrentBtwDuringResponse) {
        abortControllerRef.current = abortController;
        turnCancelledRef.current = false;
      }
      if (!prompt_id) {
        prompt_id = config2.getSessionId() + "########" + getPromptCount();
      }
      return promptIdContext.run(prompt_id, async () => {
        const { queryToSend, shouldProceed } = submitType === SendMessageType.Retry ? { queryToSend: query, shouldProceed: true } : await prepareQueryForGemini(
          query,
          userMessageTimestamp,
          abortSignal,
          prompt_id,
          submitType
        );
        if (!shouldProceed || queryToSend === null) {
          isSubmittingQueryRef.current = false;
          return;
        }
        if (submitType === SendMessageType.UserQuery || submitType === SendMessageType.Cron) {
          const formatCheck = checkImageFormatsSupport(queryToSend);
          if (formatCheck.hasUnsupportedFormats) {
            addItem(
              {
                type: "info" /* INFO */,
                text: getUnsupportedImageFormatWarning()
              },
              userMessageTimestamp
            );
          }
        }
        const finalQueryToSend = queryToSend;
        lastPromptRef.current = finalQueryToSend;
        lastPromptErroredRef.current = false;
        if (submitType === SendMessageType.UserQuery || submitType === SendMessageType.Cron) {
          startNewPrompt();
          if (typeof queryToSend === "string") {
            logUserPrompt(
              config2,
              new UserPromptEvent(
                queryToSend.length,
                prompt_id,
                config2.getContentGeneratorConfig()?.authType,
                queryToSend
              )
            );
          }
          setThought(null);
        }
        if (submitType === SendMessageType.Retry) {
          logUserRetry(config2, new UserRetryEvent(prompt_id));
        }
        setIsResponding(true);
        setInitError(null);
        setIsReceivingContent(false);
        if (submitType !== SendMessageType.ToolResult) {
          streamingResponseLengthRef.current = 0;
        }
        try {
          if (dualOutput && submitType !== SendMessageType.ToolResult) {
            const rawParts = typeof finalQueryToSend === "string" ? [finalQueryToSend] : Array.isArray(finalQueryToSend) ? finalQueryToSend : [finalQueryToSend];
            const userParts = rawParts.map(
              (p2) => typeof p2 === "string" ? { text: p2 } : p2
            );
            dualOutput.emitUserMessage(userParts);
          }
          const stream5 = geminiClient.sendMessageStream(
            finalQueryToSend,
            abortSignal,
            prompt_id,
            {
              type: submitType,
              notificationDisplayText: metadata2?.notificationDisplayText,
              modelOverride: modelOverrideRef.current
            }
          );
          const processingStatus = await processGeminiStreamEvents(
            stream5,
            userMessageTimestamp,
            abortSignal
          );
          if (processingStatus === 1 /* UserCancelled */) {
            isSubmittingQueryRef.current = false;
            return;
          }
          if (pendingHistoryItemRef.current) {
            addItem(pendingHistoryItemRef.current, userMessageTimestamp);
            setPendingHistoryItem(null);
          }
          if (retryCountdownTimerRef.current) {
            clearRetryCountdown();
          }
          if (loopDetectedRef.current) {
            loopDetectedRef.current = false;
            handleLoopDetectedEvent();
          }
          const onComplete = submitPromptOnCompleteRef.current;
          if (onComplete) {
            submitPromptOnCompleteRef.current = null;
            void onComplete();
          }
          if (geminiClient) {
            const memoryTaskPromises = geminiClient.consumePendingMemoryTaskPromises();
            for (const p2 of memoryTaskPromises) {
              void p2.then((count) => {
                if (count > 0) {
                  addItem(
                    {
                      type: "memory_saved",
                      writtenCount: count,
                      verb: "Updated"
                    },
                    Date.now()
                  );
                }
              });
            }
          }
        } catch (error40) {
          if (error40 instanceof UnauthorizedError) {
            onAuthError("Session expired or is unauthorized.");
          } else if (!isNodeError(error40) || error40.name !== "AbortError") {
            lastPromptErroredRef.current = true;
            const retryHint = t4("Press Ctrl+Y to retry");
            setPendingRetryErrorItem({
              type: "error",
              text: parseAndFormatApiError(
                getErrorMessage(error40) || "Unknown error",
                config2.getContentGeneratorConfig()?.authType
              ),
              hint: retryHint
            });
          }
        } finally {
          setIsResponding(false);
          isSubmittingQueryRef.current = false;
        }
      });
    },
    [
      streamingState,
      setModelSwitchedFromQuotaError,
      prepareQueryForGemini,
      processGeminiStreamEvents,
      pendingHistoryItemRef,
      addItem,
      setPendingHistoryItem,
      setInitError,
      geminiClient,
      onAuthError,
      config2,
      startNewPrompt,
      getPromptCount,
      handleLoopDetectedEvent,
      clearRetryCountdown,
      pendingRetryCountdownItemRef,
      pendingRetryErrorItemRef,
      setPendingRetryErrorItem,
      dualOutput
    ]
  );
  const retryLastPrompt = (0, import_react164.useCallback)(async () => {
    if (skipRetryDelayRef.current) {
      skipRetryDelayRef.current();
      skipRetryDelayRef.current = null;
      clearRetryCountdown();
      return;
    }
    if (streamingState === "responding" /* Responding */ || streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */) {
      return;
    }
    const lastPrompt = lastPromptRef.current;
    if (!lastPrompt || !lastPromptErroredRef.current) {
      addItem(
        {
          type: "info" /* INFO */,
          text: t4("No failed request to retry.")
        },
        Date.now()
      );
      return;
    }
    clearRetryCountdown();
    await submitQuery(lastPrompt, SendMessageType.Retry);
  }, [streamingState, addItem, clearRetryCountdown, submitQuery]);
  const handleApprovalModeChange = (0, import_react164.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 (error40) {
              debugLogger158.error(
                `Failed to auto-approve tool call ${call.request.callId}:`,
                error40
              );
            }
          }
        }
      }
    },
    [toolCalls]
  );
  const handleCompletedTools = (0, import_react164.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
          });
          config2.getArenaAgentClient()?.reportCancelled();
        }
        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
      );
      for (const toolCall of geminiTools) {
        if ("modelOverride" in toolCall.response) {
          modelOverrideRef.current = toolCall.response.modelOverride;
        }
      }
      if (dualOutput) {
        for (const toolCall of geminiTools) {
          dualOutput.emitToolResult(toolCall.request, toolCall.response);
        }
      }
      markToolsAsSubmitted(callIdsToMarkAsSubmitted);
      if (config2.getEmitToolUseSummaries()) {
        const successfulTools = geminiTools.filter(
          (tc) => tc.status === "success"
        );
        if (successfulTools.length > 0) {
          const toolInfoForSummary = successfulTools.map((tc) => ({
            name: tc.request.name,
            input: tc.request.args,
            output: extractToolResultText(tc.response.responseParts)
          }));
          const toolUseIds = successfulTools.map((tc) => tc.request.callId);
          const lastAssistantText = extractLastAssistantText(
            historyRef.current
          );
          const summaryAbort = new AbortController();
          summaryAbortRefsRef.current.add(summaryAbort);
          const anchorCallId = toolUseIds[0];
          void generateToolUseSummary({
            config: config2,
            tools: toolInfoForSummary,
            signal: summaryAbort.signal,
            lastAssistantText
          }).then((summary) => {
            summaryAbortRefsRef.current.delete(summaryAbort);
            const cancelled = turnCancelledRef.current || abortControllerRef.current?.signal.aborted || summaryAbort.signal.aborted;
            if (!summary || cancelled) return;
            const currentHistory = historyRef.current;
            const ourIdx = currentHistory.findIndex(
              (h3) => h3.type === "tool_group" && h3.tools.some((t5) => t5.callId === anchorCallId)
            );
            if (ourIdx < 0) return;
            const laterToolGroupExists = currentHistory.slice(ourIdx + 1).some((h3) => h3.type === "tool_group");
            if (laterToolGroupExists) return;
            if (summary && !cancelled) {
              addItem(
                {
                  type: "tool_use_summary",
                  summary,
                  precedingToolUseIds: toolUseIds
                },
                Date.now()
              );
            }
          }).catch(() => {
            summaryAbortRefsRef.current.delete(summaryAbort);
          });
        }
      }
      if (modelSwitchedFromQuotaError) {
        return;
      }
      const drained = turnCancelledRef.current || abortControllerRef.current?.signal.aborted ? [] : midTurnDrainRef?.current?.() ?? [];
      if (drained.length > 0) {
        for (const msg of drained) {
          responsesToSend.push({
            text: `
[User message received during tool execution]: ${msg}`
          });
          addItem({ type: "user" /* USER */, text: msg }, Date.now());
        }
      }
      submitQuery(responsesToSend, SendMessageType.ToolResult, prompt_ids[0]);
    },
    [
      isResponding,
      submitQuery,
      markToolsAsSubmitted,
      geminiClient,
      performMemoryRefresh,
      modelSwitchedFromQuotaError,
      config2,
      midTurnDrainRef,
      addItem,
      dualOutput
    ]
  );
  const pendingHistoryItems = (0, import_react164.useMemo)(
    () => [
      pendingHistoryItem,
      pendingRetryErrorItem,
      pendingRetryCountdownItem,
      pendingToolCallGroupDisplay
    ].filter((i4) => i4 !== void 0 && i4 !== null),
    [
      pendingHistoryItem,
      pendingRetryErrorItem,
      pendingRetryCountdownItem,
      pendingToolCallGroupDisplay
    ]
  );
  (0, import_react164.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 fs130.mkdir(checkpointDir, { recursive: true });
        } catch (error40) {
          if (!isNodeError(error40) || error40.code !== "EEXIST") {
            onDebugMessage(
              `Failed to create checkpoint directory: ${getErrorMessage(error40)}`
            );
            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 (error40) {
              onDebugMessage(
                `Failed to create new snapshot: ${getErrorMessage(error40)}. 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 = path136.basename(filePath);
            const toolCallWithSnapshotFileName = `${timestamp}-${fileName}-${toolName}.json`;
            const clientHistory = await geminiClient?.getHistory();
            const toolCallWithSnapshotFilePath = path136.join(
              checkpointDir,
              toolCallWithSnapshotFileName
            );
            await fs130.writeFile(
              toolCallWithSnapshotFilePath,
              JSON.stringify(
                {
                  history,
                  clientHistory,
                  toolCall: {
                    name: toolCall.request.name,
                    args: toolCall.request.args
                  },
                  commitHash,
                  filePath
                },
                null,
                2
              )
            );
          } catch (error40) {
            onDebugMessage(
              `Failed to create checkpoint for ${filePath}: ${getErrorMessage(
                error40
              )}. This may indicate a problem with Git or file system permissions.`
            );
          }
        }
      }
    }, "saveRestorableToolCalls");
    saveRestorableToolCalls();
  }, [
    toolCalls,
    config2,
    onDebugMessage,
    gitService,
    history,
    geminiClient,
    storage
  ]);
  const notificationQueueRef = (0, import_react164.useRef)([]);
  const [notificationTrigger, setNotificationTrigger] = (0, import_react164.useState)(0);
  (0, import_react164.useEffect)(() => {
    if (!config2.isCronEnabled()) return;
    const scheduler = config2.getCronScheduler();
    scheduler.start((job) => {
      const label = job.prompt.slice(0, 40);
      notificationQueueRef.current.push({
        displayText: `Cron: ${label}`,
        modelText: job.prompt,
        sendMessageType: SendMessageType.Cron
      });
      setNotificationTrigger((n3) => n3 + 1);
    });
    return () => {
      const summary = scheduler.getExitSummary();
      scheduler.stop();
      if (summary) {
        process.stderr.write(summary + "\n");
      }
    };
  }, [config2]);
  (0, import_react164.useEffect)(() => {
    const registry3 = config2.getBackgroundTaskRegistry();
    registry3.setNotificationCallback((displayText, modelText) => {
      notificationQueueRef.current.push({
        displayText,
        modelText,
        sendMessageType: SendMessageType.Notification
      });
      setNotificationTrigger((n3) => n3 + 1);
    });
    return () => {
      registry3.setNotificationCallback(void 0);
    };
  }, [config2]);
  (0, import_react164.useEffect)(() => {
    if (streamingState === "idle" /* Idle */ && notificationQueueRef.current.length > 0) {
      const item = notificationQueueRef.current.shift();
      addItem(
        { type: "notification", text: item.displayText },
        Date.now()
      );
      submitQuery(item.modelText, item.sendMessageType, void 0, {
        notificationDisplayText: item.displayText
      });
    }
  }, [streamingState, submitQuery, notificationTrigger, addItem]);
  return {
    streamingState,
    submitQuery,
    initError,
    pendingHistoryItems,
    thought,
    cancelOngoingRequest,
    retryLastPrompt,
    pendingToolCalls: toolCalls,
    handleApprovalModeChange,
    activePtyId,
    loopDetectionConfirmationRequest,
    streamingResponseLengthRef,
    isReceivingContent
  };
}, "useGeminiStream");

// packages/cli/src/ui/hooks/vim.ts
init_esbuild_shims();
var import_react165 = __toESM(require_react(), 1);
init_dist4();
var DIGIT_MULTIPLIER = 10;
var DEFAULT_COUNT = 1;
var DIGIT_1_TO_9 = /^[1-9]$/;
var debugLogger159 = 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_react165.useReducer)(vimReducer, initialVimState);
  (0, import_react165.useEffect)(() => {
    dispatch({ type: "SET_MODE", mode: vimMode });
  }, [vimMode]);
  const updateMode = (0, import_react165.useCallback)(
    (mode) => {
      setVimMode(mode);
      dispatch({ type: "SET_MODE", mode });
    },
    [setVimMode]
  );
  const getCurrentCount = (0, import_react165.useCallback)(
    () => state.count || DEFAULT_COUNT,
    [state.count]
  );
  const executeCommand = (0, import_react165.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_react165.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_react165.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_react165.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_react165.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_react165.useCallback)(
    (key) => {
      if (!vimEnabled) {
        return false;
      }
      let normalizedKey;
      try {
        normalizedKey = normalizeKey(key);
      } catch (error40) {
        debugLogger159.warn("Malformed key input in vim mode:", key, error40);
        return false;
      }
      if (state.mode === "INSERT") {
        return handleInsertModeInput(normalizedKey);
      }
      if (state.mode === "NORMAL") {
        if (normalizedKey.sequence === "?" && buffer.text.length === 0 && state.pendingOperator === null && state.count === 0) {
          return false;
        }
        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/useAwaySummary.ts
init_esbuild_shims();
var import_react166 = __toESM(require_react(), 1);
init_dist4();
var DEFAULT_AWAY_THRESHOLD_MINUTES = 5;
var MIN_USER_MESSAGES_TO_FIRE = 3;
var MIN_USER_MESSAGES_SINCE_LAST_RECAP = 2;
function shouldFireRecap(history) {
  let userMessageCount = 0;
  let lastRecapIndex = -1;
  for (let i4 = 0; i4 < history.length; i4++) {
    const item = history[i4];
    if (item.type === "user") userMessageCount++;
    if (item.type === "away_recap") lastRecapIndex = i4;
  }
  if (userMessageCount < MIN_USER_MESSAGES_TO_FIRE) return false;
  if (lastRecapIndex === -1) return true;
  let userSinceLast = 0;
  for (let i4 = lastRecapIndex + 1; i4 < history.length; i4++) {
    if (history[i4].type === "user") userSinceLast++;
  }
  return userSinceLast >= MIN_USER_MESSAGES_SINCE_LAST_RECAP;
}
__name(shouldFireRecap, "shouldFireRecap");
function useAwaySummary(options2) {
  const {
    enabled: enabled2,
    config: config2,
    isFocused,
    isIdle,
    addItem,
    history,
    awayThresholdMinutes
  } = options2;
  const blurredAtRef = (0, import_react166.useRef)(null);
  const recapPendingRef = (0, import_react166.useRef)(false);
  const inFlightRef = (0, import_react166.useRef)(null);
  const isIdleRef = (0, import_react166.useRef)(isIdle);
  isIdleRef.current = isIdle;
  const historyRef = (0, import_react166.useRef)(history);
  historyRef.current = history;
  const thresholdMs = (awayThresholdMinutes && awayThresholdMinutes > 0 ? awayThresholdMinutes : DEFAULT_AWAY_THRESHOLD_MINUTES) * 60 * 1e3;
  (0, import_react166.useEffect)(() => {
    if (!enabled2 || !config2) {
      inFlightRef.current?.abort();
      inFlightRef.current = null;
      blurredAtRef.current = null;
      return;
    }
    if (!isFocused) {
      if (blurredAtRef.current === null) {
        blurredAtRef.current = Date.now();
      }
      return;
    }
    const blurredAt = blurredAtRef.current;
    if (blurredAt === null) return;
    if (Date.now() - blurredAt < thresholdMs) {
      blurredAtRef.current = null;
      return;
    }
    if (recapPendingRef.current) return;
    if (!isIdleRef.current) return;
    if (!shouldFireRecap(historyRef.current)) {
      blurredAtRef.current = null;
      return;
    }
    blurredAtRef.current = null;
    recapPendingRef.current = true;
    const controller = new AbortController();
    inFlightRef.current = controller;
    void generateSessionRecap(config2, controller.signal).then((recap) => {
      if (controller.signal.aborted || !recap) return;
      if (!isIdleRef.current) return;
      const item = {
        type: "away_recap",
        text: recap.text
      };
      addItem(item, Date.now());
      try {
        config2.getChatRecordingService?.()?.recordSlashCommand({
          phase: "result",
          rawCommand: "/recap",
          outputHistoryItems: [{ ...item }]
        });
      } catch {
      }
    }).finally(() => {
      if (inFlightRef.current === controller) {
        inFlightRef.current = null;
      }
      recapPendingRef.current = false;
    });
  }, [enabled2, config2, isFocused, isIdle, addItem, thresholdMs]);
  (0, import_react166.useEffect)(
    () => () => {
      inFlightRef.current?.abort();
    },
    []
  );
}
__name(useAwaySummary, "useAwaySummary");

// packages/cli/src/ui/hooks/useBracketedPaste.ts
init_esbuild_shims();
var import_react167 = __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_react167.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();
init_types22();

// packages/cli/src/ui/hooks/usePhraseCycler.ts
init_esbuild_shims();
var import_react168 = __toESM(require_react(), 1);
init_i18n();
var WITTY_LOADING_PHRASES = ["I'm Feeling Lucky"];
var PHRASE_CHANGE_INTERVAL_MS = 15e3;
var usePhraseCycler = /* @__PURE__ */ __name((isActive, isWaiting, customPhrases) => {
  const currentLanguage2 = getCurrentLanguage();
  const loadingPhrases = (0, import_react168.useMemo)(() => {
    if (customPhrases && customPhrases.length > 0) {
      return customPhrases;
    }
    const translatedPhrases = ta("WITTY_LOADING_PHRASES");
    return translatedPhrases.length > 0 ? translatedPhrases : WITTY_LOADING_PHRASES;
  }, [customPhrases, currentLanguage2]);
  const [currentLoadingPhrase, setCurrentLoadingPhrase] = (0, import_react168.useState)(
    loadingPhrases[0]
  );
  const phraseIntervalRef = (0, import_react168.useRef)(null);
  (0, import_react168.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_react169 = __toESM(require_react(), 1);
var useLoadingIndicator = /* @__PURE__ */ __name((streamingState, customWittyPhrases, currentCandidatesTokens) => {
  const [timerResetKey, setTimerResetKey] = (0, import_react169.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_react169.useState)(0);
  const [taskStartTokens, setTaskStartTokens] = (0, import_react169.useState)(0);
  const prevStreamingStateRef = (0, import_react169.useRef)(null);
  (0, import_react169.useEffect)(() => {
    if (prevStreamingStateRef.current === "waiting_for_confirmation" /* WaitingForConfirmation */ && streamingState === "responding" /* Responding */) {
      setTimerResetKey((prevKey) => prevKey + 1);
      setRetainedElapsedTime(0);
      setTaskStartTokens(currentCandidatesTokens ?? 0);
    } else if (streamingState === "idle" /* Idle */ && prevStreamingStateRef.current === "responding" /* Responding */) {
      setTimerResetKey((prevKey) => prevKey + 1);
      setRetainedElapsedTime(0);
      setTaskStartTokens(0);
    } else if (streamingState === "responding" /* Responding */ && prevStreamingStateRef.current !== "responding" /* Responding */) {
      setTaskStartTokens(currentCandidatesTokens ?? 0);
    } else if (streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */) {
      setRetainedElapsedTime(elapsedTimeFromTimer);
    }
    prevStreamingStateRef.current = streamingState;
  }, [streamingState, elapsedTimeFromTimer, currentCandidatesTokens]);
  return {
    elapsedTime: streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ ? retainedElapsedTime : elapsedTimeFromTimer,
    currentLoadingPhrase,
    taskStartTokens
  };
}, "useLoadingIndicator");

// packages/cli/src/ui/hooks/useTerminalProgress.ts
init_esbuild_shims();
var import_react170 = __toESM(require_react(), 1);
init_types22();

// packages/cli/src/utils/osc.ts
init_esbuild_shims();
var ESC4 = "\x1B";
var BEL3 = "\x07";
var ST = ESC4 + "\\";
var OSC_PREFIX = ESC4 + "]";
var SEP3 = ";";
var OSC3 = {
  /** iTerm2 notification / progress */
  ITERM2: 9,
  /** Kitty desktop notification protocol */
  KITTY: 99,
  /** Ghostty / cmux notification */
  GHOSTTY: 777
};
function detectTerminal2() {
  const termProgram = process.env["TERM_PROGRAM"];
  switch (termProgram) {
    case "iTerm.app":
      return "iTerm.app";
    case "kitty":
      return "kitty";
    case "ghostty":
      return "ghostty";
    case "Apple_Terminal":
      return "Apple_Terminal";
    default:
      break;
  }
  if (process.env["TERM"] === "xterm-ghostty") {
    return "ghostty";
  }
  if (process.env["TERM"]?.includes("kitty")) {
    return "kitty";
  }
  if (process.env["KITTY_WINDOW_ID"]) return "kitty";
  return "unknown";
}
__name(detectTerminal2, "detectTerminal");
function sanitizeOscPayload(text) {
  return text.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x80-\x9f]/g, "");
}
__name(sanitizeOscPayload, "sanitizeOscPayload");
function osc(...parts2) {
  const isKitty = detectTerminal2() === "kitty";
  const inScreen = !!process.env["STY"];
  const terminator = isKitty && !inScreen ? ST : BEL3;
  const sanitized = parts2.map(
    (p2) => typeof p2 === "string" ? sanitizeOscPayload(p2) : p2
  );
  return `${OSC_PREFIX}${sanitized.join(SEP3)}${terminator}`;
}
__name(osc, "osc");
function wrapForMultiplexer2(sequence) {
  if (process.env["TMUX"]) {
    const escaped = sequence.replaceAll("\x1B", "\x1B\x1B");
    return `\x1BPtmux;${escaped}\x1B\\`;
  }
  if (process.env["STY"]) {
    return `\x1BP${sequence}\x1B\\`;
  }
  return sequence;
}
__name(wrapForMultiplexer2, "wrapForMultiplexer");
function encodeKittyPayload(text) {
  return Buffer.from(text, "utf8").toString("base64");
}
__name(encodeKittyPayload, "encodeKittyPayload");
function oscITerm2Notify(title, message) {
  const displayString = title ? `${title}:
${message}` : message;
  return osc(OSC3.ITERM2, `

${displayString}`);
}
__name(oscITerm2Notify, "oscITerm2Notify");
function oscKittyNotify(title, message, id) {
  return [
    osc(OSC3.KITTY, `i=${id}:d=0:p=title:e=1`, encodeKittyPayload(title)),
    osc(OSC3.KITTY, `i=${id}:p=body:e=1`, encodeKittyPayload(message)),
    osc(OSC3.KITTY, `i=${id}:d=1:a=focus`, "")
  ];
}
__name(oscKittyNotify, "oscKittyNotify");
function oscGhosttyNotify(title, message) {
  return osc(OSC3.GHOSTTY, "notify", title, message);
}
__name(oscGhosttyNotify, "oscGhosttyNotify");
function generateKittyId() {
  return Math.floor(Math.random() * 2 ** 31);
}
__name(generateKittyId, "generateKittyId");

// packages/cli/src/ui/hooks/useTerminalProgress.ts
var PROGRESS_CLEAR = wrapForMultiplexer2(`${OSC_PREFIX}9;4;0;${BEL3}`);
var PROGRESS_INDETERMINATE = wrapForMultiplexer2(`${OSC_PREFIX}9;4;3;;${BEL3}`);
function isProgressBarSupported() {
  if (!process.stdout?.isTTY) return false;
  const term = detectTerminal2();
  if (term === "iTerm.app") return true;
  if (term === "ghostty") return true;
  if (process.env["ConEmuPID"]) return true;
  if (process.env["WT_SESSION"]) return true;
  return false;
}
__name(isProgressBarSupported, "isProgressBarSupported");
function useTerminalProgress(streamingState, hasToolExecuting) {
  const { stdout: stdout2 } = use_stdout_default();
  const writeProgress = (0, import_react170.useCallback)(
    (seq) => {
      stdout2?.write(seq);
    },
    [stdout2]
  );
  (0, import_react170.useEffect)(() => {
    if (!isProgressBarSupported()) return;
    if (streamingState === "responding" /* Responding */ && hasToolExecuting) {
      writeProgress(PROGRESS_INDETERMINATE);
    } else if (streamingState === "idle" /* Idle */) {
      writeProgress(PROGRESS_CLEAR);
    }
    return () => {
      writeProgress(PROGRESS_CLEAR);
    };
  }, [streamingState, hasToolExecuting, writeProgress]);
  (0, import_react170.useEffect)(() => {
    if (!isProgressBarSupported()) return;
    const clearOnExit = /* @__PURE__ */ __name(() => {
      stdout2?.write(PROGRESS_CLEAR);
    }, "clearOnExit");
    process.on("exit", clearOnExit);
    return () => {
      process.removeListener("exit", clearOnExit);
    };
  }, [stdout2]);
}
__name(useTerminalProgress, "useTerminalProgress");

// packages/cli/src/ui/hooks/useFolderTrust.ts
init_esbuild_shims();
var import_react171 = __toESM(require_react(), 1);
import * as process40 from "node:process";
var useFolderTrust = /* @__PURE__ */ __name((settings, onTrustChange) => {
  const [isTrusted, setIsTrusted] = (0, import_react171.useState)(void 0);
  const [isFolderTrustDialogOpen, setIsFolderTrustDialogOpen] = (0, import_react171.useState)(false);
  const [isRestarting, setIsRestarting] = (0, import_react171.useState)(false);
  const folderTrust = settings.merged.security?.folderTrust?.enabled;
  (0, import_react171.useEffect)(() => {
    const { isTrusted: trusted } = isWorkspaceTrusted(settings.merged);
    setIsTrusted(trusted);
    setIsFolderTrustDialogOpen(trusted === void 0);
    onTrustChange(trusted);
  }, [folderTrust, onTrustChange, settings.merged]);
  const handleFolderTrustSelect = (0, import_react171.useCallback)(
    (choice2) => {
      const trustedFolders = loadTrustedFolders();
      const cwd6 = process40.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(cwd6, 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_react172 = __toESM(require_react(), 1);
init_dist4();

// packages/cli/src/services/command-migration-tool.ts
init_esbuild_shims();
init_esm13();
init_dist4();
init_i18n();
import { promises as fs131 } from "node:fs";
import path137 from "node:path";
async function detectTomlCommands(commandDir) {
  try {
    await fs131.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 = path137.join(commandDir, relativeFile);
    try {
      const tomlContent = await fs131.readFile(tomlPath, "utf-8");
      const markdownContent = convertTomlToMarkdown(tomlContent);
      const markdownPath = tomlPath.replace(/\.toml$/, ".md");
      try {
        await fs131.access(markdownPath);
        throw new Error(
          t4("Markdown file already exists: {{filename}}", {
            filename: path137.basename(markdownPath)
          })
        );
      } catch (error40) {
        if (error40.code !== "ENOENT") {
          throw error40;
        }
      }
      await fs131.writeFile(markdownPath, markdownContent, "utf-8");
      if (createBackup) {
        const backupPath = `${tomlPath}.backup`;
        await fs131.rename(tomlPath, backupPath);
      } else if (deleteOriginal) {
        await fs131.unlink(tomlPath);
      }
      result.convertedFiles.push(relativeFile);
    } catch (error40) {
      result.success = false;
      result.failedFiles.push({
        file: relativeFile,
        error: error40 instanceof Error ? error40.message : String(error40)
      });
    }
  }
  return result;
}
__name(migrateTomlCommands, "migrateTomlCommands");

// packages/cli/src/ui/hooks/useCommandMigration.ts
function useCommandMigration(settings, storage) {
  const [showMigrationNudge, setShowMigrationNudge] = (0, import_react172.useState)(false);
  const [tomlFiles, setTomlFiles] = (0, import_react172.useState)([]);
  (0, import_react172.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 process49 from "node:process";
import { spawn as spawn11 } from "node:child_process";
import { fileURLToPath as fileURLToPath17 } from "node:url";
import path145 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 path141 from "node:path";
import os51 from "node:os";

// node_modules/xdg-basedir/index.js
init_esbuild_shims();
import os49 from "os";
import path138 from "path";
var homeDirectory = os49.homedir();
var { env: env4 } = process;
var xdgData = env4.XDG_DATA_HOME || (homeDirectory ? path138.join(homeDirectory, ".local", "share") : void 0);
var xdgConfig = env4.XDG_CONFIG_HOME || (homeDirectory ? path138.join(homeDirectory, ".config") : void 0);
var xdgState = env4.XDG_STATE_HOME || (homeDirectory ? path138.join(homeDirectory, ".local", "state") : void 0);
var xdgCache = env4.XDG_CACHE_HOME || (homeDirectory ? path138.join(homeDirectory, ".cache") : void 0);
var xdgRuntime = env4.XDG_RUNTIME_DIR || void 0;
var xdgDataDirectories = (env4.XDG_DATA_DIRS || "/usr/local/share/:/usr/share/").split(":");
if (xdgData) {
  xdgDataDirectories.unshift(xdgData);
}
var xdgConfigDirectories = (env4.XDG_CONFIG_DIRS || "/etc/xdg").split(":");
if (xdgConfig) {
  xdgConfigDirectories.unshift(xdgConfig);
}

// node_modules/atomically/dist/index.js
init_esbuild_shims();
import path140 from "node:path";

// node_modules/stubborn-fs/dist/index.js
init_esbuild_shims();
import fs132 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(...args2) {
    return fn.apply(void 0, args2).catch(onError2);
  }, "attemptified");
}, "attemptifyAsync");
var attemptifySync = /* @__PURE__ */ __name((fn, onError2) => {
  return /* @__PURE__ */ __name(function attemptified(...args2) {
    try {
      return fn.apply(void 0, args2);
    } catch (error40) {
      return onError2(error40);
    }
  }, "attemptified");
}, "attemptifySync");

// node_modules/stubborn-fs/dist/constants.js
init_esbuild_shims();
import process41 from "node:process";
var IS_USER_ROOT = process41.getuid ? !process41.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((error40) => {
    if (!Handlers.isNodeError(error40))
      return false;
    const { code: code2 } = error40;
    if (code2 === "ENOSYS")
      return true;
    if (!IS_USER_ROOT && (code2 === "EINVAL" || code2 === "EPERM"))
      return true;
    return false;
  }, "isChangeErrorOk"),
  isNodeError: /* @__PURE__ */ __name((error40) => {
    return error40 instanceof Error;
  }, "isNodeError"),
  isRetriableError: /* @__PURE__ */ __name((error40) => {
    if (!Handlers.isNodeError(error40))
      return false;
    const { code: code2 } = error40;
    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((error40) => {
    if (!Handlers.isNodeError(error40))
      throw error40;
    if (Handlers.isChangeErrorOk(error40))
      return;
    throw error40;
  }, "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((resolve42) => {
        const cleanup = /* @__PURE__ */ __name(() => this.remove(resolver), "cleanup");
        const resolver = /* @__PURE__ */ __name(() => resolve42(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(...args2) {
      return retryify_queue_default.schedule().then((cleanup) => {
        const onResolve = /* @__PURE__ */ __name((result) => {
          cleanup();
          return result;
        }, "onResolve");
        const onReject = /* @__PURE__ */ __name((error40) => {
          cleanup();
          if (Date.now() >= timestamp)
            throw error40;
          if (isRetriableError(error40)) {
            const delay5 = Math.round(100 * Math.random());
            const delayPromise = new Promise((resolve42) => setTimeout(resolve42, delay5));
            return delayPromise.then(() => attempt.apply(void 0, args2));
          }
          throw error40;
        }, "onReject");
        return fn.apply(void 0, args2).then(onResolve, onReject);
      });
    }, "attempt");
  }, "retrified");
}, "retryifyAsync");
var retryifySync = /* @__PURE__ */ __name((fn, isRetriableError) => {
  return /* @__PURE__ */ __name(function retrified(timestamp) {
    return /* @__PURE__ */ __name(function attempt(...args2) {
      try {
        return fn.apply(void 0, args2);
      } catch (error40) {
        if (Date.now() > timestamp)
          throw error40;
        if (isRetriableError(error40))
          return attempt.apply(void 0, args2);
        throw error40;
      }
    }, "attempt");
  }, "retrified");
}, "retryifySync");

// node_modules/stubborn-fs/dist/index.js
var FS = {
  attempt: {
    /* ASYNC */
    chmod: attemptifyAsync(promisify11(fs132.chmod), handlers_default.onChangeError),
    chown: attemptifyAsync(promisify11(fs132.chown), handlers_default.onChangeError),
    close: attemptifyAsync(promisify11(fs132.close), NOOP2),
    fsync: attemptifyAsync(promisify11(fs132.fsync), NOOP2),
    mkdir: attemptifyAsync(promisify11(fs132.mkdir), NOOP2),
    realpath: attemptifyAsync(promisify11(fs132.realpath), NOOP2),
    stat: attemptifyAsync(promisify11(fs132.stat), NOOP2),
    unlink: attemptifyAsync(promisify11(fs132.unlink), NOOP2),
    /* SYNC */
    chmodSync: attemptifySync(fs132.chmodSync, handlers_default.onChangeError),
    chownSync: attemptifySync(fs132.chownSync, handlers_default.onChangeError),
    closeSync: attemptifySync(fs132.closeSync, NOOP2),
    existsSync: attemptifySync(fs132.existsSync, NOOP2),
    fsyncSync: attemptifySync(fs132.fsync, NOOP2),
    mkdirSync: attemptifySync(fs132.mkdirSync, NOOP2),
    realpathSync: attemptifySync(fs132.realpathSync, NOOP2),
    statSync: attemptifySync(fs132.statSync, NOOP2),
    unlinkSync: attemptifySync(fs132.unlinkSync, NOOP2)
  },
  retry: {
    /* ASYNC */
    close: retryifyAsync(promisify11(fs132.close), handlers_default.isRetriableError),
    fsync: retryifyAsync(promisify11(fs132.fsync), handlers_default.isRetriableError),
    open: retryifyAsync(promisify11(fs132.open), handlers_default.isRetriableError),
    readFile: retryifyAsync(promisify11(fs132.readFile), handlers_default.isRetriableError),
    rename: retryifyAsync(promisify11(fs132.rename), handlers_default.isRetriableError),
    stat: retryifyAsync(promisify11(fs132.stat), handlers_default.isRetriableError),
    write: retryifyAsync(promisify11(fs132.write), handlers_default.isRetriableError),
    writeFile: retryifyAsync(promisify11(fs132.writeFile), handlers_default.isRetriableError),
    /* SYNC */
    closeSync: retryifySync(fs132.closeSync, handlers_default.isRetriableError),
    fsyncSync: retryifySync(fs132.fsyncSync, handlers_default.isRetriableError),
    openSync: retryifySync(fs132.openSync, handlers_default.isRetriableError),
    readFileSync: retryifySync(fs132.readFileSync, handlers_default.isRetriableError),
    renameSync: retryifySync(fs132.renameSync, handlers_default.isRetriableError),
    statSync: retryifySync(fs132.statSync, handlers_default.isRetriableError),
    writeSync: retryifySync(fs132.writeSync, handlers_default.isRetriableError),
    writeFileSync: retryifySync(fs132.writeFileSync, handlers_default.isRetriableError)
  }
};
var dist_default7 = FS;

// node_modules/atomically/dist/constants.js
init_esbuild_shims();
import os50 from "node:os";
import process42 from "node:process";
var DEFAULT_ENCODING2 = "utf8";
var DEFAULT_FILE_MODE = 438;
var DEFAULT_FOLDER_MODE = 511;
var DEFAULT_WRITE_OPTIONS = {};
var DEFAULT_USER_UID = os50.userInfo().uid;
var DEFAULT_USER_GID = os50.userInfo().gid;
var DEFAULT_TIMEOUT_SYNC = 1e3;
var IS_POSIX = !!process42.getuid;
var IS_USER_ROOT2 = process42.getuid ? !process42.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 isString2 = /* @__PURE__ */ __name((value) => {
  return typeof value === "string";
}, "isString");
var isUndefined2 = /* @__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 path139 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 process44 from "node:process";

// node_modules/when-exit/dist/node/constants.js
init_esbuild_shims();
import process43 from "node:process";
var IS_LINUX = process43.platform === "linux";
var IS_WINDOWS = process43.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")) {
          process44.kill(process44.pid, "SIGTERM");
        } else {
          process44.kill(process44.pid, signal);
        }
      }
    };
    this.hook = () => {
      process44.once("exit", () => this.exit());
      for (const signal of signals_default) {
        try {
          process44.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_default3 = 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 basename34 = path139.basename(filePath);
    if (basename34.length <= LIMIT_BASENAME_LENGTH)
      return filePath;
    const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename34);
    if (!truncable)
      return filePath;
    const truncationLength = basename34.length - LIMIT_BASENAME_LENGTH;
    return `${filePath.slice(0, -basename34.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`;
  }, "truncate")
};
node_default3(Temp.purgeSyncAll);
var temp_default = Temp;

// node_modules/atomically/dist/index.js
function writeFileSync25(filePath, data, options2 = DEFAULT_WRITE_OPTIONS) {
  if (isString2(options2))
    return writeFileSync25(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 && isUndefined2(options2.chown);
    const useStatMode = isUndefined2(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 = path140.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 (isString2(data)) {
      dist_default7.retry.writeSync(timeout2)(fd, data, 0, options2.encoding || DEFAULT_ENCODING2);
    } else if (!isUndefined2(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 (error40) {
      if (!isException(error40))
        throw error40;
      if (error40.code !== "ENAMETOOLONG")
        throw error40;
      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(writeFileSync25, "writeFileSync");

// node_modules/dot-prop/index.js
init_esbuild_shims();
var isObject3 = /* @__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(path150) {
  const parts2 = [];
  let currentSegment = "";
  let currentPart = "start";
  let isIgnoring = false;
  for (const character of path150) {
    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 [];
        }
        parts2.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 [];
          }
          parts2.push(currentSegment);
          currentSegment = "";
        }
        currentPart = "index";
        break;
      }
      case "]": {
        if (currentPart === "index") {
          parts2.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 [];
      }
      parts2.push(currentSegment);
      break;
    }
    case "index": {
      throw new Error("Index was not closed");
    }
    case "start": {
      parts2.push("");
      break;
    }
  }
  return parts2;
}
__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, path150, value) {
  if (!isObject3(object3) || typeof path150 !== "string") {
    return value === void 0 ? object3 : value;
  }
  const pathArray = getPathSegments(path150);
  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, path150, value) {
  if (!isObject3(object3) || typeof path150 !== "string") {
    return object3;
  }
  const root = object3;
  const pathArray = getPathSegments(path150);
  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 (!isObject3(object3[key])) {
      object3[key] = typeof pathArray[index + 1] === "number" ? [] : {};
    }
    object3 = object3[key];
  }
  return root;
}
__name(setProperty, "setProperty");
function deleteProperty(object3, path150) {
  if (!isObject3(object3) || typeof path150 !== "string") {
    return false;
  }
  const pathArray = getPathSegments(path150);
  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 (!isObject3(object3)) {
      return false;
    }
  }
}
__name(deleteProperty, "deleteProperty");
function hasProperty(object3, path150) {
  if (!isObject3(object3) || typeof path150 !== "string") {
    return false;
  }
  const pathArray = getPathSegments(path150);
  if (pathArray.length === 0) {
    return false;
  }
  for (const key of pathArray) {
    if (!isObject3(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 ? path141.join(id, "config.json") : path141.join("configstore", `${id}.json`);
  const configDirectory = xdgConfig ?? import_graceful_fs.default.mkdtempSync(import_graceful_fs.default.realpathSync(os51.tmpdir()) + path141.sep);
  return path141.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, defaults4, options2 = {}) {
    this._path = options2.configPath ?? getConfigDirectory(id, options2.globalConfigPath);
    if (defaults4) {
      this.all = {
        ...defaults4,
        ...this.all
      };
    }
  }
  get all() {
    try {
      return JSON.parse(import_graceful_fs.default.readFileSync(this._path, "utf8"));
    } catch (error40) {
      if (error40.code === "ENOENT") {
        return {};
      }
      if (error40.code === "EACCES") {
        error40.message = `${error40.message}
${permissionError}
`;
      }
      if (error40.name === "SyntaxError") {
        writeFileSync25(this._path, "", writeFileOptions);
        return {};
      }
      throw error40;
    }
  }
  set all(value) {
    try {
      import_graceful_fs.default.mkdirSync(path141.dirname(this._path), mkdirOptions);
      writeFileSync25(this._path, JSON.stringify(value, void 0, "	"), writeFileOptions);
    } catch (error40) {
      if (error40.code === "EACCES") {
        error40.message = `${error40.message}
${permissionError}
`;
      }
      throw error40;
    }
  }
  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 matches2 = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches2) {
          return [0, 0, 0];
        }
        let [colorString] = matches2;
        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 process45 from "node:process";
import os52 from "node:os";
import tty2 from "node:tty";
function hasFlag2(flag, argv = globalThis.Deno ? globalThis.Deno.args : process45.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: env5 } = process45;
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 env5) {
    if (env5.FORCE_COLOR === "true") {
      return 1;
    }
    if (env5.FORCE_COLOR === "false") {
      return 0;
    }
    return env5.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env5.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 env5 && "AGENT_NAME" in env5) {
    return 1;
  }
  if (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min = forceColor || 0;
  if (env5.TERM === "dumb") {
    return min;
  }
  if (process45.platform === "win32") {
    const osRelease = os52.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env5) {
    if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env5)) {
      return 3;
    }
    if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env5) || env5.CI_NAME === "codeship") {
      return 1;
    }
    return min;
  }
  if ("TEAMCITY_VERSION" in env5) {
    return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env5.TEAMCITY_VERSION) ? 1 : 0;
  }
  if (env5.COLORTERM === "truecolor") {
    return 3;
  }
  if (env5.TERM === "xterm-kitty") {
    return 3;
  }
  if ("TERM_PROGRAM" in env5) {
    const version2 = Number.parseInt((env5.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env5.TERM_PROGRAM) {
      case "iTerm.app": {
        return version2 >= 3 ? 3 : 2;
      }
      case "Apple_Terminal": {
        return 2;
      }
    }
  }
  if (/-256(color)?$/i.test(env5.TERM)) {
    return 2;
  }
  if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env5.TERM)) {
    return 1;
  }
  if ("COLORTERM" in env5) {
    return 1;
  }
  return min;
}
__name(_supportsColor2, "_supportsColor");
function createSupportsColor2(stream5, options2 = {}) {
  const level = _supportsColor2(stream5, {
    streamIsTTY: stream5 && stream5.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 chalk10 = /* @__PURE__ */ __name((...strings) => strings.join(" "), "chalk");
  applyOptions2(chalk10, options2);
  Object.setPrototypeOf(chalk10, createChalk2.prototype);
  return chalk10;
}, "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_2) => {
  if (model === "rgb") {
    if (level === "ansi16m") {
      return ansi_styles_default6[type].ansi16m(...arguments_2);
    }
    if (level === "ansi256") {
      return ansi_styles_default6[type].ansi256(ansi_styles_default6.rgbToAnsi256(...arguments_2));
    }
    return ansi_styles_default6[type].ansi(ansi_styles_default6.rgbToAnsi(...arguments_2));
  }
  if (model === "hex") {
    return getModelAnsi2("rgb", level, type, ...ansi_styles_default6.hexToRgb(...arguments_2));
  }
  return ansi_styles_default6[type][model](...arguments_2);
}, "getModelAnsi");
var usedModels2 = ["rgb", "hex", "ansi256"];
for (const model of usedModels2) {
  styles9[model] = {
    get() {
      const { level } = this;
      return function(...arguments_2) {
        const styler = createStyler2(getModelAnsi2(model, levelMapping2[level], "color", ...arguments_2), 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_2) {
        const styler = createStyler2(getModelAnsi2(model, levelMapping2[level], "bgColor", ...arguments_2), 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_2) => applyStyle2(builder, arguments_2.length === 1 ? "" + arguments_2[0] : arguments_2.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 chalk9 = createChalk2();
var chalkStderr2 = createChalk2({ level: stderrColor2 ? stderrColor2.level : 0 });
var source_default2 = chalk9;

// 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 (error40) {
      if (error40 instanceof Error && error40.message === "unsupported BodyInit type") {
        return false;
      }
      throw error40;
    }
  }
  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 stop2 = 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((body2) => {
  if (!body2) {
    return 0;
  }
  if (body2 instanceof FormData) {
    let size = 0;
    for (const [key, value] of body2) {
      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 (body2 instanceof Blob) {
    return body2.size;
  }
  if (body2 instanceof ArrayBuffer) {
    return body2.byteLength;
  }
  if (typeof body2 === "string") {
    return new TextEncoder().encode(body2).length;
  }
  if (body2 instanceof URLSearchParams) {
    return new TextEncoder().encode(body2.toString()).length;
  }
  if ("byteLength" in body2) {
    return body2.byteLength;
  }
  if (typeof body2 === "object" && body2 !== null) {
    try {
      const jsonString = JSON.stringify(body2);
      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 isObject4 = /* @__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 ((!isObject4(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 (isObject4(source2)) {
      for (let [key, value] of Object.entries(source2)) {
        if (isObject4(value) && key in returnValue) {
          value = deepMerge(returnValue[key], value);
        }
        returnValue = { ...returnValue, [key]: value };
      }
      if (isObject4(source2.hooks)) {
        hooks = mergeHooks(hooks, source2.hooks);
        returnValue.hooks = hooks;
      }
      if (isObject4(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, init2, abortController, options2) {
  return new Promise((resolve42, reject) => {
    const timeoutId = setTimeout(() => {
      if (abortController) {
        abortController.abort();
      }
      reject(new TimeoutError(request4));
    }, options2.timeout);
    void options2.fetch(request4, init2).then(resolve42).catch(reject).then(() => {
      clearTimeout(timeoutId);
    });
  });
}
__name(timeout, "timeout");

// node_modules/ky/distribution/utils/delay.js
init_esbuild_shims();
async function delay4(ms, { signal }) {
  return new Promise((resolve42, 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);
      resolve42();
    }, ms);
  });
}
__name(delay4, "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 error40 = new HTTPError(response, ky2.request, ky2._options);
        for (const hook of ky2._options.hooks.beforeError) {
          error40 = await hook(error40);
        }
        throw error40;
      }
      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 url3 = 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(url3, { ...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(error40) {
    this._retryCount++;
    if (this._retryCount > this._options.retry.limit || error40 instanceof TimeoutError) {
      throw error40;
    }
    if (error40 instanceof HTTPError) {
      if (!this._options.retry.statusCodes.includes(error40.response.status)) {
        throw error40;
      }
      const retryAfter = error40.response.headers.get("Retry-After") ?? error40.response.headers.get("RateLimit-Reset") ?? error40.response.headers.get("X-RateLimit-Reset") ?? error40.response.headers.get("X-Rate-Limit-Reset");
      if (retryAfter && this._options.retry.afterStatusCodes.includes(error40.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 (error40.response.status === 413) {
        throw error40;
      }
    }
    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 (error40) {
      const ms = Math.min(this._calculateRetryDelay(error40), maxSafeTimeout);
      if (this._retryCount < 1) {
        throw error40;
      }
      await delay4(ms, { signal: this._options.signal });
      for (const hook of this._options.hooks.beforeRetry) {
        const hookResult = await hook({
          request: this.request,
          options: this._options,
          error: error40,
          retryCount: this._retryCount
        });
        if (hookResult === stop2) {
          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 createInstance2 = /* @__PURE__ */ __name((defaults4) => {
  const ky2 = /* @__PURE__ */ __name((input, options2) => Ky.create(input, validateAndMerge(defaults4, options2)), "ky");
  for (const method of requestMethods) {
    ky2[method] = (input, options2) => Ky.create(input, validateAndMerge(defaults4, options2, { method }));
  }
  ky2.create = (newDefaults) => createInstance2(validateAndMerge(newDefaults));
  ky2.extend = (newDefaults) => {
    if (typeof newDefaults === "function") {
      newDefaults = newDefaults(defaults4 ?? {});
    }
    return createInstance2(validateAndMerge(defaults4, newDefaults));
  };
  ky2.stop = stop2;
  return ky2;
}, "createInstance");
var ky = createInstance2();
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 url3 = result[`${scope}:registry`] || result.config_registry || result.registry;
  return url3.slice(-1) === "/" ? url3 : `${url3}/`;
}
__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 (error40) {
    if (error40?.response?.status === 404) {
      throw new PackageNotFoundError(packageName);
    }
    throw error40;
  }
  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, metadata2] of Object.entries(data.versions)) {
        if (metadata2.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 process46 from "node:process";
var packageJson3 = process46.env.npm_package_json;
var userAgent = process46.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 fs135 from "node:fs";
import path144 from "node:path";
import { fileURLToPath as fileURLToPath16 } from "node:url";

// node_modules/global-directory/index.js
init_esbuild_shims();
var import_ini2 = __toESM(require_ini3(), 1);
import process47 from "node:process";
import path142 from "node:path";
import os53 from "node:os";
import fs134 from "node:fs";
var isWindows8 = process47.platform === "win32";
var readRc = /* @__PURE__ */ __name((filePath) => {
  try {
    return import_ini2.default.parse(fs134.readFileSync(filePath, "utf8")).prefix;
  } catch {
  }
}, "readRc");
var getEnvNpmPrefix = /* @__PURE__ */ __name(() => Object.keys(process47.env).reduce((prefix, name4) => /^npm_config_prefix$/i.test(name4) ? process47.env[name4] : prefix, void 0), "getEnvNpmPrefix");
var getGlobalNpmrc = /* @__PURE__ */ __name(() => {
  if (isWindows8 && process47.env.APPDATA) {
    return path142.join(process47.env.APPDATA, "/npm/etc/npmrc");
  }
  if (process47.execPath.includes("/Cellar/node")) {
    const homebrewPrefix = process47.execPath.slice(0, process47.execPath.indexOf("/Cellar/node"));
    return path142.join(homebrewPrefix, "/lib/node_modules/npm/npmrc");
  }
  if (process47.execPath.endsWith("/bin/node")) {
    const installDir = path142.dirname(path142.dirname(process47.execPath));
    return path142.join(installDir, "/etc/npmrc");
  }
}, "getGlobalNpmrc");
var getDefaultNpmPrefix = /* @__PURE__ */ __name(() => {
  if (isWindows8) {
    const { APPDATA } = process47.env;
    return APPDATA ? path142.join(APPDATA, "npm") : path142.dirname(process47.execPath);
  }
  return path142.dirname(path142.dirname(process47.execPath));
}, "getDefaultNpmPrefix");
var getNpmPrefix = /* @__PURE__ */ __name(() => {
  const envPrefix = getEnvNpmPrefix();
  if (envPrefix) {
    return envPrefix;
  }
  const homePrefix = readRc(path142.join(os53.homedir(), ".npmrc"));
  if (homePrefix) {
    return homePrefix;
  }
  if (process47.env.PREFIX) {
    return process47.env.PREFIX;
  }
  const globalPrefix = readRc(getGlobalNpmrc());
  if (globalPrefix) {
    return globalPrefix;
  }
  return getDefaultNpmPrefix();
}, "getNpmPrefix");
var npmPrefix = path142.resolve(getNpmPrefix());
var getYarnWindowsDirectory = /* @__PURE__ */ __name(() => {
  if (isWindows8 && process47.env.LOCALAPPDATA) {
    const dir = path142.join(process47.env.LOCALAPPDATA, "Yarn");
    if (fs134.existsSync(dir)) {
      return dir;
    }
  }
  return false;
}, "getYarnWindowsDirectory");
var getYarnPrefix = /* @__PURE__ */ __name(() => {
  if (process47.env.PREFIX) {
    return process47.env.PREFIX;
  }
  const windowsPrefix = getYarnWindowsDirectory();
  if (windowsPrefix) {
    return windowsPrefix;
  }
  const configPrefix = path142.join(os53.homedir(), ".config/yarn");
  if (fs134.existsSync(configPrefix)) {
    return configPrefix;
  }
  const homePrefix = path142.join(os53.homedir(), ".yarn-config");
  if (fs134.existsSync(homePrefix)) {
    return homePrefix;
  }
  return npmPrefix;
}, "getYarnPrefix");
var globalDirectory = {};
globalDirectory.npm = {};
globalDirectory.npm.prefix = npmPrefix;
globalDirectory.npm.packages = path142.join(npmPrefix, isWindows8 ? "node_modules" : "lib/node_modules");
globalDirectory.npm.binaries = isWindows8 ? npmPrefix : path142.join(npmPrefix, "bin");
var yarnPrefix = path142.resolve(getYarnPrefix());
globalDirectory.yarn = {};
globalDirectory.yarn.prefix = yarnPrefix;
globalDirectory.yarn.packages = path142.join(yarnPrefix, getYarnWindowsDirectory() ? "Data/global/node_modules" : "global/node_modules");
globalDirectory.yarn.binaries = path142.join(globalDirectory.yarn.packages, ".bin");
var global_directory_default = globalDirectory;

// node_modules/is-path-inside/index.js
init_esbuild_shims();
import path143 from "node:path";
function isPathInside(childPath, parentPath) {
  const relation = path143.relative(parentPath, childPath);
  return Boolean(
    relation && relation !== ".." && !relation.startsWith(`..${path143.sep}`) && relation !== path143.resolve(childPath)
  );
}
__name(isPathInside, "isPathInside");

// node_modules/is-installed-globally/index.js
var __dirname7 = path144.dirname(fileURLToPath16(import.meta.url));
var isInstalledGlobally = (() => {
  try {
    return isPathInside(__dirname7, global_directory_default.yarn.packages) || isPathInside(__dirname7, fs135.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 process48 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 segmenter6 = 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 = stripAnsi2(string4);
  }
  if (string4.length === 0) {
    return 0;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment: character } of segmenter6.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: env6, stdout: stdout2, stderr } = process48;
  if (stdout2?.columns) {
    return stdout2.columns;
  }
  if (stderr?.columns) {
    return stderr.columns;
  }
  if (env6.COLUMNS) {
    return Number.parseInt(env6.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 && process48?.stdout) {
    let newDimensions = [process48.stdout.columns, process48.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) => (...args2) => htmlEscape(replacer(...args2)), "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 = path145.dirname(fileURLToPath17(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 process49.env || process49.env.NODE_ENV === "test" || process49.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));
        process49.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;
    }
    spawn11(process49.execPath, [path145.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 (!process49.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 {
      process49.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);
init_dist4();
var debugLogger160 = 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: name4, version: currentVersion2 } = packageJson4;
    const isNightly = currentVersion2.includes("nightly");
    const createNotifier = /* @__PURE__ */ __name((distTag) => updateNotifier({
      pkg: {
        name: name4,
        version: currentVersion2
      },
      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, currentVersion2)) {
        const message = `A new version of Qwen Code is available! ${currentVersion2} \u2192 ${bestUpdate.latest}`;
        return {
          message,
          update: { ...bestUpdate, current: currentVersion2 }
        };
      }
    } else {
      const updateInfo = await createNotifier("latest").fetchInfo();
      if (updateInfo && import_semver3.default.gt(updateInfo.latest, currentVersion2)) {
        const message = `Qwen Code update available! ${currentVersion2} \u2192 ${updateInfo.latest}`;
        return {
          message,
          update: { ...updateInfo, current: currentVersion2 }
        };
      }
    }
    return null;
  } catch (e4) {
    debugLogger160.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();
init_dist4();
import * as fs136 from "node:fs";
import * as path146 from "node:path";
import * as childProcess2 from "node:child_process";
var debugLogger161 = createDebugLogger("INSTALLATION_INFO");
function getInstallationInfo(projectRoot, isAutoUpdateEnabled) {
  const cliPath = process.argv[1];
  if (!cliPath) {
    return { packageManager: "unknown" /* UNKNOWN */, isGlobal: false };
  }
  try {
    const realPath = fs136.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 (fs136.existsSync(path146.join(projectRoot, "yarn.lock"))) {
        pm = "yarn" /* YARN */;
      } else if (fs136.existsSync(path146.join(projectRoot, "pnpm-lock.yaml"))) {
        pm = "pnpm" /* PNPM */;
      } else if (fs136.existsSync(path146.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 (error40) {
    debugLogger161.error("Failed to detect installation info:", error40);
    return { packageManager: "unknown" /* UNKNOWN */, isGlobal: false };
  }
}
__name(getInstallationInfo, "getInstallationInfo");

// packages/cli/src/utils/updateEventEmitter.ts
init_esbuild_shims();
import { EventEmitter as EventEmitter15 } from "node:events";
var updateEventEmitter = new EventEmitter15();

// packages/cli/src/utils/handleAutoUpdate.ts
init_types22();

// packages/cli/src/utils/spawnWrapper.ts
init_esbuild_shims();
import { spawn as spawn12 } from "node:child_process";
var spawnWrapper = spawn12;

// packages/cli/src/utils/handleAutoUpdate.ts
import os54 from "node:os";
function handleAutoUpdate(info2, settings, projectRoot, spawnFn = spawnWrapper) {
  if (!info2) {
    return;
  }
  const isAutoUpdateEnabled = settings.merged.general?.enableAutoUpdate !== false;
  const installationInfo = getInstallationInfo(
    projectRoot,
    isAutoUpdateEnabled
  );
  let combinedMessage = info2.message;
  if (installationInfo.updateMessage) {
    combinedMessage += `
${installationInfo.updateMessage}`;
  }
  updateEventEmitter.emit("update-received", {
    message: combinedMessage
  });
  if (!installationInfo.updateCommand || !isAutoUpdateEnabled) {
    return;
  }
  const isNightly = info2.update.latest.includes("nightly");
  const updateCommand2 = installationInfo.updateCommand.replace(
    "@latest",
    isNightly ? "@nightly" : `@${info2.update.latest}`
  );
  const isWindows9 = os54.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", (err2) => {
    updateEventEmitter.emit("update-failed", {
      message: `Automatic update failed. Please try updating manually. (error: ${err2.message})`
    });
  });
  return updateProcess;
}
__name(handleAutoUpdate, "handleAutoUpdate");
function setUpdateHandler(addItem, setUpdateInfo, isIdleRef = { current: true }) {
  let successfullyInstalled = false;
  const pendingNotifications = [];
  const addItemOrDefer = /* @__PURE__ */ __name((item) => {
    if (isIdleRef.current) {
      addItem(item, Date.now());
    } else {
      pendingNotifications.push(item);
    }
  }, "addItemOrDefer");
  const handleUpdateRecieved = /* @__PURE__ */ __name((info2) => {
    setUpdateInfo(info2);
    const savedMessage = info2.message;
    setTimeout(() => {
      if (!successfullyInstalled) {
        addItemOrDefer({
          type: "info" /* INFO */,
          text: savedMessage
        });
      }
      setUpdateInfo(null);
    }, 6e4);
  }, "handleUpdateRecieved");
  const handleUpdateFailed = /* @__PURE__ */ __name(() => {
    setUpdateInfo(null);
    addItemOrDefer({
      type: "error" /* ERROR */,
      text: `Automatic update failed. Please try updating manually`
    });
  }, "handleUpdateFailed");
  const handleUpdateSuccess = /* @__PURE__ */ __name(() => {
    successfullyInstalled = true;
    setUpdateInfo(null);
    addItemOrDefer({
      type: "info" /* INFO */,
      text: `Update successful! The new version will be used on your next run.`
    });
  }, "handleUpdateSuccess");
  const handleUpdateInfo = /* @__PURE__ */ __name((data) => {
    addItemOrDefer({
      type: "info" /* INFO */,
      text: data.message
    });
  }, "handleUpdateInfo");
  updateEventEmitter.on("update-received", handleUpdateRecieved);
  updateEventEmitter.on("update-failed", handleUpdateFailed);
  updateEventEmitter.on("update-success", handleUpdateSuccess);
  updateEventEmitter.on("update-info", handleUpdateInfo);
  const cleanup = /* @__PURE__ */ __name(() => {
    updateEventEmitter.off("update-received", handleUpdateRecieved);
    updateEventEmitter.off("update-failed", handleUpdateFailed);
    updateEventEmitter.off("update-success", handleUpdateSuccess);
    updateEventEmitter.off("update-info", handleUpdateInfo);
    pendingNotifications.length = 0;
  }, "cleanup");
  const flush = /* @__PURE__ */ __name(() => {
    while (pendingNotifications.length > 0) {
      const item = pendingNotifications.shift();
      addItem(item, Date.now());
    }
  }, "flush");
  return { cleanup, flush };
}
__name(setUpdateHandler, "setUpdateHandler");

// packages/cli/src/ui/hooks/useMessageQueue.ts
init_esbuild_shims();
var import_react173 = __toESM(require_react(), 1);
function useMessageQueue() {
  const [messageQueue, setMessageQueue] = (0, import_react173.useState)([]);
  const queueRef = (0, import_react173.useRef)([]);
  const addMessage = (0, import_react173.useCallback)((message) => {
    const trimmedMessage = message.trim();
    if (trimmedMessage.length > 0) {
      queueRef.current = [...queueRef.current, trimmedMessage];
      setMessageQueue(queueRef.current);
    }
  }, []);
  const clearQueue = (0, import_react173.useCallback)(() => {
    queueRef.current = [];
    setMessageQueue([]);
  }, []);
  const getQueuedMessagesText = (0, import_react173.useCallback)(() => {
    if (messageQueue.length === 0) return "";
    return messageQueue.join("\n\n");
  }, [messageQueue]);
  const popAllMessages = (0, import_react173.useCallback)(() => {
    const current = queueRef.current;
    if (current.length === 0) return null;
    queueRef.current = [];
    setMessageQueue([]);
    return current.join("\n\n");
  }, []);
  const drainQueue = (0, import_react173.useCallback)(() => {
    const current = queueRef.current;
    if (current.length === 0) return [];
    const drained = current.filter((message) => !isSlashCommand(message));
    if (drained.length === 0) return [];
    const rest = current.filter((message) => isSlashCommand(message));
    queueRef.current = rest;
    setMessageQueue(rest);
    return drained;
  }, []);
  const popNextSegment = (0, import_react173.useCallback)(() => {
    const current = queueRef.current;
    if (current.length === 0) return null;
    const [head, ...rest] = current;
    queueRef.current = rest;
    setMessageQueue(rest);
    return head;
  }, []);
  return {
    messageQueue,
    addMessage,
    clearQueue,
    getQueuedMessagesText,
    popAllMessages,
    drainQueue,
    popNextSegment
  };
}
__name(useMessageQueue, "useMessageQueue");

// packages/cli/src/ui/hooks/useAutoAcceptIndicator.ts
init_esbuild_shims();
init_dist4();
var import_react174 = __toESM(require_react(), 1);
init_types22();
function useAutoAcceptIndicator({
  config: config2,
  addItem,
  onApprovalModeChange,
  shouldBlockTab,
  disabled
}) {
  const currentConfigValue = config2.getApprovalMode();
  const [showAutoAcceptIndicator, setShowAutoAcceptIndicator] = (0, import_react174.useState)(currentConfigValue);
  (0, import_react174.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: !disabled }
  );
  return showAutoAcceptIndicator;
}
__name(useAutoAcceptIndicator, "useAutoAcceptIndicator");

// packages/cli/src/ui/hooks/useGitBranchName.ts
init_esbuild_shims();
var import_react175 = __toESM(require_react(), 1);
init_dist4();
import fs137 from "node:fs";
import fsPromises6 from "node:fs/promises";
import path147 from "node:path";
function useGitBranchName(cwd6) {
  const [branchName, setBranchName] = (0, import_react175.useState)(void 0);
  const fetchBranchName = (0, import_react175.useCallback)(async () => {
    try {
      if (!isCommandAvailable("git").available) {
        return;
      }
      const { stdout: stdout2 } = await execCommand2(
        "git",
        ["rev-parse", "--abbrev-ref", "HEAD"],
        { cwd: cwd6 }
      );
      const branch = stdout2.toString().trim();
      if (branch && branch !== "HEAD") {
        setBranchName(branch);
      } else {
        const { stdout: hashStdout } = await execCommand2(
          "git",
          ["rev-parse", "--short", "HEAD"],
          { cwd: cwd6 }
        );
        setBranchName(hashStdout.toString().trim());
      }
    } catch (_error) {
      setBranchName(void 0);
    }
  }, [cwd6, setBranchName]);
  (0, import_react175.useEffect)(() => {
    fetchBranchName();
    const gitLogsHeadPath = path147.join(cwd6, ".git", "logs", "HEAD");
    let watcher;
    const setupWatcher = /* @__PURE__ */ __name(async () => {
      try {
        await fsPromises6.access(gitLogsHeadPath, fs137.constants.F_OK);
        watcher = fs137.watch(gitLogsHeadPath, (eventType) => {
          if (eventType === "change" || eventType === "rename") {
            fetchBranchName();
          }
        });
      } catch (_watchError) {
      }
    }, "setupWatcher");
    setupWatcher();
    return () => {
      watcher?.close();
    };
  }, [cwd6, fetchBranchName]);
  return branchName;
}
__name(useGitBranchName, "useGitBranchName");

// packages/cli/src/ui/hooks/useExtensionUpdates.ts
init_esbuild_shims();
var import_react176 = __toESM(require_react(), 1);
init_types22();
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_react176.useReducer)(confirmationRequestsReducer, []);
  const addConfirmUpdateExtensionRequest = (0, import_react176.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_react176.useReducer)(
    settingInputRequestsReducer,
    []
  );
  const addSettingInputRequest = (0, import_react176.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_react176.useReducer)(
    pluginChoiceRequestsReducer,
    []
  );
  const addPluginChoiceRequest = (0, import_react176.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, cwd6) => {
  const [extensionsUpdateState, dispatchExtensionStateUpdate] = (0, import_react176.useReducer)(
    extensionUpdatesReducer,
    initialExtensionUpdatesState
  );
  const extensions = extensionManager.getLoadedExtensions();
  (0, import_react176.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_react176.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((error40) => {
          addItem(
            {
              type: "error" /* ERROR */,
              text: getErrorMessage4(error40)
            },
            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, cwd6]);
  const extensionsUpdateStateComputed = (0, import_react176.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/AppContainer.tsx
init_i18n();

// packages/cli/src/ui/hooks/useWelcomeBack.ts
init_esbuild_shims();
var import_react177 = __toESM(require_react(), 1);
init_dist4();
function useWelcomeBack(config2, submitQuery, buffer, settings) {
  const [welcomeBackInfo, setWelcomeBackInfo] = (0, import_react177.useState)(null);
  const [showWelcomeBackDialog, setShowWelcomeBackDialog] = (0, import_react177.useState)(false);
  const [welcomeBackChoice, setWelcomeBackChoice] = (0, import_react177.useState)(null);
  const [shouldFillInput, setShouldFillInput] = (0, import_react177.useState)(false);
  const [inputFillText, setInputFillText] = (0, import_react177.useState)(null);
  const checkWelcomeBack = (0, import_react177.useCallback)(async () => {
    if (settings.ui?.enableWelcomeBack === false) {
      return;
    }
    try {
      const info2 = await getProjectSummaryInfo();
      if (!info2.hasHistory) {
        return;
      }
      const persistedState = await getWelcomeBackState();
      const isRestartSuppressed = persistedState?.lastChoice === "restart" && persistedState.summaryFingerprint === info2.summaryFingerprint;
      if (!isRestartSuppressed) {
        setWelcomeBackInfo(info2);
        setShowWelcomeBackDialog(true);
      }
    } catch (error40) {
      config2.getDebugLogger().debug("Welcome back check failed:", error40);
    }
  }, [config2, settings.ui?.enableWelcomeBack]);
  const handleWelcomeBackSelection = (0, import_react177.useCallback)(
    (choice2) => {
      setWelcomeBackChoice(choice2);
      setShowWelcomeBackDialog(false);
      if (choice2 === "restart" && welcomeBackInfo?.summaryFingerprint) {
        void saveWelcomeBackRestartChoice(
          welcomeBackInfo.summaryFingerprint
        ).catch((error40) => {
          config2.getDebugLogger().debug("Failed to persist welcome back restart choice:", error40);
        });
      }
      if (choice2 === "continue") {
        void clearWelcomeBackState().catch((error40) => {
          config2.getDebugLogger().debug("Failed to clear welcome back state:", error40);
        });
      }
      if (choice2 === "continue" && welcomeBackInfo?.content) {
        const contextMessage = `@.qwen/PROJECT_SUMMARY.md, Based on our previous conversation,Let's continue?`;
        setInputFillText(contextMessage);
        setShouldFillInput(true);
      }
    },
    [config2, welcomeBackInfo]
  );
  const handleWelcomeBackClose = (0, import_react177.useCallback)(() => {
    setWelcomeBackChoice("restart");
    setShowWelcomeBackDialog(false);
  }, []);
  const clearInputFill = (0, import_react177.useCallback)(() => {
    setShouldFillInput(false);
    setInputFillText(null);
  }, []);
  (0, import_react177.useEffect)(() => {
    if (shouldFillInput && inputFillText) {
      buffer.setText(inputFillText);
      clearInputFill();
    }
  }, [shouldFillInput, inputFillText, buffer, clearInputFill]);
  (0, import_react177.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_react178 = __toESM(require_react(), 1);
function useDialogClose(options2) {
  const closeAnyOpenDialog = (0, import_react178.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.isMemoryDialogOpen) {
      options2.closeMemoryDialog();
      return true;
    }
    if (options2.activeArenaDialog !== null) {
      options2.closeArenaDialog();
      return true;
    }
    if (options2.isFolderTrustDialogOpen) {
      return true;
    }
    if (options2.showWelcomeBackDialog) {
      options2.handleWelcomeBackClose();
      return true;
    }
    if (options2.isBackgroundTasksDialogOpen) {
      options2.closeBackgroundTasksDialog();
      return true;
    }
    return false;
  }, [options2]);
  return { closeAnyOpenDialog };
}
__name(useDialogClose, "useDialogClose");

// packages/cli/src/ui/hooks/useInitializationAuthError.ts
init_esbuild_shims();
var import_react179 = __toESM(require_react(), 1);
var useInitializationAuthError = /* @__PURE__ */ __name((authError, onAuthError) => {
  const hasHandled = (0, import_react179.useRef)(false);
  const authErrorRef = (0, import_react179.useRef)(authError);
  const onAuthErrorRef = (0, import_react179.useRef)(onAuthError);
  authErrorRef.current = authError;
  onAuthErrorRef.current = onAuthError;
  (0, import_react179.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_react180 = __toESM(require_react(), 1);
function useSubagentCreateDialog() {
  const [isSubagentCreateDialogOpen, setIsSubagentCreateDialogOpen] = (0, import_react180.useState)(false);
  const openSubagentCreateDialog = (0, import_react180.useCallback)(() => {
    setIsSubagentCreateDialogOpen(true);
  }, []);
  const closeSubagentCreateDialog = (0, import_react180.useCallback)(() => {
    setIsSubagentCreateDialogOpen(false);
  }, []);
  return {
    isSubagentCreateDialogOpen,
    openSubagentCreateDialog,
    closeSubagentCreateDialog
  };
}
__name(useSubagentCreateDialog, "useSubagentCreateDialog");

// packages/cli/src/ui/hooks/useAgentsManagerDialog.ts
init_esbuild_shims();
var import_react181 = __toESM(require_react(), 1);
var useAgentsManagerDialog = /* @__PURE__ */ __name(() => {
  const [isAgentsManagerDialogOpen, setIsAgentsManagerDialogOpen] = (0, import_react181.useState)(false);
  const openAgentsManagerDialog = (0, import_react181.useCallback)(() => {
    setIsAgentsManagerDialogOpen(true);
  }, []);
  const closeAgentsManagerDialog = (0, import_react181.useCallback)(() => {
    setIsAgentsManagerDialogOpen(false);
  }, []);
  return {
    isAgentsManagerDialogOpen,
    openAgentsManagerDialog,
    closeAgentsManagerDialog
  };
}, "useAgentsManagerDialog");

// packages/cli/src/ui/hooks/useExtensionsManagerDialog.ts
init_esbuild_shims();
var import_react182 = __toESM(require_react(), 1);
var useExtensionsManagerDialog = /* @__PURE__ */ __name(() => {
  const [isExtensionsManagerDialogOpen, setIsExtensionsManagerDialogOpen] = (0, import_react182.useState)(false);
  const openExtensionsManagerDialog = (0, import_react182.useCallback)(() => {
    setIsExtensionsManagerDialogOpen(true);
  }, []);
  const closeExtensionsManagerDialog = (0, import_react182.useCallback)(() => {
    setIsExtensionsManagerDialogOpen(false);
  }, []);
  return {
    isExtensionsManagerDialogOpen,
    openExtensionsManagerDialog,
    closeExtensionsManagerDialog
  };
}, "useExtensionsManagerDialog");

// packages/cli/src/ui/hooks/useMcpDialog.ts
init_esbuild_shims();
var import_react183 = __toESM(require_react(), 1);
var useMcpDialog = /* @__PURE__ */ __name(() => {
  const [isMcpDialogOpen, setIsMcpDialogOpen] = (0, import_react183.useState)(false);
  const openMcpDialog = (0, import_react183.useCallback)(() => {
    setIsMcpDialogOpen(true);
  }, []);
  const closeMcpDialog = (0, import_react183.useCallback)(() => {
    setIsMcpDialogOpen(false);
  }, []);
  return {
    isMcpDialogOpen,
    openMcpDialog,
    closeMcpDialog
  };
}, "useMcpDialog");

// packages/cli/src/ui/hooks/useHooksDialog.ts
init_esbuild_shims();
var import_react184 = __toESM(require_react(), 1);
var useHooksDialog = /* @__PURE__ */ __name(() => {
  const [isHooksDialogOpen, setIsHooksDialogOpen] = (0, import_react184.useState)(false);
  const openHooksDialog = (0, import_react184.useCallback)(() => {
    setIsHooksDialogOpen(true);
  }, []);
  const closeHooksDialog = (0, import_react184.useCallback)(() => {
    setIsHooksDialogOpen(false);
  }, []);
  return {
    isHooksDialogOpen,
    openHooksDialog,
    closeHooksDialog
  };
}, "useHooksDialog");

// packages/cli/src/ui/hooks/useMemoryDialog.ts
init_esbuild_shims();
var import_react185 = __toESM(require_react(), 1);
var useMemoryDialog = /* @__PURE__ */ __name(() => {
  const [isMemoryDialogOpen, setIsMemoryDialogOpen] = (0, import_react185.useState)(false);
  const openMemoryDialog = (0, import_react185.useCallback)(() => {
    setIsMemoryDialogOpen(true);
  }, []);
  const closeMemoryDialog = (0, import_react185.useCallback)(() => {
    setIsMemoryDialogOpen(false);
  }, []);
  return {
    isMemoryDialogOpen,
    openMemoryDialog,
    closeMemoryDialog
  };
}, "useMemoryDialog");

// packages/cli/src/ui/hooks/useAttentionNotifications.ts
init_esbuild_shims();
var import_react186 = __toESM(require_react(), 1);
init_types22();
init_dist4();

// packages/cli/src/services/notificationService.ts
init_esbuild_shims();
init_dist4();
var debugLogger162 = createDebugLogger("NOTIFICATION_SERVICE");
var DEFAULT_TITLE = "Qwen Code";
function sendNotification(opts, terminal, enabled2) {
  if (!enabled2) {
    return "disabled";
  }
  if (!process.stdout?.isTTY) {
    return "disabled";
  }
  const title = opts.title ?? DEFAULT_TITLE;
  try {
    const terminalType = detectTerminal2();
    switch (terminalType) {
      case "iTerm.app":
        terminal.notifyITerm2({ ...opts, title });
        return "iterm2";
      case "kitty":
        terminal.notifyKitty({ ...opts, title, id: generateKittyId() });
        return "kitty";
      case "ghostty":
        terminal.notifyGhostty({ ...opts, title });
        return "ghostty";
      case "Apple_Terminal":
      default:
        terminal.notifyBell();
        return "terminal_bell";
    }
  } catch (error40) {
    debugLogger162.warn("Failed to send notification:", error40);
    return "error";
  }
}
__name(sendNotification, "sendNotification");

// packages/cli/src/ui/hooks/useAttentionNotifications.ts
var LONG_TASK_NOTIFICATION_THRESHOLD_SECONDS = 20;
var NOTIFICATION_TITLE = "Qwen Code";
var useAttentionNotifications = /* @__PURE__ */ __name(({
  isFocused,
  streamingState,
  elapsedTime,
  settings,
  config: config2,
  terminal,
  pendingToolCalls
}) => {
  const terminalBellEnabled = settings?.merged?.general?.terminalBell ?? true;
  const awaitingNotificationSentRef = (0, import_react186.useRef)(false);
  const respondingElapsedRef = (0, import_react186.useRef)(0);
  const idleNotificationSentRef = (0, import_react186.useRef)(false);
  const awaitingToolName = (0, import_react186.useMemo)(() => {
    const awaitingTool = pendingToolCalls?.find(
      (tc) => tc.status === "awaiting_approval"
    );
    return awaitingTool?.request.name;
  }, [pendingToolCalls]);
  (0, import_react186.useEffect)(() => {
    if (streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ && !isFocused && !awaitingNotificationSentRef.current && terminalBellEnabled) {
      const message = awaitingToolName ? `Qwen Code needs your permission to use ${awaitingToolName}` : "Qwen Code is waiting for your input";
      sendNotification(
        { message, title: NOTIFICATION_TITLE },
        terminal,
        terminalBellEnabled
      );
      awaitingNotificationSentRef.current = true;
    }
    if (streamingState !== "waiting_for_confirmation" /* WaitingForConfirmation */ || isFocused) {
      awaitingNotificationSentRef.current = false;
    }
  }, [
    isFocused,
    streamingState,
    terminalBellEnabled,
    terminal,
    awaitingToolName
  ]);
  (0, import_react186.useEffect)(() => {
    if (streamingState === "responding" /* Responding */) {
      respondingElapsedRef.current = elapsedTime;
      idleNotificationSentRef.current = false;
      return;
    }
    if (streamingState === "idle" /* Idle */) {
      const wasLongTask = respondingElapsedRef.current >= LONG_TASK_NOTIFICATION_THRESHOLD_SECONDS;
      if (wasLongTask && !isFocused && terminalBellEnabled) {
        sendNotification(
          {
            message: "Qwen Code is waiting for your input",
            title: NOTIFICATION_TITLE
          },
          terminal,
          terminalBellEnabled
        );
      }
      respondingElapsedRef.current = 0;
      if (config2 && !idleNotificationSentRef.current) {
        const messageBus = config2.getMessageBus();
        const hooksEnabled = !config2.getDisableAllHooks();
        if (hooksEnabled && messageBus) {
          fireNotificationHook(
            messageBus,
            "Qwen Code is waiting for your input",
            NotificationType.IdlePrompt,
            "Waiting for input"
          ).catch(() => {
          });
        }
        idleNotificationSentRef.current = true;
      }
      return;
    }
    idleNotificationSentRef.current = false;
  }, [
    streamingState,
    elapsedTime,
    isFocused,
    terminalBellEnabled,
    config2,
    terminal
  ]);
}, "useAttentionNotifications");

// packages/cli/src/ui/hooks/useTerminalNotification.ts
init_esbuild_shims();
function buildTerminalNotification(writeRaw) {
  return {
    notifyITerm2({ message, title }) {
      writeRaw(wrapForMultiplexer2(oscITerm2Notify(title ?? "", message)));
    },
    notifyKitty({ message, title, id }) {
      for (const seq of oscKittyNotify(title, message, id)) {
        writeRaw(wrapForMultiplexer2(seq));
      }
    },
    notifyGhostty({ message, title }) {
      writeRaw(wrapForMultiplexer2(oscGhosttyNotify(title, message)));
    },
    notifyBell() {
      writeRaw(BEL3);
    }
  };
}
__name(buildTerminalNotification, "buildTerminalNotification");

// packages/cli/src/ui/hooks/useContextualTips.ts
init_esbuild_shims();
var import_react187 = __toESM(require_react(), 1);
init_dist4();
init_types22();
init_i18n();
function useContextualTips({
  streamingState,
  lastPromptTokenCount,
  sessionPromptCount,
  config: config2,
  tipHistory,
  addItem,
  hideTips
}) {
  const prevStreamingState = (0, import_react187.useRef)("idle" /* Idle */);
  const hadResponsePhase = (0, import_react187.useRef)(false);
  (0, import_react187.useEffect)(() => {
    if (streamingState === "responding" /* Responding */ || prevStreamingState.current === "responding" /* Responding */ && streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */) {
      hadResponsePhase.current = true;
    }
    const isNowIdle = streamingState === "idle" /* Idle */;
    prevStreamingState.current = streamingState;
    if (!hadResponsePhase.current || !isNowIdle) {
      return;
    }
    hadResponsePhase.current = false;
    if (hideTips || !tipHistory) {
      return;
    }
    const contentGeneratorConfig = config2.getContentGeneratorConfig();
    const contextWindowSize = contentGeneratorConfig?.contextWindowSize ?? DEFAULT_TOKEN_LIMIT;
    const tipContext = {
      lastPromptTokenCount,
      contextWindowSize,
      sessionPromptCount,
      sessionCount: tipHistory.sessionCount,
      platform: process.platform
    };
    const tip = selectTip("post-response", tipContext, tipRegistry, tipHistory);
    if (tip) {
      tipHistory.recordShown(tip.id, sessionPromptCount);
      addItem(
        {
          type: "info" /* INFO */,
          text: `\u{1F4A1} ${t4(tip.content)}`
        },
        Date.now()
      );
    }
  }, [
    streamingState,
    lastPromptTokenCount,
    sessionPromptCount,
    config2,
    tipHistory,
    addItem,
    hideTips
  ]);
}
__name(useContextualTips, "useContextualTips");

// packages/cli/src/remoteInput/RemoteInputContext.tsx
init_esbuild_shims();
var import_react188 = __toESM(require_react(), 1);
var RemoteInputContext = (0, import_react188.createContext)(
  null
);
var useRemoteInput = /* @__PURE__ */ __name(() => (0, import_react188.useContext)(RemoteInputContext), "useRemoteInput");

// packages/cli/src/ui/AppContainer.tsx
var import_jsx_runtime150 = __toESM(require_jsx_runtime(), 1);
var CTRL_EXIT_PROMPT_DURATION_MS = 1e3;
var debugLogger163 = 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");
function useStableStickyTodos(todos) {
  const renderKey2 = getStickyTodosRenderKey(todos);
  const stableTodosRef = (0, import_react189.useRef)(null);
  if (stableTodosRef.current?.renderKey !== renderKey2) {
    stableTodosRef.current = { renderKey: renderKey2, todos };
  }
  return stableTodosRef.current.todos;
}
__name(useStableStickyTodos, "useStableStickyTodos");
function dedupeNewestFirst(messages) {
  const seen = /* @__PURE__ */ new Set();
  const result = [];
  for (const msg of messages) {
    if (!seen.has(msg)) {
      seen.add(msg);
      result.push(msg);
    }
  }
  return result;
}
__name(dedupeNewestFirst, "dedupeNewestFirst");
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_react189.useState)("");
  const [quittingMessages, setQuittingMessages] = (0, import_react189.useState)(null);
  const [themeError, setThemeError] = (0, import_react189.useState)(
    initializationResult.themeError
  );
  const [isProcessing, setIsProcessing] = (0, import_react189.useState)(false);
  const [embeddedShellFocused, setEmbeddedShellFocused] = (0, import_react189.useState)(false);
  const [geminiMdFileCount, setGeminiMdFileCount] = (0, import_react189.useState)(
    initializationResult.geminiMdFileCount
  );
  const [shellModeActive, setShellModeActive] = (0, import_react189.useState)(false);
  const [modelSwitchedFromQuotaError, setModelSwitchedFromQuotaError] = (0, import_react189.useState)(false);
  const [historyRemountKey, setHistoryRemountKey] = (0, import_react189.useState)(0);
  const [updateInfo, setUpdateInfo] = (0, import_react189.useState)(null);
  const [isTrustedFolder, setIsTrustedFolder] = (0, import_react189.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((resolve42, reject) => {
      addPluginChoiceRequest({
        marketplaceName: marketplace.name,
        plugins: marketplace.plugins.map((p2) => ({
          name: p2.name,
          description: p2.description
        })),
        onSelect: /* @__PURE__ */ __name((pluginName) => {
          resolve42(pluginName);
        }, "onSelect"),
        onCancel: /* @__PURE__ */ __name(() => {
          reject(new Error("Plugin selection cancelled"));
        }, "onCancel")
      });
    })
  );
  extensionManager.setRequestSetting(
    (setting) => new Promise((resolve42, reject) => {
      addSettingInputRequest({
        settingName: setting.name,
        settingDescription: setting.description,
        sensitive: setting.sensitive ?? false,
        onSubmit: /* @__PURE__ */ __name((value) => {
          resolve42(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 [isTrustDialogOpen, setTrustDialogOpen] = (0, import_react189.useState)(false);
  const openTrustDialog = (0, import_react189.useCallback)(() => setTrustDialogOpen(true), []);
  const closeTrustDialog = (0, import_react189.useCallback)(() => setTrustDialogOpen(false), []);
  const [isPermissionsDialogOpen, setPermissionsDialogOpen] = (0, import_react189.useState)(false);
  const openPermissionsDialog = (0, import_react189.useCallback)(
    () => setPermissionsDialogOpen(true),
    []
  );
  const closePermissionsDialog = (0, import_react189.useCallback)(
    () => setPermissionsDialogOpen(false),
    []
  );
  const [currentModel, setCurrentModel] = (0, import_react189.useState)(() => config2.getModel());
  const [isConfigInitialized, setConfigInitialized] = (0, import_react189.useState)(false);
  const [userMessages, setUserMessages] = (0, import_react189.useState)([]);
  const { columns: terminalWidth, rows: terminalHeight } = useTerminalSize();
  const { stdin: stdin2, setRawMode } = use_stdin_default();
  const { stdout: stdout2 } = use_stdout_default();
  const writeRaw = (0, import_react189.useCallback)((data) => {
    process50.stdout.write(data);
  }, []);
  const terminal = (0, import_react189.useMemo)(
    () => buildTerminalNotification(writeRaw),
    [writeRaw]
  );
  const { stats: sessionStats, startNewSession } = useSessionStats();
  const logger6 = useLogger(config2.storage, sessionStats.sessionId);
  const branchName = useGitBranchName(config2.getTargetDir());
  const mainControlsRef = (0, import_react189.useRef)(null);
  const originalTitleRef = (0, import_react189.useRef)(
    computeWindowTitle(basename32(config2.getTargetDir()))
  );
  const lastTitleRef = (0, import_react189.useRef)(null);
  const staticExtraHeight = 3;
  (0, import_react189.useEffect)(() => {
    (async () => {
      await config2.initialize();
      setConfigInitialized(true);
      const resumedSessionData = config2.getResumedSessionData();
      if (resumedSessionData) {
        const historyItems = buildResumedHistoryItems(
          resumedSessionData,
          config2
        );
        historyManager.loadHistory(historyItems);
        const title = config2.getSessionService().getSessionTitle(config2.getSessionId());
        if (title) {
          setSessionName(title);
        }
      }
      const sessionStartSource = resumedSessionData ? SessionStartSource.Resume : SessionStartSource.Startup;
      const hookSystem = config2.getHookSystem();
      if (hookSystem) {
        hookSystem.fireSessionStartEvent(
          sessionStartSource,
          config2.getModel() ?? "",
          String(config2.getApprovalMode())
        ).then(() => {
          debugLogger163.debug("SessionStart event completed successfully");
        }).catch((err2) => {
          debugLogger163.warn(`SessionStart hook failed: ${err2}`);
        });
      } else {
        debugLogger163.debug(
          "SessionStart: HookSystem not available, skipping event"
        );
      }
    })();
    registerCleanup(async () => {
      try {
        await config2.getHookSystem()?.fireSessionEndEvent(SessionEndReason.PromptInputExit);
        debugLogger163.debug("SessionEnd event completed successfully!!!");
      } catch (err2) {
        debugLogger163.error(`SessionEnd hook failed: ${err2}`);
      }
    });
    registerCleanup(async () => {
      const ideClient = await IdeClient.getInstance();
      await ideClient.disconnect();
    });
  }, [config2]);
  const isIdleRef = (0, import_react189.useRef)(true);
  const updateHandlerRef = (0, import_react189.useRef)(null);
  (0, import_react189.useEffect)(() => {
    const handler = setUpdateHandler(
      historyManager.addItem,
      setUpdateInfo,
      isIdleRef
    );
    updateHandlerRef.current = handler;
    return () => handler?.cleanup();
  }, [historyManager.addItem]);
  const { inputWidth, suggestionsWidth } = (0, import_react189.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_react189.useCallback)((filePath) => {
    try {
      return fs138.existsSync(filePath) && fs138.statSync(filePath).isFile();
    } catch (_e2) {
      return false;
    }
  }, []);
  const buffer = useTextBuffer({
    initialText: "",
    viewport: { height: 10, width: inputWidth },
    stdin: stdin2,
    setRawMode,
    isValidPath,
    shellModeActive
  });
  (0, import_react189.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
      ];
      setUserMessages(dedupeNewestFirst(combinedMessages).reverse());
    }, "fetchUserMessages");
    fetchUserMessages();
  }, [historyManager.history, logger6]);
  const remountStaticHistory = (0, import_react189.useCallback)(() => {
    setHistoryRemountKey((prev) => prev + 1);
  }, []);
  const refreshStatic = (0, import_react189.useCallback)(() => {
    stdout2.write(base_exports.clearTerminal);
    remountStaticHistory();
  }, [remountStaticHistory, stdout2]);
  (0, import_react189.useEffect)(() => {
    const unsubscribe = config2.onModelChange((model) => {
      setCurrentModel((prev) => {
        if (prev === model) {
          return prev;
        }
        refreshStatic();
        return model;
      });
    });
    return unsubscribe;
  }, [config2, refreshStatic]);
  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,
    externalAuthState,
    qwenAuthState,
    handleAuthSelect,
    handleCodingPlanSubmit,
    handleAlibabaStandardSubmit,
    handleOpenRouterSubmit,
    handleCustomApiKeySubmit,
    openAuthDialog,
    cancelAuthentication
  } = useAuthCommand(settings, config2, historyManager.addItem, refreshStatic);
  useInitializationAuthError(initializationResult.authError, onAuthError);
  (0, import_react189.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 error40 = validateAuthMethod(currentAuthType, config2);
        if (error40) {
          onAuthError(error40);
        }
      }
    }
  }, [
    settings.merged.security?.auth?.enforcedType,
    settings.merged.security?.auth?.useExternal,
    config2,
    onAuthError
  ]);
  const [editorError, setEditorError] = (0, import_react189.useState)(null);
  const {
    isEditorDialogOpen,
    openEditorDialog,
    handleEditorSelect,
    exitEditorDialog
  } = useEditorSettings(settings, setEditorError, historyManager.addItem);
  const { isSettingsDialogOpen, openSettingsDialog, closeSettingsDialog } = useSettingsCommand();
  const { isMemoryDialogOpen, openMemoryDialog, closeMemoryDialog } = useMemoryDialog();
  const {
    isModelDialogOpen,
    isFastModelMode,
    openModelDialog,
    closeModelDialog
  } = useModelCommand();
  const {
    isManageModelsDialogOpen,
    openManageModelsDialog,
    closeManageModelsDialog
  } = useManageModelsCommand();
  const { activeArenaDialog, openArenaDialog, closeArenaDialog } = useArenaCommand();
  const [sessionName, setSessionName] = (0, import_react189.useState)(null);
  const {
    isResumeDialogOpen,
    resumeMatchedSessions,
    openResumeDialog,
    closeResumeDialog,
    handleResume
  } = useResumeCommand({
    config: config2,
    historyManager,
    startNewSession,
    setSessionName,
    remount: refreshStatic
  });
  const {
    isDeleteDialogOpen,
    openDeleteDialog,
    closeDeleteDialog,
    handleDelete
  } = useDeleteCommand({
    config: config2,
    addItem: historyManager.addItem
  });
  const { toggleVimEnabled } = useVimMode();
  const {
    isSubagentCreateDialogOpen,
    openSubagentCreateDialog,
    closeSubagentCreateDialog
  } = useSubagentCreateDialog();
  const {
    isAgentsManagerDialogOpen,
    openAgentsManagerDialog,
    closeAgentsManagerDialog
  } = useAgentsManagerDialog();
  const {
    isExtensionsManagerDialogOpen,
    openExtensionsManagerDialog,
    closeExtensionsManagerDialog
  } = useExtensionsManagerDialog();
  const { isMcpDialogOpen, openMcpDialog, closeMcpDialog } = useMcpDialog();
  const { isHooksDialogOpen, openHooksDialog, closeHooksDialog } = useHooksDialog();
  const openRewindSelectorRef = (0, import_react189.useRef)(() => {
  });
  const slashCommandActions = (0, import_react189.useMemo)(
    () => ({
      openAuthDialog,
      openThemeDialog,
      openEditorDialog,
      openMemoryDialog,
      openSettingsDialog,
      openModelDialog,
      openManageModelsDialog,
      openTrustDialog,
      openArenaDialog,
      openPermissionsDialog,
      openApprovalModeDialog,
      quit: /* @__PURE__ */ __name((messages) => {
        setQuittingMessages(messages);
        setTimeout(async () => {
          await runExitCleanup();
          process50.exit(0);
        }, 100);
      }, "quit"),
      setDebugMessage,
      dispatchExtensionStateUpdate,
      addConfirmUpdateExtensionRequest,
      openSubagentCreateDialog,
      openAgentsManagerDialog,
      openExtensionsManagerDialog,
      openMcpDialog,
      openHooksDialog,
      openResumeDialog,
      openRewindSelector: /* @__PURE__ */ __name(() => openRewindSelectorRef.current(), "openRewindSelector"),
      handleResume,
      openDeleteDialog
    }),
    [
      openAuthDialog,
      openThemeDialog,
      openEditorDialog,
      openMemoryDialog,
      openSettingsDialog,
      openModelDialog,
      openManageModelsDialog,
      openArenaDialog,
      setDebugMessage,
      dispatchExtensionStateUpdate,
      openTrustDialog,
      openPermissionsDialog,
      openApprovalModeDialog,
      addConfirmUpdateExtensionRequest,
      openSubagentCreateDialog,
      openAgentsManagerDialog,
      openExtensionsManagerDialog,
      openMcpDialog,
      openHooksDialog,
      openResumeDialog,
      handleResume,
      openDeleteDialog
    ]
  );
  const {
    handleSlashCommand: handleSlashCommand2,
    slashCommands,
    pendingHistoryItems: pendingSlashCommandHistoryItems,
    btwItem,
    setBtwItem,
    cancelBtw,
    commandContext,
    shellConfirmationRequest,
    confirmationRequest
  } = useSlashCommandProcessor(
    config2,
    settings,
    historyManager.addItem,
    historyManager.clearItems,
    historyManager.loadHistory,
    remountStaticHistory,
    toggleVimEnabled,
    isProcessing,
    setIsProcessing,
    isIdleRef,
    setGeminiMdFileCount,
    slashCommandActions,
    extensionsUpdateStateInternal,
    isConfigInitialized,
    logger6,
    setSessionName
  );
  const onDebugMessage = (0, import_react189.useCallback)(
    (message) => {
      config2.getDebugLogger().debug(message);
    },
    [config2]
  );
  const performMemoryRefresh = (0, import_react189.useCallback)(async () => {
    historyManager.addItem(
      {
        type: "info" /* INFO */,
        text: "Refreshing hierarchical memory (QWEN.md or other context files)..."
      },
      Date.now()
    );
    try {
      const { memoryContent, fileCount, conditionalRules, projectRoot } = await loadHierarchicalGeminiMemory(
        process50.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.getContextRuleExcludes()
      );
      config2.setUserMemory(memoryContent);
      config2.setGeminiMdFileCount(fileCount);
      config2.setConditionalRulesRegistry(
        new ConditionalRulesRegistry(conditionalRules, projectRoot)
      );
      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()
      );
      debugLogger163.debug(
        `[DEBUG] Refreshed memory content in config: ${memoryContent.substring(
          0,
          200
        )}...`
      );
    } catch (error40) {
      const errorMessage = getErrorMessage(error40);
      historyManager.addItem(
        {
          type: "error" /* ERROR */,
          text: `Error refreshing memory: ${errorMessage}`
        },
        Date.now()
      );
      debugLogger163.error("Error refreshing memory:", error40);
    }
  }, [config2, historyManager, settings.merged]);
  const cancelHandlerRef = (0, import_react189.useRef)(() => {
  });
  const midTurnDrainRef = (0, import_react189.useRef)(null);
  const {
    streamingState,
    submitQuery,
    initError,
    pendingHistoryItems: pendingGeminiHistoryItems,
    thought,
    cancelOngoingRequest,
    retryLastPrompt,
    handleApprovalModeChange,
    activePtyId,
    loopDetectionConfirmationRequest,
    pendingToolCalls,
    streamingResponseLengthRef,
    isReceivingContent
  } = 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,
    midTurnDrainRef
  );
  isIdleRef.current = streamingState === "idle" /* Idle */;
  (0, import_react189.useEffect)(() => {
    if (streamingState === "idle" /* Idle */) {
      updateHandlerRef.current?.flush();
    }
  }, [streamingState]);
  const tipsDisabled = !!(settings.merged.ui?.hideTips || config2.getScreenReader());
  const tipHistory = (0, import_react189.useMemo)(
    () => tipsDisabled ? null : getTipHistory(),
    [tipsDisabled]
  );
  useContextualTips({
    streamingState,
    lastPromptTokenCount: sessionStats.lastPromptTokenCount,
    sessionPromptCount: sessionStats.promptCount,
    config: config2,
    tipHistory,
    addItem: historyManager.addItem,
    hideTips: tipsDisabled
  });
  const [hasSuggestionsVisible, setHasSuggestionsVisible] = (0, import_react189.useState)(false);
  const agentViewState = useAgentViewState();
  const { dialogOpen: bgTasksDialogOpen } = useBackgroundTaskViewState();
  const { closeDialog: closeBgTasksDialog } = useBackgroundTaskViewActions();
  const [promptSuggestion, setPromptSuggestion] = (0, import_react189.useState)(null);
  const prevStreamingStateRef = (0, import_react189.useRef)("idle" /* Idle */);
  const speculationRef = (0, import_react189.useRef)(IDLE_SPECULATION);
  const suggestionAbortRef = (0, import_react189.useRef)(null);
  const dismissPromptSuggestion = (0, import_react189.useCallback)(() => {
    setPromptSuggestion(null);
    suggestionAbortRef.current?.abort();
    suggestionAbortRef.current = null;
  }, []);
  const geminiClient = config2.getGeminiClient();
  const showAutoAcceptIndicator = useAutoAcceptIndicator({
    config: config2,
    addItem: historyManager.addItem,
    onApprovalModeChange: handleApprovalModeChange,
    shouldBlockTab: /* @__PURE__ */ __name(() => hasSuggestionsVisible, "shouldBlockTab"),
    disabled: agentViewState.activeView !== "main"
  });
  const {
    messageQueue,
    addMessage,
    clearQueue,
    popAllMessages,
    drainQueue,
    popNextSegment
  } = useMessageQueue();
  midTurnDrainRef.current = drainQueue;
  const remoteInput = useRemoteInput();
  (0, import_react189.useEffect)(() => {
    if (!remoteInput) return;
    remoteInput.setSubmitFn((text) => submitQuery(text));
  }, [remoteInput, submitQuery]);
  (0, import_react189.useEffect)(() => {
    if (!remoteInput) return;
    if (streamingState === "idle" /* Idle */) {
      remoteInput.notifyIdle();
    }
  }, [remoteInput, streamingState]);
  const dualOutput = useDualOutput();
  const confirmRequestMap = (0, import_react189.useRef)(/* @__PURE__ */ new Map());
  const confirmCallIdMap = (0, import_react189.useRef)(/* @__PURE__ */ new Map());
  const confirmEmitted = (0, import_react189.useRef)(/* @__PURE__ */ new Set());
  (0, import_react189.useEffect)(() => {
    if (!dualOutput || !dualOutput.isConnected) return;
    for (const tc of pendingToolCalls) {
      if (tc.status === "awaiting_approval" && !confirmEmitted.current.has(tc.request.callId)) {
        const requestId = crypto.randomUUID();
        confirmRequestMap.current.set(requestId, tc.request.callId);
        confirmCallIdMap.current.set(tc.request.callId, requestId);
        confirmEmitted.current.add(tc.request.callId);
        dualOutput.emitPermissionRequest(
          requestId,
          tc.request.name,
          tc.request.callId,
          tc.request.args
        );
      }
    }
    for (const [callId, requestId] of confirmCallIdMap.current) {
      const tc = pendingToolCalls.find((t5) => t5.request.callId === callId);
      if (tc && tc.status !== "awaiting_approval" && confirmEmitted.current.has(callId)) {
        const allowed = tc.status !== "cancelled" && tc.status !== "error";
        dualOutput.emitControlResponse(requestId, allowed);
        confirmRequestMap.current.delete(requestId);
        confirmCallIdMap.current.delete(callId);
        confirmEmitted.current.delete(callId);
      }
    }
  }, [dualOutput, pendingToolCalls]);
  const pendingToolCallsRef = (0, import_react189.useRef)(pendingToolCalls);
  pendingToolCallsRef.current = pendingToolCalls;
  const dualOutputRef = (0, import_react189.useRef)(dualOutput);
  dualOutputRef.current = dualOutput;
  (0, import_react189.useEffect)(() => {
    if (!remoteInput) return;
    remoteInput.setConfirmationHandler(
      (requestId, allowed) => {
        const callId = confirmRequestMap.current.get(requestId);
        if (!callId) {
          dualOutputRef.current?.emitControlError(
            requestId,
            "unknown request_id (already resolved, cancelled, or never issued)"
          );
          return;
        }
        const tc = pendingToolCallsRef.current.find(
          (t5) => t5.request.callId === callId && t5.status === "awaiting_approval"
        );
        if (!tc) {
          dualOutputRef.current?.emitControlError(
            requestId,
            "tool call is no longer awaiting approval"
          );
          return;
        }
        const waitingTc = tc;
        if (!waitingTc.confirmationDetails?.onConfirm) {
          dualOutputRef.current?.emitControlError(
            requestId,
            "tool call has no onConfirm handler"
          );
          return;
        }
        void waitingTc.confirmationDetails.onConfirm(
          allowed ? ToolConfirmationOutcome.ProceedOnce : ToolConfirmationOutcome.Cancel
        );
      }
    );
    return () => {
      remoteInput.setConfirmationHandler(() => {
      });
    };
  }, [remoteInput]);
  const handleFinalSubmit = (0, import_react189.useCallback)(
    (submittedValue) => {
      if (agentViewState.activeView !== "main") {
        const agent = agentViewState.agents.get(agentViewState.activeView);
        if (agent) {
          agent.interactiveAgent.enqueueMessage(submittedValue.trim());
          return;
        }
      }
      if (streamingState === "responding" /* Responding */ && isBtwCommand(submittedValue)) {
        void submitQuery(submittedValue);
        return;
      }
      if (["exit", "quit", ":q", ":q!", ":wq", ":wq!"].includes(
        submittedValue.trim()
      )) {
        void handleSlashCommand2("/quit");
        return;
      }
      const spec = speculationRef.current;
      if (spec.status !== "idle" && spec.suggestion === submittedValue && spec.status === "completed") {
        acceptSpeculation(spec, geminiClient).then((result) => {
          logSpeculation(
            config2,
            new SpeculationEvent({
              outcome: "accepted",
              turns_used: spec.messages.filter((m3) => m3.role === "model").length,
              files_written: result.filesApplied.length,
              tool_use_count: spec.toolUseCount,
              duration_ms: Date.now() - spec.startTime,
              boundary_type: spec.boundary?.type,
              had_pipelined_suggestion: !!result.nextSuggestion
            })
          );
          {
            const now = Date.now();
            for (let mi = 0; mi < result.messages.length; mi++) {
              const msg = result.messages[mi];
              if (msg.role === "user" && msg.parts) {
                const hasText = msg.parts.some(
                  (p2) => p2.text && !p2.functionResponse
                );
                if (hasText) {
                  const text = msg.parts.map((p2) => p2.text ?? "").filter(Boolean).join("");
                  if (text) {
                    historyManager.addItem(
                      { type: "user", text },
                      now
                    );
                  }
                }
              } else if (msg.role === "model" && msg.parts) {
                const textParts = msg.parts.filter((p2) => p2.text && !p2.functionCall).map((p2) => p2.text).join("");
                const toolCalls = msg.parts.filter((p2) => p2.functionCall);
                if (textParts) {
                  historyManager.addItem(
                    { type: "gemini", text: textParts },
                    now
                  );
                }
                if (toolCalls.length > 0) {
                  const nextMsg = result.messages[mi + 1];
                  const toolResults = nextMsg?.parts?.filter((p2) => p2.functionResponse) ?? [];
                  const tools = toolCalls.map((tc, i4) => {
                    const name4 = tc.functionCall?.name ?? "unknown";
                    const args2 = tc.functionCall?.args ?? {};
                    const resp = toolResults[i4]?.functionResponse?.response;
                    const resultText = typeof resp === "object" && resp ? resp["output"] ?? JSON.stringify(resp) : String(resp ?? "");
                    return {
                      callId: `spec-${name4}-${i4}`,
                      name: name4,
                      description: Object.entries(args2).map(([k2, v2]) => `${k2}: ${String(v2).slice(0, 80)}`).join(", ") || name4,
                      resultDisplay: String(resultText).slice(0, 500),
                      status: "Success" /* Success */,
                      confirmationDetails: void 0
                    };
                  });
                  const toolGroupItem = {
                    type: "tool_group",
                    tools
                  };
                  historyManager.addItem(toolGroupItem, now);
                }
              }
            }
          }
          if (result.nextSuggestion) {
            setPromptSuggestion(result.nextSuggestion);
          }
        }).catch(() => {
          addMessage(submittedValue);
        });
        speculationRef.current = IDLE_SPECULATION;
        return;
      }
      if (spec.status === "running") {
        abortSpeculation(spec).catch(() => {
        });
        speculationRef.current = IDLE_SPECULATION;
      }
      if (streamingState === "idle" /* Idle */ && isSlashCommand(submittedValue)) {
        void submitQuery(submittedValue);
        return;
      }
      addMessage(submittedValue);
    },
    [
      addMessage,
      agentViewState,
      streamingState,
      submitQuery,
      handleSlashCommand2,
      config2,
      geminiClient,
      historyManager
    ]
  );
  const handleArenaModelsSelected = (0, import_react189.useCallback)(
    (models) => {
      const value = models.join(",");
      buffer.setText(`/arena start --models ${value} `);
      closeArenaDialog();
    },
    [buffer, closeArenaDialog]
  );
  const {
    welcomeBackInfo,
    showWelcomeBackDialog,
    welcomeBackChoice,
    handleWelcomeBackSelection,
    handleWelcomeBackClose
  } = useWelcomeBack(config2, handleFinalSubmit, buffer, settings.merged);
  const pendingHistoryItems = (0, import_react189.useMemo)(
    () => [...pendingSlashCommandHistoryItems, ...pendingGeminiHistoryItems],
    [pendingSlashCommandHistoryItems, pendingGeminiHistoryItems]
  );
  const rawStickyTodos = (0, import_react189.useMemo)(
    () => getStickyTodos(historyManager.history, pendingHistoryItems),
    [historyManager.history, pendingHistoryItems]
  );
  const stickyTodos = useStableStickyTodos(rawStickyTodos);
  useTerminalProgress(streamingState, isToolExecuting(pendingHistoryItems));
  cancelHandlerRef.current = (0, import_react189.useCallback)(() => {
    const pendingHistoryItems2 = [
      ...pendingSlashCommandHistoryItems,
      ...pendingGeminiHistoryItems
    ];
    if (isToolExecuting(pendingHistoryItems2)) {
      buffer.setText("");
      clearQueue();
      return;
    }
    const popped = popAllMessages();
    if (popped) {
      const currentText = buffer.text;
      buffer.setText(currentText ? `${popped}
${currentText}` : popped);
    }
  }, [
    buffer,
    popAllMessages,
    clearQueue,
    pendingSlashCommandHistoryItems,
    pendingGeminiHistoryItems
  ]);
  const handleClearScreen = (0, import_react189.useCallback)(() => {
    historyManager.clearItems();
    clearScreen2();
    remountStaticHistory();
  }, [historyManager, remountStaticHistory]);
  const { handleInput: vimHandleInput } = useVim(buffer, handleFinalSubmit);
  const isInputActive = !initError && !isProcessing && (streamingState === "idle" /* Idle */ || streamingState === "responding" /* Responding */);
  const isFocused = useFocus();
  useBracketedPaste();
  useAwaySummary({
    enabled: settings.merged.general?.showSessionRecap ?? false,
    config: config2,
    isFocused,
    isIdle: streamingState === "idle" /* Idle */,
    addItem: historyManager.addItem,
    history: historyManager.history,
    awayThresholdMinutes: settings.merged.general?.sessionRecapAwayThresholdMinutes
  });
  const contextFileNames = (0, import_react189.useMemo)(() => {
    const fromSettings = settings.merged.context?.fileName;
    return fromSettings ? Array.isArray(fromSettings) ? fromSettings : [fromSettings] : getAllGeminiMdFilenames();
  }, [settings.merged.context?.fileName]);
  const initialPrompt = (0, import_react189.useMemo)(() => config2.getQuestion(), [config2]);
  const initialPromptSubmitted = (0, import_react189.useRef)(false);
  (0, import_react189.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 followupSuggestionsEnabled = settings.merged.ui?.enableFollowupSuggestions === true;
  (0, import_react189.useEffect)(() => {
    if (!followupSuggestionsEnabled) {
      suggestionAbortRef.current?.abort();
      setPromptSuggestion(null);
      if (speculationRef.current.status === "running") {
        abortSpeculation(speculationRef.current).catch(() => {
        });
        speculationRef.current = IDLE_SPECULATION;
      }
    }
    if (prevStreamingStateRef.current === "idle" /* Idle */ && streamingState === "responding" /* Responding */) {
      suggestionAbortRef.current?.abort();
      setPromptSuggestion(null);
      if (speculationRef.current.status !== "idle") {
        abortSpeculation(speculationRef.current).catch(() => {
        });
        speculationRef.current = IDLE_SPECULATION;
      }
    }
    if (followupSuggestionsEnabled && config2.isInteractive() && !config2.getSdkMode() && prevStreamingStateRef.current === "responding" /* Responding */ && streamingState === "idle" /* Idle */ && // Check both committed history and pending items for errors
    // (API errors go to pendingGeminiHistoryItems, not historyManager.history)
    historyManager.history[historyManager.history.length - 1]?.type !== "error" && !pendingGeminiHistoryItems.some((item) => item.type === "error") && !shellConfirmationRequest && !confirmationRequest && !loopDetectionConfirmationRequest && !isPermissionsDialogOpen && settingInputRequests.length === 0 && config2.getApprovalMode() !== ApprovalMode.PLAN) {
      const ac = new AbortController();
      suggestionAbortRef.current = ac;
      const fullHistory = geminiClient.getChat().getHistory(true);
      const conversationHistory = fullHistory.length > 40 ? fullHistory.slice(-40) : fullHistory;
      const fastModel = config2.getFastModel();
      generatePromptSuggestion(config2, conversationHistory, ac.signal, {
        enableCacheSharing: settings.merged.ui?.enableCacheSharing === true,
        model: fastModel
      }).then((result) => {
        if (ac.signal.aborted) return;
        if (result.suggestion) {
          setPromptSuggestion(result.suggestion);
          if (settings.merged.ui?.enableSpeculation) {
            startSpeculation(config2, result.suggestion, ac.signal, {
              model: fastModel
            }).then((state) => {
              speculationRef.current = state;
            }).catch(() => {
            });
          }
        } else if (result.filterReason) {
          logPromptSuggestion(
            config2,
            new PromptSuggestionEvent({
              outcome: "suppressed",
              reason: result.filterReason
            })
          );
        }
      }).catch(() => {
      });
    }
    if (prevStreamingStateRef.current !== streamingState) {
      prevStreamingStateRef.current = streamingState;
    }
    return () => {
      suggestionAbortRef.current?.abort();
      if (speculationRef.current.status !== "idle") {
        abortSpeculation(speculationRef.current).catch(() => {
        });
        speculationRef.current = IDLE_SPECULATION;
      }
    };
  }, [
    streamingState,
    followupSuggestionsEnabled,
    shellConfirmationRequest,
    confirmationRequest,
    loopDetectionConfirmationRequest,
    isPermissionsDialogOpen,
    settingInputRequests
  ]);
  (0, import_react189.useEffect)(() => {
    if (!promptSuggestion && speculationRef.current.status !== "idle") {
      abortSpeculation(speculationRef.current).catch(() => {
      });
      speculationRef.current = IDLE_SPECULATION;
    }
  }, [promptSuggestion]);
  const [idePromptAnswered, setIdePromptAnswered] = (0, import_react189.useState)(false);
  const [currentIDE, setCurrentIDE] = (0, import_react189.useState)(null);
  (0, import_react189.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_react189.useState)(false);
  const [compactMode, setCompactMode] = (0, import_react189.useState)(
    settings.merged.ui?.compactMode ?? false
  );
  const [ctrlCPressedOnce, setCtrlCPressedOnce] = (0, import_react189.useState)(false);
  const ctrlCTimerRef = (0, import_react189.useRef)(null);
  const [ctrlDPressedOnce, setCtrlDPressedOnce] = (0, import_react189.useState)(false);
  const ctrlDTimerRef = (0, import_react189.useRef)(null);
  const [escapePressedOnce, setEscapePressedOnce] = (0, import_react189.useState)(false);
  const escapeTimerRef = (0, import_react189.useRef)(null);
  const dialogsVisibleRef = (0, import_react189.useRef)(false);
  const [isRewindSelectorOpen, setIsRewindSelectorOpen] = (0, import_react189.useState)(false);
  const [rewindEscPending, setRewindEscPending] = (0, import_react189.useState)(false);
  const [constrainHeight, setConstrainHeight] = (0, import_react189.useState)(true);
  const [ideContextState, setIdeContextState] = (0, import_react189.useState)();
  const [showEscapePrompt, setShowEscapePrompt] = (0, import_react189.useState)(false);
  const [showIdeRestartPrompt, setShowIdeRestartPrompt] = (0, import_react189.useState)(false);
  const { isFolderTrustDialogOpen, handleFolderTrustSelect, isRestarting } = useFolderTrust(settings, setIsTrustedFolder);
  const {
    needsRestart: ideNeedsRestart,
    restartReason: ideTrustRestartReason
  } = useIdeTrustListener();
  const {
    isFeedbackDialogOpen,
    openFeedbackDialog,
    closeFeedbackDialog,
    temporaryCloseFeedbackDialog,
    submitFeedback
  } = useFeedbackDialog({
    config: config2,
    settings,
    streamingState,
    history: historyManager.history,
    sessionStats
  });
  const dialogsVisible = showWelcomeBackDialog || shouldShowIdePrompt || shouldShowCommandMigrationNudge || isFolderTrustDialogOpen || !!shellConfirmationRequest || !!confirmationRequest || confirmUpdateExtensionRequests.length > 0 || !!codingPlanUpdateRequest || settingInputRequests.length > 0 || pluginChoiceRequests.length > 0 || !!loopDetectionConfirmationRequest || isThemeDialogOpen || isSettingsDialogOpen || isMemoryDialogOpen || isModelDialogOpen || isManageModelsDialogOpen || isTrustDialogOpen || activeArenaDialog !== null || isPermissionsDialogOpen || isAuthDialogOpen || isAuthenticating || isEditorDialogOpen || showIdeRestartPrompt || isSubagentCreateDialogOpen || isAgentsManagerDialogOpen || isMcpDialogOpen || isHooksDialogOpen || isApprovalModeDialogOpen || isResumeDialogOpen || isDeleteDialogOpen || isExtensionsManagerDialogOpen || isRewindSelectorOpen || bgTasksDialogOpen;
  dialogsVisibleRef.current = dialogsVisible;
  const shouldShowStickyTodos = stickyTodos !== null && !dialogsVisible && !isFeedbackDialogOpen && streamingState !== "waiting_for_confirmation" /* WaitingForConfirmation */;
  const stickyTodoWidth = Math.min(mainAreaWidth, 64);
  const stickyTodoMaxVisibleItems = getStickyTodoMaxVisibleItems(terminalHeight);
  const stickyTodosLayoutKey = shouldShowStickyTodos ? getStickyTodosLayoutKey(
    stickyTodos,
    stickyTodoWidth,
    stickyTodoMaxVisibleItems
  ) : "hidden";
  const [controlsHeight, setControlsHeight] = (0, import_react189.useState)(0);
  (0, import_react189.useLayoutEffect)(() => {
    if (!mainControlsRef.current) {
      setControlsHeight(
        (previousHeight) => previousHeight === 0 ? previousHeight : 0
      );
      return;
    }
    const fullFooterMeasurement = measure_element_default(mainControlsRef.current);
    setControlsHeight(
      (previousHeight) => previousHeight === fullFooterMeasurement.height ? previousHeight : fullFooterMeasurement.height
    );
  }, [
    buffer,
    terminalWidth,
    terminalHeight,
    btwItem,
    dialogsVisible,
    stickyTodosLayoutKey
  ]);
  const tabBarHeight = agentViewState.agents.size > 0 ? 1 : 0;
  const availableTerminalHeight = Math.max(
    0,
    terminalHeight - controlsHeight - staticExtraHeight - 2 - tabBarHeight
  );
  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
  });
  (0, import_react189.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_react189.useEffect)(() => {
    if (ideNeedsRestart) {
      setShowIdeRestartPrompt(true);
    }
  }, [ideNeedsRestart]);
  (0, import_react189.useEffect)(() => {
    const unsubscribe = ideContextStore.subscribe(setIdeContextState);
    setIdeContextState(ideContextStore.get());
    return unsubscribe;
  }, []);
  const handleEscapePromptChange = (0, import_react189.useCallback)((showPrompt) => {
    setShowEscapePrompt(showPrompt);
  }, []);
  const openRewindSelector = (0, import_react189.useCallback)(() => {
    if (streamingState !== "idle" /* Idle */) return;
    if (config2.getIdeMode()) return;
    if (dialogsVisibleRef.current) return;
    const hasUserTurns = historyManager.history.some((h3) => h3.type === "user");
    if (!hasUserTurns) return;
    setIsRewindSelectorOpen(true);
  }, [streamingState, config2, historyManager.history]);
  openRewindSelectorRef.current = openRewindSelector;
  const closeRewindSelector = (0, import_react189.useCallback)(() => {
    setIsRewindSelectorOpen(false);
  }, []);
  const handleRewindConfirm = (0, import_react189.useCallback)(
    (userItem) => {
      const geminiClient2 = config2.getGeminiClient();
      if (!geminiClient2) return;
      const originalHistory = historyManager.history;
      const originalLength = originalHistory.length;
      let targetTurnIndex = 0;
      for (const h3 of originalHistory) {
        if (h3.id === userItem.id) break;
        if (isRealUserTurn(h3)) targetTurnIndex++;
      }
      const apiHistory = geminiClient2.getHistory();
      const apiTruncateIndex = computeApiTruncationIndex(
        originalHistory,
        userItem.id,
        apiHistory
      );
      if (apiTruncateIndex < 0) {
        historyManager.addItem(
          {
            type: "error",
            text: "Cannot rewind to a turn that was compressed. Try a more recent turn."
          },
          Date.now()
        );
        setIsRewindSelectorOpen(false);
        return;
      }
      geminiClient2.truncateHistory(apiTruncateIndex);
      const truncatedUi = originalHistory.filter((h3) => h3.id < userItem.id);
      historyManager.loadHistory(truncatedUi);
      refreshStatic();
      if (userItem.type === "user" && userItem.text) {
        buffer.setText(userItem.text);
      }
      historyManager.addItem(
        {
          type: "info",
          text: "Conversation rewound. Edit your prompt and press Enter to continue."
        },
        Date.now()
      );
      config2.getChatRecordingService()?.rewindRecording(targetTurnIndex, {
        truncatedCount: originalLength - truncatedUi.length
      });
      setIsRewindSelectorOpen(false);
    },
    [config2, historyManager, refreshStatic, buffer]
  );
  const handleDoubleEscRewind = useDoublePress(
    openRewindSelector,
    (pending) => setRewindEscPending(pending)
  );
  const handleIdePromptComplete = (0, import_react189.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_react189.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 (error40) {
          historyManager.addItem(
            {
              type: "error" /* ERROR */,
              text: `\u274C Migration failed: ${getErrorMessage(error40)}`
            },
            Date.now()
          );
        }
      }
    },
    [historyManager, setShowCommandMigrationNudge, config2.storage]
  );
  const currentCandidatesTokens = Object.values(
    sessionStats.metrics?.models ?? {}
  ).reduce((acc, model) => acc + (model.tokens?.candidates ?? 0), 0);
  const { elapsedTime, currentLoadingPhrase, taskStartTokens } = useLoadingIndicator(
    streamingState,
    settings.merged.ui?.customWittyPhrases,
    currentCandidatesTokens
  );
  useAttentionNotifications({
    isFocused,
    streamingState,
    elapsedTime,
    settings,
    config: config2,
    terminal,
    pendingToolCalls
  });
  const { closeAnyOpenDialog } = useDialogClose({
    isThemeDialogOpen,
    handleThemeSelect,
    isApprovalModeDialogOpen,
    handleApprovalModeSelect,
    isAuthDialogOpen,
    handleAuthSelect,
    pendingAuthType,
    isEditorDialogOpen,
    exitEditorDialog,
    isSettingsDialogOpen,
    closeSettingsDialog,
    isMemoryDialogOpen,
    closeMemoryDialog,
    activeArenaDialog,
    closeArenaDialog,
    isFolderTrustDialogOpen,
    showWelcomeBackDialog,
    handleWelcomeBackClose,
    isBackgroundTasksDialogOpen: bgTasksDialogOpen,
    closeBackgroundTasksDialog: closeBgTasksDialog
  });
  const handleExit = (0, import_react189.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 (btwItem && btwItem.btw.isPending && !dialogsVisibleRef.current) {
        cancelBtw();
        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,
      btwItem,
      cancelBtw,
      streamingState,
      cancelOngoingRequest,
      buffer
    ]
  );
  const handleGlobalKeypress = (0, import_react189.useCallback)(
    (key) => {
      if (settings.merged.general?.debugKeystrokeLogging) {
        debugLogger163.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 (btwItem && btwItem.btw.isPending && !dialogsVisibleRef.current) {
          cancelBtw();
          return;
        }
        if (buffer.text.length > 0) {
          return;
        }
        handleExit(ctrlDPressedOnce, setCtrlDPressedOnce, ctrlDTimerRef);
        return;
      } else if (keyMatchers["escape" /* ESCAPE */](key)) {
        if (btwItem && !dialogsVisibleRef.current) {
          cancelBtw();
          return;
        }
        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 (streamingState === "idle" /* Idle */ && !dialogsVisibleRef.current) {
          if (escapeTimerRef.current) {
            clearTimeout(escapeTimerRef.current);
            escapeTimerRef.current = null;
          }
          setEscapePressedOnce(false);
          handleDoubleEscRewind();
          return;
        }
        if (escapeTimerRef.current) {
          clearTimeout(escapeTimerRef.current);
          escapeTimerRef.current = null;
        }
        setEscapePressedOnce(false);
        return;
      }
      if (btwItem && !btwItem.btw.isPending && !dialogsVisibleRef.current && buffer.text.length === 0) {
        if (key.name === "return" || key.sequence === " ") {
          setBtwItem(null);
          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);
        }
      } else if (keyMatchers["toggleCompactMode" /* TOGGLE_COMPACT_MODE */](key)) {
        const newValue = !compactMode;
        setCompactMode(newValue);
        void settings.setValue("User" /* User */, "ui.compactMode", newValue);
        refreshStatic();
      }
    },
    [
      constrainHeight,
      setConstrainHeight,
      showToolDescriptions,
      setShowToolDescriptions,
      config2,
      ideContextState,
      handleExit,
      ctrlCPressedOnce,
      setCtrlCPressedOnce,
      ctrlCTimerRef,
      ctrlDPressedOnce,
      setCtrlDPressedOnce,
      ctrlDTimerRef,
      escapePressedOnce,
      setEscapePressedOnce,
      escapeTimerRef,
      streamingState,
      cancelOngoingRequest,
      buffer,
      handleSlashCommand2,
      activePtyId,
      embeddedShellFocused,
      btwItem,
      setBtwItem,
      cancelBtw,
      // `settings` is a stable LoadedSettings instance (not recreated on render).
      // ESLint requires it here because the callback calls settings.setValue().
      // debugKeystrokeLogging is read at call time, so no stale closure risk.
      settings,
      isAuthenticating,
      compactMode,
      setCompactMode,
      refreshStatic,
      handleDoubleEscRewind
    ]
  );
  useKeypress(handleGlobalKeypress, { isActive: true });
  (0, import_react189.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;
      stdout2.write(`\x1B]2;${paddedTitle}\x07`);
    }
  }, [
    streamingState,
    thought,
    settings.merged.ui?.showStatusInTitle,
    settings.merged.ui?.hideWindowTitle,
    stdout2
  ]);
  const queueDrainingRef = (0, import_react189.useRef)(false);
  const [queueDrainNonce, setQueueDrainNonce] = (0, import_react189.useState)(0);
  (0, import_react189.useEffect)(() => {
    if (queueDrainingRef.current) return;
    if (!isConfigInitialized) return;
    if (streamingState !== "idle" /* Idle */) return;
    if (dialogsVisible) return;
    if (messageQueue.length === 0) return;
    const plainPrompts = drainQueue();
    const submission = plainPrompts.length > 0 ? plainPrompts.join("\n\n") : popNextSegment();
    if (submission === null) return;
    queueDrainingRef.current = true;
    Promise.resolve(submitQuery(submission)).finally(() => {
      queueDrainingRef.current = false;
      setQueueDrainNonce((n3) => n3 + 1);
    });
  }, [
    isConfigInitialized,
    streamingState,
    dialogsVisible,
    messageQueue,
    drainQueue,
    popNextSegment,
    submitQuery,
    queueDrainNonce
  ]);
  const nightly = props.version.includes("nightly");
  const uiState = (0, import_react189.useMemo)(
    () => ({
      history: historyManager.history,
      historyManager,
      isThemeDialogOpen,
      themeError,
      isAuthenticating,
      isConfigInitialized,
      authError,
      isAuthDialogOpen,
      pendingAuthType,
      externalAuthState,
      // Qwen OAuth state
      qwenAuthState,
      editorError,
      isEditorDialogOpen,
      debugMessage,
      quittingMessages,
      isSettingsDialogOpen,
      isMemoryDialogOpen,
      isModelDialogOpen,
      isFastModelMode,
      isManageModelsDialogOpen,
      isTrustDialogOpen,
      activeArenaDialog,
      isPermissionsDialogOpen,
      isApprovalModeDialogOpen,
      isResumeDialogOpen,
      resumeMatchedSessions,
      isDeleteDialogOpen,
      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,
      stickyTodos,
      btwItem,
      setBtwItem,
      cancelBtw,
      nightly,
      branchName,
      sessionStats,
      terminalWidth,
      terminalHeight,
      mainControlsRef,
      currentIDE,
      updateInfo,
      showIdeRestartPrompt,
      ideTrustRestartReason,
      isRestarting,
      extensionsUpdateState,
      activePtyId,
      embeddedShellFocused,
      // Welcome back dialog
      showWelcomeBackDialog,
      welcomeBackInfo,
      welcomeBackChoice,
      // Subagent dialogs
      isSubagentCreateDialogOpen,
      isAgentsManagerDialogOpen,
      // Extensions manager dialog
      isExtensionsManagerDialogOpen,
      // MCP dialog
      isMcpDialogOpen,
      // Hooks dialog
      isHooksDialogOpen,
      // Feedback dialog
      isFeedbackDialogOpen,
      // Per-task token tracking
      taskStartTokens,
      // Real-time token display
      streamingResponseLengthRef,
      isReceivingContent,
      // Session name
      sessionName,
      setSessionName,
      // Prompt suggestion
      promptSuggestion,
      dismissPromptSuggestion,
      // Rewind selector
      isRewindSelectorOpen,
      rewindEscPending
    }),
    [
      isThemeDialogOpen,
      themeError,
      isAuthenticating,
      isConfigInitialized,
      authError,
      isAuthDialogOpen,
      pendingAuthType,
      externalAuthState,
      // Qwen OAuth state
      qwenAuthState,
      editorError,
      isEditorDialogOpen,
      debugMessage,
      quittingMessages,
      isSettingsDialogOpen,
      isMemoryDialogOpen,
      isModelDialogOpen,
      isFastModelMode,
      isManageModelsDialogOpen,
      isTrustDialogOpen,
      activeArenaDialog,
      isPermissionsDialogOpen,
      isApprovalModeDialogOpen,
      isResumeDialogOpen,
      resumeMatchedSessions,
      isDeleteDialogOpen,
      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,
      stickyTodos,
      btwItem,
      setBtwItem,
      cancelBtw,
      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,
      // Extensions manager dialog
      isExtensionsManagerDialogOpen,
      // MCP dialog
      isMcpDialogOpen,
      // Hooks dialog
      isHooksDialogOpen,
      // Feedback dialog
      isFeedbackDialogOpen,
      // Per-task token tracking
      taskStartTokens,
      // Real-time token display
      streamingResponseLengthRef,
      isReceivingContent,
      // Session name
      sessionName,
      setSessionName,
      // Prompt suggestion
      promptSuggestion,
      dismissPromptSuggestion,
      // Rewind selector
      isRewindSelectorOpen,
      rewindEscPending
    ]
  );
  const uiActions = (0, import_react189.useMemo)(
    () => ({
      openThemeDialog,
      openEditorDialog,
      openMemoryDialog,
      handleThemeSelect,
      handleThemeHighlight,
      handleApprovalModeSelect,
      handleAuthSelect,
      setAuthState,
      onAuthError,
      cancelAuthentication,
      handleCodingPlanSubmit,
      handleAlibabaStandardSubmit,
      handleOpenRouterSubmit,
      handleCustomApiKeySubmit,
      handleEditorSelect,
      exitEditorDialog,
      closeSettingsDialog,
      closeMemoryDialog,
      closeModelDialog,
      openModelDialog,
      openManageModelsDialog,
      closeManageModelsDialog,
      openArenaDialog,
      closeArenaDialog,
      handleArenaModelsSelected,
      dismissCodingPlanUpdate,
      closeTrustDialog,
      closePermissionsDialog,
      setShellModeActive,
      vimHandleInput,
      handleIdePromptComplete,
      handleCommandMigrationComplete,
      handleFolderTrustSelect,
      setConstrainHeight,
      onEscapePromptChange: handleEscapePromptChange,
      onSuggestionsVisibilityChange: setHasSuggestionsVisible,
      refreshStatic,
      handleFinalSubmit,
      handleRetryLastPrompt: retryLastPrompt,
      handleClearScreen,
      popAllQueuedMessages: popAllMessages,
      // Welcome back dialog
      handleWelcomeBackSelection,
      handleWelcomeBackClose,
      // Subagent dialogs
      closeSubagentCreateDialog,
      closeAgentsManagerDialog,
      // Extensions manager dialog
      closeExtensionsManagerDialog,
      // MCP dialog
      closeMcpDialog,
      // Hooks dialog
      openHooksDialog,
      // Hooks dialog
      closeHooksDialog,
      // Resume session dialog
      openResumeDialog,
      closeResumeDialog,
      handleResume,
      // Delete session dialog
      openDeleteDialog,
      closeDeleteDialog,
      handleDelete,
      // Feedback dialog
      openFeedbackDialog,
      closeFeedbackDialog,
      temporaryCloseFeedbackDialog,
      submitFeedback,
      // Rewind selector
      openRewindSelector,
      closeRewindSelector,
      handleRewindConfirm
    }),
    [
      openThemeDialog,
      openEditorDialog,
      openMemoryDialog,
      handleThemeSelect,
      handleThemeHighlight,
      handleApprovalModeSelect,
      handleAuthSelect,
      setAuthState,
      onAuthError,
      cancelAuthentication,
      handleCodingPlanSubmit,
      handleAlibabaStandardSubmit,
      handleOpenRouterSubmit,
      handleCustomApiKeySubmit,
      handleEditorSelect,
      exitEditorDialog,
      closeSettingsDialog,
      closeMemoryDialog,
      closeModelDialog,
      openModelDialog,
      openManageModelsDialog,
      closeManageModelsDialog,
      openArenaDialog,
      closeArenaDialog,
      handleArenaModelsSelected,
      dismissCodingPlanUpdate,
      closeTrustDialog,
      closePermissionsDialog,
      setShellModeActive,
      vimHandleInput,
      handleIdePromptComplete,
      handleCommandMigrationComplete,
      handleFolderTrustSelect,
      setConstrainHeight,
      handleEscapePromptChange,
      refreshStatic,
      handleFinalSubmit,
      retryLastPrompt,
      handleClearScreen,
      popAllMessages,
      handleWelcomeBackSelection,
      handleWelcomeBackClose,
      // Subagent dialogs
      closeSubagentCreateDialog,
      closeAgentsManagerDialog,
      // Extensions manager dialog
      closeExtensionsManagerDialog,
      // MCP dialog
      closeMcpDialog,
      // Hooks dialog
      openHooksDialog,
      // Hooks dialog
      closeHooksDialog,
      // Resume session dialog
      openResumeDialog,
      closeResumeDialog,
      handleResume,
      // Delete session dialog
      openDeleteDialog,
      closeDeleteDialog,
      handleDelete,
      // Feedback dialog
      openFeedbackDialog,
      closeFeedbackDialog,
      temporaryCloseFeedbackDialog,
      submitFeedback,
      // Rewind selector
      openRewindSelector,
      closeRewindSelector,
      handleRewindConfirm
    ]
  );
  const compactModeValue = (0, import_react189.useMemo)(
    () => ({ compactMode, setCompactMode }),
    [compactMode, setCompactMode]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime150.jsx)(UIStateContext.Provider, { value: uiState, children: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)(UIActionsContext.Provider, { value: uiActions, children: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)(ConfigContext.Provider, { value: config2, children: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)(
    AppContext2.Provider,
    {
      value: {
        version: props.version,
        startupWarnings: props.startupWarnings || []
      },
      children: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)(CompactModeProvider, { value: compactModeValue, children: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)(ShellFocusContext.Provider, { value: isFocused, children: /* @__PURE__ */ (0, import_jsx_runtime150.jsx)(App2, {}) }) })
    }
  ) }) }) });
}, "AppContainer");

// packages/cli/src/ui/hooks/useKittyKeyboardProtocol.ts
init_esbuild_shims();
var import_react190 = __toESM(require_react(), 1);
function useKittyKeyboardProtocol() {
  const [status] = (0, import_react190.useState)({
    supported: isKittyProtocolSupported(),
    enabled: isKittyProtocolEnabled(),
    checking: false
  });
  return status;
}
__name(useKittyKeyboardProtocol, "useKittyKeyboardProtocol");

// packages/cli/src/utils/readStdin.ts
init_esbuild_shims();
init_stdioHelpers();
async function readStdin() {
  const MAX_STDIN_SIZE = 8 * 1024 * 1024;
  return new Promise((resolve42, 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();
      resolve42(data);
    }, "onEnd");
    const onError2 = /* @__PURE__ */ __name((err2) => {
      cleanup();
      reject(err2);
    }, "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 spawn13 } from "node:child_process";
init_stdioHelpers();
async function relaunchOnExitCode(runner) {
  while (true) {
    try {
      const exitCode = await runner();
      if (exitCode !== RELAUNCH_EXIT_CODE) {
        process.exit(exitCode);
      }
    } catch (error40) {
      process.stdin.resume();
      writeStderrLine("Fatal error: Failed to relaunch the CLI process.");
      writeStderrLine(error40 instanceof Error ? error40.message : String(error40));
      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 = spawn13(process.execPath, nodeArgs, {
      stdio: "inherit",
      env: newEnv
    });
    return new Promise((resolve42, reject) => {
      child.on("error", reject);
      child.on("close", (code2) => {
        process.stdin.resume();
        resolve42(code2 ?? 1);
      });
    });
  }, "runner");
  await relaunchOnExitCode(runner);
}
__name(relaunchAppInChildProcess, "relaunchAppInChildProcess");

// packages/cli/src/utils/sandbox.ts
init_esbuild_shims();
var import_shell_quote6 = __toESM(require_shell_quote(), 1);
import { exec as exec5, execSync as execSync10, spawn as spawn14 } from "node:child_process";
import os55 from "node:os";
import path148 from "node:path";
import fs139 from "node:fs";
import { fileURLToPath as fileURLToPath18 } from "node:url";
init_dist4();
init_stdioHelpers();
import { promisify as promisify12 } from "node:util";
import { randomBytes as randomBytes8 } from "node:crypto";
var execAsync3 = promisify12(exec5);
function getContainerPath(hostPath) {
  if (os55.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 (os55.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 name4 = fullName.split("/").at(-1) ?? "unknown-image";
  return tag2 ? `${name4}-${tag2}` : name4;
}
__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 = os55.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 = path148.join(
    SETTINGS_DIRECTORY_NAME2,
    "sandbox.bashrc"
  );
  if (fs139.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_quote6.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 args2 = [...shellCmds, cliCmd, ...quotedCliArgs];
  return ["bash", "-c", args2.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 = fileURLToPath18(
      new URL(`sandbox-macos-${profile}.sb`, import.meta.url)
    );
    if (!BUILTIN_SEATBELT_PROFILES.includes(profile)) {
      profileFile = path148.join(
        SETTINGS_DIRECTORY_NAME2,
        `sandbox-macos-${profile}.sb`
      );
    }
    if (!fs139.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 args3 = [
      "-D",
      `TARGET_DIR=${fs139.realpathSync(process.cwd())}`,
      "-D",
      `TMP_DIR=${fs139.realpathSync(os55.tmpdir())}`,
      "-D",
      `HOME_DIR=${fs139.realpathSync(os55.homedir())}`,
      "-D",
      `CACHE_DIR=${fs139.realpathSync(execSync10(`getconf DARWIN_USER_CACHE_DIR`).toString().trim())}`
    ];
    const MAX_INCLUDE_DIRS = 5;
    const targetDir = fs139.realpathSync(cliConfig?.getTargetDir() || "");
    const includedDirs = [];
    if (cliConfig) {
      const workspaceContext = cliConfig.getWorkspaceContext();
      const directories = workspaceContext.getDirectories();
      for (const dir of directories) {
        const realDir = fs139.realpathSync(dir);
        if (realDir !== targetDir) {
          includedDirs.push(realDir);
        }
      }
    }
    for (let i4 = 0; i4 < MAX_INCLUDE_DIRS; i4++) {
      let dirPath = "/dev/null";
      if (i4 < includedDirs.length) {
        dirPath = includedDirs[i4];
      }
      args3.push("-D", `INCLUDE_DIR_${i4}=${dirPath}`);
    }
    const finalArgv = cliArgs;
    args3.push(
      "-f",
      profileFile,
      "sh",
      "-c",
      [
        `SANDBOX=sandbox-exec`,
        `NODE_OPTIONS="${nodeOptions}"`,
        ...finalArgv.map((arg) => (0, import_shell_quote6.quote)([arg]))
      ].join(" ")
    );
    const proxyCommand2 = process.env["QWEN_SANDBOX_PROXY_COMMAND"];
    let proxyProcess2 = void 0;
    let sandboxProcess2 = void 0;
    const sandboxEnv = { ...process.env };
    if (proxyCommand2) {
      const proxy2 = process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"] || "http://localhost:8877";
      sandboxEnv["HTTPS_PROXY"] = proxy2;
      sandboxEnv["https_proxy"] = proxy2;
      sandboxEnv["HTTP_PROXY"] = proxy2;
      sandboxEnv["http_proxy"] = proxy2;
      const noProxy = process.env["NO_PROXY"] || process.env["no_proxy"];
      if (noProxy) {
        sandboxEnv["NO_PROXY"] = noProxy;
        sandboxEnv["no_proxy"] = noProxy;
      }
      proxyProcess2 = spawn14("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 = spawn14(config2.command, args3, {
      stdio: "inherit"
    });
    return new Promise((resolve42, reject) => {
      sandboxProcess2?.on("error", reject);
      sandboxProcess2?.on("close", (code2) => {
        process.stdin.resume();
        resolve42(code2 ?? 1);
      });
    });
  }
  writeStderrLine(`hopping into sandbox (command: ${config2.command}) ...`);
  const gcPath = fs139.realpathSync(process.argv[1]);
  const projectSandboxDockerfile = path148.join(
    SETTINGS_DIRECTORY_NAME2,
    "sandbox.Dockerfile"
  );
  const isCustomProjectSandbox = fs139.existsSync(projectSandboxDockerfile);
  const image2 = config2.image;
  const workdir = path148.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 = path148.join(
        SETTINGS_DIRECTORY_NAME2,
        "sandbox.Dockerfile"
      );
      if (isCustomProjectSandbox) {
        writeStderrLine(`using ${projectSandboxDockerfile2} for sandbox`);
        buildArgs += `-f ${path148.resolve(projectSandboxDockerfile2)} -i ${image2}`;
      }
      execSync10(
        `cd ${gcRoot} && node scripts/build_sandbox.js -s ${buildArgs}`,
        {
          stdio: "inherit",
          env: {
            ...process.env,
            QWEN_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 args2 = ["run", "-i", "--rm", "--init", "--workdir", containerWorkdir];
  if (process.env["SANDBOX_FLAGS"]) {
    const flags2 = (0, import_shell_quote6.parse)(process.env["SANDBOX_FLAGS"], process.env).filter(
      (f5) => typeof f5 === "string"
    );
    args2.push(...flags2);
  }
  if (process.stdin.isTTY) {
    args2.push("-t");
  }
  args2.push("--add-host", "host.docker.internal:host-gateway");
  args2.push("--volume", `${workdir}:${containerWorkdir}`);
  const userSettingsDirOnHost = USER_SETTINGS_DIR2;
  const userSettingsDirInSandbox = getContainerPath(
    `/home/node/${SETTINGS_DIRECTORY_NAME2}`
  );
  if (!fs139.existsSync(userSettingsDirOnHost)) {
    fs139.mkdirSync(userSettingsDirOnHost);
  }
  args2.push("--volume", `${userSettingsDirOnHost}:${userSettingsDirInSandbox}`);
  if (userSettingsDirInSandbox !== userSettingsDirOnHost) {
    args2.push(
      "--volume",
      `${userSettingsDirOnHost}:${getContainerPath(userSettingsDirOnHost)}`
    );
  }
  args2.push("--volume", `${os55.tmpdir()}:${getContainerPath(os55.tmpdir())}`);
  const gcloudConfigDir = path148.join(os55.homedir(), ".config", "gcloud");
  if (fs139.existsSync(gcloudConfigDir)) {
    args2.push(
      "--volume",
      `${gcloudConfigDir}:${getContainerPath(gcloudConfigDir)}:ro`
    );
  }
  if (process.env["GOOGLE_APPLICATION_CREDENTIALS"]) {
    const adcFile = process.env["GOOGLE_APPLICATION_CREDENTIALS"];
    if (fs139.existsSync(adcFile)) {
      args2.push("--volume", `${adcFile}:${getContainerPath(adcFile)}:ro`);
      args2.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 (!path148.isAbsolute(from)) {
          throw new FatalSandboxError(
            `Path '${from}' listed in SANDBOX_MOUNTS must be absolute`
          );
        }
        if (!fs139.existsSync(from)) {
          throw new FatalSandboxError(
            `Missing mount path '${from}' listed in SANDBOX_MOUNTS`
          );
        }
        writeStderrLine(`SANDBOX_MOUNTS: ${from} -> ${to} (${opts})`);
        args2.push("--volume", mount);
      }
    }
  }
  ports().forEach((p2) => args2.push("--publish", `${p2}:${p2}`));
  if (process.env["DEBUG"]) {
    const debugPort = process.env["DEBUG_PORT"] || "9229";
    args2.push(`--publish`, `${debugPort}:${debugPort}`);
  }
  const proxyCommand = process.env["QWEN_SANDBOX_PROXY_COMMAND"];
  if (proxyCommand) {
    let proxy2 = process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"] || "http://localhost:8877";
    proxy2 = proxy2.replace("localhost", SANDBOX_PROXY_NAME);
    if (proxy2) {
      args2.push("--env", `HTTPS_PROXY=${proxy2}`);
      args2.push("--env", `https_proxy=${proxy2}`);
      args2.push("--env", `HTTP_PROXY=${proxy2}`);
      args2.push("--env", `http_proxy=${proxy2}`);
    }
    const noProxy = process.env["NO_PROXY"] || process.env["no_proxy"];
    if (noProxy) {
      args2.push("--env", `NO_PROXY=${noProxy}`);
      args2.push("--env", `no_proxy=${noProxy}`);
    }
    if (proxy2) {
      execSync10(
        `${config2.command} network inspect ${SANDBOX_NETWORK_NAME} || ${config2.command} network create --internal ${SANDBOX_NETWORK_NAME}`
      );
      args2.push("--network", SANDBOX_NETWORK_NAME);
      if (proxyCommand) {
        execSync10(
          `${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-${randomBytes8(4).toString(
      "hex"
    )}`;
    writeStderrLine(`ContainerName: ${containerName}`);
  } else {
    let index = 0;
    const containerNameCheck = execSync10(
      `${config2.command} ps -a --format "{{.Names}}"`
    ).toString().trim();
    while (containerNameCheck.includes(`${imageName}-${index}`)) {
      index++;
    }
    containerName = `${imageName}-${index}`;
    writeStderrLine(`ContainerName (regular): ${containerName}`);
  }
  args2.push("--name", containerName, "--hostname", containerName);
  if (process.env["QWEN_CODE_TEST_VAR"]) {
    args2.push(
      "--env",
      `QWEN_CODE_TEST_VAR=${process.env["QWEN_CODE_TEST_VAR"]}`
    );
  }
  if (process.env["GEMINI_API_KEY"]) {
    args2.push("--env", `GEMINI_API_KEY=${process.env["GEMINI_API_KEY"]}`);
  }
  if (process.env["GOOGLE_API_KEY"]) {
    args2.push("--env", `GOOGLE_API_KEY=${process.env["GOOGLE_API_KEY"]}`);
  }
  if (process.env["OPENAI_API_KEY"]) {
    args2.push("--env", `OPENAI_API_KEY=${process.env["OPENAI_API_KEY"]}`);
  }
  if (process.env["OPENAI_BASE_URL"]) {
    args2.push("--env", `OPENAI_BASE_URL=${process.env["OPENAI_BASE_URL"]}`);
  }
  if (process.env["OPENAI_MODEL"]) {
    args2.push("--env", `OPENAI_MODEL=${process.env["OPENAI_MODEL"]}`);
  }
  if (process.env["GOOGLE_GENAI_USE_VERTEXAI"]) {
    args2.push(
      "--env",
      `GOOGLE_GENAI_USE_VERTEXAI=${process.env["GOOGLE_GENAI_USE_VERTEXAI"]}`
    );
  }
  if (process.env["GOOGLE_GENAI_USE_GCA"]) {
    args2.push(
      "--env",
      `GOOGLE_GENAI_USE_GCA=${process.env["GOOGLE_GENAI_USE_GCA"]}`
    );
  }
  if (process.env["GOOGLE_CLOUD_PROJECT"]) {
    args2.push(
      "--env",
      `GOOGLE_CLOUD_PROJECT=${process.env["GOOGLE_CLOUD_PROJECT"]}`
    );
  }
  if (process.env["GOOGLE_CLOUD_LOCATION"]) {
    args2.push(
      "--env",
      `GOOGLE_CLOUD_LOCATION=${process.env["GOOGLE_CLOUD_LOCATION"]}`
    );
  }
  if (process.env["GEMINI_MODEL"]) {
    args2.push("--env", `GEMINI_MODEL=${process.env["GEMINI_MODEL"]}`);
  }
  if (process.env["TERM"]) {
    args2.push("--env", `TERM=${process.env["TERM"]}`);
  }
  if (process.env["COLORTERM"]) {
    args2.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]) {
      args2.push("--env", `${envVar}=${process.env[envVar]}`);
    }
  }
  if (process.env["VIRTUAL_ENV"]?.toLowerCase().startsWith(workdir.toLowerCase())) {
    const sandboxVenvPath = path148.resolve(
      SETTINGS_DIRECTORY_NAME2,
      "sandbox.venv"
    );
    if (!fs139.existsSync(sandboxVenvPath)) {
      fs139.mkdirSync(sandboxVenvPath, { recursive: true });
    }
    args2.push(
      "--volume",
      `${sandboxVenvPath}:${getContainerPath(process.env["VIRTUAL_ENV"])}`
    );
    args2.push(
      "--env",
      `VIRTUAL_ENV=${getContainerPath(process.env["VIRTUAL_ENV"])}`
    );
  }
  if (process.env["SANDBOX_ENV"]) {
    for (let env6 of process.env["SANDBOX_ENV"].split(",")) {
      if (env6 = env6.trim()) {
        if (env6.includes("=")) {
          writeStderrLine(`SANDBOX_ENV: ${env6}`);
          args2.push("--env", env6);
        } 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) {
    args2.push("--env", `NODE_OPTIONS="${allNodeOptions}"`);
  }
  args2.push("--env", `SANDBOX=${containerName}`);
  if (config2.command === "podman") {
    const emptyAuthFilePath = path148.join(os55.tmpdir(), "empty_auth.json");
    fs139.writeFileSync(emptyAuthFilePath, "{}", "utf-8");
    args2.push("--authfile", emptyAuthFilePath);
  }
  let userFlag = "";
  const finalEntrypoint = entrypoint(workdir, cliArgs);
  const useCurrentUser = await shouldUseCurrentUserInSandbox();
  if (useCurrentUser) {
    args2.push("--user", "root");
    const uid = execSync10("id -u").toString().trim();
    const gid = execSync10("id -g").toString().trim();
    const username = "qwen";
    const homeDir = getContainerPath(os55.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}`;
    args2.push("--env", `HOME=${os55.homedir()}`);
  } else if (isIntegrationTest) {
    args2.push("--user", "root");
    userFlag = "--user root";
  }
  args2.push(image2);
  args2.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 = os55.platform() === "win32";
    const proxyShell = isWindows9 ? "cmd.exe" : "bash";
    const proxyShellArgs = isWindows9 ? ["/c", proxyContainerCommand] : ["-c", proxyContainerCommand];
    proxyProcess = spawn14(proxyShell, proxyShellArgs, {
      stdio: ["ignore", "pipe", "pipe"],
      detached: true
    });
    const stopProxy = /* @__PURE__ */ __name(() => {
      writeStderrLine("stopping proxy container ...");
      execSync10(`${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 = spawn14(config2.command, args2, {
    stdio: "inherit"
  });
  return new Promise((resolve42, reject) => {
    sandboxProcess.on("error", (err2) => {
      writeStderrLine(`Sandbox process error: ${err2}`);
      reject(err2);
    });
    sandboxProcess?.on("close", (code2, signal) => {
      process.stdin.resume();
      if (code2 !== 0 && code2 !== null) {
        writeStderrLine(
          `Sandbox process exited with code: ${code2}, signal: ${signal}`
        );
      }
      resolve42(code2 ?? 1);
    });
  });
}
__name(start_sandbox, "start_sandbox");
async function imageExists(sandbox, image2) {
  return new Promise((resolve42) => {
    const args2 = ["images", "-q", image2];
    const checkProcess = spawn14(sandbox, args2);
    let stdoutData = "";
    if (checkProcess.stdout) {
      checkProcess.stdout.on("data", (data) => {
        stdoutData += data.toString();
      });
    }
    checkProcess.on("error", (err2) => {
      writeStderrLine(
        `Failed to start '${sandbox}' command for image check: ${err2.message}`
      );
      resolve42(false);
    });
    checkProcess.on("close", (code2) => {
      if (code2 !== 0) {
      }
      resolve42(stdoutData.trim() !== "");
    });
  });
}
__name(imageExists, "imageExists");
async function pullImage(sandbox, image2) {
  writeStderrLine(`Attempting to pull image ${image2} using ${sandbox}...`);
  return new Promise((resolve42) => {
    const args2 = ["pull", image2];
    const pullProcess = spawn14(sandbox, args2, { 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((err2) => {
      writeStderrLine(
        `Failed to start '${sandbox} pull ${image2}' command: ${err2.message}`
      );
      cleanup();
      resolve42(false);
    }, "onError");
    const onClose = /* @__PURE__ */ __name((code2) => {
      if (code2 === 0) {
        writeStderrLine(`Successfully pulled image ${image2}.`);
        cleanup();
        resolve42(true);
      } else {
        writeStderrLine(
          `Failed to pull image ${image2}. '${sandbox} pull ${image2}' exited with code ${code2}.`
        );
        if (stderrData.trim()) {
        }
        cleanup();
        resolve42(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();
init_dist4();
import fs140 from "node:fs/promises";
import os56 from "node:os";
import { join as pathJoin } from "node:path";
var warningsFilePath = pathJoin(os56.tmpdir(), "qwen-code-warnings.txt");
async function getStartupWarnings() {
  try {
    await fs140.access(warningsFilePath);
    const warningsContent = await fs140.readFile(warningsFilePath, "utf-8");
    const warnings = warningsContent.split("\n").filter((line) => line.trim() !== "");
    try {
      await fs140.unlink(warningsFilePath);
    } catch {
      warnings.push("Warning: Could not delete temporary warnings file.");
    }
    return warnings;
  } catch (err2) {
    if (err2 instanceof Error && "code" in err2 && err2.code === "ENOENT") {
      return [];
    }
    return [`Error checking/reading warnings file: ${getErrorMessage(err2)}`];
  }
}
__name(getStartupWarnings, "getStartupWarnings");

// packages/cli/src/utils/userStartupWarnings.ts
init_esbuild_shims();
init_dist4();
import fs141 from "node:fs/promises";
import * as os57 from "node:os";
import path149 from "node:path";
var homeDirectoryCheck = {
  id: "home-directory",
  check: /* @__PURE__ */ __name(async (options2) => {
    try {
      const [workspaceRealPath, homeRealPath] = await Promise.all([
        fs141.realpath(options2.workspaceRoot),
        fs141.realpath(os57.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 fs141.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 (path149.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 (error40) {
      return `Ripgrep not available: ${error40 instanceof Error ? error40.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/gemini.tsx
init_stdioHelpers();

// packages/cli/src/utils/earlyInputCapture.ts
init_esbuild_shims();
init_dist4();
var debugLogger164 = createDebugLogger("EARLY_INPUT");
var MAX_BUFFER_SIZE = 64 * 1024;
var inputBuffer = {
  chunks: [],
  totalBytes: 0,
  captured: false
};
var captureHandler = null;
var captureStdin = null;
var isCapturing = false;
var pendingTerminalResponse = Buffer.alloc(0);
function classifyEscapeSequence(data, startIdx) {
  if (startIdx >= data.length || data[startIdx] !== 27) {
    return "user";
  }
  const nextIdx = startIdx + 1;
  if (nextIdx >= data.length) {
    return "incomplete";
  }
  const nextByte = data[nextIdx];
  if (nextByte === 80 || // P (DCS)
  nextByte === 95 || // _ (APC)
  nextByte === 94 || // ^ (PM)
  nextByte === 93) {
    return "terminal";
  }
  if (nextByte === 91) {
    const thirdIdx = startIdx + 2;
    if (thirdIdx >= data.length) {
      return "incomplete";
    }
    const thirdByte = data[thirdIdx];
    if (thirdByte === 63 || thirdByte === 62) {
      return "terminal";
    }
    return "user";
  }
  return "user";
}
__name(classifyEscapeSequence, "classifyEscapeSequence");
function skipTerminalResponse(data, startIdx) {
  if (startIdx >= data.length || data[startIdx] !== 27) {
    return { nextIndex: startIdx + 1, complete: true };
  }
  const nextIdx = startIdx + 1;
  if (nextIdx >= data.length) {
    return { nextIndex: nextIdx, complete: false };
  }
  const nextByte = data[nextIdx];
  if (nextByte === 93) {
    let i4 = startIdx + 2;
    while (i4 < data.length) {
      if (data[i4] === 7) {
        return { nextIndex: i4 + 1, complete: true };
      }
      if (data[i4] === 27 && i4 + 1 < data.length && data[i4 + 1] === 92) {
        return { nextIndex: i4 + 2, complete: true };
      }
      i4++;
    }
    return { nextIndex: data.length, complete: false };
  }
  if (nextByte === 80 || nextByte === 95 || nextByte === 94) {
    let i4 = startIdx + 2;
    while (i4 < data.length) {
      if (data[i4] === 27 && i4 + 1 < data.length && data[i4 + 1] === 92) {
        return { nextIndex: i4 + 2, complete: true };
      }
      i4++;
    }
    return { nextIndex: data.length, complete: false };
  }
  if (nextByte === 91) {
    let i4 = startIdx + 2;
    while (i4 < data.length) {
      const byte = data[i4];
      if (byte >= 64 && byte <= 126) {
        return { nextIndex: i4 + 1, complete: true };
      }
      i4++;
    }
    return { nextIndex: data.length, complete: false };
  }
  return { nextIndex: startIdx + 1, complete: true };
}
__name(skipTerminalResponse, "skipTerminalResponse");
function filterTerminalResponses(data) {
  const result = Buffer.allocUnsafe(data.length);
  let writeIdx = 0;
  let i4 = 0;
  while (i4 < data.length) {
    if (data[i4] === 27) {
      const sequenceType = classifyEscapeSequence(data, i4);
      if (sequenceType === "incomplete") {
        return {
          filtered: result.subarray(0, writeIdx),
          trailingPartialTerminalResponse: data.subarray(i4)
        };
      }
      if (sequenceType === "terminal") {
        const skipResult = skipTerminalResponse(data, i4);
        if (!skipResult.complete) {
          return {
            filtered: result.subarray(0, writeIdx),
            trailingPartialTerminalResponse: data.subarray(i4)
          };
        }
        i4 = skipResult.nextIndex;
        continue;
      }
    }
    result[writeIdx++] = data[i4];
    i4++;
  }
  return {
    filtered: result.subarray(0, writeIdx),
    trailingPartialTerminalResponse: Buffer.alloc(0)
  };
}
__name(filterTerminalResponses, "filterTerminalResponses");
function shouldReplayPendingAtStop(pending) {
  if (pending.length === 0) {
    return false;
  }
  if (pending.length === 1 && pending[0] === 27) {
    return true;
  }
  return classifyEscapeSequence(pending, 0) === "user";
}
__name(shouldReplayPendingAtStop, "shouldReplayPendingAtStop");
function startEarlyInputCapture() {
  if (isCapturing || !process.stdin.isTTY) {
    if (!process.stdin.isTTY) {
      debugLogger164.debug("Early input capture skipped: stdin is not a TTY");
    }
    return;
  }
  if (process.env["QWEN_CODE_DISABLE_EARLY_CAPTURE"] === "1") {
    debugLogger164.debug("Early input capture disabled by environment variable");
    return;
  }
  isCapturing = true;
  inputBuffer = {
    chunks: [],
    totalBytes: 0,
    captured: false
  };
  pendingTerminalResponse = Buffer.alloc(0);
  debugLogger164.debug("Starting early input capture");
  captureHandler = /* @__PURE__ */ __name((data) => {
    if (inputBuffer.captured) {
      return;
    }
    if (inputBuffer.totalBytes >= MAX_BUFFER_SIZE) {
      debugLogger164.warn(
        `Early input capture buffer full (${MAX_BUFFER_SIZE} bytes). Stopping capture; additional keystrokes during startup will be lost.`
      );
      stopEarlyInputCapture();
      return;
    }
    const dataToFilter = pendingTerminalResponse.length > 0 ? Buffer.concat([pendingTerminalResponse, data]) : data;
    pendingTerminalResponse = Buffer.alloc(0);
    const { filtered, trailingPartialTerminalResponse } = filterTerminalResponses(dataToFilter);
    if (trailingPartialTerminalResponse.length > 0) {
      pendingTerminalResponse = Buffer.from(trailingPartialTerminalResponse);
    }
    if (filtered.length > 0) {
      const newLength = inputBuffer.totalBytes + filtered.length;
      if (newLength > MAX_BUFFER_SIZE) {
        const truncated = filtered.subarray(
          0,
          MAX_BUFFER_SIZE - inputBuffer.totalBytes
        );
        inputBuffer.chunks.push(Buffer.from(truncated));
        inputBuffer.totalBytes += truncated.length;
        debugLogger164.debug(`Buffer truncated at ${MAX_BUFFER_SIZE} bytes`);
      } else {
        inputBuffer.chunks.push(Buffer.from(filtered));
        inputBuffer.totalBytes += filtered.length;
        debugLogger164.debug(
          `Captured ${filtered.length} bytes (total: ${inputBuffer.totalBytes})`
        );
      }
    }
  }, "captureHandler");
  captureStdin = process.stdin;
  captureStdin.on("data", captureHandler);
}
__name(startEarlyInputCapture, "startEarlyInputCapture");
function stopEarlyInputCapture() {
  if (!isCapturing || !captureHandler || !captureStdin) {
    return;
  }
  captureStdin.removeListener("data", captureHandler);
  captureStdin = null;
  captureHandler = null;
  isCapturing = false;
  inputBuffer.captured = true;
  debugLogger164.debug(
    `Stopped early input capture: ${inputBuffer.totalBytes} bytes`
  );
}
__name(stopEarlyInputCapture, "stopEarlyInputCapture");
function getAndClearCapturedInput() {
  const parts2 = [...inputBuffer.chunks];
  if (shouldReplayPendingAtStop(pendingTerminalResponse)) {
    parts2.push(Buffer.from(pendingTerminalResponse));
  }
  const buffer = parts2.length > 0 ? Buffer.concat(parts2) : Buffer.alloc(0);
  inputBuffer.chunks = [];
  inputBuffer.totalBytes = 0;
  pendingTerminalResponse = Buffer.alloc(0);
  return buffer;
}
__name(getAndClearCapturedInput, "getAndClearCapturedInput");
function stopAndGetCapturedInput() {
  stopEarlyInputCapture();
  return getAndClearCapturedInput();
}
__name(stopAndGetCapturedInput, "stopAndGetCapturedInput");

// packages/cli/src/utils/apiPreconnect.ts
init_esbuild_shims();
init_dist4();
var debugLogger165 = createDebugLogger("PRECONNECT");
var preconnectFired = false;
var DEFAULT_BASE_URLS = {
  openai: "https://api.openai.com",
  "qwen-oauth": "https://coding.dashscope.aliyuncs.com",
  anthropic: "https://api.anthropic.com",
  dashscope: "https://dashscope.aliyuncs.com"
};
var ALL_DEFAULT_URLS = [
  ...Object.values(DEFAULT_BASE_URLS),
  ...Object.values(ALIBABA_STANDARD_API_KEY_ENDPOINTS)
];
function shouldSkipPreconnect() {
  if (process.env["NODE_EXTRA_CA_CERTS"]) {
    debugLogger165.debug("Skipping preconnect: custom CA certificate configured");
    return true;
  }
  return false;
}
__name(shouldSkipPreconnect, "shouldSkipPreconnect");
function isInSandboxMode() {
  return process.env["SANDBOX"] !== void 0;
}
__name(isInSandboxMode, "isInSandboxMode");
function isDefaultBaseUrl(baseUrl) {
  const normalizedInput = baseUrl.toLowerCase().replace(/^https?:\/\//, "").replace(/\/+$/, "");
  return ALL_DEFAULT_URLS.some((defaultUrl) => {
    const normalizedDefault = defaultUrl.toLowerCase().replace(/^https?:\/\//, "").replace(/\/+$/, "");
    return normalizedInput === normalizedDefault || normalizedInput.startsWith(normalizedDefault + "/");
  });
}
__name(isDefaultBaseUrl, "isDefaultBaseUrl");
function getPreconnectTargetUrl(authType, resolvedBaseUrl) {
  if (resolvedBaseUrl && /^https?:\/\//i.test(resolvedBaseUrl)) {
    if (isDefaultBaseUrl(resolvedBaseUrl)) {
      return resolvedBaseUrl;
    }
    debugLogger165.debug(
      "Skipping preconnect: resolved baseUrl is not a default URL"
    );
    return void 0;
  }
  if (authType && DEFAULT_BASE_URLS[authType]) {
    return DEFAULT_BASE_URLS[authType];
  }
  return void 0;
}
__name(getPreconnectTargetUrl, "getPreconnectTargetUrl");
function preconnectApi(authType, options2 = {}) {
  if (preconnectFired) {
    return;
  }
  if (process.env["QWEN_CODE_DISABLE_PRECONNECT"] === "1") {
    debugLogger165.debug("Preconnect disabled by environment variable");
    preconnectFired = true;
    return;
  }
  if (isInSandboxMode()) {
    debugLogger165.debug("Skipping preconnect: sandbox mode detected");
    preconnectFired = true;
    return;
  }
  if (shouldSkipPreconnect()) {
    preconnectFired = true;
    return;
  }
  if (detectRuntime() !== "node") {
    debugLogger165.debug("Skipping preconnect: unsupported runtime");
    preconnectFired = true;
    return;
  }
  const targetUrl = getPreconnectTargetUrl(authType, options2.resolvedBaseUrl);
  if (!targetUrl) {
    debugLogger165.debug("No target URL for preconnect");
    return;
  }
  preconnectFired = true;
  debugLogger165.debug(`Preconnecting to: ${targetUrl}`);
  try {
    const dispatcher = getOrCreateSharedDispatcher(options2.proxy);
    fetch(targetUrl, {
      method: "HEAD",
      signal: AbortSignal.timeout(5e3),
      headers: {
        "User-Agent": "QwenCode-Preconnect/1.0"
      },
      dispatcher
    }).then(() => {
      debugLogger165.debug("Preconnect completed");
    }).catch((error40) => {
      debugLogger165.debug(`Preconnect failed (ignored): ${error40}`);
    });
  } catch (error40) {
    debugLogger165.debug(`Preconnect failed (ignored): ${error40}`);
  }
}
__name(preconnectApi, "preconnectApi");

// packages/cli/src/validateNonInterActiveAuth.ts
init_esbuild_shims();
init_dist4();
init_stdioHelpers();
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 err2 = validateAuthMethod(resolvedAuthType, nonInteractiveConfig);
      if (err2 != null) {
        throw new Error(err2);
      }
    }
    await nonInteractiveConfig.refreshAuth(resolvedAuthType);
    return nonInteractiveConfig;
  } catch (error40) {
    const outputFormat = nonInteractiveConfig.getOutputFormat();
    if (outputFormat === OutputFormat.JSON || outputFormat === OutputFormat.STREAM_JSON) {
      let adapter2;
      if (outputFormat === OutputFormat.JSON) {
        adapter2 = new JsonOutputAdapter(nonInteractiveConfig);
      } else {
        adapter2 = new StreamJsonOutputAdapter(
          nonInteractiveConfig,
          nonInteractiveConfig.getIncludePartialMessages()
        );
      }
      const errorMessage = error40 instanceof Error ? error40.message : String(error40);
      adapter2.emitResult({
        isError: true,
        errorMessage,
        durationMs: 0,
        apiDurationMs: 0,
        numTurns: 0,
        usage: void 0
      });
      await runExitCleanup();
      process.exit(1);
    }
    writeStderrLine(error40 instanceof Error ? error40.message : String(error40));
    process.exit(1);
  }
}
__name(validateNonInteractiveAuth, "validateNonInteractiveAuth");

// packages/cli/src/ui/components/StandaloneSessionPicker.tsx
init_esbuild_shims();
var import_react191 = __toESM(require_react(), 1);
init_dist4();
init_stdioHelpers();
var import_jsx_runtime151 = __toESM(require_jsx_runtime(), 1);
var PREVIEW_CONFIG_STUB = {
  getShouldUseNodePtyShell: /* @__PURE__ */ __name(() => false, "getShouldUseNodePtyShell"),
  getIdeMode: /* @__PURE__ */ __name(() => false, "getIdeMode"),
  isTrustedFolder: /* @__PURE__ */ __name(() => false, "isTrustedFolder"),
  getToolRegistry: /* @__PURE__ */ __name(() => ({ getTool: /* @__PURE__ */ __name(() => void 0, "getTool") }), "getToolRegistry"),
  getContentGenerator: /* @__PURE__ */ __name(() => ({ useSummarizedThinking: /* @__PURE__ */ __name(() => false, "useSummarizedThinking") }), "getContentGenerator")
};
var PREVIEW_SETTINGS_STUB = {
  merged: { ui: {} }
};
function StandalonePickerScreen({
  sessionService,
  onSelect,
  onCancel,
  currentBranch,
  initialSessions
}) {
  const { exit } = use_app_default();
  const [isExiting, setIsExiting] = (0, import_react191.useState)(false);
  const handleExit = /* @__PURE__ */ __name(() => {
    setIsExiting(true);
    exit();
  }, "handleExit");
  if (isExiting) {
    return /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(Box_default, {});
  }
  return /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(ConfigContext.Provider, { value: PREVIEW_CONFIG_STUB, children: /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(SettingsContext.Provider, { value: PREVIEW_SETTINGS_STUB, children: /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(
    SessionPicker,
    {
      sessionService,
      onSelect: (id) => {
        onSelect(id);
        handleExit();
      },
      onCancel: () => {
        onCancel();
        handleExit();
      },
      currentBranch,
      centerSelection: true,
      initialSessions,
      enablePreview: true
    }
  ) }) });
}
__name(StandalonePickerScreen, "StandalonePickerScreen");
function clearScreen3() {
  process.stdout.write("\x1B[2J\x1B[H");
}
__name(clearScreen3, "clearScreen");
async function showResumeSessionPicker(cwd6 = process.cwd(), initialSessions) {
  const sessionService = new SessionService(cwd6);
  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((resolve42) => {
    let selectedId;
    const { unmount, waitUntilExit } = render_default(
      /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(
        KeypressProvider,
        {
          kittyProtocolEnabled: false,
          pasteWorkaround: process.platform === "win32" || parseInt(process.versions.node.split(".")[0], 10) < 20,
          children: /* @__PURE__ */ (0, import_jsx_runtime151.jsx)(
            StandalonePickerScreen,
            {
              sessionService,
              onSelect: (id) => {
                selectedId = id;
              },
              onCancel: () => {
                selectedId = void 0;
              },
              currentBranch: getGitBranch(cwd6),
              initialSessions
            }
          )
        }
      ),
      {
        exitOnCtrlC: false
      }
    );
    waitUntilExit().then(() => {
      unmount();
      clearScreen3();
      if (process.stdin.isTTY && !wasRaw && !selectedId) {
        process.stdin.setRawMode(false);
      }
      resolve42(selectedId);
    });
  });
}
__name(showResumeSessionPicker, "showResumeSessionPicker");

// packages/cli/src/dualOutput/DualOutputBridge.ts
init_esbuild_shims();
init_dist4();
import {
  createWriteStream as createWriteStream6,
  fstatSync,
  openSync as openSync2,
  constants as constants4
} from "node:fs";

// packages/cli/src/nonInteractive/io/index.ts
init_esbuild_shims();

// packages/cli/src/dualOutput/DualOutputBridge.ts
var debugLogger166 = createDebugLogger("DUAL_OUTPUT");
var SUPPORTED_EVENTS = [
  "system",
  "user",
  "assistant",
  "stream_event",
  "result",
  "control_request",
  "control_response"
];
var DUAL_OUTPUT_PROTOCOL_VERSION = 1;
var DualOutputBridge = class {
  static {
    __name(this, "DualOutputBridge");
  }
  adapter;
  stream;
  sessionId;
  active = true;
  shutdownPromise = null;
  constructor(config2, target, options2 = {}) {
    this.sessionId = config2.getSessionId();
    if ("fd" in target) {
      if (target.fd <= 2) {
        throw new Error(
          `--json-fd ${target.fd}: file descriptors 0 (stdin), 1 (stdout), and 2 (stderr) are reserved. Use fd 3 or higher.`
        );
      }
      try {
        fstatSync(target.fd);
      } catch {
        throw new Error(
          `--json-fd ${target.fd}: file descriptor is not open. The caller must provide this fd via spawn stdio configuration or shell redirection (e.g., 3>/tmp/events.jsonl).`
        );
      }
      this.stream = createWriteStream6("", { fd: target.fd });
    } else {
      try {
        const fd = openSync2(
          target.filePath,
          constants4.O_WRONLY | constants4.O_NONBLOCK
        );
        this.stream = createWriteStream6("", { fd });
      } catch (err2) {
        const code2 = err2.code;
        if (code2 === "ENXIO" || code2 === "ENOENT") {
          this.stream = createWriteStream6(target.filePath, { flags: "w" });
        } else {
          throw err2;
        }
      }
    }
    this.stream.on("error", (err2) => {
      const code2 = err2.code;
      if (code2 === "EPIPE" || code2 === "ERR_STREAM_DESTROYED") {
        debugLogger166.warn("DualOutput: consumer disconnected, disabling");
      } else {
        debugLogger166.error("DualOutput stream error:", err2);
      }
      this.active = false;
    });
    this.adapter = new StreamJsonOutputAdapter(
      config2,
      true,
      // includePartialMessages — always emit streaming events
      this.stream
    );
    try {
      this.adapter.emitSystemMessage("session_start", {
        session_id: this.sessionId,
        cwd: process.cwd(),
        protocol_version: DUAL_OUTPUT_PROTOCOL_VERSION,
        version: options2.version,
        supported_events: [...SUPPORTED_EVENTS]
      });
    } catch (err2) {
      debugLogger166.error("DualOutput session_start error:", err2);
      this.active = false;
    }
  }
  processEvent(event) {
    if (!this.active) return;
    try {
      this.adapter.processEvent(event);
    } catch (err2) {
      debugLogger166.error("DualOutput processEvent error:", err2);
      this.active = false;
    }
  }
  startAssistantMessage() {
    if (!this.active) return;
    try {
      this.adapter.startAssistantMessage();
    } catch (err2) {
      debugLogger166.error("DualOutput startAssistantMessage error:", err2);
      this.active = false;
    }
  }
  finalizeAssistantMessage() {
    if (!this.active) return;
    try {
      this.adapter.finalizeAssistantMessage();
    } catch (err2) {
      debugLogger166.error("DualOutput finalizeAssistantMessage error:", err2);
      this.active = false;
    }
  }
  emitUserMessage(parts2) {
    if (!this.active) return;
    try {
      this.adapter.emitUserMessage(parts2);
    } catch (err2) {
      debugLogger166.error("DualOutput emitUserMessage error:", err2);
      this.active = false;
    }
  }
  emitToolResult(request4, response) {
    if (!this.active) return;
    try {
      this.adapter.emitToolResult(request4, response);
    } catch (err2) {
      debugLogger166.error("DualOutput emitToolResult error:", err2);
      this.active = false;
    }
  }
  /** Whether the underlying stream is still writable. */
  get isConnected() {
    return this.active;
  }
  /**
   * Emits a `can_use_tool` permission request so an external consumer can
   * approve or deny the tool call. Pairs with {@link emitControlResponse}.
   */
  emitPermissionRequest(requestId, toolName, toolUseId, input, blockedPath = null) {
    if (!this.active) return;
    try {
      this.adapter.emitPermissionRequest(
        requestId,
        toolName,
        toolUseId,
        input,
        blockedPath
      );
    } catch (err2) {
      debugLogger166.error("DualOutput emitPermissionRequest error:", err2);
      this.active = false;
    }
  }
  /**
   * Emits the result of a permission decision (made either in the TUI or by
   * the external consumer) so all observers stay in sync.
   */
  emitControlResponse(requestId, allowed) {
    if (!this.active) return;
    try {
      this.adapter.emitControlResponse(requestId, allowed);
    } catch (err2) {
      debugLogger166.error("DualOutput emitControlResponse error:", err2);
      this.active = false;
    }
  }
  /**
   * Emits a `control_response` with subtype `error` — used when an external
   * `confirmation_response` cannot be satisfied (unknown request_id, the
   * tool call already resolved, stream already closed, etc.). Lets
   * consumers retry or surface the error instead of silently hanging.
   */
  emitControlError(requestId, message) {
    if (!this.active) return;
    try {
      this.adapter.emitControlError(requestId, message);
    } catch (err2) {
      debugLogger166.error("DualOutput emitControlError error:", err2);
      this.active = false;
    }
  }
  /** General-purpose system event escape hatch. */
  emitSystemMessage(subtype, data) {
    if (!this.active) return;
    try {
      this.adapter.emitSystemMessage(subtype, data);
    } catch (err2) {
      debugLogger166.error("DualOutput emitSystemMessage error:", err2);
      this.active = false;
    }
  }
  shutdown() {
    if (this.shutdownPromise) return this.shutdownPromise;
    if (this.active) {
      try {
        this.adapter.emitSystemMessage("session_end", {
          session_id: this.sessionId
        });
      } catch {
      }
    }
    this.active = false;
    this.shutdownPromise = new Promise((resolve42) => {
      if (this.stream.closed) {
        resolve42();
        return;
      }
      const cleanup = /* @__PURE__ */ __name(() => {
        this.stream.off("close", onClose);
        this.stream.off("error", onError2);
      }, "cleanup");
      const onClose = /* @__PURE__ */ __name(() => {
        cleanup();
        resolve42();
      }, "onClose");
      const onError2 = /* @__PURE__ */ __name((err2) => {
        debugLogger166.debug("DualOutput: stream error during shutdown:", err2);
      }, "onError");
      this.stream.once("close", onClose);
      this.stream.once("error", onError2);
      try {
        this.stream.end();
      } catch (err2) {
        cleanup();
        debugLogger166.debug("DualOutput: stream end error during shutdown:", err2);
        resolve42();
      }
    });
    return this.shutdownPromise;
  }
};

// packages/cli/src/remoteInput/RemoteInputWatcher.ts
init_esbuild_shims();
init_dist4();
import { createReadStream as createReadStream3, watchFile as watchFile2, unwatchFile as unwatchFile2, statSync as statSync13 } from "node:fs";
import { createInterface as createInterface2 } from "node:readline";
var debugLogger167 = createDebugLogger("REMOTE_INPUT");
var RemoteInputWatcher = class {
  static {
    __name(this, "RemoteInputWatcher");
  }
  submitFn = null;
  confirmationHandler = null;
  queue = [];
  processing = false;
  active = true;
  bytesRead = 0;
  reading = false;
  filePath;
  retryTimer = null;
  pollIntervalMs;
  constructor(filePath, options2) {
    this.filePath = filePath;
    this.pollIntervalMs = options2?.pollIntervalMs ?? 500;
    this.startWatching();
  }
  /**
   * Register the TUI's submit function. Called from AppContainer
   * once useGeminiStream's submitQuery is available.
   */
  setSubmitFn(fn) {
    this.submitFn = fn;
    this.processQueue();
  }
  /**
   * Register the handler invoked when a `confirmation_response` command is
   * read from the input file. Used to bridge external approvals back into
   * the tool's `onConfirm` callback.
   */
  setConfirmationHandler(fn) {
    this.confirmationHandler = fn;
  }
  /**
   * Notify the watcher that the TUI has become idle.
   * Call this when streamingState transitions to Idle — it triggers
   * processing of any queued commands that were deferred due to TUI busy.
   */
  notifyIdle() {
    if (this.queue.length > 0 && !this.processing) {
      this.processQueue();
    }
  }
  startWatching() {
    try {
      const stat14 = statSync13(this.filePath);
      this.bytesRead = stat14.size;
    } catch {
      this.bytesRead = 0;
    }
    watchFile2(this.filePath, { interval: this.pollIntervalMs }, () => {
      if (!this.active) return;
      this.readNewLines();
    });
    debugLogger167.debug(`RemoteInput: watching ${this.filePath}`);
  }
  /**
   * Manually trigger a check for new input. Returns a promise that resolves
   * once any new lines have been read and processed. In production the
   * `watchFile` poll calls this automatically; tests can call it directly
   * to avoid depending on filesystem-polling timing.
   */
  checkForNewInput() {
    return this.readNewLines();
  }
  readNewLines() {
    if (!this.active || this.reading) return Promise.resolve();
    let currentSize;
    try {
      const stat14 = statSync13(this.filePath);
      currentSize = stat14.size;
    } catch {
      return Promise.resolve();
    }
    if (currentSize <= this.bytesRead) return Promise.resolve();
    this.reading = true;
    const stream5 = createReadStream3(this.filePath, {
      start: this.bytesRead,
      encoding: "utf-8"
    });
    const rl = createInterface2({ input: stream5, crlfDelay: Infinity });
    rl.on("line", (line) => {
      const trimmed2 = line.trim();
      if (!trimmed2) return;
      try {
        const cmd = JSON.parse(trimmed2);
        if (cmd && cmd.type === "confirmation_response" && typeof cmd.request_id === "string" && typeof cmd.allowed === "boolean") {
          debugLogger167.debug(
            `RemoteInput: confirmation_response for ${cmd.request_id} (allowed=${cmd.allowed})`
          );
          this.confirmationHandler?.(cmd.request_id, cmd.allowed);
        } else if (cmd && cmd.type === "submit" && typeof cmd.text === "string") {
          debugLogger167.debug(
            `RemoteInput: queued command: ${cmd.text.slice(0, 50)}...`
          );
          this.queue.push(
            cmd
          );
        } else {
          debugLogger167.warn(
            `RemoteInput: unknown command type: ${String(cmd?.type)}`
          );
        }
      } catch (_err) {
        debugLogger167.warn(`RemoteInput: failed to parse line: ${trimmed2}`);
      }
    });
    return new Promise((resolve42) => {
      rl.on("close", () => {
        this.bytesRead = currentSize;
        this.reading = false;
        this.processQueue();
        resolve42();
      });
    });
  }
  async processQueue() {
    if (this.processing || !this.submitFn || this.queue.length === 0) return;
    this.processing = true;
    if (this.retryTimer) {
      clearTimeout(this.retryTimer);
      this.retryTimer = null;
    }
    try {
      while (this.queue.length > 0 && this.active) {
        if (!this.submitFn) break;
        const cmd = this.queue[0];
        debugLogger167.debug(
          `RemoteInput: submitting: ${cmd.text.slice(0, 50)}...`
        );
        try {
          const result = await this.submitFn(cmd.text);
          if (result === false) {
            debugLogger167.debug("RemoteInput: TUI busy, will retry on idle");
            this.scheduleRetry();
            break;
          }
          this.queue.shift();
        } catch (err2) {
          debugLogger167.error("RemoteInput: submit failed:", err2);
          this.queue.shift();
        }
        if (this.queue.length > 0) {
          await new Promise((r5) => setTimeout(r5, 500));
        }
      }
    } finally {
      this.processing = false;
    }
  }
  scheduleRetry() {
    if (this.retryTimer) return;
    this.retryTimer = setTimeout(() => {
      this.retryTimer = null;
      if (this.queue.length > 0 && !this.processing) {
        this.processQueue();
      }
    }, 2e3);
  }
  shutdown() {
    this.active = false;
    unwatchFile2(this.filePath);
    if (this.retryTimer) clearTimeout(this.retryTimer);
    this.queue.length = 0;
    debugLogger167.debug("RemoteInput: shut down");
  }
};

// packages/cli/src/ui/utils/terminalRedrawOptimizer.ts
init_esbuild_shims();
var ESC5 = "\x1B[";
var ERASE_LINE = `${ESC5}2K`;
var CURSOR_UP_ONE = `${ESC5}1A`;
var CURSOR_DOWN_ONE = `${ESC5}1B`;
var CURSOR_LEFT = `${ESC5}G`;
var MULTILINE_ERASE_LINES_PATTERN = new RegExp(
  `(?:${escapeRegExp2(ERASE_LINE + CURSOR_UP_ONE)})+${escapeRegExp2(
    ERASE_LINE + CURSOR_LEFT
  )}`,
  "g"
);
function escapeRegExp2(value) {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
__name(escapeRegExp2, "escapeRegExp");
function countOccurrences2(value, search) {
  let count = 0;
  let index = 0;
  while ((index = value.indexOf(search, index)) !== -1) {
    count++;
    index += search.length;
  }
  return count;
}
__name(countOccurrences2, "countOccurrences");
var terminalRedrawStats = {
  stdoutWriteCount: 0,
  stdoutBytes: 0,
  clearTerminalCount: 0,
  eraseLinesOptimizedCount: 0
};
function getChunkByteLength(chunk, encodingOrCallback) {
  if (typeof chunk === "string") {
    const encoding = typeof encodingOrCallback === "string" ? encodingOrCallback : void 0;
    return Buffer.byteLength(chunk, encoding);
  }
  return chunk.byteLength;
}
__name(getChunkByteLength, "getChunkByteLength");
function optimizeMultilineEraseLinesWithCount(output) {
  let optimizedSequenceCount = 0;
  const optimizedOutput = output.replace(
    MULTILINE_ERASE_LINES_PATTERN,
    (sequence) => {
      const lineCount = countOccurrences2(sequence, ERASE_LINE);
      const cursorUpCount = lineCount - 1;
      if (cursorUpCount <= 1) {
        return sequence;
      }
      optimizedSequenceCount += 1;
      let boundedErase = `${ESC5}${cursorUpCount}A`;
      for (let line = 0; line < lineCount; line++) {
        boundedErase += ERASE_LINE;
        if (line < lineCount - 1) {
          boundedErase += CURSOR_DOWN_ONE;
        }
      }
      return `${boundedErase}${ESC5}${cursorUpCount}A${CURSOR_LEFT}`;
    }
  );
  return { output: optimizedOutput, optimizedSequenceCount };
}
__name(optimizeMultilineEraseLinesWithCount, "optimizeMultilineEraseLinesWithCount");
function installTerminalRedrawOptimizer(stdout2) {
  if (process.env["QWEN_CODE_LEGACY_ERASE_LINES"] === "1") {
    return () => {
    };
  }
  const originalWrite = stdout2.write;
  const optimizedWrite = /* @__PURE__ */ __name(function(chunk, encodingOrCallback, callback) {
    const optimizedResult = typeof chunk === "string" ? optimizeMultilineEraseLinesWithCount(chunk) : void 0;
    const optimizedChunk = optimizedResult?.output ?? chunk;
    if (typeof optimizedChunk === "string" || optimizedChunk instanceof Uint8Array || Buffer.isBuffer(optimizedChunk)) {
      terminalRedrawStats.stdoutWriteCount += 1;
      terminalRedrawStats.stdoutBytes += getChunkByteLength(
        optimizedChunk,
        encodingOrCallback
      );
      if (typeof optimizedChunk === "string") {
        terminalRedrawStats.clearTerminalCount += countOccurrences2(
          optimizedChunk,
          base_exports.clearTerminal
        );
      }
    }
    if (optimizedResult) {
      terminalRedrawStats.eraseLinesOptimizedCount += optimizedResult.optimizedSequenceCount;
    }
    return originalWrite.call(
      this,
      optimizedChunk,
      encodingOrCallback,
      callback
    );
  }, "optimizedWrite");
  stdout2.write = optimizedWrite;
  return () => {
    if (stdout2.write === optimizedWrite) {
      stdout2.write = originalWrite;
    }
  };
}
__name(installTerminalRedrawOptimizer, "installTerminalRedrawOptimizer");

// packages/cli/src/ui/utils/synchronizedOutput.ts
init_esbuild_shims();
var BEGIN_SYNCHRONIZED_UPDATE = "\x1B[?2026h";
var END_SYNCHRONIZED_UPDATE = "\x1B[?2026l";
var synchronizedOutputStats = {
  synchronizedOutputFrameCount: 0,
  synchronizedOutputBeginCount: 0,
  synchronizedOutputEndCount: 0
};
var installed = false;
function terminalSupportsSynchronizedOutput(env6 = process.env) {
  if (env6["QWEN_CODE_DISABLE_SYNCHRONIZED_OUTPUT"] === "1" || env6["QWEN_CODE_SYNCHRONIZED_OUTPUT"] === "0") {
    return false;
  }
  if (env6["QWEN_CODE_FORCE_SYNCHRONIZED_OUTPUT"] === "1" || env6["QWEN_CODE_SYNCHRONIZED_OUTPUT"] === "1") {
    return true;
  }
  if (env6["TMUX"] || env6["SSH_TTY"] || env6["SSH_CLIENT"]) {
    return false;
  }
  const termProgram = env6["TERM_PROGRAM"];
  if (termProgram === "WezTerm" || termProgram === "iTerm.app") {
    return true;
  }
  const term = env6["TERM"];
  return Boolean(env6["KITTY_WINDOW_ID"] || term?.includes("kitty"));
}
__name(terminalSupportsSynchronizedOutput, "terminalSupportsSynchronizedOutput");
function installSynchronizedOutput(stdout2 = process.stdout, env6 = process.env) {
  if (installed || !stdout2.isTTY || !terminalSupportsSynchronizedOutput(env6)) {
    return () => {
    };
  }
  const originalWrite = stdout2.write;
  let inFrame = false;
  const writeControlSequence = /* @__PURE__ */ __name((sequence) => {
    originalWrite.call(stdout2, sequence);
  }, "writeControlSequence");
  const endFrame = /* @__PURE__ */ __name(() => {
    if (!inFrame) {
      return;
    }
    inFrame = false;
    synchronizedOutputStats.synchronizedOutputEndCount += 1;
    writeControlSequence(END_SYNCHRONIZED_UPDATE);
  }, "endFrame");
  const patchedWrite = /* @__PURE__ */ __name(function(chunk, encodingOrCallback, callback) {
    if (!inFrame) {
      inFrame = true;
      synchronizedOutputStats.synchronizedOutputFrameCount += 1;
      synchronizedOutputStats.synchronizedOutputBeginCount += 1;
      writeControlSequence(BEGIN_SYNCHRONIZED_UPDATE);
      queueMicrotask(endFrame);
    }
    return originalWrite.call(
      this,
      chunk,
      encodingOrCallback,
      callback
    );
  }, "patchedWrite");
  const exitHandler = /* @__PURE__ */ __name(() => {
    try {
      endFrame();
    } catch {
    }
  }, "exitHandler");
  stdout2.write = patchedWrite;
  installed = true;
  process.once("exit", exitHandler);
  return () => {
    if (stdout2.write === patchedWrite) {
      endFrame();
      stdout2.write = originalWrite;
    }
    process.removeListener("exit", exitHandler);
    installed = false;
  };
}
__name(installSynchronizedOutput, "installSynchronizedOutput");

// packages/cli/src/acp-integration/acpAgent.ts
init_esbuild_shims();
init_dist4();
init_acp();

// packages/cli/src/acp-integration/authMethods.ts
init_esbuild_shims();
init_dist4();
function buildAuthMethods() {
  return [
    {
      id: AuthType2.USE_OPENAI,
      name: "Use OpenAI API key",
      description: "Requires setting the `OPENAI_API_KEY` environment variable",
      _meta: {
        type: "terminal",
        args: ["--auth-type=openai"]
      }
    },
    {
      id: AuthType2.QWEN_OAUTH,
      name: "Qwen OAuth",
      description: "Qwen OAuth (free tier discontinued 2026-04-15)",
      _meta: {
        type: "terminal",
        args: ["--auth-type=qwen-oauth"]
      }
    }
  ];
}
__name(buildAuthMethods, "buildAuthMethods");

// packages/cli/src/acp-integration/service/filesystem.ts
init_esbuild_shims();
init_acp();
var RESOURCE_NOT_FOUND_CODE = -32002;
function getErrorCode3(error40) {
  if (error40 instanceof RequestError) {
    return error40.code;
  }
  if (typeof error40 === "object" && error40 !== null && "code" in error40) {
    return error40.code;
  }
  return void 0;
}
__name(getErrorCode3, "getErrorCode");
function createEnoentError(filePath) {
  const err2 = new Error(`File not found: ${filePath}`);
  err2.code = "ENOENT";
  err2.errno = -2;
  err2.path = filePath;
  return err2;
}
__name(createEnoentError, "createEnoentError");
var AcpFileSystemService = class {
  constructor(connection, sessionId, capabilities, fallback) {
    this.connection = connection;
    this.sessionId = sessionId;
    this.capabilities = capabilities;
    this.fallback = fallback;
  }
  static {
    __name(this, "AcpFileSystemService");
  }
  async readTextFile(params) {
    if (!this.capabilities.readTextFile) {
      return this.fallback.readTextFile(params);
    }
    let response;
    try {
      response = await this.connection.readTextFile({
        ...params,
        sessionId: this.sessionId
      });
    } catch (error40) {
      const errorCode = getErrorCode3(error40);
      if (errorCode === RESOURCE_NOT_FOUND_CODE) {
        throw createEnoentError(params.path);
      }
      throw error40;
    }
    return response;
  }
  async writeTextFile(params) {
    if (!this.capabilities.writeTextFile) {
      return this.fallback.writeTextFile(params);
    }
    const finalContent = params._meta?.["bom"] ? "\uFEFF" + params.content : params.content;
    await this.connection.writeTextFile({
      ...params,
      content: finalContent,
      sessionId: this.sessionId
    });
    return { _meta: params._meta };
  }
  findFiles(fileName, searchPaths) {
    return this.fallback.findFiles(fileName, searchPaths);
  }
};

// packages/cli/src/acp-integration/acpAgent.ts
import { Readable as Readable7, Writable as Writable3 } from "node:stream";
init_zod();

// packages/cli/src/acp-integration/session/Session.ts
init_esbuild_shims();
init_dist4();
init_acp();
init_zod();
init_types21();

// packages/cli/src/utils/acpModelUtils.ts
init_esbuild_shims();
init_dist4();
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_dist4();
init_zod();

// packages/cli/src/acp-integration/session/permissionUtils.ts
init_esbuild_shims();
init_dist4();
var basicPermissionOptions = [
  {
    optionId: ToolConfirmationOutcome.ProceedOnce,
    name: "Allow",
    kind: "allow_once"
  },
  {
    optionId: ToolConfirmationOutcome.Cancel,
    name: "Reject",
    kind: "reject_once"
  }
];
function supportsHideAlwaysAllow(confirmation) {
  return confirmation.type !== "ask_user_question";
}
__name(supportsHideAlwaysAllow, "supportsHideAlwaysAllow");
function filterAlwaysAllowOptions(confirmation, options2, forceHideAlwaysAllow = false) {
  const hideAlwaysAllow = forceHideAlwaysAllow || supportsHideAlwaysAllow(confirmation) && confirmation.hideAlwaysAllow === true;
  return hideAlwaysAllow ? options2.filter((option2) => option2.kind !== "allow_always") : options2;
}
__name(filterAlwaysAllowOptions, "filterAlwaysAllowOptions");
function formatExecPermissionScopeLabel(confirmation) {
  const permissionRules = confirmation.permissionRules ?? [];
  const bashRules = permissionRules.map((rule) => {
    const match2 = /^Bash\((.*)\)$/.exec(rule.trim());
    return match2?.[1]?.trim() || void 0;
  }).filter((rule) => Boolean(rule));
  const uniqueRules = [...new Set(bashRules)];
  if (uniqueRules.length === 1) {
    return uniqueRules[0];
  }
  if (uniqueRules.length > 1) {
    return uniqueRules.join(", ");
  }
  return confirmation.rootCommand;
}
__name(formatExecPermissionScopeLabel, "formatExecPermissionScopeLabel");
function buildPermissionRequestContent(confirmation) {
  const content = [];
  if (confirmation.type === "edit") {
    content.push({
      type: "diff",
      path: confirmation.filePath ?? confirmation.fileName,
      oldText: confirmation.originalContent ?? "",
      newText: confirmation.newContent
    });
  }
  if (confirmation.type === "plan") {
    content.push({
      type: "content",
      content: {
        type: "text",
        text: confirmation.plan
      }
    });
  }
  return content;
}
__name(buildPermissionRequestContent, "buildPermissionRequestContent");
function toPermissionOptions(confirmation, forceHideAlwaysAllow = false) {
  switch (confirmation.type) {
    case "edit":
      return filterAlwaysAllowOptions(
        confirmation,
        [
          {
            optionId: ToolConfirmationOutcome.ProceedAlways,
            name: "Allow All Edits",
            kind: "allow_always"
          },
          ...basicPermissionOptions
        ],
        forceHideAlwaysAllow
      );
    case "exec": {
      const label = formatExecPermissionScopeLabel(confirmation);
      return filterAlwaysAllowOptions(
        confirmation,
        [
          {
            optionId: ToolConfirmationOutcome.ProceedAlwaysProject,
            name: `Always Allow in project: ${label}`,
            kind: "allow_always"
          },
          {
            optionId: ToolConfirmationOutcome.ProceedAlwaysUser,
            name: `Always Allow for user: ${label}`,
            kind: "allow_always"
          },
          ...basicPermissionOptions
        ],
        forceHideAlwaysAllow
      );
    }
    case "mcp":
      return filterAlwaysAllowOptions(
        confirmation,
        [
          {
            optionId: ToolConfirmationOutcome.ProceedAlwaysProject,
            name: `Always Allow in project: ${confirmation.toolName}`,
            kind: "allow_always"
          },
          {
            optionId: ToolConfirmationOutcome.ProceedAlwaysUser,
            name: `Always Allow for user: ${confirmation.toolName}`,
            kind: "allow_always"
          },
          ...basicPermissionOptions
        ],
        forceHideAlwaysAllow
      );
    case "info":
      return filterAlwaysAllowOptions(
        confirmation,
        [
          {
            optionId: ToolConfirmationOutcome.ProceedAlwaysProject,
            name: "Always Allow in project",
            kind: "allow_always"
          },
          {
            optionId: ToolConfirmationOutcome.ProceedAlwaysUser,
            name: "Always Allow for user",
            kind: "allow_always"
          },
          ...basicPermissionOptions
        ],
        forceHideAlwaysAllow
      );
    case "plan":
      return [
        {
          optionId: ToolConfirmationOutcome.RestorePrevious,
          name: `Yes, restore previous mode (${confirmation.prePlanMode ?? "default"})`,
          kind: "allow_once"
        },
        {
          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"
        }
      ];
    case "ask_user_question":
      return [
        {
          optionId: ToolConfirmationOutcome.ProceedOnce,
          name: "Submit",
          kind: "allow_once"
        },
        {
          optionId: ToolConfirmationOutcome.Cancel,
          name: "Cancel",
          kind: "reject_once"
        }
      ];
    default: {
      const unreachable = confirmation;
      throw new Error(`Unexpected: ${unreachable}`);
    }
  }
}
__name(toPermissionOptions, "toPermissionOptions");

// packages/cli/src/acp-integration/session/SubAgentTracker.ts
var debugLogger168 = createDebugLogger("ACP_SUBAGENT_TRACKER");
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 AgentEventEmitter from AgentTool
   * @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(AgentEventType.TOOL_CALL, onToolCall);
    eventEmitter.on(AgentEventType.TOOL_RESULT, onToolResult);
    eventEmitter.on(AgentEventType.TOOL_WAITING_APPROVAL, onApproval);
    eventEmitter.on(AgentEventType.USAGE_METADATA, onUsageMetadata);
    eventEmitter.on(AgentEventType.STREAM_TEXT, onStreamText);
    return [
      () => {
        eventEmitter.off(AgentEventType.TOOL_CALL, onToolCall);
        eventEmitter.off(AgentEventType.TOOL_RESULT, onToolResult);
        eventEmitter.off(AgentEventType.TOOL_WAITING_APPROVAL, onApproval);
        eventEmitter.off(AgentEventType.USAGE_METADATA, onUsageMetadata);
        eventEmitter.off(AgentEventType.STREAM_TEXT, onStreamText);
        this.toolStates.clear();
      }
    ];
  }
  /**
   * Creates a handler for tool call start events.
   */
  createToolCallHandler(abortSignal) {
    return (...args2) => {
      const event = args2[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) {
          debugLogger168.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 (...args2) => {
      const event = args2[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 (...args2) => {
      const event = args2[0];
      if (abortSignal.aborted) return;
      const state = this.toolStates.get(event.callId);
      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: toPermissionOptions(fullConfirmationDetails),
        toolCall: {
          toolCallId: event.callId,
          status: "pending",
          title,
          content: buildPermissionRequestContent(fullConfirmationDetails),
          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, {
          answers: "answers" in output ? output.answers : void 0
        });
      } catch (error40) {
        debugLogger168.error(
          `Permission request failed for subagent tool ${event.name}:`,
          error40
        );
        await event.respond(ToolConfirmationOutcome.Cancel);
      }
    };
  }
  /**
   * Creates a handler for usage metadata events.
   */
  createUsageMetadataHandler(abortSignal) {
    return (...args2) => {
      const event = args2[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 (...args2) => {
      const event = args2[0];
      if (abortSignal.aborted) return;
      void this.messageEmitter.emitMessage(
        event.text,
        "assistant",
        event.thought ?? false
      );
    };
  }
};

// packages/cli/src/acp-integration/session/rewrite/index.ts
init_esbuild_shims();

// packages/cli/src/acp-integration/session/rewrite/MessageRewriteMiddleware.ts
init_esbuild_shims();
init_dist4();

// packages/cli/src/acp-integration/session/rewrite/TurnBuffer.ts
init_esbuild_shims();
var TurnBuffer = class {
  static {
    __name(this, "TurnBuffer");
  }
  thoughts = [];
  messages = [];
  _hasToolCalls = false;
  appendThought(text) {
    if (text) this.thoughts.push(text);
  }
  appendMessage(text) {
    if (text) this.messages.push(text);
  }
  markToolCall() {
    this._hasToolCalls = true;
  }
  /**
   * Returns accumulated content and resets the buffer.
   * Returns null if buffer is empty.
   */
  flush() {
    const thoughtText = this.thoughts.join("");
    const messageText = this.messages.join("");
    if (!thoughtText.trim() && !messageText.trim()) {
      this.reset();
      return null;
    }
    const content = {
      thoughts: this.thoughts.filter((t5) => t5.trim()),
      messages: this.messages.filter((m3) => m3.trim()),
      hasToolCalls: this._hasToolCalls
    };
    this.reset();
    return content;
  }
  reset() {
    this.thoughts = [];
    this.messages = [];
    this._hasToolCalls = false;
  }
  get isEmpty() {
    return this.thoughts.length === 0 && this.messages.length === 0;
  }
};

// packages/cli/src/acp-integration/session/rewrite/LlmRewriter.ts
init_esbuild_shims();
init_dist4();
import { readFileSync as readFileSync35, existsSync as existsSync44 } from "node:fs";
import { resolve as resolve41 } from "node:path";
var debugLogger169 = createDebugLogger("MESSAGE_REWRITER");
var DEFAULT_REWRITE_PROMPT = `You are an assistant that rewrites raw coding-agent output into concise, user-friendly progress updates.

The agent is a software engineering assistant that reads files, writes code, runs commands, and uses tools. Its raw output mixes internal reasoning with user-facing information. Your job: extract what the user cares about, drop what they don't.

## Rules

1. **Strictly based on original**: only surface information already in the input. Never invent details, plans, or conclusions the agent didn't state.
2. **Keep**: goals, decisions, key findings, results, errors that affect the user, status updates.
3. **Drop**: file paths, tool/skill names, internal reasoning about which tool to call, code snippets, stack traces, "let me\u2026" / "now I'll\u2026" filler phrases.
4. **Progress turns**: if the agent is just starting a step (reading files, running a command, exploring code), output one short sentence describing what's happening \u2014 so the user isn't staring at silence.
5. **Rich content**: if the input already contains well-structured user-facing content (tables, lists, formatted results), do light cleanup only (remove stray paths/tool names) and preserve the structure.
6. **Pure internal ops**: if the input is entirely internal (fixing a typo in its own code, retrying a failed tool call, creating temp directories) \u2192 return empty string.
7. **Preserve data exactly**: never alter numbers, percentages, file sizes, error codes, or quoted output.

## Context continuity

If "Previous rewrite output" is provided, the user has already seen it. Don't repeat \u2014 build on it. If this turn adds nothing new, return empty string.

Output only the rewritten text, or empty string if the input has no user-facing value.`;
var LlmRewriter = class {
  constructor(config2, rewriteConfig) {
    this.config = config2;
    this.rewriteModel = rewriteConfig.model || void 0;
    this.contextTurns = rewriteConfig.contextTurns === "all" ? Infinity : rewriteConfig.contextTurns ?? 1;
    if (rewriteConfig.promptFile) {
      const filePath = resolve41(rewriteConfig.promptFile);
      if (existsSync44(filePath)) {
        this.prompt = readFileSync35(filePath, "utf-8").trim();
        debugLogger169.info(
          `Loaded rewrite prompt from file: ${filePath} (${this.prompt.length} chars)`
        );
      } else {
        debugLogger169.warn(
          `Rewrite prompt file not found: ${filePath}, using default`
        );
        this.prompt = DEFAULT_REWRITE_PROMPT;
      }
    } else {
      this.prompt = rewriteConfig.prompt || DEFAULT_REWRITE_PROMPT;
    }
  }
  static {
    __name(this, "LlmRewriter");
  }
  prompt;
  /** Previous successful rewrite outputs, used as context for coherence */
  outputHistory = [];
  /** How many previous outputs to include: 0=none, N=last N, Infinity=all */
  contextTurns;
  rewriteModel;
  /**
   * Rewrite a turn's content using LLM.
   * Returns null if the turn has no valuable content for users.
   */
  async rewrite(turnContent, signal) {
    const inputParts = [];
    if (turnContent.thoughts.length > 0) {
      inputParts.push("[\u5185\u90E8\u63A8\u7406]\n" + turnContent.thoughts.join("\n"));
    }
    if (turnContent.messages.length > 0) {
      inputParts.push("[\u56DE\u590D\u6587\u672C]\n" + turnContent.messages.join("\n"));
    }
    if (this.contextTurns > 0 && this.outputHistory.length > 0) {
      const contextSlice = this.contextTurns === Infinity ? this.outputHistory : this.outputHistory.slice(-this.contextTurns);
      inputParts.unshift("[\u4E0A\u4E00\u8F6E\u6539\u5199\u7ED3\u679C]\n" + contextSlice.join("\n---\n"));
    }
    const inputText = inputParts.join("\n\n");
    if (!inputText.trim()) return null;
    if (inputText.length < 10) return null;
    debugLogger169.info(
      `[REWRITE INPUT] system_prompt_len=${this.prompt.length} input_len=${inputText.length} context_turns=${this.outputHistory.length}
--- INPUT TEXT ---
${inputText}
---`
    );
    try {
      const contentGenerator = this.config.getContentGenerator();
      if (!contentGenerator) {
        debugLogger169.warn("No content generator available for rewriting");
        return null;
      }
      const model = this.rewriteModel || this.config.getModel();
      const result = await contentGenerator.generateContent(
        {
          model,
          config: {
            systemInstruction: this.prompt,
            abortSignal: signal,
            temperature: 0.3,
            maxOutputTokens: 1024,
            // Disable thinking to avoid thinking leaking into output
            thinkingConfig: { includeThoughts: false }
          },
          contents: [
            {
              role: "user",
              parts: [{ text: inputText }]
            }
          ]
        },
        `rewrite-turn`
      );
      const rewritten = result.candidates?.[0]?.content?.parts?.filter((p2) => !p2.thought).map((p2) => p2.text).filter(Boolean).join("") ?? "";
      if (!rewritten.trim() || rewritten.trim().length < 5) {
        debugLogger169.info(`[REWRITE OUTPUT] empty or too short, skipping`);
        return null;
      }
      const trimmed2 = rewritten.trim();
      debugLogger169.info(
        `[REWRITE OUTPUT] len=${trimmed2.length}
--- OUTPUT ---
${trimmed2}
---`
      );
      this.outputHistory.push(trimmed2);
      return trimmed2;
    } catch (error40) {
      debugLogger169.warn(
        `LLM rewrite failed, skipping: ${error40 instanceof Error ? error40.message : String(error40)}`
      );
      return null;
    }
  }
};

// packages/cli/src/acp-integration/session/rewrite/MessageRewriteMiddleware.ts
var debugLogger170 = createDebugLogger("MESSAGE_REWRITE");
var DEFAULT_REWRITE_TIMEOUT_MS = 3e4;
var MessageRewriteMiddleware = class {
  constructor(config2, rewriteConfig, sendUpdate) {
    this.sendUpdate = sendUpdate;
    this.turnBuffer = new TurnBuffer();
    this.rewriter = new LlmRewriter(config2, rewriteConfig);
    this.target = rewriteConfig.target;
    this.timeoutMs = rewriteConfig.timeoutMs ?? DEFAULT_REWRITE_TIMEOUT_MS;
  }
  static {
    __name(this, "MessageRewriteMiddleware");
  }
  turnBuffer;
  rewriter;
  target;
  timeoutMs;
  turnIndex = 0;
  /**
   * Intercept an ACP update. Original messages pass through,
   * thought/message chunks are also accumulated for turn-end rewriting.
   */
  async interceptUpdate(update2, signal) {
    const updateRecord2 = update2;
    const updateType = updateRecord2["sessionUpdate"];
    if (updateType === "tool_call") {
      await this.flushTurn(signal);
      this.turnBuffer.markToolCall();
      return this.sendUpdate(update2);
    }
    if (updateType !== "agent_thought_chunk" && updateType !== "agent_message_chunk") {
      return this.sendUpdate(update2);
    }
    const content = updateRecord2["content"];
    const text = content?.["text"] ?? "";
    await this.sendUpdate(update2);
    if (updateType === "agent_thought_chunk") {
      if (this.target === "thought" || this.target === "all") {
        this.turnBuffer.appendThought(text);
      }
    } else if (updateType === "agent_message_chunk") {
      if (this.target === "message" || this.target === "all") {
        this.turnBuffer.appendMessage(text);
      }
    }
  }
  /** Pending rewrite promises — all must settle before session exits */
  pendingRewrites = [];
  /**
   * Flush the turn buffer: rewrite accumulated content and emit.
   *
   * Non-blocking: rewrite runs in background, parallel to tool execution.
   *
   * Called when:
   * - A tool_call is about to be emitted (turn boundary)
   * - Usage metadata is emitted (end of model response)
   * - Session prompt ends
   */
  async flushTurn(signal) {
    const content = this.turnBuffer.flush();
    if (!content) return;
    this.turnIndex++;
    const turnIdx = this.turnIndex;
    const timeoutSignal = AbortSignal.timeout(this.timeoutMs);
    const rewriteSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
    this.pendingRewrites.push(
      (async () => {
        try {
          const rewritten = await this.rewriter.rewrite(content, rewriteSignal);
          if (!rewritten) {
            debugLogger170.info(`Turn ${turnIdx}: no rewrite output`);
            return;
          }
          debugLogger170.info(
            `Turn ${turnIdx}: rewritten ${rewritten.length} chars`
          );
          await this.sendUpdate({
            sessionUpdate: "agent_message_chunk",
            content: { type: "text", text: rewritten },
            _meta: {
              rewritten: true,
              turnIndex: turnIdx
            }
          });
        } catch (error40) {
          debugLogger170.warn(
            `Turn ${turnIdx}: rewrite failed: ${error40 instanceof Error ? error40.message : String(error40)}`
          );
        }
      })()
    );
  }
  /**
   * Wait for all pending rewrites to complete.
   * Call this before session ends to ensure all rewrites are flushed.
   */
  async waitForPendingRewrites() {
    if (this.pendingRewrites.length > 0) {
      await Promise.allSettled(this.pendingRewrites);
      this.pendingRewrites = [];
    }
  }
};

// packages/cli/src/acp-integration/session/rewrite/config.ts
init_esbuild_shims();
function loadRewriteConfig(settings) {
  const userOriginal = settings.user?.originalSettings;
  const workspaceOriginal = settings.isTrusted ? settings.workspace?.originalSettings : void 0;
  return workspaceOriginal?.["messageRewrite"] ?? userOriginal?.["messageRewrite"];
}
__name(loadRewriteConfig, "loadRewriteConfig");

// packages/cli/src/acp-integration/session/Session.ts
var debugLogger171 = createDebugLogger("SESSION");
var Session3 = class {
  constructor(id, config2, client, settings) {
    this.config = config2;
    this.client = client;
    this.settings = settings;
    this.sessionId = id;
    this.runtimeBaseDir = Storage.getRuntimeBaseDir();
    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;
  /**
   * Tracks the completion of the current prompt so that the next prompt
   * can await it.  This prevents a new prompt from reading chat history
   * before the previous prompt's tool results have been added —
   * a race condition that causes malformed history on Windows where
   * process termination is slow.
   */
  pendingPromptCompletion = null;
  turn = 0;
  runtimeBaseDir;
  // Cron scheduling state
  cronQueue = [];
  cronProcessing = false;
  cronAbortController = null;
  cronCompletion = null;
  // Modular components
  historyReplayer;
  toolCallEmitter;
  planEmitter;
  messageEmitter;
  // Message rewrite middleware (optional, installed after history replay)
  messageRewriter;
  // Implement SessionContext interface
  sessionId;
  getId() {
    return this.sessionId;
  }
  getConfig() {
    return this.config;
  }
  /**
   * Install the message rewrite middleware if configured.
   * Must be called AFTER history replay to avoid rewriting historical messages.
   */
  installRewriter() {
    const rewriteConfig = loadRewriteConfig(this.settings);
    if (rewriteConfig?.enabled) {
      debugLogger171.info("Message rewrite middleware enabled");
      this.messageRewriter = new MessageRewriteMiddleware(
        this.config,
        rewriteConfig,
        (update2) => this.sendUpdate(update2)
      );
    }
  }
  /**
   * 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() {
    const hadPrompt = !!this.pendingPrompt;
    const hadCron = !!this.cronAbortController;
    if (!hadPrompt && !hadCron) {
      throw new Error("Not currently generating");
    }
    if (this.pendingPrompt) {
      this.pendingPrompt.abort();
      this.pendingPrompt = null;
    }
    if (this.cronAbortController) {
      this.cronAbortController.abort();
      this.cronAbortController = null;
      this.cronQueue = [];
      this.cronProcessing = false;
    }
    const scheduler = this.config.isCronEnabled() ? this.config.getCronScheduler() : null;
    if (scheduler) {
      const summary = scheduler.getExitSummary();
      scheduler.stop();
      if (summary) {
        await this.messageEmitter.emitAgentMessage(summary);
      }
    }
  }
  async prompt(params) {
    this.pendingPrompt?.abort();
    const pendingSend = new AbortController();
    this.pendingPrompt = pendingSend;
    if (this.cronAbortController) {
      this.cronAbortController.abort();
      this.cronAbortController = null;
      this.cronQueue = [];
      this.cronProcessing = false;
    }
    if (this.cronCompletion) {
      try {
        await this.cronCompletion;
      } catch {
      }
      this.cronCompletion = null;
    }
    if (this.pendingPromptCompletion) {
      try {
        await this.pendingPromptCompletion;
      } catch {
      }
    }
    if (pendingSend.signal.aborted) {
      return { stopReason: "cancelled" };
    }
    let resolveCompletion;
    this.pendingPromptCompletion = new Promise((resolve42) => {
      resolveCompletion = resolve42;
    });
    try {
      const result = await this.#executePrompt(params, pendingSend);
      this.pendingPrompt = null;
      this.#startCronSchedulerIfNeeded();
      void this.#drainCronQueue();
      return result;
    } finally {
      resolveCompletion();
    }
  }
  async #executePrompt(params, pendingSend) {
    return Storage.runWithRuntimeBaseDir(
      this.runtimeBaseDir,
      this.config.getWorkingDir(),
      async () => {
        this.turn += 1;
        const chat = this.config.getGeminiClient().getChat();
        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 parts2;
        if (isSlashCommand(inputText)) {
          const slashCommandResult = await handleSlashCommand(
            inputText,
            pendingSend,
            this.config,
            this.settings
          );
          parts2 = await this.#processSlashCommandResult(
            slashCommandResult,
            params.prompt
          );
          if (parts2 === null) {
            return { stopReason: "end_turn" };
          }
        } else {
          parts2 = await this.#resolvePrompt(params.prompt, pendingSend.signal);
        }
        const hooksEnabled = !this.config.getDisableAllHooks?.();
        const messageBus = this.config.getMessageBus?.();
        if (hooksEnabled && messageBus && this.config.hasHooksForEvent?.("UserPromptSubmit")) {
          const response = await messageBus.request(
            {
              type: MessageBusType.HOOK_EXECUTION_REQUEST,
              eventName: "UserPromptSubmit",
              input: {
                prompt: promptText
              },
              signal: pendingSend.signal
            },
            MessageBusType.HOOK_EXECUTION_RESPONSE
          );
          const hookOutput = response.output ? createHookOutput("UserPromptSubmit", response.output) : void 0;
          if (hookOutput?.isBlockingDecision() || hookOutput?.shouldStopExecution()) {
            const blockReason = hookOutput?.getEffectiveReason() || "No reason provided";
            await this.messageEmitter.emitAgentMessage(
              `\u{1F6AB} **UserPromptSubmit blocked**: ${blockReason}`
            );
            return { stopReason: "end_turn" };
          }
          const additionalContext = hookOutput?.getAdditionalContext();
          if (additionalContext) {
            parts2 = [...parts2, { text: additionalContext }];
          }
        }
        const systemReminders = await this.#buildInitialSystemReminders();
        if (systemReminders.length > 0) {
          parts2 = [...systemReminders, ...parts2];
        }
        let nextMessage = { role: "user", parts: parts2 };
        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 (error40) {
            const errorStatus = getErrorStatus(error40);
            const errorMessage = error40 instanceof Error ? error40.message : String(error40);
            const errorType = classifyApiError({
              message: errorMessage,
              status: errorStatus
            });
            const hookSystem = this.config.getHookSystem?.();
            const hooksEnabledForStopFailure = !this.config.getDisableAllHooks?.();
            if (hooksEnabledForStopFailure && hookSystem && this.config.hasHooksForEvent?.("StopFailure")) {
              hookSystem.fireStopFailureEvent(errorType, errorMessage).catch((err2) => {
                debugLogger171.warn(`StopFailure hook failed: ${err2}`);
              });
            }
            if (errorStatus === 429) {
              throw new RequestError(
                429,
                "Rate limit exceeded. Try again later."
              );
            }
            throw error40;
          }
          if (usageMetadata) {
            if (this.messageRewriter) {
              this.messageRewriter.flushTurn(pendingSend.signal);
            }
            const durationMs = Date.now() - streamStartTime;
            await this.messageEmitter.emitUsageMetadata(
              usageMetadata,
              "",
              durationMs
            );
          }
          if (functionCalls.length > 0) {
            const toolResponseParts = await this.runToolCalls(
              pendingSend.signal,
              promptId,
              functionCalls
            );
            nextMessage = { role: "user", parts: toolResponseParts };
          }
        }
        if (this.messageRewriter) {
          await this.messageRewriter.waitForPendingRewrites();
        }
        return this.#handleStopHookLoop(
          chat,
          pendingSend,
          promptId,
          hooksEnabled,
          messageBus
        );
      }
    );
  }
  /**
   * Handles the Stop hook iteration loop.
   * This method processes Stop hooks after a model response completes with no pending tool calls.
   * If a Stop hook requests continuation, it sends a follow-up message and loops back.
   * Maximum iterations (100) prevent infinite loops.
   *
   * @param chat - The GeminiChat instance
   * @param pendingSend - The abort controller for the current prompt
   * @param promptId - The prompt ID for tracking
   * @param hooksEnabled - Whether hooks are enabled
   * @param messageBus - The MessageBus for hook communication (may be undefined)
   * @returns The stop reason ('end_turn' or 'cancelled')
   */
  async #handleStopHookLoop(chat, pendingSend, promptId, hooksEnabled, messageBus) {
    const MAX_STOP_HOOK_ITERATIONS = 100;
    let stopHookIterationCount = 0;
    let stopHookReasons = [];
    while (stopHookIterationCount < MAX_STOP_HOOK_ITERATIONS) {
      if (!hooksEnabled || !messageBus || pendingSend.signal.aborted || !this.config.hasHooksForEvent?.("Stop")) {
        return { stopReason: "end_turn" };
      }
      const history = chat.getHistory();
      const lastModelMessage = history.filter((msg) => msg.role === "model").pop();
      const responseText = lastModelMessage?.parts?.filter((p2) => "text" in p2).map((p2) => p2.text).join("") || "[no response text]";
      const response = await messageBus.request(
        {
          type: MessageBusType.HOOK_EXECUTION_REQUEST,
          eventName: "Stop",
          input: {
            stop_hook_active: true,
            last_assistant_message: responseText
          },
          signal: pendingSend.signal
        },
        MessageBusType.HOOK_EXECUTION_RESPONSE
      );
      if (pendingSend.signal.aborted) {
        return { stopReason: "cancelled" };
      }
      const hookOutput = response.output ? createHookOutput("Stop", response.output) : void 0;
      const stopOutput = hookOutput;
      if (stopOutput?.systemMessage) {
        await this.messageEmitter.emitAgentMessage(stopOutput.systemMessage);
      }
      if (stopOutput?.isBlockingDecision() || stopOutput?.shouldStopExecution()) {
        const continueReason = stopOutput.getEffectiveReason();
        stopHookIterationCount++;
        stopHookReasons = [...stopHookReasons, continueReason];
        if (stopHookIterationCount > 1) {
          await this.messageEmitter.emitStopHookLoop(
            stopHookIterationCount,
            stopHookReasons,
            response.stopHookCount ?? 1
          );
        }
        const continueParts = [{ text: continueReason }];
        let nextMessage = {
          role: "user",
          parts: continueParts
        };
        while (nextMessage !== null) {
          if (pendingSend.signal.aborted) {
            return { stopReason: "cancelled" };
          }
          const functionCalls = [];
          let usageMetadata = null;
          const streamStartTime = Date.now();
          try {
            const continueResponseStream = await chat.sendMessageStream(
              this.config.getModel(),
              {
                message: nextMessage?.parts ?? [],
                config: {
                  abortSignal: pendingSend.signal
                }
              },
              promptId + "_stop_hook_" + stopHookIterationCount
            );
            nextMessage = null;
            for await (const resp of continueResponseStream) {
              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 (error40) {
            const errorStatus = getErrorStatus(error40);
            const errorMessage = error40 instanceof Error ? error40.message : String(error40);
            const errorType = classifyApiError({
              message: errorMessage,
              status: errorStatus
            });
            const hookSystem = this.config.getHookSystem?.();
            const hooksEnabledForStopFailure = !this.config.getDisableAllHooks?.();
            if (hooksEnabledForStopFailure && hookSystem && this.config.hasHooksForEvent?.("StopFailure")) {
              hookSystem.fireStopFailureEvent(errorType, errorMessage).catch((err2) => {
                debugLogger171.warn(`StopFailure hook failed: ${err2}`);
              });
            }
            if (errorStatus === 429) {
              throw new RequestError(
                429,
                "Rate limit exceeded. Try again later."
              );
            }
            throw error40;
          }
          if (usageMetadata) {
            const durationMs = Date.now() - streamStartTime;
            await this.messageEmitter.emitUsageMetadata(
              usageMetadata,
              "",
              durationMs
            );
          }
          if (functionCalls.length > 0) {
            const toolResponseParts = await this.runToolCalls(
              pendingSend.signal,
              promptId,
              functionCalls
            );
            nextMessage = { role: "user", parts: toolResponseParts };
          }
        }
        continue;
      }
      break;
    }
    if (stopHookIterationCount >= MAX_STOP_HOOK_ITERATIONS) {
      debugLogger171.warn(
        `Stop hook loop reached maximum iterations (${MAX_STOP_HOOK_ITERATIONS}), forcing stop`
      );
    }
    return { stopReason: "end_turn" };
  }
  async sendUpdate(update2) {
    const params = {
      sessionId: this.sessionId,
      update: update2
    };
    await this.client.sessionUpdate(params);
  }
  /**
   * Starts the cron scheduler if cron is enabled and jobs exist.
   * The scheduler runs in the background, pushing fired prompts into
   * `cronQueue` and triggering `#drainCronQueue`.
   */
  #startCronSchedulerIfNeeded() {
    if (!this.config.isCronEnabled()) return;
    const scheduler = this.config.getCronScheduler();
    if (scheduler.size === 0) return;
    scheduler.start((job) => {
      this.cronQueue.push(job.prompt);
      void this.#drainCronQueue();
    });
  }
  /**
   * Processes queued cron prompts one at a time. Uses `cronProcessing`
   * as a mutex to prevent concurrent access to the chat.
   */
  async #drainCronQueue() {
    if (this.cronProcessing) return;
    if (this.pendingPrompt) return;
    this.cronProcessing = true;
    let resolveCompletion;
    this.cronCompletion = new Promise((resolve42) => {
      resolveCompletion = resolve42;
    });
    try {
      while (this.cronQueue.length > 0) {
        const prompt = this.cronQueue.shift();
        await this.#executeCronPrompt(prompt);
      }
    } finally {
      this.cronProcessing = false;
      resolveCompletion();
      this.cronCompletion = null;
      if (this.config.isCronEnabled()) {
        const scheduler = this.config.getCronScheduler();
        if (scheduler.size === 0) {
          scheduler.stop();
        }
      }
    }
  }
  /**
   * Executes a single cron-fired prompt: echoes it as a user message with
   * `_meta.source='cron'`, streams the model response, and handles tool calls.
   */
  async #executeCronPrompt(prompt) {
    return Storage.runWithRuntimeBaseDir(
      this.runtimeBaseDir,
      this.config.getWorkingDir(),
      async () => {
        const ac = new AbortController();
        this.cronAbortController = ac;
        const promptId = this.config.getSessionId() + "########cron" + Date.now();
        try {
          await this.sendUpdate({
            sessionUpdate: "user_message_chunk",
            content: { type: "text", text: prompt },
            _meta: { source: "cron" }
          });
          const cronReminders = await this.#buildInitialSystemReminders();
          let nextMessage = {
            role: "user",
            parts: [...cronReminders, { text: prompt }]
          };
          while (nextMessage !== null) {
            if (ac.signal.aborted) return;
            const functionCalls = [];
            let usageMetadata = null;
            const streamStartTime = Date.now();
            const responseStream = await this.config.getGeminiClient().getChat().sendMessageStream(
              this.config.getModel(),
              {
                message: nextMessage.parts ?? [],
                config: { abortSignal: ac.signal }
              },
              promptId
            );
            nextMessage = null;
            for await (const resp of responseStream) {
              if (ac.signal.aborted) return;
              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);
              }
            }
            if (usageMetadata) {
              if (this.messageRewriter) {
                this.messageRewriter.flushTurn(ac.signal);
              }
              const durationMs = Date.now() - streamStartTime;
              await this.messageEmitter.emitUsageMetadata(
                usageMetadata,
                "",
                durationMs
              );
            }
            if (functionCalls.length > 0) {
              const toolResponseParts = await this.runToolCalls(
                ac.signal,
                promptId,
                functionCalls
              );
              nextMessage = { role: "user", parts: toolResponseParts };
            }
          }
        } catch (error40) {
          if (ac.signal.aborted) return;
          debugLogger171.error("Error processing cron prompt:", error40);
          const msg = error40 instanceof Error ? error40.message : String(error40);
          await this.messageEmitter.emitAgentMessage(`[cron error] ${msg}`);
        } finally {
          if (this.cronAbortController === ac) {
            this.cronAbortController = null;
          }
        }
      }
    );
  }
  async sendAvailableCommandsUpdate() {
    const abortController = new AbortController();
    try {
      const slashCommands = await getAvailableCommands(
        this.config,
        abortController.signal,
        "acp"
      );
      const availableCommands = slashCommands.map((cmd) => {
        const acceptsInput = cmd.kind !== "built-in" /* BUILT_IN */ || cmd.completion != null || cmd.argumentHint != null || cmd.subCommands != null && cmd.subCommands.length > 0;
        return {
          name: cmd.name,
          description: cmd.description,
          input: acceptsInput ? { hint: cmd.argumentHint ?? "" } : null
        };
      });
      let availableSkills;
      try {
        const skillManager = this.config.getSkillManager();
        if (skillManager) {
          const skills = await skillManager.listSkills();
          availableSkills = skills.map((skill) => skill.name);
        }
      } catch (error40) {
        debugLogger171.error("Error loading available skills:", error40);
      }
      const update2 = {
        sessionUpdate: "available_commands_update",
        availableCommands,
        ...availableSkills ? {
          _meta: {
            availableSkills
          }
        } : {}
      };
      await this.sendUpdate(update2);
    } catch (error40) {
      debugLogger171.error("Error sending available commands update:", error40);
    }
  }
  /**
   * 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);
  }
  /**
   * 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(void 0, "modelId cannot be empty");
    }
    const parsed = parseAcpModelOption(rawModelId);
    const previousAuthType = this.config.getAuthType?.();
    const selectedAuthType = parsed.authType ?? previousAuthType;
    if (!selectedAuthType) {
      throw RequestError.invalidParams(
        void 0,
        `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
    );
  }
  /**
   * 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.RestorePrevious:
        newModeId = this.config.getApprovalMode();
        break;
      case ToolConfirmationOutcome.ProceedOnce:
      default:
        newModeId = "default";
        break;
    }
    const update2 = {
      sessionUpdate: "current_mode_update",
      currentModeId: newModeId
    };
    await this.sendUpdate(update2);
  }
  /**
   * Execute a batch of model-returned tool calls, running Agent calls
   * concurrently while keeping other tools sequential.
   *
   * Mirrors the partition logic in `coreToolScheduler.partitionToolCalls`:
   * consecutive Agent calls form a parallel batch (they spawn independent
   * sub-agents with no shared mutable state); any other tool forms its own
   * sequential batch to preserve the implicit ordering the model may rely
   * on. Response-part ordering matches the original `functionCalls` order.
   */
  async runToolCalls(abortSignal, promptId, functionCalls) {
    const batches = [];
    for (const fc of functionCalls) {
      const isAgent = fc.name === ToolNames.AGENT;
      const last2 = batches[batches.length - 1];
      if (isAgent && last2?.concurrent) {
        last2.calls.push(fc);
      } else {
        batches.push({ concurrent: isAgent, calls: [fc] });
      }
    }
    const runBounded = /* @__PURE__ */ __name(async (calls) => {
      const parsed = parseInt(
        process.env["QWEN_CODE_MAX_TOOL_CONCURRENCY"] || "",
        10
      );
      const maxConcurrency = Number.isFinite(parsed) && parsed >= 1 ? parsed : 10;
      const results = new Array(calls.length);
      const executing = /* @__PURE__ */ new Set();
      for (let i4 = 0; i4 < calls.length; i4++) {
        const idx = i4;
        const p2 = this.runTool(abortSignal, promptId, calls[idx]).then((r5) => {
          results[idx] = r5;
        }).finally(() => {
          executing.delete(p2);
        });
        executing.add(p2);
        if (executing.size >= maxConcurrency) {
          await Promise.race(executing);
        }
      }
      await Promise.all(executing);
      return results;
    }, "runBounded");
    const parts2 = [];
    for (const batch of batches) {
      if (batch.concurrent && batch.calls.length > 1) {
        const results = await runBounded(batch.calls);
        for (const r5 of results) parts2.push(...r5);
      } else {
        for (const fc of batch.calls) {
          const r5 = await this.runTool(abortSignal, promptId, fc);
          parts2.push(...r5);
        }
      }
    }
    return parts2;
  }
  /**
   * Assemble the per-turn system reminders the model needs to see at the
   * start of a user query or cron fire. Mirrors the subagent/plan/arena
   * branches in `GeminiClient.sendMessageStream` (`client.ts:848-878`) —
   * the ACP path bypasses that code, so without this helper plan mode is
   * silently inert (#1151) and subagent/arena sessions lose context.
   *
   * Scope note: the `relevantAutoMemory` reminder is intentionally NOT
   * included here. Managed auto-memory requires a prefetch pipeline that
   * lives in `GeminiClient`, and porting it into the ACP path is tracked
   * separately as part of the broader middleware-alignment work.
   */
  async #buildInitialSystemReminders() {
    const reminders = [];
    const hasAgentTool = await this.config.getToolRegistry().ensureTool(ToolNames.AGENT);
    const subagents = (await this.config.getSubagentManager().listSubagents()).filter((subagent) => subagent.level !== "builtin").map((subagent) => subagent.name);
    if (hasAgentTool && subagents.length > 0) {
      reminders.push({ text: getSubagentSystemReminder(subagents) });
    }
    if (this.config.getApprovalMode() === ApprovalMode.PLAN) {
      reminders.push({
        text: getPlanModeSystemReminder(this.config.getSdkMode?.())
      });
    }
    const arenaManager = this.config.getArenaManager?.();
    if (arenaManager) {
      try {
        const sessionDir = arenaManager.getArenaSessionDir();
        const configPath = `${sessionDir}/config.json`;
        reminders.push({ text: getArenaSystemReminder(configPath) });
      } catch {
      }
    }
    return reminders;
  }
  async runTool(abortSignal, promptId, fc) {
    const callId = fc.id ?? `${fc.name}-${Date.now()}`;
    let args2 = fc.args ?? {};
    const startTime = Date.now();
    const errorResponse = /* @__PURE__ */ __name((error40) => {
      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: args2,
        duration_ms: durationMs,
        status: "error",
        success: false,
        error: error40.message,
        tool_type: typeof tool !== "undefined" && tool instanceof DiscoveredMCPTool ? "mcp" : "native"
      });
      return [
        {
          functionResponse: {
            id: callId,
            name: fc.name ?? "",
            response: { error: error40.message }
          }
        }
      ];
    }, "errorResponse");
    const earlyErrorResponse = /* @__PURE__ */ __name(async (error40, toolName = fc.name ?? "unknown_tool") => {
      if (toolName !== ToolNames.TODO_WRITE) {
        await this.toolCallEmitter.emitError(callId, toolName, error40);
      }
      const errorParts = errorResponse(error40);
      this.config.getChatRecordingService()?.recordToolResult(errorParts, {
        callId,
        status: "error",
        resultDisplay: void 0,
        error: error40,
        errorType: void 0
      });
      return errorParts;
    }, "earlyErrorResponse");
    if (!fc.name) {
      return earlyErrorResponse(new Error("Missing function name"));
    }
    const toolRegistry = this.config.getToolRegistry();
    const tool = toolRegistry.getTool(fc.name);
    if (!tool) {
      return earlyErrorResponse(
        new Error(`Tool "${fc.name}" not found in registry.`)
      );
    }
    const pm = this.config.getPermissionManager?.();
    if (pm && !await pm.isToolEnabled(fc.name)) {
      return earlyErrorResponse(
        new Error(
          `Qwen Code requires permission to use "${fc.name}", but that permission was declined.`
        ),
        fc.name
      );
    }
    const isTodoWriteTool = tool.name === ToolNames.TODO_WRITE;
    const isAgentTool = tool.name === ToolNames.AGENT;
    const isExitPlanModeTool = tool.name === ToolNames.EXIT_PLAN_MODE;
    let subAgentCleanupFunctions = [];
    const toolUseId = generateToolUseId();
    const approvalMode = this.config.getApprovalMode();
    try {
      const invocation = tool.build(args2);
      const taskEventEmitter = invocation.eventEmitter;
      if (isAgentTool && taskEventEmitter) {
        const parentToolCallId = callId;
        const subagentType = args2["subagent_type"] ?? "";
        const subSubAgentTracker = new SubAgentTracker(
          this,
          this.client,
          parentToolCallId,
          subagentType
        );
        subAgentCleanupFunctions = subSubAgentTracker.setup(
          taskEventEmitter,
          abortSignal
        );
      }
      const isAskUserQuestionTool = fc.name === ToolNames.ASK_USER_QUESTION;
      const defaultPermission = this.config.getApprovalMode() !== ApprovalMode.YOLO || isAskUserQuestionTool ? await invocation.getDefaultPermission() : "allow";
      const toolParams = invocation.params;
      const pmCtx = buildPermissionCheckContext(
        fc.name,
        toolParams,
        this.config.getTargetDir?.() ?? ""
      );
      const { finalPermission, pmForcedAsk } = await evaluatePermissionRules(
        pm,
        defaultPermission,
        pmCtx
      );
      const needsConfirmation = finalPermission === "ask";
      const isPlanMode = approvalMode === ApprovalMode.PLAN;
      if (finalPermission === "deny") {
        return earlyErrorResponse(
          new Error(
            defaultPermission === "deny" ? `Tool "${fc.name}" is denied: command substitution is not allowed for security reasons.` : `Tool "${fc.name}" is denied by permission rules.`
          ),
          fc.name
        );
      }
      let didRequestPermission = false;
      let confirmationDetails;
      if (needsConfirmation) {
        confirmationDetails = await invocation.getConfirmationDetails(abortSignal);
        injectPermissionRulesIfMissing(confirmationDetails, pmCtx);
        if (isPlanMode && !isExitPlanModeTool && !isAskUserQuestionTool && confirmationDetails.type !== "info") {
          return earlyErrorResponse(
            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.`
            ),
            fc.name
          );
        }
        const messageBus = this.config.getMessageBus?.();
        const hooksEnabled = !this.config.getDisableAllHooks?.();
        let hookHandled = false;
        if (hooksEnabled && messageBus) {
          const hookResult = await firePermissionRequestHook(
            messageBus,
            fc.name,
            args2,
            String(approvalMode)
          );
          if (hookResult.hasDecision) {
            hookHandled = true;
            if (hookResult.shouldAllow) {
              if (hookResult.updatedInput) {
                args2 = hookResult.updatedInput;
                invocation.params = hookResult.updatedInput;
              }
              await confirmationDetails.onConfirm(
                ToolConfirmationOutcome.ProceedOnce
              );
            } else {
              return earlyErrorResponse(
                new Error(
                  hookResult.denyMessage || `Permission denied by hook for "${fc.name}"`
                ),
                fc.name
              );
            }
          }
        }
        if (approvalMode === ApprovalMode.AUTO_EDIT && (confirmationDetails.type === "edit" || confirmationDetails.type === "info")) {
        } else if (!hookHandled) {
          didRequestPermission = true;
          const content = buildPermissionRequestContent(confirmationDetails);
          const mappedKind = this.toolCallEmitter.mapToolKind(
            tool.kind,
            fc.name
          );
          if (hooksEnabled && messageBus) {
            void fireNotificationHook(
              messageBus,
              `Qwen Code needs your permission to use ${fc.name}`,
              NotificationType.PermissionPrompt,
              "Permission needed"
            );
          }
          const params = {
            sessionId: this.sessionId,
            options: toPermissionOptions(confirmationDetails, pmForcedAsk),
            toolCall: {
              toolCallId: callId,
              status: "pending",
              title: invocation.getDescription(),
              content,
              locations: invocation.toolLocations(),
              kind: mappedKind,
              rawInput: args2
            }
          };
          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, {
            answers: output.answers
          });
          if (outcome === ToolConfirmationOutcome.ProceedAlways || outcome === ToolConfirmationOutcome.ProceedAlwaysProject || outcome === ToolConfirmationOutcome.ProceedAlwaysUser) {
            await persistPermissionOutcome(
              outcome,
              confirmationDetails,
              this.config.getOnPersistPermissionRule?.(),
              this.config.getPermissionManager?.(),
              { answers: output.answers }
            );
          }
          if (isExitPlanModeTool && outcome !== ToolConfirmationOutcome.Cancel) {
            await this.sendCurrentModeUpdateNotification(outcome);
          }
          if (confirmationDetails.type === "edit" && outcome === ToolConfirmationOutcome.ProceedAlways) {
            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.ProceedAlwaysProject:
            case ToolConfirmationOutcome.ProceedAlwaysUser:
            case ToolConfirmationOutcome.ProceedAlwaysServer:
            case ToolConfirmationOutcome.ProceedAlwaysTool:
            case ToolConfirmationOutcome.ModifyWithEditor:
            case ToolConfirmationOutcome.RestorePrevious:
              break;
            default: {
              const resultOutcome = outcome;
              throw new Error(`Unexpected: ${resultOutcome}`);
            }
          }
        }
      }
      if (!didRequestPermission && !isTodoWriteTool) {
        const startParams = {
          callId,
          toolName: fc.name,
          args: args2,
          status: "in_progress"
        };
        await this.toolCallEmitter.emitStart(startParams);
      }
      const hooksEnabledForTool = !this.config.getDisableAllHooks?.();
      const messageBusForTool = this.config.getMessageBus?.();
      const permissionMode = String(approvalMode);
      if (hooksEnabledForTool && messageBusForTool) {
        const preHookResult = await firePreToolUseHook(
          messageBusForTool,
          fc.name,
          args2,
          toolUseId,
          permissionMode,
          abortSignal
        );
        if (!preHookResult.shouldProceed) {
          const blockReason = preHookResult.blockReason || "Blocked by PreToolUse hook";
          await this.messageEmitter.emitAgentMessage(
            `\u{1F6AB} **PreToolUse blocked**: ${fc.name} - ${blockReason}`
          );
          return earlyErrorResponse(new Error(blockReason), fc.name);
        }
        if (preHookResult.additionalContext) {
          debugLogger171.debug(
            `PreToolUse hook additional context for ${fc.name}: ${preHookResult.additionalContext}`
          );
        }
      }
      const toolResult = await invocation.execute(abortSignal);
      subAgentCleanupFunctions.forEach((cleanup) => cleanup());
      const responseParts = convertToFunctionResponse(
        fc.name,
        callId,
        toolResult.llmContent
      );
      if (hooksEnabledForTool && messageBusForTool && !toolResult.error) {
        const toolResponse = {
          llmContent: toolResult.llmContent,
          returnDisplay: toolResult.returnDisplay
        };
        const postHookResult = await firePostToolUseHook(
          messageBusForTool,
          fc.name,
          args2,
          toolResponse,
          toolUseId,
          permissionMode,
          abortSignal
        );
        if (postHookResult.shouldStop) {
          const stopMessage = postHookResult.stopReason || "Execution stopped by PostToolUse hook";
          debugLogger171.info(
            `PostToolUse hook requested stop for ${fc.name}: ${stopMessage}`
          );
          return earlyErrorResponse(new Error(stopMessage), fc.name);
        }
        if (postHookResult.additionalContext) {
          const contextPart = { text: postHookResult.additionalContext };
          responseParts.push(contextPart);
        }
      } else if (hooksEnabledForTool && messageBusForTool && toolResult.error) {
        const failureHookResult = await firePostToolUseFailureHook(
          messageBusForTool,
          toolUseId,
          fc.name ?? "unknown_tool",
          args2,
          toolResult.error.message,
          false,
          // not an interrupt
          permissionMode,
          abortSignal
        );
        if (failureHookResult.additionalContext) {
          debugLogger171.debug(
            `PostToolUseFailure hook additional context for ${fc.name}: ${failureHookResult.additionalContext}`
          );
        }
      }
      if (isTodoWriteTool) {
        const todos = this.planEmitter.extractTodos(
          toolResult.returnDisplay,
          args2
        );
        if (todos && todos.length > 0 || Array.isArray(args2["todos"])) {
          await this.planEmitter.emitPlan(todos ?? []);
        }
      } else {
        const error40 = toolResult.error ? new Error(toolResult.error.message) : void 0;
        await this.toolCallEmitter.emitResult({
          callId,
          toolName: fc.name,
          args: args2,
          message: responseParts,
          resultDisplay: toolResult.returnDisplay,
          error: error40,
          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: args2,
        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 error40 = e4 instanceof Error ? e4 : new Error(String(e4));
      const hooksEnabledForError = !this.config.getDisableAllHooks?.();
      const messageBusForError = this.config.getMessageBus?.();
      const isInterrupt = abortSignal.aborted;
      if (hooksEnabledForError && messageBusForError) {
        const failureHookResult = await firePostToolUseFailureHook(
          messageBusForError,
          toolUseId,
          fc.name ?? "unknown_tool",
          args2,
          error40.message,
          isInterrupt,
          String(approvalMode),
          abortSignal
        );
        if (failureHookResult.additionalContext) {
          debugLogger171.debug(
            `PostToolUseFailure hook additional context for ${fc.name}: ${failureHookResult.additionalContext}`
          );
        }
      }
      await this.toolCallEmitter.emitError(
        callId,
        fc.name ?? "unknown_tool",
        error40
      );
      const errorParts = [
        {
          functionResponse: {
            id: callId,
            name: fc.name ?? "",
            response: { error: error40.message }
          }
        }
      ];
      this.config.getChatRecordingService()?.recordToolResult(errorParts, {
        callId,
        status: "error",
        resultDisplay: void 0,
        error: error40,
        errorType: void 0
      });
      return errorResponse(error40);
    }
  }
  /**
   * 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": {
        if (result.messageType === "error") {
          throw new Error(result.content || "Slash command failed.");
        }
        const rendered = (result.content || "").replace(/\n/g, "  \n");
        await this.messageEmitter.emitAgentMessage(rendered);
        this.config.getChatRecordingService()?.recordSlashCommand({
          phase: "result",
          rawCommand: originalPrompt.filter((b2) => b2.type === "text").map((b2) => b2.type === "text" ? b2.text : "").join(" "),
          outputHistoryItems: [
            { type: "assistant", text: result.content || "" }
          ]
        });
        return null;
      }
      case "stream_messages": {
        const chunks = [];
        for await (const msg of result.messages) {
          if (msg.messageType === "error") {
            throw new Error(msg.content || "Slash command failed.");
          }
          await this.messageEmitter.emitAgentMessage(
            (msg.content || "").replace(/\n/g, "  \n")
          );
          chunks.push(msg.content || "");
        }
        if (chunks.length > 0) {
          this.config.getChatRecordingService()?.recordSlashCommand({
            phase: "result",
            rawCommand: originalPrompt.filter((b2) => b2.type === "text").map((b2) => b2.type === "text" ? b2.text : "").join(" "),
            outputHistoryItems: [
              { type: "assistant", text: chunks.join("\n") }
            ]
          });
        }
        return null;
      }
      case "unsupported": {
        const unsupportedError = `Slash command not supported in ACP integration: ${result.reason}`;
        throw new Error(unsupportedError);
      }
      case "no_command":
        return this.#resolvePrompt(
          originalPrompt,
          new AbortController().signal
        );
      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 parts2 = 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 = parts2.filter((part) => "fileData" in part);
    if (atPathCommandParts.length === 0 && embeddedContext.length === 0) {
      return parts2;
    }
    const pathSpecsToRead = atPathCommandParts.map(
      (part) => part.fileData.fileUri
    );
    let initialQueryText = "";
    for (let i4 = 0; i4 < parts2.length; i4++) {
      const chunk = parts2[i4];
      if ("text" in chunk) {
        initialQueryText += chunk.text;
      } else if ("fileData" in chunk) {
        const pathName = chunk.fileData.fileUri;
        if (i4 > 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()) {
      debugLogger171.warn(msg);
    }
  }
};

// packages/cli/src/acp-integration/runtimeOutputDirContext.ts
init_esbuild_shims();
init_dist4();
function runWithAcpRuntimeOutputDir(settings, cwd6, fn) {
  return Storage.runWithRuntimeBaseDir(
    settings.merged.advanced?.runtimeOutputDir,
    cwd6,
    fn
  );
}
__name(runWithAcpRuntimeOutputDir, "runWithAcpRuntimeOutputDir");

// packages/cli/src/acp-integration/acpAgent.ts
var debugLogger172 = createDebugLogger("ACP_AGENT");
async function runAcpAgent(config2, settings, argv) {
  await config2.initialize();
  const stdout2 = Writable3.toWeb(process.stdout);
  const stdin2 = Readable7.toWeb(process.stdin);
  console.log = console.error;
  console.info = console.error;
  console.debug = console.error;
  const stream5 = ndJsonStream(stdout2, stdin2);
  const connection = new AgentSideConnection(
    (conn) => new QwenAgent(config2, settings, argv, conn),
    stream5
  );
  let shuttingDown = false;
  let sessionEndFired = false;
  const fireSessionEndOnce = /* @__PURE__ */ __name(async (reason) => {
    if (sessionEndFired) return;
    sessionEndFired = true;
    const hookSystem = config2.getHookSystem?.();
    const hooksEnabled = !config2.getDisableAllHooks?.();
    if (hooksEnabled && hookSystem && config2.hasHooksForEvent?.("SessionEnd")) {
      try {
        await hookSystem.fireSessionEndEvent(reason);
      } catch (err2) {
        debugLogger172.warn(
          `SessionEnd hook failed: ${err2 instanceof Error ? err2.message : String(err2)}`
        );
      }
    }
  }, "fireSessionEndOnce");
  const shutdownHandler = /* @__PURE__ */ __name(async () => {
    if (shuttingDown) return;
    shuttingDown = true;
    debugLogger172.debug("[ACP] Shutdown signal received, closing streams");
    await fireSessionEndOnce(SessionEndReason.Other);
    try {
      process.stdin.destroy();
    } catch {
    }
    try {
      process.stdout.destroy();
    } catch {
    }
    runExitCleanup().catch((err2) => {
      debugLogger172.error("[ACP] Cleanup error:", err2);
    }).finally(() => {
      process.exit(0);
    });
  }, "shutdownHandler");
  process.on("SIGTERM", shutdownHandler);
  process.on("SIGINT", shutdownHandler);
  await connection.closed;
  await fireSessionEndOnce(SessionEndReason.PromptInputExit);
  process.off("SIGTERM", shutdownHandler);
  process.off("SIGINT", shutdownHandler);
}
__name(runAcpAgent, "runAcpAgent");
function toStdioServer(server) {
  if ("command" in server && "args" in server && "env" in server) {
    return server;
  }
  return void 0;
}
__name(toStdioServer, "toStdioServer");
function toSseServer(server) {
  if ("type" in server && server.type === "sse") {
    return server;
  }
  return void 0;
}
__name(toSseServer, "toSseServer");
function toHttpServer(server) {
  if ("type" in server && server.type === "http") {
    return server;
  }
  return void 0;
}
__name(toHttpServer, "toHttpServer");
var QwenAgent = class {
  constructor(config2, settings, argv, connection) {
    this.config = config2;
    this.settings = settings;
    this.argv = argv;
    this.connection = connection;
  }
  static {
    __name(this, "QwenAgent");
  }
  sessions = /* @__PURE__ */ new Map();
  clientCapabilities;
  async initialize(args2) {
    this.clientCapabilities = args2.clientCapabilities;
    const authMethods = buildAuthMethods();
    const version2 = "0.15.6";
    return {
      protocolVersion: PROTOCOL_VERSION,
      agentInfo: {
        name: "qwen-code",
        title: "Qwen Code",
        version: version2
      },
      authMethods,
      agentCapabilities: {
        loadSession: true,
        promptCapabilities: {
          image: true,
          audio: true,
          embeddedContext: true
        },
        sessionCapabilities: {
          list: {},
          resume: {}
        },
        mcpCapabilities: {
          sse: true,
          http: 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.connection.extNotification("authenticate/update", {
        _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);
      }
    }
  }
  async newSession({
    cwd: cwd6,
    mcpServers
  }) {
    const config2 = await this.newSessionConfig(cwd6, mcpServers);
    await this.ensureAuthenticated(config2);
    this.setupFileSystem(config2);
    const session = await this.createAndStoreSession(config2);
    const availableModels = this.buildAvailableModels(config2);
    const modesData = this.buildModesData(config2);
    const configOptions = this.buildConfigOptions(config2);
    return {
      sessionId: session.getId(),
      models: availableModels,
      modes: modesData,
      configOptions
    };
  }
  async loadSession(params) {
    const exists3 = await runWithAcpRuntimeOutputDir(
      this.settings,
      params.cwd,
      async () => {
        const sessionService = new SessionService(params.cwd);
        return sessionService.sessionExists(params.sessionId);
      }
    );
    const config2 = await this.newSessionConfig(
      params.cwd,
      params.mcpServers,
      params.sessionId,
      exists3
    );
    await this.ensureAuthenticated(config2);
    this.setupFileSystem(config2);
    const sessionData = config2.getResumedSessionData();
    await this.createAndStoreSession(config2, sessionData?.conversation);
    const modesData = this.buildModesData(config2);
    const availableModels = this.buildAvailableModels(config2);
    const configOptions = this.buildConfigOptions(config2);
    return {
      modes: modesData,
      models: availableModels,
      configOptions
    };
  }
  async unstable_listSessions(params) {
    const cwd6 = params.cwd || process.cwd();
    const numericCursor = params.cursor ? Number(params.cursor) : void 0;
    const metaSize = params._meta?.["size"];
    const size = typeof metaSize === "number" && metaSize > 0 ? Math.floor(metaSize) : void 0;
    const result = await runWithAcpRuntimeOutputDir(this.settings, cwd6, () => {
      const sessionService = new SessionService(cwd6);
      return sessionService.listSessions({
        cursor: Number.isNaN(numericCursor) ? void 0 : numericCursor,
        size
      });
    });
    const sessions = result.items.map((item) => ({
      cwd: item.cwd,
      sessionId: item.sessionId,
      title: item.customTitle || item.prompt || "(session)",
      updatedAt: new Date(item.mtime).toISOString()
    }));
    return {
      sessions,
      nextCursor: result.nextCursor != null ? String(result.nextCursor) : void 0
    };
  }
  async setSessionMode(params) {
    const session = this.sessions.get(params.sessionId);
    if (!session) {
      throw RequestError.invalidParams(
        void 0,
        `Session not found for id: ${params.sessionId}`
      );
    }
    return session.setMode(params);
  }
  async unstable_setSessionModel(params) {
    const session = this.sessions.get(params.sessionId);
    if (!session) {
      throw RequestError.invalidParams(
        void 0,
        `Session not found for id: ${params.sessionId}`
      );
    }
    return await session.setModel(params);
  }
  async setSessionConfigOption(params) {
    const { sessionId, configId, value } = params;
    const session = this.sessions.get(sessionId);
    if (!session) {
      throw RequestError.invalidParams(
        void 0,
        `Session not found for id: ${sessionId}`
      );
    }
    switch (configId) {
      case "mode": {
        await this.setSessionMode({
          sessionId,
          modeId: value
        });
        break;
      }
      case "model": {
        await this.unstable_setSessionModel({
          sessionId,
          modelId: value
        });
        break;
      }
      default:
        throw RequestError.invalidParams(
          void 0,
          `Unsupported configId: ${configId}`
        );
    }
    return {
      configOptions: this.buildConfigOptions(session.getConfig())
    };
  }
  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 cancel(params) {
    const session = this.sessions.get(params.sessionId);
    if (!session) {
      throw new Error(`Session not found: ${params.sessionId}`);
    }
    await session.cancelPendingPrompt();
  }
  async extMethod(method, params) {
    const cwd6 = params["cwd"] || process.cwd();
    const SESSION_ID_RE = /^[0-9a-fA-F-]{32,36}$/;
    switch (method) {
      case "deleteSession": {
        const sessionId = params["sessionId"];
        if (!sessionId || !SESSION_ID_RE.test(sessionId)) {
          throw RequestError.invalidParams(
            void 0,
            "Invalid or missing sessionId"
          );
        }
        const success2 = await runWithAcpRuntimeOutputDir(
          this.settings,
          cwd6,
          async () => {
            const sessionService = new SessionService(cwd6);
            return sessionService.removeSession(sessionId);
          }
        );
        return { success: success2 };
      }
      case "renameSession": {
        const sessionId = params["sessionId"];
        const title = params["title"];
        if (!sessionId || !SESSION_ID_RE.test(sessionId)) {
          throw RequestError.invalidParams(
            void 0,
            "Invalid or missing sessionId"
          );
        }
        if (!title || typeof title !== "string") {
          throw RequestError.invalidParams(
            void 0,
            "Invalid or missing title"
          );
        }
        if (title.length > SESSION_TITLE_MAX_LENGTH) {
          throw RequestError.invalidParams(
            void 0,
            `Title too long (max ${SESSION_TITLE_MAX_LENGTH} chars)`
          );
        }
        const success2 = await runWithAcpRuntimeOutputDir(
          this.settings,
          cwd6,
          async () => {
            const sessionService = new SessionService(cwd6);
            return sessionService.renameSession(sessionId, title);
          }
        );
        return { success: success2 };
      }
      case "getAccountInfo": {
        const sessionId = params["sessionId"];
        const session = sessionId ? this.sessions.get(sessionId) : void 0;
        const config2 = session ? session.getConfig() : this.config;
        const cfg = config2.getContentGeneratorConfig();
        return {
          authType: cfg?.authType ?? config2.getAuthType() ?? null,
          model: cfg?.model ?? config2.getModel() ?? null,
          baseUrl: cfg?.baseUrl ?? null,
          apiKeyEnvKey: cfg?.apiKeyEnvKey ?? null
        };
      }
      default:
        throw RequestError.methodNotFound(method);
    }
  }
  // --- private helpers ---
  async newSessionConfig(cwd6, mcpServers, sessionId, resume) {
    this.settings = loadSettings(cwd6);
    const mergedMcpServers = { ...this.settings.merged.mcpServers };
    for (const server of mcpServers) {
      const stdioServer = toStdioServer(server);
      if (stdioServer) {
        const env6 = {};
        for (const { name: envName, value } of stdioServer.env) {
          env6[envName] = value;
        }
        mergedMcpServers[stdioServer.name] = new MCPServerConfig(
          stdioServer.command,
          stdioServer.args,
          env6,
          cwd6
        );
        continue;
      }
      const sseServer = toSseServer(server);
      if (sseServer) {
        const headers = {};
        for (const { name: headerName, value } of sseServer.headers) {
          headers[headerName] = value;
        }
        mergedMcpServers[sseServer.name] = new MCPServerConfig(
          void 0,
          void 0,
          void 0,
          void 0,
          sseServer.url,
          void 0,
          Object.keys(headers).length > 0 ? headers : void 0
        );
        continue;
      }
      const httpServer = toHttpServer(server);
      if (httpServer) {
        const headers = {};
        for (const { name: headerName, value } of httpServer.headers) {
          headers[headerName] = value;
        }
        mergedMcpServers[httpServer.name] = new MCPServerConfig(
          void 0,
          void 0,
          void 0,
          void 0,
          void 0,
          httpServer.url,
          Object.keys(headers).length > 0 ? headers : void 0
        );
        continue;
      }
    }
    const settings = { ...this.settings.merged, mcpServers: mergedMcpServers };
    const argvForSession = {
      ...this.argv,
      ...resume ? { resume: sessionId } : { sessionId },
      continue: false
    };
    const config2 = await loadCliConfig(
      settings,
      argvForSession,
      cwd6,
      [],
      // Pass separated hooks for proper source attribution
      {
        userHooks: this.settings.getUserHooks(),
        projectHooks: this.settings.getProjectHooks()
      }
    );
    await config2.initialize();
    return config2;
  }
  async ensureAuthenticated(config2) {
    const selectedType = config2.getModelsConfig().getCurrentAuthType();
    if (!selectedType) {
      throw RequestError.authRequired(
        { authMethods: this.pickAuthMethodsForAuthRequired() },
        "Use Qwen Code CLI to authenticate first."
      );
    }
    try {
      await config2.refreshAuth(selectedType, true);
    } catch (e4) {
      debugLogger172.error(`Authentication failed: ${e4}`);
      throw RequestError.authRequired(
        {
          authMethods: this.pickAuthMethodsForAuthRequired(selectedType, e4)
        },
        "Authentication failed: " + e4.message
      );
    }
  }
  pickAuthMethodsForAuthRequired(selectedType, error40) {
    const authMethods = buildAuthMethods();
    const errorMessage = this.extractErrorMessage(error40);
    if (errorMessage?.includes("qwen-oauth") || errorMessage?.includes("Qwen OAuth")) {
      const qwenOAuthMethods = authMethods.filter(
        (m3) => m3.id === AuthType2.QWEN_OAUTH
      );
      return qwenOAuthMethods.length ? qwenOAuthMethods : authMethods;
    }
    if (selectedType) {
      const matched = authMethods.filter((m3) => m3.id === selectedType);
      return matched.length ? matched : authMethods;
    }
    return authMethods;
  }
  extractErrorMessage(error40) {
    if (error40 instanceof Error) return error40.message;
    if (typeof error40 === "object" && error40 != null && "message" in error40 && typeof error40.message === "string") {
      return error40.message;
    }
    if (typeof error40 === "string") return error40;
    return void 0;
  }
  setupFileSystem(config2) {
    if (!this.clientCapabilities?.fs) return;
    const acpFileSystemService = new AcpFileSystemService(
      this.connection,
      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 session = new Session3(
      sessionId,
      config2,
      this.connection,
      this.settings
    );
    this.sessions.set(sessionId, session);
    const hookSystem = config2.getHookSystem();
    const hooksEnabled = !config2.getDisableAllHooks();
    if (hooksEnabled && hookSystem && config2.hasHooksForEvent("SessionStart")) {
      const source2 = conversation ? SessionStartSource.Resume : SessionStartSource.Startup;
      const model = config2.getModel();
      const permissionMode = String(config2.getApprovalMode());
      try {
        await hookSystem.fireSessionStartEvent(source2, model, permissionMode);
      } catch (err2) {
        debugLogger172.warn(
          `SessionStart hook failed: ${err2 instanceof Error ? err2.message : String(err2)}`
        );
      }
    }
    setTimeout(async () => {
      await session.sendAvailableCommandsUpdate();
    }, 0);
    if (conversation && conversation.messages) {
      await session.replayHistory(conversation.messages);
    }
    session.installRewriter();
    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 mappedAvailableModels = allConfiguredModels.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
    };
  }
  buildModesData(config2) {
    const currentApprovalMode = config2.getApprovalMode();
    const availableModes = APPROVAL_MODES.map((mode) => ({
      id: mode,
      name: APPROVAL_MODE_INFO[mode].name,
      description: APPROVAL_MODE_INFO[mode].description
    }));
    return {
      currentModeId: currentApprovalMode,
      availableModes
    };
  }
  buildConfigOptions(config2) {
    const currentApprovalMode = config2.getApprovalMode();
    const allConfiguredModels = config2.getAllConfiguredModels();
    const rawCurrentModelId = (config2.getModel() || "").trim();
    const currentAuthType = config2.getAuthType?.();
    const activeRuntimeSnapshot = config2.getActiveRuntimeModelSnapshot?.();
    const currentModelId = activeRuntimeSnapshot ? formatAcpModelId(
      activeRuntimeSnapshot.id,
      activeRuntimeSnapshot.authType
    ) : this.formatCurrentModelId(rawCurrentModelId, currentAuthType);
    const modeOptions = APPROVAL_MODES.map((mode) => ({
      value: mode,
      name: APPROVAL_MODE_INFO[mode].name,
      description: APPROVAL_MODE_INFO[mode].description
    }));
    const modeConfigOption = {
      id: "mode",
      name: "Mode",
      description: "Session permission mode",
      category: "mode",
      type: "select",
      currentValue: currentApprovalMode,
      options: modeOptions
    };
    const modelOptions = allConfiguredModels.map((model) => {
      const effectiveModelId = model.isRuntimeModel && model.runtimeSnapshotId ? model.runtimeSnapshotId : model.id;
      return {
        value: formatAcpModelId(effectiveModelId, model.authType),
        name: model.label,
        description: model.description ?? ""
      };
    });
    const modelConfigOption = {
      id: "model",
      name: "Model",
      description: "AI model to use",
      category: "model",
      type: "select",
      currentValue: currentModelId,
      options: modelOptions
    };
    return [modeConfigOption, modelConfigOption];
  }
  formatCurrentModelId(baseModelId, authType) {
    if (!baseModelId) return baseModelId;
    return authType ? formatAcpModelId(baseModelId, authType) : baseModelId;
  }
};

// packages/cli/src/gemini.tsx
var import_jsx_runtime152 = __toESM(require_jsx_runtime(), 1);
var debugLogger173 = 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 = os58.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, _promise2) => {
    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(basename33(workspaceRoot), settings);
  const restoreTerminalRedrawOptimizer = process.stdout.isTTY && !config2.getScreenReader() ? installTerminalRedrawOptimizer(process.stdout) : () => {
  };
  const restoreSynchronizedOutput = process.stdout.isTTY && !config2.getScreenReader() ? installSynchronizedOutput(process.stdout) : () => {
  };
  let dualOutputBridge = null;
  const jsonFd = config2.getJsonFd?.();
  const jsonFile = config2.getJsonFile?.();
  try {
    if (jsonFd != null) {
      dualOutputBridge = new DualOutputBridge(
        config2,
        { fd: jsonFd },
        { version: version2 }
      );
    } else if (jsonFile != null) {
      dualOutputBridge = new DualOutputBridge(
        config2,
        { filePath: jsonFile },
        { version: version2 }
      );
    }
  } catch (err2) {
    debugLogger173.error("Failed to initialize dual output bridge:", err2);
    writeStderrLine(
      `Warning: dual output disabled \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`
    );
  }
  let remoteInputWatcher = null;
  const inputFile = config2.getInputFile?.();
  if (inputFile) {
    try {
      remoteInputWatcher = new RemoteInputWatcher(inputFile);
    } catch (err2) {
      debugLogger173.error("Failed to initialize remote input watcher:", err2);
      writeStderrLine(
        `Warning: remote input disabled \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`
      );
    }
  }
  const initialCapturedInput = stopAndGetCapturedInput();
  const AppWrapper = /* @__PURE__ */ __name(() => {
    const kittyProtocolStatus = useKittyKeyboardProtocol();
    const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
    return /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(RemoteInputContext.Provider, { value: remoteInputWatcher, children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(DualOutputContext.Provider, { value: dualOutputBridge, children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(SettingsContext.Provider, { value: settings, children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(
      KeypressProvider,
      {
        kittyProtocolEnabled: kittyProtocolStatus.enabled,
        config: config2,
        debugKeystrokeLogging: settings.merged.general?.debugKeystrokeLogging,
        pasteWorkaround: process.platform === "win32" || nodeMajorVersion < 20,
        initialCapturedInput,
        children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(SessionStatsProvider, { sessionId: config2.getSessionId(), children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(VimModeProvider, { settings, children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(AgentViewProvider, { config: config2, children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(BackgroundTaskViewProvider, { config: config2, children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(
          AppContainer,
          {
            config: config2,
            settings,
            startupWarnings,
            version: version2,
            initializationResult
          }
        ) }) }) }) })
      }
    ) }) }) });
  }, "AppWrapper");
  const instance2 = render_default(
    process.env["DEBUG"] ? /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(import_react192.default.StrictMode, { children: /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(AppWrapper, {}) }) : /* @__PURE__ */ (0, import_jsx_runtime152.jsx)(AppWrapper, {}),
    {
      exitOnCtrlC: false,
      isScreenReaderEnabled: config2.getScreenReader()
    }
  );
  if (settings.merged.general?.enableAutoUpdate !== false) {
    checkForUpdates().then((info2) => {
      handleAutoUpdate(info2, settings, config2.getProjectRoot());
    }).catch((err2) => {
      debugLogger173.warn(`Update check failed: ${err2}`);
    });
  }
  registerCleanup(async () => {
    remoteInputWatcher?.shutdown();
    await dualOutputBridge?.shutdown();
    disableKittyProtocol();
    instance2.unmount();
    restoreSynchronizedOutput();
    restoreTerminalRedrawOptimizer();
  });
}
__name(startInteractiveUI, "startInteractiveUI");
async function main() {
  profileCheckpoint("main_entry");
  setupUnhandledRejectionHandler();
  if (process.argv.includes("--bare")) {
    process.env[QWEN_CODE_SIMPLE_ENV_VAR] = "1";
  }
  let argv = await parseArguments();
  profileCheckpoint("after_parse_arguments");
  if (isBareMode(argv.bare)) {
    process.env[QWEN_CODE_SIMPLE_ENV_VAR] = "1";
  }
  const settings = isBareMode(argv.bare) ? createMinimalSettings() : loadSettings();
  await cleanupCheckpoints();
  profileCheckpoint("after_load_settings");
  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);
  dns2.setDefaultResultOrder(
    validateDnsResolutionOrder(settings.merged.advanced?.dnsResolutionOrder)
  );
  themeManager.loadCustomThemes(settings.merged.ui?.customThemes);
  const configuredTheme = settings.merged.ui?.theme;
  if (configuredTheme && configuredTheme !== AUTO_THEME_NAME) {
    if (!themeManager.setActiveTheme(configuredTheme)) {
      writeStderrLine(`Warning: Theme "${configuredTheme}" not found.`);
    }
  } else {
    themeManager.setActiveTheme(AUTO_THEME_NAME);
  }
  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,
        [],
        // Pass separated hooks for proper source attribution
        {
          userHooks: settings.getUserHooks(),
          projectHooks: settings.getProjectHooks()
        }
      );
      if (!settings.merged.security?.auth?.useExternal) {
        try {
          const authType = partialConfig.getModelsConfig().getCurrentAuthType();
          if (authType) {
            const err2 = validateAuthMethod(authType, partialConfig);
            if (err2) {
              throw new Error(err2);
            }
            await partialConfig.refreshAuth(authType);
          }
        } catch (err2) {
          writeStderrLine(`Error authenticating: ${err2}`);
          process.exit(1);
        }
      }
      const inputFormat = argv.inputFormat;
      const isAcpMode = argv.acp || argv.experimentalAcp;
      let stdinData = "";
      if (!process.stdin.isTTY && inputFormat !== "stream-json" && !isAcpMode) {
        stdinData = await readStdin();
      }
      const injectStdinIntoArgs = /* @__PURE__ */ __name((args2, stdinData2) => {
        const finalArgs = [...args2];
        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 !== void 0) {
    Storage.setRuntimeBaseDir(
      settings.merged.advanced?.runtimeOutputDir,
      process.cwd()
    );
    let resolvedSessionId;
    if (argv.resume === "") {
      resolvedSessionId = await showResumeSessionPicker();
    } else if (!isValidSessionId(argv.resume)) {
      const sessionService = new SessionService(process.cwd());
      const matches2 = await sessionService.findSessionsByTitle(argv.resume);
      if (matches2.length === 1) {
        resolvedSessionId = matches2[0].sessionId;
      } else if (matches2.length > 1) {
        writeStderrLine(
          `Multiple sessions found with title "${argv.resume}". Please select one:`
        );
        resolvedSessionId = await showResumeSessionPicker(
          process.cwd(),
          matches2
        );
      }
    }
    if (resolvedSessionId !== void 0) {
      argv = { ...argv, resume: resolvedSessionId };
    } else if (argv.resume === "" || !isValidSessionId(argv.resume)) {
      if (argv.resume !== "") {
        writeStderrLine(`No saved session found with title "${argv.resume}".`);
        process.exit(1);
      } else {
        process.exit(0);
      }
    }
  }
  profileCheckpoint("after_sandbox_check");
  if (!isBareMode(argv.bare)) {
    initializeLlmOutputLanguage(settings.merged.general?.outputLanguage);
  }
  {
    const config2 = await loadCliConfig(
      settings.merged,
      argv,
      process.cwd(),
      argv.extensions,
      // Pass separated hooks for proper source attribution
      {
        userHooks: settings.getUserHooks(),
        projectHooks: settings.getProjectHooks()
      }
    );
    profileCheckpoint("after_load_cli_config");
    registerCleanup(() => config2.shutdown());
    try {
      const modelsConfig = config2.getModelsConfig();
      const authType = modelsConfig.getCurrentAuthType();
      const resolvedBaseUrl = modelsConfig.getGenerationConfig().baseUrl;
      const proxy2 = config2.getProxy();
      preconnectApi(authType, { resolvedBaseUrl, proxy: proxy2 });
    } catch (error40) {
      debugLogger173.debug(
        `Preconnect skipped due to error getting authType: ${error40}`
      );
    }
    const wasRaw = process.stdin.isRaw;
    let kittyProtocolDetectionComplete;
    let themeAutoDetectionComplete;
    if (config2.isInteractive() && !wasRaw && process.stdin.isTTY) {
      process.stdin.setRawMode(true);
      startEarlyInputCapture();
      registerCleanup(() => stopAndGetCapturedInput());
      process.on("SIGTERM", () => {
        process.stdin.setRawMode(wasRaw);
      });
      process.on("SIGINT", () => {
        process.stdin.setRawMode(wasRaw);
      });
      kittyProtocolDetectionComplete = detectAndEnableKittyProtocol();
      if (!configuredTheme || configuredTheme === AUTO_THEME_NAME) {
        themeAutoDetectionComplete = themeManager.resolveAutoThemeAsync().catch((err2) => {
          debugLogger173.warn("Async theme auto-detection failed:", err2);
        });
      }
    }
    setMaxSizedBoxDebugging(isDebugMode2);
    const inputFormat = process.stdin.isTTY ? InputFormat.TEXT : typeof config2.getInputFormat === "function" ? config2.getInputFormat() : InputFormat.TEXT;
    const initializationResult = await initializeApp(config2, settings);
    profileCheckpoint("after_initialize_app");
    if (config2.getExperimentalZedIntegration()) {
      await runAcpAgent(config2, settings, argv);
      await runExitCleanup();
      process.exit(0);
    }
    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(),
        ...config2.getModelsConfig().getCurrentAuthType() === AuthType2.QWEN_OAUTH ? [
          "Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan or another provider."
        ] : []
      ])
    ];
    profileCheckpoint("before_render");
    finalizeStartupProfile(config2.getSessionId());
    if (config2.isInteractive()) {
      await kittyProtocolDetectionComplete;
      await themeAutoDetectionComplete;
      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
    });
    debugLogger173.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
init_dist4();
init_stdioHelpers();
initStartupProfiler();
var getErrnoCode2 = /* @__PURE__ */ __name((error40) => {
  if (!error40 || typeof error40 !== "object") {
    return void 0;
  }
  const code2 = error40.code;
  return typeof code2 === "string" ? code2 : void 0;
}, "getErrnoCode");
var isExpectedPtyRaceError = /* @__PURE__ */ __name((error40) => {
  if (!(error40 instanceof Error)) {
    return false;
  }
  const message = error40.message;
  const code2 = getErrnoCode2(error40);
  if (code2 === "EIO" && message.includes("read") || message.includes("read EIO")) {
    return true;
  }
  if (code2 === "EAGAIN" && message.includes("read") || message.includes("read EAGAIN")) {
    return true;
  }
  if (message.includes("ioctl(2) failed, EBADF") || message.includes("Cannot resize a pty that has already exited")) {
    return true;
  }
  return false;
}, "isExpectedPtyRaceError");
process.on("uncaughtException", (error40) => {
  if (isExpectedPtyRaceError(error40)) {
    return;
  }
  if (error40 instanceof Error) {
    writeStderrLine(error40.stack ?? error40.message);
  } else {
    writeStderrLine(String(error40));
  }
  process.exit(1);
});
main().catch((error40) => {
  if (error40 instanceof FatalError) {
    let errorMessage = error40.message;
    if (!process.env["NO_COLOR"]) {
      errorMessage = `\x1B[31m${errorMessage}\x1B[0m`;
    }
    console.error(errorMessage);
    process.exit(error40.exitCode);
  }
  console.error("An unexpected critical error occurred:");
  if (error40 instanceof Error) {
    console.error(error40.stack);
  } else {
    console.error(String(error40));
  }
  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 Code
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Internal Prompt ID utilities
 *
 * Centralises the set of prompt IDs used by background operations
 * (suggestion generation, forked queries) so that logging, recording,
 * and UI layers can consistently recognise and filter them.
 */
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Coding Plan constants — shared between CLI and VSCode extension.
 * Single source of truth for model templates, regions, and env keys.
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Shared Follow-up Suggestions State Logic
 *
 * Framework-agnostic state management for prompt suggestions,
 * shared between CLI (Ink) and WebUI (React) hooks.
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Prompt Suggestion Generator
 *
 * Uses a lightweight LLM call to predict what the user would naturally
 * type next (Next-step Suggestion / NES).
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Copy-on-Write Overlay Filesystem
 *
 * Provides file isolation for speculative execution. Writes go to a temporary
 * overlay directory while reads resolve to overlay (if previously written)
 * or the real filesystem.
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Speculation Tool Gate
 *
 * Determines which tool calls are allowed during speculative execution.
 * Returns 'allow' for safe read-only tools, 'redirect' for write tools
 * (only when approval mode permits), or 'boundary' to stop speculation.
 *
 * SECURITY: Speculation bypasses the normal permission/approval flow.
 * Write tools are ONLY redirected to overlay when the user's approval mode
 * already permits automatic edits (auto-edit or yolo). In default/plan mode,
 * write tools hit boundary — no silent writes without user consent.
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Speculation Engine
 *
 * Speculatively executes the accepted suggestion before the user confirms,
 * using a forked GeminiChat with copy-on-write file isolation.
 *
 * Flow:
 * 1. Suggestion shown → startSpeculation() fires
 * 2. Speculative loop runs in background (read-only tools + overlay writes)
 * 3. User presses Tab/Enter → acceptSpeculation() copies overlay to real FS
 * 4. User types → abortSpeculation() cleans up
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Prompt Suggestion Module
 *
 * Exports for the prompt suggestion feature.
 */
/**
 * @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.
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Prompt Suggestion Hook for CLI
 *
 * Thin React wrapper around the framework-agnostic controller from core.
 */
/*! 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.
   *)

mime-db/index.js:
  (*!
   * mime-db
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2015-2022 Douglas Christopher Wilson
   * MIT Licensed
   *)

mime-types/index.js:
  (*!
   * mime-types
   * Copyright(c) 2014 Jonathan Ong
   * Copyright(c) 2015 Douglas Christopher Wilson
   * MIT Licensed
   *)

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 *)
*/
