import {
  __commonJS,
  __require
} from "./chunk-MCKGQKYU.js";

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

// ../../node_modules/undici/lib/util/timers.js
var require_timers = __commonJS({
  "../../node_modules/undici/lib/util/timers.js"(exports, module) {
    "use strict";
    var fastNow = 0;
    var RESOLUTION_MS = 1e3;
    var TICK_MS = (RESOLUTION_MS >> 1) - 1;
    var fastNowTimeout;
    var kFastTimer = /* @__PURE__ */ Symbol("kFastTimer");
    var fastTimers = [];
    var NOT_IN_LIST = -2;
    var TO_BE_CLEARED = -1;
    var PENDING = 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 === PENDING) {
          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();
      }
    }
    function refreshTimeout() {
      if (fastNowTimeout?.refresh) {
        fastNowTimeout.refresh();
      } else {
        clearTimeout(fastNowTimeout);
        fastNowTimeout = setTimeout(onTick, TICK_MS);
        fastNowTimeout?.unref();
      }
    }
    var FastTimer = class {
      [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, delay, arg) {
        this._onTimeout = callback;
        this._idleTimeout = delay;
        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 = PENDING;
      }
      /**
       * The `clear` method cancels the timer, preventing it from executing.
       *
       * @returns {void}
       * @private
       */
      clear() {
        this._state = TO_BE_CLEARED;
        this._idleStart = -1;
      }
    };
    module.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, delay, arg) {
        return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg);
      },
      /**
       * The clearTimeout method cancels an instantiated Timer previously created
       * by calling setTimeout.
       *
       * @param {NodeJS.Timeout|FastTimer} timeout
       */
      clearTimeout(timeout) {
        if (timeout[kFastTimer]) {
          timeout.clear();
        } else {
          clearTimeout(timeout);
        }
      },
      /**
       * 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, delay, arg) {
        return new FastTimer(callback, delay, arg);
      },
      /**
       * The clearTimeout method cancels an instantiated FastTimer previously
       * created by calling setFastTimeout.
       *
       * @param {FastTimer} timeout
       */
      clearFastTimeout(timeout) {
        timeout.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(delay = 0) {
        fastNow += delay - RESOLUTION_MS + 1;
        onTick();
        onTick();
      },
      /**
       * Reset FastTimers.
       * Exported for testing purposes only.
       * Marking as deprecated to discourage any use outside of testing.
       * @deprecated
       */
      reset() {
        fastNow = 0;
        fastTimers.length = 0;
        clearTimeout(fastNowTimeout);
        fastNowTimeout = null;
      },
      /**
       * Exporting for testing purposes only.
       * Marking as deprecated to discourage any use outside of testing.
       * @deprecated
       */
      kFastTimer
    };
  }
});

// ../../node_modules/undici/lib/core/errors.js
var require_errors = __commonJS({
  "../../node_modules/undici/lib/core/errors.js"(exports, module) {
    "use strict";
    var kUndiciError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR");
    var UndiciError = class extends Error {
      constructor(message, options) {
        super(message, options);
        this.name = "UndiciError";
        this.code = "UND_ERR";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kUndiciError] === true;
      }
      get [kUndiciError]() {
        return true;
      }
    };
    var kConnectTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_CONNECT_TIMEOUT");
    var ConnectTimeoutError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "ConnectTimeoutError";
        this.message = message || "Connect Timeout Error";
        this.code = "UND_ERR_CONNECT_TIMEOUT";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kConnectTimeoutError] === true;
      }
      get [kConnectTimeoutError]() {
        return true;
      }
    };
    var kHeadersTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HEADERS_TIMEOUT");
    var HeadersTimeoutError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "HeadersTimeoutError";
        this.message = message || "Headers Timeout Error";
        this.code = "UND_ERR_HEADERS_TIMEOUT";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHeadersTimeoutError] === true;
      }
      get [kHeadersTimeoutError]() {
        return true;
      }
    };
    var kHeadersOverflowError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HEADERS_OVERFLOW");
    var HeadersOverflowError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "HeadersOverflowError";
        this.message = message || "Headers Overflow Error";
        this.code = "UND_ERR_HEADERS_OVERFLOW";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHeadersOverflowError] === true;
      }
      get [kHeadersOverflowError]() {
        return true;
      }
    };
    var kBodyTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_BODY_TIMEOUT");
    var BodyTimeoutError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "BodyTimeoutError";
        this.message = message || "Body Timeout Error";
        this.code = "UND_ERR_BODY_TIMEOUT";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kBodyTimeoutError] === true;
      }
      get [kBodyTimeoutError]() {
        return true;
      }
    };
    var kInvalidArgumentError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INVALID_ARG");
    var InvalidArgumentError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "InvalidArgumentError";
        this.message = message || "Invalid Argument Error";
        this.code = "UND_ERR_INVALID_ARG";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInvalidArgumentError] === true;
      }
      get [kInvalidArgumentError]() {
        return true;
      }
    };
    var kInvalidReturnValueError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INVALID_RETURN_VALUE");
    var InvalidReturnValueError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "InvalidReturnValueError";
        this.message = message || "Invalid Return Value Error";
        this.code = "UND_ERR_INVALID_RETURN_VALUE";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInvalidReturnValueError] === true;
      }
      get [kInvalidReturnValueError]() {
        return true;
      }
    };
    var kAbortError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_ABORT");
    var AbortError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "AbortError";
        this.message = message || "The operation was aborted";
        this.code = "UND_ERR_ABORT";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kAbortError] === true;
      }
      get [kAbortError]() {
        return true;
      }
    };
    var kRequestAbortedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_ABORTED");
    var RequestAbortedError = class extends AbortError {
      constructor(message) {
        super(message);
        this.name = "AbortError";
        this.message = message || "Request aborted";
        this.code = "UND_ERR_ABORTED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestAbortedError] === true;
      }
      get [kRequestAbortedError]() {
        return true;
      }
    };
    var kInformationalError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INFO");
    var InformationalError = class extends UndiciError {
      constructor(message, options) {
        super(message, options);
        this.name = "InformationalError";
        this.message = message || "Request information";
        this.code = "UND_ERR_INFO";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInformationalError] === true;
      }
      get [kInformationalError]() {
        return true;
      }
    };
    var kRequestContentLengthMismatchError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH");
    var RequestContentLengthMismatchError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "RequestContentLengthMismatchError";
        this.message = message || "Request body length does not match content-length header";
        this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestContentLengthMismatchError] === true;
      }
      get [kRequestContentLengthMismatchError]() {
        return true;
      }
    };
    var kResponseContentLengthMismatchError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH");
    var ResponseContentLengthMismatchError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "ResponseContentLengthMismatchError";
        this.message = message || "Response body length does not match content-length header";
        this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseContentLengthMismatchError] === true;
      }
      get [kResponseContentLengthMismatchError]() {
        return true;
      }
    };
    var kClientDestroyedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_DESTROYED");
    var ClientDestroyedError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "ClientDestroyedError";
        this.message = message || "The client is destroyed";
        this.code = "UND_ERR_DESTROYED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kClientDestroyedError] === true;
      }
      get [kClientDestroyedError]() {
        return true;
      }
    };
    var kClientClosedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_CLOSED");
    var ClientClosedError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "ClientClosedError";
        this.message = message || "The client is closed";
        this.code = "UND_ERR_CLOSED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kClientClosedError] === true;
      }
      get [kClientClosedError]() {
        return true;
      }
    };
    var kSocketError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_SOCKET");
    var SocketError = class extends UndiciError {
      constructor(message, socket) {
        super(message);
        this.name = "SocketError";
        this.message = message || "Socket error";
        this.code = "UND_ERR_SOCKET";
        this.socket = socket;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kSocketError] === true;
      }
      get [kSocketError]() {
        return true;
      }
    };
    var kNotSupportedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_NOT_SUPPORTED");
    var NotSupportedError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "NotSupportedError";
        this.message = message || "Not supported error";
        this.code = "UND_ERR_NOT_SUPPORTED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kNotSupportedError] === true;
      }
      get [kNotSupportedError]() {
        return true;
      }
    };
    var kBalancedPoolMissingUpstreamError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_BPL_MISSING_UPSTREAM");
    var BalancedPoolMissingUpstreamError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "MissingUpstreamError";
        this.message = message || "No upstream has been added to the BalancedPool";
        this.code = "UND_ERR_BPL_MISSING_UPSTREAM";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kBalancedPoolMissingUpstreamError] === true;
      }
      get [kBalancedPoolMissingUpstreamError]() {
        return true;
      }
    };
    var kHTTPParserError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HTTP_PARSER");
    var HTTPParserError = class extends Error {
      constructor(message, code, data) {
        super(message);
        this.name = "HTTPParserError";
        this.code = code ? `HPE_${code}` : void 0;
        this.data = data ? data.toString() : void 0;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHTTPParserError] === true;
      }
      get [kHTTPParserError]() {
        return true;
      }
    };
    var kResponseExceededMaxSizeError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE");
    var ResponseExceededMaxSizeError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "ResponseExceededMaxSizeError";
        this.message = message || "Response content exceeded max size";
        this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseExceededMaxSizeError] === true;
      }
      get [kResponseExceededMaxSizeError]() {
        return true;
      }
    };
    var kRequestRetryError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_REQ_RETRY");
    var RequestRetryError = class extends UndiciError {
      constructor(message, code, { headers, data }) {
        super(message);
        this.name = "RequestRetryError";
        this.message = message || "Request retry error";
        this.code = "UND_ERR_REQ_RETRY";
        this.statusCode = code;
        this.data = data;
        this.headers = headers;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestRetryError] === true;
      }
      get [kRequestRetryError]() {
        return true;
      }
    };
    var kResponseError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RESPONSE");
    var ResponseError = class extends UndiciError {
      constructor(message, code, { headers, body }) {
        super(message);
        this.name = "ResponseError";
        this.message = message || "Response error";
        this.code = "UND_ERR_RESPONSE";
        this.statusCode = code;
        this.body = body;
        this.headers = headers;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseError] === true;
      }
      get [kResponseError]() {
        return true;
      }
    };
    var kSecureProxyConnectionError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_PRX_TLS");
    var SecureProxyConnectionError = class extends UndiciError {
      constructor(cause, message, options = {}) {
        super(message, { cause, ...options });
        this.name = "SecureProxyConnectionError";
        this.message = message || "Secure Proxy Connection failed";
        this.code = "UND_ERR_PRX_TLS";
        this.cause = cause;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kSecureProxyConnectionError] === true;
      }
      get [kSecureProxyConnectionError]() {
        return true;
      }
    };
    var kMaxOriginsReachedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_MAX_ORIGINS_REACHED");
    var MaxOriginsReachedError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "MaxOriginsReachedError";
        this.message = message || "Maximum allowed origins reached";
        this.code = "UND_ERR_MAX_ORIGINS_REACHED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kMaxOriginsReachedError] === true;
      }
      get [kMaxOriginsReachedError]() {
        return true;
      }
    };
    var Socks5ProxyError = class extends UndiciError {
      constructor(message, code) {
        super(message);
        this.name = "Socks5ProxyError";
        this.message = message || "SOCKS5 proxy error";
        this.code = code || "UND_ERR_SOCKS5";
      }
    };
    var kMessageSizeExceededError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED");
    var MessageSizeExceededError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "MessageSizeExceededError";
        this.message = message || "Max decompressed message size exceeded";
        this.code = "UND_ERR_WS_MESSAGE_SIZE_EXCEEDED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kMessageSizeExceededError] === true;
      }
      get [kMessageSizeExceededError]() {
        return true;
      }
    };
    module.exports = {
      AbortError,
      HTTPParserError,
      UndiciError,
      HeadersTimeoutError,
      HeadersOverflowError,
      BodyTimeoutError,
      RequestContentLengthMismatchError,
      ConnectTimeoutError,
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError,
      ClientDestroyedError,
      ClientClosedError,
      InformationalError,
      SocketError,
      NotSupportedError,
      ResponseContentLengthMismatchError,
      BalancedPoolMissingUpstreamError,
      ResponseExceededMaxSizeError,
      RequestRetryError,
      ResponseError,
      SecureProxyConnectionError,
      MaxOriginsReachedError,
      Socks5ProxyError,
      MessageSizeExceededError
    };
  }
});

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

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

// ../../node_modules/undici/lib/core/util.js
var require_util = __commonJS({
  "../../node_modules/undici/lib/core/util.js"(exports, module) {
    "use strict";
    var assert = __require("assert");
    var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols();
    var { IncomingMessage } = __require("http");
    var stream = __require("stream");
    var net = __require("net");
    var { stringify } = __require("querystring");
    var { EventEmitter: EE, addAbortListener: addAbortListenerNative } = __require("events");
    var timers = require_timers();
    var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
    var { headerNameLowerCasedRecord } = require_constants();
    var { tree } = require_tree();
    var BodyAsyncIterable = class {
      constructor(body) {
        this[kBody] = body;
        this[kBodyUsed] = false;
      }
      async *[Symbol.asyncIterator]() {
        assert(!this[kBodyUsed], "disturbed");
        this[kBodyUsed] = true;
        yield* this[kBody];
      }
    };
    function noop() {
    }
    function wrapRequestBody(body) {
      if (isStream(body)) {
        if (bodyLength(body) === 0) {
          body.on("data", function() {
            assert(false);
          });
        }
        if (typeof body.readableDidRead !== "boolean") {
          body[kBodyUsed] = false;
          EE.prototype.on.call(body, "data", function() {
            this[kBodyUsed] = true;
          });
        }
        return body;
      } else if (body && typeof body.pipeTo === "function") {
        return new BodyAsyncIterable(body);
      } else if (body && isFormDataLike(body)) {
        return body;
      } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) {
        return new BodyAsyncIterable(body);
      } else {
        return body;
      }
    }
    function isStream(obj) {
      return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
    }
    function isBlobLike(object) {
      return object instanceof Blob;
    }
    function pathHasQueryOrFragment(url) {
      return url.includes("?") || url.includes("#");
    }
    function serializePathWithQuery(url, queryParams) {
      if (pathHasQueryOrFragment(url)) {
        throw new Error('Query params cannot be passed when url already contains "?" or "#".');
      }
      const stringified = stringify(queryParams);
      if (stringified) {
        url += "?" + stringified;
      }
      return url;
    }
    function isValidPort(port) {
      const value = parseInt(port, 10);
      return value === Number(port) && value >= 0 && value <= 65535;
    }
    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] === ":");
    }
    function parseURL(url) {
      if (typeof url === "string") {
        url = new URL(url);
        if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
          throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
        }
        return url;
      }
      if (!url || typeof url !== "object") {
        throw new InvalidArgumentError("Invalid URL: The URL argument must be a non-null object.");
      }
      if (!(url instanceof URL)) {
        if (url.port != null && url.port !== "" && isValidPort(url.port) === false) {
          throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer.");
        }
        if (url.path != null && typeof url.path !== "string") {
          throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined.");
        }
        if (url.pathname != null && typeof url.pathname !== "string") {
          throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined.");
        }
        if (url.hostname != null && typeof url.hostname !== "string") {
          throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined.");
        }
        if (url.origin != null && typeof url.origin !== "string") {
          throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined.");
        }
        if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
          throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
        }
        const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80;
        let origin = url.origin != null ? url.origin : `${url.protocol || ""}//${url.hostname || ""}:${port}`;
        let path = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
        if (origin[origin.length - 1] === "/") {
          origin = origin.slice(0, origin.length - 1);
        }
        if (path && path[0] !== "/") {
          path = `/${path}`;
        }
        return new URL(`${origin}${path}`);
      }
      if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
        throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
      }
      return url;
    }
    function parseOrigin(url) {
      url = parseURL(url);
      if (url.pathname !== "/" || url.search || url.hash) {
        throw new InvalidArgumentError("invalid url");
      }
      return url;
    }
    function getHostname(host) {
      if (host[0] === "[") {
        const idx2 = host.indexOf("]");
        assert(idx2 !== -1);
        return host.substring(1, idx2);
      }
      const idx = host.indexOf(":");
      if (idx === -1) return host;
      return host.substring(0, idx);
    }
    function getServerName(host) {
      if (!host) {
        return null;
      }
      assert(typeof host === "string");
      const servername = getHostname(host);
      if (net.isIP(servername)) {
        return "";
      }
      return servername;
    }
    function deepClone(obj) {
      return JSON.parse(JSON.stringify(obj));
    }
    function isAsyncIterable(obj) {
      return !!(obj != null && typeof obj[Symbol.asyncIterator] === "function");
    }
    function isIterable(obj) {
      return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
    }
    function hasSafeIterator(obj) {
      const prototype = Object.getPrototypeOf(obj);
      const ownIterator = Object.hasOwn(obj, Symbol.iterator);
      return ownIterator || prototype != null && prototype !== Object.prototype && typeof obj[Symbol.iterator] === "function";
    }
    function bodyLength(body) {
      if (body == null) {
        return 0;
      } else if (isStream(body)) {
        const state = body._readableState;
        return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null;
      } else if (isBlobLike(body)) {
        return body.size != null ? body.size : null;
      } else if (isBuffer(body)) {
        return body.byteLength;
      }
      return null;
    }
    function isDestroyed(body) {
      return body && !!(body.destroyed || body[kDestroyed] || stream.isDestroyed?.(body));
    }
    function destroy(stream2, err) {
      if (stream2 == null || !isStream(stream2) || isDestroyed(stream2)) {
        return;
      }
      if (typeof stream2.destroy === "function") {
        if (Object.getPrototypeOf(stream2).constructor === IncomingMessage) {
          stream2.socket = null;
        }
        stream2.destroy(err);
      } else if (err) {
        queueMicrotask(() => {
          stream2.emit("error", err);
        });
      }
      if (stream2.destroyed !== true) {
        stream2[kDestroyed] = true;
      }
    }
    var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/;
    function parseKeepAliveTimeout(val) {
      const m = val.match(KEEPALIVE_TIMEOUT_EXPR);
      return m ? parseInt(m[1], 10) * 1e3 : null;
    }
    function headerNameToString(value) {
      return typeof value === "string" ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() : tree.lookup(value) ?? value.toString("latin1").toLowerCase();
    }
    function bufferToLowerCasedHeaderName(value) {
      return tree.lookup(value) ?? value.toString("latin1").toLowerCase();
    }
    function parseHeaders(headers, obj) {
      if (obj === void 0) obj = {};
      for (let i = 0; i < headers.length; i += 2) {
        const key = headerNameToString(headers[i]);
        let val = obj[key];
        if (val !== void 0) {
          if (!Object.hasOwn(obj, key)) {
            const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1");
            if (key === "__proto__") {
              Object.defineProperty(obj, key, {
                value: headersValue,
                enumerable: true,
                configurable: true,
                writable: true
              });
            } else {
              obj[key] = headersValue;
            }
          } else {
            if (typeof val === "string") {
              val = [val];
              obj[key] = val;
            }
            val.push(headers[i + 1].toString("latin1"));
          }
        } else {
          const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1");
          obj[key] = headersValue;
        }
      }
      return obj;
    }
    function parseRawHeaders(headers) {
      if (headers == null) {
        return [];
      }
      if (!Array.isArray(headers)) {
        const rawHeaders = [];
        for (const [name, value] of Object.entries(headers)) {
          if (Array.isArray(value)) {
            for (const entry of value) {
              rawHeaders.push(name, `${entry}`);
            }
          } else {
            rawHeaders.push(name, `${value}`);
          }
        }
        return rawHeaders;
      }
      const headersLength = headers.length;
      const ret = new Array(headersLength);
      let key;
      let val;
      for (let n = 0; n < headersLength; n += 2) {
        key = headers[n];
        val = headers[n + 1];
        typeof key !== "string" && (key = key.toString());
        typeof val !== "string" && (val = val.toString("latin1"));
        ret[n] = key;
        ret[n + 1] = val;
      }
      return ret;
    }
    function toRawHeaders(headers) {
      const rawHeaders = [];
      for (const [name, value] of Object.entries(headers)) {
        if (Array.isArray(value)) {
          for (const entry of value) {
            rawHeaders.push(Buffer.from(name, "latin1"), Buffer.from(`${entry}`, "latin1"));
          }
        } else {
          rawHeaders.push(Buffer.from(name, "latin1"), Buffer.from(`${value}`, "latin1"));
        }
      }
      return rawHeaders;
    }
    function encodeRawHeaders(headers) {
      if (!Array.isArray(headers)) {
        throw new TypeError("expected headers to be an array");
      }
      return headers.map((x) => Buffer.from(x));
    }
    function isBuffer(buffer) {
      return buffer instanceof Uint8Array || Buffer.isBuffer(buffer);
    }
    function assertRequestHandler(handler, method, upgrade) {
      if (!handler || typeof handler !== "object") {
        throw new InvalidArgumentError("handler must be an object");
      }
      if (typeof handler.onRequestStart !== "function") {
        throw new InvalidArgumentError("invalid onRequestStart method");
      }
      if (typeof handler.onResponseError !== "function") {
        throw new InvalidArgumentError("invalid onResponseError method");
      }
      if (typeof handler.onBodySent !== "function" && handler.onBodySent !== void 0) {
        throw new InvalidArgumentError("invalid onBodySent method");
      }
      if (typeof handler.onRequestSent !== "function" && handler.onRequestSent !== void 0) {
        throw new InvalidArgumentError("invalid onRequestSent method");
      }
      if (upgrade || method === "CONNECT") {
        if (typeof handler.onRequestUpgrade !== "function") {
          throw new InvalidArgumentError("invalid onRequestUpgrade method");
        }
      } else {
        if (typeof handler.onResponseStart !== "function") {
          throw new InvalidArgumentError("invalid onResponseStart method");
        }
        if (typeof handler.onResponseData !== "function") {
          throw new InvalidArgumentError("invalid onResponseData method");
        }
        if (typeof handler.onResponseEnd !== "function") {
          throw new InvalidArgumentError("invalid onResponseEnd method");
        }
      }
    }
    function isDisturbed(body) {
      return !!(body && (stream.isDisturbed(body) || body[kBodyUsed]));
    }
    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
      };
    }
    function ReadableStreamFrom(iterable) {
      let iterator;
      return new ReadableStream(
        {
          start() {
            iterator = iterable[Symbol.asyncIterator]();
          },
          pull(controller) {
            return iterator.next().then(({ done, value }) => {
              if (done) {
                return queueMicrotask(() => {
                  controller.close();
                  controller.byobRequest?.respond(0);
                });
              } else {
                const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
                if (buf.byteLength) {
                  return controller.enqueue(new Uint8Array(buf));
                } else {
                  return this.pull(controller);
                }
              }
            });
          },
          cancel() {
            return iterator.return();
          },
          type: "bytes"
        }
      );
    }
    function isFormDataLike(object) {
      return object && typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && object[Symbol.toStringTag] === "FormData";
    }
    function addAbortListener(signal, listener) {
      if (!signal || "aborted" in signal) {
        return addAbortListenerNative(signal, listener)[Symbol.dispose];
      }
      if (typeof signal.addEventListener === "function") {
        signal.addEventListener("abort", listener, { once: true });
        return () => signal.removeEventListener("abort", listener);
      }
      signal.once("abort", listener);
      return () => signal.removeListener("abort", listener);
    }
    var validTokenChars = new Uint8Array([
      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-9:;<=>?)
      0,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      // 64-79 (@A-O)
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      1,
      1,
      // 80-95 (P-Z[\]^_)
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      // 96-111 (`a-o)
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      1,
      0,
      1,
      0,
      // 112-127 (p-z{|}~)
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 128-143
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 144-159
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 160-175
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 176-191
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 192-207
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 208-223
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 224-239
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0
      // 240-255
    ]);
    function isTokenCharCode(c) {
      return validTokenChars[c] === 1;
    }
    var tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
    function isValidHTTPToken(characters) {
      if (characters.length >= 12) return tokenRegExp.test(characters);
      if (characters.length === 0) return false;
      for (let i = 0; i < characters.length; i++) {
        if (validTokenChars[characters.charCodeAt(i)] !== 1) {
          return false;
        }
      }
      return true;
    }
    var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
    function isValidHeaderValue(characters) {
      return !headerCharRegex.test(characters);
    }
    var rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+|\*)?$/;
    function parseRangeHeader(range) {
      if (range == null || range === "") return { start: 0, end: null, size: null };
      if (!range) return null;
      const m = rangeHeaderRegex.exec(range);
      return m ? {
        start: parseInt(m[1]),
        end: m[2] ? parseInt(m[2]) : null,
        size: m[3] && m[3] !== "*" ? parseInt(m[3]) : null
      } : null;
    }
    function addListener(obj, name, listener) {
      const listeners = obj[kListeners] ??= [];
      listeners.push([name, listener]);
      obj.on(name, listener);
      return obj;
    }
    function removeAllListeners(obj) {
      if (obj[kListeners] != null) {
        for (const [name, listener] of obj[kListeners]) {
          obj.removeListener(name, listener);
        }
        obj[kListeners] = null;
      }
      return obj;
    }
    function errorRequest(client, request, err) {
      try {
        request.onResponseError(err);
        assert(request.aborted);
      } catch (err2) {
        client.emit("error", err2);
      }
    }
    var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop;
      }
      let s1 = null;
      let s2 = null;
      const fastTimer = timers.setFastTimeout(() => {
        s1 = setImmediate(() => {
          s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts));
        });
      }, opts.timeout);
      return () => {
        timers.clearFastTimeout(fastTimer);
        clearImmediate(s1);
        clearImmediate(s2);
      };
    } : (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop;
      }
      let s1 = null;
      const fastTimer = timers.setFastTimeout(() => {
        s1 = setImmediate(() => {
          onConnectTimeout(socketWeakRef.deref(), opts);
        });
      }, opts.timeout);
      return () => {
        timers.clearFastTimeout(fastTimer);
        clearImmediate(s1);
      };
    };
    function onConnectTimeout(socket, opts) {
      if (socket == null) {
        return;
      }
      let message = "Connect Timeout Error";
      if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
        message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(", ")},`;
      } else {
        message += ` (attempted address: ${opts.hostname}:${opts.port},`;
      }
      message += ` timeout: ${opts.timeout}ms)`;
      destroy(socket, new ConnectTimeoutError(message));
    }
    function getProtocolFromUrlString(urlString) {
      if (urlString[0] === "h" && urlString[1] === "t" && urlString[2] === "t" && urlString[3] === "p") {
        switch (urlString[4]) {
          case ":":
            return "http:";
          case "s":
            if (urlString[5] === ":") {
              return "https:";
            }
        }
      }
      return urlString.slice(0, urlString.indexOf(":") + 1);
    }
    var kEnumerableProperty = {
      __proto__: null,
      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);
    module.exports = {
      kEnumerableProperty,
      isDisturbed,
      isBlobLike,
      parseOrigin,
      parseURL,
      getServerName,
      isStream,
      isIterable,
      hasSafeIterator,
      isAsyncIterable,
      isDestroyed,
      headerNameToString,
      bufferToLowerCasedHeaderName,
      addListener,
      removeAllListeners,
      errorRequest,
      parseRawHeaders,
      toRawHeaders,
      encodeRawHeaders,
      parseHeaders,
      parseKeepAliveTimeout,
      destroy,
      bodyLength,
      deepClone,
      ReadableStreamFrom,
      isBuffer,
      assertRequestHandler,
      getSocketInfo,
      isFormDataLike,
      pathHasQueryOrFragment,
      serializePathWithQuery,
      addAbortListener,
      isValidHTTPToken,
      isValidHeaderValue,
      isTokenCharCode,
      parseRangeHeader,
      normalizedMethodRecordsBase,
      normalizedMethodRecords,
      isValidPort,
      isHttpOrHttpsPrefixed,
      safeHTTPMethods: Object.freeze(["GET", "HEAD", "OPTIONS", "TRACE"]),
      wrapRequestBody,
      setupConnectTimeout,
      getProtocolFromUrlString
    };
  }
});

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

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

// ../../node_modules/undici/lib/core/request.js
var require_request = __commonJS({
  "../../node_modules/undici/lib/core/request.js"(exports, module) {
    "use strict";
    var {
      InvalidArgumentError,
      NotSupportedError
    } = require_errors();
    var assert = __require("assert");
    var {
      isValidHTTPToken,
      isValidHeaderValue,
      isStream,
      destroy,
      isBuffer,
      isFormDataLike,
      isIterable,
      hasSafeIterator,
      isBlobLike,
      serializePathWithQuery,
      parseHeaders,
      assertRequestHandler,
      getServerName,
      normalizedMethodRecords,
      getProtocolFromUrlString
    } = require_util();
    var { channels } = require_diagnostics();
    var { headerNameLowerCasedRecord } = require_constants();
    var invalidPathRegex = /[^\u0021-\u00ff]/;
    function isValidContentLengthHeaderValue(val) {
      if (typeof val !== "string" || val.length === 0) {
        return false;
      }
      for (let i = 0; i < val.length; i++) {
        const charCode = val.charCodeAt(i);
        if (charCode < 48 || charCode > 57) {
          return false;
        }
      }
      return true;
    }
    var kHandler = /* @__PURE__ */ Symbol("handler");
    var kController = /* @__PURE__ */ Symbol("controller");
    var kResume = /* @__PURE__ */ Symbol("resume");
    var RequestController = class {
      #paused = false;
      #reason = null;
      #aborted = false;
      #abort;
      [kResume] = null;
      rawHeaders = null;
      rawTrailers = null;
      constructor(abort) {
        this.#abort = abort;
      }
      pause() {
        this.#paused = true;
      }
      resume() {
        if (this.#paused) {
          this.#paused = false;
          this[kResume]?.();
        }
      }
      abort(reason) {
        if (!this.#aborted) {
          this.#aborted = true;
          this.#reason = reason;
          this.#abort(reason);
        }
      }
      get aborted() {
        return this.#aborted;
      }
      get reason() {
        return this.#reason;
      }
      get paused() {
        return this.#paused;
      }
    };
    var Request = class {
      constructor(origin, {
        path,
        method,
        body,
        headers,
        query,
        idempotent,
        blocking,
        upgrade,
        headersTimeout,
        bodyTimeout,
        reset,
        expectContinue,
        servername,
        throwOnError,
        maxRedirections,
        typeOfService
      }, handler) {
        if (typeof path !== "string") {
          throw new InvalidArgumentError("path must be a string");
        } else if (path[0] !== "/" && !(path.startsWith("http://") || path.startsWith("https://")) && method !== "CONNECT") {
          throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
        } else if (invalidPathRegex.test(path)) {
          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 (upgrade && !isValidHeaderValue(upgrade)) {
          throw new InvalidArgumentError("invalid upgrade header");
        }
        if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
          throw new InvalidArgumentError("invalid headersTimeout");
        }
        if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
          throw new InvalidArgumentError("invalid bodyTimeout");
        }
        if (reset != null && typeof reset !== "boolean") {
          throw new InvalidArgumentError("invalid reset");
        }
        if (expectContinue != null && typeof expectContinue !== "boolean") {
          throw new InvalidArgumentError("invalid expectContinue");
        }
        if (throwOnError != null) {
          throw new InvalidArgumentError("invalid throwOnError");
        }
        if (maxRedirections != null && maxRedirections !== 0) {
          throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor");
        }
        if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) {
          throw new InvalidArgumentError("typeOfService must be an integer between 0 and 255");
        }
        this.headersTimeout = headersTimeout;
        this.bodyTimeout = bodyTimeout;
        this.method = method;
        this.typeOfService = typeOfService ?? 0;
        this.abort = null;
        if (body == null) {
          this.body = null;
        } else if (isStream(body)) {
          this.body = body;
          const rState = this.body._readableState;
          if (!rState || !rState.autoDestroy) {
            this.endHandler = function autoDestroy() {
              destroy(this);
            };
            this.body.on("end", this.endHandler);
          }
          this.errorHandler = (err) => {
            if (this.abort) {
              this.abort(err);
            } else {
              this.error = err;
            }
          };
          this.body.on("error", this.errorHandler);
        } else if (isBuffer(body)) {
          this.body = body.byteLength ? body : null;
        } else if (ArrayBuffer.isView(body)) {
          this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null;
        } else if (body instanceof ArrayBuffer) {
          this.body = body.byteLength ? Buffer.from(body) : null;
        } else if (typeof body === "string") {
          this.body = body.length ? Buffer.from(body) : null;
        } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) {
          this.body = body;
        } else {
          throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable");
        }
        this.completed = false;
        this.aborted = false;
        this.upgrade = upgrade || null;
        this.path = query ? serializePathWithQuery(path, query) : path;
        this.origin = origin;
        this.protocol = getProtocolFromUrlString(origin);
        this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
        this.blocking = blocking ?? this.method !== "HEAD";
        this.reset = reset == null ? null : reset;
        this.host = null;
        this.contentLength = null;
        this.contentType = null;
        this.headers = [];
        this.expectContinue = expectContinue != null ? expectContinue : false;
        if (Array.isArray(headers)) {
          if (headers.length % 2 !== 0) {
            throw new InvalidArgumentError("headers array must be even");
          }
          for (let i = 0; i < headers.length; i += 2) {
            processHeader(this, headers[i], headers[i + 1]);
          }
        } else if (headers && typeof headers === "object") {
          if (hasSafeIterator(headers)) {
            for (const header of headers) {
              if (!Array.isArray(header) || header.length !== 2) {
                throw new InvalidArgumentError("headers must be in key-value pair format");
              }
              processHeader(this, header[0], header[1]);
            }
          } else {
            const keys = Object.keys(headers);
            for (let i = 0; i < keys.length; ++i) {
              processHeader(this, keys[i], headers[keys[i]]);
            }
          }
        } else if (headers != null) {
          throw new InvalidArgumentError("headers must be an object or an array");
        }
        assertRequestHandler(handler, method, upgrade);
        this.servername = servername || getServerName(this.host) || null;
        this[kHandler] = handler;
        if (channels.create.hasSubscribers) {
          channels.create.publish({ request: this });
        }
      }
      onBodySent(chunk) {
        if (channels.bodyChunkSent.hasSubscribers) {
          channels.bodyChunkSent.publish({ request: this, chunk });
        }
        if (this[kHandler].onBodySent) {
          try {
            return this[kHandler].onBodySent(chunk);
          } catch (err) {
            this.abort(err);
          }
        }
      }
      onRequestSent() {
        if (channels.bodySent.hasSubscribers) {
          channels.bodySent.publish({ request: this });
        }
        if (this[kHandler].onRequestSent) {
          try {
            return this[kHandler].onRequestSent();
          } catch (err) {
            this.abort(err);
          }
        }
      }
      onRequestStart(abort, context) {
        assert(!this.aborted);
        assert(!this.completed);
        this[kController] = new RequestController(abort);
        if (this.error) {
          this[kController].abort(this.error);
          return;
        }
        this.abort = abort;
        return this[kHandler].onRequestStart(this[kController], context);
      }
      onResponseStarted() {
        return this[kHandler].onResponseStarted?.();
      }
      onResponseStart(statusCode, headers, resume, statusText) {
        assert(!this.aborted);
        assert(!this.completed);
        if (channels.headers.hasSubscribers) {
          channels.headers.publish({ request: this, response: { statusCode, headers, statusText } });
        }
        const controller = this[kController];
        if (controller) {
          controller[kResume] = resume;
          controller.rawHeaders = headers;
        }
        const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers;
        try {
          this[kHandler].onResponseStart?.(controller, statusCode, parsedHeaders, statusText);
          return !controller?.paused;
        } catch (err) {
          this.abort(err);
          return false;
        }
      }
      onResponseData(chunk) {
        assert(!this.aborted);
        assert(!this.completed);
        if (channels.bodyChunkReceived.hasSubscribers) {
          channels.bodyChunkReceived.publish({ request: this, chunk });
        }
        const controller = this[kController];
        try {
          this[kHandler].onResponseData?.(controller, chunk);
          return !controller?.paused;
        } catch (err) {
          this.abort(err);
          return false;
        }
      }
      onRequestUpgrade(statusCode, headers, socket) {
        assert(!this.aborted);
        assert(!this.completed);
        const controller = this[kController];
        if (controller) {
          controller.rawHeaders = headers;
        }
        const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers;
        return this[kHandler].onRequestUpgrade?.(controller, statusCode, parsedHeaders, socket);
      }
      onResponseEnd(trailers) {
        this.onFinally();
        assert(!this.aborted);
        assert(!this.completed);
        this.completed = true;
        if (channels.trailers.hasSubscribers) {
          channels.trailers.publish({ request: this, trailers });
        }
        const controller = this[kController];
        if (controller) {
          controller.rawTrailers = trailers;
        }
        const parsedTrailers = Array.isArray(trailers) ? parseHeaders(trailers) : trailers;
        try {
          return this[kHandler].onResponseEnd?.(controller, parsedTrailers);
        } catch (err) {
          this.onResponseError(err);
        }
      }
      onResponseError(error) {
        this.onFinally();
        if (channels.error.hasSubscribers) {
          channels.error.publish({ request: this, error });
        }
        if (this.aborted) {
          return;
        }
        this.aborted = true;
        const controller = this[kController];
        return this[kHandler].onResponseError?.(controller, error);
      }
      onFinally() {
        if (this.errorHandler) {
          this.body.off("error", this.errorHandler);
          this.errorHandler = null;
        }
        if (this.endHandler) {
          this.body.off("end", this.endHandler);
          this.endHandler = null;
        }
      }
      addHeader(key, value) {
        processHeader(this, key, value);
        return this;
      }
    };
    function processHeader(request, key, val) {
      if (val && (typeof val === "object" && !Array.isArray(val))) {
        throw new InvalidArgumentError(`invalid ${key} header`);
      } else if (val === void 0) {
        return;
      }
      let headerName = headerNameLowerCasedRecord[key];
      if (headerName === void 0) {
        headerName = key.toLowerCase();
        if (headerNameLowerCasedRecord[headerName] === void 0 && !isValidHTTPToken(headerName)) {
          throw new InvalidArgumentError("invalid header key");
        }
      }
      if (Array.isArray(val)) {
        const arr = [];
        for (let i = 0; i < val.length; i++) {
          if (typeof val[i] === "string") {
            if (!isValidHeaderValue(val[i])) {
              throw new InvalidArgumentError(`invalid ${key} header`);
            }
            arr.push(val[i]);
          } else if (val[i] === null) {
            arr.push("");
          } else if (typeof val[i] === "object") {
            throw new InvalidArgumentError(`invalid ${key} header`);
          } else {
            arr.push(`${val[i]}`);
          }
        }
        val = arr;
      } else if (typeof val === "string") {
        if (!isValidHeaderValue(val)) {
          throw new InvalidArgumentError(`invalid ${key} header`);
        }
      } else if (val === null) {
        val = "";
      } else {
        val = `${val}`;
      }
      if (headerName === "host") {
        if (request.host !== null) {
          throw new InvalidArgumentError("duplicate host header");
        }
        if (typeof val !== "string") {
          throw new InvalidArgumentError("invalid host header");
        }
        request.host = val;
      } else if (headerName === "content-length") {
        if (request.contentLength !== null) {
          throw new InvalidArgumentError("duplicate content-length header");
        }
        if (!isValidContentLengthHeaderValue(val)) {
          throw new InvalidArgumentError("invalid content-length header");
        }
        request.contentLength = parseInt(val, 10);
      } else if (request.contentType === null && headerName === "content-type") {
        request.contentType = val;
        request.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 : null;
        if (value === null) {
          throw new InvalidArgumentError("invalid connection header");
        }
        for (const token of value.toLowerCase().split(",")) {
          const trimmed = token.trim();
          if (!isValidHTTPToken(trimmed)) {
            throw new InvalidArgumentError("invalid connection header");
          }
          if (trimmed === "close") {
            request.reset = true;
          }
        }
      } else if (headerName === "expect") {
        throw new NotSupportedError("expect header not supported");
      } else {
        request.headers.push(key, val);
      }
    }
    module.exports = Request;
  }
});

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

// ../../node_modules/undici/lib/dispatcher/dispatcher-base.js
var require_dispatcher_base = __commonJS({
  "../../node_modules/undici/lib/dispatcher/dispatcher-base.js"(exports, module) {
    "use strict";
    var Dispatcher = require_dispatcher();
    var {
      ClientDestroyedError,
      ClientClosedError,
      InvalidArgumentError
    } = require_errors();
    var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols();
    var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed");
    var kOnClosed = /* @__PURE__ */ Symbol("onClosed");
    var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions");
    var DispatcherBase = class extends Dispatcher {
      /** @type {boolean} */
      [kDestroyed] = false;
      /** @type {Array<Function|null} */
      [kOnDestroyed] = null;
      /** @type {boolean} */
      [kClosed] = false;
      /** @type {Array<Function>|null} */
      [kOnClosed] = null;
      /**
       * @param {import('../../types/dispatcher').DispatcherOptions} [opts]
       */
      constructor(opts) {
        super();
        this[kWebSocketOptions] = opts?.webSocket ?? {};
      }
      /**
       * @returns {import('../../types/dispatcher').WebSocketOptions}
       */
      get webSocketOptions() {
        return {
          maxFragments: this[kWebSocketOptions].maxFragments ?? 131072,
          maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024
          // 128 MB default
        };
      }
      /** @returns {boolean} */
      get destroyed() {
        return this[kDestroyed];
      }
      /** @returns {boolean} */
      get closed() {
        return this[kClosed];
      }
      close(callback) {
        if (callback === void 0) {
          return new Promise((resolve, reject) => {
            this.close((err, data) => {
              return err ? reject(err) : resolve(data);
            });
          });
        }
        if (typeof callback !== "function") {
          throw new InvalidArgumentError("invalid callback");
        }
        if (this[kDestroyed]) {
          const err = new ClientDestroyedError();
          queueMicrotask(() => callback(err, null));
          return;
        }
        if (this[kClosed]) {
          if (this[kOnClosed]) {
            this[kOnClosed].push(callback);
          } else {
            queueMicrotask(() => callback(null, null));
          }
          return;
        }
        this[kClosed] = true;
        this[kOnClosed] ??= [];
        this[kOnClosed].push(callback);
        const onClosed = () => {
          const callbacks = this[kOnClosed];
          this[kOnClosed] = null;
          for (let i = 0; i < callbacks.length; i++) {
            callbacks[i](null, null);
          }
        };
        this[kClose]().then(() => this.destroy()).then(() => queueMicrotask(onClosed));
      }
      destroy(err, callback) {
        if (typeof err === "function") {
          callback = err;
          err = null;
        }
        if (callback === void 0) {
          return new Promise((resolve, reject) => {
            this.destroy(err, (err2, data) => {
              return err2 ? reject(err2) : resolve(data);
            });
          });
        }
        if (typeof callback !== "function") {
          throw new InvalidArgumentError("invalid callback");
        }
        if (this[kDestroyed]) {
          if (this[kOnDestroyed]) {
            this[kOnDestroyed].push(callback);
          } else {
            queueMicrotask(() => callback(null, null));
          }
          return;
        }
        if (!err) {
          err = new ClientDestroyedError();
        }
        this[kDestroyed] = true;
        this[kOnDestroyed] ??= [];
        this[kOnDestroyed].push(callback);
        const onDestroyed = () => {
          const callbacks = this[kOnDestroyed];
          this[kOnDestroyed] = null;
          for (let i = 0; i < callbacks.length; i++) {
            callbacks[i](null, null);
          }
        };
        this[kDestroy](err).then(() => queueMicrotask(onDestroyed));
      }
      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 (opts.dispatcher) {
            throw new InvalidArgumentError("opts.dispatcher is not supported by instance methods. Pass opts.dispatcher to the top-level undici functions or call the dispatcher instance method directly.");
          }
          if (this[kDestroyed] || this[kOnDestroyed]) {
            throw new ClientDestroyedError();
          }
          if (this[kClosed]) {
            throw new ClientClosedError();
          }
          return this[kDispatch](opts, handler);
        } catch (err) {
          if (typeof handler.onResponseError !== "function") {
            throw err;
          }
          handler.onResponseError(null, err);
          return false;
        }
      }
    };
    module.exports = DispatcherBase;
  }
});

// ../../node_modules/undici/lib/core/connect.js
var require_connect = __commonJS({
  "../../node_modules/undici/lib/core/connect.js"(exports, module) {
    "use strict";
    var net = __require("net");
    var assert = __require("assert");
    var util = require_util();
    var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
    var tls;
    var SessionCache = class WeakSessionCache {
      constructor(maxCachedSessions) {
        this._maxCachedSessions = maxCachedSessions;
        this._sessionCache = /* @__PURE__ */ new Map();
        this._sessionRegistry = new FinalizationRegistry((key) => {
          if (this._sessionCache.size < this._maxCachedSessions) {
            return;
          }
          const ref = this._sessionCache.get(key);
          if (ref !== void 0 && ref.deref() === void 0) {
            this._sessionCache.delete(key);
          }
        });
      }
      get(sessionKey) {
        const ref = this._sessionCache.get(sessionKey);
        return ref ? ref.deref() : null;
      }
      set(sessionKey, session) {
        if (this._maxCachedSessions === 0) {
          return;
        }
        if (this._sessionCache.has(sessionKey)) {
          this._sessionCache.delete(sessionKey);
        } else if (this._sessionCache.size >= this._maxCachedSessions) {
          for (const [key, ref] of this._sessionCache) {
            if (ref.deref() === void 0) {
              this._sessionCache.delete(key);
              return;
            }
          }
          const oldest = this._sessionCache.keys().next();
          if (!oldest.done) {
            this._sessionCache.delete(oldest.value);
          }
        }
        this._sessionCache.set(sessionKey, new WeakRef(session));
        this._sessionRegistry.register(session, sessionKey);
      }
    };
    function buildConnector({ allowH2, preferH2, useH2c, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) {
      if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
        throw new InvalidArgumentError("maxCachedSessions must be a positive integer or zero");
      }
      const options = { path: socketPath, ...opts };
      const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions);
      timeout = timeout == null ? 1e4 : timeout;
      allowH2 = allowH2 != null ? allowH2 : true;
      return function connect({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
        let socket;
        if (protocol === "https:") {
          if (!tls) {
            tls = __require("tls");
          }
          servername = servername || options.servername || util.getServerName(host) || null;
          const sessionKey = servername || hostname;
          assert(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...
            ...options,
            servername,
            session,
            localAddress,
            ALPNProtocols: allowH2 ? preferH2 ? ["h2", "http/1.1"] : ["http/1.1", "h2"] : ["http/1.1"],
            socket: httpSocket,
            // upgrade socket connection
            port,
            host: hostname
          });
          socket.on("session", function(session2) {
            sessionCache.set(sessionKey, session2);
          });
        } else {
          assert(!httpSocket, "httpSocket can only be sent on TLS update");
          port = port || 80;
          socket = net.connect({
            highWaterMark: 64 * 1024,
            // Same as nodejs fs streams.
            ...options,
            localAddress,
            port,
            host: hostname
          });
          if (useH2c === true) {
            socket.alpnProtocol = "h2";
          }
        }
        if (options.keepAlive == null || options.keepAlive) {
          const keepAliveInitialDelay = options.keepAliveInitialDelay === void 0 ? 6e4 : options.keepAliveInitialDelay;
          socket.setKeepAlive(true, keepAliveInitialDelay);
        }
        const clearConnectTimeout = util.setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port });
        socket.setNoDelay(true).once(protocol === "https:" ? "secureConnect" : "connect", function() {
          queueMicrotask(clearConnectTimeout);
          if (callback) {
            const cb = callback;
            callback = null;
            cb(null, this);
          }
        }).on("error", function(err) {
          queueMicrotask(clearConnectTimeout);
          if (callback) {
            const cb = callback;
            callback = null;
            cb(maybeNormalizeConnectError(err, this, { timeout, hostname, port }));
          }
        });
        return socket;
      };
    }
    function maybeNormalizeConnectError(err, socket, opts) {
      if (err instanceof AggregateError && (err.code === "ETIMEDOUT" || err.errors.some((e) => e != null && e.code === "ETIMEDOUT"))) {
        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)`;
        const wrapped = new ConnectTimeoutError(message);
        wrapped.cause = err;
        return wrapped;
      }
      return err;
    }
    module.exports = buildConnector;
  }
});

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

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

// ../../node_modules/undici/lib/llhttp/llhttp-wasm.js
var require_llhttp_wasm = __commonJS({
  "../../node_modules/undici/lib/llhttp/llhttp-wasm.js"(exports, module) {
    "use strict";
    var { Buffer: Buffer2 } = __require("buffer");
    var wasmBase64 = " ";
    var wasmBuffer;
    Object.defineProperty(module, "exports", {
      get: () => {
        return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer2.from(wasmBase64, "base64");
      }
    });
  }
});

// ../../node_modules/undici/lib/llhttp/llhttp_simd-wasm.js
var require_llhttp_simd_wasm = __commonJS({
  "../../node_modules/undici/lib/llhttp/llhttp_simd-wasm.js"(exports, module) {
    "use strict";
    var { Buffer: Buffer2 } = __require("buffer");
    var wasmBase64 = " ";
    var wasmBuffer;
    Object.defineProperty(module, "exports", {
      get: () => {
        return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer2.from(wasmBase64, "base64");
      }
    });
  }
});

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

// ../../node_modules/undici/lib/web/fetch/global.js
var require_global = __commonJS({
  "../../node_modules/undici/lib/web/fetch/global.js"(exports, module) {
    "use strict";
    var globalOrigin = /* @__PURE__ */ Symbol.for("undici.globalOrigin.1");
    function getGlobalOrigin() {
      return globalThis[globalOrigin];
    }
    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
      });
    }
    module.exports = {
      getGlobalOrigin,
      setGlobalOrigin
    };
  }
});

// ../../node_modules/undici/lib/encoding/index.js
var require_encoding = __commonJS({
  "../../node_modules/undici/lib/encoding/index.js"(exports, module) {
    "use strict";
    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;
    }
    module.exports = {
      utf8DecodeBytes
    };
  }
});

// ../../node_modules/undici/lib/web/infra/index.js
var require_infra = __commonJS({
  "../../node_modules/undici/lib/web/infra/index.js"(exports, module) {
    "use strict";
    var assert = __require("assert");
    var { utf8DecodeBytes } = require_encoding();
    function collectASequenceOfCodePoints(condition, input, position) {
      let result = "";
      while (position.position < input.length && condition(input[position.position])) {
        result += input[position.position];
        position.position++;
      }
      return result;
    }
    function collectASequenceOfCodePointsFast(char, input, position) {
      const idx = input.indexOf(char, position.position);
      const start = position.position;
      if (idx === -1) {
        position.position = input.length;
        return input.slice(start);
      }
      position.position = idx;
      return input.slice(start, position.position);
    }
    var ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g;
    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);
    }
    function isASCIIWhitespace(char) {
      return char === 9 || // \t
      char === 10 || // \n
      char === 12 || // \f
      char === 13 || // \r
      char === 32;
    }
    function isomorphicDecode(input) {
      const length = input.length;
      if ((2 << 15) - 1 > length) {
        return String.fromCharCode.apply(null, input);
      }
      let result = "";
      let i = 0;
      let addition = (2 << 15) - 1;
      while (i < length) {
        if (i + addition > length) {
          addition = length - i;
        }
        result += String.fromCharCode.apply(null, input.subarray(i, i += addition));
      }
      return result;
    }
    var invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/;
    function isomorphicEncode(input) {
      assert(!invalidIsomorphicEncodeValueRegex.test(input));
      return input;
    }
    function parseJSONFromBytes(bytes) {
      return JSON.parse(utf8DecodeBytes(bytes));
    }
    function removeASCIIWhitespace(str, leading = true, trailing = true) {
      return removeChars(str, leading, trailing, isASCIIWhitespace);
    }
    function removeChars(str, leading, trailing, predicate) {
      let lead = 0;
      let trail = str.length - 1;
      if (leading) {
        while (lead < str.length && predicate(str.charCodeAt(lead))) lead++;
      }
      if (trailing) {
        while (trail > 0 && predicate(str.charCodeAt(trail))) trail--;
      }
      return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1);
    }
    function serializeJavascriptValueToJSONString(value) {
      const result = JSON.stringify(value);
      if (result === void 0) {
        throw new TypeError("Value is not JSON serializable");
      }
      assert(typeof result === "string");
      return result;
    }
    module.exports = {
      collectASequenceOfCodePoints,
      collectASequenceOfCodePointsFast,
      forgivingBase64,
      isASCIIWhitespace,
      isomorphicDecode,
      isomorphicEncode,
      parseJSONFromBytes,
      removeASCIIWhitespace,
      removeChars,
      serializeJavascriptValueToJSONString
    };
  }
});

// ../../node_modules/undici/lib/web/fetch/data-url.js
var require_data_url = __commonJS({
  "../../node_modules/undici/lib/web/fetch/data-url.js"(exports, module) {
    "use strict";
    var assert = __require("assert");
    var { forgivingBase64, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, isomorphicDecode, removeASCIIWhitespace, removeChars } = require_infra();
    var encoder = new TextEncoder();
    var HTTP_TOKEN_CODEPOINTS = /^[-!#$%&'*+.^_|~A-Za-z0-9]+$/u;
    var HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/u;
    var HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/u;
    function dataURLProcessor(dataURL) {
      assert(dataURL.protocol === "data:");
      let input = URLSerializer(dataURL, true);
      input = input.slice(5);
      const position = { position: 0 };
      let mimeType = collectASequenceOfCodePointsFast(
        ",",
        input,
        position
      );
      const mimeTypeLength = mimeType.length;
      mimeType = removeASCIIWhitespace(mimeType, true, true);
      if (position.position >= input.length) {
        return "failure";
      }
      position.position++;
      const encodedBody = input.slice(mimeTypeLength + 1);
      let body = stringPercentDecode(encodedBody);
      if (/;(?:\u0020*)base64$/ui.test(mimeType)) {
        const stringBody = isomorphicDecode(body);
        body = forgivingBase64(stringBody);
        if (body === "failure") {
          return "failure";
        }
        mimeType = mimeType.slice(0, -6);
        mimeType = mimeType.replace(/(\u0020+)$/u, "");
        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 };
    }
    function URLSerializer(url, excludeFragment = false) {
      if (!excludeFragment) {
        return url.href;
      }
      const href = url.href;
      const hashLength = url.hash.length;
      const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength);
      if (!hashLength && href.endsWith("#")) {
        return serialized.slice(0, -1);
      }
      return serialized;
    }
    function stringPercentDecode(input) {
      const bytes = encoder.encode(input);
      return percentDecode(bytes);
    }
    function isHexCharByte(byte) {
      return byte >= 48 && byte <= 57 || byte >= 65 && byte <= 70 || byte >= 97 && byte <= 102;
    }
    function hexByteToNumber(byte) {
      return (
        // 0-9
        byte >= 48 && byte <= 57 ? byte - 48 : (byte & 223) - 55
      );
    }
    function percentDecode(input) {
      const length = input.length;
      const output = new Uint8Array(length);
      let j = 0;
      let i = 0;
      while (i < length) {
        const byte = input[i];
        if (byte !== 37) {
          output[j++] = byte;
        } else if (byte === 37 && !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))) {
          output[j++] = 37;
        } else {
          output[j++] = hexByteToNumber(input[i + 1]) << 4 | hexByteToNumber(input[i + 2]);
          i += 2;
        }
        ++i;
      }
      return length === j ? output : output.subarray(0, j);
    }
    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;
    }
    function collectAnHTTPQuotedString(input, position, extractValue = false) {
      const positionStart = position.position;
      let value = "";
      assert(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 {
          assert(quoteOrBackslash === '"');
          break;
        }
      }
      if (extractValue) {
        return value;
      }
      return input.slice(positionStart, position.position);
    }
    function serializeAMimeType(mimeType) {
      assert(mimeType !== "failure");
      const { parameters, essence } = mimeType;
      let serialization = essence;
      for (let [name, value] of parameters.entries()) {
        serialization += ";";
        serialization += name;
        serialization += "=";
        if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
          value = value.replace(/[\\"]/ug, "\\$&");
          value = '"' + value;
          value += '"';
        }
        serialization += value;
      }
      return serialization;
    }
    function isHTTPWhiteSpace(char) {
      return char === 13 || char === 10 || char === 9 || char === 32;
    }
    function removeHTTPWhitespace(str, leading = true, trailing = true) {
      return removeChars(str, leading, trailing, isHTTPWhiteSpace);
    }
    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 "";
    }
    module.exports = {
      dataURLProcessor,
      URLSerializer,
      stringPercentDecode,
      parseMIMEType,
      collectAnHTTPQuotedString,
      serializeAMimeType,
      removeHTTPWhitespace,
      minimizeSupportedMimeType,
      HTTP_TOKEN_CODEPOINTS
    };
  }
});

// ../../node_modules/undici/lib/web/webidl/index.js
var require_webidl = __commonJS({
  "../../node_modules/undici/lib/web/webidl/index.js"(exports, module) {
    "use strict";
    var assert = __require("assert");
    var { types, inspect } = __require("util");
    var { markAsUncloneable } = __require("worker_threads");
    var UNDEFINED = 1;
    var BOOLEAN = 2;
    var STRING = 3;
    var SYMBOL = 4;
    var NUMBER = 5;
    var BIGINT = 6;
    var NULL = 7;
    var OBJECT = 8;
    var FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]);
    var webidl = {
      converters: {},
      util: {},
      errors: {},
      is: {}
    };
    webidl.errors.exception = function(message) {
      return new TypeError(`${message.header}: ${message.message}`);
    };
    webidl.errors.conversionFailed = function(opts) {
      const plural = opts.types.length === 1 ? "" : " one of";
      const message = `${opts.argument} could not be converted to${plural}: ${opts.types.join(", ")}.`;
      return webidl.errors.exception({
        header: opts.prefix,
        message
      });
    };
    webidl.errors.invalidArgument = function(context) {
      return webidl.errors.exception({
        header: context.prefix,
        message: `"${context.value}" is an invalid ${context.type}.`
      });
    };
    webidl.brandCheck = function(V, I) {
      if (!FunctionPrototypeSymbolHasInstance(I, V)) {
        const err = new TypeError("Illegal invocation");
        err.code = "ERR_INVALID_THIS";
        throw err;
      }
    };
    webidl.brandCheckMultiple = function(List) {
      const prototypes = List.map((c) => webidl.util.MakeTypeAssertion(c));
      return (V) => {
        if (prototypes.every((typeCheck) => !typeCheck(V))) {
          const err = new TypeError("Illegal invocation");
          err.code = "ERR_INVALID_THIS";
          throw err;
        }
      };
    };
    webidl.argumentLengthCheck = function({ length }, min, ctx) {
      if (length < min) {
        throw webidl.errors.exception({
          message: `${min} argument${min !== 1 ? "s" : ""} required, but${length ? " only" : ""} ${length} found.`,
          header: ctx
        });
      }
    };
    webidl.illegalConstructor = function() {
      throw webidl.errors.exception({
        header: "TypeError",
        message: "Illegal constructor"
      });
    };
    webidl.util.MakeTypeAssertion = function(I) {
      return (O) => FunctionPrototypeSymbolHasInstance(I, O);
    };
    webidl.util.Type = function(V) {
      switch (typeof V) {
        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 (V === null) {
            return NULL;
          }
          return OBJECT;
        }
      }
    };
    webidl.util.Types = {
      UNDEFINED,
      BOOLEAN,
      STRING,
      SYMBOL,
      NUMBER,
      BIGINT,
      NULL,
      OBJECT
    };
    webidl.util.TypeValueToString = function(o) {
      switch (webidl.util.Type(o)) {
        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 NULL:
          return "Null";
        case OBJECT:
          return "Object";
      }
    };
    webidl.util.markAsUncloneable = markAsUncloneable;
    webidl.util.ConvertToInt = function(V, bitLength, signedness, flags) {
      let upperBound;
      let lowerBound;
      if (bitLength === 64) {
        upperBound = Math.pow(2, 53) - 1;
        if (signedness === "unsigned") {
          lowerBound = 0;
        } else {
          lowerBound = Math.pow(-2, 53) + 1;
        }
      } else if (signedness === "unsigned") {
        lowerBound = 0;
        upperBound = Math.pow(2, bitLength) - 1;
      } else {
        lowerBound = -Math.pow(2, bitLength - 1);
        upperBound = Math.pow(2, bitLength - 1) - 1;
      }
      let x = Number(V);
      if (x === 0) {
        x = 0;
      }
      if (webidl.util.HasFlag(flags, webidl.attributes.EnforceRange)) {
        if (Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) {
          throw webidl.errors.exception({
            header: "Integer conversion",
            message: `Could not convert ${webidl.util.Stringify(V)} to an integer.`
          });
        }
        x = webidl.util.IntegerPart(x);
        if (x < lowerBound || x > upperBound) {
          throw webidl.errors.exception({
            header: "Integer conversion",
            message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
          });
        }
        return x;
      }
      if (!Number.isNaN(x) && webidl.util.HasFlag(flags, webidl.attributes.Clamp)) {
        x = Math.min(Math.max(x, lowerBound), upperBound);
        if (Math.floor(x) % 2 === 0) {
          x = Math.floor(x);
        } else {
          x = Math.ceil(x);
        }
        return x;
      }
      if (Number.isNaN(x) || x === 0 && Object.is(0, x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) {
        return 0;
      }
      x = webidl.util.IntegerPart(x);
      x = x % Math.pow(2, bitLength);
      if (signedness === "signed" && x >= Math.pow(2, bitLength - 1)) {
        return x - Math.pow(2, bitLength);
      }
      return x;
    };
    webidl.util.IntegerPart = function(n) {
      const r = Math.floor(Math.abs(n));
      if (n < 0) {
        return -1 * r;
      }
      return r;
    };
    webidl.util.Stringify = function(V) {
      const type = webidl.util.Type(V);
      switch (type) {
        case SYMBOL:
          return `Symbol(${V.description})`;
        case OBJECT:
          return inspect(V);
        case STRING:
          return `"${V}"`;
        case BIGINT:
          return `${V}n`;
        default:
          return `${V}`;
      }
    };
    webidl.util.IsResizableArrayBuffer = function(V) {
      if (types.isArrayBuffer(V)) {
        return V.resizable;
      }
      if (types.isSharedArrayBuffer(V)) {
        return V.growable;
      }
      throw webidl.errors.exception({
        header: "IsResizableArrayBuffer",
        message: `"${webidl.util.Stringify(V)}" is not an array buffer.`
      });
    };
    webidl.util.HasFlag = function(flags, attributes) {
      return typeof flags === "number" && (flags & attributes) === attributes;
    };
    webidl.sequenceConverter = function(converter) {
      return (V, prefix, argument, Iterable) => {
        if (webidl.util.Type(V) !== OBJECT) {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.`
          });
        }
        const method = typeof Iterable === "function" ? Iterable() : V?.[Symbol.iterator]?.();
        const seq = [];
        let index = 0;
        if (method === void 0 || typeof method.next !== "function") {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} is not iterable.`
          });
        }
        while (true) {
          const { done, value } = method.next();
          if (done) {
            break;
          }
          seq.push(converter(value, prefix, `${argument}[${index++}]`));
        }
        return seq;
      };
    };
    webidl.recordConverter = function(keyConverter, valueConverter) {
      return (O, prefix, argument) => {
        if (webidl.util.Type(O) !== OBJECT) {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} ("${webidl.util.TypeValueToString(O)}") is not an Object.`
          });
        }
        const result = {};
        if (!types.isProxy(O)) {
          const keys2 = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)];
          for (const key of keys2) {
            const keyName = webidl.util.Stringify(key);
            const typedKey = keyConverter(key, prefix, `Key ${keyName} in ${argument}`);
            const typedValue = valueConverter(O[key], prefix, `${argument}[${keyName}]`);
            result[typedKey] = typedValue;
          }
          return result;
        }
        const keys = Reflect.ownKeys(O);
        for (const key of keys) {
          const desc = Reflect.getOwnPropertyDescriptor(O, key);
          if (desc?.enumerable) {
            const typedKey = keyConverter(key, prefix, argument);
            const typedValue = valueConverter(O[key], prefix, argument);
            result[typedKey] = typedValue;
          }
        }
        return result;
      };
    };
    webidl.interfaceConverter = function(TypeCheck, name) {
      return (V, prefix, argument) => {
        if (!TypeCheck(V)) {
          throw webidl.errors.exception({
            header: prefix,
            message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${name}.`
          });
        }
        return V;
      };
    };
    webidl.dictionaryConverter = function(converters) {
      converters.sort((a, b) => (a.key > b.key) - (a.key < b.key));
      return (dictionary, prefix, argument) => {
        const dict = {};
        if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) {
          throw webidl.errors.exception({
            header: prefix,
            message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
          });
        }
        for (const options of converters) {
          const { key, defaultValue, required, converter } = options;
          if (required === true) {
            if (dictionary == null || !Object.hasOwn(dictionary, key)) {
              throw webidl.errors.exception({
                header: prefix,
                message: `Missing required key "${key}".`
              });
            }
          }
          let value = dictionary?.[key];
          const hasDefault = defaultValue !== void 0;
          if (hasDefault && value === void 0) {
            value = defaultValue();
          }
          if (required || hasDefault || value !== void 0) {
            value = converter(value, prefix, `${argument}.${key}`);
            if (options.allowedValues && !options.allowedValues.includes(value)) {
              throw webidl.errors.exception({
                header: prefix,
                message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(", ")}.`
              });
            }
            dict[key] = value;
          }
        }
        return dict;
      };
    };
    webidl.nullableConverter = function(converter) {
      return (V, prefix, argument) => {
        if (V === null) {
          return V;
        }
        return converter(V, prefix, argument);
      };
    };
    webidl.is.USVString = function(value) {
      return typeof value === "string" && value.isWellFormed();
    };
    webidl.is.ReadableStream = webidl.util.MakeTypeAssertion(ReadableStream);
    webidl.is.Blob = webidl.util.MakeTypeAssertion(Blob);
    webidl.is.URLSearchParams = webidl.util.MakeTypeAssertion(URLSearchParams);
    webidl.is.File = webidl.util.MakeTypeAssertion(File);
    webidl.is.URL = webidl.util.MakeTypeAssertion(URL);
    webidl.is.AbortSignal = webidl.util.MakeTypeAssertion(AbortSignal);
    webidl.is.MessagePort = webidl.util.MakeTypeAssertion(MessagePort);
    webidl.is.BufferSource = function(V) {
      return types.isArrayBuffer(V) || ArrayBuffer.isView(V) && types.isArrayBuffer(V.buffer);
    };
    webidl.util.getCopyOfBytesHeldByBufferSource = function(bufferSource) {
      const jsBufferSource = bufferSource;
      let jsArrayBuffer = jsBufferSource;
      let offset = 0;
      let length = 0;
      if (types.isTypedArray(jsBufferSource) || types.isDataView(jsBufferSource)) {
        jsArrayBuffer = jsBufferSource.buffer;
        offset = jsBufferSource.byteOffset;
        length = jsBufferSource.byteLength;
      } else {
        assert(types.isAnyArrayBuffer(jsBufferSource));
        length = jsBufferSource.byteLength;
      }
      if (jsArrayBuffer.detached) {
        return new Uint8Array(0);
      }
      const bytes = new Uint8Array(length);
      const view = new Uint8Array(jsArrayBuffer, offset, length);
      bytes.set(view);
      return bytes;
    };
    webidl.converters.DOMString = function(V, prefix, argument, flags) {
      if (V === null && webidl.util.HasFlag(flags, webidl.attributes.LegacyNullToEmptyString)) {
        return "";
      }
      if (typeof V === "symbol") {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} is a symbol, which cannot be converted to a DOMString.`
        });
      }
      return String(V);
    };
    webidl.converters.ByteString = function(V, prefix, argument) {
      if (typeof V === "symbol") {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} is a symbol, which cannot be converted to a ByteString.`
        });
      }
      const x = String(V);
      for (let index = 0; index < x.length; index++) {
        if (x.charCodeAt(index) > 255) {
          throw new TypeError(
            `Cannot convert argument to a ByteString because the character at index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
          );
        }
      }
      return x;
    };
    webidl.converters.USVString = function(value) {
      if (typeof value === "string") {
        return value.toWellFormed();
      }
      return `${value}`.toWellFormed();
    };
    webidl.converters.boolean = function(V) {
      const x = Boolean(V);
      return x;
    };
    webidl.converters.any = function(V) {
      return V;
    };
    webidl.converters["long long"] = function(V, prefix, argument) {
      const x = webidl.util.ConvertToInt(V, 64, "signed", 0, prefix, argument);
      return x;
    };
    webidl.converters["unsigned long long"] = function(V, prefix, argument) {
      const x = webidl.util.ConvertToInt(V, 64, "unsigned", 0, prefix, argument);
      return x;
    };
    webidl.converters["unsigned long"] = function(V, prefix, argument) {
      const x = webidl.util.ConvertToInt(V, 32, "unsigned", 0, prefix, argument);
      return x;
    };
    webidl.converters["unsigned short"] = function(V, prefix, argument, flags) {
      const x = webidl.util.ConvertToInt(V, 16, "unsigned", flags, prefix, argument);
      return x;
    };
    webidl.converters.ArrayBuffer = function(V, prefix, argument, flags) {
      if (webidl.util.Type(V) !== OBJECT || !types.isArrayBuffer(V)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V)}")`,
          types: ["ArrayBuffer"]
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a resizable ArrayBuffer.`
        });
      }
      return V;
    };
    webidl.converters.SharedArrayBuffer = function(V, prefix, argument, flags) {
      if (webidl.util.Type(V) !== OBJECT || !types.isSharedArrayBuffer(V)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V)}")`,
          types: ["SharedArrayBuffer"]
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a resizable SharedArrayBuffer.`
        });
      }
      return V;
    };
    webidl.converters.TypedArray = function(V, T, prefix, argument, flags) {
      if (webidl.util.Type(V) !== OBJECT || !types.isTypedArray(V) || V.constructor.name !== T.name) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V)}")`,
          types: [T.name]
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a shared array buffer.`
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a resizable array buffer.`
        });
      }
      return V;
    };
    webidl.converters.DataView = function(V, prefix, argument, flags) {
      if (webidl.util.Type(V) !== OBJECT || !types.isDataView(V)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V)}")`,
          types: ["DataView"]
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a shared array buffer.`
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a resizable array buffer.`
        });
      }
      return V;
    };
    webidl.converters.ArrayBufferView = function(V, prefix, argument, flags) {
      if (webidl.util.Type(V) !== OBJECT || !types.isArrayBufferView(V)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V)}")`,
          types: ["ArrayBufferView"]
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a shared array buffer.`
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a resizable array buffer.`
        });
      }
      return V;
    };
    webidl.converters.BufferSource = function(V, prefix, argument, flags) {
      if (types.isArrayBuffer(V)) {
        return webidl.converters.ArrayBuffer(V, prefix, argument, flags);
      }
      if (types.isArrayBufferView(V)) {
        flags &= ~webidl.attributes.AllowShared;
        return webidl.converters.ArrayBufferView(V, prefix, argument, flags);
      }
      if (types.isSharedArrayBuffer(V)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a SharedArrayBuffer.`
        });
      }
      throw webidl.errors.conversionFailed({
        prefix,
        argument: `${argument} ("${webidl.util.Stringify(V)}")`,
        types: ["ArrayBuffer", "ArrayBufferView"]
      });
    };
    webidl.converters.AllowSharedBufferSource = function(V, prefix, argument, flags) {
      if (types.isArrayBuffer(V)) {
        return webidl.converters.ArrayBuffer(V, prefix, argument, flags);
      }
      if (types.isSharedArrayBuffer(V)) {
        return webidl.converters.SharedArrayBuffer(V, prefix, argument, flags);
      }
      if (types.isArrayBufferView(V)) {
        flags |= webidl.attributes.AllowShared;
        return webidl.converters.ArrayBufferView(V, prefix, argument, flags);
      }
      throw webidl.errors.conversionFailed({
        prefix,
        argument: `${argument} ("${webidl.util.Stringify(V)}")`,
        types: ["ArrayBuffer", "SharedArrayBuffer", "ArrayBufferView"]
      });
    };
    webidl.converters["sequence<ByteString>"] = webidl.sequenceConverter(
      webidl.converters.ByteString
    );
    webidl.converters["sequence<sequence<ByteString>>"] = webidl.sequenceConverter(
      webidl.converters["sequence<ByteString>"]
    );
    webidl.converters["record<ByteString, ByteString>"] = webidl.recordConverter(
      webidl.converters.ByteString,
      webidl.converters.ByteString
    );
    webidl.converters.Blob = webidl.interfaceConverter(webidl.is.Blob, "Blob");
    webidl.converters.AbortSignal = webidl.interfaceConverter(
      webidl.is.AbortSignal,
      "AbortSignal"
    );
    webidl.converters.EventHandlerNonNull = function(V) {
      if (webidl.util.Type(V) !== OBJECT) {
        return null;
      }
      if (typeof V === "function") {
        return V;
      }
      return () => {
      };
    };
    webidl.attributes = {
      Clamp: 1 << 0,
      EnforceRange: 1 << 1,
      AllowShared: 1 << 2,
      AllowResizable: 1 << 3,
      LegacyNullToEmptyString: 1 << 4
    };
    module.exports = {
      webidl
    };
  }
});

// ../../node_modules/undici/lib/web/fetch/util.js
var require_util2 = __commonJS({
  "../../node_modules/undici/lib/web/fetch/util.js"(exports, module) {
    "use strict";
    var { Transform } = __require("stream");
    var zlib = __require("zlib");
    var { redirectStatusSet, referrerPolicyTokens, badPortsSet } = require_constants3();
    var { getGlobalOrigin } = require_global();
    var { collectAnHTTPQuotedString, parseMIMEType } = require_data_url();
    var { performance: performance2 } = __require("perf_hooks");
    var { ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = require_util();
    var assert = __require("assert");
    var { isUint8Array } = __require("util/types");
    var { webidl } = require_webidl();
    var { isomorphicEncode, collectASequenceOfCodePoints, removeChars } = require_infra();
    function responseURL(response) {
      const urlList = response.urlList;
      const length = urlList.length;
      return length === 0 ? null : urlList[length - 1].toString();
    }
    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;
    }
    function isValidEncodedURL(url) {
      for (let i = 0; i < url.length; ++i) {
        const code = url.charCodeAt(i);
        if (code > 126 || // Non-US-ASCII + DEL
        code < 32) {
          return false;
        }
      }
      return true;
    }
    function normalizeBinaryStringToUtf8(value) {
      return Buffer.from(value, "binary").toString("utf8");
    }
    function requestCurrentURL(request) {
      return request.urlList[request.urlList.length - 1];
    }
    function requestBadPort(request) {
      const url = requestCurrentURL(request);
      if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
        return "blocked";
      }
      return "allowed";
    }
    function isErrorLike(object) {
      return object instanceof Error || (object?.constructor?.name === "Error" || object?.constructor?.name === "DOMException");
    }
    function isValidReasonPhrase(statusText) {
      for (let i = 0; i < statusText.length; ++i) {
        const c = statusText.charCodeAt(i);
        if (!(c === 9 || // HTAB
        c >= 32 && c <= 126 || // SP / VCHAR
        c >= 128 && c <= 255)) {
          return false;
        }
      }
      return true;
    }
    var isValidHeaderName = isValidHTTPToken;
    function isValidHeaderValue(potentialValue) {
      return (potentialValue[0] === "	" || potentialValue[0] === " " || potentialValue[potentialValue.length - 1] === "	" || potentialValue[potentialValue.length - 1] === " " || potentialValue.includes("\n") || potentialValue.includes("\r") || potentialValue.includes("\0")) === false;
    }
    function parseReferrerPolicy(actualResponse) {
      const policyHeader = (actualResponse.headersList.get("referrer-policy", true) ?? "").split(",");
      let policy = "";
      if (policyHeader.length) {
        for (let i = policyHeader.length; i !== 0; i--) {
          const token = policyHeader[i - 1].trim();
          if (referrerPolicyTokens.has(token)) {
            policy = token;
            break;
          }
        }
      }
      return policy;
    }
    function setRequestReferrerPolicyOnRedirect(request, actualResponse) {
      const policy = parseReferrerPolicy(actualResponse);
      if (policy !== "") {
        request.referrerPolicy = policy;
      }
    }
    function crossOriginResourcePolicyCheck() {
      return "allowed";
    }
    function corsCheck() {
      return "success";
    }
    function TAOCheck() {
      return "success";
    }
    function appendFetchMetadata(httpRequest) {
      let header = null;
      header = httpRequest.mode;
      httpRequest.headersList.set("sec-fetch-mode", header, true);
    }
    function appendRequestOriginHeader(request) {
      let serializedOrigin = request.origin;
      if (serializedOrigin === "client" || serializedOrigin === void 0) {
        return;
      }
      if (request.responseTainting === "cors" || request.mode === "websocket") {
        request.headersList.append("origin", serializedOrigin, true);
      } else if (request.method !== "GET" && request.method !== "HEAD") {
        switch (request.referrerPolicy) {
          case "no-referrer":
            serializedOrigin = null;
            break;
          case "no-referrer-when-downgrade":
          case "strict-origin":
          case "strict-origin-when-cross-origin":
            if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
              serializedOrigin = null;
            }
            break;
          case "same-origin":
            if (!sameOrigin(request, requestCurrentURL(request))) {
              serializedOrigin = null;
            }
            break;
          default:
        }
        request.headersList.append("origin", serializedOrigin, true);
      }
    }
    function coarsenTime(timestamp, crossOriginIsolatedCapability) {
      return timestamp;
    }
    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
      };
    }
    function coarsenedSharedCurrentTime(crossOriginIsolatedCapability) {
      return coarsenTime(performance2.now(), crossOriginIsolatedCapability);
    }
    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
      };
    }
    function makePolicyContainer() {
      return {
        referrerPolicy: "strict-origin-when-cross-origin"
      };
    }
    function clonePolicyContainer(policyContainer) {
      return {
        referrerPolicy: policyContainer.referrerPolicy
      };
    }
    function determineRequestsReferrer(request) {
      const policy = request.referrerPolicy;
      assert(policy);
      let referrerSource = null;
      if (request.referrer === "client") {
        const globalOrigin = getGlobalOrigin();
        if (!globalOrigin || globalOrigin.origin === "null") {
          return "no-referrer";
        }
        referrerSource = new URL(globalOrigin);
      } else if (webidl.is.URL(request.referrer)) {
        referrerSource = request.referrer;
      }
      let referrerURL = stripURLForReferrer(referrerSource);
      const referrerOrigin = stripURLForReferrer(referrerSource, true);
      if (referrerURL.toString().length > 4096) {
        referrerURL = referrerOrigin;
      }
      switch (policy) {
        case "no-referrer":
          return "no-referrer";
        case "origin":
          if (referrerOrigin != null) {
            return referrerOrigin;
          }
          return stripURLForReferrer(referrerSource, true);
        case "unsafe-url":
          return referrerURL;
        case "strict-origin": {
          const currentURL = requestCurrentURL(request);
          if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
            return "no-referrer";
          }
          return referrerOrigin;
        }
        case "strict-origin-when-cross-origin": {
          const currentURL = requestCurrentURL(request);
          if (sameOrigin(referrerURL, currentURL)) {
            return referrerURL;
          }
          if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
            return "no-referrer";
          }
          return referrerOrigin;
        }
        case "same-origin":
          if (sameOrigin(request, referrerURL)) {
            return referrerURL;
          }
          return "no-referrer";
        case "origin-when-cross-origin":
          if (sameOrigin(request, referrerURL)) {
            return referrerURL;
          }
          return referrerOrigin;
        case "no-referrer-when-downgrade": {
          const currentURL = requestCurrentURL(request);
          if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
            return "no-referrer";
          }
          return referrerURL;
        }
      }
    }
    function stripURLForReferrer(url, originOnly = false) {
      assert(webidl.is.URL(url));
      url = new URL(url);
      if (urlIsLocal(url)) {
        return "no-referrer";
      }
      url.username = "";
      url.password = "";
      url.hash = "";
      if (originOnly === true) {
        url.pathname = "";
        url.search = "";
      }
      return url;
    }
    var isPotentialleTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/);
    var isPotentiallyTrustworthyIPv6 = RegExp.prototype.test.bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/);
    function isOriginIPPotentiallyTrustworthy(origin) {
      if (origin.includes(":")) {
        if (origin[0] === "[" && origin[origin.length - 1] === "]") {
          origin = origin.slice(1, -1);
        }
        return isPotentiallyTrustworthyIPv6(origin);
      }
      return isPotentialleTrustworthyIPv4(origin);
    }
    function isOriginPotentiallyTrustworthy(origin) {
      if (origin == null || origin === "null") {
        return false;
      }
      origin = new URL(origin);
      if (origin.protocol === "https:" || origin.protocol === "wss:") {
        return true;
      }
      if (isOriginIPPotentiallyTrustworthy(origin.hostname)) {
        return true;
      }
      if (origin.hostname === "localhost" || origin.hostname === "localhost.") {
        return true;
      }
      if (origin.hostname.endsWith(".localhost") || origin.hostname.endsWith(".localhost.")) {
        return true;
      }
      if (origin.protocol === "file:") {
        return true;
      }
      return false;
    }
    function isURLPotentiallyTrustworthy(url) {
      if (!webidl.is.URL(url)) {
        return false;
      }
      if (url.href === "about:blank" || url.href === "about:srcdoc") {
        return true;
      }
      if (url.protocol === "data:") return true;
      if (url.protocol === "blob:") return true;
      return isOriginPotentiallyTrustworthy(url.origin);
    }
    function tryUpgradeRequestToAPotentiallyTrustworthyURL(request) {
    }
    function sameOrigin(A, B) {
      if (A.origin === B.origin && A.origin === "null") {
        return true;
      }
      if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
        return true;
      }
      return false;
    }
    function isAborted(fetchParams) {
      return fetchParams.controller.state === "aborted";
    }
    function isCancelled(fetchParams) {
      return fetchParams.controller.state === "aborted" || fetchParams.controller.state === "terminated";
    }
    function normalizeMethod(method) {
      return normalizedMethodRecordsBase[method.toLowerCase()] ?? method;
    }
    var esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
    function createIterator(name, kInternalIterator, keyIndex = 0, valueIndex = 1) {
      class FastIterableIterator {
        /** @type {any} */
        #target;
        /** @type {'key' | 'value' | 'key+value'} */
        #kind;
        /** @type {number} */
        #index;
        /**
         * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object
         * @param {unknown} target
         * @param {'key' | 'value' | 'key+value'} kind
         */
        constructor(target, kind) {
          this.#target = target;
          this.#kind = kind;
          this.#index = 0;
        }
        next() {
          if (typeof this !== "object" || this === null || !(#target in this)) {
            throw new TypeError(
              `'next' called on an object that does not implement interface ${name} Iterator.`
            );
          }
          const index = this.#index;
          const values = kInternalIterator(this.#target);
          const len = values.length;
          if (index >= len) {
            return {
              value: void 0,
              done: true
            };
          }
          const { [keyIndex]: key, [valueIndex]: value } = values[index];
          this.#index = index + 1;
          let result;
          switch (this.#kind) {
            case "key":
              result = key;
              break;
            case "value":
              result = value;
              break;
            case "key+value":
              result = [key, value];
              break;
          }
          return {
            value: result,
            done: false
          };
        }
      }
      delete FastIterableIterator.prototype.constructor;
      Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype);
      Object.defineProperties(FastIterableIterator.prototype, {
        [Symbol.toStringTag]: {
          writable: false,
          enumerable: false,
          configurable: true,
          value: `${name} Iterator`
        },
        next: { writable: true, enumerable: true, configurable: true }
      });
      return function(target, kind) {
        return new FastIterableIterator(target, kind);
      };
    }
    function iteratorMixin(name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) {
      const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex);
      const properties = {
        keys: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: function keys() {
            webidl.brandCheck(this, object);
            return makeIterator(this, "key");
          }
        },
        values: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: function values() {
            webidl.brandCheck(this, object);
            return makeIterator(this, "value");
          }
        },
        entries: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: function entries() {
            webidl.brandCheck(this, object);
            return makeIterator(this, "key+value");
          }
        },
        forEach: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: function forEach(callbackfn, thisArg = globalThis) {
            webidl.brandCheck(this, object);
            webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`);
            if (typeof callbackfn !== "function") {
              throw new TypeError(
                `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.`
              );
            }
            for (const { 0: key, 1: value } of makeIterator(this, "key+value")) {
              callbackfn.call(thisArg, value, key, this);
            }
          }
        }
      };
      return Object.defineProperties(object.prototype, {
        ...properties,
        [Symbol.iterator]: {
          writable: true,
          enumerable: false,
          configurable: true,
          value: properties.entries.value
        }
      });
    }
    function fullyReadBody(body, processBody, processBodyError) {
      const successSteps = processBody;
      const errorSteps = processBodyError;
      try {
        const reader = body.stream.getReader();
        readAllBytes(reader, successSteps, errorSteps);
      } catch (e) {
        errorSteps(e);
      }
    }
    function readableStreamClose(controller) {
      try {
        controller.close();
        controller.byobRequest?.respond(0);
      } catch (err) {
        if (!err.message.includes("Controller is already closed") && !err.message.includes("ReadableStream is already closed")) {
          throw err;
        }
      }
    }
    async function readAllBytes(reader, successSteps, failureSteps) {
      try {
        const bytes = [];
        let byteLength = 0;
        do {
          const { done, value: chunk } = await reader.read();
          if (done) {
            successSteps(Buffer.concat(bytes, byteLength));
            return;
          }
          if (!isUint8Array(chunk)) {
            failureSteps(new TypeError("Received non-Uint8Array chunk"));
            return;
          }
          bytes.push(chunk);
          byteLength += chunk.length;
        } while (true);
      } catch (e) {
        failureSteps(e);
      }
    }
    function urlIsLocal(url) {
      assert("protocol" in url);
      const protocol = url.protocol;
      return protocol === "about:" || protocol === "blob:" || protocol === "data:";
    }
    function urlHasHttpsScheme(url) {
      return typeof url === "string" && url[5] === ":" && url[0] === "h" && url[1] === "t" && url[2] === "t" && url[3] === "p" && url[4] === "s" || url.protocol === "https:";
    }
    function urlIsHttpHttpsScheme(url) {
      assert("protocol" in url);
      const protocol = url.protocol;
      return protocol === "http:" || protocol === "https:";
    }
    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 code = char.charCodeAt(0);
          return code >= 48 && code <= 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 code = char.charCodeAt(0);
          return code >= 48 && code <= 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 };
    }
    function buildContentRange(rangeStart, rangeEnd, fullLength) {
      let contentRange = "bytes ";
      contentRange += isomorphicEncode(`${rangeStart}`);
      contentRange += "-";
      contentRange += isomorphicEncode(`${rangeEnd}`);
      contentRange += "/";
      contentRange += isomorphicEncode(`${fullLength}`);
      return contentRange;
    }
    var InflateStream = class extends Transform {
      #zlibOptions;
      /** @param {zlib.ZlibOptions} [zlibOptions] */
      constructor(zlibOptions) {
        super();
        this.#zlibOptions = zlibOptions;
      }
      _transform(chunk, encoding, callback) {
        if (!this._inflateStream) {
          if (chunk.length === 0) {
            callback();
            return;
          }
          this._inflateStream = (chunk[0] & 15) === 8 ? zlib.createInflate(this.#zlibOptions) : zlib.createInflateRaw(this.#zlibOptions);
          this._inflateStream.on("data", this.push.bind(this));
          this._inflateStream.on("end", () => this.push(null));
          this._inflateStream.on("error", (err) => this.destroy(err));
        }
        this._inflateStream.write(chunk, encoding, callback);
      }
      _final(callback) {
        if (this._inflateStream) {
          this._inflateStream.end();
          this._inflateStream = null;
        }
        callback();
      }
    };
    function createInflate(zlibOptions) {
      return new InflateStream(zlibOptions);
    }
    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;
    }
    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 {
            assert(input.charCodeAt(position.position) === 44);
            position.position++;
          }
        }
        temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 9 || char === 32);
        values.push(temporaryValue);
        temporaryValue = "";
      }
      return values;
    }
    function getDecodeSplit(name, list) {
      const value = list.get(name, true);
      if (value === null) {
        return null;
      }
      return gettingDecodingSplitting(value);
    }
    function hasAuthenticationEntry(request) {
      return false;
    }
    function includesCredentials(url) {
      return !!(url.username || url.password);
    }
    function isTraversableNavigable(navigable) {
      return navigable != null && navigable !== "client" && navigable !== "no-traversable";
    }
    var EnvironmentSettingsObjectBase = class {
      get baseUrl() {
        return getGlobalOrigin();
      }
      get origin() {
        return this.baseUrl?.origin;
      }
      policyContainer = makePolicyContainer();
    };
    var EnvironmentSettingsObject = class {
      settingsObject = new EnvironmentSettingsObjectBase();
    };
    var environmentSettingsObject = new EnvironmentSettingsObject();
    module.exports = {
      isAborted,
      isCancelled,
      isValidEncodedURL,
      ReadableStreamFrom,
      tryUpgradeRequestToAPotentiallyTrustworthyURL,
      clampAndCoarsenConnectionTimingInfo,
      coarsenedSharedCurrentTime,
      determineRequestsReferrer,
      makePolicyContainer,
      clonePolicyContainer,
      appendFetchMetadata,
      appendRequestOriginHeader,
      TAOCheck,
      corsCheck,
      crossOriginResourcePolicyCheck,
      createOpaqueTimingInfo,
      setRequestReferrerPolicyOnRedirect,
      isValidHTTPToken,
      requestBadPort,
      requestCurrentURL,
      responseURL,
      responseLocationURL,
      isURLPotentiallyTrustworthy,
      isValidReasonPhrase,
      sameOrigin,
      normalizeMethod,
      iteratorMixin,
      createIterator,
      isValidHeaderName,
      isValidHeaderValue,
      isErrorLike,
      fullyReadBody,
      readableStreamClose,
      urlIsLocal,
      urlHasHttpsScheme,
      urlIsHttpHttpsScheme,
      readAllBytes,
      simpleRangeHeaderValue,
      buildContentRange,
      createInflate,
      extractMimeType,
      getDecodeSplit,
      environmentSettingsObject,
      isOriginIPPotentiallyTrustworthy,
      hasAuthenticationEntry,
      includesCredentials,
      isTraversableNavigable
    };
  }
});

// ../../node_modules/undici/lib/util/runtime-features.js
var require_runtime_features = __commonJS({
  "../../node_modules/undici/lib/util/runtime-features.js"(exports, module) {
    "use strict";
    var lazyLoaders = {
      __proto__: null,
      "node:crypto": () => __require("crypto"),
      "node:sqlite": () => __require("sqlite")
    };
    function detectRuntimeFeatureByNodeModule(moduleName) {
      try {
        lazyLoaders[moduleName]();
        return true;
      } catch (err) {
        if (err.code !== "ERR_UNKNOWN_BUILTIN_MODULE" && err.code !== "ERR_NO_CRYPTO") {
          throw err;
        }
        return false;
      }
    }
    var runtimeFeaturesAsNodeModule = (
      /** @type {const} */
      ["crypto", "sqlite"]
    );
    function detectRuntimeFeature(feature) {
      if (runtimeFeaturesAsNodeModule.includes(
        /** @type {RuntimeFeatureByNodeModule} */
        feature
      )) {
        return detectRuntimeFeatureByNodeModule(`node:${feature}`);
      }
      throw new TypeError(`unknown feature: ${feature}`);
    }
    var RuntimeFeatures = class {
      /** @type {Map<Feature, boolean>} */
      #map = /* @__PURE__ */ new Map();
      /**
       * Clears all cached feature detections.
       */
      clear() {
        this.#map.clear();
      }
      /**
       * @param {Feature} feature
       * @returns {boolean}
       */
      has(feature) {
        return this.#map.get(feature) ?? this.#detectRuntimeFeature(feature);
      }
      /**
       * @param {Feature} feature
       * @param {boolean} value
       */
      set(feature, value) {
        if (runtimeFeaturesAsNodeModule.includes(feature) === false) {
          throw new TypeError(`unknown feature: ${feature}`);
        }
        this.#map.set(feature, value);
      }
      /**
       * @param {Feature} feature
       * @returns {boolean}
       */
      #detectRuntimeFeature(feature) {
        const result = detectRuntimeFeature(feature);
        this.#map.set(feature, result);
        return result;
      }
    };
    var instance = new RuntimeFeatures();
    module.exports.runtimeFeatures = instance;
    module.exports.default = instance;
  }
});

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

// ../../node_modules/undici/lib/web/fetch/formdata-parser.js
var require_formdata_parser = __commonJS({
  "../../node_modules/undici/lib/web/fetch/formdata-parser.js"(exports, module) {
    "use strict";
    var { bufferToLowerCasedHeaderName } = require_util();
    var { HTTP_TOKEN_CODEPOINTS } = require_data_url();
    var { makeEntry } = require_formdata();
    var { webidl } = require_webidl();
    var assert = __require("assert");
    var { isomorphicDecode } = require_infra();
    var dd = Buffer.from("--");
    var decoder = new TextDecoder();
    var decoderIgnoreBOM = new TextDecoder("utf-8", { ignoreBOM: true });
    function isAsciiString(chars) {
      for (let i = 0; i < chars.length; ++i) {
        if ((chars.charCodeAt(i) & ~127) !== 0) {
          return false;
        }
      }
      return true;
    }
    function validateBoundary(boundary) {
      const length = boundary.length;
      if (length < 27 || length > 70) {
        return false;
      }
      for (let i = 0; i < length; ++i) {
        const cp = boundary.charCodeAt(i);
        if (!(cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 39 || cp === 45 || cp === 95)) {
          return false;
        }
      }
      return true;
    }
    function multipartFormDataParser(input, mimeType) {
      assert(mimeType !== "failure" && mimeType.essence === "multipart/form-data");
      const boundaryString = mimeType.parameters.get("boundary");
      if (boundaryString === void 0) {
        throw parsingError("missing boundary in content-type header");
      }
      const boundary = Buffer.from(`--${boundaryString}`, "utf8");
      const entryList = [];
      const position = { position: 0 };
      const firstBoundaryIndex = input.indexOf(boundary);
      if (firstBoundaryIndex === -1) {
        throw parsingError("no boundary found in multipart body");
      }
      position.position = firstBoundaryIndex;
      while (true) {
        if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) {
          position.position += boundary.length;
        } else {
          throw parsingError("expected a value starting with -- and the boundary");
        }
        if (bufferStartsWith(input, dd, position)) {
          return entryList;
        }
        if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
          throw parsingError("expected CRLF");
        }
        position.position += 2;
        const result = parseMultipartFormDataHeaders(input, position);
        let { name, filename, contentType, encoding } = result;
        position.position += 2;
        let body;
        {
          const boundaryIndex = input.indexOf(boundary.subarray(2), position.position);
          if (boundaryIndex === -1) {
            throw parsingError("expected boundary after body");
          }
          body = input.subarray(position.position, boundaryIndex - 4);
          position.position += body.length;
          if (encoding === "base64") {
            body = Buffer.from(body.toString(), "base64");
          }
        }
        if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
          throw parsingError("expected CRLF");
        } else {
          position.position += 2;
        }
        let value;
        if (filename !== null) {
          contentType ??= "text/plain";
          if (!isAsciiString(contentType)) {
            contentType = "";
          }
          value = new File([body], filename, { type: contentType });
        } else {
          value = decoderIgnoreBOM.decode(Buffer.from(body));
        }
        assert(webidl.is.USVString(name));
        assert(typeof value === "string" && webidl.is.USVString(value) || webidl.is.File(value));
        entryList.push(makeEntry(name, value, filename));
      }
    }
    function parseContentDispositionAttribute(input, position) {
      if (input[position.position] === 59) {
        position.position++;
      }
      collectASequenceOfBytes(
        (char) => char === 32 || char === 9,
        input,
        position
      );
      const attributeName = collectASequenceOfBytes(
        (char) => isToken(char) && char !== 61 && char !== 42,
        // not = or *
        input,
        position
      );
      if (attributeName.length === 0) {
        return null;
      }
      const attrNameStr = attributeName.toString("ascii").toLowerCase();
      const isExtended = input[position.position] === 42;
      if (isExtended) {
        position.position++;
      }
      if (input[position.position] !== 61) {
        return null;
      }
      position.position++;
      collectASequenceOfBytes(
        (char) => char === 32 || char === 9,
        input,
        position
      );
      let value;
      if (isExtended) {
        const headerValue = collectASequenceOfBytes(
          (char) => char !== 32 && char !== 13 && char !== 10 && char !== 59,
          // not space, CRLF, or ;
          input,
          position
        );
        if (headerValue[0] !== 117 && headerValue[0] !== 85 || // u or U
        headerValue[1] !== 116 && headerValue[1] !== 84 || // t or T
        headerValue[2] !== 102 && headerValue[2] !== 70 || // f or F
        headerValue[3] !== 45 || // -
        headerValue[4] !== 56) {
          throw parsingError("unknown encoding, expected utf-8''");
        }
        value = decodeURIComponent(decoder.decode(headerValue.subarray(7)));
      } else if (input[position.position] === 34) {
        position.position++;
        const quotedValue = collectASequenceOfBytes(
          (char) => char !== 10 && char !== 13 && char !== 34,
          // not LF, CR, or "
          input,
          position
        );
        if (input[position.position] !== 34) {
          throw parsingError("Closing quote not found");
        }
        position.position++;
        value = decoder.decode(quotedValue).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"');
      } else {
        const tokenValue = collectASequenceOfBytes(
          (char) => isToken(char) && char !== 59,
          // not ;
          input,
          position
        );
        value = decoder.decode(tokenValue);
      }
      return { name: attrNameStr, value, extended: isExtended };
    }
    function parseMultipartFormDataHeaders(input, position) {
      let name = null;
      let filename = null;
      let contentType = null;
      let encoding = null;
      while (true) {
        if (input[position.position] === 13 && input[position.position + 1] === 10) {
          if (name === null) {
            throw parsingError("header name is null");
          }
          return { name, filename, contentType, encoding };
        }
        let headerName = collectASequenceOfBytes(
          (char) => char !== 10 && char !== 13 && char !== 58,
          input,
          position
        );
        headerName = removeChars(headerName, true, true, (char) => char === 9 || char === 32);
        if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) {
          throw parsingError("header name does not match the field-name token production");
        }
        if (input[position.position] !== 58) {
          throw parsingError("expected :");
        }
        position.position++;
        collectASequenceOfBytes(
          (char) => char === 32 || char === 9,
          input,
          position
        );
        switch (bufferToLowerCasedHeaderName(headerName)) {
          case "content-disposition": {
            name = filename = null;
            let filenameIsExtended = false;
            const dispositionType = collectASequenceOfBytes(
              (char) => isToken(char),
              input,
              position
            );
            if (dispositionType.toString("ascii").toLowerCase() !== "form-data") {
              throw parsingError("expected form-data for content-disposition header");
            }
            while (position.position < input.length && (input[position.position] !== 13 || input[position.position + 1] !== 10)) {
              const attribute = parseContentDispositionAttribute(input, position);
              if (!attribute) {
                break;
              }
              if (attribute.name === "name") {
                name = attribute.value;
              } else if (attribute.name === "filename") {
                if (attribute.extended) {
                  filename = attribute.value;
                  filenameIsExtended = true;
                } else if (!filenameIsExtended) {
                  filename = attribute.value;
                }
              }
            }
            if (name === null) {
              throw parsingError("name attribute is required in content-disposition header");
            }
            break;
          }
          case "content-type": {
            let headerValue = collectASequenceOfBytes(
              (char) => char !== 10 && char !== 13,
              input,
              position
            );
            headerValue = removeChars(headerValue, false, true, (char) => char === 9 || char === 32);
            contentType = isomorphicDecode(headerValue);
            break;
          }
          case "content-transfer-encoding": {
            let headerValue = collectASequenceOfBytes(
              (char) => char !== 10 && char !== 13,
              input,
              position
            );
            headerValue = removeChars(headerValue, false, true, (char) => char === 9 || char === 32);
            encoding = isomorphicDecode(headerValue);
            break;
          }
          default: {
            collectASequenceOfBytes(
              (char) => char !== 10 && char !== 13,
              input,
              position
            );
          }
        }
        if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
          throw parsingError("expected CRLF");
        } else {
          position.position += 2;
        }
      }
    }
    function collectASequenceOfBytes(condition, input, position) {
      let start = position.position;
      while (start < input.length && condition(input[start])) {
        ++start;
      }
      return input.subarray(position.position, position.position = start);
    }
    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);
    }
    function bufferStartsWith(buffer, start, position) {
      if (buffer.length < start.length) {
        return false;
      }
      for (let i = 0; i < start.length; i++) {
        if (start[i] !== buffer[position.position + i]) {
          return false;
        }
      }
      return true;
    }
    function parsingError(cause) {
      return new TypeError("Failed to parse body as FormData.", { cause: new TypeError(cause) });
    }
    function isCTL(char) {
      return char <= 31 || char === 127;
    }
    function isTSpecial(char) {
      return char === 40 || // (
      char === 41 || // )
      char === 60 || // <
      char === 62 || // >
      char === 64 || // @
      char === 44 || // ,
      char === 59 || // ;
      char === 58 || // :
      char === 92 || // \
      char === 34 || // "
      char === 47 || // /
      char === 91 || // [
      char === 93 || // ]
      char === 63 || // ?
      char === 61;
    }
    function isToken(char) {
      return char <= 127 && // ascii
      char !== 32 && // space
      char !== 9 && !isCTL(char) && !isTSpecial(char);
    }
    module.exports = {
      multipartFormDataParser,
      validateBoundary
    };
  }
});

// ../../node_modules/undici/lib/web/fetch/body.js
var require_body = __commonJS({
  "../../node_modules/undici/lib/web/fetch/body.js"(exports, module) {
    "use strict";
    var util = require_util();
    var {
      ReadableStreamFrom,
      readableStreamClose,
      fullyReadBody,
      extractMimeType
    } = require_util2();
    var { FormData, setFormDataState, getFormDataBoundary } = require_formdata();
    var { webidl } = require_webidl();
    var assert = __require("assert");
    var { isErrored, isDisturbed } = __require("stream");
    var { isUint8Array } = __require("util/types");
    var { serializeAMimeType } = require_data_url();
    var { multipartFormDataParser } = require_formdata_parser();
    var { parseJSONFromBytes } = require_infra();
    var { utf8DecodeBytes } = require_encoding();
    var textEncoder = new TextEncoder();
    function noop() {
    }
    var streamRegistry = new FinalizationRegistry((weakRef) => {
      const stream = weakRef.deref();
      if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) {
        stream.cancel("Response object has been garbage collected").catch(noop);
      }
    });
    function extractBody(object, keepalive = false) {
      let stream = null;
      let controller = null;
      if (webidl.is.ReadableStream(object)) {
        stream = object;
      } else if (webidl.is.Blob(object)) {
        stream = object.stream();
      } else {
        stream = new ReadableStream({
          pull() {
          },
          start(c) {
            controller = c;
          },
          cancel() {
          },
          type: "bytes"
        });
      }
      assert(webidl.is.ReadableStream(stream));
      let action = null;
      let source = null;
      let length = null;
      let type = null;
      if (typeof object === "string") {
        source = object;
        type = "text/plain;charset=UTF-8";
      } else if (webidl.is.URLSearchParams(object)) {
        source = object.toString();
        type = "application/x-www-form-urlencoded;charset=UTF-8";
      } else if (webidl.is.BufferSource(object)) {
        source = webidl.util.getCopyOfBytesHeldByBufferSource(object);
      } else if (webidl.is.FormData(object)) {
        const boundary = getFormDataBoundary(object);
        const prefix = `--${boundary}\r
Content-Disposition: form-data`;
        const formdataEscape = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
        const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, "\r\n");
        const blobParts = [];
        const rn = new Uint8Array([13, 10]);
        length = 0;
        let hasUnknownSizeValue = false;
        for (const [name, value] of object) {
          if (typeof value === "string") {
            const chunk2 = textEncoder.encode(prefix + `; name="${formdataEscape(normalizeLinefeeds(name))}"\r
\r
${normalizeLinefeeds(value)}\r
`);
            blobParts.push(chunk2);
            length += chunk2.byteLength;
          } else {
            const chunk2 = textEncoder.encode(`${prefix}; name="${formdataEscape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${formdataEscape(value.name)}"` : "") + `\r
Content-Type: ${value.type || "application/octet-stream"}\r
\r
`);
            blobParts.push(chunk2, value, rn);
            if (typeof value.size === "number") {
              length += chunk2.byteLength + value.size + rn.byteLength;
            } else {
              hasUnknownSizeValue = true;
            }
          }
        }
        const chunk = textEncoder.encode(`--${boundary}--\r
`);
        blobParts.push(chunk);
        length += chunk.byteLength;
        if (hasUnknownSizeValue) {
          length = null;
        }
        source = object;
        action = async function* () {
          for (const part of blobParts) {
            if (part.stream) {
              yield* part.stream();
            } else {
              yield part;
            }
          }
        };
        type = `multipart/form-data; boundary=${boundary}`;
      } else if (webidl.is.Blob(object)) {
        source = object;
        length = object.size;
        if (object.type) {
          type = object.type;
        }
      } else if (typeof object[Symbol.asyncIterator] === "function") {
        if (keepalive) {
          throw new TypeError("keepalive");
        }
        if (util.isDisturbed(object) || object.locked) {
          throw new TypeError(
            "Response body object should not be disturbed or locked"
          );
        }
        stream = webidl.is.ReadableStream(object) ? object : ReadableStreamFrom(object);
      }
      if (typeof source === "string" || isUint8Array(source)) {
        action = () => {
          length = typeof source === "string" ? Buffer.byteLength(source) : source.length;
          return source;
        };
      }
      if (action != null) {
        ;
        (async () => {
          const result = action();
          const iterator = result?.[Symbol.asyncIterator]?.();
          if (iterator) {
            for await (const bytes of iterator) {
              if (isErrored(stream)) break;
              if (bytes.length) {
                controller.enqueue(new Uint8Array(bytes));
              }
            }
          } else if (result?.length && !isErrored(stream)) {
            controller.enqueue(typeof result === "string" ? textEncoder.encode(result) : new Uint8Array(result));
          }
          queueMicrotask(() => readableStreamClose(controller));
        })();
      }
      const body = { stream, source, length };
      return [body, type];
    }
    function safelyExtractBody(object, keepalive = false) {
      if (webidl.is.ReadableStream(object)) {
        assert(!util.isDisturbed(object), "The body has already been consumed.");
        assert(!object.locked, "The stream is locked.");
      }
      return extractBody(object, keepalive);
    }
    function cloneBody(body) {
      const { 0: out1, 1: out2 } = body.stream.tee();
      body.stream = out1;
      return {
        stream: out2,
        length: body.length,
        source: body.source
      };
    }
    function bodyMixinMethods(instance, getInternalState) {
      const methods = {
        blob() {
          return consumeBody(this, (bytes) => {
            let mimeType = bodyMimeType(getInternalState(this));
            if (mimeType === null) {
              mimeType = "";
            } else if (mimeType) {
              mimeType = serializeAMimeType(mimeType);
            }
            return new Blob([bytes], { type: mimeType });
          }, instance, getInternalState);
        },
        arrayBuffer() {
          return consumeBody(this, (bytes) => {
            return new Uint8Array(bytes).buffer;
          }, instance, getInternalState);
        },
        text() {
          return consumeBody(this, utf8DecodeBytes, instance, getInternalState);
        },
        json() {
          return consumeBody(this, parseJSONFromBytes, instance, getInternalState);
        },
        formData() {
          return consumeBody(this, (value) => {
            const mimeType = bodyMimeType(getInternalState(this));
            if (mimeType !== null) {
              switch (mimeType.essence) {
                case "multipart/form-data": {
                  const parsed = multipartFormDataParser(value, mimeType);
                  const fd = new FormData();
                  setFormDataState(fd, parsed);
                  return fd;
                }
                case "application/x-www-form-urlencoded": {
                  const entries = new URLSearchParams(value.toString());
                  const fd = new FormData();
                  for (const [name, value2] of entries) {
                    fd.append(name, value2);
                  }
                  return fd;
                }
              }
            }
            throw new TypeError(
              'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
            );
          }, instance, getInternalState);
        },
        bytes() {
          return consumeBody(this, (bytes) => {
            return new Uint8Array(bytes);
          }, instance, getInternalState);
        },
        textStream() {
          const this_ = getInternalState(this);
          if (bodyUnusable(this_)) {
            throw new TypeError("Body is unusable: Body has already been read");
          }
          if (this_.body == null) {
            let controller;
            const emptyStream = new ReadableStream({
              start: (c) => {
                controller = c;
              },
              pull: () => Promise.resolve(),
              cancel: () => Promise.resolve()
            }, {
              size: () => 1
            });
            controller.close();
            return emptyStream;
          }
          const stream = this_.body.stream;
          const decoder = new TextDecoderStream("UTF-8");
          return stream.pipeThrough(decoder);
        }
      };
      return methods;
    }
    function mixinBody(prototype, getInternalState) {
      Object.assign(prototype.prototype, bodyMixinMethods(prototype, getInternalState));
    }
    function consumeBody(object, convertBytesToJSValue, instance, getInternalState) {
      try {
        webidl.brandCheck(object, instance);
      } catch (e) {
        return Promise.reject(e);
      }
      object = getInternalState(object);
      if (bodyUnusable(object)) {
        return Promise.reject(new TypeError("Body is unusable: Body has already been read"));
      }
      const promise = Promise.withResolvers();
      const errorSteps = promise.reject;
      const successSteps = (data) => {
        try {
          promise.resolve(convertBytesToJSValue(data));
        } catch (e) {
          errorSteps(e);
        }
      };
      if (object.body == null) {
        successSteps(Buffer.allocUnsafe(0));
        return promise.promise;
      }
      fullyReadBody(object.body, successSteps, errorSteps);
      return promise.promise;
    }
    function bodyUnusable(object) {
      const body = object.body;
      return body != null && (body.stream.locked || util.isDisturbed(body.stream));
    }
    function bodyMimeType(requestOrResponse) {
      const headers = requestOrResponse.headersList;
      const mimeType = extractMimeType(headers);
      if (mimeType === "failure") {
        return null;
      }
      return mimeType;
    }
    module.exports = {
      extractBody,
      safelyExtractBody,
      cloneBody,
      mixinBody,
      streamRegistry,
      bodyUnusable
    };
  }
});

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

// ../../node_modules/undici/lib/dispatcher/client-h2.js
var require_client_h2 = __commonJS({
  "../../node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) {
    "use strict";
    var assert = __require("assert");
    var { pipeline } = __require("stream");
    var util = require_util();
    var {
      RequestContentLengthMismatchError,
      RequestAbortedError,
      SocketError,
      InformationalError,
      InvalidArgumentError,
      HeadersTimeoutError,
      BodyTimeoutError
    } = require_errors();
    var {
      kUrl,
      kReset,
      kClient,
      kRunning,
      kPending,
      kQueue,
      kPendingIdx,
      kRunningIdx,
      kError,
      kSocket,
      kStrictContentLength,
      kOnError,
      kMaxConcurrentStreams,
      kPingInterval,
      kHTTP2Session,
      kHTTP2InitialWindowSize,
      kHTTP2ConnectionWindowSize,
      kHostAuthority,
      kResume,
      kSize,
      kHTTPContext,
      kClosed,
      kKeepAliveDefaultTimeout,
      kHeadersTimeout,
      kBodyTimeout,
      kEnableConnectProtocol,
      kRemoteSettings,
      kHTTP2Stream,
      kHTTP2SessionState
    } = require_symbols();
    var { channels } = require_diagnostics();
    var kOpenStreams = /* @__PURE__ */ Symbol("open streams");
    var kRequestStreamId = /* @__PURE__ */ Symbol("request stream id");
    var kRequestStream = /* @__PURE__ */ Symbol("request stream");
    var kRequestStreamCleanup = /* @__PURE__ */ Symbol("request stream cleanup");
    var kRequestStreamState = /* @__PURE__ */ Symbol("request stream state");
    var kReceivedGoAway = /* @__PURE__ */ Symbol("received goaway");
    var extractBody;
    var http2;
    try {
      http2 = __require("http2");
    } catch {
      http2 = { 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,
        HTTP2_HEADER_PROTOCOL,
        NGHTTP2_NO_ERROR,
        NGHTTP2_REFUSED_STREAM
      }
    } = http2;
    function getGoAwayError(session, errorCode) {
      return session[kError] || (errorCode === NGHTTP2_NO_ERROR ? new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`) : new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(session[kSocket])));
    }
    function resetHttp2Session(session, err) {
      const client = session[kClient];
      const socket = session[kSocket];
      if (client[kHTTP2Session] === session) {
        client[kSocket] = null;
        client[kHTTPContext] = null;
        client[kHTTP2Session] = null;
      }
      if (socket != null && socket[kError] == null) {
        socket[kError] = err;
      }
      if (!session.closed && !session.destroyed) {
        try {
          session.destroy(err);
        } catch {
        }
      }
      util.destroy(socket, err);
    }
    function getGoAwayPendingIdx(client, lastStreamID) {
      const maxAcceptedStreamID = Number.isInteger(lastStreamID) ? lastStreamID : Number.MAX_SAFE_INTEGER;
      for (let i = client[kRunningIdx]; i < client[kPendingIdx]; i++) {
        const request = client[kQueue][i];
        if (request == null) {
          continue;
        }
        if (typeof request[kRequestStreamId] !== "number" || request[kRequestStreamId] > maxAcceptedStreamID) {
          return i;
        }
      }
      return client[kPendingIdx];
    }
    function detachRequestFromStream(request) {
      request[kRequestStreamId] = null;
      request[kRequestStream] = null;
      request[kRequestStreamCleanup] = null;
    }
    function bindRequestToStream(request, stream, cleanup) {
      const previousCleanup = request[kRequestStreamCleanup];
      const previousStream = request[kRequestStream];
      detachRequestFromStream(request);
      previousCleanup?.(previousStream);
      request[kRequestStreamId] = stream.id;
      request[kRequestStream] = stream;
      request[kRequestStreamCleanup] = cleanup;
    }
    function clearRequestStream(request) {
      const cleanup = request[kRequestStreamCleanup];
      const stream = request[kRequestStream];
      detachRequestFromStream(request);
      cleanup?.(stream);
    }
    function requeueUnsentRequest(client, request) {
      client[kQueue].splice(client[kPendingIdx] + 1, 0, request);
    }
    function completeRequest(client, request, resetPendingIdx = false) {
      const index = client[kQueue].indexOf(request, client[kRunningIdx]);
      if (index === -1 || index >= client[kPendingIdx]) {
        return;
      }
      client[kQueue].splice(index, 1);
      client[kPendingIdx]--;
      if (resetPendingIdx && client[kPendingIdx] < client[kRunningIdx]) {
        client[kPendingIdx] = client[kRunningIdx];
      }
    }
    function canRetryRequestAfterGoAway(request) {
      const { body } = request;
      return body == null || util.isBuffer(body) || util.isBlobLike(body);
    }
    function closeRequestStream(request, code = NGHTTP2_REFUSED_STREAM) {
      const stream = request[kRequestStream];
      clearRequestStream(request);
      if (stream != null && !stream.destroyed && !stream.closed) {
        try {
          stream.close(code);
        } catch {
        }
      }
    }
    function connectH2(client, socket) {
      client[kSocket] = socket;
      const http2InitialWindowSize = client[kHTTP2InitialWindowSize];
      const http2ConnectionWindowSize = client[kHTTP2ConnectionWindowSize];
      const session = http2.connect(client[kUrl], {
        createConnection: () => socket,
        peerMaxConcurrentStreams: client[kMaxConcurrentStreams],
        settings: {
          // TODO(metcoder95): add support for PUSH
          enablePush: false,
          ...http2InitialWindowSize != null ? { initialWindowSize: http2InitialWindowSize } : null
        }
      });
      client[kSocket] = socket;
      session[kOpenStreams] = 0;
      session[kClient] = client;
      session[kSocket] = socket;
      session[kHTTP2SessionState] = {
        idleTimeout: null,
        ping: {
          interval: client[kPingInterval] === 0 ? null : setInterval(onHttp2SendPing, client[kPingInterval], session).unref()
        }
      };
      session[kReceivedGoAway] = false;
      session[kEnableConnectProtocol] = false;
      session[kRemoteSettings] = false;
      if (http2ConnectionWindowSize) {
        util.addListener(session, "connect", applyConnectionWindowSize.bind(session, http2ConnectionWindowSize));
      }
      util.addListener(session, "error", onHttp2SessionError);
      util.addListener(session, "frameError", onHttp2FrameError);
      util.addListener(session, "end", onHttp2SessionEnd);
      util.addListener(session, "goaway", onHttp2SessionGoAway);
      util.addListener(session, "close", onHttp2SessionClose);
      util.addListener(session, "remoteSettings", onHttp2RemoteSettings);
      session.unref();
      client[kHTTP2Session] = session;
      socket[kHTTP2Session] = session;
      util.addListener(socket, "error", onHttp2SocketError);
      util.addListener(socket, "end", onHttp2SocketEnd);
      util.addListener(socket, "close", onHttp2SocketClose);
      socket[kClosed] = false;
      socket.on("close", onSocketClose);
      return {
        version: "h2",
        defaultPipelining: Infinity,
        /**
         * @param {import('../core/request.js')} request
         * @returns {boolean}
        */
        write(request) {
          return writeH2(client, request);
        },
        /**
         * @returns {void}
         */
        resume() {
          resumeH2(client);
        },
        /**
         * @param {Error | null} err
         * @param {() => void} callback
         */
        destroy(err, callback) {
          if (socket[kClosed]) {
            queueMicrotask(callback);
          } else {
            socket.destroy(err).on("close", callback);
          }
        },
        /**
         * @type {boolean}
         */
        get destroyed() {
          return socket.destroyed;
        },
        /**
         * @param {import('../core/request.js')} request
         * @returns {boolean}
        */
        busy(request) {
          if (session[kRemoteSettings] === false && client[kRunning] > 0) {
            return true;
          }
          if (client[kRunning] >= client[kMaxConcurrentStreams]) {
            return true;
          }
          if (request != null) {
            if (client[kRunning] > 0) {
              if ((request.upgrade === "websocket" || request.method === "CONNECT") && session[kRemoteSettings] === false) return true;
              if (util.bodyLength(request.body) !== 0 && (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) return true;
            } else {
              return (request.upgrade === "websocket" || request.method === "CONNECT") && session[kRemoteSettings] === false;
            }
          }
          return false;
        }
      };
    }
    function resumeH2(client) {
      const socket = client[kSocket];
      const session = client[kHTTP2Session];
      if (socket?.destroyed === false) {
        if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
          socket.unref();
          session.unref();
        } else {
          socket.ref();
          session.ref();
        }
        if (client[kSize] === 0 && session[kOpenStreams] === 0) {
          setHttp2IdleTimeout(session);
        } else {
          clearHttp2IdleTimeout(session);
        }
      }
    }
    function clearHttp2IdleTimeout(session) {
      const state = session[kHTTP2SessionState];
      if (state?.idleTimeout != null) {
        clearTimeout(state.idleTimeout);
        state.idleTimeout = null;
      }
    }
    function setHttp2IdleTimeout(session) {
      const client = session[kClient];
      if (client[kHTTP2Session] !== session || session.closed || session.destroyed) {
        return;
      }
      if (session[kOpenStreams] !== 0 || client[kSize] !== 0) {
        clearHttp2IdleTimeout(session);
        return;
      }
      const state = session[kHTTP2SessionState];
      if (state.idleTimeout == null) {
        state.idleTimeout = setTimeout(onHttp2SessionIdleTimeout, client[kKeepAliveDefaultTimeout], session).unref();
      }
    }
    function onHttp2SessionIdleTimeout(session) {
      const client = session[kClient];
      const socket = session[kSocket];
      const state = session[kHTTP2SessionState];
      state.idleTimeout = null;
      if (client[kHTTP2Session] !== session || session[kOpenStreams] !== 0 || client[kSize] !== 0 || session.closed || session.destroyed) {
        return;
      }
      const err = new InformationalError("socket idle timeout");
      socket[kError] = err;
      util.destroy(socket, err);
    }
    function applyConnectionWindowSize(connectionWindowSize) {
      try {
        if (typeof this.setLocalWindowSize === "function") {
          this.setLocalWindowSize(connectionWindowSize);
        }
      } catch {
      }
    }
    function onHttp2RemoteSettings(settings) {
      this[kClient][kMaxConcurrentStreams] = settings.maxConcurrentStreams ?? this[kClient][kMaxConcurrentStreams];
      if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) {
        const err = new InformationalError("HTTP/2: Server disabled extended CONNECT protocol against RFC-8441");
        this[kSocket][kError] = err;
        this[kClient][kOnError](err);
        return;
      }
      this[kEnableConnectProtocol] = settings.enableConnectProtocol ?? this[kEnableConnectProtocol];
      this[kRemoteSettings] = true;
      this[kClient][kResume]();
    }
    function onHttp2SendPing(session) {
      const state = session[kHTTP2SessionState];
      if ((session.closed || session.destroyed) && state.ping.interval != null) {
        clearInterval(state.ping.interval);
        state.ping.interval = null;
        return;
      }
      session.ping(onPing.bind(session));
      function onPing(err, duration) {
        const client = this[kClient];
        const socket = this[kSocket];
        if (err != null) {
          const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`);
          socket[kError] = error;
          client[kOnError](error);
        } else {
          client.emit("ping", duration);
        }
      }
    }
    function onHttp2SessionError(err) {
      assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
      this[kSocket][kError] = err;
      this[kClient][kOnError](err);
    }
    function onHttp2FrameError(type, code, id) {
      if (id === 0) {
        const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`);
        this[kSocket][kError] = err;
        this[kClient][kOnError](err);
      }
    }
    function onHttp2SessionEnd() {
      const err = new SocketError("other side closed", util.getSocketInfo(this[kSocket]));
      this.destroy(err);
      util.destroy(this[kSocket], err);
    }
    function onHttp2SessionGoAway(errorCode, lastStreamID) {
      if (this[kReceivedGoAway]) {
        return;
      }
      this[kReceivedGoAway] = true;
      const err = getGoAwayError(this, errorCode);
      const client = this[kClient];
      const previousPendingIdx = client[kPendingIdx];
      const pendingIdx = getGoAwayPendingIdx(client, lastStreamID);
      const retriableRequests = [];
      for (let i = pendingIdx; i < previousPendingIdx; i++) {
        const request = client[kQueue][i];
        if (request != null) {
          closeRequestStream(request);
          if (canRetryRequestAfterGoAway(request)) {
            retriableRequests.push(request);
          } else {
            util.errorRequest(client, request, err);
          }
        }
      }
      if (pendingIdx !== previousPendingIdx) {
        const remainingPendingRequests = client[kQueue].slice(previousPendingIdx);
        client[kQueue].length = pendingIdx;
        client[kQueue].push(...retriableRequests, ...remainingPendingRequests);
      }
      if (client[kHTTP2Session] === this) {
        client[kSocket] = null;
        client[kHTTPContext] = null;
        client[kHTTP2Session] = null;
      }
      clearHttp2IdleTimeout(this);
      if (!this.closed && !this.destroyed) {
        this.close();
      }
      client[kPendingIdx] = pendingIdx;
      client.emit("disconnect", client[kUrl], [client], err);
      client[kResume]();
    }
    function onHttp2SessionClose() {
      const { [kClient]: client, [kHTTP2SessionState]: state, [kSocket]: socket } = this;
      const err = socket[kError] || this[kError] || new SocketError("closed", util.getSocketInfo(socket));
      if (client[kHTTP2Session] === this) {
        client[kSocket] = null;
        client[kHTTPContext] = null;
        client[kHTTP2Session] = null;
      }
      clearHttp2IdleTimeout(this);
      if (state.ping.interval != null) {
        clearInterval(state.ping.interval);
        state.ping.interval = null;
      }
      if (client.destroyed) {
        assert(client[kPending] === 0);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i = 0; i < requests.length; i++) {
          const request = requests[i];
          if (request != null) {
            util.errorRequest(client, request, err);
          }
        }
      }
    }
    function onHttp2SocketClose() {
      const err = this[kError] || new SocketError("closed", util.getSocketInfo(this));
      const session = this[kHTTP2Session];
      const client = session[kClient];
      if (client[kSocket] !== this) {
        if (session[kReceivedGoAway] || client[kHTTP2Session] != null && client[kHTTP2Session] !== session) {
          return;
        }
      }
      client[kSocket] = null;
      client[kHTTPContext] = null;
      if (client[kHTTP2Session] === session) {
        client[kHTTP2Session] = null;
      }
      session.destroy(err);
      client[kPendingIdx] = client[kRunningIdx];
      assert(client[kRunning] === 0);
      client.emit("disconnect", client[kUrl], [client], err);
      client[kResume]();
    }
    function onHttp2SocketError(err) {
      assert(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
      this[kError] = err;
      this[kClient][kOnError](err);
    }
    function onHttp2SocketEnd() {
      util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this)));
    }
    function onSocketClose() {
      this[kClosed] = true;
    }
    function noop() {
    }
    function closeStreamSession(stream) {
      const session = stream[kHTTP2Session];
      stream[kHTTP2Session] = null;
      session[kOpenStreams] -= 1;
      if (session[kOpenStreams] === 0) {
        session.unref();
        setHttp2IdleTimeout(session);
      }
    }
    function onUpgradeStreamClose() {
      this.off("error", noop);
      const state = this[kRequestStreamState];
      this[kRequestStreamState] = null;
      failUpgradeStream(state, new InformationalError("HTTP/2: stream closed before response headers"));
      closeStreamSession(this);
    }
    function onRequestStreamClose() {
      const state = this[kRequestStreamState];
      if (state) {
        releaseRequestStream(this);
        if (state.pendingEnd && !state.request.aborted && !state.request.completed) {
          state.request.onResponseEnd(state.trailers || {});
          state.finalizeRequest();
        }
      }
      this.off("data", onData);
      this.off("error", noop);
      closeStreamSession(this);
      this[kRequestStreamState] = null;
    }
    function shouldSendContentLength(method) {
      return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
    }
    function buildRequestHeaders(reqHeaders) {
      const headers = {};
      for (let n = 0; n < reqHeaders.length; n += 2) {
        const key = reqHeaders[n + 0];
        const val = reqHeaders[n + 1];
        const current = headers[key];
        if (key === "cookie") {
          if (current != null) {
            headers[key] = Array.isArray(current) ? (current.push(val), current) : [current, val];
          } else {
            headers[key] = val;
          }
          continue;
        }
        if (typeof val === "string") {
          headers[key] = current ? `${current}, ${val}` : val;
          continue;
        }
        for (let i = 0; i < val.length; i++) {
          headers[key] = headers[key] ? `${headers[key]}, ${val[i]}` : val[i];
        }
      }
      return headers;
    }
    function removeUpgradeStreamListeners(stream) {
      stream.off("response", onUpgradeResponse);
      stream.off("error", onUpgradeStreamError);
      stream.off("end", onUpgradeStreamEnd);
      stream.off("timeout", onUpgradeStreamTimeout);
      stream.off("error", noop);
    }
    function releaseUpgradeStream(stream) {
      if (stream == null) {
        return;
      }
      const state = stream[kRequestStreamState];
      if (state == null) {
        return;
      }
      const { request } = state;
      if (request[kRequestStream] === stream) {
        detachRequestFromStream(request);
      }
      removeUpgradeStreamListeners(stream);
      if (!stream.destroyed && !stream.closed) {
        stream.once("error", noop);
      }
    }
    function failUpgradeStream(state, err) {
      if (state == null) {
        return;
      }
      const { request } = state;
      if (state.responseReceived || request.aborted || request.completed) {
        return;
      }
      releaseUpgradeStream(state.stream);
      state.abort(err, true);
    }
    function onUpgradeStreamError() {
      const state = this[kRequestStreamState];
      if (typeof this.rstCode === "number" && this.rstCode !== 0) {
        failUpgradeStream(state, new InformationalError(`HTTP/2: "stream error" received - code ${this.rstCode}`));
      } else {
        failUpgradeStream(state, new InformationalError("HTTP/2: stream errored before response headers"));
      }
    }
    function onUpgradeStreamEnd() {
      failUpgradeStream(this[kRequestStreamState], new InformationalError("HTTP/2: stream half-closed (remote)"));
    }
    function onUpgradeStreamTimeout() {
      const state = this[kRequestStreamState];
      failUpgradeStream(state, new InformationalError(`HTTP/2: "stream timeout after ${state.headersTimeout}"`));
    }
    function onUpgradeResponse(headers, _flags) {
      const stream = this;
      const state = stream[kRequestStreamState];
      const { request } = state;
      state.responseReceived = true;
      const statusCode = headers[HTTP2_HEADER_STATUS];
      delete headers[HTTP2_HEADER_STATUS];
      request.onRequestUpgrade(statusCode, headers, stream);
      if (request.aborted || request.completed) {
        return;
      }
      removeUpgradeStreamListeners(stream);
      detachRequestFromStream(request);
      state.finalizeRequest();
    }
    function setupUpgradeStream(stream, state) {
      const { request, headersTimeout, session } = state;
      stream[kHTTP2Stream] = true;
      stream[kHTTP2Session] = session;
      stream[kRequestStreamState] = state;
      state.stream = stream;
      bindRequestToStream(request, stream, releaseUpgradeStream);
      stream.once("response", onUpgradeResponse);
      stream.on("error", onUpgradeStreamError);
      stream.once("end", onUpgradeStreamEnd);
      stream.on("timeout", onUpgradeStreamTimeout);
      stream.once("close", onUpgradeStreamClose);
      clearHttp2IdleTimeout(session);
      ++session[kOpenStreams];
      stream.setTimeout(headersTimeout);
    }
    function writeH2(client, request) {
      const headersTimeout = request.headersTimeout ?? client[kHeadersTimeout];
      const bodyTimeout = request.bodyTimeout ?? client[kBodyTimeout];
      const session = client[kHTTP2Session];
      const { method, path, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
      let { body } = request;
      if (upgrade != null && upgrade !== "websocket") {
        util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
        return false;
      }
      const headers = buildRequestHeaders(reqHeaders);
      let stream = null;
      headers[HTTP2_HEADER_AUTHORITY] = host || client[kHostAuthority];
      headers[HTTP2_HEADER_METHOD] = method;
      let requestFinalized = false;
      const finalizeRequest = (resetPendingIdx = false) => {
        if (requestFinalized) {
          return;
        }
        requestFinalized = true;
        completeRequest(client, request, resetPendingIdx);
        client[kResume]();
      };
      const abort = (err, resetPendingIdx = false) => {
        if (request.aborted || request.completed) {
          return;
        }
        err = err || new RequestAbortedError();
        util.errorRequest(client, request, err);
        if (stream != null) {
          clearRequestStream(request);
          stream.close();
          client[kOnError](err);
          finalizeRequest(resetPendingIdx);
        }
        util.destroy(body, err);
      };
      const requestStream = (headers2, options) => {
        try {
          return session.request(headers2, options);
        } catch (err) {
          if (err?.code === "ERR_HTTP2_INVALID_SESSION") {
            const wrappedErr2 = new SocketError(err.message, util.getSocketInfo(session[kSocket]));
            wrappedErr2.cause = err;
            session[kError] = wrappedErr2;
            resetHttp2Session(session, wrappedErr2);
            requeueUnsentRequest(client, request);
            return null;
          }
          const wrappedErr = new InformationalError(err.message, { cause: err });
          session[kError] = wrappedErr;
          session[kSocket][kError] = wrappedErr;
          session.destroy(wrappedErr);
          util.destroy(session[kSocket], wrappedErr);
          abort(wrappedErr);
          return null;
        }
      };
      try {
        request.onRequestStart(abort, null);
      } catch (err) {
        util.errorRequest(client, request, err);
      }
      if (request.aborted) {
        return false;
      }
      if (upgrade || method === "CONNECT") {
        session.ref();
        const upgradeState = {
          abort,
          finalizeRequest,
          request,
          headersTimeout,
          bodyTimeout,
          responseReceived: false,
          session,
          stream: null
        };
        if (upgrade === "websocket") {
          if (session[kEnableConnectProtocol] === false) {
            util.errorRequest(client, request, new InformationalError("HTTP/2: Extended CONNECT protocol not supported by server"));
            session.unref();
            return false;
          }
          headers[HTTP2_HEADER_METHOD] = "CONNECT";
          headers[HTTP2_HEADER_PROTOCOL] = "websocket";
          headers[HTTP2_HEADER_PATH] = path;
          if (protocol === "ws:" || protocol === "wss:") {
            headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
          } else {
            headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
          }
          stream = requestStream(headers, { endStream: false, signal });
          if (stream == null) {
            session.unref();
            return false;
          }
          setupUpgradeStream(stream, upgradeState);
          return true;
        }
        stream = requestStream(headers, { endStream: false, signal });
        if (stream == null) {
          session.unref();
          return false;
        }
        setupUpgradeStream(stream, upgradeState);
        return true;
      }
      headers[HTTP2_HEADER_PATH] = path;
      headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
      if (body && typeof body.read === "function") {
        body.read(0);
      }
      let contentLength = util.bodyLength(body);
      if (util.isFormDataLike(body)) {
        extractBody ??= require_body().extractBody;
        const [bodyStream, contentType] = extractBody(body);
        headers["content-type"] = contentType;
        body = bodyStream.stream;
        contentLength = bodyStream.length;
      }
      if (contentLength == null) {
        contentLength = request.contentLength;
      }
      if (contentLength === 0 && !expectsPayload) {
        contentLength = null;
      }
      if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
        if (client[kStrictContentLength]) {
          util.errorRequest(client, request, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      if (contentLength != null) {
        assert(body || contentLength === 0, "no body must not have content length");
        headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
      }
      session.ref();
      if (channels.sendHeaders.hasSubscribers) {
        let header = "";
        for (const key in headers) {
          header += `${key}: ${headers[key]}\r
`;
        }
        channels.sendHeaders.publish({ request, headers: header, socket: session[kSocket] });
      }
      const shouldEndStream = body === null || contentLength === 0;
      const state = {
        abort,
        body,
        client,
        contentLength,
        expectsPayload,
        finalizeRequest,
        request,
        headersTimeout,
        bodyTimeout,
        responseReceived: false,
        session,
        stream: null
      };
      if (expectContinue) {
        headers[HTTP2_HEADER_EXPECT] = "100-continue";
      }
      stream = requestStream(headers, { endStream: shouldEndStream, signal });
      if (stream == null) {
        return false;
      }
      stream[kHTTP2Stream] = true;
      stream[kRequestStreamState] = state;
      state.stream = stream;
      clearHttp2IdleTimeout(session);
      ++session[kOpenStreams];
      stream.setTimeout(headersTimeout);
      stream[kHTTP2Session] = session;
      stream.once("close", onRequestStreamClose);
      bindRequestToStream(request, stream, releaseRequestStream);
      if (expectContinue) {
        stream.once("continue", writeBodyH2);
      }
      stream.once("response", onResponse);
      stream.once("end", onEnd);
      stream.once("error", onError);
      stream.once("frameError", onFrameError);
      stream.on("aborted", onAborted);
      stream.on("timeout", onTimeout);
      stream.once("trailers", onTrailers);
      if (!expectContinue) {
        writeBodyH2.call(stream);
      }
      return true;
    }
    function removeRequestStreamListeners(stream) {
      stream.off("error", noop);
      stream.off("continue", writeBodyH2);
      stream.off("response", onResponse);
      stream.off("end", onEnd);
      stream.off("error", onError);
      stream.off("frameError", onFrameError);
      stream.off("aborted", onAborted);
      stream.off("timeout", onTimeout);
      stream.off("trailers", onTrailers);
      stream.off("data", onData);
    }
    function releaseRequestStream(stream) {
      if (stream == null) {
        return;
      }
      const state = stream[kRequestStreamState];
      if (state == null) {
        return;
      }
      const { request } = state;
      if (request[kRequestStream] === stream) {
        detachRequestFromStream(request);
      }
      removeRequestStreamListeners(stream);
      if (!stream.destroyed && !stream.closed) {
        stream.once("error", noop);
      }
    }
    function onData(chunk) {
      const stream = this;
      const { request } = stream[kRequestStreamState];
      if (request.aborted || request.completed) {
        return;
      }
      if (request.onResponseData(chunk) === false) {
        stream.pause();
      }
    }
    function onResponse(headers) {
      const stream = this;
      const state = stream[kRequestStreamState];
      const { request } = state;
      stream.off("response", onResponse);
      const statusCode = headers[HTTP2_HEADER_STATUS];
      delete headers[HTTP2_HEADER_STATUS];
      request.onResponseStarted();
      state.responseReceived = true;
      stream.setTimeout(state.bodyTimeout);
      if (request.aborted) {
        releaseRequestStream(stream);
        return;
      }
      if (request.onResponseStart(Number(statusCode), headers, stream.resume.bind(stream), "") === false) {
        stream.pause();
      }
      stream.on("data", onData);
    }
    function onEnd() {
      const stream = this;
      const state = stream[kRequestStreamState];
      const { request } = state;
      stream.off("end", onEnd);
      if (state.responseReceived) {
        if (!request.aborted && !request.completed) {
          state.pendingEnd = true;
        }
      } else {
        state.abort(new InformationalError("HTTP/2: stream half-closed (remote)"), true);
      }
    }
    function onError(err) {
      const stream = this;
      const state = stream[kRequestStreamState];
      stream.off("error", onError);
      state.abort(err);
    }
    function onFrameError(type, code) {
      const stream = this;
      const state = stream[kRequestStreamState];
      stream.off("frameError", onFrameError);
      state.abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`));
    }
    function onAborted() {
      this.off("data", onData);
    }
    function onTimeout() {
      const stream = this;
      const state = stream[kRequestStreamState];
      stream.off("timeout", onTimeout);
      const err = state.responseReceived ? new BodyTimeoutError(`HTTP/2: "stream timeout after ${state.bodyTimeout}"`) : new HeadersTimeoutError(`HTTP/2: "headers timeout after ${state.headersTimeout}"`);
      state.abort(err);
    }
    function onTrailers(trailers) {
      const stream = this;
      const state = stream[kRequestStreamState];
      const { request } = state;
      stream.off("trailers", onTrailers);
      stream.off("data", onData);
      if (request.aborted || request.completed) {
        return;
      }
      state.trailers = trailers;
    }
    function writeBodyH2() {
      const stream = this;
      const state = stream[kRequestStreamState];
      const { abort, body, client, contentLength, expectsPayload, request } = state;
      if (!body || contentLength === 0) {
        writeBuffer(
          abort,
          stream,
          null,
          client,
          request,
          client[kSocket],
          contentLength,
          expectsPayload
        );
      } else if (util.isBuffer(body)) {
        writeBuffer(
          abort,
          stream,
          body,
          client,
          request,
          client[kSocket],
          contentLength,
          expectsPayload
        );
      } else if (util.isBlobLike(body)) {
        if (typeof body.stream === "function") {
          writeIterable(
            abort,
            stream,
            body.stream(),
            client,
            request,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else {
          writeBlob(
            abort,
            stream,
            body,
            client,
            request,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        }
      } else if (util.isStream(body)) {
        writeStream(
          abort,
          client[kSocket],
          expectsPayload,
          stream,
          body,
          client,
          request,
          contentLength
        );
      } else if (util.isIterable(body)) {
        writeIterable(
          abort,
          stream,
          body,
          client,
          request,
          client[kSocket],
          contentLength,
          expectsPayload
        );
      } else {
        assert(false);
      }
    }
    function writeBuffer(abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
      try {
        if (body != null && util.isBuffer(body)) {
          assert(contentLength === body.byteLength, "buffer body must have content length");
          h2stream.cork();
          h2stream.write(body);
          h2stream.uncork();
          h2stream.end();
          request.onBodySent(body);
        }
        if (!expectsPayload) {
          socket[kReset] = true;
        }
        request.onRequestSent();
        client[kResume]();
      } catch (error) {
        abort(error);
      }
    }
    function writeStream(abort, socket, expectsPayload, h2stream, body, client, request, contentLength) {
      assert(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      const pipe = pipeline(
        body,
        h2stream,
        (err) => {
          if (err) {
            util.destroy(pipe, err);
            abort(err);
          } else {
            util.removeAllListeners(pipe);
            request.onRequestSent();
            if (!expectsPayload) {
              socket[kReset] = true;
            }
            client[kResume]();
          }
        }
      );
      util.addListener(pipe, "data", onPipeData);
      function onPipeData(chunk) {
        request.onBodySent(chunk);
      }
    }
    async function writeBlob(abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
      try {
        if (contentLength != null && contentLength !== body.size) {
          throw new RequestContentLengthMismatchError();
        }
        const buffer = Buffer.from(await body.arrayBuffer());
        h2stream.cork();
        h2stream.write(buffer);
        h2stream.uncork();
        h2stream.end();
        request.onBodySent(buffer);
        request.onRequestSent();
        if (!expectsPayload) {
          socket[kReset] = true;
        }
        client[kResume]();
      } catch (err) {
        abort(err);
      }
    }
    async function writeIterable(abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
      assert(contentLength !== 0 || client[kRunning] === 0, "iterator body cannot be pipelined");
      let callback = null;
      function onDrain() {
        if (callback) {
          const cb = callback;
          callback = null;
          cb();
        }
      }
      const waitForDrain = () => new Promise((resolve, reject) => {
        assert(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve;
        }
      });
      h2stream.on("close", onDrain).on("drain", onDrain);
      try {
        for await (const chunk of body) {
          if (socket[kError]) {
            throw socket[kError];
          }
          const res = h2stream.write(chunk);
          request.onBodySent(chunk);
          if (!res) {
            await waitForDrain();
          }
        }
        h2stream.end();
        request.onRequestSent();
        if (!expectsPayload) {
          socket[kReset] = true;
        }
        client[kResume]();
      } catch (err) {
        abort(err);
      } finally {
        h2stream.off("close", onDrain).off("drain", onDrain);
      }
    }
    module.exports = connectH2;
  }
});

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

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

// ../../node_modules/undici/lib/dispatcher/pool-base.js
var require_pool_base = __commonJS({
  "../../node_modules/undici/lib/dispatcher/pool-base.js"(exports, module) {
    "use strict";
    var { PoolStats } = require_stats();
    var DispatcherBase = require_dispatcher_base();
    var FixedQueue = require_fixed_queue();
    var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols();
    var kClients = /* @__PURE__ */ Symbol("clients");
    var kNeedDrain = /* @__PURE__ */ Symbol("needDrain");
    var kQueue = /* @__PURE__ */ Symbol("queue");
    var kClosedResolve = /* @__PURE__ */ Symbol("closed resolve");
    var kOnDrain = /* @__PURE__ */ Symbol("onDrain");
    var kOnConnect = /* @__PURE__ */ Symbol("onConnect");
    var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect");
    var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError");
    var kGetDispatcher = /* @__PURE__ */ Symbol("get dispatcher");
    var kHasDispatcher = /* @__PURE__ */ Symbol("has dispatcher");
    var kAddClient = /* @__PURE__ */ Symbol("add client");
    var kRemoveClient = /* @__PURE__ */ Symbol("remove client");
    var PoolBase = class extends DispatcherBase {
      [kQueue] = new FixedQueue();
      [kQueued] = 0;
      [kClients] = [];
      [kNeedDrain] = false;
      [kOnDrain](client, origin, targets) {
        const queue = this[kQueue];
        let needDrain = false;
        while (!needDrain) {
          const item = queue.shift();
          if (!item) {
            break;
          }
          this[kQueued]--;
          needDrain = !client.dispatch(item.opts, item.handler);
        }
        client[kNeedDrain] = needDrain;
        if (!needDrain && this[kNeedDrain]) {
          this[kNeedDrain] = false;
          this.emit("drain", origin, [this, ...targets]);
        }
        if (this[kClosedResolve] && queue.isEmpty()) {
          const closeAll = [];
          for (let i = 0; i < this[kClients].length; i++) {
            const client2 = this[kClients][i];
            if (!client2.destroyed) {
              closeAll.push(client2.close());
            }
          }
          return Promise.all(closeAll).then(this[kClosedResolve]);
        }
      }
      [kOnConnect] = (origin, targets) => {
        this.emit("connect", origin, [this, ...targets]);
      };
      [kOnDisconnect] = (origin, targets, err) => {
        this.emit("disconnect", origin, [this, ...targets], err);
      };
      [kOnConnectionError] = (origin, targets, err) => {
        this.emit("connectionError", origin, [this, ...targets], err);
      };
      get [kBusy]() {
        return this[kNeedDrain];
      }
      get [kConnected]() {
        let ret = 0;
        for (const { [kConnected]: connected } of this[kClients]) {
          ret += connected;
        }
        return ret;
      }
      get [kFree]() {
        let ret = 0;
        for (const { [kConnected]: connected, [kNeedDrain]: needDrain } of this[kClients]) {
          ret += connected && !needDrain;
        }
        return ret;
      }
      get [kPending]() {
        let ret = this[kQueued];
        for (const { [kPending]: pending } of this[kClients]) {
          ret += pending;
        }
        return ret;
      }
      get [kRunning]() {
        let ret = 0;
        for (const { [kRunning]: running } of this[kClients]) {
          ret += running;
        }
        return ret;
      }
      get [kSize]() {
        let ret = this[kQueued];
        for (const { [kSize]: size } of this[kClients]) {
          ret += size;
        }
        return ret;
      }
      get stats() {
        return new PoolStats(this);
      }
      [kClose]() {
        if (this[kQueue].isEmpty()) {
          const closeAll = [];
          for (let i = 0; i < this[kClients].length; i++) {
            const client = this[kClients][i];
            if (!client.destroyed) {
              closeAll.push(client.close());
            }
          }
          return Promise.all(closeAll);
        } else {
          return new Promise((resolve) => {
            this[kClosedResolve] = resolve;
          });
        }
      }
      [kDestroy](err) {
        while (true) {
          const item = this[kQueue].shift();
          if (!item) {
            break;
          }
          item.handler.onResponseError(null, err);
        }
        const destroyAll = new Array(this[kClients].length);
        for (let i = 0; i < this[kClients].length; i++) {
          destroyAll[i] = this[kClients][i].destroy(err);
        }
        return Promise.all(destroyAll);
      }
      [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[kHasDispatcher]();
        }
        return !this[kNeedDrain];
      }
      [kHasDispatcher]() {
        for (let i = 0; i < this[kClients].length; i++) {
          const dispatcher = this[kClients][i];
          if (!dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true) {
            return true;
          }
        }
        return false;
      }
      [kAddClient](client) {
        client.on("drain", this[kOnDrain].bind(this, client)).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, client[kUrl], [client, this]);
            }
          });
        }
        return this;
      }
      [kRemoveClient](client) {
        const idx = this[kClients].indexOf(client);
        if (idx !== -1) {
          this[kClients].splice(idx, 1);
        }
        client.close(() => {
        });
        this[kNeedDrain] = !this[kClients].some((dispatcher) => !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true);
      }
    };
    module.exports = {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kRemoveClient,
      kGetDispatcher,
      kHasDispatcher
    };
  }
});

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

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

// ../../node_modules/undici/lib/dispatcher/round-robin-pool.js
var require_round_robin_pool = __commonJS({
  "../../node_modules/undici/lib/dispatcher/round-robin-pool.js"(exports, module) {
    "use strict";
    var {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kGetDispatcher,
      kHasDispatcher,
      kRemoveClient
    } = require_pool_base();
    var Client = require_client();
    var {
      InvalidArgumentError
    } = require_errors();
    var util = require_util();
    var { kUrl } = require_symbols();
    var buildConnector = require_connect();
    var kOptions = /* @__PURE__ */ Symbol("options");
    var kConnections = /* @__PURE__ */ Symbol("connections");
    var kFactory = /* @__PURE__ */ Symbol("factory");
    var kIndex = /* @__PURE__ */ Symbol("index");
    function defaultFactory(origin, opts) {
      return new Client(origin, opts);
    }
    var RoundRobinPool = class extends PoolBase {
      constructor(origin, {
        connections,
        factory = defaultFactory,
        connect,
        connectTimeout,
        tls,
        maxCachedSessions,
        socketPath,
        autoSelectFamily,
        autoSelectFamilyAttemptTimeout,
        allowH2,
        clientTtl,
        ...options
      } = {}) {
        if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
          throw new InvalidArgumentError("invalid connections");
        }
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
          throw new InvalidArgumentError("connect must be a function or an object");
        }
        if (typeof connect !== "function") {
          connect = buildConnector({
            ...tls,
            maxCachedSessions,
            allowH2,
            socketPath,
            timeout: connectTimeout,
            ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
            ...connect
          });
        }
        super();
        this[kConnections] = connections || null;
        this[kUrl] = util.parseOrigin(origin);
        this[kOptions] = { ...util.deepClone(options), connect, allowH2, clientTtl, socketPath };
        this[kFactory] = factory;
        this[kIndex] = -1;
        this.on("connect", (origin2, targets) => {
          if (clientTtl != null && clientTtl > 0) {
            for (const target of targets) {
              Object.assign(target, { ttl: Date.now() });
            }
          }
        });
        this.on("connectionError", (origin2, targets, error) => {
          for (const target of targets) {
            const idx = this[kClients].indexOf(target);
            if (idx !== -1) {
              this[kClients].splice(idx, 1);
            }
          }
        });
      }
      [kGetDispatcher]() {
        const clientTtlOption = this[kOptions].clientTtl;
        if (this[kClients].length === 0) {
          const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
          this[kAddClient](dispatcher);
          return dispatcher;
        }
        let checked = 0;
        while (checked < this[kClients].length) {
          this[kIndex] = (this[kIndex] + 1) % this[kClients].length;
          const client = this[kClients][this[kIndex]];
          if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) {
            this[kRemoveClient](client);
            this[kIndex]--;
            continue;
          }
          if (!client[kNeedDrain]) {
            return client;
          }
          checked++;
        }
        if (!this[kConnections] || this[kClients].length < this[kConnections]) {
          const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
          this[kAddClient](dispatcher);
          return dispatcher;
        }
      }
      [kHasDispatcher]() {
        const clientTtlOption = this[kOptions].clientTtl;
        for (let i = 0; i < this[kClients].length; i++) {
          const client = this[kClients][i];
          if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) {
            this[kRemoveClient](client);
            if (i <= this[kIndex]) {
              this[kIndex]--;
            }
            i--;
          } else if (!client[kNeedDrain]) {
            return true;
          }
        }
        if (!this[kConnections] || this[kClients].length < this[kConnections]) {
          const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
          this[kAddClient](dispatcher);
          return true;
        }
        return false;
      }
    };
    module.exports = RoundRobinPool;
  }
});

// ../../node_modules/undici/lib/dispatcher/agent.js
var require_agent = __commonJS({
  "../../node_modules/undici/lib/dispatcher/agent.js"(exports, module) {
    "use strict";
    var { InvalidArgumentError, MaxOriginsReachedError } = require_errors();
    var { kBusy, kClients, kConnected, kRunning, kClose, kDestroy, kDispatch, kUrl } = require_symbols();
    var DispatcherBase = require_dispatcher_base();
    var Pool = require_pool();
    var Client = require_client();
    var util = require_util();
    var kOnConnect = /* @__PURE__ */ Symbol("onConnect");
    var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect");
    var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError");
    var kOnDrain = /* @__PURE__ */ Symbol("onDrain");
    var kFactory = /* @__PURE__ */ Symbol("factory");
    var kOptions = /* @__PURE__ */ Symbol("options");
    var kOrigins = /* @__PURE__ */ Symbol("origins");
    function defaultFactory(origin, opts) {
      return opts && opts.connections === 1 ? new Client(origin, opts) : new Pool(origin, opts);
    }
    var Agent = class extends DispatcherBase {
      constructor({ factory = defaultFactory, maxOrigins = Infinity, connect, ...options } = {}) {
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
          throw new InvalidArgumentError("connect must be a function or an object");
        }
        if (typeof maxOrigins !== "number" || Number.isNaN(maxOrigins) || maxOrigins <= 0) {
          throw new InvalidArgumentError("maxOrigins must be a number greater than 0");
        }
        super(options);
        if (connect && typeof connect !== "function") {
          connect = { ...connect };
        }
        this[kOptions] = { ...util.deepClone(options), maxOrigins, connect };
        this[kFactory] = factory;
        this[kClients] = /* @__PURE__ */ new Map();
        this[kOrigins] = /* @__PURE__ */ new Set();
        this[kOnDrain] = (origin, targets) => {
          this.emit("drain", origin, [this, ...targets]);
        };
        this[kOnConnect] = (origin, targets) => {
          this.emit("connect", origin, [this, ...targets]);
        };
        this[kOnDisconnect] = (origin, targets, err) => {
          this.emit("disconnect", origin, [this, ...targets], err);
        };
        this[kOnConnectionError] = (origin, targets, err) => {
          this.emit("connectionError", origin, [this, ...targets], err);
        };
      }
      get [kRunning]() {
        let ret = 0;
        for (const dispatcher of this[kClients].values()) {
          ret += dispatcher[kRunning];
        }
        return ret;
      }
      [kDispatch](opts, handler) {
        let origin;
        if (opts.origin && (typeof opts.origin === "string" || opts.origin instanceof URL)) {
          origin = String(opts.origin);
        } else {
          throw new InvalidArgumentError("opts.origin must be a non-empty string or URL.");
        }
        const allowH2 = opts.allowH2 ?? this[kOptions].allowH2;
        const key = allowH2 === false ? `${origin}#http1-only` : origin;
        if (this[kOrigins].size >= this[kOptions].maxOrigins && !this[kOrigins].has(origin)) {
          throw new MaxOriginsReachedError();
        }
        let dispatcher = this[kClients].get(key);
        if (!dispatcher) {
          dispatcher = this[kFactory](opts.origin, allowH2 === false ? { ...this[kOptions], allowH2: false } : this[kOptions]);
          const closeClientIfUnused = () => {
            if (this[kClients].get(key) !== dispatcher) {
              return;
            }
            if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) {
              return;
            }
            this[kClients].delete(key);
            if (!dispatcher.destroyed) {
              dispatcher.close();
            }
            let hasOrigin = false;
            for (const client of this[kClients].values()) {
              if (client[kUrl].origin === dispatcher[kUrl].origin) {
                hasOrigin = true;
                break;
              }
            }
            if (!hasOrigin) {
              this[kOrigins].delete(dispatcher[kUrl].origin);
            }
          };
          dispatcher.on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", (origin2, targets, err) => {
            closeClientIfUnused();
            this[kOnDisconnect](origin2, targets, err);
          }).on("connectionError", (origin2, targets, err) => {
            closeClientIfUnused();
            this[kOnConnectionError](origin2, targets, err);
          });
          this[kClients].set(key, dispatcher);
          this[kOrigins].add(origin);
        }
        return dispatcher.dispatch(opts, handler);
      }
      [kClose]() {
        const closePromises = [];
        for (const dispatcher of this[kClients].values()) {
          closePromises.push(dispatcher.close());
        }
        this[kClients].clear();
        return Promise.all(closePromises);
      }
      [kDestroy](err) {
        const destroyPromises = [];
        for (const dispatcher of this[kClients].values()) {
          destroyPromises.push(dispatcher.destroy(err));
        }
        this[kClients].clear();
        return Promise.all(destroyPromises);
      }
      get stats() {
        const allClientStats = {};
        for (const dispatcher of this[kClients].values()) {
          if (dispatcher.stats) {
            allClientStats[dispatcher[kUrl].origin] = dispatcher.stats;
          }
        }
        return allClientStats;
      }
    };
    module.exports = Agent;
  }
});

// ../../node_modules/undici/lib/dispatcher/dispatcher1-wrapper.js
var require_dispatcher1_wrapper = __commonJS({
  "../../node_modules/undici/lib/dispatcher/dispatcher1-wrapper.js"(exports, module) {
    "use strict";
    var Dispatcher = require_dispatcher();
    var { InvalidArgumentError } = require_errors();
    var { toRawHeaders } = require_util();
    var LegacyHandlerWrapper = class {
      #handler;
      constructor(handler) {
        this.#handler = handler;
      }
      onRequestStart(controller, context) {
        this.#handler.onConnect?.((reason) => controller.abort(reason), context);
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        const rawHeaders = controller?.rawHeaders ?? toRawHeaders(headers ?? {});
        this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        const rawHeaders = controller?.rawHeaders ?? toRawHeaders(headers ?? {});
        if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
          controller.pause();
        }
      }
      onResponseData(controller, chunk) {
        if (this.#handler.onData?.(chunk) === false) {
          controller.pause();
        }
      }
      onResponseEnd(controller, trailers) {
        const rawTrailers = controller?.rawTrailers ?? toRawHeaders(trailers ?? {});
        this.#handler.onComplete?.(rawTrailers);
      }
      onResponseError(_controller, err) {
        if (!this.#handler.onError) {
          throw err;
        }
        this.#handler.onError(err);
      }
      onBodySent(chunk) {
        this.#handler.onBodySent?.(chunk);
      }
      onRequestSent() {
        this.#handler.onRequestSent?.();
      }
      onResponseStarted() {
        this.#handler.onResponseStarted?.();
      }
    };
    var Dispatcher1Wrapper = class _Dispatcher1Wrapper extends Dispatcher {
      #dispatcher;
      constructor(dispatcher) {
        super();
        if (!dispatcher || typeof dispatcher.dispatch !== "function") {
          throw new InvalidArgumentError("Argument dispatcher must implement dispatch");
        }
        this.#dispatcher = dispatcher;
      }
      static wrapHandler(handler) {
        if (!handler || typeof handler !== "object") {
          throw new InvalidArgumentError("handler must be an object");
        }
        if (typeof handler.onRequestStart === "function") {
          return handler;
        }
        return new LegacyHandlerWrapper(handler);
      }
      dispatch(opts, handler) {
        if (opts.allowH2 !== false) {
          opts = { ...opts, allowH2: false };
        }
        return this.#dispatcher.dispatch(opts, _Dispatcher1Wrapper.wrapHandler(handler));
      }
      close(...args) {
        return this.#dispatcher.close(...args);
      }
      destroy(...args) {
        return this.#dispatcher.destroy(...args);
      }
    };
    module.exports = Dispatcher1Wrapper;
  }
});

// ../../node_modules/undici/lib/core/socks5-utils.js
var require_socks5_utils = __commonJS({
  "../../node_modules/undici/lib/core/socks5-utils.js"(exports, module) {
    "use strict";
    var { Buffer: Buffer2 } = __require("buffer");
    var net = __require("net");
    var { InvalidArgumentError } = require_errors();
    function parseAddress(address) {
      if (net.isIPv4(address)) {
        const parts = address.split(".").map(Number);
        return {
          type: 1,
          // IPv4
          buffer: Buffer2.from(parts)
        };
      }
      if (net.isIPv6(address)) {
        return {
          type: 4,
          // IPv6
          buffer: parseIPv6(address)
        };
      }
      const domainBuffer = Buffer2.from(address, "utf8");
      if (domainBuffer.length > 255) {
        throw new InvalidArgumentError("Domain name too long (max 255 bytes)");
      }
      return {
        type: 3,
        // Domain
        buffer: Buffer2.concat([Buffer2.from([domainBuffer.length]), domainBuffer])
      };
    }
    function parseIPv6(address) {
      const buffer = Buffer2.alloc(16);
      let normalizedAddress = address;
      if (address.includes(".")) {
        const lastColonIndex = address.lastIndexOf(":");
        const ipv4Part = address.slice(lastColonIndex + 1);
        if (net.isIPv4(ipv4Part)) {
          const octets = ipv4Part.split(".").map(Number);
          const high = (octets[0] << 8 | octets[1]).toString(16);
          const low = (octets[2] << 8 | octets[3]).toString(16);
          normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}`;
        }
      }
      const doubleColonIndex = normalizedAddress.indexOf("::");
      if (doubleColonIndex !== -1) {
        const before = normalizedAddress.slice(0, doubleColonIndex);
        const after = normalizedAddress.slice(doubleColonIndex + 2);
        const beforeParts = before === "" ? [] : before.split(":");
        const afterParts = after === "" ? [] : after.split(":");
        let bufferIndex = 0;
        for (const part of beforeParts) {
          buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
          bufferIndex += 2;
        }
        bufferIndex = 16 - afterParts.length * 2;
        for (const part of afterParts) {
          buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
          bufferIndex += 2;
        }
      } else {
        const parts = normalizedAddress.split(":");
        for (let i = 0; i < parts.length; i++) {
          buffer.writeUInt16BE(parseInt(parts[i], 16), i * 2);
        }
      }
      return buffer;
    }
    function buildAddressBuffer(type, addressBuffer, port) {
      const portBuffer = Buffer2.allocUnsafe(2);
      portBuffer.writeUInt16BE(port, 0);
      return Buffer2.concat([
        Buffer2.from([type]),
        addressBuffer,
        portBuffer
      ]);
    }
    function parseResponseAddress(buffer, offset = 0) {
      if (buffer.length < offset + 1) {
        throw new InvalidArgumentError("Buffer too small to contain address type");
      }
      const addressType = buffer[offset];
      let address;
      let currentOffset = offset + 1;
      switch (addressType) {
        case 1: {
          if (buffer.length < currentOffset + 6) {
            throw new InvalidArgumentError("Buffer too small for IPv4 address");
          }
          address = Array.from(buffer.subarray(currentOffset, currentOffset + 4)).join(".");
          currentOffset += 4;
          break;
        }
        case 3: {
          if (buffer.length < currentOffset + 1) {
            throw new InvalidArgumentError("Buffer too small for domain length");
          }
          const domainLength = buffer[currentOffset];
          currentOffset += 1;
          if (buffer.length < currentOffset + domainLength + 2) {
            throw new InvalidArgumentError("Buffer too small for domain address");
          }
          address = buffer.subarray(currentOffset, currentOffset + domainLength).toString("utf8");
          currentOffset += domainLength;
          break;
        }
        case 4: {
          if (buffer.length < currentOffset + 18) {
            throw new InvalidArgumentError("Buffer too small for IPv6 address");
          }
          const parts = [];
          for (let i = 0; i < 8; i++) {
            const value = buffer.readUInt16BE(currentOffset + i * 2);
            parts.push(value.toString(16));
          }
          address = parts.join(":");
          currentOffset += 16;
          break;
        }
        default:
          throw new InvalidArgumentError(`Invalid address type: ${addressType}`);
      }
      if (buffer.length < currentOffset + 2) {
        throw new InvalidArgumentError("Buffer too small for port");
      }
      const port = buffer.readUInt16BE(currentOffset);
      currentOffset += 2;
      return {
        address,
        port,
        bytesRead: currentOffset - offset
      };
    }
    function createReplyError(replyCode) {
      const messages = {
        1: "General SOCKS server failure",
        2: "Connection not allowed by ruleset",
        3: "Network unreachable",
        4: "Host unreachable",
        5: "Connection refused",
        6: "TTL expired",
        7: "Command not supported",
        8: "Address type not supported"
      };
      const message = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}`;
      const error = new Error(message);
      error.code = `SOCKS5_${replyCode}`;
      return error;
    }
    module.exports = {
      parseAddress,
      parseIPv6,
      buildAddressBuffer,
      parseResponseAddress,
      createReplyError
    };
  }
});

// ../../node_modules/undici/lib/core/socks5-client.js
var require_socks5_client = __commonJS({
  "../../node_modules/undici/lib/core/socks5-client.js"(exports, module) {
    "use strict";
    var { EventEmitter } = __require("events");
    var { Buffer: Buffer2 } = __require("buffer");
    var { InvalidArgumentError, Socks5ProxyError } = require_errors();
    var { debuglog } = __require("util");
    var { parseAddress } = require_socks5_utils();
    var debug = debuglog("undici:socks5");
    var EMPTY_BUFFER = Buffer2.alloc(0);
    var SOCKS_VERSION = 5;
    var AUTH_METHODS = {
      NO_AUTH: 0,
      GSSAPI: 1,
      USERNAME_PASSWORD: 2,
      NO_ACCEPTABLE: 255
    };
    var COMMANDS = {
      CONNECT: 1,
      BIND: 2,
      UDP_ASSOCIATE: 3
    };
    var ADDRESS_TYPES = {
      IPV4: 1,
      DOMAIN: 3,
      IPV6: 4
    };
    var REPLY_CODES = {
      SUCCEEDED: 0,
      GENERAL_FAILURE: 1,
      CONNECTION_NOT_ALLOWED: 2,
      NETWORK_UNREACHABLE: 3,
      HOST_UNREACHABLE: 4,
      CONNECTION_REFUSED: 5,
      TTL_EXPIRED: 6,
      COMMAND_NOT_SUPPORTED: 7,
      ADDRESS_TYPE_NOT_SUPPORTED: 8
    };
    var STATES = {
      INITIAL: "initial",
      HANDSHAKING: "handshaking",
      AUTHENTICATING: "authenticating",
      AUTHENTICATED: "authenticated",
      CONNECTING: "connecting",
      CONNECTED: "connected",
      ERROR: "error",
      CLOSED: "closed"
    };
    var Socks5Client = class extends EventEmitter {
      constructor(socket, options = {}) {
        super();
        if (!socket) {
          throw new InvalidArgumentError("socket is required");
        }
        this.socket = socket;
        this.options = options;
        this.state = STATES.INITIAL;
        this.buffer = EMPTY_BUFFER;
        this.onSocketData = this.onData.bind(this);
        this.onSocketError = this.onError.bind(this);
        this.onSocketClose = this.onClose.bind(this);
        this.authMethods = [];
        if (options.username && options.password) {
          this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD);
        }
        this.authMethods.push(AUTH_METHODS.NO_AUTH);
        this.socket.on("data", this.onSocketData);
        this.socket.on("error", this.onSocketError);
        this.socket.on("close", this.onSocketClose);
      }
      /**
       * Handle incoming data from the socket
       */
      onData(data) {
        debug("received data", data.length, "bytes in state", this.state);
        this.buffer = Buffer2.concat([this.buffer, data]);
        try {
          switch (this.state) {
            case STATES.HANDSHAKING:
              this.handleHandshakeResponse();
              break;
            case STATES.AUTHENTICATING:
              this.handleAuthResponse();
              break;
            case STATES.CONNECTING:
              this.handleConnectResponse();
              break;
          }
        } catch (err) {
          this.onError(err);
        }
      }
      /**
       * Handle socket errors
       */
      onError(err) {
        debug("socket error", err);
        this.state = STATES.ERROR;
        this.emit("error", err);
        this.destroy();
      }
      /**
       * Handle socket close
       */
      onClose() {
        debug("socket closed");
        this.state = STATES.CLOSED;
        this.emit("close");
      }
      /**
       * Destroy the client and underlying socket
       */
      destroy() {
        if (this.socket && !this.socket.destroyed) {
          this.socket.destroy();
        }
      }
      markAuthenticated() {
        this.state = STATES.AUTHENTICATED;
        this.emit("authenticated");
      }
      /**
       * Start the SOCKS5 handshake
       */
      handshake() {
        if (this.state !== STATES.INITIAL) {
          throw new InvalidArgumentError("Handshake already started");
        }
        debug("starting handshake with", this.authMethods.length, "auth methods");
        this.state = STATES.HANDSHAKING;
        const request = Buffer2.alloc(2 + this.authMethods.length);
        request[0] = SOCKS_VERSION;
        request[1] = this.authMethods.length;
        this.authMethods.forEach((method, i) => {
          request[2 + i] = method;
        });
        this.socket.write(request);
      }
      /**
       * Handle handshake response from server
       */
      handleHandshakeResponse() {
        if (this.buffer.length < 2) {
          return;
        }
        const version = this.buffer[0];
        const method = this.buffer[1];
        if (version !== SOCKS_VERSION) {
          throw new Socks5ProxyError(`Invalid SOCKS version: ${version}`, "UND_ERR_SOCKS5_VERSION");
        }
        if (method === AUTH_METHODS.NO_ACCEPTABLE) {
          throw new Socks5ProxyError("No acceptable authentication method", "UND_ERR_SOCKS5_AUTH_REJECTED");
        }
        this.buffer = this.buffer.subarray(2);
        debug("server selected auth method", method);
        if (method === AUTH_METHODS.NO_AUTH) {
          this.markAuthenticated();
        } else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
          this.state = STATES.AUTHENTICATING;
          this.sendAuthRequest();
        } else {
          throw new Socks5ProxyError(`Unsupported authentication method: ${method}`, "UND_ERR_SOCKS5_AUTH_METHOD");
        }
      }
      /**
       * Send username/password authentication request
       */
      sendAuthRequest() {
        const { username, password } = this.options;
        if (!username || !password) {
          throw new InvalidArgumentError("Username and password required for authentication");
        }
        debug("sending username/password auth");
        const usernameBuffer = Buffer2.from(username);
        const passwordBuffer = Buffer2.from(password);
        if (usernameBuffer.length > 255 || passwordBuffer.length > 255) {
          throw new InvalidArgumentError("Username or password too long");
        }
        const request = Buffer2.alloc(3 + usernameBuffer.length + passwordBuffer.length);
        request[0] = 1;
        request[1] = usernameBuffer.length;
        usernameBuffer.copy(request, 2);
        request[2 + usernameBuffer.length] = passwordBuffer.length;
        passwordBuffer.copy(request, 3 + usernameBuffer.length);
        this.socket.write(request);
      }
      /**
       * Handle authentication response
       */
      handleAuthResponse() {
        if (this.buffer.length < 2) {
          return;
        }
        const version = this.buffer[0];
        const status = this.buffer[1];
        if (version !== 1) {
          throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version}`, "UND_ERR_SOCKS5_AUTH_VERSION");
        }
        if (status !== 0) {
          throw new Socks5ProxyError("Authentication failed", "UND_ERR_SOCKS5_AUTH_FAILED");
        }
        this.buffer = this.buffer.subarray(2);
        debug("authentication successful");
        this.markAuthenticated();
      }
      /**
       * Send CONNECT command
       * @param {string} address - Target address (IP or domain)
       * @param {number} port - Target port
       */
      connect(address, port) {
        if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) {
          throw new InvalidArgumentError("Connection already in progress");
        }
        if (this.state !== STATES.AUTHENTICATED) {
          throw new InvalidArgumentError("Client must be authenticated before CONNECT");
        }
        debug("connecting to", address, port);
        this.state = STATES.CONNECTING;
        const request = this.buildConnectRequest(COMMANDS.CONNECT, address, port);
        this.socket.write(request);
      }
      /**
       * Build a SOCKS5 request
       */
      buildConnectRequest(command, address, port) {
        const { type: addressType, buffer: addressBuffer } = parseAddress(address);
        const request = Buffer2.alloc(4 + addressBuffer.length + 2);
        request[0] = SOCKS_VERSION;
        request[1] = command;
        request[2] = 0;
        request[3] = addressType;
        addressBuffer.copy(request, 4);
        request.writeUInt16BE(port, 4 + addressBuffer.length);
        return request;
      }
      /**
       * Handle CONNECT response
       */
      handleConnectResponse() {
        if (this.buffer.length < 4) {
          return;
        }
        const version = this.buffer[0];
        const reply = this.buffer[1];
        const addressType = this.buffer[3];
        if (version !== SOCKS_VERSION) {
          throw new Socks5ProxyError(`Invalid SOCKS version in reply: ${version}`, "UND_ERR_SOCKS5_REPLY_VERSION");
        }
        let responseLength = 4;
        if (addressType === ADDRESS_TYPES.IPV4) {
          responseLength += 4 + 2;
        } else if (addressType === ADDRESS_TYPES.DOMAIN) {
          if (this.buffer.length < 5) {
            return;
          }
          responseLength += 1 + this.buffer[4] + 2;
        } else if (addressType === ADDRESS_TYPES.IPV6) {
          responseLength += 16 + 2;
        } else {
          throw new Socks5ProxyError(`Invalid address type in reply: ${addressType}`, "UND_ERR_SOCKS5_ADDR_TYPE");
        }
        if (this.buffer.length < responseLength) {
          return;
        }
        if (reply !== REPLY_CODES.SUCCEEDED) {
          const errorMessage = this.getReplyErrorMessage(reply);
          throw new Socks5ProxyError(`SOCKS5 connection failed: ${errorMessage}`, `UND_ERR_SOCKS5_REPLY_${reply}`);
        }
        let boundAddress;
        let offset = 4;
        if (addressType === ADDRESS_TYPES.IPV4) {
          boundAddress = Array.from(this.buffer.subarray(offset, offset + 4)).join(".");
          offset += 4;
        } else if (addressType === ADDRESS_TYPES.DOMAIN) {
          const domainLength = this.buffer[offset];
          offset += 1;
          boundAddress = this.buffer.subarray(offset, offset + domainLength).toString();
          offset += domainLength;
        } else if (addressType === ADDRESS_TYPES.IPV6) {
          const parts = [];
          for (let i = 0; i < 8; i++) {
            const value = this.buffer.readUInt16BE(offset + i * 2);
            parts.push(value.toString(16));
          }
          boundAddress = parts.join(":");
          offset += 16;
        }
        const boundPort = this.buffer.readUInt16BE(offset);
        this.buffer = EMPTY_BUFFER;
        this.state = STATES.CONNECTED;
        this.socket.removeListener("data", this.onSocketData);
        debug("connected, bound address:", boundAddress, "port:", boundPort);
        this.emit("connected", { address: boundAddress, port: boundPort });
      }
      /**
       * Get human-readable error message for reply code
       */
      getReplyErrorMessage(reply) {
        switch (reply) {
          case REPLY_CODES.GENERAL_FAILURE:
            return "General SOCKS server failure";
          case REPLY_CODES.CONNECTION_NOT_ALLOWED:
            return "Connection not allowed by ruleset";
          case REPLY_CODES.NETWORK_UNREACHABLE:
            return "Network unreachable";
          case REPLY_CODES.HOST_UNREACHABLE:
            return "Host unreachable";
          case REPLY_CODES.CONNECTION_REFUSED:
            return "Connection refused";
          case REPLY_CODES.TTL_EXPIRED:
            return "TTL expired";
          case REPLY_CODES.COMMAND_NOT_SUPPORTED:
            return "Command not supported";
          case REPLY_CODES.ADDRESS_TYPE_NOT_SUPPORTED:
            return "Address type not supported";
          default:
            return `Unknown error code: ${reply}`;
        }
      }
    };
    module.exports = {
      Socks5Client,
      AUTH_METHODS,
      COMMANDS,
      ADDRESS_TYPES,
      REPLY_CODES,
      STATES
    };
  }
});

// ../../node_modules/undici/lib/dispatcher/socks5-proxy-agent.js
var require_socks5_proxy_agent = __commonJS({
  "../../node_modules/undici/lib/dispatcher/socks5-proxy-agent.js"(exports, module) {
    "use strict";
    var { URL: URL2 } = __require("url");
    var tls;
    var DispatcherBase = require_dispatcher_base();
    var { InvalidArgumentError } = require_errors();
    var { Socks5Client, STATES } = require_socks5_client();
    var { kDispatch, kClose, kDestroy } = require_symbols();
    var Pool = require_pool();
    var buildConnector = require_connect();
    var { debuglog } = __require("util");
    var debug = debuglog("undici:socks5-proxy");
    var kProxyUrl = /* @__PURE__ */ Symbol("proxy url");
    var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
    var kProxyAuth = /* @__PURE__ */ Symbol("proxy auth");
    var kProxyProtocol = /* @__PURE__ */ Symbol("proxy protocol");
    var kPools = /* @__PURE__ */ Symbol("pools");
    var kConnector = /* @__PURE__ */ Symbol("connector");
    var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
    var experimentalWarningEmitted = false;
    var Socks5ProxyAgent = class extends DispatcherBase {
      constructor(proxyUrl, options = {}) {
        super();
        if (!experimentalWarningEmitted) {
          process.emitWarning(
            "SOCKS5 proxy support is experimental and subject to change",
            "ExperimentalWarning"
          );
          experimentalWarningEmitted = true;
        }
        if (!proxyUrl) {
          throw new InvalidArgumentError("Proxy URL is mandatory");
        }
        const url = typeof proxyUrl === "string" ? new URL2(proxyUrl) : proxyUrl;
        if (url.protocol !== "socks5:" && url.protocol !== "socks:") {
          throw new InvalidArgumentError("Proxy URL must use socks5:// or socks:// protocol");
        }
        this[kProxyUrl] = url;
        this[kProxyHeaders] = options.headers || {};
        this[kProxyProtocol] = options.proxyTls ? "https:" : "http:";
        this[kRequestTls] = options.requestTls;
        this[kProxyAuth] = {
          username: options.username || (url.username ? decodeURIComponent(url.username) : null),
          password: options.password || (url.password ? decodeURIComponent(url.password) : null)
        };
        this[kConnector] = options.connect || buildConnector({
          ...options.proxyTls,
          servername: options.proxyTls?.servername || url.hostname
        });
        this[kPools] = /* @__PURE__ */ new Map();
      }
      /**
       * Create a SOCKS5 connection to the proxy
       */
      async createSocks5Connection(targetHost, targetPort) {
        const proxyHost = this[kProxyUrl].hostname;
        const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
        debug("creating SOCKS5 connection to", proxyHost, proxyPort);
        const socketReady = Promise.withResolvers();
        this[kConnector]({
          hostname: proxyHost,
          host: proxyHost,
          port: proxyPort,
          protocol: this[kProxyProtocol]
        }, (err, socket2) => {
          if (err) {
            socketReady.reject(err);
          } else {
            socketReady.resolve(socket2);
          }
        });
        const socket = await socketReady.promise;
        const socks5Client = new Socks5Client(socket, this[kProxyAuth]);
        socks5Client.on("error", (err) => {
          debug("SOCKS5 error:", err);
          socket.destroy();
        });
        await socks5Client.handshake();
        const authenticationReady = Promise.withResolvers();
        const authenticationTimeout = setTimeout(() => {
          authenticationReady.reject(new Error("SOCKS5 authentication timeout"));
        }, 5e3);
        const onAuthenticated = () => {
          clearTimeout(authenticationTimeout);
          socks5Client.removeListener("error", onAuthenticationError);
          authenticationReady.resolve();
        };
        const onAuthenticationError = (err) => {
          clearTimeout(authenticationTimeout);
          socks5Client.removeListener("authenticated", onAuthenticated);
          authenticationReady.reject(err);
        };
        if (socks5Client.state === STATES.AUTHENTICATED) {
          clearTimeout(authenticationTimeout);
          authenticationReady.resolve();
        } else {
          socks5Client.once("authenticated", onAuthenticated);
          socks5Client.once("error", onAuthenticationError);
        }
        await authenticationReady.promise;
        await socks5Client.connect(targetHost, targetPort);
        const connectionReady = Promise.withResolvers();
        const connectionTimeout = setTimeout(() => {
          connectionReady.reject(new Error("SOCKS5 connection timeout"));
        }, 5e3);
        const onConnected = (info) => {
          debug("SOCKS5 tunnel established to", targetHost, targetPort, "via", info);
          clearTimeout(connectionTimeout);
          socks5Client.removeListener("error", onConnectionError);
          connectionReady.resolve();
        };
        const onConnectionError = (err) => {
          clearTimeout(connectionTimeout);
          socks5Client.removeListener("connected", onConnected);
          connectionReady.reject(err);
        };
        socks5Client.once("connected", onConnected);
        socks5Client.once("error", onConnectionError);
        await connectionReady.promise;
        return socket;
      }
      /**
       * Dispatch a request through the SOCKS5 proxy
       */
      [kDispatch](opts, handler) {
        const { origin } = opts;
        debug("dispatching request to", origin, "via SOCKS5");
        try {
          const originKey = String(origin);
          let pool = this[kPools].get(originKey);
          if (!pool || pool.destroyed || pool.closed) {
            pool = new Pool(origin, {
              pipelining: opts.pipelining,
              connections: opts.connections,
              connect: async (connectOpts, callback) => {
                try {
                  const url = new URL2(origin);
                  const targetHost = url.hostname;
                  const targetPort = parseInt(url.port) || (url.protocol === "https:" ? 443 : 80);
                  debug("establishing SOCKS5 connection to", targetHost, targetPort);
                  const socket = await this.createSocks5Connection(targetHost, targetPort);
                  let finalSocket = socket;
                  if (url.protocol === "https:") {
                    if (!tls) {
                      tls = __require("tls");
                    }
                    debug("upgrading to TLS");
                    finalSocket = tls.connect({
                      ...this[kRequestTls],
                      socket,
                      servername: this[kRequestTls]?.servername || targetHost
                    });
                    const tlsReady = Promise.withResolvers();
                    finalSocket.once("secureConnect", tlsReady.resolve);
                    finalSocket.once("error", tlsReady.reject);
                    await tlsReady.promise;
                  }
                  callback(null, finalSocket);
                } catch (err) {
                  debug("SOCKS5 connection error:", err);
                  callback(err);
                }
              }
            });
            this[kPools].set(originKey, pool);
          }
          return pool[kDispatch](opts, handler);
        } catch (err) {
          debug("dispatch error:", err);
          if (typeof handler.onResponseError === "function") {
            handler.onResponseError(null, err);
            return false;
          } else if (typeof handler.onError === "function") {
            handler.onError(err);
            return false;
          } else {
            throw err;
          }
        }
      }
      async [kClose]() {
        const closePromises = [];
        for (const pool of this[kPools].values()) {
          closePromises.push(pool.close());
        }
        this[kPools].clear();
        await Promise.all(closePromises);
      }
      async [kDestroy](err) {
        const destroyPromises = [];
        for (const pool of this[kPools].values()) {
          destroyPromises.push(pool.destroy(err));
        }
        this[kPools].clear();
        await Promise.all(destroyPromises);
      }
    };
    module.exports = Socks5ProxyAgent;
  }
});

// ../../node_modules/undici/lib/dispatcher/proxy-agent.js
var require_proxy_agent = __commonJS({
  "../../node_modules/undici/lib/dispatcher/proxy-agent.js"(exports, module) {
    "use strict";
    var { kProxy, kClose, kDestroy, kDispatch } = require_symbols();
    var Agent = require_agent();
    var Pool = require_pool();
    var DispatcherBase = require_dispatcher_base();
    var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors();
    var buildConnector = require_connect();
    var Client = require_client();
    var { channels } = require_diagnostics();
    var Socks5ProxyAgent = require_socks5_proxy_agent();
    var kAgent = /* @__PURE__ */ Symbol("proxy agent");
    var kClient = /* @__PURE__ */ Symbol("proxy client");
    var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
    var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
    var kProxyTls = /* @__PURE__ */ Symbol("proxy tls settings");
    var kConnectEndpoint = /* @__PURE__ */ Symbol("connect endpoint function");
    var kConnectEndpointHTTP1 = /* @__PURE__ */ Symbol("connect endpoint function (http/1.1 only)");
    var kTunnelProxy = /* @__PURE__ */ Symbol("tunnel proxy");
    var proxyAuthorization = "proxy-authorization";
    function defaultProtocolPort(protocol) {
      return protocol === "https:" ? 443 : 80;
    }
    function defaultFactory(origin, opts) {
      return new Pool(origin, opts);
    }
    var noop = () => {
    };
    function defaultAgentFactory(origin, opts) {
      if (opts.connections === 1) {
        return new Client(origin, opts);
      }
      return new Pool(origin, opts);
    }
    var Http1ProxyWrapper = class extends DispatcherBase {
      #client;
      constructor(proxyUrl, { headers = {}, connect, factory }) {
        if (!proxyUrl) {
          throw new InvalidArgumentError("Proxy URL is mandatory");
        }
        super();
        this[kProxyHeaders] = headers;
        if (factory) {
          this.#client = factory(proxyUrl, { connect });
        } else {
          this.#client = new Client(proxyUrl, { connect });
        }
      }
      [kDispatch](opts, handler) {
        const onResponseStart = handler.onResponseStart;
        handler.onResponseStart = function(controller, statusCode, data, statusMessage) {
          if (statusCode === 407) {
            if (typeof handler.onResponseError === "function") {
              handler.onResponseError(controller, new InvalidArgumentError("Proxy Authentication Required (407)"));
            }
            return;
          }
          if (onResponseStart) onResponseStart.call(this, controller, statusCode, data, statusMessage);
        };
        const {
          origin,
          path = "/",
          headers = {}
        } = opts;
        opts.path = origin + path;
        if (!("host" in headers) && !("Host" in headers)) {
          const { host } = new URL(origin);
          headers.host = host;
        }
        opts.headers = { ...this[kProxyHeaders], ...headers };
        return this.#client[kDispatch](opts, handler);
      }
      [kClose]() {
        return this.#client.close();
      }
      [kDestroy](err) {
        return this.#client.destroy(err);
      }
    };
    var ProxyAgent = class extends DispatcherBase {
      constructor(opts) {
        if (!opts || typeof opts === "object" && !(opts instanceof URL) && !opts.uri) {
          throw new InvalidArgumentError("Proxy uri is mandatory");
        }
        const { clientFactory = defaultFactory } = opts;
        if (typeof clientFactory !== "function") {
          throw new InvalidArgumentError("Proxy opts.clientFactory must be a function.");
        }
        const { proxyTunnel = true, connectTimeout } = opts;
        super();
        const url = this.#getUrl(opts);
        const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url;
        this[kProxy] = { uri: href, protocol };
        this[kRequestTls] = opts.requestTls;
        this[kProxyTls] = opts.proxyTls;
        this[kProxyHeaders] = opts.headers || {};
        this[kTunnelProxy] = proxyTunnel;
        if (opts.auth && opts.token) {
          throw new InvalidArgumentError("opts.auth cannot be used in combination with opts.token");
        } else if (opts.auth) {
          this[kProxyHeaders]["proxy-authorization"] = `Basic ${opts.auth}`;
        } else if (opts.token) {
          this[kProxyHeaders]["proxy-authorization"] = opts.token;
        } else if (username && password) {
          this[kProxyHeaders]["proxy-authorization"] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString("base64")}`;
        } else if (username) {
          this[kProxyHeaders]["proxy-authorization"] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:`).toString("base64")}`;
        }
        const connect = buildConnector({ timeout: connectTimeout, ...opts.proxyTls });
        this[kConnectEndpoint] = buildConnector({ timeout: connectTimeout, ...opts.requestTls });
        this[kConnectEndpointHTTP1] = buildConnector({ timeout: connectTimeout, ...opts.requestTls, allowH2: false });
        const agentFactory = opts.factory || defaultAgentFactory;
        const factory = (origin2, options) => {
          const { protocol: protocol2 } = new URL(origin2);
          if (this[kProxy].protocol === "socks5:" || this[kProxy].protocol === "socks:") {
            return new Socks5ProxyAgent(this[kProxy].uri, {
              headers: this[kProxyHeaders],
              connect,
              factory: agentFactory,
              username: opts.username || username,
              password: opts.password || password,
              proxyTls: opts.proxyTls,
              requestTls: opts.requestTls
            });
          }
          if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
            return new Http1ProxyWrapper(this[kProxy].uri, {
              headers: this[kProxyHeaders],
              connect,
              factory: agentFactory
            });
          }
          return agentFactory(origin2, options);
        };
        if (protocol === "socks5:" || protocol === "socks:") {
          this[kClient] = null;
        } else {
          this[kClient] = clientFactory(url, { connect });
        }
        this[kAgent] = new Agent({
          ...opts,
          factory,
          connect: async (opts2, callback) => {
            if (!this[kClient]) {
              callback(new InvalidArgumentError("Cannot establish tunnel connection without a proxy client"));
              return;
            }
            let requestedPath = opts2.host;
            if (!opts2.port) {
              requestedPath += `:${defaultProtocolPort(opts2.protocol)}`;
            }
            try {
              const connectParams = {
                origin,
                port,
                path: requestedPath,
                signal: opts2.signal,
                headers: {
                  ...this[kProxyHeaders],
                  host: opts2.host,
                  ...opts2.connections == null || opts2.connections > 0 ? { "proxy-connection": "keep-alive" } : {}
                },
                servername: this[kProxyTls]?.servername || proxyHostname
              };
              const { socket, statusCode } = await this[kClient].connect(connectParams);
              if (statusCode !== 200) {
                socket.on("error", noop).destroy();
                callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`));
                return;
              }
              if (channels.proxyConnected.hasSubscribers) {
                channels.proxyConnected.publish({
                  socket,
                  connectParams
                });
              }
              if (opts2.protocol !== "https:") {
                callback(null, socket);
                return;
              }
              let servername;
              if (this[kRequestTls]) {
                servername = this[kRequestTls].servername;
              } else {
                servername = opts2.servername;
              }
              const connectEndpoint = opts2.allowH2 === false ? this[kConnectEndpointHTTP1] : this[kConnectEndpoint];
              connectEndpoint({ ...opts2, servername, httpSocket: socket }, callback);
            } catch (err) {
              if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
                callback(new SecureProxyConnectionError(err));
              } else {
                callback(err);
              }
            }
          }
        });
      }
      dispatch(opts, handler) {
        const headers = buildHeaders(opts.headers);
        throwIfProxyAuthIsSent(headers);
        if (headers && !("host" in headers) && !("Host" in headers)) {
          const { host } = new URL(opts.origin);
          headers.host = host;
        }
        return this[kAgent].dispatch(
          {
            ...opts,
            headers
          },
          handler
        );
      }
      /**
       * @param {import('../../types/proxy-agent').ProxyAgent.Options | string | URL} opts
       * @returns {URL}
       */
      #getUrl(opts) {
        if (typeof opts === "string") {
          return new URL(opts);
        } else if (opts instanceof URL) {
          return opts;
        } else {
          return new URL(opts.uri);
        }
      }
      [kClose]() {
        const promises = [this[kAgent].close()];
        if (this[kClient]) {
          promises.push(this[kClient].close());
        }
        return Promise.all(promises);
      }
      [kDestroy]() {
        const promises = [this[kAgent].destroy()];
        if (this[kClient]) {
          promises.push(this[kClient].destroy());
        }
        return Promise.all(promises);
      }
    };
    function buildHeaders(headers) {
      if (Array.isArray(headers)) {
        const headersPair = {};
        for (let i = 0; i < headers.length; i += 2) {
          if (isProxyAuthorizationHeader(headers[i])) {
            throwProxyAuthError();
          }
          headersPair[headers[i]] = headers[i + 1];
        }
        return headersPair;
      }
      return headers;
    }
    function throwIfProxyAuthIsSent(headers) {
      for (const key in headers) {
        if (isProxyAuthorizationHeader(key)) {
          throwProxyAuthError();
        }
      }
    }
    function isProxyAuthorizationHeader(key) {
      return key.length === proxyAuthorization.length && key.toLowerCase() === proxyAuthorization;
    }
    function throwProxyAuthError() {
      throw new InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
    }
    module.exports = ProxyAgent;
  }
});

// ../../node_modules/undici/lib/dispatcher/env-http-proxy-agent.js
var require_env_http_proxy_agent = __commonJS({
  "../../node_modules/undici/lib/dispatcher/env-http-proxy-agent.js"(exports, module) {
    "use strict";
    var DispatcherBase = require_dispatcher_base();
    var { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require_symbols();
    var ProxyAgent = require_proxy_agent();
    var Agent = require_agent();
    var DEFAULT_PORTS = {
      "http:": 80,
      "https:": 443
    };
    var EnvHttpProxyAgent = class extends DispatcherBase {
      #noProxyValue = null;
      #noProxyEntries = null;
      #opts = null;
      constructor(opts = {}) {
        super();
        this.#opts = opts;
        const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts;
        this[kNoProxyAgent] = new Agent(agentOpts);
        const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
        if (HTTP_PROXY) {
          this[kHttpProxyAgent] = new ProxyAgent({ ...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 ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY });
        } else {
          this[kHttpsProxyAgent] = this[kHttpProxyAgent];
        }
        this.#parseNoProxy();
      }
      [kDispatch](opts, handler) {
        const url = new URL(opts.origin);
        const agent = this.#getProxyAgentForUrl(url);
        return agent.dispatch(opts, handler);
      }
      [kClose]() {
        return Promise.all([
          this[kNoProxyAgent].close(),
          !this[kHttpProxyAgent][kClosed] && this[kHttpProxyAgent].close(),
          !this[kHttpsProxyAgent][kClosed] && this[kHttpsProxyAgent].close()
        ]);
      }
      [kDestroy](err) {
        return Promise.all([
          this[kNoProxyAgent].destroy(err),
          !this[kHttpProxyAgent][kDestroyed] && this[kHttpProxyAgent].destroy(err),
          !this[kHttpsProxyAgent][kDestroyed] && this[kHttpsProxyAgent].destroy(err)
        ]);
      }
      #getProxyAgentForUrl(url) {
        let { protocol, host: hostname, port } = url;
        hostname = hostname.replace(/:\d*$/, "").toLowerCase();
        port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0;
        if (!this.#shouldProxy(hostname, port)) {
          return this[kNoProxyAgent];
        }
        if (protocol === "https:") {
          return this[kHttpsProxyAgent];
        }
        return this[kHttpProxyAgent];
      }
      #shouldProxy(hostname, port) {
        if (this.#noProxyChanged) {
          this.#parseNoProxy();
        }
        if (this.#noProxyEntries.length === 0) {
          return true;
        }
        if (this.#noProxyValue === "*") {
          return false;
        }
        for (let i = 0; i < this.#noProxyEntries.length; i++) {
          const entry = this.#noProxyEntries[i];
          if (entry.port && entry.port !== port) {
            continue;
          }
          if (hostname === entry.hostname) {
            return false;
          }
          if (hostname.slice(-(entry.hostname.length + 1)) === `.${entry.hostname}`) {
            return false;
          }
        }
        return true;
      }
      #parseNoProxy() {
        const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv;
        const noProxySplit = noProxyValue.split(/[,\s]/);
        const noProxyEntries = [];
        for (let i = 0; i < noProxySplit.length; i++) {
          const entry = noProxySplit[i];
          if (!entry) {
            continue;
          }
          const parsed = entry.match(/^(.+):(\d+)$/);
          noProxyEntries.push({
            // strip leading dot or asterisk with dot
            hostname: (parsed ? parsed[1] : entry).replace(/^\*?\./, "").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 ?? "";
      }
    };
    module.exports = EnvHttpProxyAgent;
  }
});

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

// ../../node_modules/undici/lib/dispatcher/retry-agent.js
var require_retry_agent = __commonJS({
  "../../node_modules/undici/lib/dispatcher/retry-agent.js"(exports, module) {
    "use strict";
    var Dispatcher = require_dispatcher();
    var RetryHandler = require_retry_handler();
    var RetryAgent = class extends Dispatcher {
      #agent = null;
      #options = null;
      constructor(agent, options = {}) {
        super(options);
        this.#agent = agent;
        this.#options = options;
      }
      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();
      }
    };
    module.exports = RetryAgent;
  }
});

// ../../node_modules/undici/lib/dispatcher/h2c-client.js
var require_h2c_client = __commonJS({
  "../../node_modules/undici/lib/dispatcher/h2c-client.js"(exports, module) {
    "use strict";
    var { InvalidArgumentError } = require_errors();
    var Client = require_client();
    var H2CClient = class extends Client {
      constructor(origin, clientOpts) {
        if (typeof origin === "string") {
          origin = new URL(origin);
        }
        if (origin.protocol !== "http:") {
          throw new InvalidArgumentError(
            "h2c-client: Only h2c protocol is supported"
          );
        }
        const { maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
        const defaultMaxConcurrentStreams = maxConcurrentStreams ?? 100;
        let defaultPipelining = 100;
        if (maxConcurrentStreams != null && (!Number.isInteger(maxConcurrentStreams) || maxConcurrentStreams < 1)) {
          throw new InvalidArgumentError("maxConcurrentStreams must be a positive integer, greater than 0");
        }
        if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) {
          defaultPipelining = pipelining;
        }
        if (defaultPipelining > defaultMaxConcurrentStreams) {
          throw new InvalidArgumentError(
            "h2c-client: pipelining cannot be greater than maxConcurrentStreams"
          );
        }
        super(origin, {
          ...opts,
          maxConcurrentStreams: defaultMaxConcurrentStreams,
          pipelining: defaultPipelining,
          allowH2: true,
          useH2c: true
        });
      }
    };
    module.exports = H2CClient;
  }
});

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

// ../../node_modules/undici/lib/api/api-request.js
var require_api_request = __commonJS({
  "../../node_modules/undici/lib/api/api-request.js"(exports, module) {
    "use strict";
    var assert = __require("assert");
    var { AsyncResource } = __require("async_hooks");
    var { Readable } = require_readable();
    var { InvalidArgumentError, RequestAbortedError } = require_errors();
    var util = require_util();
    function noop() {
    }
    var RequestHandler = class extends AsyncResource {
      constructor(opts, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts;
        try {
          if (typeof callback !== "function") {
            throw new InvalidArgumentError("invalid callback");
          }
          if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) {
            throw new InvalidArgumentError("invalid highWaterMark");
          }
          if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
            throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
          }
          if (method === "CONNECT") {
            throw new InvalidArgumentError("invalid method");
          }
          if (onInfo && typeof onInfo !== "function") {
            throw new InvalidArgumentError("invalid onInfo callback");
          }
          super("UNDICI_REQUEST");
        } catch (err) {
          if (util.isStream(body)) {
            util.destroy(body.on("error", noop), err);
          }
          throw err;
        }
        this.method = method;
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.callback = callback;
        this.res = null;
        this.abort = null;
        this.body = body;
        this.trailers = {};
        this.context = null;
        this.controller = null;
        this.onInfo = onInfo || null;
        this.highWaterMark = highWaterMark;
        this.reason = null;
        this.removeAbortListener = null;
        if (signal?.aborted) {
          this.reason = signal.reason ?? new RequestAbortedError();
        } else if (signal) {
          this.removeAbortListener = util.addAbortListener(signal, () => {
            this.reason = signal.reason ?? new RequestAbortedError();
            if (this.res) {
              util.destroy(this.res.on("error", noop), this.reason);
            } else if (this.abort) {
              this.abort(this.reason);
            }
          });
        }
      }
      onRequestStart(controller, context) {
        if (this.reason) {
          controller.abort(this.reason);
          return;
        }
        assert(this.callback);
        this.controller = controller;
        this.abort = (reason) => controller.abort(reason);
        this.context = context;
      }
      onResponseStart(controller, statusCode, headers, statusText) {
        const { callback, opaque, context, responseHeaders, highWaterMark } = this;
        const rawHeaders = controller?.rawHeaders;
        const responseHeaderData = responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : headers;
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers: responseHeaderData });
          }
          return;
        }
        const parsedHeaders = headers;
        const contentType = parsedHeaders?.["content-type"];
        const contentLength = parsedHeaders?.["content-length"];
        const res = new Readable({
          resume: () => controller.resume(),
          abort: (reason) => controller.abort(reason),
          contentType,
          contentLength: this.method !== "HEAD" && contentLength ? Number(contentLength) : null,
          highWaterMark
        });
        if (this.removeAbortListener) {
          res.on("close", this.removeAbortListener);
          this.removeAbortListener = null;
        }
        this.callback = null;
        this.res = res;
        if (callback !== null) {
          try {
            this.runInAsyncScope(callback, null, null, {
              statusCode,
              statusText,
              headers: responseHeaderData,
              trailers: this.trailers,
              opaque,
              body: res,
              context
            });
          } catch (err) {
            this.res = null;
            util.destroy(res.on("error", noop), err);
            queueMicrotask(() => {
              throw err;
            });
          }
        }
      }
      onResponseData(controller, chunk) {
        if (!this.res) {
          return;
        }
        if (this.res.push(chunk) === false) {
          controller.pause();
        }
      }
      onResponseEnd(_controller, trailers) {
        if (trailers && typeof trailers === "object") {
          for (const key of Object.keys(trailers)) {
            if (key === "__proto__") {
              Object.defineProperty(this.trailers, key, {
                value: trailers[key],
                enumerable: true,
                configurable: true,
                writable: true
              });
            } else {
              this.trailers[key] = trailers[key];
            }
          }
        }
        this.res?.push(null);
      }
      onResponseError(_controller, err) {
        const { res, callback, body, opaque } = this;
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
        if (res) {
          this.res = null;
          queueMicrotask(() => {
            util.destroy(res.on("error", noop), err);
          });
        }
        if (body) {
          this.body = null;
          if (util.isStream(body)) {
            body.on("error", noop);
            util.destroy(body, err);
          }
        }
        if (this.removeAbortListener) {
          this.removeAbortListener();
          this.removeAbortListener = null;
        }
      }
    };
    function request(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve, reject) => {
          request.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve(data);
          });
        });
      }
      try {
        const handler = new RequestHandler(opts, callback);
        this.dispatch(opts, handler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    module.exports = request;
    module.exports.RequestHandler = RequestHandler;
  }
});

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

// ../../node_modules/undici/lib/api/api-stream.js
var require_api_stream = __commonJS({
  "../../node_modules/undici/lib/api/api-stream.js"(exports, module) {
    "use strict";
    var assert = __require("assert");
    var { AsyncResource } = __require("async_hooks");
    var { InvalidArgumentError, InvalidReturnValueError } = require_errors();
    var util = require_util();
    var { addSignal, removeSignal } = require_abort_signal();
    function noop() {
    }
    function getWritableError(stream2) {
      return stream2.errored ?? stream2.writableErrored ?? stream2._writableState?.errored;
    }
    function createPrematureCloseError() {
      const err = new Error("Premature close");
      err.code = "ERR_STREAM_PREMATURE_CLOSE";
      return err;
    }
    function trackWritableLifecycle(stream2, callback) {
      let done = false;
      const cleanup = () => {
        stream2.removeListener("close", onClose);
        stream2.removeListener("error", onError);
        stream2.removeListener("finish", onFinish);
      };
      const finish = (err, fromErrorEvent = false) => {
        if (done) {
          return;
        }
        done = true;
        cleanup();
        callback(err, fromErrorEvent);
      };
      const onClose = () => {
        const err = getWritableError(stream2);
        finish(err ?? (!stream2.writableFinished ? createPrematureCloseError() : void 0));
      };
      const onError = (err) => finish(err, true);
      const onFinish = () => finish();
      stream2.on("close", onClose);
      stream2.on("error", onError);
      stream2.on("finish", onFinish);
      if (stream2.closed) {
        process.nextTick(onClose);
      } else if (stream2.writableFinished) {
        process.nextTick(onFinish);
      }
    }
    var StreamHandler = class extends AsyncResource {
      constructor(opts, factory, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        const { signal, method, opaque, body, onInfo, responseHeaders } = opts;
        try {
          if (typeof callback !== "function") {
            throw new InvalidArgumentError("invalid callback");
          }
          if (typeof factory !== "function") {
            throw new InvalidArgumentError("invalid factory");
          }
          if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
            throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
          }
          if (method === "CONNECT") {
            throw new InvalidArgumentError("invalid method");
          }
          if (onInfo && typeof onInfo !== "function") {
            throw new InvalidArgumentError("invalid onInfo callback");
          }
          super("UNDICI_STREAM");
        } catch (err) {
          if (util.isStream(body)) {
            util.destroy(body.on("error", noop), err);
          }
          throw err;
        }
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.factory = factory;
        this.callback = callback;
        this.res = null;
        this.abort = null;
        this.context = null;
        this.controller = null;
        this.trailers = null;
        this.body = body;
        this.onInfo = onInfo || null;
        if (util.isStream(body)) {
          body.on("error", (err) => {
            this.onResponseError(this.controller, err);
          });
        }
        addSignal(this, signal);
      }
      onRequestStart(controller, context) {
        if (this.reason) {
          controller.abort(this.reason);
          return;
        }
        assert(this.callback);
        this.controller = controller;
        this.abort = (reason) => controller.abort(reason);
        this.context = context;
      }
      onResponseStart(controller, statusCode, headers, _statusMessage) {
        const { factory, opaque, context, responseHeaders } = this;
        const rawHeaders = controller?.rawHeaders;
        const responseHeaderData = responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : headers;
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers: responseHeaderData });
          }
          return;
        }
        this.factory = null;
        if (factory === null) {
          return;
        }
        const res = this.runInAsyncScope(factory, null, {
          statusCode,
          headers: responseHeaderData,
          opaque,
          context
        });
        if (!res || typeof res.write !== "function" || typeof res.end !== "function" || typeof res.on !== "function") {
          throw new InvalidReturnValueError("expected Writable");
        }
        trackWritableLifecycle(res, (err, fromErrorEvent) => {
          const { callback, res: res2, opaque: opaque2, trailers, abort } = this;
          this.res = null;
          if (err || !res2?.readable) {
            util.destroy(res2, fromErrorEvent ? void 0 : err);
          }
          this.callback = null;
          this.runInAsyncScope(callback, null, err || null, { opaque: opaque2, trailers });
          if (err) {
            abort(err);
          }
        });
        res.on("drain", () => controller.resume());
        this.res = res;
        const needDrain = res.writableNeedDrain !== void 0 ? res.writableNeedDrain : res._writableState?.needDrain;
        if (needDrain === true) {
          controller.pause();
        }
      }
      onResponseData(controller, chunk) {
        const { res } = this;
        if (!res) {
          return;
        }
        if (res.write(chunk) === false) {
          controller.pause();
        }
      }
      onResponseEnd(_controller, trailers) {
        const { res } = this;
        removeSignal(this);
        if (!res) {
          return;
        }
        if (trailers && typeof trailers === "object") {
          this.trailers = trailers;
        }
        res.end();
      }
      onResponseError(_controller, err) {
        const { res, callback, opaque, body } = this;
        removeSignal(this);
        this.factory = null;
        if (res) {
          this.res = null;
          util.destroy(res, err);
        } else if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
        if (body) {
          this.body = null;
          util.destroy(body, err);
        }
      }
    };
    function stream(opts, factory, callback) {
      if (callback === void 0) {
        return new Promise((resolve, reject) => {
          stream.call(this, opts, factory, (err, data) => {
            return err ? reject(err) : resolve(data);
          });
        });
      }
      try {
        const handler = new StreamHandler(opts, factory, callback);
        this.dispatch(opts, handler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    module.exports = stream;
  }
});

// ../../node_modules/undici/lib/api/api-pipeline.js
var require_api_pipeline = __commonJS({
  "../../node_modules/undici/lib/api/api-pipeline.js"(exports, module) {
    "use strict";
    var {
      Readable,
      Duplex,
      PassThrough
    } = __require("stream");
    var assert = __require("assert");
    var { AsyncResource } = __require("async_hooks");
    var {
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError
    } = require_errors();
    var util = require_util();
    var { kBodyUsed } = require_symbols();
    var { addSignal, removeSignal } = require_abort_signal();
    function noop() {
    }
    var kResume = /* @__PURE__ */ Symbol("resume");
    var PipelineRequest = class extends Readable {
      constructor() {
        super({ autoDestroy: true });
        this[kResume] = null;
        this[kBodyUsed] = true;
      }
      _read() {
        const { [kResume]: resume } = this;
        if (resume) {
          this[kResume] = null;
          resume();
        }
      }
      _destroy(err, callback) {
        this._read();
        callback(err);
      }
    };
    var PipelineResponse = class extends Readable {
      constructor(resume) {
        super({ autoDestroy: true });
        this[kResume] = resume;
      }
      _read() {
        this[kResume]();
      }
      _destroy(err, callback) {
        if (!err && !this._readableState.endEmitted) {
          err = new RequestAbortedError();
        }
        callback(err);
      }
    };
    var PipelineHandler = class extends AsyncResource {
      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", noop);
        this.ret = new Duplex({
          readableObjectMode: opts.objectMode,
          autoDestroy: true,
          read: () => {
            const { body } = this;
            if (body?.resume) {
              body.resume();
            }
          },
          write: (chunk, encoding, callback) => {
            const { req } = this;
            if (req.push(chunk, encoding) || req._readableState.destroyed) {
              callback();
            } else {
              req[kResume] = callback;
            }
          },
          destroy: (err, callback) => {
            const { body, req, res, ret, abort } = this;
            if (!err && !ret._readableState.endEmitted) {
              err = new RequestAbortedError();
            }
            if (abort && err) {
              abort();
            }
            util.destroy(body, err);
            util.destroy(req, err);
            util.destroy(res, err);
            removeSignal(this);
            callback(err);
          }
        }).on("prefinish", () => {
          const { req } = this;
          req.push(null);
        });
        this.res = null;
        addSignal(this, signal);
      }
      onRequestStart(controller, context) {
        const { res } = this;
        if (this.reason) {
          controller.abort(this.reason);
          return;
        }
        assert(!res, "pipeline cannot be retried");
        this.abort = (reason) => controller.abort(reason);
        this.context = context;
      }
      onResponseStart(controller, statusCode, headers, _statusMessage) {
        const { opaque, handler, context } = this;
        if (statusCode < 200) {
          if (this.onInfo) {
            const rawHeaders = controller?.rawHeaders;
            const responseHeaders = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : headers;
            this.onInfo({ statusCode, headers: responseHeaders });
          }
          return;
        }
        this.res = new PipelineResponse(() => controller.resume());
        let body;
        try {
          this.handler = null;
          const rawHeaders = controller?.rawHeaders;
          const responseHeaders = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : headers;
          body = this.runInAsyncScope(handler, null, {
            statusCode,
            headers: responseHeaders,
            opaque,
            body: this.res,
            context
          });
        } catch (err) {
          this.res.on("error", noop);
          throw err;
        }
        if (!body || typeof body.on !== "function") {
          throw new InvalidReturnValueError("expected Readable");
        }
        body.on("data", (chunk) => {
          const { ret, body: body2 } = this;
          if (!ret.push(chunk) && body2.pause) {
            body2.pause();
          }
        }).on("error", (err) => {
          const { ret } = this;
          util.destroy(ret, err);
        }).on("end", () => {
          const { ret } = this;
          ret.push(null);
        }).on("close", () => {
          const { ret } = this;
          if (!ret._readableState.ended) {
            util.destroy(ret, new RequestAbortedError());
          }
        });
        this.body = body;
      }
      onResponseData(controller, chunk) {
        const { res } = this;
        if (res.push(chunk) === false) {
          controller.pause();
        }
      }
      onResponseEnd(_controller, _trailers) {
        const { res } = this;
        res.push(null);
      }
      onResponseError(_controller, err) {
        const { ret } = this;
        this.handler = null;
        util.destroy(ret, err);
      }
    };
    function pipeline(opts, handler) {
      try {
        const pipelineHandler = new PipelineHandler(opts, handler);
        this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
        return pipelineHandler.ret;
      } catch (err) {
        return new PassThrough().destroy(err);
      }
    }
    module.exports = pipeline;
  }
});

// ../../node_modules/undici/lib/api/api-upgrade.js
var require_api_upgrade = __commonJS({
  "../../node_modules/undici/lib/api/api-upgrade.js"(exports, module) {
    "use strict";
    var { InvalidArgumentError, SocketError } = require_errors();
    var { AsyncResource } = __require("async_hooks");
    var assert = __require("assert");
    var util = require_util();
    var { kHTTP2Stream } = require_symbols();
    var { addSignal, removeSignal } = require_abort_signal();
    var UpgradeHandler = class extends AsyncResource {
      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);
      }
      onRequestStart(controller, context) {
        if (this.reason) {
          controller.abort(this.reason);
          return;
        }
        assert(this.callback);
        this.abort = (reason) => controller.abort(reason);
        this.context = context;
      }
      onResponseStart() {
        throw new SocketError("bad upgrade", null);
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        const expectedStatusCode = socket[kHTTP2Stream] === true ? 200 : 101;
        if (statusCode !== expectedStatusCode) {
          const socketInfo = socket[kHTTP2Stream] === true ? null : util.getSocketInfo(socket);
          controller.abort(new SocketError("bad upgrade", socketInfo));
          return;
        }
        const { callback, opaque, context } = this;
        removeSignal(this);
        this.callback = null;
        const rawHeaders = controller?.rawHeaders;
        const responseHeaders = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : headers;
        this.runInAsyncScope(callback, null, null, {
          headers: responseHeaders,
          socket,
          opaque,
          context
        });
      }
      onResponseError(_controller, err) {
        const { callback, opaque } = this;
        removeSignal(this);
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
      }
    };
    function upgrade(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve, reject) => {
          upgrade.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve(data);
          });
        });
      }
      try {
        const upgradeHandler = new UpgradeHandler(opts, callback);
        const upgradeOpts = {
          ...opts,
          method: opts.method || "GET",
          upgrade: opts.protocol || "Websocket"
        };
        this.dispatch(upgradeOpts, upgradeHandler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    module.exports = upgrade;
  }
});

// ../../node_modules/undici/lib/api/api-connect.js
var require_api_connect = __commonJS({
  "../../node_modules/undici/lib/api/api-connect.js"(exports, module) {
    "use strict";
    var assert = __require("assert");
    var { AsyncResource } = __require("async_hooks");
    var { InvalidArgumentError, SocketError } = require_errors();
    var util = require_util();
    var { addSignal, removeSignal } = require_abort_signal();
    var ConnectHandler = class extends AsyncResource {
      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);
      }
      onRequestStart(controller, context) {
        if (this.reason) {
          controller.abort(this.reason);
          return;
        }
        assert(this.callback);
        this.abort = (reason) => controller.abort(reason);
        this.context = context;
      }
      onResponseStart() {
        throw new SocketError("bad connect", null);
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        const { callback, opaque, context } = this;
        removeSignal(this);
        this.callback = null;
        let responseHeaders = headers;
        const rawHeaders = controller?.rawHeaders;
        if (responseHeaders != null) {
          responseHeaders = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : headers;
        }
        this.runInAsyncScope(callback, null, null, {
          statusCode,
          headers: responseHeaders,
          socket,
          opaque,
          context
        });
      }
      onResponseError(_controller, err) {
        const { callback, opaque } = this;
        removeSignal(this);
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
      }
    };
    function connect(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve, reject) => {
          connect.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve(data);
          });
        });
      }
      try {
        const connectHandler = new ConnectHandler(opts, callback);
        const connectOptions = { ...opts, method: "CONNECT" };
        this.dispatch(connectOptions, connectHandler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    module.exports = connect;
  }
});

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

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

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

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

// ../../node_modules/undici/lib/mock/mock-interceptor.js
var require_mock_interceptor = __commonJS({
  "../../node_modules/undici/lib/mock/mock-interceptor.js"(exports, module) {
    "use strict";
    var { getResponseData, buildKey, addMockDispatch } = require_mock_utils();
    var {
      kDispatches,
      kDispatchKey,
      kDefaultHeaders,
      kDefaultTrailers,
      kContentLength,
      kMockDispatch,
      kIgnoreTrailingSlash
    } = require_mock_symbols();
    var { InvalidArgumentError } = require_errors();
    var { serializePathWithQuery } = require_util();
    var MockScope = class {
      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 {
      constructor(opts, mockDispatches) {
        if (typeof opts !== "object") {
          throw new InvalidArgumentError("opts must be an object");
        }
        if (typeof opts.path === "undefined") {
          throw new InvalidArgumentError("opts.path must be defined");
        }
        if (typeof opts.method === "undefined") {
          opts.method = "GET";
        }
        if (typeof opts.path === "string") {
          if (opts.query) {
            opts.path = serializePathWithQuery(opts.path, opts.query);
          } else {
            const parsedURL = new URL(opts.path, "data://");
            opts.path = parsedURL.pathname + parsedURL.search;
          }
        }
        if (typeof opts.method === "string") {
          opts.method = opts.method.toUpperCase();
        }
        this[kDispatchKey] = buildKey(opts);
        this[kDispatches] = mockDispatches;
        this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
        this[kDefaultHeaders] = {};
        this[kDefaultTrailers] = {};
        this[kContentLength] = false;
      }
      createMockScopeDispatchData({ statusCode, data, responseOptions }) {
        const responseData = getResponseData(data);
        const contentLength = this[kContentLength] ? { "content-length": responseData.length } : {};
        const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers };
        const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers };
        return { statusCode, data, headers, trailers };
      }
      validateReplyParameters(replyParameters) {
        if (typeof replyParameters.statusCode === "undefined") {
          throw new InvalidArgumentError("statusCode must be defined");
        }
        if (typeof replyParameters.responseOptions !== "object" || replyParameters.responseOptions === null) {
          throw new InvalidArgumentError("responseOptions must be an object");
        }
      }
      /**
       * Mock an undici request with a defined reply.
       */
      reply(replyOptionsCallbackOrStatusCode) {
        if (typeof replyOptionsCallbackOrStatusCode === "function") {
          const wrappedDefaultsCallback = (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)
            };
          };
          const newMockDispatch2 = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
          return new MockScope(newMockDispatch2);
        }
        const replyParameters = {
          statusCode: replyOptionsCallbackOrStatusCode,
          data: arguments[1] === void 0 ? "" : arguments[1],
          responseOptions: arguments[2] === void 0 ? {} : arguments[2]
        };
        this.validateReplyParameters(replyParameters);
        const dispatchData = this.createMockScopeDispatchData(replyParameters);
        const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
        return new MockScope(newMockDispatch);
      }
      /**
       * Mock an undici request with a defined error.
       */
      replyWithError(error) {
        if (typeof error === "undefined") {
          throw new InvalidArgumentError("error must be defined");
        }
        const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
        return new MockScope(newMockDispatch);
      }
      /**
       * Set default reply headers on the interceptor for subsequent replies
       */
      defaultReplyHeaders(headers) {
        if (typeof headers === "undefined") {
          throw new InvalidArgumentError("headers must be defined");
        }
        this[kDefaultHeaders] = headers;
        return this;
      }
      /**
       * Set default reply trailers on the interceptor for subsequent replies
       */
      defaultReplyTrailers(trailers) {
        if (typeof trailers === "undefined") {
          throw new InvalidArgumentError("trailers must be defined");
        }
        this[kDefaultTrailers] = trailers;
        return this;
      }
      /**
       * Set reply content length header for replies on the interceptor
       */
      replyContentLength() {
        this[kContentLength] = true;
        return this;
      }
    };
    module.exports.MockInterceptor = MockInterceptor;
    module.exports.MockScope = MockScope;
  }
});

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

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

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

// ../../node_modules/undici/lib/mock/pending-interceptors-formatter.js
var require_pending_interceptors_formatter = __commonJS({
  "../../node_modules/undici/lib/mock/pending-interceptors-formatter.js"(exports, module) {
    "use strict";
    var { Transform } = __require("stream");
    var { Console } = __require("console");
    var PERSISTENT = process.versions.icu ? "\u2705" : "Y ";
    var NOT_PERSISTENT = process.versions.icu ? "\u274C" : "N ";
    module.exports = class PendingInterceptorsFormatter {
      constructor({ disableColors } = {}) {
        this.transform = new Transform({
          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, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
            Method: method,
            Origin: origin,
            Path: path,
            "Status code": statusCode,
            Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
            Invocations: timesInvoked,
            Remaining: persist ? Infinity : times - timesInvoked
          })
        );
        this.logger.table(withPrettyHeaders);
        return this.transform.read().toString();
      }
    };
  }
});

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

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

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

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

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

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

// ../../node_modules/undici/lib/global.js
var require_global2 = __commonJS({
  "../../node_modules/undici/lib/global.js"(exports, module) {
    "use strict";
    var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.2");
    var legacyGlobalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
    var { InvalidArgumentError } = require_errors();
    var Agent = require_agent();
    var Dispatcher1Wrapper = require_dispatcher1_wrapper();
    if (getGlobalDispatcher() === void 0) {
      setGlobalDispatcher(new Agent());
    }
    function setGlobalDispatcher(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
      });
      const legacyAgent = agent instanceof Dispatcher1Wrapper ? agent : new Dispatcher1Wrapper(agent);
      Object.defineProperty(globalThis, legacyGlobalDispatcher, {
        value: legacyAgent,
        writable: true,
        enumerable: false,
        configurable: false
      });
    }
    function getGlobalDispatcher() {
      return globalThis[globalDispatcher];
    }
    var installedExports = (
      /** @type {const} */
      [
        "fetch",
        "Headers",
        "Response",
        "Request",
        "FormData",
        "WebSocket",
        "CloseEvent",
        "ErrorEvent",
        "MessageEvent",
        "EventSource"
      ]
    );
    module.exports = {
      setGlobalDispatcher,
      getGlobalDispatcher,
      installedExports
    };
  }
});

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

// ../../node_modules/undici/lib/handler/redirect-handler.js
var require_redirect_handler = __commonJS({
  "../../node_modules/undici/lib/handler/redirect-handler.js"(exports, module) {
    "use strict";
    var util = require_util();
    var assert = __require("assert");
    var { InvalidArgumentError } = require_errors();
    var redirectableStatusCodes = [300, 301, 302, 303, 307, 308];
    var noop = () => {
    };
    var RedirectHandler = class _RedirectHandler {
      static buildDispatch(dispatcher, maxRedirections) {
        if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        const dispatch = dispatcher.dispatch.bind(dispatcher);
        return (opts, originalHandler) => dispatch(opts, new _RedirectHandler(dispatch, maxRedirections, opts, originalHandler));
      }
      constructor(dispatch, maxRedirections, opts, handler) {
        if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        if (opts.throwOnMaxRedirect != null && typeof opts.throwOnMaxRedirect !== "boolean") {
          throw new InvalidArgumentError("throwOnMaxRedirect must be a boolean");
        }
        this.dispatch = dispatch;
        this.location = null;
        const { maxRedirections: _, stripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect, ...cleanOpts } = opts;
        this.opts = cleanOpts;
        this.opts.body = util.wrapRequestBody(this.opts.body);
        this.stripHeadersOnRedirect = normalizeStripHeaders(stripHeadersOnRedirect, "stripHeadersOnRedirect");
        this.stripHeadersOnCrossOriginRedirect = normalizeStripHeaders(stripHeadersOnCrossOriginRedirect, "stripHeadersOnCrossOriginRedirect");
        this.maxRedirections = maxRedirections;
        this.handler = handler;
        this.history = [];
      }
      onRequestStart(controller, context) {
        this.handler.onRequestStart?.(controller, { ...context, history: this.history });
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
          throw new Error("max redirects");
        }
        if ((statusCode === 301 || statusCode === 302) && this.opts.method === "POST") {
          this.opts.method = "GET";
          if (util.isStream(this.opts.body)) {
            util.destroy(this.opts.body.on("error", noop));
          }
          this.opts.body = null;
        }
        if (statusCode === 303 && this.opts.method !== "HEAD") {
          this.opts.method = "GET";
          if (util.isStream(this.opts.body)) {
            util.destroy(this.opts.body.on("error", noop));
          }
          this.opts.body = null;
        }
        this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1 ? null : headers.location;
        if (this.opts.origin) {
          this.history.push(new URL(this.opts.path, this.opts.origin));
        }
        if (!this.location) {
          this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
          return;
        }
        const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
        const path = search ? `${pathname}${search}` : pathname;
        const redirectUrlString = `${origin}${path}`;
        for (const historyUrl of this.history) {
          if (historyUrl.toString() === redirectUrlString) {
            throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
          }
        }
        this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin, this.stripHeadersOnRedirect, this.stripHeadersOnCrossOriginRedirect);
        this.opts.path = path;
        this.opts.origin = origin;
        this.opts.query = null;
      }
      onResponseData(controller, chunk) {
        if (this.location) {
        } else {
          this.handler.onResponseData?.(controller, chunk);
        }
      }
      onResponseEnd(controller, trailers) {
        if (this.location) {
          this.dispatch(this.opts, this);
        } else {
          this.handler.onResponseEnd(controller, trailers);
        }
      }
      onResponseError(controller, error) {
        this.handler.onResponseError?.(controller, error);
      }
    };
    function shouldRemoveHeader(header, removeContent, unknownOrigin, stripHeaders, stripHeadersOnCrossOrigin) {
      const name = util.headerNameToString(header);
      if (name === "host") {
        return true;
      }
      if (stripHeaders?.has(name) || unknownOrigin && stripHeadersOnCrossOrigin?.has(name)) {
        return true;
      }
      if (removeContent && name.startsWith("content-")) {
        return true;
      }
      if (unknownOrigin) {
        return name === "authorization" || name === "cookie" || name === "proxy-authorization";
      }
      return false;
    }
    function normalizeStripHeaders(headers, optionName) {
      if (headers == null) {
        return null;
      }
      if (!Array.isArray(headers)) {
        throw new InvalidArgumentError(`${optionName} must be an array`);
      }
      const normalized = /* @__PURE__ */ new Set();
      for (const header of headers) {
        if (typeof header !== "string") {
          throw new InvalidArgumentError(`${optionName} must contain header names`);
        }
        normalized.add(util.headerNameToString(header));
      }
      return normalized;
    }
    function cleanRequestHeaders(headers, removeContent, unknownOrigin, stripHeaders, stripHeadersOnCrossOrigin) {
      const ret = [];
      if (Array.isArray(headers)) {
        for (let i = 0; i < headers.length; i += 2) {
          if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin, stripHeaders, stripHeadersOnCrossOrigin)) {
            ret.push(headers[i], headers[i + 1]);
          }
        }
      } else if (headers && typeof headers === "object") {
        const entries = util.hasSafeIterator(headers) ? headers : Object.entries(headers);
        for (const [key, value] of entries) {
          if (!shouldRemoveHeader(key, removeContent, unknownOrigin, stripHeaders, stripHeadersOnCrossOrigin)) {
            ret.push(key, value);
          }
        }
      } else {
        assert(headers == null, "headers must be an object or an array");
      }
      return ret;
    }
    module.exports = RedirectHandler;
  }
});

// ../../node_modules/undici/lib/interceptor/redirect.js
var require_redirect = __commonJS({
  "../../node_modules/undici/lib/interceptor/redirect.js"(exports, module) {
    "use strict";
    var RedirectHandler = require_redirect_handler();
    function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections, throwOnMaxRedirect: defaultThrowOnMaxRedirect, stripHeadersOnRedirect: defaultStripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect: defaultStripHeadersOnCrossOriginRedirect } = {}) {
      return (dispatch) => {
        return function Intercept(opts, handler) {
          const { maxRedirections = defaultMaxRedirections, throwOnMaxRedirect = defaultThrowOnMaxRedirect, stripHeadersOnRedirect = defaultStripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect = defaultStripHeadersOnCrossOriginRedirect, ...rest } = opts;
          if (maxRedirections == null || maxRedirections === 0) {
            return dispatch(opts, handler);
          }
          const dispatchOpts = { ...rest, throwOnMaxRedirect, stripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect };
          const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler);
          return dispatch(dispatchOpts, redirectHandler);
        };
      };
    }
    module.exports = createRedirectInterceptor;
  }
});

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

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

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

// ../../node_modules/undici/lib/interceptor/dns.js
var require_dns = __commonJS({
  "../../node_modules/undici/lib/interceptor/dns.js"(exports, module) {
    "use strict";
    var { isIP } = __require("net");
    var { lookup } = __require("dns");
    var DecoratorHandler = require_decorator_handler();
    var { InvalidArgumentError, InformationalError } = require_errors();
    var maxInt = Math.pow(2, 31) - 1;
    function hasSafeIterator(headers) {
      const prototype = Object.getPrototypeOf(headers);
      const ownIterator = Object.hasOwn(headers, Symbol.iterator);
      return ownIterator || prototype != null && prototype !== Object.prototype && typeof headers[Symbol.iterator] === "function";
    }
    function isHostHeader(key) {
      return typeof key === "string" && key.toLowerCase() === "host";
    }
    function normalizeHeaders(headers) {
      if (headers == null) {
        return null;
      }
      if (Array.isArray(headers)) {
        if (headers.length === 0 || !Array.isArray(headers[0])) {
          return headers;
        }
        const normalized = [];
        for (const header of headers) {
          if (Array.isArray(header) && header.length === 2) {
            normalized.push(header[0], header[1]);
          } else {
            normalized.push(header);
          }
        }
        return normalized;
      }
      if (typeof headers === "object" && hasSafeIterator(headers)) {
        const normalized = [];
        for (const header of headers) {
          if (Array.isArray(header) && header.length === 2) {
            normalized.push(header[0], header[1]);
          } else {
            normalized.push(header);
          }
        }
        return normalized;
      }
      return headers;
    }
    function hasHostHeader(headers) {
      if (headers == null) {
        return false;
      }
      if (Array.isArray(headers)) {
        if (headers.length === 0) {
          return false;
        }
        for (let i = 0; i < headers.length; i += 2) {
          if (isHostHeader(headers[i])) {
            return true;
          }
        }
        return false;
      }
      if (typeof headers === "object") {
        for (const key in headers) {
          if (isHostHeader(key)) {
            return true;
          }
        }
      }
      return false;
    }
    function withHostHeader(host, headers) {
      const normalizedHeaders = normalizeHeaders(headers);
      if (hasHostHeader(normalizedHeaders)) {
        return normalizedHeaders;
      }
      if (Array.isArray(normalizedHeaders)) {
        return ["host", host, ...normalizedHeaders];
      }
      if (normalizedHeaders && typeof normalizedHeaders === "object") {
        return {
          host,
          ...normalizedHeaders
        };
      }
      return { host };
    }
    var DNSStorage = class {
      #maxItems = 0;
      #records = /* @__PURE__ */ new Map();
      constructor(opts) {
        this.#maxItems = opts.maxItems;
      }
      get size() {
        return this.#records.size;
      }
      get(hostname) {
        return this.#records.get(hostname) ?? null;
      }
      set(hostname, records) {
        this.#records.set(hostname, records);
      }
      delete(hostname) {
        this.#records.delete(hostname);
      }
      // Delegate to storage decide can we do more lookups or not
      full() {
        return this.size >= this.#maxItems;
      }
    };
    var DNSInstance = class {
      #maxTTL = 0;
      #maxItems = 0;
      dualStack = true;
      affinity = null;
      lookup = null;
      pick = null;
      storage = 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;
        this.storage = opts.storage ?? new DNSStorage(opts);
      }
      runLookup(origin, opts, cb) {
        const ips = this.storage.get(origin.hostname);
        if (ips == null && this.storage.full()) {
          cb(null, origin);
          return;
        }
        const newOpts = {
          affinity: this.affinity,
          dualStack: this.dualStack,
          lookup: this.lookup,
          pick: this.pick,
          ...opts.dns,
          maxTTL: this.#maxTTL,
          maxItems: this.#maxItems
        };
        if (ips == null) {
          this.lookup(origin, newOpts, (err, addresses) => {
            if (err || addresses == null || addresses.length === 0) {
              cb(err ?? new InformationalError("No DNS entries found"));
              return;
            }
            this.setRecords(origin, addresses);
            const records = this.storage.get(origin.hostname);
            const ip = this.pick(
              origin,
              records,
              newOpts.affinity
            );
            let port;
            if (typeof ip.port === "number") {
              port = `:${ip.port}`;
            } else if (origin.port !== "") {
              port = `:${origin.port}`;
            } else {
              port = "";
            }
            cb(
              null,
              new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`)
            );
          });
        } else {
          const ip = this.pick(
            origin,
            ips,
            newOpts.affinity
          );
          if (ip == null) {
            this.storage.delete(origin.hostname);
            this.runLookup(origin, opts, cb);
            return;
          }
          let port;
          if (typeof ip.port === "number") {
            port = `:${ip.port}`;
          } else if (origin.port !== "") {
            port = `:${origin.port}`;
          } else {
            port = "";
          }
          cb(
            null,
            new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`)
          );
        }
      }
      #defaultLookup(origin, opts, cb) {
        lookup(
          origin.hostname,
          {
            all: true,
            family: this.dualStack === false ? this.affinity : 0,
            order: "ipv4first"
          },
          (err, addresses) => {
            if (err) {
              return cb(err);
            }
            const results = /* @__PURE__ */ new Map();
            for (const addr of addresses) {
              results.set(`${addr.address}:${addr.family}`, addr);
            }
            cb(null, results.values());
          }
        );
      }
      #defaultPick(origin, hostnameRecords, affinity) {
        let ip = null;
        const { records, offset } = hostnameRecords;
        let family;
        if (this.dualStack) {
          if (affinity == null) {
            if (offset == null || offset === maxInt) {
              hostnameRecords.offset = 0;
              affinity = 4;
            } else {
              hostnameRecords.offset++;
              affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4;
            }
          }
          if (records[affinity] != null && records[affinity].ips.length > 0) {
            family = records[affinity];
          } else {
            family = records[affinity === 4 ? 6 : 4];
          }
        } else {
          family = records[affinity];
        }
        if (family == null || family.ips.length === 0) {
          return ip;
        }
        if (family.offset == null || family.offset === maxInt) {
          family.offset = 0;
        } else {
          family.offset++;
        }
        const position = family.offset % family.ips.length;
        ip = family.ips[position] ?? null;
        if (ip == null) {
          return ip;
        }
        if (Date.now() - ip.timestamp > ip.ttl) {
          family.ips.splice(position, 1);
          return this.pick(origin, hostnameRecords, affinity);
        }
        return ip;
      }
      pickFamily(origin, ipFamily) {
        const records = this.storage.get(origin.hostname)?.records;
        if (!records) {
          return null;
        }
        const family = records[ipFamily];
        if (!family) {
          return null;
        }
        if (family.offset == null || family.offset === maxInt) {
          family.offset = 0;
        } else {
          family.offset++;
        }
        const position = family.offset % family.ips.length;
        const ip = family.ips[position] ?? null;
        if (ip == null) {
          return ip;
        }
        if (Date.now() - ip.timestamp > ip.ttl) {
          family.ips.splice(position, 1);
        }
        return ip;
      }
      setRecords(origin, addresses) {
        const timestamp = Date.now();
        const records = { records: { 4: null, 6: null } };
        let minTTL = this.#maxTTL;
        for (const record of addresses) {
          record.timestamp = timestamp;
          if (typeof record.ttl === "number") {
            record.ttl = Math.min(record.ttl, this.#maxTTL);
            minTTL = Math.min(minTTL, record.ttl);
          } else {
            record.ttl = this.#maxTTL;
          }
          const familyRecords = records.records[record.family] ?? { ips: [] };
          familyRecords.ips.push(record);
          records.records[record.family] = familyRecords;
        }
        this.storage.set(origin.hostname, records, { ttl: minTTL });
      }
      deleteRecords(origin) {
        this.storage.delete(origin.hostname);
      }
      getHandler(meta, opts) {
        return new DNSDispatchHandler(this, meta, opts);
      }
    };
    var DNSDispatchHandler = class extends DecoratorHandler {
      #state = null;
      #opts = null;
      #dispatch = null;
      #origin = null;
      #controller = null;
      #newOrigin = null;
      #firstTry = true;
      constructor(state, { origin, handler, dispatch, newOrigin }, opts) {
        super(handler);
        this.#origin = origin;
        this.#newOrigin = newOrigin;
        this.#opts = { ...opts };
        this.#state = state;
        this.#dispatch = dispatch;
      }
      onResponseError(controller, err) {
        switch (err.code) {
          case "ETIMEDOUT":
          case "ECONNREFUSED": {
            if (this.#state.dualStack) {
              if (!this.#firstTry) {
                super.onResponseError(controller, err);
                return;
              }
              this.#firstTry = false;
              const otherFamily = this.#newOrigin.hostname[0] === "[" ? 4 : 6;
              const ip = this.#state.pickFamily(this.#origin, otherFamily);
              if (ip == null) {
                super.onResponseError(controller, err);
                return;
              }
              let port;
              if (typeof ip.port === "number") {
                port = `:${ip.port}`;
              } else if (this.#origin.port !== "") {
                port = `:${this.#origin.port}`;
              } else {
                port = "";
              }
              const dispatchOpts = {
                ...this.#opts,
                origin: `${this.#origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`,
                headers: withHostHeader(this.#origin.host, this.#opts.headers)
              };
              this.#dispatch(dispatchOpts, this);
              return;
            }
            super.onResponseError(controller, err);
            break;
          }
          case "ENOTFOUND":
            this.#state.deleteRecords(this.#origin);
            super.onResponseError(controller, err);
            break;
          default:
            super.onResponseError(controller, err);
            break;
        }
      }
    };
    module.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");
      }
      if (interceptorOpts?.storage != null && (typeof interceptorOpts?.storage?.get !== "function" || typeof interceptorOpts?.storage?.set !== "function" || typeof interceptorOpts?.storage?.full !== "function" || typeof interceptorOpts?.storage?.delete !== "function")) {
        throw new InvalidArgumentError("Invalid storage. Must be a object with methods: { get, set, full, delete }");
      }
      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,
        storage: interceptorOpts?.storage
      };
      const instance = new DNSInstance(opts);
      return (dispatch) => {
        return function dnsInterceptor(origDispatchOpts, handler) {
          if (origDispatchOpts.origin == null) {
            return dispatch(origDispatchOpts, handler);
          }
          const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
          if (isIP(origin.hostname) !== 0) {
            return dispatch(origDispatchOpts, handler);
          }
          instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
            if (err) {
              return handler.onResponseError(null, err);
            }
            const dispatchOpts = {
              ...origDispatchOpts,
              servername: origin.hostname,
              // For SNI on TLS
              origin: newOrigin.origin,
              headers: withHostHeader(origin.host, origDispatchOpts.headers)
            };
            dispatch(
              dispatchOpts,
              instance.getHandler(
                { origin, dispatch, handler, newOrigin },
                origDispatchOpts
              )
            );
          });
          return true;
        };
      };
    };
  }
});

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

// ../../node_modules/undici/lib/util/date.js
var require_date = __commonJS({
  "../../node_modules/undici/lib/util/date.js"(exports, module) {
    "use strict";
    function parseHttpDate(date) {
      switch (date[3]) {
        case ",":
          return parseImfDate(date);
        case " ":
          return parseAscTimeDate(date);
        default:
          return parseRfc850Date(date);
      }
    }
    function parseImfDate(date) {
      if (date.length !== 29 || date[4] !== " " || date[7] !== " " || date[11] !== " " || date[16] !== " " || date[19] !== ":" || date[22] !== ":" || date[25] !== " " || date[26] !== "G" || date[27] !== "M" || date[28] !== "T") {
        return void 0;
      }
      let weekday = -1;
      if (date[0] === "S" && date[1] === "u" && date[2] === "n") {
        weekday = 0;
      } else if (date[0] === "M" && date[1] === "o" && date[2] === "n") {
        weekday = 1;
      } else if (date[0] === "T" && date[1] === "u" && date[2] === "e") {
        weekday = 2;
      } else if (date[0] === "W" && date[1] === "e" && date[2] === "d") {
        weekday = 3;
      } else if (date[0] === "T" && date[1] === "h" && date[2] === "u") {
        weekday = 4;
      } else if (date[0] === "F" && date[1] === "r" && date[2] === "i") {
        weekday = 5;
      } else if (date[0] === "S" && date[1] === "a" && date[2] === "t") {
        weekday = 6;
      } else {
        return void 0;
      }
      let day = 0;
      if (date[5] === "0") {
        const code = date.charCodeAt(6);
        if (code < 49 || code > 57) {
          return void 0;
        }
        day = code - 48;
      } else {
        const code1 = date.charCodeAt(5);
        if (code1 < 49 || code1 > 51) {
          return void 0;
        }
        const code2 = date.charCodeAt(6);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        day = (code1 - 48) * 10 + (code2 - 48);
      }
      let monthIdx = -1;
      if (date[8] === "J" && date[9] === "a" && date[10] === "n") {
        monthIdx = 0;
      } else if (date[8] === "F" && date[9] === "e" && date[10] === "b") {
        monthIdx = 1;
      } else if (date[8] === "M" && date[9] === "a") {
        if (date[10] === "r") {
          monthIdx = 2;
        } else if (date[10] === "y") {
          monthIdx = 4;
        } else {
          return void 0;
        }
      } else if (date[8] === "J") {
        if (date[9] === "a" && date[10] === "n") {
          monthIdx = 0;
        } else if (date[9] === "u") {
          if (date[10] === "n") {
            monthIdx = 5;
          } else if (date[10] === "l") {
            monthIdx = 6;
          } else {
            return void 0;
          }
        } else {
          return void 0;
        }
      } else if (date[8] === "A") {
        if (date[9] === "p" && date[10] === "r") {
          monthIdx = 3;
        } else if (date[9] === "u" && date[10] === "g") {
          monthIdx = 7;
        } else {
          return void 0;
        }
      } else if (date[8] === "S" && date[9] === "e" && date[10] === "p") {
        monthIdx = 8;
      } else if (date[8] === "O" && date[9] === "c" && date[10] === "t") {
        monthIdx = 9;
      } else if (date[8] === "N" && date[9] === "o" && date[10] === "v") {
        monthIdx = 10;
      } else if (date[8] === "D" && date[9] === "e" && date[10] === "c") {
        monthIdx = 11;
      } else {
        return void 0;
      }
      const yearDigit1 = date.charCodeAt(12);
      if (yearDigit1 < 48 || yearDigit1 > 57) {
        return void 0;
      }
      const yearDigit2 = date.charCodeAt(13);
      if (yearDigit2 < 48 || yearDigit2 > 57) {
        return void 0;
      }
      const yearDigit3 = date.charCodeAt(14);
      if (yearDigit3 < 48 || yearDigit3 > 57) {
        return void 0;
      }
      const yearDigit4 = date.charCodeAt(15);
      if (yearDigit4 < 48 || yearDigit4 > 57) {
        return void 0;
      }
      const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
      let hour = 0;
      if (date[17] === "0") {
        const code = date.charCodeAt(18);
        if (code < 48 || code > 57) {
          return void 0;
        }
        hour = code - 48;
      } else {
        const code1 = date.charCodeAt(17);
        if (code1 < 48 || code1 > 50) {
          return void 0;
        }
        const code2 = date.charCodeAt(18);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        if (code1 === 50 && code2 > 51) {
          return void 0;
        }
        hour = (code1 - 48) * 10 + (code2 - 48);
      }
      let minute = 0;
      if (date[20] === "0") {
        const code = date.charCodeAt(21);
        if (code < 48 || code > 57) {
          return void 0;
        }
        minute = code - 48;
      } else {
        const code1 = date.charCodeAt(20);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(21);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        minute = (code1 - 48) * 10 + (code2 - 48);
      }
      let second = 0;
      if (date[23] === "0") {
        const code = date.charCodeAt(24);
        if (code < 48 || code > 57) {
          return void 0;
        }
        second = code - 48;
      } else {
        const code1 = date.charCodeAt(23);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(24);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        second = (code1 - 48) * 10 + (code2 - 48);
      }
      const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
      return result.getUTCDay() === weekday ? result : void 0;
    }
    function parseAscTimeDate(date) {
      if (date.length !== 24 || date[7] !== " " || date[10] !== " " || date[19] !== " ") {
        return void 0;
      }
      let weekday = -1;
      if (date[0] === "S" && date[1] === "u" && date[2] === "n") {
        weekday = 0;
      } else if (date[0] === "M" && date[1] === "o" && date[2] === "n") {
        weekday = 1;
      } else if (date[0] === "T" && date[1] === "u" && date[2] === "e") {
        weekday = 2;
      } else if (date[0] === "W" && date[1] === "e" && date[2] === "d") {
        weekday = 3;
      } else if (date[0] === "T" && date[1] === "h" && date[2] === "u") {
        weekday = 4;
      } else if (date[0] === "F" && date[1] === "r" && date[2] === "i") {
        weekday = 5;
      } else if (date[0] === "S" && date[1] === "a" && date[2] === "t") {
        weekday = 6;
      } else {
        return void 0;
      }
      let monthIdx = -1;
      if (date[4] === "J" && date[5] === "a" && date[6] === "n") {
        monthIdx = 0;
      } else if (date[4] === "F" && date[5] === "e" && date[6] === "b") {
        monthIdx = 1;
      } else if (date[4] === "M" && date[5] === "a") {
        if (date[6] === "r") {
          monthIdx = 2;
        } else if (date[6] === "y") {
          monthIdx = 4;
        } else {
          return void 0;
        }
      } else if (date[4] === "J") {
        if (date[5] === "a" && date[6] === "n") {
          monthIdx = 0;
        } else if (date[5] === "u") {
          if (date[6] === "n") {
            monthIdx = 5;
          } else if (date[6] === "l") {
            monthIdx = 6;
          } else {
            return void 0;
          }
        } else {
          return void 0;
        }
      } else if (date[4] === "A") {
        if (date[5] === "p" && date[6] === "r") {
          monthIdx = 3;
        } else if (date[5] === "u" && date[6] === "g") {
          monthIdx = 7;
        } else {
          return void 0;
        }
      } else if (date[4] === "S" && date[5] === "e" && date[6] === "p") {
        monthIdx = 8;
      } else if (date[4] === "O" && date[5] === "c" && date[6] === "t") {
        monthIdx = 9;
      } else if (date[4] === "N" && date[5] === "o" && date[6] === "v") {
        monthIdx = 10;
      } else if (date[4] === "D" && date[5] === "e" && date[6] === "c") {
        monthIdx = 11;
      } else {
        return void 0;
      }
      let day = 0;
      if (date[8] === " ") {
        const code = date.charCodeAt(9);
        if (code < 49 || code > 57) {
          return void 0;
        }
        day = code - 48;
      } else {
        const code1 = date.charCodeAt(8);
        if (code1 < 49 || code1 > 51) {
          return void 0;
        }
        const code2 = date.charCodeAt(9);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        day = (code1 - 48) * 10 + (code2 - 48);
      }
      let hour = 0;
      if (date[11] === "0") {
        const code = date.charCodeAt(12);
        if (code < 48 || code > 57) {
          return void 0;
        }
        hour = code - 48;
      } else {
        const code1 = date.charCodeAt(11);
        if (code1 < 48 || code1 > 50) {
          return void 0;
        }
        const code2 = date.charCodeAt(12);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        if (code1 === 50 && code2 > 51) {
          return void 0;
        }
        hour = (code1 - 48) * 10 + (code2 - 48);
      }
      let minute = 0;
      if (date[14] === "0") {
        const code = date.charCodeAt(15);
        if (code < 48 || code > 57) {
          return void 0;
        }
        minute = code - 48;
      } else {
        const code1 = date.charCodeAt(14);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(15);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        minute = (code1 - 48) * 10 + (code2 - 48);
      }
      let second = 0;
      if (date[17] === "0") {
        const code = date.charCodeAt(18);
        if (code < 48 || code > 57) {
          return void 0;
        }
        second = code - 48;
      } else {
        const code1 = date.charCodeAt(17);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(18);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        second = (code1 - 48) * 10 + (code2 - 48);
      }
      const yearDigit1 = date.charCodeAt(20);
      if (yearDigit1 < 48 || yearDigit1 > 57) {
        return void 0;
      }
      const yearDigit2 = date.charCodeAt(21);
      if (yearDigit2 < 48 || yearDigit2 > 57) {
        return void 0;
      }
      const yearDigit3 = date.charCodeAt(22);
      if (yearDigit3 < 48 || yearDigit3 > 57) {
        return void 0;
      }
      const yearDigit4 = date.charCodeAt(23);
      if (yearDigit4 < 48 || yearDigit4 > 57) {
        return void 0;
      }
      const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
      const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
      return result.getUTCDay() === weekday ? result : void 0;
    }
    function parseRfc850Date(date) {
      let commaIndex = -1;
      let weekday = -1;
      if (date[0] === "S") {
        if (date[1] === "u" && date[2] === "n" && date[3] === "d" && date[4] === "a" && date[5] === "y") {
          weekday = 0;
          commaIndex = 6;
        } else if (date[1] === "a" && date[2] === "t" && date[3] === "u" && date[4] === "r" && date[5] === "d" && date[6] === "a" && date[7] === "y") {
          weekday = 6;
          commaIndex = 8;
        }
      } else if (date[0] === "M" && date[1] === "o" && date[2] === "n" && date[3] === "d" && date[4] === "a" && date[5] === "y") {
        weekday = 1;
        commaIndex = 6;
      } else if (date[0] === "T") {
        if (date[1] === "u" && date[2] === "e" && date[3] === "s" && date[4] === "d" && date[5] === "a" && date[6] === "y") {
          weekday = 2;
          commaIndex = 7;
        } else if (date[1] === "h" && date[2] === "u" && date[3] === "r" && date[4] === "s" && date[5] === "d" && date[6] === "a" && date[7] === "y") {
          weekday = 4;
          commaIndex = 8;
        }
      } else if (date[0] === "W" && date[1] === "e" && date[2] === "d" && date[3] === "n" && date[4] === "e" && date[5] === "s" && date[6] === "d" && date[7] === "a" && date[8] === "y") {
        weekday = 3;
        commaIndex = 9;
      } else if (date[0] === "F" && date[1] === "r" && date[2] === "i" && date[3] === "d" && date[4] === "a" && date[5] === "y") {
        weekday = 5;
        commaIndex = 6;
      } else {
        return void 0;
      }
      if (date[commaIndex] !== "," || date.length - commaIndex - 1 !== 23 || date[commaIndex + 1] !== " " || date[commaIndex + 4] !== "-" || date[commaIndex + 8] !== "-" || date[commaIndex + 11] !== " " || date[commaIndex + 14] !== ":" || date[commaIndex + 17] !== ":" || date[commaIndex + 20] !== " " || date[commaIndex + 21] !== "G" || date[commaIndex + 22] !== "M" || date[commaIndex + 23] !== "T") {
        return void 0;
      }
      let day = 0;
      if (date[commaIndex + 2] === "0") {
        const code = date.charCodeAt(commaIndex + 3);
        if (code < 49 || code > 57) {
          return void 0;
        }
        day = code - 48;
      } else {
        const code1 = date.charCodeAt(commaIndex + 2);
        if (code1 < 49 || code1 > 51) {
          return void 0;
        }
        const code2 = date.charCodeAt(commaIndex + 3);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        day = (code1 - 48) * 10 + (code2 - 48);
      }
      let monthIdx = -1;
      if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "n") {
        monthIdx = 0;
      } else if (date[commaIndex + 5] === "F" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "b") {
        monthIdx = 1;
      } else if (date[commaIndex + 5] === "M" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "r") {
        monthIdx = 2;
      } else if (date[commaIndex + 5] === "A" && date[commaIndex + 6] === "p" && date[commaIndex + 7] === "r") {
        monthIdx = 3;
      } else if (date[commaIndex + 5] === "M" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "y") {
        monthIdx = 4;
      } else if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "n") {
        monthIdx = 5;
      } else if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "l") {
        monthIdx = 6;
      } else if (date[commaIndex + 5] === "A" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "g") {
        monthIdx = 7;
      } else if (date[commaIndex + 5] === "S" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "p") {
        monthIdx = 8;
      } else if (date[commaIndex + 5] === "O" && date[commaIndex + 6] === "c" && date[commaIndex + 7] === "t") {
        monthIdx = 9;
      } else if (date[commaIndex + 5] === "N" && date[commaIndex + 6] === "o" && date[commaIndex + 7] === "v") {
        monthIdx = 10;
      } else if (date[commaIndex + 5] === "D" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "c") {
        monthIdx = 11;
      } else {
        return void 0;
      }
      const yearDigit1 = date.charCodeAt(commaIndex + 9);
      if (yearDigit1 < 48 || yearDigit1 > 57) {
        return void 0;
      }
      const yearDigit2 = date.charCodeAt(commaIndex + 10);
      if (yearDigit2 < 48 || yearDigit2 > 57) {
        return void 0;
      }
      let year = (yearDigit1 - 48) * 10 + (yearDigit2 - 48);
      year += year < 70 ? 2e3 : 1900;
      let hour = 0;
      if (date[commaIndex + 12] === "0") {
        const code = date.charCodeAt(commaIndex + 13);
        if (code < 48 || code > 57) {
          return void 0;
        }
        hour = code - 48;
      } else {
        const code1 = date.charCodeAt(commaIndex + 12);
        if (code1 < 48 || code1 > 50) {
          return void 0;
        }
        const code2 = date.charCodeAt(commaIndex + 13);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        if (code1 === 50 && code2 > 51) {
          return void 0;
        }
        hour = (code1 - 48) * 10 + (code2 - 48);
      }
      let minute = 0;
      if (date[commaIndex + 15] === "0") {
        const code = date.charCodeAt(commaIndex + 16);
        if (code < 48 || code > 57) {
          return void 0;
        }
        minute = code - 48;
      } else {
        const code1 = date.charCodeAt(commaIndex + 15);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(commaIndex + 16);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        minute = (code1 - 48) * 10 + (code2 - 48);
      }
      let second = 0;
      if (date[commaIndex + 18] === "0") {
        const code = date.charCodeAt(commaIndex + 19);
        if (code < 48 || code > 57) {
          return void 0;
        }
        second = code - 48;
      } else {
        const code1 = date.charCodeAt(commaIndex + 18);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(commaIndex + 19);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        second = (code1 - 48) * 10 + (code2 - 48);
      }
      const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
      return result.getUTCDay() === weekday ? result : void 0;
    }
    module.exports = {
      parseHttpDate
    };
  }
});

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

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

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

// ../../node_modules/undici/lib/interceptor/cache.js
var require_cache2 = __commonJS({
  "../../node_modules/undici/lib/interceptor/cache.js"(exports, module) {
    "use strict";
    var assert = __require("assert");
    var { Readable } = __require("stream");
    var util = require_util();
    var CacheHandler = require_cache_handler();
    var MemoryCacheStore = require_memory_cache_store();
    var CacheRevalidationHandler = require_cache_revalidation_handler();
    var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache();
    var { AbortError } = require_errors();
    function assertCacheOrigins(origins, name) {
      if (origins === void 0) return;
      if (!Array.isArray(origins)) {
        throw new TypeError(`expected ${name} to be an array or undefined, got ${typeof origins}`);
      }
      for (let i = 0; i < origins.length; i++) {
        const origin = origins[i];
        if (typeof origin !== "string" && !(origin instanceof RegExp)) {
          throw new TypeError(`expected ${name}[${i}] to be a string or RegExp, got ${typeof origin}`);
        }
      }
    }
    var nop = () => {
    };
    function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
      if (cacheControlDirectives?.["no-cache"]) {
        return true;
      }
      if (result.cacheControlDirectives?.["no-cache"] && !Array.isArray(result.cacheControlDirectives["no-cache"])) {
        return true;
      }
      if (headers["if-modified-since"] || headers["if-none-match"]) {
        return true;
      }
      return false;
    }
    function isStale(result, cacheControlDirectives) {
      const now = Date.now();
      if (now > result.staleAt) {
        if (cacheControlDirectives?.["max-stale"]) {
          const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
          return now > gracePeriod;
        }
        return true;
      }
      if (cacheControlDirectives?.["min-fresh"]) {
        const timeLeftTillStale = result.staleAt - now;
        const threshold = cacheControlDirectives["min-fresh"] * 1e3;
        return timeLeftTillStale <= threshold;
      }
      return false;
    }
    function withinStaleWhileRevalidateWindow(result) {
      const staleWhileRevalidate = result.cacheControlDirectives?.["stale-while-revalidate"];
      if (!staleWhileRevalidate) {
        return false;
      }
      const now = Date.now();
      const staleWhileRevalidateExpiry = result.staleAt + staleWhileRevalidate * 1e3;
      return now <= staleWhileRevalidateExpiry;
    }
    function handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl) {
      if (reqCacheControl?.["only-if-cached"]) {
        let aborted = false;
        const controller = {
          paused: false,
          rawHeaders: [],
          rawTrailers: [],
          pause() {
            this.paused = true;
          },
          resume() {
            this.paused = false;
          },
          abort: (reason) => {
            aborted = true;
            handler.onResponseError?.(controller, reason ?? new AbortError());
          }
        };
        try {
          handler.onRequestStart?.(controller, null);
          if (aborted) {
            return;
          }
          handler.onResponseStart?.(controller, 504, {}, "Gateway Timeout");
          if (aborted) {
            return;
          }
          handler.onResponseEnd?.(controller, {});
        } catch (err) {
          if (typeof handler.onResponseError === "function") {
            handler.onResponseError(controller, err);
          }
        }
        return true;
      }
      return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
    }
    function sendCachedValue(handler, opts, result, age, context, isStale2) {
      const stream = util.isStream(result.body) ? result.body : Readable.from(result.body ?? []);
      assert(!stream.destroyed, "stream should not be destroyed");
      assert(!stream.readableDidRead, "stream should not be readableDidRead");
      const controller = {
        rawHeaders: [],
        rawTrailers: [],
        resume() {
          stream.resume();
        },
        pause() {
          stream.pause();
        },
        get paused() {
          return stream.isPaused();
        },
        get aborted() {
          return stream.destroyed;
        },
        get reason() {
          return stream.errored;
        },
        abort(reason) {
          stream.destroy(reason ?? new AbortError());
        }
      };
      stream.on("error", function(err) {
        if (!this.readableEnded) {
          if (typeof handler.onResponseError === "function") {
            handler.onResponseError(controller, err);
          } else {
            throw err;
          }
        }
      }).on("close", function() {
        if (!this.errored) {
          handler.onResponseEnd?.(controller, {});
        }
      });
      handler.onRequestStart?.(controller, context);
      if (stream.destroyed) {
        return;
      }
      const headers = { ...result.headers, age: String(age) };
      if (isStale2) {
        headers.warning = '110 - "response is stale"';
      }
      controller.rawHeaders = util.toRawHeaders(headers);
      handler.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage);
      if (opts.method === "HEAD") {
        stream.destroy();
      } else {
        stream.on("data", function(chunk) {
          handler.onResponseData?.(controller, chunk);
        });
      }
    }
    function handleResult(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl, result) {
      if (!result) {
        return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
      }
      const now = Date.now();
      if (now > result.deleteAt) {
        return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
      }
      const age = Math.round((now - result.cachedAt) / 1e3);
      if (reqCacheControl?.["max-age"] && age >= reqCacheControl["max-age"]) {
        return dispatch(opts, handler);
      }
      const stale = isStale(result, reqCacheControl);
      const revalidate = needsRevalidation(result, reqCacheControl, opts);
      if (stale || revalidate) {
        if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) {
          return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
        }
        if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
          sendCachedValue(handler, opts, result, age, null, true);
          queueMicrotask(() => {
            const headers2 = {
              ...opts.headers,
              "if-modified-since": new Date(result.cachedAt).toUTCString()
            };
            if (result.etag) {
              headers2["if-none-match"] = result.etag;
            }
            if (result.vary) {
              for (const key in result.vary) {
                if (result.vary[key] != null) {
                  headers2[key] = result.vary[key];
                }
              }
            }
            dispatch(
              {
                ...opts,
                headers: headers2
              },
              new CacheHandler(globalOpts, cacheKey, {
                // Silent handler that just updates the cache
                onRequestStart() {
                },
                onRequestUpgrade() {
                },
                onResponseStart() {
                },
                onResponseData() {
                },
                onResponseEnd() {
                },
                onResponseError() {
                }
              })
            );
          });
          return true;
        }
        let withinStaleIfErrorThreshold = false;
        const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
        if (staleIfErrorExpiry) {
          withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
        }
        const headers = {
          ...opts.headers,
          "if-modified-since": new Date(result.cachedAt).toUTCString()
        };
        if (result.etag) {
          headers["if-none-match"] = result.etag;
        }
        if (result.vary) {
          for (const key in result.vary) {
            if (result.vary[key] != null) {
              headers[key] = result.vary[key];
            }
          }
        }
        return dispatch(
          {
            ...opts,
            headers
          },
          new CacheRevalidationHandler(
            (success, context) => {
              if (success) {
                sendCachedValue(handler, opts, result, age, context, stale);
              } else if (util.isStream(result.body)) {
                result.body.on("error", nop).destroy();
              }
            },
            new CacheHandler(globalOpts, cacheKey, handler),
            withinStaleIfErrorThreshold
          )
        );
      }
      if (util.isStream(opts.body)) {
        opts.body.on("error", nop).destroy();
      }
      sendCachedValue(handler, opts, result, age, null, false);
    }
    module.exports = (opts = {}) => {
      const {
        store = new MemoryCacheStore(),
        methods = ["GET"],
        cacheByDefault = void 0,
        type = "shared",
        origins = void 0
      } = opts;
      if (typeof opts !== "object" || opts === null) {
        throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
      }
      assertCacheStore(store, "opts.store");
      assertCacheMethods(methods, "opts.methods");
      assertCacheOrigins(origins, "opts.origins");
      if (typeof cacheByDefault !== "undefined" && typeof cacheByDefault !== "number") {
        throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`);
      }
      if (typeof type !== "undefined" && type !== "shared" && type !== "private") {
        throw new TypeError(`expected opts.type to be shared, private, or undefined, got ${typeof type}`);
      }
      const globalOpts = {
        store,
        methods,
        cacheByDefault,
        type
      };
      const safeMethodsToNotCache = util.safeHTTPMethods.filter((method) => methods.includes(method) === false);
      return (dispatch) => {
        return (opts2, handler) => {
          if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
            return dispatch(opts2, handler);
          }
          if (origins !== void 0) {
            const requestOrigin = opts2.origin.toString().toLowerCase();
            let isAllowed = false;
            for (let i = 0; i < origins.length; i++) {
              const allowed = origins[i];
              if (typeof allowed === "string") {
                if (allowed.toLowerCase() === requestOrigin) {
                  isAllowed = true;
                  break;
                }
              } else if (allowed.test(requestOrigin)) {
                isAllowed = true;
                break;
              }
            }
            if (!isAllowed) {
              return dispatch(opts2, handler);
            }
          }
          opts2 = {
            ...opts2,
            headers: normalizeHeaders(opts2)
          };
          const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
          if (reqCacheControl?.["no-store"]) {
            return dispatch(opts2, handler);
          }
          const cacheKey = makeCacheKey(opts2);
          const result = store.get(cacheKey);
          if (result && typeof result.then === "function") {
            return result.then((result2) => handleResult(
              dispatch,
              globalOpts,
              cacheKey,
              handler,
              opts2,
              reqCacheControl,
              result2
            ));
          } else {
            return handleResult(
              dispatch,
              globalOpts,
              cacheKey,
              handler,
              opts2,
              reqCacheControl,
              result
            );
          }
        };
      };
    };
  }
});

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

// ../../node_modules/undici/lib/handler/deduplication-handler.js
var require_deduplication_handler = __commonJS({
  "../../node_modules/undici/lib/handler/deduplication-handler.js"(exports, module) {
    "use strict";
    var { RequestAbortedError } = require_errors();
    var DEFAULT_MAX_BUFFER_SIZE = 5 * 1024 * 1024;
    var DeduplicationHandler = class {
      /**
       * @type {DispatchHandler}
       */
      #primaryHandler;
      /**
       * @type {WaitingHandler[]}
       */
      #waitingHandlers = [];
      /**
       * @type {number}
       */
      #maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
      /**
       * @type {number}
       */
      #statusCode = 0;
      /**
       * @type {Record<string, string | string[]>}
       */
      #headers = {};
      /**
       * @type {string}
       */
      #statusMessage = "";
      /**
       * @type {boolean}
       */
      #aborted = false;
      /**
       * @type {boolean}
       */
      #responseStarted = false;
      /**
       * @type {boolean}
       */
      #responseDataStarted = false;
      /**
       * @type {boolean}
       */
      #completed = false;
      /**
       * @type {import('../../types/dispatcher.d.ts').default.DispatchController | null}
       */
      #controller = null;
      /**
       * @type {(() => void) | null}
       */
      #onComplete = null;
      /**
       * @param {DispatchHandler} primaryHandler The primary handler
       * @param {() => void} onComplete Callback when request completes
       * @param {number} [maxBufferSize] Maximum paused buffer size per waiting handler
       */
      constructor(primaryHandler, onComplete, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE) {
        this.#primaryHandler = primaryHandler;
        this.#onComplete = onComplete;
        this.#maxBufferSize = maxBufferSize;
      }
      /**
       * Add a waiting handler that will receive response events.
       * Returns false if deduplication can no longer safely attach this handler.
       *
       * @param {DispatchHandler} handler
       * @returns {boolean}
       */
      addWaitingHandler(handler) {
        if (this.#completed || this.#responseDataStarted) {
          return false;
        }
        const waitingHandler = this.#createWaitingHandler(handler);
        const waitingController = waitingHandler.controller;
        try {
          handler.onRequestStart?.(waitingController, null);
          if (waitingController.aborted) {
            waitingHandler.done = true;
            return true;
          }
          if (this.#responseStarted) {
            handler.onResponseStart?.(
              waitingController,
              this.#statusCode,
              this.#headers,
              this.#statusMessage
            );
          }
        } catch {
          waitingHandler.done = true;
          return true;
        }
        if (!waitingController.aborted) {
          this.#waitingHandlers.push(waitingHandler);
        }
        return true;
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {any} context
       */
      onRequestStart(controller, context) {
        this.#controller = controller;
        this.#primaryHandler.onRequestStart?.(controller, context);
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {number} statusCode
       * @param {import('../../types/header.d.ts').IncomingHttpHeaders} headers
       * @param {Socket} socket
       */
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.#primaryHandler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {number} statusCode
       * @param {Record<string, string | string[]>} headers
       * @param {string} statusMessage
       */
      onResponseStart(controller, statusCode, headers, statusMessage) {
        this.#responseStarted = true;
        this.#statusCode = statusCode;
        this.#headers = headers;
        this.#statusMessage = statusMessage;
        this.#primaryHandler.onResponseStart?.(controller, statusCode, headers, statusMessage);
        for (const waitingHandler of this.#waitingHandlers) {
          const { handler, controller: waitingController } = waitingHandler;
          if (waitingHandler.done || waitingController.aborted) {
            waitingHandler.done = true;
            continue;
          }
          try {
            handler.onResponseStart?.(
              waitingController,
              statusCode,
              headers,
              statusMessage
            );
          } catch {
          }
          if (waitingController.aborted) {
            waitingHandler.done = true;
          }
        }
        this.#pruneDoneWaitingHandlers();
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {Buffer} chunk
       */
      onResponseData(controller, chunk) {
        if (this.#aborted || this.#completed) {
          return;
        }
        this.#responseDataStarted = true;
        this.#primaryHandler.onResponseData?.(controller, chunk);
        for (const waitingHandler of this.#waitingHandlers) {
          const { handler, controller: waitingController } = waitingHandler;
          if (waitingHandler.done || waitingController.aborted) {
            waitingHandler.done = true;
            continue;
          }
          if (waitingController.paused) {
            this.#bufferWaitingChunk(waitingHandler, chunk);
            continue;
          }
          try {
            handler.onResponseData?.(waitingController, chunk);
          } catch {
          }
          if (waitingController.aborted) {
            waitingHandler.done = true;
            waitingHandler.bufferedChunks = [];
            waitingHandler.bufferedBytes = 0;
          }
        }
        this.#pruneDoneWaitingHandlers();
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {object} trailers
       */
      onResponseEnd(controller, trailers) {
        if (this.#aborted || this.#completed) {
          return;
        }
        this.#completed = true;
        this.#primaryHandler.onResponseEnd?.(controller, trailers);
        for (const waitingHandler of this.#waitingHandlers) {
          if (waitingHandler.done || waitingHandler.controller.aborted) {
            waitingHandler.done = true;
            continue;
          }
          this.#flushWaitingHandler(waitingHandler);
          if (waitingHandler.done || waitingHandler.controller.aborted) {
            waitingHandler.done = true;
            continue;
          }
          if (waitingHandler.controller.paused && waitingHandler.bufferedChunks.length > 0) {
            waitingHandler.pendingTrailers = trailers;
            continue;
          }
          try {
            waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, trailers);
          } catch {
          }
          waitingHandler.done = true;
        }
        this.#pruneDoneWaitingHandlers();
        this.#onComplete?.();
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {Error} err
       */
      onResponseError(controller, err) {
        if (this.#completed) {
          return;
        }
        this.#aborted = true;
        this.#completed = true;
        this.#primaryHandler.onResponseError?.(controller, err);
        for (const waitingHandler of this.#waitingHandlers) {
          this.#errorWaitingHandler(waitingHandler, err);
        }
        this.#waitingHandlers = [];
        this.#onComplete?.();
      }
      /**
       * @param {DispatchHandler} handler
       * @returns {WaitingHandler}
       */
      #createWaitingHandler(handler) {
        const waitingHandler = {
          handler,
          controller: null,
          bufferedChunks: [],
          bufferedBytes: 0,
          pendingTrailers: null,
          done: false
        };
        const state = {
          aborted: false,
          paused: false,
          reason: null
        };
        waitingHandler.controller = {
          resume: () => {
            if (state.aborted) {
              return;
            }
            state.paused = false;
            this.#flushWaitingHandler(waitingHandler);
            if (this.#completed && waitingHandler.pendingTrailers && waitingHandler.bufferedChunks.length === 0 && !state.paused && !state.aborted) {
              try {
                waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, waitingHandler.pendingTrailers);
              } catch {
              }
              waitingHandler.pendingTrailers = null;
              waitingHandler.done = true;
            }
            this.#pruneDoneWaitingHandlers();
          },
          pause: () => {
            if (!state.aborted) {
              state.paused = true;
            }
          },
          get paused() {
            return state.paused;
          },
          get aborted() {
            return state.aborted;
          },
          get reason() {
            return state.reason;
          },
          abort: (reason) => {
            state.aborted = true;
            state.reason = reason ?? null;
            waitingHandler.done = true;
            waitingHandler.pendingTrailers = null;
            waitingHandler.bufferedChunks = [];
            waitingHandler.bufferedBytes = 0;
          }
        };
        return waitingHandler;
      }
      /**
       * @param {WaitingHandler} waitingHandler
       * @param {Buffer} chunk
       */
      #bufferWaitingChunk(waitingHandler, chunk) {
        if (waitingHandler.done || waitingHandler.controller.aborted) {
          waitingHandler.done = true;
          waitingHandler.bufferedChunks = [];
          waitingHandler.bufferedBytes = 0;
          return;
        }
        const bufferedChunk = Buffer.from(chunk);
        waitingHandler.bufferedChunks.push(bufferedChunk);
        waitingHandler.bufferedBytes += bufferedChunk.length;
        if (waitingHandler.bufferedBytes > this.#maxBufferSize) {
          const err = new RequestAbortedError(`Deduplicated waiting handler exceeded maxBufferSize (${this.#maxBufferSize} bytes) while paused`);
          this.#errorWaitingHandler(waitingHandler, err);
        }
      }
      /**
       * @param {WaitingHandler} waitingHandler
       */
      #flushWaitingHandler(waitingHandler) {
        const { handler, controller } = waitingHandler;
        while (!waitingHandler.done && !controller.aborted && !controller.paused && waitingHandler.bufferedChunks.length > 0) {
          const bufferedChunk = waitingHandler.bufferedChunks.shift();
          waitingHandler.bufferedBytes -= bufferedChunk.length;
          try {
            handler.onResponseData?.(controller, bufferedChunk);
          } catch {
          }
          if (controller.aborted) {
            waitingHandler.done = true;
            waitingHandler.pendingTrailers = null;
            waitingHandler.bufferedChunks = [];
            waitingHandler.bufferedBytes = 0;
            break;
          }
        }
      }
      /**
       * @param {WaitingHandler} waitingHandler
       * @param {Error} err
       */
      #errorWaitingHandler(waitingHandler, err) {
        if (waitingHandler.done) {
          return;
        }
        waitingHandler.done = true;
        waitingHandler.pendingTrailers = null;
        waitingHandler.bufferedChunks = [];
        waitingHandler.bufferedBytes = 0;
        try {
          waitingHandler.controller.abort(err);
          waitingHandler.handler.onResponseError?.(waitingHandler.controller, err);
        } catch {
        }
      }
      #pruneDoneWaitingHandlers() {
        this.#waitingHandlers = this.#waitingHandlers.filter((waitingHandler) => waitingHandler.done === false);
      }
    };
    module.exports = DeduplicationHandler;
  }
});

// ../../node_modules/undici/lib/interceptor/deduplicate.js
var require_deduplicate = __commonJS({
  "../../node_modules/undici/lib/interceptor/deduplicate.js"(exports, module) {
    "use strict";
    var diagnosticsChannel = __require("diagnostics_channel");
    var util = require_util();
    var DeduplicationHandler = require_deduplication_handler();
    var { normalizeHeaders, makeCacheKey, makeDeduplicationKey } = require_cache();
    var pendingRequestsChannel = diagnosticsChannel.channel("undici:request:pending-requests");
    module.exports = (opts = {}) => {
      const {
        methods = ["GET"],
        skipHeaderNames = [],
        excludeHeaderNames = [],
        maxBufferSize = 5 * 1024 * 1024
      } = opts;
      if (typeof opts !== "object" || opts === null) {
        throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
      }
      if (!Array.isArray(methods)) {
        throw new TypeError(`expected opts.methods to be an array, got ${typeof methods}`);
      }
      for (const method of methods) {
        if (!util.safeHTTPMethods.includes(method)) {
          throw new TypeError(`expected opts.methods to only contain safe HTTP methods, got ${method}`);
        }
      }
      if (!Array.isArray(skipHeaderNames)) {
        throw new TypeError(`expected opts.skipHeaderNames to be an array, got ${typeof skipHeaderNames}`);
      }
      if (!Array.isArray(excludeHeaderNames)) {
        throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`);
      }
      if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {
        throw new TypeError(`expected opts.maxBufferSize to be a positive finite number, got ${maxBufferSize}`);
      }
      const skipHeaderNamesSet = new Set(skipHeaderNames.map((name) => name.toLowerCase()));
      const excludeHeaderNamesSet = new Set(excludeHeaderNames.map((name) => name.toLowerCase()));
      const pendingRequests = /* @__PURE__ */ new Map();
      return (dispatch) => {
        return (opts2, handler) => {
          if (!opts2.origin || methods.includes(opts2.method) === false) {
            return dispatch(opts2, handler);
          }
          opts2 = {
            ...opts2,
            headers: normalizeHeaders(opts2)
          };
          if (skipHeaderNamesSet.size > 0) {
            for (const headerName of Object.keys(opts2.headers)) {
              if (skipHeaderNamesSet.has(headerName.toLowerCase())) {
                return dispatch(opts2, handler);
              }
            }
          }
          const cacheKey = makeCacheKey(opts2);
          const dedupeKey = makeDeduplicationKey(cacheKey, excludeHeaderNamesSet);
          const pendingHandler = pendingRequests.get(dedupeKey);
          if (pendingHandler) {
            if (pendingHandler.addWaitingHandler(handler)) {
              return true;
            }
            return dispatch(opts2, handler);
          }
          const deduplicationHandler = new DeduplicationHandler(
            handler,
            () => {
              pendingRequests.delete(dedupeKey);
              if (pendingRequestsChannel.hasSubscribers) {
                pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "removed" });
              }
            },
            maxBufferSize
          );
          pendingRequests.set(dedupeKey, deduplicationHandler);
          if (pendingRequestsChannel.hasSubscribers) {
            pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "added" });
          }
          return dispatch(opts2, deduplicationHandler);
        };
      };
    };
  }
});

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

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

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

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

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

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

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

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

// ../../node_modules/undici/lib/web/fetch/index.js
var require_fetch = __commonJS({
  "../../node_modules/undici/lib/web/fetch/index.js"(exports, module) {
    "use strict";
    var {
      makeNetworkError,
      makeAppropriateNetworkError,
      filterResponse,
      makeResponse,
      fromInnerResponse,
      getResponseState
    } = require_response();
    var { HeadersList } = require_headers();
    var { Request, cloneRequest, getRequestDispatcher, getRequestState, removeRequestAbortListener } = require_request2();
    var zlib = __require("zlib");
    var {
      makePolicyContainer,
      clonePolicyContainer,
      requestBadPort,
      TAOCheck,
      appendRequestOriginHeader,
      responseLocationURL,
      requestCurrentURL,
      setRequestReferrerPolicyOnRedirect,
      tryUpgradeRequestToAPotentiallyTrustworthyURL,
      createOpaqueTimingInfo,
      appendFetchMetadata,
      corsCheck,
      crossOriginResourcePolicyCheck,
      determineRequestsReferrer,
      coarsenedSharedCurrentTime,
      sameOrigin,
      isCancelled,
      isAborted,
      isErrorLike,
      fullyReadBody,
      readableStreamClose,
      urlIsLocal,
      urlIsHttpHttpsScheme,
      urlHasHttpsScheme,
      clampAndCoarsenConnectionTimingInfo,
      simpleRangeHeaderValue,
      buildContentRange,
      createInflate,
      extractMimeType,
      hasAuthenticationEntry,
      includesCredentials,
      isTraversableNavigable
    } = require_util2();
    var assert = __require("assert");
    var { safelyExtractBody, extractBody } = require_body();
    var {
      redirectStatusSet,
      nullBodyStatus,
      safeMethodsSet,
      requestBodyHeader,
      subresourceSet
    } = require_constants3();
    var EE = __require("events");
    var { Readable, pipeline, finished, isErrored, isReadable } = __require("stream");
    var { addAbortListener, bufferToLowerCasedHeaderName } = require_util();
    var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
    var { getGlobalDispatcher } = require_global2();
    var { webidl } = require_webidl();
    var { STATUS_CODES } = __require("http");
    var { bytesMatch } = require_subresource_integrity();
    var { isomorphicEncode } = require_infra();
    var GET_OR_HEAD = ["GET", "HEAD"];
    var defaultUserAgent = typeof __UNDICI_IS_NODE__ !== "undefined" || typeof esbuildDetection !== "undefined" ? "node" : "undici";
    var resolveObjectURL;
    function appendHeadersListFromResponseHeaders(headersList, headers, rawHeaders) {
      if (Array.isArray(rawHeaders)) {
        for (let i = 0; i < rawHeaders.length; i += 2) {
          const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
          const value = rawHeaders[i + 1];
          if (Array.isArray(value) && !Buffer.isBuffer(value)) {
            for (const val of value) {
              headersList.append(nameStr, val.toString("latin1"), true);
            }
          } else {
            headersList.append(nameStr, value.toString("latin1"), true);
          }
        }
        return;
      }
      for (const [name, value] of Object.entries(headers ?? {})) {
        if (Array.isArray(value)) {
          for (const entry of value) {
            headersList.append(name, `${entry}`, true);
          }
        } else {
          headersList.append(name, `${value}`, true);
        }
      }
    }
    var Fetch = class extends EE {
      constructor(dispatcher) {
        super();
        this.dispatcher = dispatcher;
        this.connection = null;
        this.dump = false;
        this.state = "ongoing";
      }
      terminate(reason) {
        if (this.state !== "ongoing") {
          return;
        }
        this.state = "terminated";
        this.connection?.destroy(reason);
        this.emit("terminated", reason);
      }
      // https://fetch.spec.whatwg.org/#fetch-controller-abort
      abort(error) {
        if (this.state !== "ongoing") {
          return;
        }
        this.state = "aborted";
        if (!error) {
          error = new DOMException("The operation was aborted.", "AbortError");
        }
        this.serializedAbortReason = error;
        this.connection?.destroy(error);
        this.emit("terminated", error);
      }
    };
    function handleFetchDone(response) {
      finalizeAndReportTiming(response, "fetch");
    }
    function fetch(input, init = void 0) {
      webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch");
      let p = Promise.withResolvers();
      let requestObject;
      try {
        requestObject = new Request(input, init);
      } catch (e) {
        p.reject(e);
        return p.promise;
      }
      const request = getRequestState(requestObject);
      if (requestObject.signal.aborted) {
        abortFetch(p, request, null, requestObject.signal.reason, null);
        return p.promise;
      }
      const globalObject = request.client.globalObject;
      if (globalObject?.constructor?.name === "ServiceWorkerGlobalScope") {
        request.serviceWorkers = "none";
      }
      let responseObject = null;
      let locallyAborted = false;
      let controller = null;
      const removeAbortListener = addAbortListener(
        requestObject.signal,
        () => {
          locallyAborted = true;
          assert(controller != null);
          controller.abort(requestObject.signal.reason);
          const realResponse = responseObject?.deref();
          abortFetch(p, request, realResponse, requestObject.signal.reason, controller.controller);
        }
      );
      const cleanupAbortListeners = () => {
        removeAbortListener();
        removeRequestAbortListener(requestObject);
      };
      const processResponse = (response) => {
        if (locallyAborted) {
          return;
        }
        if (response.aborted) {
          abortFetch(p, request, responseObject, controller.serializedAbortReason, controller.controller);
          cleanupAbortListeners();
          return;
        }
        if (response.type === "error") {
          p.reject(new TypeError("fetch failed", { cause: response.error }));
          cleanupAbortListeners();
          return;
        }
        responseObject = new WeakRef(fromInnerResponse(response, "immutable"));
        p.resolve(responseObject.deref());
        p = null;
      };
      controller = fetching({
        request,
        processResponseEndOfBody: (response) => {
          handleFetchDone(response);
          cleanupAbortListeners();
        },
        processResponse,
        dispatcher: getRequestDispatcher(requestObject),
        // undici
        // Keep requestObject alive to prevent its AbortController from being GC'd
        // See https://github.com/nodejs/undici/issues/4627
        requestObject
      });
      return p.promise;
    }
    function finalizeAndReportTiming(response, initiatorType = "other") {
      if (response.type === "error" && response.aborted) {
        return;
      }
      if (!response.urlList?.length) {
        return;
      }
      const originalURL = response.urlList[0];
      let timingInfo = response.timingInfo;
      let cacheState = response.cacheState;
      if (!urlIsHttpHttpsScheme(originalURL)) {
        return;
      }
      if (timingInfo === null) {
        return;
      }
      if (!response.timingAllowPassed) {
        timingInfo = createOpaqueTimingInfo({
          startTime: timingInfo.startTime
        });
        cacheState = "";
      }
      timingInfo.endTime = coarsenedSharedCurrentTime();
      response.timingInfo = timingInfo;
      markResourceTiming(
        timingInfo,
        originalURL.href,
        initiatorType,
        globalThis,
        cacheState,
        "",
        // bodyType
        response.status
      );
    }
    var markResourceTiming = performance.markResourceTiming;
    function abortFetch(p, request, responseObject, error, controller) {
      if (p) {
        p.reject(error);
      }
      if (request.body?.stream != null && isReadable(request.body.stream)) {
        request.body.stream.cancel(error).catch((err) => {
          if (err.code === "ERR_INVALID_STATE") {
            return;
          }
          throw err;
        });
      }
      if (responseObject == null) {
        return;
      }
      const response = getResponseState(responseObject);
      if (response.body?.stream != null && isReadable(response.body.stream)) {
        controller.error(error);
      }
    }
    function fetching({
      request,
      processRequestBodyChunkLength,
      processRequestEndOfBody,
      processResponse,
      processResponseEndOfBody,
      processResponseConsumeBody,
      useParallelQueue = false,
      dispatcher = getGlobalDispatcher(),
      // undici
      requestObject = null
      // Keep alive to prevent AbortController GC, see #4627
    }) {
      assert(dispatcher);
      let taskDestination = null;
      let crossOriginIsolatedCapability = false;
      if (request.client != null) {
        taskDestination = request.client.globalObject;
        crossOriginIsolatedCapability = request.client.crossOriginIsolatedCapability;
      }
      const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability);
      const timingInfo = createOpaqueTimingInfo({
        startTime: currentTime
      });
      const fetchParams = {
        controller: new Fetch(dispatcher),
        request,
        timingInfo,
        processRequestBodyChunkLength,
        processRequestEndOfBody,
        processResponse,
        processResponseConsumeBody,
        processResponseEndOfBody,
        taskDestination,
        crossOriginIsolatedCapability,
        // Keep requestObject alive to prevent its AbortController from being GC'd
        requestObject
      };
      assert(!request.body || request.body.stream);
      if (request.window === "client") {
        request.window = request.client?.globalObject?.constructor?.name === "Window" ? request.client : "no-window";
      }
      if (request.origin === "client") {
        request.origin = request.client.origin;
      }
      if (request.policyContainer === "client") {
        if (request.client != null) {
          request.policyContainer = clonePolicyContainer(
            request.client.policyContainer
          );
        } else {
          request.policyContainer = makePolicyContainer();
        }
      }
      if (!request.headersList.contains("accept", true)) {
        const value = "*/*";
        request.headersList.append("accept", value, true);
      }
      if (!request.headersList.contains("accept-language", true)) {
        request.headersList.append("accept-language", "*", true);
      }
      if (request.priority === null) {
      }
      if (subresourceSet.has(request.destination)) {
      }
      mainFetch(fetchParams, false);
      return fetchParams.controller;
    }
    async function mainFetch(fetchParams, recursive) {
      try {
        const request = fetchParams.request;
        let response = null;
        if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
          response = makeNetworkError("local URLs only");
        }
        tryUpgradeRequestToAPotentiallyTrustworthyURL(request);
        if (requestBadPort(request) === "blocked") {
          response = makeNetworkError("bad port");
        }
        if (request.referrerPolicy === "") {
          request.referrerPolicy = request.policyContainer.referrerPolicy;
        }
        if (request.referrer !== "no-referrer") {
          request.referrer = determineRequestsReferrer(request);
        }
        if (response === null) {
          const currentURL = requestCurrentURL(request);
          if (
            // - request’s current URL’s origin is same origin with request’s origin,
            //   and request’s response tainting is "basic"
            sameOrigin(currentURL, request.url) && request.responseTainting === "basic" || // request’s current URL’s scheme is "data"
            currentURL.protocol === "data:" || // - request’s mode is "navigate" or "websocket"
            (request.mode === "navigate" || request.mode === "websocket")
          ) {
            request.responseTainting = "basic";
            response = await schemeFetch(fetchParams);
          } else if (request.mode === "same-origin") {
            response = makeNetworkError('request mode cannot be "same-origin"');
          } else if (request.mode === "no-cors") {
            if (request.redirect !== "follow") {
              response = makeNetworkError(
                'redirect mode cannot be "follow" for "no-cors" request'
              );
            } else {
              request.responseTainting = "opaque";
              response = await schemeFetch(fetchParams);
            }
          } else if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
            response = makeNetworkError("URL scheme must be a HTTP(S) scheme");
          } else {
            request.responseTainting = "cors";
            response = await httpFetch(fetchParams);
          }
        }
        if (recursive) {
          return response;
        }
        if (response.status !== 0 && !response.internalResponse) {
          if (request.responseTainting === "cors") {
          }
          if (request.responseTainting === "basic") {
            response = filterResponse(response, "basic");
          } else if (request.responseTainting === "cors") {
            response = filterResponse(response, "cors");
          } else if (request.responseTainting === "opaque") {
            response = filterResponse(response, "opaque");
          } else {
            assert(false);
          }
        }
        let internalResponse = response.status === 0 ? response : response.internalResponse;
        if (internalResponse.urlList.length === 0) {
          internalResponse.urlList.push(...request.urlList);
        }
        if (!request.timingAllowFailed) {
          response.timingAllowPassed = true;
        }
        if (response.type === "opaque" && internalResponse.status === 206 && internalResponse.rangeRequested && !request.headers.contains("range", true)) {
          response = internalResponse = makeNetworkError();
        }
        if (response.status !== 0 && (request.method === "HEAD" || request.method === "CONNECT" || nullBodyStatus.includes(internalResponse.status))) {
          internalResponse.body = null;
          fetchParams.controller.dump = true;
        }
        if (request.integrity) {
          const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason));
          if (request.responseTainting === "opaque" || response.body == null) {
            processBodyError(response.error);
            return;
          }
          const processBody = (bytes) => {
            if (!bytesMatch(bytes, request.integrity)) {
              processBodyError("integrity mismatch");
              return;
            }
            response.body = safelyExtractBody(bytes)[0];
            fetchFinale(fetchParams, response);
          };
          fullyReadBody(response.body, processBody, processBodyError);
        } else {
          fetchFinale(fetchParams, response);
        }
      } catch (err) {
        fetchParams.controller.terminate(err);
      }
    }
    function schemeFetch(fetchParams) {
      if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
        return Promise.resolve(makeAppropriateNetworkError(fetchParams));
      }
      const { request } = fetchParams;
      const { protocol: scheme } = requestCurrentURL(request);
      switch (scheme) {
        case "about:": {
          return Promise.resolve(makeNetworkError("about scheme is not supported"));
        }
        case "blob:": {
          if (!resolveObjectURL) {
            resolveObjectURL = __require("buffer").resolveObjectURL;
          }
          const blobURLEntry = requestCurrentURL(request);
          if (blobURLEntry.search.length !== 0) {
            return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource."));
          }
          const blob = resolveObjectURL(blobURLEntry.toString());
          if (request.method !== "GET" || !webidl.is.Blob(blob)) {
            return Promise.resolve(makeNetworkError("invalid method"));
          }
          const response = makeResponse();
          const fullLength = blob.size;
          const serializedFullLength = isomorphicEncode(`${fullLength}`);
          const type = blob.type;
          if (!request.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 = request.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 + 1, 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(request);
          const dataURLStruct = dataURLProcessor(currentURL);
          if (dataURLStruct === "failure") {
            return Promise.resolve(makeNetworkError("failed to fetch the data URL"));
          }
          const mimeType = serializeAMimeType(dataURLStruct.mimeType);
          return Promise.resolve(makeResponse({
            statusText: "OK",
            headersList: [
              ["content-type", { name: "Content-Type", value: mimeType }]
            ],
            body: safelyExtractBody(dataURLStruct.body)[0]
          }));
        }
        case "file:": {
          return Promise.resolve(makeNetworkError("not implemented... yet..."));
        }
        case "http:":
        case "https:": {
          return httpFetch(fetchParams).catch((err) => makeNetworkError(err));
        }
        default: {
          return Promise.resolve(makeNetworkError("unknown scheme"));
        }
      }
    }
    function finalizeResponse(fetchParams, response) {
      fetchParams.request.done = true;
      if (fetchParams.processResponseDone != null) {
        queueMicrotask(() => fetchParams.processResponseDone(response));
      }
    }
    function fetchFinale(fetchParams, response) {
      let timingInfo = fetchParams.timingInfo;
      const processResponseEndOfBody = () => {
        const unsafeEndTime = Date.now();
        if (fetchParams.request.destination === "document") {
          fetchParams.controller.fullTimingInfo = timingInfo;
        }
        fetchParams.controller.reportTimingSteps = () => {
          if (!urlIsHttpHttpsScheme(fetchParams.request.url)) {
            return;
          }
          timingInfo.endTime = unsafeEndTime;
          let cacheState = response.cacheState;
          const bodyInfo = response.bodyInfo;
          if (!response.timingAllowPassed) {
            timingInfo = createOpaqueTimingInfo(timingInfo);
            cacheState = "";
          }
          let responseStatus = 0;
          if (fetchParams.request.mode !== "navigate" || !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 = () => {
          fetchParams.request.done = true;
          if (fetchParams.processResponseEndOfBody != null) {
            queueMicrotask(() => fetchParams.processResponseEndOfBody(response));
          }
          if (fetchParams.request.initiatorType != null) {
            fetchParams.controller.reportTimingSteps();
          }
        };
        queueMicrotask(() => processResponseEndOfBodyTask());
      };
      if (fetchParams.processResponse != null) {
        queueMicrotask(() => {
          fetchParams.processResponse(response);
          fetchParams.processResponse = null;
        });
      }
      const internalResponse = response.type === "error" ? response : response.internalResponse ?? response;
      if (internalResponse.body == null) {
        processResponseEndOfBody();
      } else {
        finished(internalResponse.body.stream, () => {
          processResponseEndOfBody();
        });
      }
    }
    async function httpFetch(fetchParams) {
      const request = fetchParams.request;
      let response = null;
      let actualResponse = null;
      const timingInfo = fetchParams.timingInfo;
      if (request.serviceWorkers === "all") {
      }
      if (response === null) {
        if (request.redirect === "follow") {
          request.serviceWorkers = "none";
        }
        actualResponse = response = await httpNetworkOrCacheFetch(fetchParams);
        if (request.responseTainting === "cors" && corsCheck(request, response) === "failure") {
          return makeNetworkError("cors failure");
        }
        if (TAOCheck(request, response) === "failure") {
          request.timingAllowFailed = true;
        }
      }
      if ((request.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck(
        request.origin,
        request.client,
        request.destination,
        actualResponse
      ) === "blocked") {
        return makeNetworkError("blocked");
      }
      if (redirectStatusSet.has(actualResponse.status)) {
        if (request.redirect !== "manual") {
          fetchParams.controller.connection.destroy(void 0, false);
        }
        if (request.redirect === "error") {
          response = makeNetworkError("unexpected redirect");
        } else if (request.redirect === "manual") {
          response = actualResponse;
        } else if (request.redirect === "follow") {
          response = await httpRedirectFetch(fetchParams, response);
        } else {
          assert(false);
        }
      }
      response.timingInfo = timingInfo;
      return response;
    }
    function httpRedirectFetch(fetchParams, response) {
      const request = fetchParams.request;
      const actualResponse = response.internalResponse ? response.internalResponse : response;
      let locationURL;
      try {
        locationURL = responseLocationURL(
          actualResponse,
          requestCurrentURL(request).hash
        );
        if (locationURL == null) {
          return response;
        }
      } catch (err) {
        return Promise.resolve(makeNetworkError(err));
      }
      if (!urlIsHttpHttpsScheme(locationURL)) {
        return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme"));
      }
      if (request.redirectCount === 20) {
        return Promise.resolve(makeNetworkError("redirect count exceeded"));
      }
      request.redirectCount += 1;
      if (request.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL)) {
        return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'));
      }
      if (request.responseTainting === "cors" && (locationURL.username || locationURL.password)) {
        return Promise.resolve(makeNetworkError(
          'URL cannot contain credentials for request mode "cors"'
        ));
      }
      if (actualResponse.status !== 303 && request.body != null && request.body.source == null) {
        return Promise.resolve(makeNetworkError());
      }
      if ([301, 302].includes(actualResponse.status) && request.method === "POST" || actualResponse.status === 303 && !GET_OR_HEAD.includes(request.method)) {
        request.method = "GET";
        request.body = null;
        for (const headerName of requestBodyHeader) {
          request.headersList.delete(headerName);
        }
      }
      if (!sameOrigin(requestCurrentURL(request), locationURL)) {
        request.headersList.delete("authorization", true);
        request.headersList.delete("proxy-authorization", true);
        request.headersList.delete("cookie", true);
        request.headersList.delete("host", true);
      }
      if (request.body != null) {
        assert(request.body.source != null);
        request.body = safelyExtractBody(request.body.source)[0];
      }
      const timingInfo = fetchParams.timingInfo;
      timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
      if (timingInfo.redirectStartTime === 0) {
        timingInfo.redirectStartTime = timingInfo.startTime;
      }
      request.urlList.push(locationURL);
      setRequestReferrerPolicyOnRedirect(request, actualResponse);
      return mainFetch(fetchParams, true);
    }
    async function httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false) {
      const request = fetchParams.request;
      let httpFetchParams = null;
      let httpRequest = null;
      let response = null;
      const httpCache = null;
      const revalidatingFlag = false;
      if (request.window === "no-window" && request.redirect === "error") {
        httpFetchParams = fetchParams;
        httpRequest = request;
      } else {
        httpRequest = cloneRequest(request);
        httpFetchParams = { ...fetchParams };
        httpFetchParams.request = httpRequest;
      }
      const includeCredentials = request.credentials === "include" || request.credentials === "same-origin" && request.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.contains("content-length", true)) {
        httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
      }
      if (contentLength != null && httpRequest.keepalive) {
      }
      if (webidl.is.URL(httpRequest.referrer)) {
        httpRequest.headersList.append("referer", isomorphicEncode(httpRequest.referrer.href), true);
      }
      appendRequestOriginHeader(httpRequest);
      appendFetchMetadata(httpRequest);
      if (!httpRequest.headersList.contains("user-agent", true)) {
        httpRequest.headersList.append("user-agent", defaultUserAgent, true);
      }
      if (httpRequest.cache === "default" && (httpRequest.headersList.contains("if-modified-since", true) || httpRequest.headersList.contains("if-none-match", true) || httpRequest.headersList.contains("if-unmodified-since", true) || httpRequest.headersList.contains("if-match", true) || httpRequest.headersList.contains("if-range", true))) {
        httpRequest.cache = "no-store";
      }
      if (httpRequest.cache === "no-cache" && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains("cache-control", true)) {
        httpRequest.headersList.append("cache-control", "max-age=0", true);
      }
      if (httpRequest.cache === "no-store" || httpRequest.cache === "reload") {
        if (!httpRequest.headersList.contains("pragma", true)) {
          httpRequest.headersList.append("pragma", "no-cache", true);
        }
        if (!httpRequest.headersList.contains("cache-control", true)) {
          httpRequest.headersList.append("cache-control", "no-cache", true);
        }
      }
      if (httpRequest.headersList.contains("range", true)) {
        httpRequest.headersList.append("accept-encoding", "identity", true);
      }
      if (!httpRequest.headersList.contains("accept-encoding", true)) {
        if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
          httpRequest.headersList.append("accept-encoding", "br, gzip, deflate", true);
        } else {
          httpRequest.headersList.append("accept-encoding", "gzip, deflate", true);
        }
      }
      httpRequest.headersList.delete("host", true);
      if (includeCredentials) {
        if (!httpRequest.headersList.contains("authorization", true)) {
          let authorizationValue = null;
          if (hasAuthenticationEntry(httpRequest) && (httpRequest.useURLCredentials === void 0 || !includesCredentials(requestCurrentURL(httpRequest)))) {
          } else if (includesCredentials(requestCurrentURL(httpRequest)) && isAuthenticationFetch) {
            const { username, password } = requestCurrentURL(httpRequest);
            authorizationValue = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
          }
          if (authorizationValue !== null) {
            httpRequest.headersList.append("Authorization", authorizationValue, false);
          }
        }
      }
      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 === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && (request.useURLCredentials !== void 0 || isTraversableNavigable(request.traversableForUserPrompts))) {
        if (request.body != null) {
          if (request.body.source == null) {
            return response;
          }
          request.body = safelyExtractBody(request.body.source)[0];
        }
        if (request.useURLCredentials === void 0 || isAuthenticationFetch) {
          if (isCancelled(fetchParams)) {
            return makeAppropriateNetworkError(fetchParams);
          }
          return response;
        }
        fetchParams.controller.connection.destroy();
        response = await httpNetworkOrCacheFetch(fetchParams, true);
      }
      if (response.status === 407) {
        if (request.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
        (request.body == null || request.body.source != null)
      ) {
        if (isCancelled(fetchParams)) {
          return makeAppropriateNetworkError(fetchParams);
        }
        fetchParams.controller.connection.destroy();
        response = await httpNetworkOrCacheFetch(
          fetchParams,
          isAuthenticationFetch,
          true
        );
      }
      if (isAuthenticationFetch) {
      }
      return response;
    }
    async function httpNetworkFetch(fetchParams, includeCredentials = false, forceNewConnection = false) {
      assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed);
      fetchParams.controller.connection = {
        abort: null,
        destroyed: false,
        destroy(err, abort = true) {
          if (!this.destroyed) {
            this.destroyed = true;
            if (abort) {
              this.abort?.(err ?? new DOMException("The operation was aborted.", "AbortError"));
            }
          }
        }
      };
      const request = fetchParams.request;
      let response = null;
      const timingInfo = fetchParams.timingInfo;
      const httpCache = null;
      if (httpCache == null) {
        request.cache = "no-store";
      }
      const newConnection = forceNewConnection ? "yes" : "no";
      if (request.mode === "websocket") {
      } else {
      }
      let requestBody = null;
      if (request.body == null && fetchParams.processRequestEndOfBody) {
        queueMicrotask(() => fetchParams.processRequestEndOfBody());
      } else if (request.body != null) {
        const processBodyChunk = async function* (bytes) {
          if (isCancelled(fetchParams)) {
            return;
          }
          yield bytes;
          fetchParams.processRequestBodyChunkLength?.(bytes.byteLength);
        };
        const processEndOfBody = () => {
          if (isCancelled(fetchParams)) {
            return;
          }
          if (fetchParams.processRequestEndOfBody) {
            fetchParams.processRequestEndOfBody();
          }
        };
        const processBodyError = (e) => {
          if (isCancelled(fetchParams)) {
            return;
          }
          if (e.name === "AbortError") {
            fetchParams.controller.abort();
          } else {
            fetchParams.controller.terminate(e);
          }
        };
        requestBody = (async function* () {
          try {
            for await (const bytes of request.body.stream) {
              yield* processBodyChunk(bytes);
            }
            processEndOfBody();
          } catch (err) {
            processBodyError(err);
          }
        })();
      }
      try {
        const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody });
        if (socket) {
          response = makeResponse({ status, statusText, headersList, socket });
        } else {
          const iterator = body[Symbol.asyncIterator]();
          fetchParams.controller.next = () => iterator.next();
          response = makeResponse({ status, statusText, headersList });
        }
      } catch (err) {
        if (err.name === "AbortError") {
          fetchParams.controller.connection.destroy();
          return makeAppropriateNetworkError(fetchParams, err);
        }
        return makeNetworkError(err);
      }
      const pullAlgorithm = () => {
        return fetchParams.controller.resume();
      };
      const cancelAlgorithm = (reason) => {
        if (!isCancelled(fetchParams)) {
          fetchParams.controller.abort(reason);
        }
      };
      const stream = new ReadableStream(
        {
          start(controller) {
            fetchParams.controller.controller = controller;
          },
          pull: pullAlgorithm,
          cancel: cancelAlgorithm,
          type: "bytes"
        }
      );
      response.body = { stream, source: null, length: null };
      if (!fetchParams.controller.resume) {
        fetchParams.controller.on("terminated", onAborted);
      }
      fetchParams.controller.resume = async () => {
        while (true) {
          let bytes;
          let isFailure;
          try {
            const { done, value } = await fetchParams.controller.next();
            if (isAborted(fetchParams)) {
              break;
            }
            bytes = done ? void 0 : value;
          } catch (err) {
            if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
              bytes = void 0;
            } else {
              bytes = err;
              isFailure = true;
            }
          }
          if (bytes === void 0) {
            readableStreamClose(fetchParams.controller.controller);
            finalizeResponse(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(stream)) {
            fetchParams.controller.terminate();
            return;
          }
          if (fetchParams.controller.controller.desiredSize <= 0) {
            return;
          }
        }
      };
      function onAborted(reason) {
        if (isAborted(fetchParams)) {
          response.aborted = true;
          if (isReadable(stream)) {
            fetchParams.controller.controller.error(
              fetchParams.controller.serializedAbortReason
            );
          }
        } else {
          if (isReadable(stream)) {
            fetchParams.controller.controller.error(new TypeError("terminated", {
              cause: isErrorLike(reason) ? reason : void 0
            }));
          }
        }
        fetchParams.controller.connection.destroy();
      }
      return response;
      function dispatch({ body }) {
        const url = requestCurrentURL(request);
        const agent = fetchParams.controller.dispatcher;
        const path = url.pathname + url.search;
        const hasTrailingQuestionMark = url.search.length === 0 && url.href[url.href.length - url.hash.length - 1] === "?";
        return dispatchWithProtocolPreference(body);
        function dispatchWithProtocolPreference(body2, allowH2) {
          return new Promise((resolve, reject) => agent.dispatch(
            {
              path: hasTrailingQuestionMark ? `${path}?` : path,
              origin: url.origin,
              method: request.method,
              body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body2,
              // Preserve the serialized fetch body for MockAgent net-connect fallthroughs.
              __mockAgentBodyForDispatch: body2,
              headers: request.headersList.entries,
              maxRedirections: 0,
              upgrade: request.mode === "websocket" ? "websocket" : void 0,
              ...allowH2 === false ? { allowH2 } : null
            },
            {
              body: null,
              abort: null,
              onRequestStart(controller) {
                const { connection } = fetchParams.controller;
                timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability);
                const abort = (reason) => controller.abort(reason);
                if (connection.destroyed) {
                  abort(new DOMException("The operation was aborted.", "AbortError"));
                } else {
                  fetchParams.controller.on("terminated", abort);
                  this.abort = connection.abort = abort;
                }
                timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
              },
              onResponseStarted() {
                timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
              },
              onResponseStart(controller, status, headers, statusText) {
                if (status < 200) {
                  return;
                }
                const rawHeaders = controller?.rawHeaders ?? [];
                const headersList = new HeadersList();
                appendHeadersListFromResponseHeaders(headersList, headers, rawHeaders);
                const location = headersList.get("location", true);
                this.body = new Readable({ read: () => controller.resume() });
                const willFollow = location && request.redirect === "follow" && redirectStatusSet.has(status);
                const decoders = [];
                if (request.method !== "HEAD" && request.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) {
                  const contentEncoding = headersList.get("content-encoding", true);
                  const codings = contentEncoding ? contentEncoding.toLowerCase().split(",") : [];
                  const maxContentEncodings = 5;
                  if (codings.length > maxContentEncodings) {
                    reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`));
                    return;
                  }
                  for (let i = codings.length - 1; i >= 0; --i) {
                    const coding = codings[i].trim();
                    if (coding === "x-gzip" || coding === "gzip") {
                      decoders.push(zlib.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: zlib.constants.Z_SYNC_FLUSH,
                        finishFlush: zlib.constants.Z_SYNC_FLUSH
                      }));
                    } else if (coding === "deflate") {
                      decoders.push(createInflate({
                        flush: zlib.constants.Z_SYNC_FLUSH,
                        finishFlush: zlib.constants.Z_SYNC_FLUSH
                      }));
                    } else if (coding === "br") {
                      decoders.push(zlib.createBrotliDecompress({
                        flush: zlib.constants.BROTLI_OPERATION_FLUSH,
                        finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
                      }));
                    } else if (coding === "zstd") {
                      decoders.push(zlib.createZstdDecompress({
                        flush: zlib.constants.ZSTD_e_continue,
                        finishFlush: zlib.constants.ZSTD_e_end
                      }));
                    } else {
                      decoders.length = 0;
                      break;
                    }
                  }
                }
                const onError = (err) => this.onResponseError(controller, err);
                resolve({
                  status,
                  statusText,
                  headersList,
                  body: decoders.length ? pipeline(this.body, ...decoders, (err) => {
                    if (err) {
                      this.onResponseError(controller, err);
                    }
                  }).on("error", onError) : this.body.on("error", onError)
                });
              },
              onResponseData(controller, chunk) {
                if (fetchParams.controller.dump) {
                  return;
                }
                const bytes = chunk;
                timingInfo.encodedBodySize += bytes.byteLength;
                if (this.body.push(bytes) === false) {
                  controller.pause();
                }
              },
              onResponseEnd() {
                if (this.abort) {
                  fetchParams.controller.off("terminated", this.abort);
                }
                fetchParams.controller.ended = true;
                this.body?.push(null);
              },
              onResponseError(_controller, error) {
                if (this.abort) {
                  fetchParams.controller.off("terminated", this.abort);
                }
                if (request.mode === "websocket" && allowH2 !== false && error?.code === "UND_ERR_INFO" && error?.message === "HTTP/2: Extended CONNECT protocol not supported by server") {
                  resolve(dispatchWithProtocolPreference(body2, false));
                  return;
                }
                this.body?.destroy(error);
                fetchParams.controller.terminate(error);
                reject(error);
              },
              onRequestUpgrade(controller, status, headers, socket) {
                if (socket.session != null && status !== 200 || socket.session == null && status !== 101) {
                  return false;
                }
                const rawHeaders = controller?.rawHeaders ?? [];
                const headersList = new HeadersList();
                appendHeadersListFromResponseHeaders(headersList, headers, rawHeaders);
                resolve({
                  status,
                  statusText: STATUS_CODES[status],
                  headersList,
                  socket
                });
                return true;
              }
            }
          ));
        }
      }
    }
    module.exports = {
      fetch,
      Fetch,
      fetching,
      finalizeAndReportTiming
    };
  }
});

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

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

// ../../node_modules/undici/lib/web/cache/cachestorage.js
var require_cachestorage = __commonJS({
  "../../node_modules/undici/lib/web/cache/cachestorage.js"(exports, module) {
    "use strict";
    var { Cache } = require_cache3();
    var { webidl } = require_webidl();
    var { kEnumerableProperty } = require_util();
    var { kConstruct } = require_symbols();
    var CacheStorage = class _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(request, options = {}) {
        webidl.brandCheck(this, _CacheStorage);
        webidl.argumentLengthCheck(arguments, 1, "CacheStorage.match");
        request = webidl.converters.RequestInfo(request);
        options = webidl.converters.MultiCacheQueryOptions(options);
        if (options.cacheName != null) {
          if (this.#caches.has(options.cacheName)) {
            const cacheList = this.#caches.get(options.cacheName);
            const cache = new Cache(kConstruct, cacheList);
            return await cache.match(request, options);
          }
        } else {
          for (const cacheList of this.#caches.values()) {
            const cache = new Cache(kConstruct, cacheList);
            const response = await cache.match(request, options);
            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 cache2 = this.#caches.get(cacheName);
          return new Cache(kConstruct, cache2);
        }
        const cache = [];
        this.#caches.set(cacheName, cache);
        return new Cache(kConstruct, cache);
      }
      /**
       * @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
    });
    module.exports = {
      CacheStorage
    };
  }
});

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

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

// ../../node_modules/undici/lib/web/cookies/parse.js
var require_parse = __commonJS({
  "../../node_modules/undici/lib/web/cookies/parse.js"(exports, module) {
    "use strict";
    var { collectASequenceOfCodePointsFast } = require_infra();
    var { maxNameValuePairSize, maxAttributeValueSize } = require_constants4();
    var { isCTLExcludingHtab } = require_util4();
    var assert = __require("assert");
    function parseSetCookie(header) {
      if (isCTLExcludingHtab(header)) {
        return null;
      }
      let nameValuePair = "";
      let unparsedAttributes = "";
      let name = "";
      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 };
        name = collectASequenceOfCodePointsFast(
          "=",
          nameValuePair,
          position
        );
        value = nameValuePair.slice(position.position + 1);
      }
      name = name.trim();
      value = value.trim();
      if (name.length + value.length > maxNameValuePairSize) {
        return null;
      }
      return {
        name,
        value,
        ...parseUnparsedAttributes(unparsedAttributes)
      };
    }
    function parseUnparsedAttributes(unparsedAttributes, cookieAttributeList = {}) {
      if (unparsedAttributes.length === 0) {
        return cookieAttributeList;
      }
      assert(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") {
        const attributeValueLowercase = attributeValue.toLowerCase();
        if (attributeValueLowercase === "none") {
          cookieAttributeList.sameSite = "None";
        } else if (attributeValueLowercase === "strict") {
          cookieAttributeList.sameSite = "Strict";
        } else if (attributeValueLowercase === "lax") {
          cookieAttributeList.sameSite = "Lax";
        }
      } else {
        cookieAttributeList.unparsed ??= [];
        cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`);
      }
      return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
    }
    module.exports = {
      parseSetCookie,
      parseUnparsedAttributes
    };
  }
});

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

// ../../node_modules/undici/lib/web/websocket/events.js
var require_events = __commonJS({
  "../../node_modules/undici/lib/web/websocket/events.js"(exports, module) {
    "use strict";
    var { webidl } = require_webidl();
    var { kEnumerableProperty } = require_util();
    var { kConstruct } = require_symbols();
    var MessageEvent = class _MessageEvent extends Event {
      #eventInit;
      constructor(type, eventInitDict = {}) {
        if (type === kConstruct) {
          super(arguments[1], arguments[2]);
          webidl.util.markAsUncloneable(this);
          return;
        }
        const prefix = "MessageEvent constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        type = webidl.converters.DOMString(type, prefix, "type");
        eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, "eventInitDict");
        super(type, eventInitDict);
        this.#eventInit = eventInitDict;
        webidl.util.markAsUncloneable(this);
      }
      get data() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.data;
      }
      get origin() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.origin;
      }
      get lastEventId() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.lastEventId;
      }
      get source() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.source;
      }
      get ports() {
        webidl.brandCheck(this, _MessageEvent);
        if (!Object.isFrozen(this.#eventInit.ports)) {
          Object.freeze(this.#eventInit.ports);
        }
        return this.#eventInit.ports;
      }
      initMessageEvent(type, bubbles = false, cancelable = false, data = null, origin = "", lastEventId = "", source = null, ports = []) {
        webidl.brandCheck(this, _MessageEvent);
        webidl.argumentLengthCheck(arguments, 1, "MessageEvent.initMessageEvent");
        return new _MessageEvent(type, {
          bubbles,
          cancelable,
          data,
          origin,
          lastEventId,
          source,
          ports
        });
      }
      static createFastMessageEvent(type, init) {
        const messageEvent = new _MessageEvent(kConstruct, type, init);
        messageEvent.#eventInit = init;
        messageEvent.#eventInit.data ??= null;
        messageEvent.#eventInit.origin ??= "";
        messageEvent.#eventInit.lastEventId ??= "";
        messageEvent.#eventInit.source ??= null;
        messageEvent.#eventInit.ports ??= [];
        return messageEvent;
      }
    };
    var { createFastMessageEvent } = MessageEvent;
    delete MessageEvent.createFastMessageEvent;
    var CloseEvent = class _CloseEvent extends Event {
      #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 ErrorEvent = class _ErrorEvent extends Event {
      #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(MessageEvent.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(ErrorEvent.prototype, {
      [Symbol.toStringTag]: {
        value: "ErrorEvent",
        configurable: true
      },
      message: kEnumerableProperty,
      filename: kEnumerableProperty,
      lineno: kEnumerableProperty,
      colno: kEnumerableProperty,
      error: kEnumerableProperty
    });
    webidl.converters.MessagePort = webidl.interfaceConverter(
      webidl.is.MessagePort,
      "MessagePort"
    );
    webidl.converters["sequence<MessagePort>"] = webidl.sequenceConverter(
      webidl.converters.MessagePort
    );
    var eventInit = [
      {
        key: "bubbles",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      },
      {
        key: "cancelable",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      },
      {
        key: "composed",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      }
    ];
    webidl.converters.MessageEventInit = webidl.dictionaryConverter([
      ...eventInit,
      {
        key: "data",
        converter: webidl.converters.any,
        defaultValue: () => null
      },
      {
        key: "origin",
        converter: webidl.converters.USVString,
        defaultValue: () => ""
      },
      {
        key: "lastEventId",
        converter: webidl.converters.DOMString,
        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: () => null
      },
      {
        key: "ports",
        converter: webidl.converters["sequence<MessagePort>"],
        defaultValue: () => []
      }
    ]);
    webidl.converters.CloseEventInit = webidl.dictionaryConverter([
      ...eventInit,
      {
        key: "wasClean",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      },
      {
        key: "code",
        converter: webidl.converters["unsigned short"],
        defaultValue: () => 0
      },
      {
        key: "reason",
        converter: webidl.converters.USVString,
        defaultValue: () => ""
      }
    ]);
    webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
      ...eventInit,
      {
        key: "message",
        converter: webidl.converters.DOMString,
        defaultValue: () => ""
      },
      {
        key: "filename",
        converter: webidl.converters.USVString,
        defaultValue: () => ""
      },
      {
        key: "lineno",
        converter: webidl.converters["unsigned long"],
        defaultValue: () => 0
      },
      {
        key: "colno",
        converter: webidl.converters["unsigned long"],
        defaultValue: () => 0
      },
      {
        key: "error",
        converter: webidl.converters.any
      }
    ]);
    module.exports = {
      MessageEvent,
      CloseEvent,
      ErrorEvent,
      createFastMessageEvent
    };
  }
});

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

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

// ../../node_modules/undici/lib/web/websocket/frame.js
var require_frame = __commonJS({
  "../../node_modules/undici/lib/web/websocket/frame.js"(exports, module) {
    "use strict";
    var { runtimeFeatures } = require_runtime_features();
    var { maxUnsigned16Bit, opcodes } = require_constants5();
    var BUFFER_SIZE = 8 * 1024;
    var buffer = null;
    var bufIdx = BUFFER_SIZE;
    var randomFillSync = runtimeFeatures.has("crypto") ? __require("crypto").randomFillSync : null;
    function generateMask() {
      if (bufIdx === BUFFER_SIZE) {
        bufIdx = 0;
        randomFillSync(buffer ??= Buffer.allocUnsafeSlow(BUFFER_SIZE), 0, BUFFER_SIZE);
      }
      return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]];
    }
    var WebsocketFrameSend = class {
      /**
       * @param {Buffer|undefined} data
       */
      constructor(data) {
        this.frameData = data;
      }
      createFrame(opcode) {
        const frameData = this.frameData;
        const maskKey = generateMask();
        const bodyLength = frameData?.byteLength ?? 0;
        let payloadLength = bodyLength;
        let offset = 6;
        if (bodyLength > maxUnsigned16Bit) {
          offset += 8;
          payloadLength = 127;
        } else if (bodyLength > 125) {
          offset += 2;
          payloadLength = 126;
        }
        const buffer2 = Buffer.allocUnsafe(bodyLength + offset);
        buffer2[0] = buffer2[1] = 0;
        buffer2[0] |= 128;
        buffer2[0] = (buffer2[0] & 240) + opcode;
        buffer2[offset - 4] = maskKey[0];
        buffer2[offset - 3] = maskKey[1];
        buffer2[offset - 2] = maskKey[2];
        buffer2[offset - 1] = maskKey[3];
        buffer2[1] = payloadLength;
        if (payloadLength === 126) {
          buffer2.writeUInt16BE(bodyLength, 2);
        } else if (payloadLength === 127) {
          buffer2[2] = buffer2[3] = 0;
          buffer2.writeUIntBE(bodyLength, 4, 6);
        }
        buffer2[1] |= 128;
        for (let i = 0; i < bodyLength; ++i) {
          buffer2[offset + i] = frameData[i] ^ maskKey[i & 3];
        }
        return buffer2;
      }
      /**
       * @param {Uint8Array} buffer
       */
      static createFastTextFrame(buffer2) {
        const maskKey = generateMask();
        const bodyLength = buffer2.length;
        for (let i = 0; i < bodyLength; ++i) {
          buffer2[i] ^= maskKey[i & 3];
        }
        let payloadLength = bodyLength;
        let offset = 6;
        if (bodyLength > maxUnsigned16Bit) {
          offset += 8;
          payloadLength = 127;
        } else if (bodyLength > 125) {
          offset += 2;
          payloadLength = 126;
        }
        const head = Buffer.allocUnsafeSlow(offset);
        head[0] = 128 | opcodes.TEXT;
        head[1] = payloadLength | 128;
        head[offset - 4] = maskKey[0];
        head[offset - 3] = maskKey[1];
        head[offset - 2] = maskKey[2];
        head[offset - 1] = maskKey[3];
        if (payloadLength === 126) {
          head.writeUInt16BE(bodyLength, 2);
        } else if (payloadLength === 127) {
          head[2] = head[3] = 0;
          head.writeUIntBE(bodyLength, 4, 6);
        }
        return [head, buffer2];
      }
    };
    module.exports = {
      WebsocketFrameSend,
      generateMask
      // for benchmark
    };
  }
});

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

// ../../node_modules/undici/lib/web/websocket/permessage-deflate.js
var require_permessage_deflate = __commonJS({
  "../../node_modules/undici/lib/web/websocket/permessage-deflate.js"(exports, module) {
    "use strict";
    var { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __require("zlib");
    var { isValidClientWindowBits } = require_util5();
    var { MessageSizeExceededError } = require_errors();
    var tail = Buffer.from([0, 0, 255, 255]);
    var kBuffer = /* @__PURE__ */ Symbol("kBuffer");
    var kLength = /* @__PURE__ */ Symbol("kLength");
    var PerMessageDeflate = class {
      /** @type {import('node:zlib').InflateRaw} */
      #inflate;
      #options = {};
      #maxPayloadSize = 0;
      /**
       * @param {Map<string, string>} extensions
       */
      constructor(extensions, options) {
        this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
        this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
        this.#maxPayloadSize = options.maxPayloadSize;
      }
      /**
       * Decompress a compressed payload.
       * @param {Buffer} chunk Compressed data
       * @param {boolean} fin Final fragment flag
       * @param {Function} callback Callback function
       */
      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);
          }
          try {
            this.#inflate = createInflateRaw({ windowBits });
          } catch (err) {
            callback(err);
            return;
          }
          this.#inflate[kBuffer] = [];
          this.#inflate[kLength] = 0;
          this.#inflate.on("data", (data) => {
            this.#inflate[kLength] += data.length;
            if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {
              callback(new MessageSizeExceededError());
              this.#inflate.removeAllListeners();
              this.#inflate = null;
              return;
            }
            this.#inflate[kBuffer].push(data);
          });
          this.#inflate.on("error", (err) => {
            this.#inflate = null;
            callback(err);
          });
        }
        this.#inflate.write(chunk);
        if (fin) {
          this.#inflate.write(tail);
        }
        this.#inflate.flush(() => {
          if (!this.#inflate) {
            return;
          }
          const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
          this.#inflate[kBuffer].length = 0;
          this.#inflate[kLength] = 0;
          callback(null, full);
        });
      }
    };
    module.exports = { PerMessageDeflate };
  }
});

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

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

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

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

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

// ../../node_modules/undici/lib/web/eventsource/util.js
var require_util6 = __commonJS({
  "../../node_modules/undici/lib/web/eventsource/util.js"(exports, module) {
    "use strict";
    var { makeRequest } = require_request2();
    function isValidLastEventId(value) {
      return value.indexOf("\0") === -1;
    }
    function isASCIINumber(value) {
      if (value.length === 0) return false;
      for (let i = 0; i < value.length; i++) {
        if (value.charCodeAt(i) < 48 || value.charCodeAt(i) > 57) return false;
      }
      return true;
    }
    function createPotentialCORSRequest(url, destination, corsAttributeState, sameOriginFallback) {
      let mode = corsAttributeState === "no cors" ? "no-cors" : "cors";
      if (sameOriginFallback && mode === "no-cors") {
        mode = "same-origin";
      }
      let credentialsMode = "include";
      if (corsAttributeState === "anonymous") {
        credentialsMode = "same-origin";
      }
      return makeRequest({
        urlList: [url],
        destination,
        mode,
        credentials: credentialsMode,
        useCredentials: true
      });
    }
    module.exports = {
      isValidLastEventId,
      isASCIINumber,
      createPotentialCORSRequest
    };
  }
});

// ../../node_modules/undici/lib/web/eventsource/eventsource-stream.js
var require_eventsource_stream = __commonJS({
  "../../node_modules/undici/lib/web/eventsource/eventsource-stream.js"(exports, module) {
    "use strict";
    var { Transform } = __require("stream");
    var { isASCIINumber, isValidLastEventId } = require_util6();
    var BOM = [239, 187, 191];
    var LF = 10;
    var CR = 13;
    var COLON = 58;
    var SPACE = 32;
    var DATA = Buffer.from("data");
    var EVENT = Buffer.from("event");
    var ID = Buffer.from("id");
    var RETRY = Buffer.from("retry");
    function isASCIINumberBytes(buffer, start) {
      if (start >= buffer.length) {
        return false;
      }
      for (let i = start; i < buffer.length; i++) {
        if (buffer[i] < 48 || buffer[i] > 57) {
          return false;
        }
      }
      return true;
    }
    function isValidLastEventIdBytes(buffer, start) {
      for (let i = start; i < buffer.length; i++) {
        if (buffer[i] === 0) {
          return false;
        }
      }
      return true;
    }
    function isFieldName(line, length, field) {
      if (length !== field.length) {
        return false;
      }
      for (let i = 0; i < length; i++) {
        if (line[i] !== field[i]) {
          return false;
        }
      }
      return true;
    }
    var EventSourceStream = class extends Transform {
      /**
       * @type {eventSourceSettings}
       */
      state;
      /**
       * Leading byte-order-mark check.
       * @type {boolean}
       */
      checkBOM = true;
      /**
       * @type {boolean}
       */
      crlfCheck = false;
      /**
       * @type {boolean}
       */
      eventEndCheck = false;
      /**
       * @type {Buffer[]}
       */
      chunks = [];
      chunkIndex = 0;
      pos = 0;
      lineChunkIndex = 0;
      linePos = 0;
      event = {
        data: void 0,
        event: void 0,
        id: void 0,
        retry: void 0
      };
      /**
       * @param {object} options
       * @param {boolean} [options.readableObjectMode]
       * @param {eventSourceSettings} [options.eventSourceSettings]
       * @param {(chunk: any, encoding?: BufferEncoding | undefined) => boolean} [options.push]
       */
      constructor(options = {}) {
        options.readableObjectMode = true;
        super(options);
        this.state = options.eventSourceSettings || {};
        if (options.push) {
          this.push = options.push;
        }
      }
      /**
       * @param {Buffer} chunk
       * @param {string} _encoding
       * @param {Function} callback
       * @returns {void}
       */
      _transform(chunk, _encoding, callback) {
        if (chunk.length === 0) {
          callback();
          return;
        }
        this.chunks.push(chunk);
        if (this.checkBOM) {
          if (this.handleBOM()) {
            callback();
            return;
          }
        }
        while (this.hasCurrentByte()) {
          const byte = this.currentByte();
          if (this.eventEndCheck) {
            if (this.crlfCheck) {
              if (byte === LF) {
                this.crlfCheck = false;
                this.consumeCurrentByte();
                continue;
              }
              this.crlfCheck = false;
            }
            if (byte === LF || byte === CR) {
              if (byte === CR) {
                this.crlfCheck = true;
              }
              this.consumeCurrentByte();
              if (this.hasPendingEvent()) {
                this.processEvent(this.event);
              }
              this.clearEvent();
              continue;
            }
            this.eventEndCheck = false;
            continue;
          }
          if (byte === LF || byte === CR) {
            if (byte === CR) {
              this.crlfCheck = true;
            }
            this.parseLine(this.readLine(), this.event);
            this.consumeCurrentByte();
            this.eventEndCheck = true;
            continue;
          }
          this.advanceCursor();
        }
        callback();
      }
      /**
       * @param {Buffer} line
       * @param {EventSourceStreamEvent} event
       */
      parseLine(line, event) {
        if (line.length === 0) {
          return;
        }
        const colonPosition = line.indexOf(COLON);
        if (colonPosition === 0) {
          return;
        }
        let fieldLength = line.length;
        let valueStart = line.length;
        if (colonPosition !== -1) {
          fieldLength = colonPosition;
          valueStart = colonPosition + 1;
          if (line[valueStart] === SPACE) {
            ++valueStart;
          }
        }
        if (isFieldName(line, fieldLength, DATA)) {
          const value = line.toString("utf8", valueStart);
          if (event.data === void 0) {
            event.data = value;
          } else {
            event.data += `
${value}`;
          }
          return;
        }
        if (isFieldName(line, fieldLength, RETRY)) {
          if (isASCIINumberBytes(line, valueStart)) {
            event.retry = line.toString("utf8", valueStart);
          }
          return;
        }
        if (isFieldName(line, fieldLength, ID)) {
          if (isValidLastEventIdBytes(line, valueStart)) {
            event.id = line.toString("utf8", valueStart);
          }
          return;
        }
        if (isFieldName(line, fieldLength, EVENT)) {
          const value = line.toString("utf8", valueStart);
          if (value.length > 0) {
            event.event = value;
          }
        }
      }
      /**
       * @param {EventSourceStreamEvent} event
       */
      processEvent(event) {
        if (event.retry && isASCIINumber(event.retry)) {
          this.state.reconnectionTime = parseInt(event.retry, 10);
        }
        if (event.id !== void 0 && 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;
        this.event.event = void 0;
        this.event.id = void 0;
        this.event.retry = void 0;
      }
      hasPendingEvent() {
        return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0;
      }
      hasCurrentByte() {
        return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length;
      }
      currentByte() {
        return this.chunks[this.chunkIndex][this.pos];
      }
      consumeCurrentByte() {
        this.advanceCursor();
        this.syncLineStartToCursor();
      }
      advanceCursor() {
        this.pos++;
        while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) {
          this.chunkIndex++;
          this.pos = 0;
        }
      }
      syncLineStartToCursor() {
        this.lineChunkIndex = this.chunkIndex;
        this.linePos = this.pos;
        this.dropConsumedChunks();
      }
      dropConsumedChunks() {
        while (this.lineChunkIndex > 0) {
          this.chunks.shift();
          this.lineChunkIndex--;
          this.chunkIndex--;
        }
        if (this.chunkIndex === this.chunks.length) {
          this.chunks.length = 0;
          this.chunkIndex = 0;
          this.pos = 0;
          this.lineChunkIndex = 0;
          this.linePos = 0;
        }
      }
      readLine() {
        if (this.lineChunkIndex === this.chunkIndex) {
          return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos);
        }
        const chunks = [];
        let length = 0;
        for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) {
          const chunk = this.chunks[i];
          const start = i === this.lineChunkIndex ? this.linePos : 0;
          const end = i === this.chunkIndex ? this.pos : chunk.length;
          const slice = chunk.subarray(start, end);
          length += slice.length;
          chunks.push(slice);
        }
        return Buffer.concat(chunks, length);
      }
      peekBufferedByte(offset) {
        let chunkIndex = this.lineChunkIndex;
        let pos = this.linePos;
        while (chunkIndex < this.chunks.length) {
          const chunk = this.chunks[chunkIndex];
          const remaining = chunk.length - pos;
          if (offset < remaining) {
            return chunk[pos + offset];
          }
          offset -= remaining;
          chunkIndex++;
          pos = 0;
        }
      }
      discardLeadingBytes(count) {
        while (count > 0 && this.lineChunkIndex < this.chunks.length) {
          const chunk = this.chunks[this.lineChunkIndex];
          const remaining = chunk.length - this.linePos;
          if (count < remaining) {
            this.linePos += count;
            count = 0;
          } else {
            count -= remaining;
            this.lineChunkIndex++;
            this.linePos = 0;
          }
        }
        this.chunkIndex = this.lineChunkIndex;
        this.pos = this.linePos;
        this.dropConsumedChunks();
      }
      handleBOM() {
        const first = this.peekBufferedByte(0);
        const second = this.peekBufferedByte(1);
        const third = this.peekBufferedByte(2);
        if (second === void 0) {
          if (first === BOM[0]) {
            return true;
          }
          this.checkBOM = false;
          return true;
        }
        if (third === void 0) {
          if (first === BOM[0] && second === BOM[1]) {
            return true;
          }
          this.checkBOM = false;
          return false;
        }
        if (first === BOM[0] && second === BOM[1] && third === BOM[2]) {
          this.discardLeadingBytes(3);
        }
        this.checkBOM = false;
        return !this.hasCurrentByte();
      }
    };
    module.exports = {
      EventSourceStream
    };
  }
});

// ../../node_modules/undici/lib/web/eventsource/eventsource.js
var require_eventsource = __commonJS({
  "../../node_modules/undici/lib/web/eventsource/eventsource.js"(exports, module) {
    "use strict";
    var { pipeline } = __require("stream");
    var { fetching } = require_fetch();
    var { webidl } = require_webidl();
    var { EventSourceStream } = require_eventsource_stream();
    var { parseMIMEType } = require_data_url();
    var { createFastMessageEvent } = require_events();
    var { isNetworkError } = require_response();
    var { kEnumerableProperty } = require_util();
    var { environmentSettingsObject } = require_util2();
    var { createPotentialCORSRequest } = require_util6();
    var experimentalWarned = false;
    var defaultReconnectionTime = 3e3;
    var CONNECTING = 0;
    var OPEN = 1;
    var CLOSED = 2;
    var ANONYMOUS = "anonymous";
    var USE_CREDENTIALS = "use-credentials";
    var EventSource = class _EventSource extends EventTarget {
      #events = {
        open: null,
        error: null,
        message: null
      };
      #url;
      #withCredentials = false;
      /**
       * @type {ReadyState}
       */
      #readyState = CONNECTING;
      #request = null;
      #controller = null;
      #dispatcher;
      /**
       * @type {import('./eventsource-stream').eventSourceSettings}
       */
      #state;
      /**
       * Creates a new EventSource object.
       * @param {string} url
       * @param {EventSourceInit} [eventSourceInitDict={}]
       * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
       */
      constructor(url, 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"
          });
        }
        url = webidl.converters.USVString(url);
        eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict");
        this.#dispatcher = eventSourceInitDict.node.dispatcher || eventSourceInitDict.dispatcher;
        this.#state = {
          lastEventId: "",
          reconnectionTime: eventSourceInitDict.node.reconnectionTime
        };
        const settings = environmentSettingsObject;
        let urlRecord;
        try {
          urlRecord = new URL(url, settings.settingsObject.baseUrl);
          this.#state.origin = urlRecord.origin;
        } catch (e) {
          throw new DOMException(e, "SyntaxError");
        }
        this.#url = urlRecord.href;
        let corsAttributeState = ANONYMOUS;
        if (eventSourceInitDict.withCredentials === true) {
          corsAttributeState = USE_CREDENTIALS;
          this.#withCredentials = true;
        }
        const request = createPotentialCORSRequest(urlRecord, "", corsAttributeState);
        request.client = environmentSettingsObject.settingsObject;
        request.headersList.set("Accept", "text/event-stream");
        request.cache = "no-store";
        request.initiator = "other";
        this.#request = request;
        this.#connect();
      }
      /**
       * Returns the state of this EventSource object's connection. It can have the
       * values described below.
       * @returns {ReadyState}
       * @readonly
       */
      get readyState() {
        return this.#readyState;
      }
      /**
       * Returns the URL providing the event stream.
       * @readonly
       * @returns {string}
       */
      get url() {
        return this.#url;
      }
      /**
       * Returns a boolean indicating whether the EventSource object was
       * instantiated with CORS credentials set (true), or not (false, the default).
       */
      get withCredentials() {
        return this.#withCredentials;
      }
      #connect() {
        if (this.#readyState === CLOSED) return;
        this.#readyState = CONNECTING;
        const fetchParams = {
          request: this.#request,
          dispatcher: this.#dispatcher
        };
        const processEventSourceEndOfBody = (response) => {
          if (!isNetworkError(response)) {
            return this.#reconnect();
          }
        };
        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: (event) => {
              this.dispatchEvent(createFastMessageEvent(
                event.type,
                event.options
              ));
            }
          });
          pipeline(
            response.body.stream,
            eventSourceStream,
            (error) => {
              if (error?.aborted === false) {
                this.close();
                this.dispatchEvent(new Event("error"));
              }
            }
          );
        };
        this.#controller = fetching(fetchParams);
      }
      /**
       * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
       * @returns {void}
       */
      #reconnect() {
        if (this.#readyState === CLOSED) return;
        this.#readyState = CONNECTING;
        this.dispatchEvent(new Event("error"));
        setTimeout(() => {
          if (this.#readyState !== CONNECTING) return;
          if (this.#state.lastEventId.length) {
            this.#request.headersList.set("last-event-id", this.#state.lastEventId, true);
          }
          this.#connect();
        }, this.#state.reconnectionTime)?.unref();
      }
      /**
       * Closes the connection, if any, and sets the readyState attribute to
       * CLOSED.
       */
      close() {
        webidl.brandCheck(this, _EventSource);
        if (this.#readyState === CLOSED) return;
        this.#readyState = CLOSED;
        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);
        }
        const listener = webidl.converters.EventHandlerNonNull(fn);
        if (listener !== null) {
          this.addEventListener("open", listener);
          this.#events.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);
        }
        const listener = webidl.converters.EventHandlerNonNull(fn);
        if (listener !== null) {
          this.addEventListener("message", listener);
          this.#events.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);
        }
        const listener = webidl.converters.EventHandlerNonNull(fn);
        if (listener !== null) {
          this.addEventListener("error", listener);
          this.#events.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: CLOSED,
        writable: false
      }
    };
    Object.defineProperties(EventSource, constantsPropertyDescriptors);
    Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors);
    Object.defineProperties(EventSource.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: () => false
      },
      {
        key: "dispatcher",
        // undici only
        converter: webidl.converters.any
      },
      {
        key: "node",
        // undici only
        converter: webidl.dictionaryConverter([
          {
            key: "reconnectionTime",
            converter: webidl.converters["unsigned long"],
            defaultValue: () => defaultReconnectionTime
          },
          {
            key: "dispatcher",
            converter: webidl.converters.any
          }
        ]),
        defaultValue: () => ({})
      }
    ]);
    module.exports = {
      EventSource,
      defaultReconnectionTime
    };
  }
});

// ../../node_modules/undici/index.js
var require_undici = __commonJS({
  "../../node_modules/undici/index.js"(exports, module) {
    var Client = require_client();
    var Dispatcher = require_dispatcher();
    var Pool = require_pool();
    var BalancedPool = require_balanced_pool();
    var RoundRobinPool = require_round_robin_pool();
    var Agent = require_agent();
    var Dispatcher1Wrapper = require_dispatcher1_wrapper();
    var ProxyAgent = require_proxy_agent();
    var Socks5ProxyAgent = require_socks5_proxy_agent();
    var EnvHttpProxyAgent = require_env_http_proxy_agent();
    var RetryAgent = require_retry_agent();
    var H2CClient = require_h2c_client();
    var errors = require_errors();
    var util = require_util();
    var { InvalidArgumentError } = errors;
    var api = require_api();
    var buildConnector = require_connect();
    var MockClient = require_mock_client();
    var { MockCallHistory, MockCallHistoryLog } = require_mock_call_history();
    var MockAgent = require_mock_agent();
    var MockPool = require_mock_pool();
    var SnapshotAgent = require_snapshot_agent();
    var mockErrors = require_mock_errors();
    var RetryHandler = require_retry_handler();
    var { getGlobalDispatcher, setGlobalDispatcher } = require_global2();
    var DecoratorHandler = require_decorator_handler();
    var RedirectHandler = require_redirect_handler();
    Object.assign(Dispatcher.prototype, api);
    module.exports.Dispatcher = Dispatcher;
    module.exports.Client = Client;
    module.exports.Pool = Pool;
    module.exports.BalancedPool = BalancedPool;
    module.exports.RoundRobinPool = RoundRobinPool;
    module.exports.Agent = Agent;
    module.exports.Dispatcher1Wrapper = Dispatcher1Wrapper;
    module.exports.ProxyAgent = ProxyAgent;
    module.exports.Socks5ProxyAgent = Socks5ProxyAgent;
    module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent;
    module.exports.RetryAgent = RetryAgent;
    module.exports.H2CClient = H2CClient;
    module.exports.RetryHandler = RetryHandler;
    module.exports.DecoratorHandler = DecoratorHandler;
    module.exports.RedirectHandler = RedirectHandler;
    module.exports.interceptors = {
      redirect: require_redirect(),
      responseError: require_response_error(),
      retry: require_retry(),
      dump: require_dump(),
      dns: require_dns(),
      cache: require_cache2(),
      decompress: require_decompress(),
      deduplicate: require_deduplicate()
    };
    module.exports.cacheStores = {
      MemoryCacheStore: require_memory_cache_store()
    };
    var SqliteCacheStore = require_sqlite_cache_store();
    module.exports.cacheStores.SqliteCacheStore = SqliteCacheStore;
    module.exports.buildConnector = buildConnector;
    module.exports.errors = errors;
    module.exports.util = {
      parseHeaders: util.parseHeaders,
      headerNameToString: util.headerNameToString
    };
    function makeDispatcher(fn) {
      return (url, opts, handler) => {
        if (typeof opts === "function") {
          handler = opts;
          opts = null;
        }
        if (!url || typeof url !== "string" && typeof url !== "object" && !(url 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 path = opts.path;
          if (!opts.path.startsWith("/")) {
            path = `/${path}`;
          }
          url = new URL(util.parseOrigin(url).origin + path);
        } else {
          if (!opts) {
            opts = typeof url === "object" ? url : {};
          }
          url = util.parseURL(url);
        }
        const { agent, dispatcher = getGlobalDispatcher(), ...restOpts } = opts;
        if (agent) {
          throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?");
        }
        return fn.call(dispatcher, {
          ...restOpts,
          origin: url.origin,
          path: url.search ? `${url.pathname}${url.search}` : url.pathname,
          method: opts.method || (opts.body ? "PUT" : "GET")
        }, handler);
      };
    }
    module.exports.setGlobalDispatcher = setGlobalDispatcher;
    module.exports.getGlobalDispatcher = getGlobalDispatcher;
    var fetchImpl = require_fetch().fetch;
    var currentFilename = typeof __filename !== "undefined" ? __filename : void 0;
    function appendFetchStackTrace(err, filename) {
      if (!err || typeof err !== "object") {
        return;
      }
      const stack = typeof err.stack === "string" ? err.stack : "";
      const normalizedFilename = filename.replace(/\\/g, "/");
      if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) {
        return;
      }
      const capture = {};
      Error.captureStackTrace(capture, appendFetchStackTrace);
      if (!capture.stack) {
        return;
      }
      const captureLines = capture.stack.split("\n").slice(1).join("\n");
      err.stack = stack ? `${stack}
${captureLines}` : capture.stack;
    }
    module.exports.fetch = function fetch(init, options = void 0) {
      return fetchImpl(init, options).catch((err) => {
        if (currentFilename) {
          appendFetchStackTrace(err, currentFilename);
        } else if (err && typeof err === "object") {
          Error.captureStackTrace(err, module.exports.fetch);
        }
        throw err;
      });
    };
    module.exports.Headers = require_headers().Headers;
    module.exports.Response = require_response().Response;
    module.exports.Request = require_request2().Request;
    module.exports.FormData = require_formdata().FormData;
    var { setGlobalOrigin, getGlobalOrigin } = require_global();
    module.exports.setGlobalOrigin = setGlobalOrigin;
    module.exports.getGlobalOrigin = getGlobalOrigin;
    var { CacheStorage } = require_cachestorage();
    var { kConstruct } = require_symbols();
    module.exports.caches = new CacheStorage(kConstruct);
    var { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = require_cookies();
    module.exports.deleteCookie = deleteCookie;
    module.exports.getCookies = getCookies;
    module.exports.getSetCookies = getSetCookies;
    module.exports.setCookie = setCookie;
    module.exports.parseCookie = parseCookie;
    var { parseMIMEType, serializeAMimeType } = require_data_url();
    module.exports.parseMIMEType = parseMIMEType;
    module.exports.serializeAMimeType = serializeAMimeType;
    var { CloseEvent, ErrorEvent, MessageEvent } = require_events();
    var { WebSocket, ping } = require_websocket();
    module.exports.WebSocket = WebSocket;
    module.exports.CloseEvent = CloseEvent;
    module.exports.ErrorEvent = ErrorEvent;
    module.exports.MessageEvent = MessageEvent;
    module.exports.ping = ping;
    module.exports.WebSocketStream = require_websocketstream().WebSocketStream;
    module.exports.WebSocketError = require_websocketerror().WebSocketError;
    module.exports.request = makeDispatcher(api.request);
    module.exports.stream = makeDispatcher(api.stream);
    module.exports.pipeline = makeDispatcher(api.pipeline);
    module.exports.connect = makeDispatcher(api.connect);
    module.exports.upgrade = makeDispatcher(api.upgrade);
    module.exports.MockClient = MockClient;
    module.exports.MockCallHistory = MockCallHistory;
    module.exports.MockCallHistoryLog = MockCallHistoryLog;
    module.exports.MockPool = MockPool;
    module.exports.MockAgent = MockAgent;
    module.exports.SnapshotAgent = SnapshotAgent;
    module.exports.mockErrors = mockErrors;
    var { EventSource } = require_eventsource();
    module.exports.EventSource = EventSource;
    function install() {
      globalThis.fetch = module.exports.fetch;
      globalThis.Headers = module.exports.Headers;
      globalThis.Response = module.exports.Response;
      globalThis.Request = module.exports.Request;
      globalThis.FormData = module.exports.FormData;
      globalThis.WebSocket = module.exports.WebSocket;
      globalThis.CloseEvent = module.exports.CloseEvent;
      globalThis.ErrorEvent = module.exports.ErrorEvent;
      globalThis.MessageEvent = module.exports.MessageEvent;
      globalThis.EventSource = module.exports.EventSource;
    }
    module.exports.install = install;
  }
});
export default require_undici();
/*! Bundled license information:

undici/lib/web/fetch/body.js:
  (*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

undici/lib/web/websocket/frame.js:
  (*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> *)
*/
